You are on page 1of 23

HowtoBuildaCombined

AgentBased/SystemDynamicsModel
inAnyLogic
—–‘”‹ƒŽ

©2008XJTechnologieswww.anylogic.com

 
HowToBuildaCombinedAgentBased/SystemDynamicsModelinAnyLogic.Tutorial

Contents
Introduction...................................................................................................................................................3
Theproblemdefinition..................................................................................................................................4
Theplan.........................................................................................................................................................5
Modeldevelopment......................................................................................................................................6
Phase1.Create1000agentswithemptybehavior..................................................................................6
Phase2.AddsimplestateͲbasedbehaviortotheagents.........................................................................9
Phase3.AddtheretailerstockwithsomeinitialamountofproductA.................................................11
Phase4.AddSDsupplychainfortheproductA.....................................................................................12
Phase5.Visualizethedynamicsofdemandanduserbase....................................................................14
Phase6.Addagentcommunicationtomodelwordofmouth...............................................................16
Phase7.Addproductdiscards................................................................................................................18
Phase8.AddproductBtothemodel.....................................................................................................19
Phase9.Addproductswitchingtriggeredbywaitingtime....................................................................20
Experimentingwiththemodel....................................................................................................................23



©2008XJTechnologieswww.anylogic.com Ͳ2Ͳ

HowToBuildaCombinedAgentBased/SystemDynamicsModelinAnyLogic.Tutorial

Introduction
AnyLogicallowsyoutobuildasimulationmodelusingmultiplemethods:SystemDynamics,AgentBased
andDiscreteEvent(ProcessͲcentric)modeling.Moreover,youcancombinedifferentmethodsinone
model:putagentsintoanenvironmentwhosedynamicsisdefinedinSDstyle,useprocessdiagramsor
SDtodefineinternalsofagents,etc,etc.AnykindofmixedarchitectureispossibleduetoflexibleobjectͲ
orientedAnyLogicmodelinglanguage.
Thechoiceofmodelarchitecture(howtopartitionthemodelintocomponents,whattoaggregate,
whichgranularitytouse,whatbehaviorisbestmappedtoaprocessdiagram,andwhat––toastatechart,
etc)belongsmainlytothedomainofartandintuitionofthemodelerandisoutsidethescopeofthis
shorttutorial.ThegoalofthistutorialistoshowstepͲbyͲstephowtobuildacombinedAB+SDmodelin
AnyLogicusingoneparticulararchitecture.Wewillhighlightthe““pointsofinteraction””ofagentsand
systemdynamicsandtrytoshowthatmodelelementsbelongingtodifferentapproachesliveasingle
spaceofAnyLogicmodelandcaneasilyaccesseachother.Havingcompletedthistutorialyoushouldbe
abletobuildvariousmultiͲmethodmodelswithmoreconfidenceandefficiency.
ThetutorialdetailslevelassumessomefamiliaritywithAnyLogicmodeldevelopmentenvironment:the
instructionsinmostcasesareofthetype:““CreateastatePotentialUser””ratherthan““OpentheModel
palette,clickontheStateitem,thenclickonthecanvasandenterPotentialUserintheeditbox””.

©2008XJTechnologieswww.anylogic.com Ͳ3Ͳ

HowToBuildaCombinedAgentBased/SystemDynamicsModelinAnyLogic.Tutorial

Theproblemdefinition
Wewillbuildamodelofaconsumermarketandasupplychain.
Theassumptionswemakeaboutthemarketaresimilartoonesoftheclassicalmodelsof
product/innovationdiffusion,e.g.ofBassmodelwithdiscardsandreplacements.Wewillhowever
considertwocompetingproductsinsteadofone.

x TherearetwoalternativeproductsAandBmanufacturedbydifferent(andcompeting)
companies.Theproductsareequivalent,i.e.canreplaceeachother.Theproductpricesare
equalandthereforedonotmatter.
x Consumers(thereareTotalPopulation=1000ofthem)initiallyarenotusinganyproductsbut
allarepotentiallyinterested(arepotentialusers).
x Consumersaresensitivetoadvertizingandtowordofmouth.
x Advertizinggeneratesthedemandforaproductamongthepotentialusers.Advertizing
Effectiveness=0.011isthepercentofpotentialusersthatbecomereadytobuyaparticular
product(AorB)duringaday.Bothcompaniesdoadvertizing.
x Consumerscontacteachother.AconsumercontactsonaverageaContactRate=5other
peopleperday.
x Duringthosecontactstheusersofproductsmayinfluencepotentialusers.Ifauserofe.g.A
contactsapotentialuser,thelatterwillwanttobuyAwithprobabilityAdoptionFraction=
0.015,sameforB.
x AnyproductdiscardsinDiscardTime=uniform(17,23)daysandgeneratestheimmediateneed
tobuyareplacementofthesamebrand.
x Ifapersonwantstobuye.g.A,butAisnotavailableforMaximumWaitingTime=2days,he
becomesreadytobuyanythingthatisavailable(AorB),sameforB.
Eachcompany(AandB)hasitsownsupplychainthatdeliversproductstotheendconsumers.The
supplychainsareverysimpleandworkasfollows:

