Agent based modeling. Technology overview
Agent based modeling. Technology overview
In this chapter, we will present an overview of the technologies and techniques used In this chapter, we will present an overview of the technologies and techniques used in agent based modeling. It is important to understand that there is no special or in agent based modeling. It is important to understand that there is no special or standard language for agent based modeling. Agent
standard language for agent based modeling. Agent based models are very diverse inbased models are very diverse in architecture, behavior types, number of agents, space, and
architecture, behavior types, number of agents, space, and so on. Other modelingso on. Other modeling methods (discrete event and system dynamics) are
methods (discrete event and system dynamics) are often used inside and outsideoften used inside and outside agents. There are, however, “design patterns” that are
agents. There are, however, “design patterns” that are common to many agent basedcommon to many agent based models, which we will consider:
models, which we will consider:
•
• “Object-based” architecture“Object-based” architecture •
• Time model: asynchronous or synchronous (steps or clock Time model: asynchronous or synchronous (steps or clock ticks)ticks) •
• Space (continuous, discrete, geographical) and mobilitySpace (continuous, discrete, geographical) and mobility •
• Networks and links between agentsNetworks and links between agents •
• Communication between agents, and between agents and Communication between agents, and between agents and environmentenvironment •
• Dynamic creation and destruction of agentsDynamic creation and destruction of agents •
• Statistics collection on agent populationsStatistics collection on agent populations
Before we dive into the technical stuff, we will discuss what kind of real world objects Before we dive into the technical stuff, we will discuss what kind of real world objects the agents actually represent.
the agents actually represent.
Who are the agents?
Who are the agents?
Agents in an agent bas
Agents in an agent based model may represent very diverse things: vehicles, units ed model may represent very diverse things: vehicles, units ofof equipment, projects, products, ideas, organizations, investments, pieces of land, equipment, projects, products, ideas, organizations, investments, pieces of land, people in different roles, etc.
people in different roles, etc.
Agents may be… Agents may be…
People in different roles:
People in different roles:
consumers, citizens, employees, consumers, citizens, employees, patients, doctors, clients, soldiers, … patients, doctors, clients, soldiers, …Equipment, vehicles:
Equipment, vehicles:
trucks, cars, cranes, aircrafts, trucks, cars, cranes, aircrafts,rail cars, machines, … rail cars, machines, …
Non-material things:
Non-material things:
projects, products, innovations, ideas, projects, products, innovations, ideas,
investments … investments …
Organizations:
Organizations:
companies, political parties, countries, … companies, political parties, countries, …
Given a particular problem we are
Given a particular problem we are solving with the help of solving with the help of agent based modeling, howagent based modeling, how do we choose who the agents are? This may not be as trivial as it seems. Consider the do we choose who the agents are? This may not be as trivial as it seems. Consider the following example.
following example.
Who are the agents in an American automotive market model?
Who are the agents in an American automotive market model?
You are going to model the A
You are going to model the American automotive market (for example, to forecast itsmerican automotive market (for example, to forecast its reaction to a certain move by one of the players) and you have decided to use agent reaction to a certain move by one of the players) and you have decided to use agent based modeling. In automotive market, people buy and sell cars. So, the first thing that based modeling. In automotive market, people buy and sell cars. So, the first thing that comes to mind is that agents are people because they make decisions.
comes to mind is that agents are people because they make decisions.
Agents are people Agents are people
What about cars? Cars, at first glance, are passive objects that have different What about cars? Cars, at first glance, are passive objects that have different parameters and may vary in appeal to
parameters and may vary in appeal to different people. But cars do have sodifferent people. But cars do have someme dynamics because with age they lose appeal and value. So, should we model cars as dynamics because with age they lose appeal and value. So, should we model cars as agents or just leave them as plain objects, or entities, being handled by agents/people? agents or just leave them as plain objects, or entities, being handled by agents/people?
Agents are people and cars Agents are people and cars
What if a person shares a car with a spouse? Who makes the decision then? Should we What if a person shares a car with a spouse? Who makes the decision then? Should we model collaboration between family members?
model collaboration between family members?
?
?
?
?
A car shared by two family members. Collaborative decision making A car shared by two family members. Collaborative decision making
The situation gets even more complicated if
The situation gets even more complicated if we consider families with children,we consider families with children, families with multiple cars shared by multiple people, and so on.
families with multiple cars shared by multiple people, and so on.
Multiple cars shared by multiple people Multiple cars shared by multiple people
There is no universal answer to the question. Depending on the details of the problem, There is no universal answer to the question. Depending on the details of the problem, different model architectures may make sense. In the Vehicle Market Model created by different model architectures may make sense. In the Vehicle Market Model created by Mark Paich (
Mark Paich (Decisio Consulting and Lexidyne), the agents Decisio Consulting and Lexidyne), the agents were not individual people,were not individual people, but
but householdshouseholds. Households had garage slots with cars, and cars were not agents, they. Households had garage slots with cars, and cars were not agents, they were objects with properties like year, make, and model. Decisions about selling or were objects with properties like year, make, and model. Decisions about selling or buying a car were made at the household level, taking into account the number of buying a car were made at the household level, taking into account the number of family members, their ages, income, and other factors.
family members, their ages, income, and other factors.
Agents are households Agents are households
?
?
?
Agent based modeling and
Agent based modeling and
object-oriented design
object-oriented design
Agent based simulation modeling and object-oriented software design have a Agent based simulation modeling and object-oriented software design have a lot inlot in common. When software engineers think about how to choose a
common. When software engineers think about how to choose a set of classset of classes, wherees, where to draw the line between interface and implementation, and which set of constructors to draw the line between interface and implementation, and which set of constructors a class should have, they are doing a type of agent based, or individual based,
a class should have, they are doing a type of agent based, or individual based, modeling for the problem that the software is addressing.
modeling for the problem that the software is addressing.
We can extend this analogy to the
We can extend this analogy to the procedural programming paradigm procedural programming paradigm that historically that historically preceded the object-oriented paradigm. In procedural programming, the software preceded the object-oriented paradigm. In procedural programming, the software developer was thinking of the program as a
developer was thinking of the program as a (possibly hierarchical) sequence of steps(possibly hierarchical) sequence of steps that should be taken to reach a goal. Similarly, in discrete event (process-centric) that should be taken to reach a goal. Similarly, in discrete event (process-centric) modeling, the modeler represents the system as
modeling, the modeler represents the system as a (possibly hierarchical) sequence ofa (possibly hierarchical) sequence of operations that are performed over entities. However, unlike procedural
operations that are performed over entities. However, unlike procedural
programming, which was almost totally replaced by object-oriented programming, programming, which was almost totally replaced by object-oriented programming, discrete event modeling successfully coexists with agent
discrete event modeling successfully coexists with agent based modeling.based modeling.
Let’s also discuss classes and objects.
Let’s also discuss classes and objects. ClassClass is, in a way, a is, in a way, a design-time termdesign-time term; it is a; it is a description
description. Class describes a set of similar objects, but these objects (cal. Class describes a set of similar objects, but these objects (cal ledled instancesinstances
of the class) will not be created until the program is run. Objects exist at
of the class) will not be created until the program is run. Objects exist at runtime. So,runtime. So, speaking rigorously, agents exist only in a
speaking rigorously, agents exist only in a running agent based model. When you arerunning agent based model. When you are developing the model, you only construct
developing the model, you only construct agent classesagent classes.. Agents (objects) of the same
Agents (objects) of the same class have common structure and behavior, but class have common structure and behavior, but maymay differ in details, such as parameter values and
differ in details, such as parameter values and state informationstate information (memory) that (memory) that includes variable values, statechart and ev
includes variable values, statechart and event states, etc. ent states, etc. For example, two agents ofFor example, two agents of the class
the classPatientPatient have the same set of parameters and the same behavior pattern, but have the same set of parameters and the same behavior pattern, but may differ in age, location, disease state, or contact lists.
may differ in age, location, disease state, or contact lists.
Interface of the agent
Interface of the agent (object) is the set of things other agents and external parts of (object) is the set of things other agents and external parts of thethe model can see and use to interact with the agent. These can be variables (in
model can see and use to interact with the agent. These can be variables (in OOOO terminology these would be “public fields”), functions (“
terminology these would be “public fields”), functions (“ public methods”), ports, orpublic methods”), ports, or messages. As opposed to interface,
messages. As opposed to interface, implementation of the agent implementation of the agent (object) is a set of (object) is a set of things internal to the agent
things internal to the agent and hidden from the external and hidden from the external world (variables, functions,world (variables, functions, statecharts, events, embedded agents, etc).
statecharts, events, embedded agents, etc).
Separation of interface and implementation in
Separation of interface and implementation in OO programming allows for modularOO programming allows for modular development: one can change (optimize, extend, or improve) a
development: one can change (optimize, extend, or improve) a class by changing itsclass by changing its implementation and other classes will not need to know about the changes as long as implementation and other classes will not need to know about the changes as long as the interface stays the same. In
the interface stays the same. In OO programming, this separation is stronglyOO programming, this separation is strongly supported by the restrictive language constructs that prevent
accessing the implementation from outside the class
accessing the implementation from outside the class (for example, the Java keywords(for example, the Java keywords “private” or “protected”).
“private” or “protected”).
In agent based modeling, those formal access restrictions are often omitted for the In agent based modeling, those formal access restrictions are often omitted for the purpose of simplicity and more rapid development. For
purpose of simplicity and more rapid development. For example, the statechart statesexample, the statechart states and transitions in AnyLogic are visible from outside the agent so that one can make and transitions in AnyLogic are visible from outside the agent so that one can make inquiries and collect statistics on the agent state by simply writing
inquiries and collect statistics on the agent state by simply writing <agent name>.<state<agent name>.<state name>
name>. The modeler, however, should not abuse the . The modeler, however, should not abuse the transparency of the agent bordertransparency of the agent border
(which he should define himself and keep
(which he should define himself and keep in mind) and refrain fin mind) and refrain from interacting withrom interacting with the agent in an “illegal” manner. Examples of this would be assigning a new value to the agent in an “illegal” manner. Examples of this would be assigning a new value to the agent variable or resetting the agent internal event from outside.
the agent variable or resetting the agent internal event from outside.
Important differences between agent based modeling a
Important differences between agent based modeling and OO programming are thatnd OO programming are that agents are typically dynamic, have internal time delays, can initiate events, and can agents are typically dynamic, have internal time delays, can initiate events, and can have continuously changing variables inside, whereas objects in an
have continuously changing variables inside, whereas objects in an OO programOO program typically “act upon request”; they do something only when their methods are called. typically “act upon request”; they do something only when their methods are called. Agents in a running agent based model, in this sense, are more like
Agents in a running agent based model, in this sense, are more like threadsthreads or or concurrent processes
concurrent processes in a running program. in a running program. This makes the techniques applied in theThis makes the techniques applied in the design of concurrent and parallel systems (such as
design of concurrent and parallel systems (such as message sequence diagramsmessage sequence diagrams explained in the
explained in the Field Service exampleField Service example) useful in agent based modeling.) useful in agent based modeling.
Similar to objects, agents can be created and destroyed dynamically. Similar to objects, agents can be created and destroyed dynamically.
There are things that are fundamentally important in OO design, but are not widely There are things that are fundamentally important in OO design, but are not widely used in agent based modeling. These a
used in agent based modeling. These a re, for example, inheritance and polymorphism.re, for example, inheritance and polymorphism. Agent based modelers, in general, are not really keen on creating class hierarchies and Agent based modelers, in general, are not really keen on creating class hierarchies and interfaces or overriding methods in Java or C++ s
interfaces or overriding methods in Java or C++ style. Instead, they often usetyle. Instead, they often use conditional functions and behavior components.
conditional functions and behavior components.
Consider a population model where males and
Consider a population model where males and females have differences in females have differences in behavior.behavior. An OO purist would create a class hierarchy like the one shown in the Figure on the An OO purist would create a class hierarchy like the one shown in the Figure on the left. Properties and behavior common for all people would be located in the base class left. Properties and behavior common for all people would be located in the base class
Person
Person, whereas behavior specific to males and females would be placed in the two, whereas behavior specific to males and females would be placed in the two corresponding subclasses
corresponding subclassesMaleMale and andFemaleFemale. A non OO-minded modeler . A non OO-minded modeler would createwould create just one class
just one class PersonPerson, with the parameter, with the parameterSexSex, and one behavior component with two, and one behavior component with two branches as shown in the same figure on the right. Both versions may make sense, but branches as shown in the same figure on the right. Both versions may make sense, but which one is better depends
OO purist and non OO-minded modeler versions of agent classes in a population model OO purist and non OO-minded modeler versions of agent classes in a population model
OO modeling in AnyLogic
OO modeling in AnyLogic
Any AnyLogic model, not just an agent based one, consists of classes that inherit from Any AnyLogic model, not just an agent based one, consists of classes that inherit from
ActiveObject
ActiveObject..ActiveObjectActiveObject is the base class for all is the base class for all model components (calledmodel components (called activeactive
objects
objects) defined in the AnyLogic engine.) defined in the AnyLogic engine.
In the simplest case, there is just one active object class
In the simplest case, there is just one active object classMainMain in the model. When you in the model. When you create a new model, this class is added automatically and its editor opens. Then you create a new model, this class is added automatically and its editor opens. Then you can start to fill the class with process flowcharts, stocks, flows, statecharts, events, and can start to fill the class with process flowcharts, stocks, flows, statecharts, events, and graphics. graphics. Person Person Education Education Birth date Birth date Male Male Male Male lifephase lifephase Female Female Female Female lifephase lifephase Base class Base class Subclasses Subclasses Agent Agent Coordinates Coordinates Connections Connections … …
AnyLogic engine classes AnyLogic engine classes Classes in the user model Classes in the user model
Subclass of Subclass of Person Person Education Education Birth date Birth date Sex Sex Male Male lifephases
lifephases FemaleFemalelifephaseslifephases Lifephase
Lifephase Sex
Sex == == MALE MALE Sex Sex == == FEMALEFEMALE Subclass of
Subclass of
ActiveObject ActiveObject
The base class for all model The base class for all model components
components
A subclass of ActiveObject A subclass of ActiveObject that extends it with
that extends it with networking, moblity, networking, moblity, message passing and other message passing and other useful functionality
useful functionality
OO purist version
OO purist version
Non OO-minded modeler version Non OO-minded modeler version Subclass of
In a hierarchical model there is more than one class, and when the model runs objects In a hierarchical model there is more than one class, and when the model runs objects of different classes are
of different classes are embedded embedded one into another. When we say an active object is one into another. When we say an active object is embedded into another active object (call
embedded into another active object (calleded container object container object ), it means:), it means:
•
• The embedded object does not exist without the container; it is created whenThe embedded object does not exist without the container; it is created when
the container is created, and deleted when the container is deleted. the container is created, and deleted when the container is deleted.
•
• If the embedded object is replicated, i.e., has multiple instances, the containerIf the embedded object is replicated, i.e., has multiple instances, the container
object controls dynamic creation and deletion of the instances. object controls dynamic creation and deletion of the instances.
•
• The animation of the embedded object becomes a part of the animation of theThe animation of the embedded object becomes a part of the animation of the
container object (“embedded animation”). container object (“embedded animation”).
•
• From a Java viewpoint, the embedded object is a member, or field, of theFrom a Java viewpoint, the embedded object is a member, or field, of the
container object and exists in its “namespace” at the same level as variables, container object and exists in its “namespace” at the same level as variables, parameters, statecharts, etc.
parameters, statecharts, etc.
Any agent based model is hierarchical and has at least two classes: the top-level clas Any agent based model is hierarchical and has at least two classes: the top-level clas ss (like
(likeMainMain) that contains the agents, and the agent class ) that contains the agents, and the agent class (like(likePersonPerson). Agents typically). Agents typically exist as a
exist as a replicated object replicated object (a collection of multiple objects of the same type) (a collection of multiple objects of the same type) embedded into
embedded intoMainMain, see the Figure. User agent classes do not inherit directly from the, see the Figure. User agent classes do not inherit directly from the
ActiveObject
ActiveObject class; they are subclasses of the class class; they are subclasses of the class AgentAgent, which extends, which extendsActiveObjectActiveObject with features specific for agent based
with features specific for agent based modeling.modeling.
UML diagram of a typical agent based model UML diagram of a typical agent based model
In AnyLogic you do not need to write code to create subclasses and embed objects into In AnyLogic you do not need to write code to create subclasses and embed objects into one another; it is done by using drag and drop and wizards. The simplest way of
one another; it is done by using drag and drop and wizards. The simplest way of setting up the architecture of an agent based model is to use the
setting up the architecture of an agent based model is to use the Agent populationAgent population
wizard. wizard. Main Main Agent Agent
AnyLogic engine classes AnyLogic engine classes Classes in the user model Classes in the user model
Subclass of Subclass of Person Person Subclass of Subclass of ActiveObject ActiveObject people[…] people[…] Contains Contains multiple multiple instances of instances of Subclass of Subclass of
To create a population of agents: To create a population of agents:
1.
1. Drag theDrag theAgent populationAgent population item from the item from theGeneralGeneral palette to the editor of palette to the editor ofMainMain (or (or another container object).
another container object). 2.
2. In the wizard, specify the name of the agent class (e.g.,In the wizard, specify the name of the agent class (e.g.,PersonPerson), the name of the), the name of the population (e.g.
population (e.g.peoplepeople), the initial number of agents, and, optionally, the space), the initial number of agents, and, optionally, the space and network settings.
and network settings.
The population of agents, the environment, and the animation created by the wizard The population of agents, the environment, and the animation created by the wizard
There is also a general way of creating a new active object cla
There is also a general way of creating a new active object cla ss, making it an agentss, making it an agent class, and embedding it into the container class. It includes the following steps. class, and embedding it into the container class. It includes the following steps.
To create a new active object class: To create a new active object class:
3.
3. Right-click in theRight-click in theProjectsProjects tree and choose tree and chooseNew | Active object classNew | Active object class from the from the context menu.
context menu. 4.
4. Enter the class name (by convention, the first letter of class name should beEnter the class name (by convention, the first letter of class name should be capitalized) and click
capitalized) and clickFinishFinish.. 5.
5. The new class appears in theThe new class appears in theProjectsProjects tree and its editor opens. Note that the tree and its editor opens. Note that the class created this way is not embedded anywhere yet.
class created this way is not embedded anywhere yet.
To make an active object class an agent class: To make an active object class an agent class:
1.
1. On theOn theGeneralGeneral page of your active object class properties, check the page of your active object class properties, check theAgentAgent
checkbox. This changes the base class from
checkbox. This changes the base class fromActiveObjectActiveObject to toAgentAgent. The. TheAgentAgent
page of the properties becomes available and the icon of the class changes. page of the properties becomes available and the icon of the class changes.
To embed one active object class into another: To embed one active object class into another:
1.
1. Drag the class icon from the Projects tree to the editor of the container object.Drag the class icon from the Projects tree to the editor of the container object. An embedded object is created inside the container object. So far, there is a An embedded object is created inside the container object. So far, there is a single instance.
single instance.
To replicate (to create multiple instances of) the embedded object: To replicate (to create multiple instances of) the embedded object:
1.
1. Select the embedded object in the editor of the container object and select theSelect the embedded object in the editor of the container object and select the Replicated checkbox in its properties. Specify the initial number of objects (by Replicated checkbox in its properties. Specify the initial number of objects (by default, the initial number is 0).
default, the initial number is 0).
Drag
The general way of creating a replicated embedded object The general way of creating a replicated embedded object
Choose this menu
Choose this menu
item to create a
item to create a
new active object or
new active object or
agent class
agent class
The new class appears in
The new class appears in
the Projects tree
the Projects tree Select the Agent checkbox to makeSelect the Agent checkbox to makethe class an agent classthe class an agent class
Drag the class icon to the editor of the
Drag the class icon to the editor of the another class to create ananother class to create an
embedded object
embedded object
Drag
Drag
In the properties of the embedded object select the Replicated checkbox to
In the properties of the embedded object select the Replicated checkbox to
create multple instances
Time in agent based models
Time in agent based models
When talking about agent based models, we need to distinguish between When talking about agent based models, we need to distinguish between asynchronous and synchronous time models.
asynchronous and synchronous time models. Asynchronous time Asynchronous time means there is no means there is no “grid” on the time axis and events may occur at arbitrary moments, exactly when they “grid” on the time axis and events may occur at arbitrary moments, exactly when they are to occur.
are to occur. Synchronous timeSynchronous time assumes things can only happen during discrete time assumes things can only happen during discrete time steps (they are “snapped to the time grid”), and nothing happens in between, see the steps (they are “snapped to the time grid”), and nothing happens in between, see the Figure. In synchronous models, on every time step,
Figure. In synchronous models, on every time step, every agent checks whether itevery agent checks whether it needs to do something.
needs to do something.
Do not confuse these time steps with the time steps of the
Do not confuse these time steps with the time steps of the numeric solvernumeric solver that solves that solves continuous-time algebraic and differential equations. The latter are typically smaller continuous-time algebraic and differential equations. The latter are typically smaller and are out of the user control. The user cannot associate an arbitrary action with a and are out of the user control. The user cannot associate an arbitrary action with a numeric step or even know how many ti
numeric step or even know how many times the equations are evaluated.mes the equations are evaluated.
Synchronous and asynchronous time in agent based models Synchronous and asynchronous time in agent based models
Some people think that agent
Some people think that agent based modeling assumes synchronous time (time steps).based modeling assumes synchronous time (time steps). This is not true. On the contrary, the most elegant and practically useful agent based This is not true. On the contrary, the most elegant and practically useful agent based
time time Agent 3 Agent 3 Agent 2 Agent 2 Agent 1 Agent 1 time time Agent 3 Agent 3 Agent 2 Agent 2 Agent 1 Agent 1 Step
Step 1 1 Step 2 Step 2 Step Step 3 3 Step Step 4 4 Step Step 5 5 Step Step 66 “Preparation” for the step,
“Preparation” for the step, no public state change occur
no public state change occur The actual step – stateThe actual step – statechange occurs herechange occurs here Synchronous time model
Synchronous time model Asynchronous time model Asynchronous time model
models are either asynchronous or have a mixture of
models are either asynchronous or have a mixture of asynchronous time and timeasynchronous time and time steps.
steps.
Synchronous time only makes sense in these ca Synchronous time only makes sense in these cases:ses:
•
• When modeling an artificial world, which is When modeling an artificial world, which is synchronous by definition, such assynchronous by definition, such as
in
in The Game of LifeThe Game of Life or in or in The Shelling Segregation ModelThe Shelling Segregation Model..
•
• When the real world system is When the real world system is synchronous. These cases are rare. An examplesynchronous. These cases are rare. An example
would be a supply chain
would be a supply chain where inventory decisions are made, for example, on where inventory decisions are made, for example, on aa monthly basis.
monthly basis.
•
• When the agent needs to be updated on what happens around it to recalculateWhen the agent needs to be updated on what happens around it to recalculate
internal variables and check conditions. For example, in the
internal variables and check conditions. For example, in the HispanicHispanic population acculturation model, a person periodically updates his
population acculturation model, a person periodically updates his contact ratecontact rate with other Hispanics, which depends on how ma
with other Hispanics, which depends on how many there are in his ny there are in his region. Thisregion. This is, in a way,
is, in a way, emulation of continuous time dynamics, typically done at emulation of continuous time dynamics, typically done at timetime steps larger than those of
steps larger than those of numerical solver.numerical solver.
In any case, we recommend using asynchronous time
In any case, we recommend using asynchronous time whenever possible, i.e., lettingwhenever possible, i.e., letting things happen when they really are going t
things happen when they really are going to happen. Individual decisions likeo happen. Individual decisions like purchases, job changes, moves, contacts between people, a
purchases, job changes, moves, contacts between people, a nd stochastic events (likend stochastic events (like breakdowns, recovery, etc.) can just occur at their exact
breakdowns, recovery, etc.) can just occur at their exact times on the continuous timetimes on the continuous time axis.
axis. If there is still a need for time steps, such as in thIf there is still a need for time steps, such as in the latter case above, you can mixe latter case above, you can mix time steps with continuous time. The model
time steps with continuous time. The model Air Defense SystemAir Defense System presented later in this presented later in this chapter is a good example of
chapter is a good example of such a mixture.such a mixture.
Synchronous time inevitably introduces a certain degree of inaccuracy and raises a lot Synchronous time inevitably introduces a certain degree of inaccuracy and raises a lot of questions (and thus provides for numerous discussions at
of questions (and thus provides for numerous discussions at “academic conferences”“academic conferences” on agent based modeling). Do the results depend on the size of the time step? Do they on agent based modeling). Do the results depend on the size of the time step? Do they depend on the order the agents a
depend on the order the agents are processed within a time stre processed within a time step (deterministic,ep (deterministic, random)? Can we do a single loop across all agents or do we need to
random)? Can we do a single loop across all agents or do we need to do two loopsdo two loops within a step: the first one to prepare the action and the second one to execute it? within a step: the first one to prepare the action and the second one to execute it? InIn The Game of Life, for example, you cannot do a single loop: all cells
The Game of Life, for example, you cannot do a single loop: all cells must see themust see the previous state of other cells before changing their own state. If a message is sent on a previous state of other cells before changing their own state. If a message is sent on a certain time step, on what time step should it be delivered? In addition, synchronous certain time step, on what time step should it be delivered? In addition, synchronous time models are typically computationally less efficient than asynchronous models as time models are typically computationally less efficient than asynchronous models as every agent is “visited” on every time step, even if it is not doing anything.
every agent is “visited” on every time step, even if it is not doing anything.
Statistics collection in agent based models can also be synchronous and asynchronous. Statistics collection in agent based models can also be synchronous and asynchronous. For example, to find out the number of infected people in an epidemic model, you can For example, to find out the number of infected people in an epidemic model, you can loop throughout the population and calculate the number at the time you need it, or loop throughout the population and calculate the number at the time you need it, or you can have an always up-to-date counter, which is
the agents when they change their individual states.
the agents when they change their individual states. The “synchronous” statisticsThe “synchronous” statistics collection is, however, more standard and common.
collection is, however, more standard and common.
Space in agent based models
Space in agent based models
Space is widely used in agent based models. Even in the models where location and Space is widely used in agent based models. Even in the models where location and movement of agents are not important from the model logic viewpoint, space is often movement of agents are not important from the model logic viewpoint, space is often used to visualize the agents.
used to visualize the agents.
Space types in AnyLogic Space types in AnyLogic
AnyLogic supports four
AnyLogic supports four types of spacetypes of space::
Airplane
Airplane
Agent Agent
AnyLogic engine classes AnyLogic engine classes User model User model AgentContinuousGIS AgentContinuousGIS AgentContinuous2D AgentContinuous3D AgentContinuous2D AgentContinuous3D AgentContinuous AgentDiscrete2D AgentContinuous AgentDiscrete2D Combine
Combine Bomber Bomber CellCell
moveTo( longitude,
moveTo( longitude,
latitude )
latitude ) moveTo( moveTo( x,y x,y ) ) moveTo( moveTo( x,y, x,y, z z ) ) jumpToCell( jumpToCell( column )column ) row,row,
X X Y Y X X Y Y Z Z 41°8′44″N 41°8′44″N 3°59′42″W 3°59′42″W [4,3] [4,3] Subclass of Subclass of
•
• Continuous three-dimensional spaceContinuous three-dimensional space •
• Discrete space (grid of cells)Discrete space (grid of cells) •
• GIS (Geographic Information System) spaceGIS (Geographic Information System) space
Correspondingly, there are four base classes for agents:
Correspondingly, there are four base classes for agents: AgentContinuous2DAgentContinuous2D,,
AgentContinuous3D
AgentContinuous3D,, AgentDiscrete2DAgentDiscrete2D, and, andAgentContinuousGISAgentContinuousGIS, see the Figure. Depending, see the Figure. Depending on the space type, agents will have different space-related functions and properties, on the space type, agents will have different space-related functions and properties, like
likemoveTo()moveTo(),, distanceTo()distanceTo(),, jumpToCell() jumpToCell(), velocity, column, row,, velocity, column, row, On arrivalOn arrival action, etc. action, etc. Do not confuse the type of space and the type of animation: 2D continuous or discrete Do not confuse the type of space and the type of animation: 2D continuous or discrete space applies to the model logic only and does not prevent you from creating
space applies to the model logic only and does not prevent you from creating 3D3D animation
animation of the model. of the model.
The space settings are defined in two places: in the agent itself a
The space settings are defined in two places: in the agent itself a nd in thend in theEnvironmentEnvironment
object, see the Figure. The
object, see the Figure. The EnvironmentEnvironment object is required for the discrete and GIS space object is required for the discrete and GIS space types and is o
types and is optional for continuous ptional for continuous spaces. spaces. If theIf theEnvironmentEnvironment object is used, its space object is used, its space type should match the space type of all agents in the environment. If space is
type should match the space type of all agents in the environment. If space is irrelevant to the model logic and
irrelevant to the model logic and animation, you can choose arbitrary space sanimation, you can choose arbitrary space settings.ettings.
Agents of different types, populations as well as individual agents, can belong to the Agents of different types, populations as well as individual agents, can belong to the same environment object and share the same space. Environment can be used to same environment object and share the same space. Environment can be used to apply layouts to the agents; i
apply layouts to the agents; it also provides some space-related functions, such ast also provides some space-related functions, such as
getAgentAtCell() getAgentAtCell()..
Space type settings Space type settings
The space type of the
The space type of the
environment and the
environment and the
agent must match
agent must match
This puts the agent
This puts the agent
population into the
population into the
environment
environment
Airplane – agent class
Airplane – agent class
Main class
Discrete space
Discrete space
Thinking of agents as cellular automata living in discrete space is another common Thinking of agents as cellular automata living in discrete space is another common misconception (the first one is assumption of discrete time). Indeed, there are a lot misconception (the first one is assumption of discrete time). Indeed, there are a lot academic models that use discrete space (for example, The
academic models that use discrete space (for example, The Game of LifeGame of Life, Schelling, Schelling Segregation, Heat Bugs, etc.), but in most
Segregation, Heat Bugs, etc.), but in most industrial-level models, space-aware agentsindustrial-level models, space-aware agents live and move in continuous 2D
live and move in continuous 2D or 3D space.or 3D space.
Examples of discrete spaces Examples of discrete spaces
With that said, we will, nevertheless, spend some time on discrete space because there With that said, we will, nevertheless, spend some time on discrete space because there
The Game of Life
The Game of Life The Schelling Segregation ModelThe Schelling Segregation Model
Wildfire
model dynamics of vegetation, water resources, wildfire, or population density model dynamics of vegetation, water resources, wildfire, or population density in ain a geographical space. In such models, land is partitioned in square cells with each cell geographical space. In such models, land is partitioned in square cells with each cell being an agent with its own variables and behavior. Cells may interact with each other being an agent with its own variables and behavior. Cells may interact with each other and with other types of agents, for example, with agents freely moving in 2D space and with other types of agents, for example, with agents freely moving in 2D space that overlaps the discrete space, see the example model
that overlaps the discrete space, see the example model WildfireWildfire described later in described later in this section.
this section.
Discrete space
Discrete space is a rectangular grid of cells, see the Figure. In AnyLogic, it is created is a rectangular grid of cells, see the Figure. In AnyLogic, it is created under the control of the
under the control of the EnvironmentEnvironment object. object.
To create an agent population living in discrete space: To create an agent population living in discrete space:
2.
2. Drag theDrag theAgent populationAgent population object from the object from theGeneralGeneral palette to the graphical palette to the graphical editor.
editor. 3.
3. In theIn theConfigure new environmentConfigure new environment page of the wizard choose page of the wizard chooseSpace typeSpace type::DiscreteDiscrete 2D
2D and set up the space size. and set up the space size.
The options are shown in the Figure. You can choose the visual size of the entire space The options are shown in the Figure. You can choose the visual size of the entire space and the number of rows and columns. A cell is, in general, a rectangle whose width and the number of rows and columns. A cell is, in general, a rectangle whose width equals the space width divided by the number of columns, and height is the space equals the space width divided by the number of columns, and height is the space height divided by the number of rows. AnyLogic does
height divided by the number of rows. AnyLogic does not draw any grid lines not draw any grid lines oror rectangles for cells so it is up to you to decorate the space.
rectangles for cells so it is up to you to decorate the space.
Discrete space options (Advanced page of the Environment properties) Discrete space options (Advanced page of the Environment properties)
The position of the discrete space rectangle on the canvas of the container object, The position of the discrete space rectangle on the canvas of the container object, namely its top left corner, is defined by the position of the presentation of the discrete namely its top left corner, is defined by the position of the presentation of the discrete
Discrete space is chosen
Discrete space is chosen
The visual size of the (rectangular) space
The visual size of the (rectangular) space
The number of grid cells in this case is 200 * 200 = 40000
The number of grid cells in this case is 200 * 200 = 40000
Moore (8 neighbors) or Euclidean (4 neighbors)
Moore (8 neighbors) or Euclidean (4 neighbors)
Arranged, random, or custom
Arranged, random, or custom
Also: random, ring
Also: random, ring
lattice, small world,
lattice, small world,
and scale free
space agent, see the Figure. Therefore, if there are multiple populations of agents in a space agent, see the Figure. Therefore, if there are multiple populations of agents in a single discrete space environment, their presentation shapes should
single discrete space environment, their presentation shapes should be located at thebe located at the same point.
same point.
A grid cell may be either empty or occupied by, at most, one agent. In many models A grid cell may be either empty or occupied by, at most, one agent. In many models there is an agent in every cell. In other words,
there is an agent in every cell. In other words, a cell is itself an agent a cell is itself an agent . In such models,. In such models, agents typically do not move. In
agents typically do not move. In other models (for example, in theother models (for example, in the SchellingSchelling Segregation Model
Segregation Model), there are fewer agents than cells and agents can move from one), there are fewer agents than cells and agents can move from one cell to another. In the latter case you can apply different layout types to the agents, cell to another. In the latter case you can apply different layout types to the agents, such as random or arranged.
such as random or arranged.
Dimensions and neighborhood types of the discrete space Dimensions and neighborhood types of the discrete space
In discrete space there is a notion of
In discrete space there is a notion of neighborhood neighborhood . There are two types of. There are two types of neighborhood
neighborhoods: Moore and s: Moore and Euclidean (also known as Von Euclidean (also known as Von Neumann). In theNeumann). In the MooreMoore
neighborhood
neighborhood a cell has eight neighbors, and the a cell has eight neighbors, and the Euclidean neighborhood Euclidean neighborhood a cell has a cell has
Moore neighborhood Moore neighborhood (8 neighbor cells) (8 neighbor cells) N N NE NE E E W W S S SESE SW SW NW NW NN E E W W S S Euclidean Euclidean neighborhood neighborhood (4 neighbor cells) (4 neighbor cells) Position of the Position of the presentation shape of presentation shape of the discrete space agent the discrete space agent defines the top left defines the top left corner of the space
corner of the space WidthWidth
Height Height Columns Columns Rows Rows
getNeighbors()
getNeighbors() function. The constants function. The constantsNORTHNORTH,, NORTHEASTNORTHEAST,,EASTEAST, etc. defined in the, etc. defined in theAgentAgent class are used to address directions in the discrete space.
class are used to address directions in the discrete space.
Although networks are not frequently used in c
Although networks are not frequently used in conjunction with discrete space, aonjunction with discrete space, a choice of social networks is available, as you can see in the Figure.
choice of social networks is available, as you can see in the Figure.
Example: Schelling segregation
Example: Schelling segregation
In the 1970s, Thomas Schelling, a Nobel
In the 1970s, Thomas Schelling, a Nobel prize winning economist, showed in hisprize winning economist, showed in his articles dealing with racial dynamics “that a preference that one's neighbors be of the articles dealing with racial dynamics “that a preference that one's neighbors be of the same color, or even a preference for a mixture "up to some limit", could lead to total same color, or even a preference for a mixture "up to some limit", could lead to total segregation, thus arguing that motives, malicious or not, were indistinguishable as segregation, thus arguing that motives, malicious or not, were indistinguishable as toto explaining the phenomenon of complete local
explaining the phenomenon of complete local separation of distinct groups. He usedseparation of distinct groups. He used coins on graph paper to demonstrate his theory by placing pennies and nickels in coins on graph paper to demonstrate his theory by placing pennies and nickels in different patterns on the "board" and then moving them one by one if they were in an different patterns on the "board" and then moving them one by one if they were in an "unhappy" situation.” [
"unhappy" situation.” [Wikipedia].Wikipedia].
We will implement Schelling’s model as a discrete space/discrete time agent based We will implement Schelling’s model as a discrete space/discrete time agent based model. The space represents a city, and each cell represents a house. Agents are model. The space represents a city, and each cell represents a house. Agents are people and are two colors: yellow and red. Initially, people are randomly distributed people and are two colors: yellow and red. Initially, people are randomly distributed across the city. There are fewer people than houses, so there is always the possibility across the city. There are fewer people than houses, so there is always the possibility that a person could move. The ag
that a person could move. The agent behavior in this model is ent behavior in this model is very simple:very simple:
•
• If the percentage of people of the same color among one’s neighbors is lowerIf the percentage of people of the same color among one’s neighbors is lower
than a certain threshold value, the person feels unhappy and moves to a than a certain threshold value, the person feels unhappy and moves to a randomly chosen empty house; otherwise the person is h
randomly chosen empty house; otherwise the person is happy and doesappy and does nothing.
nothing.
The threshold value (the preference for the same color) will be a parameter of the The threshold value (the preference for the same color) will be a parameter of the model. Discrete time is originally a
model. Discrete time is originally assumed in this model: the evaluation of hassumed in this model: the evaluation of happinessppiness and moves are performed on discrete time
and moves are performed on discrete time steps. It is, however, possible steps. It is, however, possible to implementto implement an asynchronous version of the model.
an asynchronous version of the model.
Create the population of agents and discrete space: Create the population of agents and discrete space:
1.
1. Create a new model and drag theCreate a new model and drag theAgent populationAgent population object from the object from the GeneralGeneral
palette to the editor of palette to the editor ofMainMain.. 2.
2. In the first page of the wizard, set theIn the first page of the wizard, set thePopulation namePopulation name to topeoplepeople, the, theInitialInitial population size
population size to to80008000, and choose, and chooserectanglerectangle as asAnimationAnimation.. 3.
3. In the next page of the wizard, choose theIn the next page of the wizard, choose theDiscrete 2DDiscrete 2D space type and click space type and click
Finish Finish.. 4.
4. Open the editor ofOpen the editor ofPersonPerson, and add a new parameter. Set the parameter name, and add a new parameter. Set the parameter name to
5.
5. Type the following expression in the default value field of the parameter:Type the following expression in the default value field of the parameter:
randomTrue( 0.5 ) ? red : yellow.
randomTrue( 0.5 ) ? red : yellow. This will ensure there is approximately the same This will ensure there is approximately the same number of red and yellow people in the model.
number of red and yellow people in the model. 6.
6. Select the rectangle shape at the coordinate origin ofSelect the rectangle shape at the coordinate origin ofPersonPerson and type color in and type color in the
theFill colorFill color field of its field of itsDynamicDynamic property page. property page. 7.
7. Run the model. See the rRun the model. See the red and yellow people randomly ed and yellow people randomly distributed acrossdistributed across the discrete 100 by 100 space, see the Figure on the left.
the discrete 100 by 100 space, see the Figure on the left.
The Schelling Segregation Model. Preference is set to The Schelling Segregation Model. Preference is set to 60%60%
Enable the discrete time in the model and implement agent behavior: Enable the discrete time in the model and implement agent behavior:
8.
8. InInMainMain, create a new parameter, create a new parameterPreferencePreference of type of typedoubledouble and default value 0.6. and default value 0.6. This will be the minimum threshold value for the percentage of same color This will be the minimum threshold value for the percentage of same color neighbors.
neighbors. 9.
9. Open the editor ofOpen the editor ofMainMain, select the, select theenvironmentenvironment object, and select object, and selectEnable stepsEnable steps in in its properties. This enables time steps and now we can type behavior rules in its properties. This enables time steps and now we can type behavior rules in the
theOn before stepOn before step and andOn stepOn step action fields of the agents. action fields of the agents. 10.
10. Return to the editor ofReturn to the editor of PersonPerson and add a Boolean variable and add a Boolean variablehappyhappy with initial with initial values
valuestruetrue.. 11.
11. Open theOpen theAgentAgent page of page ofPersonPerson properties and type the following code in the properties and type the following code in theOnOn before step
before step field: field:
Agent[] neighbors = getNeighbors();
Agent[] neighbors = getNeighbors();//default neighborhood model is Moore//default neighborhood model is Moore if( neighbors == null ) {
if( neighbors == null ) { happy = true;
happy = true;//no neighbors are good neighbors//no neighbors are good neighbors } else {
} else {
//count same color neighbors //count same color neighbors int nsamecolor = 0;
int nsamecolor = 0; Initially the population
for( Agent a : neighbors ) for( Agent a : neighbors )
if( ((Person)a).color.equals( color ) )
if( ((Person)a).color.equals( color ) )//need to cast generis Agent to Person//need to cast generis Agent to Person nsamecolor++;
nsamecolor++;
//compare with minimum number //compare with minimum number
happy = nsamecolor >= neighbors.length * get_Main().Preference; happy = nsamecolor >= neighbors.length * get_Main().Preference; }
} 12.
12. And in the fieldAnd in the fieldOn stepOn step type: type:
if( ! happy ) if( ! happy )
jumpToRandomEmptyCell(); jumpToRandomEmptyCell(); 13.
13. Run the model. Watch how the initially Run the model. Watch how the initially mixed population becomes almostmixed population becomes almost fully segregated in just a few steps; see the Figure on the right.
fully segregated in just a few steps; see the Figure on the right.
Even a slight preference to have at least 60% of neighbors of the same color leads to Even a slight preference to have at least 60% of neighbors of the same color leads to strong segregation. You can link a slider control to the
strong segregation. You can link a slider control to thePreferencePreference parameter and parameter and experiment with different values. Another implicit parameter of the
experiment with different values. Another implicit parameter of the model is themodel is the occupancy of the space. In our case it is 80% because we have 8,000 people and occupancy of the space. In our case it is 80% because we have 8,000 people and 10,000 cells (houses). Occupancy affects the ability o
10,000 cells (houses). Occupancy affects the ability o f the system to f the system to reach equilibriumreach equilibrium at high values of preference.
at high values of preference.
Some comments on the model implementation. Notice that in this model each step has Some comments on the model implementation. Notice that in this model each step has two phases: preparation and action (this scheme is shown in the Figure). An agent two phases: preparation and action (this scheme is shown in the Figure). An agent evaluates its neighborhood in the preparation phase (
evaluates its neighborhood in the preparation phase (On before stepOn before step) and moves in the) and moves in the action phase (
action phase (On stepOn step). The agent’s internal variable). The agent’s internal variablehappyhappy is only needed to keep the is only needed to keep the neighborhood evaluation results between the two phases.
neighborhood evaluation results between the two phases.
The two-phase steps are necessary in this case because we must ensure people do not The two-phase steps are necessary in this case because we must ensure people do not move before everyone has evaluated their current neighborhood. If agents were d move before everyone has evaluated their current neighborhood. If agents were d oingoing both things at once, some pe
both things at once, some people would be evaluating their current ople would be evaluating their current neighborhood andneighborhood and some
some would be evaluating “intermediate” neighbowould be evaluating “intermediate” neighborhoods in the middle of movrhoods in the middle of moving,ing, which does not make any sense.
which does not make any sense.
?
?
Convert this model into an asynchronous model. Instead of global steps you can use aConvert this model into an asynchronous model. Instead of global steps you can use acyclic event with random recurrence time inside
cyclic event with random recurrence time inside each agent. In the asynchronouseach agent. In the asynchronous model you will not need to
model you will not need to separate neighborhood evaluation and moving. Compareseparate neighborhood evaluation and moving. Compare the simulation results.
the simulation results.
Example: Conway’s Game of Life
Example: Conway’s Game of Life
And of course we will show how to program, in AnyLogic, The Game of Life – the And of course we will show how to program, in AnyLogic, The Game of Life – the famous invention of John Conway that “opened up a whole new field of mathematical famous invention of John Conway that “opened up a whole new field of mathematical research, the field of cellular automata” [
research, the field of cellular automata” [Martin Gardner, Scientific American]. TheMartin Gardner, Scientific American]. The universe of The Game of Life
cells, each of which is in one of two possible states: dead
cells, each of which is in one of two possible states: dead or alive. Every cell interactsor alive. Every cell interacts with its eight neighbors (Moore neighborhood model is assumed). At each
with its eight neighbors (Moore neighborhood model is assumed). At each step:step:
•
• Any live cell with fewer than two live neighbors dies, as if caused by under-Any live cell with fewer than two live neighbors dies, as if caused by
under-population. population.
•
• Any live cell with two or three live neighbors lives on to the next generation.Any live cell with two or three live neighbors lives on to the next generation. •
• Any live cell with more Any live cell with more than three live neighbors dies, as than three live neighbors dies, as if by overcrowding.if by overcrowding. •
• Any dead cell with exactly three live neighbors becomes a live cell, as if byAny dead cell with exactly three live neighbors becomes a live cell, as if by
reproduction. reproduction.
The initial pattern constitutes the seed of the system, and the rules are applied The initial pattern constitutes the seed of the system, and the rules are applied repeatedly to create further generations [
repeatedly to create further generations [Wikipedia].Wikipedia].
The following is interesting in the
The following is interesting in the context of the agent based modeling technique. context of the agent based modeling technique. OneOne may try to model a dead cell as a cell
may try to model a dead cell as a cell with no agent in it, and a live cell as with no agent in it, and a live cell as a cell with ana cell with an agent. This however will lead to
agent. This however will lead to a very awkward algorithm of reproduction. A morea very awkward algorithm of reproduction. A more elegant implementation is having, in every cell, an agent with two possible states: elegant implementation is having, in every cell, an agent with two possible states: dead or alive.
dead or alive.
Create discrete space and cells: Create discrete space and cells:
1.
1. Create a new model and drag theCreate a new model and drag theAgent populationAgent population object from the object from the GeneralGeneral
palette to the editor of palette to the editor ofMainMain.. 2.
2. In the first page of the wizard, set theIn the first page of the wizard, set theAgent class nameAgent class name to toCellCell,,Population namePopulation name to to
cells
cells, the, theInitial population sizeInitial population size to to1000010000, and choose, and chooserectanglerectangle as asAnimationAnimation.. 3.
3. In the next page of the wizard, choose theIn the next page of the wizard, choose theDiscrete 2DDiscrete 2D space type and click space type and click
Finish Finish.. 4.
4. Open the editor ofOpen the editor ofCellCell and add a Boolean variable and add a Boolean variablealivealive with initial value with initial value
randomTrue( 0.2 )
randomTrue( 0.2 ). 20% of cells will be randomly chosen to be initially alive.. 20% of cells will be randomly chosen to be initially alive. 5.
5. Select the rectangle (the cell animation shape created by the wizard) and typeSelect the rectangle (the cell animation shape created by the wizard) and type this code in the
this code in theFill colorFill color field of its field of itsDynamicDynamic property page: property page:alive ? mediumBlue :alive ? mediumBlue : lavender
lavender.. 6.
6. Run the model. See the initial random pattern.Run the model. See the initial random pattern.
Program the cell behavior: Program the cell behavior:
7.
7. Open the editor ofOpen the editor ofMainMain, select the, select theenvironmentenvironment object, and select object, and selectEnable stepsEnable steps in in its properties. This enables time steps and now we can type behavior rules in its properties. This enables time steps and now we can type behavior rules in the
theOn before stepOn before step and andOn stepOn step action fields of the agents. action fields of the agents. 8.
8. Return to the editor ofReturn to the editor of CellCell and add an integer variable and add an integer variablenaliveneighborsnaliveneighbors. This. This variable will keep a count of live neighbor cells between the evaluation and variable will keep a count of live neighbor cells between the evaluation and action phases of the step, similar to the
action phases of the step, similar to thehappyhappy variable in the variable in the SchellingSchelling Segregation Model
9.
9. Open theOpen theAgentAgent page of page ofCellCell properties and type the following code in the properties and type the following code in theOnOn before step
before step field: field:
naliveneighbrs = 0;
naliveneighbrs = 0;//reset counter//reset counter for( Agent a : getNeighbors() )
for( Agent a : getNeighbors() ) //count all alive neighbors//count all alive neighbors if( ((Cell)a).alive )
if( ((Cell)a).alive )//need to cast generic Agent to Cell//need to cast generic Agent to Cell naliveneighbrs++;
naliveneighbrs++; 10.
10. And in the fieldAnd in the fieldOn stepOn step type: type:
if( alive && naliveneighbrs < 2 ) if( alive && naliveneighbrs < 2 )
alive = false;
alive = false;//die because of loneliness//die because of loneliness else if( !alive && naliveneighbrs == 3 ) else if( !alive && naliveneighbrs == 3 )
alive = true;
alive = true;//new cell is born//new cell is born else if( alive && naliveneighbrs > 3 ) else if( alive && naliveneighbrs > 3 )
alive = false;
alive = false;//die because of overcrowding//die because of overcrowding
11.
11. Run the model and watch the evolution of this exciting artificial world.Run the model and watch the evolution of this exciting artificial world.
The Game of Life The Game of Life
Although The Game of Life is
Although The Game of Life is a “zero-player game”, i.e., its evolution is a “zero-player game”, i.e., its evolution is entirelyentirely determined by its initial state [
determined by its initial state [Wikipedia], we can bring in Wikipedia], we can bring in some instructiveness. Forsome instructiveness. For example, we can program the cell to toggle its state on mouse click. Then we will example, we can program the cell to toggle its state on mouse click. Then we will bebe able to initiate additional waves of evolution in static or oscillating configurations. able to initiate additional waves of evolution in static or oscillating configurations.
Add cell’s reaction on mouse click: Add cell’s reaction on mouse click:
12.
12. In the editor ofIn the editor ofCellCell, select the rectangle animation shape and type this code in, select the rectangle animation shape and type this code in the
theOn clickOn click field of its field of itsDynamicDynamic property page: property page:alive = ! alive;alive = ! alive; 13.
13. Play with the model.Play with the model.
Initial
Initial configuraion configuraion (randomly (randomly generated) generated) Step Step 51495149
Pulsar Pulsar
Example: Wildfire
Example: Wildfire
We will build a model of a wildfire. In this example we will
We will build a model of a wildfire. In this example we will show how the two types ofshow how the two types of space, continuous and discrete, can be linked.
space, continuous and discrete, can be linked.
We will model vegetation as grid cells – agents in discrete space. The burning time of a We will model vegetation as grid cells – agents in discrete space. The burning time of a cell is proportional to the amount of “fuel” in the cell, which will
cell is proportional to the amount of “fuel” in the cell, which will be randomlybe randomly generated at the model startup. While burning, the cell may cause ignition in the generated at the model startup. While burning, the cell may cause ignition in the adjacent cells. The ignition may also be caused by a bomb dropped by an aircraft – adjacent cells. The ignition may also be caused by a bomb dropped by an aircraft – anan agent moving in continuous 2D space that
agent moving in continuous 2D space that overlaps the discrete space.overlaps the discrete space.
As an additional exercise, we can introduce the wind into the model and make the As an additional exercise, we can introduce the wind into the model and make the probability of ignition depend on the
probability of ignition depend on the wind direction.wind direction.
Create the grid cells: Create the grid cells:
1.
1. Create a new model and drag the Agent population object to the editor ofCreate a new model and drag the Agent population object to the editor of
Main
Main. On the first page of the wizard type:. On the first page of the wizard type:
Agent class name
Agent class name::GridCellGridCell Population name
Population name::gridcellsgridcells Initial population size
Initial population size::4000040000 Animation
Animation::RectangleRectangle
Press PressNextNext.. 2.
2. On the second page of the wizard, choose theOn the second page of the wizard, choose theDiscrete 2DDiscrete 2D Space typeSpace type for the for the environment and make the foll
environment and make the following settings:owing settings:
Width Width: 600: 600 Height Height: 600: 600 Columns Columns: 200: 200 Rows Rows: 200: 200 Initial location
Initial location::ArrangedArranged
Press
PressFinishFinish. The wizard creates a new environment object, a population of. The wizard creates a new environment object, a population of grid cells, and places the animation of a cell
grid cells, and places the animation of a cell (a small blue rectangle) nearby.(a small blue rectangle) nearby. 3.
3. Run the model. You should see a square space filled with 40,000 cells. YouRun the model. You should see a square space filled with 40,000 cells. You should also see that the model consumes 60-70% of the default available should also see that the model consumes 60-70% of the default available memory (64K). This is because of the number of agents.
memory (64K). This is because of the number of agents. 4.
4. Open the editor ofOpen the editor ofGridCellGridCell. Select the blue rectangle and change both its . Select the blue rectangle and change both its widthwidth and height to 3 pixels (these settings are on the
and height to 3 pixels (these settings are on theAdvancedAdvanced property page). Now property page). Now the cell animations will not overlap.
the cell animations will not overlap. 5.
5. Open the editor of theOpen the editor of theSimulationSimulation experiment and extend the frame (the default experiment and extend the frame (the default model window border) to 800 by 650 pixels. The entire area now will be
model window border) to 800 by 650 pixels. The entire area now will be visible.