How to Build a Combined
Agent Based / System Dynamics Model
in AnyLogic
Tutorial
4
“ technologies © 2008 X! Technologies www.anylogic.com
BY How To Build a Combined Agent Based / System Dynamics Model in AnyLogic. Tutorial
Contents
Introduction...
The problem definition
The plan
Model development
Phase 1. Create 1000 agents with empty behavior
Phase 2. Add simple state-based behavior to the agents
Phase 3. Add the retailer stock with some initial amount of product A...
Phase 4. Add SD supply chain for the product A
Phase 5. Visualize the dynamics of demand and user base
Phase 6. Add agent communication to model word of mouth
Phase 7. Add product discards
Phase 8. Add product B to the model
Phase 9. Add product switching triggered by waiting time
Experimenting with the model
© 2008 XJ Technologies www.anylogic.com -2-
BY How To Build a Combined Agent Based / System Dynamics Model in AnyLogic. Tutorial
Introduction
AnyLogic allows you to build a simulation model using multiple methods: System Dynamics, Agent Based
and Discrete Event (Process-centric) modeling. Moreover, you can combine different methods in one
model: put agents into an environment whose dynamics is defined in SD style, use process diagrams or
SD to define internals of agents, etc, etc. Any kind of mixed architecture is possible due to flexible object-
oriented AnyLogic modeling language.
The choice of model architecture (how to partition the model into components, what to aggregate,
which granularity to use, what behavior is best mapped to a process diagram, and what — to a statechart,
etc) belongs mainly to the domain of art and intuition of the modeler and is outside the scope of this
short tutorial. The goal of this tutorial is to show step-by-step how to build a combined AB+SD model in
AnyLogic using one particular architecture. We will highlight the “points of interaction” of agents and
system dynamics and try to show that model elements belonging to different approaches live a single
space of AnyLogic model and can easily access each other. Having completed this tutorial you should be
able to build various multi-method models with more confidence and efficiency.
The tutorial details level assumes some familiarity with AnyLogic model development environment: the
instructions in most cases are of the type: “Create a state PotentialUser” rather than “Open the Model
palette, click on the State item, then click on the canvas and enter PotentialUser in the edit box”.
© 2008 XJ Technologies www.anylogic.com -3-
BY How To Build a Combined Agent Based / System Dynamics Model in AnyLogic. Tutorial
The problem definition
We will build a model of a consumer market and a supply chain.
The assumptions we make about the market are similar to ones of the classical models of
product/innovation diffusion, e.g. of Bass model with discards and replacements. We will however
consider two competing products instead of one.
There are two alternative products A and B manufactured by different (and competing)
companies. The products are equivalent, i.e. can replace each other. The product prices are
equal and therefore do not matter.
Consumers (there are Total Population = 1000 of them) initially are not using any products but
all are potentially interested (are potential users).
Consumers are sensitive to advertizing and to word of mouth.
Advertizing generates the demand for a product among the potential users. Advertizing
Effectiveness = 0.011 is the percent of potential users that become ready to buy a particular
product (A or B) during a day. Both companies do advertizing.
Consumers contact each other. A consumer contacts on average a Contact Rate = 5 other
people per day.
During those contacts the users of products may influence potential users. If a user of e.g. A
contacts a potential user, the latter will want to buy A with probability Adoption Fraction =
0.015, same for B.
Any product discards in Discard Time = uniform(17,23) days and generates the immediate need
to buy a replacement of the same brand.
If a person wants to buy e.g. A, but A is not available for Maximum Waiting Time = 2 days, he
becomes ready to buy anything that is available (A or B), same for B.
Each company (A and B) has its own supply chain that delivers products to the end consumers. The
supply chains are very simple and work as follows:
The product can be purchased by a consumer only from the retailer stock, initially holding a
certain amount (Initial Retailer Stock = 100) of product.
The product is manufactured by a producer. A producer makes Production Rate products per
day, and this rate may vary, e.g. it can be adjusted according to the demand (which is known to
the producer)
The finished products are delivered to the retailer within Delivery Time = 2 days.
The output of the model should include the market shares for A and B, the demand (i.e. the number of
people who want to buy while the product(s) are not available) and the inventory levels in the supply
chains.
© 2008 XJ Technologies www.anylogic.com -4-
BS How To Build a Combined Agent Based / System Dynamics Model in AnyLogic, Tutorial
The plan
We will model the consumer market in Agent Based way: each consumer will be an agent. The supply
chains for both products A and B will be done using System Dynamics. Please note that the problem
definition allows many other choices — this is just one of them.
a —~ The Supply Chain : \
A
As you obviously know, the best way to develop simulation models is to do it iteratively, i.e. in multiple
phases with a runnable model at the end of each phase. In our case it makes sense to have the following
order:
1. Start with the market model and just one product (A)
a. Build the behavior model of an individual consumer
b. Populate the market with the consumers
c. Assume the product is available
2. Add supply chain for the product A
3. Add product B
© 2008 XJ Technologies www.anylogic.com -5-
BS How To Build a Combined Agent Based / System Dynamics Model in AnyLogic, Tutorial
Model development
Phase 1. Create 1000 agents with empty behavior
In this phase we will create a new AnyLogic project, define an Active Object class for our consumers,
draw a simple animation of a consumer, define, create and visualize a population of 1000 consumers.
The consumers will have no behavior at this time, so the model will be doing nothing.
1. Create a new project Mixed Method Model - AB Market and SD Supply Chain
© Consumer
© Main
© Simulation: Main
3. In the properties of the class Consumer specify that Consumer is an Agent
© Consumer - Active Object Class
Genet Name: Consumer Hilgnore
“Advanced
Agent Elsen
4. Inthe editor of Consumer draw a visual representation of a consumer using e.g. a Curve shape
near the coordinate origin. You may want to use maximum zoom for fine positioning of the curve
points. Set line color of the curve to No Color and fill color to gray
fi i BY Or| 7 BS 00% ~Q|
& Main a Consumer £3
5. Drag the class Consumer from the project tree to the editor of Main
© 2008 XJ Technologies www.anylogic.com -6-
§S How To Build a Combined Agent Based / System Dynamics Model in AnyLogic. Tutorial
$s Project £3 | =o)
@ Mixed Method Model - AB Market and SD §
© Consumer
© Main
@ Simulation: Main
6. Move the presentation of the embedded consumer to the position (50,250) on Main
7. Set the Replication property of the embedded consumer to 1000. Change the name of the
embedded object from consumer to consumers
8. Add environment object from the Model palette to Main. Set the property Environment of the
consumer population to environment
g
Properties 52 | EI Console 1
{@| consumers - Consumer
——__]
General
Name: consumers
Type: Consumer
Package: mixed_method_model__ab_ma
Replication:
9. Run the model
© 2008 XJ Technologies www.anylogic.com TF:
BS How To Build a Combined Agent Based / System Dynamics Model in AnyLogic, Tutorial
10. In the project tree expand the experiment item Simulation:Main and then expand its
Presentation subitem. Click on Frame to view its properties. Set the width of the frame to 1000
and Height to 600.
4 @ Mixed Method Model - AB
> @ Consumer
» © Main
4 @ Simulation: Main
4 %& Presentation (7 frame - Frame
[frame (aay
Aa tet: Mixed... General Width: 1000
Aa textl: Experi.
( button Height: 600
11. In the editor of Main click environment. In the Advanced page of its properties set space width
to 900 and space height to 300.
© environment - Environment
‘ontinuous © Discrete
[Genel | spacetype
Advanced
Width: 900
Desetetion | Height: | 300]
12. Run the model again
© 2008 XJ Technologies www.anylogic.com
BS How To Build a Combined Agent Based / System Dynamics Model in AnyLogic, Tutorial
Phase 2. Add simple state-based behavior to the agents
Based on the problem definition, we will define the behavior of a consumer as a sequence of three
states: PotentialUser, WantA, UsesA. We will assume that the product is always available, so the
transition from WantA to UsesA will be unconditional and immediate. The effect of advertizing will be
modeled as stochastic delay associated with a transition from PotentialUser to WantA. No product
discards and no agent-to-agent communication will be added in this phase.
1. In the editor of Consumer draw three states (top down): PotentialUser, WantA and UsesA. Draw
the statechart entry point pointing to the state PotentialUser.
statechart
2. Draw transition from PotentialUser to WantA and call it AdA. Draw transition from WantA to
UsesA and call it BuyA. Check the checkbox Show name for each transition and adjust the
positions of labels in the editor
“& statechart
3. Specify the following properties for the transition AdA: Trigger type: Rate and Rate: 0.011
© 2008 XJ Technologies www.anylogic.com =9-
§S How To Build a Combined Agent Based / System Dynamics Model in AnyLogic. Tutorial
\ AdA - Transition
7
Triggered by: | Rate
Name: AdA
5. Inthe Entry action of the state WantA write: curve.setFillColor( pink );
In the Entry action of the state UsesA write: curve.setFillColor( red );
@ UsesA - State
I
bcd Name: Uses
Fill Color Default =
Entry Action:
| curve.setFilicolor( red );
6. Run the model. After a while you may press the Virtual time button to speed up the model.
Sere ait
Fore eres reread
Can
Omri
Sn
wee te
fat
© 2008 XJ Technologies www.anylogic.com -10-
BS How To Build a Combined Agent Based / System Dynamics Model in AnyLogic, Tutorial
7. Open the properties of experiment Simulation:Main. On the General page set Random seed
(unique simulation runs).In the Model time page set Stop time: Never.
8. Run the model again
Phase 3. Add the retailer stock with some initial amount of product A
In this phase we will add the first (actually the end) element of the supply chain for product A: the
retailer stock. The (System Dynamics) stock will have some initial amount of product, so some consumers
will be able to buy the product. We will modify the consumer behavior so that the transition from WantA
to UsesA will only be possible if the there is at least one unit of product on stock. As a result of a
consumer taking this transition the amount of available product will be decremented. This is the first
point of interaction of the Agent Based and the System Dynamics components in the model.
1. Open the editor of Main and add a stock variable RetailerStock. Set its initial value to 100.
@ consumers [1
Gevicenen
G Retailerstocka
2. Go to the editor of Consumer and change the properties of the transition BuyA: it should now
have trigger type Condition, the Condition: get_Main().RetailerStockA >= 1 and Action:
get_Main().RetailerStockA--;
© 2008 XJ Technologies www.anylogic.com -11-
BS How To Build a Combined Agent Based / System Dynamics Model in AnyLogic, Tutorial
BuyA - Transition
caerel Name: BuyA (WshowName [5
Description
Triggered by: | Condition ~
Condition: get _Main().RetailerStockA >= 1
Action:
get_Main() .RetailerStockA--;
3. Run the model in virtual time (fast) mode.
Ga a
ree els ef Cane |
Phase 4. Add SD supply chain for the product A
We will add the remaining part of the supply chain for A: production and delivery. The supply chain will
be a pure System Dynamics construct starting with Production flow into Factory stock and then through
the Delivery flow to the Retailer stock. We will first make the production rate constant and then —
variable, depending on the demand for the product. This will be a second point of interaction between
the AB and the SD parts of the model. To feed the demand into the SD part we will add a statistics item
to the consumer population: it will calculate the number of consumers that are in the state WantA. The
production rate will be recalculated once a day according to that number.
1. In the editor of Main add the stock FactoryStockA to the left of RetailerStockA. Draw flow from
FactoryStockAm to RetailerStockA (by double-clicking the source stock and clicking at the sink
stock). Call the created flow DeliveryA. Set the formula for DeliveryA = FactoryStockA / 2
/ \
=x =a
FactoryStockA Delivery RetailerStockA
2. Add the flow variable ProductionA to the left of FactoryStockA and let it flow into FactoryStockA.
Let the ProductionA = 15.
© 2008 XJ Technologies www.anylogic.com -12-
BS How To Build a Combined Agent Based / System Dynamics Model in AnyLogic, Tutorial
EEN
ProductionA FactoryStockA DeliveryA —RetailerStockA
3. Run the model
ProductionA —FactoryStockA —DeliveryA—_RetallerStock
ita 3 rc 2815.49
x Re qt Rh 2 of
Oe et ae
Bits ‘id atta eS
t *
ti; tek ®
vy
4. Inthe editor of Main click on the icon of the embedded consumers and open the Statistics page
of their properties. Add the statistics item with name NWantA. Leave the type of statistics count.
In the condition field write: item.statechart.isStateActive( item.WantA )
{| consumers - Consumer
Name: NWantA
Type @ Count © Sum © Average © Min © Max
Expression:
Condition: | item.statechart.isStateActive( item.WantA )
5. Inthe editor of Main add event nearby the flow ProductionA. Call it updateProductionA. In the
properties of the event specify Trigger type: timeout, Mode: Cyclic, Recurrence time: 1, Action:
ProductionA = consumers.NWantA();
© 2008 XJ Technologies www.anylogic.com -13-
BS How To Build a Combined Agent Based / System Dynamics Model in AnyLogic, Tutorial
¥ updateProductionA - Event
‘General Name: updateProductionA, (ZishowName [I
(Bescietionsal
Trigger Type: [Timeout ~| Mode: | Cyclic =
First occurrence time (absolute) @ | 0
8 20 | 12
Recurrencetime 2
Action:
ProductionA = consumers.NWantA();
6. In the formula for ProductionA remove “15”
7. Run the model. Click on the ProductionA to bring up its inspect window and then click switch it
to chart mode by clicking the small chart icon in the upper right corner.
i ini Si Ki ss
i) Ol 64 Cum le oo
Phase 5. Visualize the dynamics of demand and user base
In this phase we will visualize the dynamics of unsatisfied demand generated by the market and the
number of users. As we are modeling the market in a completely disaggregated way, we need to add
another statistics items to the population of consumers, namely the one counting the number of agents
that are in UsesA state. Also, if we want to see the history of these outputs, we need to create a couple
of datasets and a chart, e.g. a time stack chart.
1. In the editor of Main click on the consumers and go to their Statistics page. Add the second
statistics item NUseA of “count” type with expression item.statechart.isStateActive( item.UsesA
) (which you can copy from the item NWantA and modify).
2. Stay in Main and add two datasets from the Analysis palette: NWantADS and NUseADS.
© consumers [.} © NWantans
Qerirorment @ Nuseans
© 2008 XJ Technologies www.anylogic.com -14-
§S How To Build a Combined Agent Based / System Dynamics Model in AnyLogic. Tutorial
3. Inthe properties of NWantADS specify the Vertical axis value: consumers.NWantA\(), for
NUseADS correspondingly: consumers.NUseA().
4. From the Analysis palette drop Time stack chart to the editor of Main
© Nwantans
@ Nuseans 4
9 10 20 30 40 50 60. 2 80. 90 100
5. Inthe properties of the chart add two data sets: NUseA with title Users A color red and
NWantADS with title Demand for A and color pink. Set the Vertical scale of the chart as Fixed to
1000.
\ chart- Time Stack Chart
Name: chart Show Name [Ignore Public
Title Users A
DataSet: _ NUseADS coc: Ta - |
Title Demand for A_
DataSet | NWantaDS Color, [apie ~ |
Time Window: 100
Vertical scale: Fixed 7
6. Run the model
© 2008 XJ Technologies www.anylogic.com -15-
BS How To Build a Combined Agent Based / System Dynamics Model in AnyLogic, Tutorial
Phase 6. Add agent communication to model word of mouth
In this phase agents will start talking to each other. As we are interested in users of the product talking
to potential users, we will set up a cyclic transition in the state UsesA. The transition will be taken
periodically and on each occurrence the agent-user will be sending a message to a random other agent
saying that product A is good. If another agent is a potential user (i.e. is in the state PotentialUser), he
will react to such a message by changing its state to WantA. Obviously, we will achieve this be adding a
transition from PotentialUser to WantA triggered by the corresponding message.
1. Go to the editor of Consumer and draw a transition inside the state UsesA such that it starts and
ends on the borders of the state and all its segments are inside the state. Call it ContactA. Set
the trigger type of the transition to Rate with rate = 5 * 0.015. Set its Action to send( "Buy A!",
RANDOM );
[Properties £2 | El Console|
\ ContactA - Transition
(Semomtel Name: Contact
Triggered by: [Timeout =
Timeout: a.
Action:
send( "Buy A!", RANDOM );
2. Go to the Agent page of the properties of the Consumer class. In the On message received field
write statechart.receiveMessage( msg );
© 2008 XJ Technologies www.anylogic.com -16-
§S How To Build a Combined Agent Based / System Dynamics Model in AnyLogic. Tutorial
‘On Message Received:
statechart.receiveMessage( msg );
3. Add one more transition to the statechart of the Consumer: from PotentialUser to WantA and
call it WomA. Set the trigger of the transition to Message, the type of the message: String, and
let the transition to fire If message equals “Buy A!”.
“@ statechart
Ada WomA
BuyA
« Sa
i Properties £ | El Console
WomA - Transition
j
Gener Name: WomA (WZ) show Name
(Desenptionsal|
Triggered by: | Message ~
Message type: © boolean double @ String
Class Name:
Fire transition: © Unconditionally
message equals
Buy Ai"
4. Run the model.
© 2008 XJ Technologies www.anylogic.com -17-
BS How To Build a Combined Agent Based / Sy
stem Dynamics Model in AnyLogic. Tutorial
we
em aed eae
tym a TE yt athe
gat att oh,
Sele es bag
Phase 7. Add product discards
This is a very simple phase. As the product is discarded after a certain period and the user needs to buy a
replacement, we will add a transition from UsesA to WantA triggered by a constant timeout Discard
Time. Having defined such transition we restrict the sojourn time in the state UsesA by Discard Time.
1. In the statechart of a consumer add a transition from UsesA to WantA, call it DiscardA. Set the
trigger to Timeout with value uniform( 17, 23).
Discard
‘
© Properties £% | EI Console
DiscardA - Transition
General
‘Description |
Name: DiscardA
Triggered by: [Timeout ~
Timeout: uniform(
2. Run the model
17, 23)
© 2008 XJ Technologies www.anylogic.com
-18-
BS How To Build a Combined Agent Based / System Dynamics Model in AnyLogic, Tutorial
Phase 8. Add product B to the model
Now we can add the product B that competes with product A. We will do it by simply copying the supply
chain for A and renaming its elements. The product-specific part of the consumer’s statechart will also
be copied so that PotentialUser will have two alternatives: transition to WantA or to WantB. At this time
we will not model the maximum waiting time for a product. Two new statistics items and two datasets
will be needed to show the dynamics of the market.
1. In the editor of Consumer select two states WantA and UsesA and all transitions (in other words,
select all statechart elements except for the state PotentialUser and the statechart entry point.
Make a copy of the selection and arrange the transitions as shown in the screenshot below.
Rename “A1” that appears in the endings of the copied elements to “B”.
In the transitions WomB and ContactB change “Buy A!” to “Buy B!”.
In the properties of the transition BuyB change RetailerStockB to RetailerStockB.
In the Entry actions of states WantB and UsesB change the colors to lightBlue and blue.
2. In the editor of Main click on the consumers and go to the Statistics page. Add two more statistic
items: NWantB and NUseB with conditions
© 2008 XJ Technologies www.anylogic.com -19-
BS How To Build a Combined Agent Based / System Dynamics Model in AnyLogic, Tutorial
item.statechart.isStateActive( item.WantB ) and item.statechart.isStateActive( item.UsesB )
correspondingly
3. In the editor of Main select the whole supply chain for product A (all SD elements) and also the
event updateProductionA, copy it and paste to the right. Rename:
event updateProductionA1 to updateProductionB, stock ProductionA1 to ProductionB, etc.
Change the action of updateProductionB to ProductionB = consumers.NWantB();
Change A to B in all formulas in the supply chain for product B.
g updateProductionA, & updateProduction’_
/ /
X op () ae X o> Xx > @] oe X ee
ProductionA —FactoryStockA Delivery _—_RetailerStockA. ProductionB —FactoryStockB —DeliveryB_—_RetailerStockB
4. Inthe editor of Main make a copy of the two datasets. Change the names of the new items to
NWantBDS and NUseBDS. Change their values to consumers.NWantB() and
consumers.NUseB(). Add these datasets to the chart with titles “Demand for B” and “Users B”.
1,000
@ NWantans
NUseADS
e 500
@ Nwanteos
@ Nusesos 0
10 20 30 40 50 60 70 80 90 100110120
wm Users A Demand for A mm Users 8 Demand For B
5. Run the model
Raa i)
Serer ea ee co
Phase 9. Add product switching triggered by waiting time
According to our problem definition, if a consumer waits too long for a particular product, he becomes
impatient and will buy whatever is available (A or B), so product switching is possible. The consumer
© 2008 XJ Technologies www.anylogic.com -20-
BS How To Build a Combined Agent Based / System Dynamics Model in AnyLogic, Tutorial
statechart can easily be modified to capture this: we should add two timeout transitions from WantA
and WantB to a new state WantAnything. From that state, in turn, there will be two alternative
condition-type transitions to UsesA and UsesB triggered by the purchase of the corresponding product.
1. Add anew state WantAnything in the middle of the consumer’s statechart. Draw two transitions
from WantA and from WantB to the new state. Call them GiveUpWainingA and
GiveUpWaitingB. Both transitions should be of Timeout type with timeout 2. Make a copy of the
transition BuyA (it will be called BuyA1) and place it from WantAnything to UsesA. Similarly,
create a copy of BuyB. Leave the triggers of those transitions as they are. In the Entry action of
WantAnything write curve.setFillColor( gold );
GiveUpWaitingA GiveUpWaitingB
2. In the editor of Main click on the consumers and add yet another statistics item NWantAny with
condition item.statechart.isStateActive( item.WantAnything ). Add the corresponding dataset
NWantAnyDS with Vertical axis value consumers.NWantAny() and add that dataset to the chart
with gold color.
3. Run the model
"Wma ini pm Sen open
© 2008 XJ Technologies www.anylogic.com -21-
BS How To Build a Combined Agent Based / System Dynamics Model in AnyLogic, Tutorial
4. Modify the actions of events updateProductionA and updateProductionB in the following way:
write ProductionA = consumers.NWantA() + consumers.NWantAny(); and ProductionB =
consumers.NWantB() + consumers.NWantAny();.
5. Run the model
9G) © ae
Saget gt
© 2008 XJ Technologies www.anylogic.com -22-
BY How To Build a Combined Agent Based / System Dynamics Model in AnyLogic. Tutorial
Experimenting with the model
At this time the model fully reflects the problem definition and you can do various experiments with it.
For example, you can play with the supply chain policies and explore how they affect the resulting
market shares. It might make sense to monitor not only the demand satisfaction but also the inventory
level at the stocks (which, obviously, you wish to keep at minimum level).
The supply chain can be modeled using “discrete event” or “process” technology (with AnyLogic
Enterprise Library blocks) instead of the SD. Then it will be a lot easier to model the delivery time and
granularity.
Another interesting set of experiments can be done with the consumer behavior and consumer
population. You can add a social network into the model where contacts can only occur between people
who know each other. This will obviously affect the diffusion process. You can add heterogeneity to the
consumers at the parameters level (e.g. different sensitivity to advertising and to word of mouth,
different level of brand loyalty), or at the behavior pattern level (e.g. some consumers may become
frustrated with the product, spread negative information, etc.).
© 2008 XJ Technologies www.anylogic.com -23-