x Theproductcanbepurchasedbyaconsumeronlyfromtheretailerstock,initiallyholdinga
certainamount(InitialRetailerStock=100)ofproduct.
x Theproductismanufacturedbyaproducer.AproducermakesProductionRateproductsper
day,andthisratemayvary,e.g.itcanbeadjustedaccordingtothedemand(whichisknownto
theproducer)
x ThefinishedproductsaredeliveredtotheretailerwithinDeliveryTime=2days.
TheoutputofthemodelshouldincludethemarketsharesforAandB,thedemand(i.e.thenumberof
peoplewhowanttobuywhiletheproduct(s)arenotavailable)andtheinventorylevelsinthesupply
chains.

©2008XJTechnologieswww.anylogic.com Ͳ4Ͳ

HowToBuildaCombinedAgentBased/SystemDynamicsModelinAnyLogic.Tutorial

Theplan
WewillmodeltheconsumermarketinAgentBasedway:eachconsumerwillbeanagent.Thesupply
chainsforbothproductsAandBwillbedoneusingSystemDynamics.Pleasenotethattheproblem
definitionallowsmanyotherchoices––thisisjustoneofthem.

TheMarket

TheSupplyChain


Asyouobviouslyknow,thebestwaytodevelopsimulationmodelsistodoititeratively,i.e.inmultiple
phaseswitharunnablemodelattheendofeachphase.Inourcaseitmakessensetohavethefollowing
order:
1. Startwiththemarketmodelandjustoneproduct(A)
a. Buildthebehaviormodelofanindividualconsumer
b. Populatethemarketwiththeconsumers
c. Assumetheproductisavailable
2. AddsupplychainfortheproductA
3. AddproductB

©2008XJTechnologieswww.anylogic.com Ͳ5Ͳ

HowToBuildaCombinedAgentBased/SystemDynamicsModelinAnyLogic.Tutorial

Modeldevelopment
Phase1.Create1000agentswithemptybehavior
InthisphasewewillcreateanewAnyLogicproject,defineanActiveObjectclassforourconsumers,
drawasimpleanimationofaconsumer,define,createandvisualizeapopulationof1000consumers.
Theconsumerswillhavenobehavioratthistime,sothemodelwillbedoingnothing.
1. CreateanewprojectMixedMethodModelͲABMarketandSDSupplyChain
AnewprojectalwayshasoneActiveObjectclassMain,whoseeditoropensautomatically.Mainwillbe
thetoplevelofourmodelwherewewilldefinetheinteractionbetweentheagentbasedandsystem
dynamicsparts.Wewillleaveitblankfornowandstartwithdevelopingthemodelofaconsumer.

2. CreateanewActiveObjectclassConsumer
Weneedaseparateclassforconsumers,inwhichwewilldefinetheconsumerbehavior.Havingthat
behaviorencapsulatedinaclassenablesustocreatemultipleinstancesofconsumers.Theeditorand
propertiesoftheclassConsumeropenwhenyoucreateit.


3. InthepropertiesoftheclassConsumerspecifythatConsumerisanAgent
ThiswillenablesomeusefulAnyLogicservicesforagents,forexamplecommunication,space,layout,etc.
TheiconoftheactiveobjectclassConsumerchanges.


4. IntheeditorofConsumerdrawavisualrepresentationofaconsumerusinge.g.aCurveshape
nearthecoordinateorigin.Youmaywanttousemaximumzoomforfinepositioningofthecurve
points.SetlinecolorofthecurvetoNoColorandfillcolortogray
Eachconsumerwillbevisualizedbysuchshape.Thecoloroftheshapeaswellasitsotherpropertiescan
bedynamicallysetupbyeachindividualconsumer.


5. DragtheclassConsumerfromtheprojecttreetotheeditorofMain

©2008XJTechnologieswww.anylogic.com Ͳ6Ͳ

HowToBuildaCombinedAgentBased/SystemDynamicsModelinAnyLogic.Tutorial

ThiswaywespecifythatinstanceofConsumerisembeddedinthetopͲlevelobjectMain.Theiconandthe
presentationofconsumerappearintheeditorofMain.


6. Movethepresentationoftheembeddedconsumertotheposition(50,250)onMain
Thiswillbethetopleftcorneroftherectangularspacewherewewilllateronvisualizetheconsumer
population.Theothermodelelementswillbelocatedaboveit.

7. SettheReplicationpropertyoftheembeddedconsumerto1000.Changethenameofthe
embeddedobjectfromconsumertoconsumers
ThiswaywetellAnyLogicthatinsideMaintherewillbenotonebut1000consumers.consumerswillbe
thenameofthatpopulation.Thesquarebrackets[..]appearnearthenametoindicatethereplication.

8. AddenvironmentobjectfromtheModelpalettetoMain.SetthepropertyEnvironmentofthe
consumerpopulationtoenvironment
Environmenttakescareofspace,layout,network,communicationofagents.Inourcaseweneed
environmenttolayouttheagentpresentationsandtomodelwordofmouthbyagentͲtoͲagent
interaction.


9. Runthemodel
Youshouldbeabletoseethepicturesimilartotheonebelow.Thereisnodynamicsinthemodel,so
nothingchangesovertime.Inthenextstepwewilladjustthewindowsizeandtheagentspaceborders.

©2008XJTechnologieswww.anylogic.com Ͳ7Ͳ

HowToBuildaCombinedAgentBased/SystemDynamicsModelinAnyLogic.Tutorial


10. IntheprojecttreeexpandtheexperimentitemSimulation:Mainandthenexpandits
Presentationsubitem.ClickonFrametoviewitsproperties.Setthewidthoftheframeto1000
andHeightto600.
Thisisthewayyouspecifytheinitialwindowsizeofthesimulation.


11. IntheeditorofMainclickenvironment.IntheAdvancedpageofitspropertiessetspacewidth
to900andspaceheightto300.
Nowtheagentswillbevisualizedinarectangularspacethatfitsthewindow.


12. Runthemodelagain
Thelayoutshouldlookbetternow.

©2008XJTechnologieswww.anylogic.com Ͳ8Ͳ

HowToBuildaCombinedAgentBased/SystemDynamicsModelinAnyLogic.Tutorial

Phase2.AddsimplestateǦbasedbehaviortotheagents
Basedontheproblemdefinition,wewilldefinethebehaviorofaconsumerasasequenceofthree
states:PotentialUser,WantA,UsesA.Wewillassumethattheproductisalwaysavailable,sothe
transitionfromWantAtoUsesAwillbeunconditionalandimmediate.Theeffectofadvertizingwillbe
modeledasstochasticdelayassociatedwithatransitionfromPotentialUsertoWantA.Noproduct
discardsandnoagentͲtoͲagentcommunicationwillbeaddedinthisphase.
1. IntheeditorofConsumerdrawthreestates(topdown):PotentialUser,WantAandUsesA.Draw
thestatechartentrypointpointingtothestatePotentialUser.
Thestatesinthestatechartarealternative:theagent(inourcase––theconsumer)canonlybeinonestate
atatime.Thestatechartentrypointmarkstheinitialstate,whichobviouslyisPotentialUser.Thenameof
thestatechartentrypointisthenameofthestatechart.Ingeneral,anActiveObjectinAnyLogicmayhave
multiplestatecharts,butnowweneedonlyone.


2. DrawtransitionfromPotentialUsertoWantAandcallitAdA.DrawtransitionfromWantAto
UsesAandcallitBuyA.CheckthecheckboxShownameforeachtransitionandadjustthe
positionsoflabelsintheeditor
Transitionsdefinehowtheobjectchangesitsstates.Atransitionmaybetriggeredbye.g.amessage
arrival,acondition,ortime.ThetransitionAdAwillmodeltheeffectofadvertizing,andBuyA––theevent
ofpurchasingtheproductA.


3. SpecifythefollowingpropertiesforthetransitionAdA:Triggertype:RateandRate:0.011

©2008XJTechnologieswww.anylogic.com Ͳ9Ͳ

HowToBuildaCombinedAgentBased/SystemDynamicsModelinAnyLogic.Tutorial

TransitionofratetypeinAnyLogicinthiscaseisthesameastransitiontriggeredbyastochastictimeout
distributedexponentially.WhenthestatechartentersthestatePotentialUse,adrawfromtheexponential
distributionismadeandthetimeoutissetup.Therefore,eachconsumerwillhavedifferenttimeof
adoptionbecauseofadvertizing,sothatonaverage1.1%ofpotentialuserswillwanttobuytheproductin
onetimeunit(day).


4. SpecifythefollowingpropertiesforthetransitionBuyA:Trigger:timeoutandTimeout:0.
Asweassumethattheproductisalwaysavailable,anybodywhowantstheproductcanimmediatelybuyit
––thereforeoncetheconsumerstatechartentersthestateWantA,itwillproceedtostateUsesAwithzero
delay.

5. IntheEntryactionofthestateWantAwrite:curve.setFillColor(pink);
IntheEntryactionofthestateUsesAwrite:curve.setFillColor(red);
Thiswaywewillchangethecoloroftheconsumerpresentationtovisualizethechangeofitsstate.Asyou
cansee,allmodelandpresentationelementsoftheactiveobjectclassareaccessibleonefromanother.
NotethatifyouhaveusedotherkindofshapetodrawthepresentationofConsumer,youmayneedto
useothernamefortheshape.


6. Runthemodel.AfterawhileyoumaypresstheVirtualtimebuttontospeedupthemodel.
Youshouldbeabletoseehowthepopulationofconsumersgraduallyturnsred––thisistheeffectof
advertizing.AlthougheachconsumergoesthroughthestateWantA,inwhichheshouldbepink,youwill
notbeabletoseeitashedoesnotstayinthatstateandimmediatelyproceedstoUsesA.Themodelwill
stopattime100whensomeconsumersareusersandsomearenot.

©2008XJTechnologieswww.anylogic.com Ͳ10Ͳ

HowToBuildaCombinedAgentBased/SystemDynamicsModelinAnyLogic.Tutorial

7. OpenthepropertiesofexperimentSimulation:Main.OntheGeneralpagesetRandomseed
(uniquesimulationruns).IntheModeltimepagesetStoptime:Never.
Asourmodelisstochastic(youmayrememberthatthesourceofstochasticityistheratetransitionAdAin
theconsumers’’statecharts),thesimulationresultswilldependontherandomnumbergeneration.By
settingtheRandomseedyoutellAnylogictousedifferentsequencesofrandomnumbersforeachrun.By
settingtheStoptimetoneveryoutellAnyLogictoexecutethemodelinfinitelylong(oruntilthereis
nothingtoexecute).

8. Runthemodelagain
Youwillseethateventuallyallconsumerswillbuytheproduct.

Phase3.AddtheretailerstockwithsomeinitialamountofproductA
Inthisphasewewilladdthefirst(actuallytheend)elementofthesupplychainforproductA:the
retailerstock.The(SystemDynamics)stockwillhavesomeinitialamountofproduct,sosomeconsumers
willbeabletobuytheproduct.WewillmodifytheconsumerbehaviorsothatthetransitionfromWantA
toUsesAwillonlybepossibleifthethereisatleastoneunitofproductonstock.Asaresultofa
consumertakingthistransitiontheamountofavailableproductwillbedecremented.Thisisthefirst
pointofinteractionoftheAgentBasedandtheSystemDynamicscomponentsinthemodel.
1. OpentheeditorofMainandaddastockvariableRetailerStock.Setitsinitialvalueto100.
ThisisthefirstSystemDynamicselementinthemodel.WedefineitinMain––onthesamelevelwherewe
haveembeddedthepopulationofagentsͲconsumers.


2. GototheeditorofConsumerandchangethepropertiesofthetransitionBuyA:itshouldnow
havetriggertypeCondition,theCondition:get_Main().RetailerStockA>=1andAction:
get_Main().RetailerStockAͲͲ;
ThisishowweimplementtheABͲSDinteraction:wheninthestateWantAaconsumerconstantly
monitorsthestockRetailerStockA;whenthestockcontainsatleastoneproduct,thetransitionistaken
and,asaresult,oneunitofproductisdeductedfromthestock.Pleasenotethat,asthestockislocated
onelevelupregardingtheconsumerbehavior(attheMainobjectthatcontainstheconsumer),weneed
firstgettoMainandonlythenwecanaccessthestock––thatiswhyweusetheprefixget_Main(),which
bringsustothecontainerofConsumeroftypeMain.

©2008XJTechnologieswww.anylogic.com Ͳ11Ͳ

HowToBuildaCombinedAgentBased/SystemDynamicsModelinAnyLogic.Tutorial


3. Runthemodelinvirtualtime(fast)mode.
Youwillseethat100consumerswillbeabletobuyA,whileallotherswilleventuallyturnpinkasthe
retailerisoutofstock.

Phase4.AddSDsupplychainfortheproductA
WewilladdtheremainingpartofthesupplychainforA:productionanddelivery.Thesupplychainwill
beapureSystemDynamicsconstructstartingwithProductionflowintoFactorystockandthenthrough
theDeliveryflowtotheRetailerstock.Wewillfirstmaketheproductionrateconstantandthen––
variable,dependingonthedemandfortheproduct.Thiswillbeasecondpointofinteractionbetween
theABandtheSDpartsofthemodel.TofeedthedemandintotheSDpartwewilladdastatisticsitem
totheconsumerpopulation:itwillcalculatethenumberofconsumersthatareinthestateWantA.The
productionratewillberecalculatedonceadayaccordingtothatnumber.
1. IntheeditorofMainaddthestockFactoryStockAtotheleftofRetailerStockA.Drawflowfrom
FactoryStockAmtoRetailerStockA(bydoubleͲclickingthesourcestockandclickingatthesink
stock).CallthecreatedflowDeliveryA.SettheformulaforDeliveryA=FactoryStockA/2
Thiswaywemodelthedeliverydelayof2daysfromthefactorytotheretailerstock.


2. AddtheflowvariableProductionAtotheleftofFactoryStockAandletitflowintoFactoryStockA.
LettheProductionA=15.
Wewillassumeaconstantproductionratefornow.

©2008XJTechnologieswww.anylogic.com Ͳ12Ͳ

HowToBuildaCombinedAgentBased/SystemDynamicsModelinAnyLogic.Tutorial


3. Runthemodel
Youwillseethatnowthedemandcanbefullysatisfied,andmoreover,theamountofproducedproductis
muchgreaterthanneeded.Obviously,wheneverybodyhaspurchasedtheproduct,thesupplychain
continuestogrowtheretailerstock.


4. IntheeditorofMainclickontheiconoftheembeddedconsumersandopentheStatisticspage
oftheirproperties.AddthestatisticsitemwithnameNWantA.Leavethetypeofstatisticscount.
Intheconditionfieldwrite:item.statechart.isStateActive(item.WantA)
Asourconsumermarketiscompletelydisaggregated,weneedtoiteratethroughallagentstofindout
howmanyofthemwanttobuytheproduct,i.e.areinthestateWantA.Thestatisticsoftypecountdoes
exactlythat:ititeratesthroughthepopulationandcountshowmanyagentssatisfythegivencondition.In
theconditionexpression““item””representsthecurrentagent,““statechart””isthenameoftheconsumer’’s
statechart,““isStateActive””isastandardmethodofstatechart,and““WantA””isthenameofthestate
definedwithintheagent,thatiswhyitneedstheprefix““item.””.


5. IntheeditorofMainaddeventnearbytheflowProductionA.CallitupdateProductionA.Inthe
propertiesoftheeventspecifyTriggertype:timeout,Mode:Cyclic,Recurrencetime:1,Action:
ProductionA=consumers.NWantA();
ByaddingsucheventwebuildyetanotherlinkbetweentheABandSDmodels:nowatthebeginningof
eachdaytheproductionratewillbemodifiedaccordingtothenumberofconsumerswhoarewillingto
buytheproduct.Therecouldbebetterformulasthan““rate=demand””,butthat’’sthesimplestone.
NWantA()isthestatisticsmethodwehavedefinedintheconsumerpopulationinthepreviousstep.

©2008XJTechnologieswww.anylogic.com Ͳ13Ͳ

HowToBuildaCombinedAgentBased/SystemDynamicsModelinAnyLogic.Tutorial


6. IntheformulaforProductionAremove““15””
Nowtheproductionrateisfullycontrolledbytheeventupdatingit,soformulamustberemoved.

7. Runthemodel.ClickontheProductionAtobringupitsinspectwindowandthenclickswitchit
tochartmodebyclickingthesmallcharticonintheupperrightcorner.
Youshouldbeabletoseethatnowtheproductionrateoscillates,whichistypicalforthesupplychains
withtheirinevitabledelays.

Phase5.Visualizethedynamicsofdemandanduserbase
Inthisphasewewillvisualizethedynamicsofunsatisfieddemandgeneratedbythemarketandthe
numberofusers.Aswearemodelingthemarketinacompletelydisaggregatedway,weneedtoadd
anotherstatisticsitemstothepopulationofconsumers,namelytheonecountingthenumberofagents
thatareinUsesAstate.Also,ifwewanttoseethehistoryoftheseoutputs,weneedtocreateacouple
ofdatasetsandachart,e.g.atimestackchart.
1. IntheeditorofMainclickontheconsumersandgototheirStatisticspage.Addthesecond
statisticsitemNUseAof““count””typewithexpressionitem.statechart.isStateActive(item.UsesA
)(whichyoucancopyfromtheitemNWantAandmodify).
2. StayinMainandaddtwodatasetsfromtheAnalysispalette:NWantADSandNUseADS.
Tobeabletovisualizethehistoryofacertainvalue,weneedtokeepthathistoryinadatasetobject.

©2008XJTechnologieswww.anylogic.com Ͳ14Ͳ

HowToBuildaCombinedAgentBased/SystemDynamicsModelinAnyLogic.Tutorial

3. InthepropertiesofNWantADSspecifytheVerticalaxisvalue:consumers.NWantA(),for
NUseADScorrespondingly:consumers.NUseA().
DatasetsinAnyLogicarearraysofpairs(x,y).Ashorizontalaxisvalue(x)istimebydefault,thedataadded
tothee.g.NWantADSwillbeoftype(t,demandattimet).Bydefaultthecapacityofadatasetis100
samples.

4. FromtheAnalysispalettedropTimestackcharttotheeditorofMain
Thebestwaytovisualizethedynamicsoffractionsofthepopulationintimeistimestackchart.


5. Inthepropertiesofthechartaddtwodatasets:NUseADSwithtitleUsersAcolorredand
NWantADSwithtitleDemandforAandcolorpink.SettheVerticalscaleofthechartasFixedto
1000.
Thisdefineswhatwillbeshowninthechart.Bydefaultthetimewindowofthechartis100anditwill
automaticallyupdatethedatasetseach1timeunit.


6. Runthemodel
YouwillseehowtheuserbaseforAgrows.Thesupplychainworkswellandthereisonlyasmallslightly
oscillatingunsatisfieddemand.

©2008XJTechnologieswww.anylogic.com Ͳ15Ͳ

HowToBuildaCombinedAgentBased/SystemDynamicsModelinAnyLogic.Tutorial

Phase6.Addagentcommunicationtomodelwordofmouth
Inthisphaseagentswillstarttalkingtoeachother.Asweareinterestedinusersoftheproducttalking
topotentialusers,wewillsetupacyclictransitioninthestateUsesA.Thetransitionwillbetaken
periodicallyandoneachoccurrencetheagentͲuserwillbesendingamessagetoarandomotheragent
sayingthatproductAisgood.Ifanotheragentisapotentialuser(i.e.isinthestatePotentialUser),he
willreacttosuchamessagebychangingitsstatetoWantA.Obviously,wewillachievethisbeaddinga
transitionfromPotentialUsertoWantAtriggeredbythecorrespondingmessage.
1. GototheeditorofConsumeranddrawatransitioninsidethestateUsesAsuchthatitstartsand
endsonthebordersofthestateandallitssegmentsareinsidethestate.CallitContactA.Set
thetriggertypeofthetransitiontoRatewithrate=5*0.015.SetitsActiontosend("BuyA!",
RANDOM);
Theinternaltransitionisacyclictransitionthatdoesnottakethestatechartoutofthestateinwhichitis
defined.InthiscasethetransitionContactAwilloccurwiththespecifiedrate.Thevalueofrate(5*0.015)
needstobefurtherexplained.Wecouldmodelallcontactsstraightforwardly,i.e.5contactsperday,in
whichcasetheratewouldbe5.Butweknowthatnotallcontactsaresuccessful,i.e.convincepotential
userstobuyA.Thereforeherewemodelonlya““successfulfraction””ofcontactsandmakethemmorerare
bymultiplyingby0.015.Intheactionofthetransitiontheconsumerchoosesanotherrandomconsumer
(notnecessarilythepotentialuser!)andsendshimatextmessage““BuyA!””.


2. GototheAgentpageofthepropertiesoftheConsumerclass.IntheOnmessagereceivedfield
writestatechart.receiveMessage(msg);

©2008XJTechnologieswww.anylogic.com Ͳ16Ͳ

HowToBuildaCombinedAgentBased/SystemDynamicsModelinAnyLogic.Tutorial

InthepreviousstepwehavesetuptheagentsͲuserstoperiodicallycontactotheragentsbysendingthem
themessage““BuyA!””.InthesectionOnmessagereceivedwecanspecifythereactionontheincoming
messages.Thecodeforwardsthemessagetothestatechart,wherewewillspecifyoneadditional
transitioninthenextstep.


3. AddonemoretransitiontothestatechartoftheConsumer:fromPotentialUsertoWantAand
callitWomA.SetthetriggerofthetransitiontoMessage,thetypeofthemessage:String,and
letthetransitiontofireIfmessageequals““BuyA!””.
Thisisthelaststepinmodelingthewordofmouth.Themessagethatcomesfromanotheragentis
forwardedthestatechart,and,ifthestatechartisinthestatePotentialUser,causesanimmediate
transitiontoWantA.Inallotherstatesthemessageisignored.


4. Runthemodel.
Youshouldseethatthemarketsaturationisachievedalotfasternow.ThechartshowsthewellͲknownSͲ
shapedcurveoftheproductadoption.Theunsatisfieddemandduringthepeakofinteresttotheproduct
isquitesignificant.

©2008XJTechnologieswww.anylogic.com Ͳ17Ͳ

HowToBuildaCombinedAgentBased/SystemDynamicsModelinAnyLogic.Tutorial

Phase7.Addproductdiscards
Thisisaverysimplephase.Astheproductisdiscardedafteracertainperiodandtheuserneedstobuya
replacement,wewilladdatransitionfromUsesAtoWantAtriggeredbyaconstanttimeoutDiscard
Time.HavingdefinedsuchtransitionwerestrictthesojourntimeinthestateUsesAbyDiscardTime.
1. InthestatechartofaconsumeraddatransitionfromUsesAtoWantA,callitDiscardA.Setthe
triggertoTimeoutwithvalueuniform(17,23).
WhenthestatechartentersthestateUsesA,asampleofstochastictimeoutisevaluatedandcountdownis
startedforthetransitionDiscardA.Thetimeofusingaparticularproductitem(i.e.thetimespentin
UsesA)thereforewillbedistributeduniformlyfrom17to23.PleasenotethatthetransitionContactAwill
notberesettingthattimeoutasitisaninternaltransition.AftertakingDiscardAtheconsumerwillenter
WantAstate,whichmeansheimmediatelyiswillingtobuyareplacement.


2. Runthemodel
Afterthemarketissaturated(everybodyisusingtheproduct),youwillobservetheperiodicshortagesin
theproductsupplycausedbytheproductexpirationatthemajorityofusers.Thesupplychainasitisset
upnowisnotcapableofsatisfyingthesepeaksofdemand.

©2008XJTechnologieswww.anylogic.com Ͳ18Ͳ

HowToBuildaCombinedAgentBased/SystemDynamicsModelinAnyLogic.Tutorial

Phase8.AddproductBtothemodel
NowwecanaddtheproductBthatcompeteswithproductA.Wewilldoitbysimplycopyingthesupply
chainforAandrenamingitselements.TheproductͲspecificpartoftheconsumer’’sstatechartwillalso
becopiedsothatPotentialUserwillhavetwoalternatives:transitiontoWantAortoWantB.Atthistime
wewillnotmodelthemaximumwaitingtimeforaproduct.Twonewstatisticsitemsandtwodatasets
willbeneededtoshowthedynamicsofthemarket.
1. IntheeditorofConsumerselecttwostatesWantAandUsesAandalltransitions(inotherwords,
selectallstatechartelementsexceptforthestatePotentialUserandthestatechartentrypoint.
Makeacopyoftheselectionandarrangethetransitionsasshowninthescreenshotbelow.
Rename““A1””thatappearsintheendingsofthecopiedelementsto““B””.
InthetransitionsWomBandContactBchange““BuyA!””to““BuyB!””.
InthepropertiesofthetransitionBuyBchangeRetailerStockBtoRetailerStockB.
IntheEntryactionsofstatesWantBandUsesBchangethecolorstolightBlueandblue.
Inthisstepwehavedefinedanalternativepathoftheconsumerbehavior.Weassumethesame
advertizingeffectivenessforproductB(0.011)andsamecontactrateandadoptionfraction(obviouslywe
canchangeanyofthoseparameters).Notethatthenewstatechartstructureallowsonlyinitialchoiceof
productbyapotentialuser;oncetheinitialchoicehasbeenmade,thereisnowayforaconsumerto
switch.


2. IntheeditorofMainclickontheconsumersandgototheStatisticspage.Addtwomorestatistic
items:NWantBandNUseBwithconditions

©2008XJTechnologieswww.anylogic.com Ͳ19Ͳ

HowToBuildaCombinedAgentBased/SystemDynamicsModelinAnyLogic.Tutorial

item.statechart.isStateActive(item.WantB)anditem.statechart.isStateActive(item.UsesB)
correspondingly
ThesestatisticsitemswillcountthedemandandthenumberofusersoftheproductB.

3. IntheeditorofMainselectthewholesupplychainforproductA(allSDelements)andalsothe
eventupdateProductionA,copyitandpastetotheright.Rename:
eventupdateProductionA1toupdateProductionB,stockProductionA1toProductionB,etc.
ChangetheactionofupdateProductionBtoProductionB=consumers.NWantB();
ChangeAtoBinallformulasinthesupplychainforproductB.
Needlesstosay,allthatcopyingandrenamingdoesnotlookelegant.Andindeed,AnyLogicoffersmuch
betterwayofreplicatingpiecesofmodel:youcanpackthesupplychainandthecorrespondingeventinto
anewActiveObjectclass,parameterizeitwithe.g.demand,andinstantiateittwiceinMain:onceforA
andonceforB.Forsimplicityhoweverwearenotdoingitinthistutorial.


4. IntheeditorofMainmakeacopyofthetwodatasets.Changethenamesofthenewitemsto
NWantBDSandNUseBDS.Changetheirvaluestoconsumers.NWantB()and
consumers.NUseB().Addthesedatasetstothechartwithtitles““DemandforB””and““UsersB””.


5. Runthemodel
YouwillseethesymmetricdiffusiondynamicsforAandB.Pleasenotethatthemarketshareisdefined
onlybytheinitialadoptionandcannotchangelateron––becauseoftheconsumer’’sstatechartstructure.

Phase9.Addproductswitchingtriggeredbywaitingtime
Accordingtoourproblemdefinition,ifaconsumerwaitstoolongforaparticularproduct,hebecomes
impatientandwillbuywhateverisavailable(AorB),soproductswitchingispossible.Theconsumer

©2008XJTechnologieswww.anylogic.com Ͳ20Ͳ

HowToBuildaCombinedAgentBased/SystemDynamicsModelinAnyLogic.Tutorial

statechartcaneasilybemodifiedtocapturethis:weshouldaddtwotimeouttransitionsfromWantA
andWantBtoanewstateWantAnything.Fromthatstate,inturn,therewillbetwoalternative
conditionͲtypetransitionstoUsesAandUsesBtriggeredbythepurchaseofthecorrespondingproduct.
1. AddanewstateWantAnythinginthemiddleoftheconsumer’’sstatechart.Drawtwotransitions
fromWantAandfromWantBtothenewstate.CallthemGiveUpWainingAand
GiveUpWaitingB.BothtransitionsshouldbeofTimeouttypewithtimeout2.Makeacopyofthe
transitionBuyA(itwillbecalledBuyA1)andplaceitfromWantAnythingtoUsesA.Similarly,
createacopyofBuyB.Leavethetriggersofthosetransitionsastheyare.IntheEntryactionof
WantAnythingwritecurve.setFillColor(gold);
Thetimeouttransitionsrestrictthewaitingtimeforaparticularproductto5.Oncetheconsumergetsto
thestateWantAnything,hestartsmonitoringavailabilityofbothproductsandwillbuywhateverbecomes
availablefirst.


2. IntheeditorofMainclickontheconsumersandaddyetanotherstatisticsitemNWantAnywith
conditionitem.statechart.isStateActive(item.WantAnything).Addthecorrespondingdataset
NWantAnyDSwithVerticalaxisvalueconsumers.NWantAny()andaddthatdatasettothechart
withgoldcolor.
3. Runthemodel
Youwillseethattheunsatisfieddemandgrowsovertime.Thisiscausedbythewrongdemand
estimationsmadebythesupplychains:theproductionrateforeachproductdependsonlyonthenumber
ofconsumersthatarewaitingforthatparticularproductanddoesnottakeintoaccountthosewhoarein
thestateWantAnything.

©2008XJTechnologieswww.anylogic.com Ͳ21Ͳ

HowToBuildaCombinedAgentBased/SystemDynamicsModelinAnyLogic.Tutorial

4. ModifytheactionsofeventsupdateProductionAandupdateProductionBinthefollowingway:
writeProductionA=consumers.NWantA()+consumers.NWantAny();andProductionB=
consumers.NWantB()+consumers.NWantAny();.
Thiswaywetakeintoaccountthedemandofthoseconsumerswhoarereadytobuyanyproduct.

5. Runthemodel
Nowthesupplychainsworkbetter,althoughthereareslightperiodicshortages.Youcanalsoseethatthe
marketsharesfluctuatealittlebit,i.e.theproductswitchingoccurs.ButthebalancebetweenAandB
staysaround50/50becausethemodeliscompletelysymmetric.

©2008XJTechnologieswww.anylogic.com Ͳ22Ͳ

HowToBuildaCombinedAgentBased/SystemDynamicsModelinAnyLogic.Tutorial

Experimentingwiththemodel
Atthistimethemodelfullyreflectstheproblemdefinitionandyoucandovariousexperimentswithit.
Forexample,youcanplaywiththesupplychainpoliciesandexplorehowtheyaffecttheresulting
marketshares.Itmightmakesensetomonitornotonlythedemandsatisfactionbutalsotheinventory
levelatthestocks(which,obviously,youwishtokeepatminimumlevel).
Thesupplychaincanbemodeledusing““discreteevent””or““process””technology(withAnyLogic
EnterpriseLibraryblocks)insteadoftheSD.Thenitwillbealoteasiertomodelthedeliverytimeand
granularity.
Anotherinterestingsetofexperimentscanbedonewiththeconsumerbehaviorandconsumer
population.Youcanaddasocialnetworkintothemodelwherecontactscanonlyoccurbetweenpeople
whoknoweachother.Thiswillobviouslyaffectthediffusionprocess.Youcanaddheterogeneitytothe
consumersattheparameterslevel(e.g.differentsensitivitytoadvertisingandtowordofmouth,
differentlevelofbrandloyalty),oratthebehaviorpatternlevel(e.g.someconsumersmaybecome
frustratedwiththeproduct,spreadnegativeinformation,etc.).

©2008XJTechnologieswww.anylogic.com Ͳ23Ͳ


You might also like