Upload
others
View
2
Download
0
Embed Size (px)
Citation preview
NetworkSciencewithNetlogo version13/09/2018
1
NetworkSciencewithNetlogoTutorialByTomBrughmans
Firstversion:March2016
Thisversioncreated13/09/2018
Netlogoversionused:6.0.1
Extensionused:nw(pre-packagedwithNetlogo6.0.1)https://github.com/NetLogo/NW-Extension
Citethistutorialas:
Brughmans,T.(2016).NetworkSciencewithNetlogoTutorial,https://archaeologicalnetworks.wordpress.com/resources/#netlogo.
NetworkSciencewithNetlogo version13/09/2018
2
1. IntroductionThistutorialprovidesanintroductiontocreatingagent-basednetworkmodelswithNetlogo.Byworkingthroughthistutorialyouwilllearnhowtocreatenodes,createedges,performlayoutsintroduceprobabilityinedgecreation,createatradeprocessworkingonthenetworkandhowtoderivenetworkmeasures.
2. Conventions,tipsandassumedknowledgeThistutorialassumesbasicknowledgeofNetlogoandofsimulation.ItisrecommendedtowalkthroughtheintroductorytutorialsontheNetlogowebsiteorthetutorialonNetlogoforarchaeologistsontheSimulatingComplexityblog:
https://simulatingcomplexity.files.wordpress.com/2014/07/dispersal_tutorial.pdf
https://ccl.northwestern.edu/netlogo/docs/
Thistutorialwillalsorefertosomenetworksciencejargon,conceptsandtechniques.Youcangetabasicdefinitionofallofthesefromtheglossaryonmyblog:
https://archaeologicalnetworks.wordpress.com/resources/#glossary
Goodintroductionstonetworkscienceincludethefollowing:
Brandes,U.,Robins,G.,McCranie,A.,&Wasserman,S.2013.Whatisnetworkscience?NetworkScience1(01):p.1–15.
Newman,M.E.J.,2010.Networks:anintroduction,Oxford:OxfordUniversityPress.
Codewritteninthistutorialwillbeformattedasinthefollowingexample:breed [nodes node]
Saveyourproject!Dothisregularlyandusemultipleversionsthroughoutthetutorialsothatyoucanfallbackonanearlierversionatanytime.Iwillremindyouregularlythroughoutthetutorialtosaveyourproject.
NetworkSciencewithNetlogo version13/09/2018
3
3. DownloadandinstallNetlogoNetlogoisopensourcesoftwareandcanbedownloadedfreeofchargeforWindows,MacOSXandLinux.
Gotohttps://ccl.northwestern.edu/netlogo/download.shtml.
DownloadtheNetlogoinstaller(thistutorialusesversion6.0.1).
RuntheinstallerandinstallNetlogo.
4. Netlogoresources,manualandinterfaceNetlogohasgreatdocumentationaboutallitsfeaturesandcodeinitsusermanual:https://ccl.northwestern.edu/netlogo/docs/
Thismanualincludestutorials,areferencetothesoftwarefunctions,adictionarytoitsprogramminglanguage,documentationofitsextensionsandmuchmore.
Additionalexternalresourcescanbefoundontheresourcespage:
https://ccl.northwestern.edu/netlogo/resources.shtml
AdetailedreferencetoNetlogo’sInterfacecanbefoundhere:https://ccl.northwestern.edu/netlogo/docs/
ThistutorialwillonlygiveaverybriefintroductiontothekeyelementsoftheNetlogointerfaceyouwillbeusingthroughoutthetutorial.
NetworkSciencewithNetlogo version13/09/2018
4
WhenyouopenNetlogoitshouldlooksomethinglikethis:
Ithasthreetabs:Interface,Info,Code.
TheInterfacetabiswhereyouwatchyourmodelrun.Throughoutthetutorialyouwilladdbuttonsandsliderstocontrolthevariablesofyourmodel,andyouwilladdmonitorsandplotstoinspectwhatyourmodelisdoing.Youcanspeeduporslowdownthesimulationusingthespeedslideratthetopoftheinterface.Thecommandcenteratthebottomwilldisplaymessagesyouaskthemodeltoproduce,andyoucanalsouseittogivetocommandstothemodelfromtheinterfacetab.
NetworkSciencewithNetlogo version13/09/2018
5
TheInfotabiswhereyoudescribeyourmodelusingastandardizedsetofquestions.Addingthisinformationwhenyoushareyourmodelwithotheriscrucialtoenablethemtoworkwithyourmodel.WewillnotworkwiththeInfotabinthistutorial.
TheCodetabiswhereyouwriteandstorethecodeforthemodel.InthistutorialwewillbemainlyworkingintheCodetab.AusefulfeatureistheCheckfunctionatthetopofthistab:clickthistoletNetlogocheckyourcodeforerrors.Ifitfindserrorsthenyouwillbeguided
NetworkSciencewithNetlogo version13/09/2018
6
totheerrorandaskedtoresolveitbeforeyoucancontinue,ifitdoesnotfinderrorsthenyoucanproceedwithcodingorviewingyourmodelinaction.NOTE:thiserrorcheckeronlycheckswhethertheprimitivesusedandtheorderofthecodecomplywiththeNetlogorules(i.e.thecode’svocabularyandgrammar).Itwillnotcheckwhetherthecodedoeswhatyouwantittodo,sogettingnoerrorsisnoguaranteethatthecodeworksthewayitshouldorthewayyouthinkitdoes.Theerrorcheckerwillalwaysneedtobeusedalongsideothererrorcheckingtechniques,likereportingvariablevaluesandcheckingthemagainstexpectations,ortestingsubmodelsindependently.
5. NetlogodictionaryAcrucialresourcewhencodinginNetlogoisitsdictionary:https://ccl.northwestern.edu/netlogo/docs/
Forthistutorial,youwillfindthesectionon‘Links’intheNetlogodictionaryparticularlyuseful,aswellasthedocumentationofthe‘nw’extension.
Youcangetdirectaccess(evenoffline)totheentryaboutaparticularprimitivebyright-clickingitandselectingQuickHelp.
NetworkSciencewithNetlogo version13/09/2018
7
6. CreatenodesNetworksconsistofatleasttwothings:asetofnodesandasetofedges(networksciencejargonforanundirectedrelationship).NodesandedgesinNetlogoareatypeofagents,orturtlesinNetlogojargon.WewillfirstcreatethenodesinNetlogo.
Toavoidusingtheconfusingterm‘turtles’torefertoournodes,wewillcreateanewbreedofagentscalled‘nodes’.Abreedisasetofagentsthatisgivenaspecificnameandcanbecommandedusingspecificvariablesgiventothisagentset.
Tocreateabreed,writeatthetopoftheCodetab:breed [nodes node]
Ifyouclickthecheckboxnowyouwillnoticethattherearenoerrors,sowecancontinuetocode.
Saveyourmodel!
TocreateanumberofnodesandvisualisethemintheInterfacewewillcreateasetupprocedure.AddthefollowingbelowthebreedcommandintheCodetab:
to setup clear-all reset-ticks end
ThisisastandardsetupprocedureinNetlogothatresetstheNetlogointerfaceofanysettingsfromprevioussimulationsandresetstheticksto0toinitiateanewsimulation(Netlogojargonforatimestep).Settingupasimulationmeanswearereadytorunthesimulation.
Nowwewilladdcommandstothisstandardsetupproceduretocreateournodes.Expandtheproceduretothefollowing:
to setup clear-all set-default-shape nodes "circle" create-nodes 50 reset-ticks end
Oursetupprocedurewillnowcreate50nodes,andtheywillberepresentedascircles.Toseethisinaction,wewillneedtoaddabuttonintheInterfacetab.DothefollowingintheInterfacetab:
NetworkSciencewithNetlogo version13/09/2018
8
• Makesurethedropdownboxnexttothegreenplussignhas‘Button’selected.• Clickthegreenplussigncalled‘Add’(seefigurebelow).Yourcursorwillbecomea
bigplussign.• Clickanywhereinthewhitespacenexttotheblackinterfacewindow.Abuttonwill
appearandanewwindowwillopenwhereyoucandeterminewhatthisbuttonwillbeusedfor.
• WritesetupinthecommandsboxofthisnewwindowandclickOK(seefigurebelow).
NetworkSciencewithNetlogo version13/09/2018
9
Youjustcreatedabuttoncalled‘setup’.WhenyoupressthisbuttonthesetupprocedurewewroteintheCodetabwillbeexecuted.Tryit!
Youwillseeacirclebeingcreatedattheverycentreoftheinterfacewindow.Althoughitlookslikeasinglenode,wehaveactuallycreated50nodesthatareallplacedontopofeachotherinthecentreofthewindow,becausewedidnotspecifywheretheyshouldbeplaced.Right-clickthenodeandyouwillnoticethereare50overlappingnodesasinthisfigure:
Wewillsolvethisissueofnodeplacementsoon,butfirstweshouldgiveourselvesmorecontroloverthenumberofnodes.Nowwehave‘hard-coded’thenumberofnodesinourCodetab,whichmakesitalotofworktochangethenumberofnodeswhenexploringourfinalmodelandrunningsimulationexperiments.
Toovercomethisissuewewillnowaddavariablethatcontrolsthenumberofnodes.IntheCodetab,replacecreate-nodes 50with:
create-nodes num-nodes
Wehavenowcreateavariablecallednum-nodeswhichwilldeterminehowmanynodesarecreatedbycreate-nodes.Whenyouclicktheerrorchecker,youwillnoticethatNetlogohasfoundanerror:“NothingnamedNUM-NODEShasbeendefined”.Thisisbecausewehavewrittenavariablethathasnotbeendefinedearlierinthecodeorontheinterface.Wewanttocontrolthevariableintheinterfacewithaslidersothatwecaneasilychangeitwhenrunningoursimulation.
ToovercomethiserrorandcontrolthisvariableintheInterfacetabdothefollowing:
• Clickthedropdownmenunexttothe‘Add’button.• Select‘Slider’.Yourcursorwillchangeintoalargeplussign.• Clickinthewhitespacebelowthe‘setup’button.Asliderwillbecreatedandanew
windowwillopenwhereyoucandeterminewhatthissliderwillbeusedfor.
NetworkSciencewithNetlogo version13/09/2018
10
• Wewillusethisslidertocontrolthevariablenum-nodes,sowritenum-nodesinthebox‘globalvariable’.Setthe‘minimum’to2andclickOK(seefigurebelow).
Youhavenowcreatedasliderwhereyoucanmodifyhowmanynodesyoucreate.Youwillalsonoticethattheerrormessageonthecodetabnolongerappears.
Butthenodesarestilloverlapping,solet’stakecareofthatrightnow!
Saveyourmodel!
7. CircularlayoutYoucanplaceyournodesinmanydifferentwaysdependingonwhatfeatureofthenetworkyouwishtoemphasise,aswewillseelaterinthetutorial.Butsinceweonlyhavenodesandnoedgesyet,let’sjustplaceallnodesalongacircularlayouttoavoidoverlappingnodes.
IntheCodetabaddthefollowingafterthelinecreatingthenodes:layout-circle nodes 10
WehaveusedaNetlogocommandthatpositionsnodesalongacirclewitharadiusof10inarandomorder.IfyougototheInterfacetabnowandclickthesetupbuttonthenyournodeswillbepositionedalongacircleasinthisfigure:
NetworkSciencewithNetlogo version13/09/2018
11
However,youmightwantmorecontrolovertheorderinwhichthenodesareplaced,andnotjustletthembeplacedinarandomorder.Toachievethis,reworkthelayoutlineintheCodetabtoreadlikethis:
layout-circle sort nodes 10
IfyouclickthesetupbuttonintheInterfacetabnow,youwillgetacircularpositioningofallnodes,buttheyareorderedaccordingtotheir‘Who’number(theuniqueIDofaturtleassignedbyNetlogowhenitiscreated)clockwisestartingfromthetopmiddlenodeinthecircle.Youcancheckthisbyrightclickingthenodesinorderandyouwillnoticethattheorderofnodesis0,1,2,3,….(seefigurebelow).
NetworkSciencewithNetlogo version13/09/2018
12
However,onceagainwehard-codedsomethingthatisnotveryflexibleifthemodelenvironmentchanges:thecircleradiusof10.Itwouldbefarbetterifthisradiuswasdefinedbytheresolutionoftheinterfacewindow(i.e.themodel’s‘World’settingsexpressedincoordinates,whichcanbeviewedbyright-clickingtheinterfacewindowandselecting‘Edit’).
IntheCodetabchangethelayoutlinetothefollowing:layout-circle sort nodes max-pxcor - 1
WhenyouclickthesetupbuttonnowontheInterfacetabthecircularlayoutwillhavearadiusequaltotheradiusoftheinterfacewindow(i.e.theWorld’smax-pxcor)minus1topreventitfrombeingtooclosetotheedgesofthewindow:
NetworkSciencewithNetlogo version13/09/2018
13
Saveyourmodel!
8. Networkcreationprocedures:whydoyoucreateanetworkmodel?
Nowthatwehaveasetofnodeswecancreateasetofedgesconnectingthenodes.
Thewayinwhichnodesareconnectedintoanetworkwilldependonyourresearchcontext,andultimatelywillberootedinyourreasonsfordecidingtobuildanetworkmodelinthefirstplace.Edgescouldberandomlyconnected,edgescanbeinformedbyempiricalobservations,orthenetworkstructurecouldrepresentahypothesisedsocial/spatial/othernetworkstructure.
Inthistutorialwewillrandomlycreateanetworkstructure,usingtheErdős–Rényirandomgraphmodel(fromnowonreferredtoasERmodel):anetworkconstructedbyconnectingrandomlyselectedpairsofnodeswithacertainprobabilityindependentfromeveryotheredge.https://en.wikipedia.org/wiki/Erd%C5%91s%E2%80%93R%C3%A9nyi_model
Thisisthemostcommonwayofrandomlycreatingnetworks.Suchnetworksareveryusefulforcomparisonwithhypothesisedsocialprocesses,i.e.processescreatingedgeswithprobabilitiesdependentontheexistenceofotheredges.Forexample,acommonhypothesisforsocialnetworksoffriendshipistheideathatapairofunrelatedindividualshasahigherprobabilityofbecomingfriends(i.e.ofcreatinganedgebetweenapairofnodes)iftheyhaveafriendincommon(i.e.theprobabilityofthenewedgeisdependentontheexistenceofotheredges).NodesAandBinthefigurebelowhavenodeCasamutualfriend,soaccordingtothishypothesistheedgebetweenAandBwillbemorelikelytoappear:
NetworkSciencewithNetlogo version13/09/2018
14
Wecancreatesimulationmodelsrepresentingthishypothesisednetworkcreationprocessandtherandomprocess,andcomparehowtheresultingnetworksdiffer.Canobservedfriendshiprelationshipsbereproducedthrougharandomprocess?Cantheybebetterreproducedthroughanotherhypothesisedprocess?Whatarethestructuralfeaturesofthenetworksarisingfromthehypothesis?
Decidinghowtoconnectnodesthroughedgesinyournetworkwilldependentirelyonyourresearchaimsandcontext.Tothinkaboutwhatmightbethemostappropriatewayofcreatingedgesinyourcontextyoucouldaskyourselfthefollowingquestions:
• WhydidIdecidetomakeanetworkmodel?• Whatarethenodesinmynetwork?• Whataretheedgesinmynetwork?• Arenodesandedgestakenfromempiricalobservations?• Willthenetworkmodelrepresentahypotheticalscenariothatwillbecompared
withempiricalobservations?• Whyarerelationshipsimportantinmyresearchcontext?• Howarerelationshipsdependentoneachother?• Whatkindsofconfigurationsorpatternsofedgesareimportant?• Whataremyhypothesesabouthowedgesarecreated?
9. CreateedgesRelationshipsinNetlogoarecalled‘links’andtheycanbeusedinasimilarwayas‘turtles’.Theycanbeeitherundirectedinwhichcasenetworkscientistsrefertothemas‘edges’,ortheycanbedirectedwhicharecommonlycalled‘arcs’.
Wewillcreateanewbreedofundirected‘links’called‘edges’.IntheCodetabbelowthepreviousbreedaddthefollowing:
undirected-link-breed [edges edge]
NowthatwehavecreatedabreedwecanstartimplementingtheproceduretocreateanERrandomgraphmodel.Wewilldothisinseveralsteps,slowlybuildingupthelinesofcode.
Inthesetupprocedure,addanewproceduretoconnectnodesafterthelayoutofthenodes:
connect-nodes
NetworkSciencewithNetlogo version13/09/2018
15
Yourmodelshouldnowlooklikethis:breed [nodes node] undirected-link-breed [edges edge] to setup clear-all set-default-shape nodes "circle" create-nodes num-nodes layout-circle sort nodes max-pxcor - 1 connect-nodes reset-ticks end
Whenyouclicktheerrorcheckeritwillgiveyouanerrorsaying‘connect-nodes’hasnotbeendefined.Wewillnowaddanewprocedurecalledconnect-nodesbelowthesetupprocedure:
to connect-nodes end
Thiswillresolvetheerrormessage.
Asafirststepwewilladdthefollowingcommandinthisnewprocedure:to connect-nodes repeat 100 [ ask one-of nodes [create-edge-with one-of other nodes] ] end
Thiscodewillselect100nodesrandomlyinturnandeachnodewillbeaskedtocreateanedgewithanotherrandomlyselectednode.
NotethatthenormalcommandforcreatinglinksinNetlogoiscreate-link-with.Butbecausewehavecreatedabreedcallededges,wecanmodifythistocreate-edge-with.HavealookattheNetlogodictionaryformoreinformation:https://ccl.northwestern.edu/netlogo/docs/.
However,nowwhenyouclickthesetupbuttonontheInterfacetabyouwillgetaweirdnetworkwhereedgesseemtocrossthebordersoftheinterfacewindow:
NetworkSciencewithNetlogo version13/09/2018
16
ThishappensbecausebydefaulttheNetlogo‘World’willwraparoundthehorizontalandverticaledges.Thisdoesnotmakemuchsensewhenmakinganetworkmodel!Attheveryleastitisnothelpfulforvisualexploration.Toavoidtheedgesfromcrossingtheseboundaries,right-clicktheinterfacewindow,selectEdit,andintheModelsettingswindowunchecktheboxesfor‘Worldwrapshorizontally’and‘Worldwrapsvertically’:
Whenyoudothis,thenetworkwilllooksomethinglikethis(notethatyournetworkwilllookdifferentbecausetheedgesarerandomlycreated):
NetworkSciencewithNetlogo version13/09/2018
17
WenowneedtoaddanumberoffeaturestomakethisarealERmodel.Thecurrentcodestillallowsforpairsofnodestobeconnectedthatarealreadyconnected,andthenumberofedges(currently100)shouldnotbehard-codedbutratherreflectadesiredfeaturelikethedesireddensityofthenetwork.Networkdensityisdefinedasthefractionofthenumberofedgesthatarepresenttothemaximumpossiblenumberofedgesinthenetwork.
First,wewillasknodestoonlyconsidercreatinganedgewithanodethatitisnotyetconnectedto,bymodifyingtheedgecreationlinetothis:
ask one-of nodes [create-edge-with one-of other nodes with [edge-with myself = nobody]]
Inthiscode,‘myself’referstothenodethatdoestheasking,i.e.thenodeweselectinthefirstlineofthiscode.
Second,wewillreplacethe100toonlycreatethenumberofedgesneededtocreatethedesireddensity.IntheCodetabreplacerepeat 100 withthefollowing:
repeat (target-density * (((num-nodes * num-nodes) - num-nodes)) / 2)
Thisisacalculationofdensityinundirectednetworks.Themaximumnumberofedgesinsuchanetworkcanbecalculatedas:themaximumnumberofedgesisthenumberofnodestimesthenumberofnodes,minusthenumberofnodes(i.e.nodescannotbeconnectedtothemselves),anddividedbytwo(i.e.edgesarenotdirected:indirectednetworkstherearedoubleasmanymaximumlinksbecausetheycangointwodirections).Sincethedensitymeasurerepresentsacertainfractionofthismaximumnumberofedges,wemultiplyitbythevariabletarget-density,whichrepresentthedensitywedesireforournetwork:0representsnoedges,0.5representshalfthemaximumnumberofedgesbeingpresent,1representsallthemaximumnumberofedgesbeingpresent.
Whenyouclicktheerrorcheckeryouwillnoticeanerrorbecausewehavenotyetdefinedthevariabletarget-density.WewilladdthisvariableintheInterfacetabasaslider:
• Makesure‘Slider’isselectedinthedropdownbox.
NetworkSciencewithNetlogo version13/09/2018
18
• Clickthe‘Add’button.• Clickinthewhitespacebelowthe‘num-nodes’slider.Awindowwillappear.• Entertarget-densityinthe‘Globalvariable’field.Theminimumwillbe0,the
increment0.05,themaximum1andtheValue(defaultvalue)0.5.ClickOK.
Theerrormessagewillberesolved.
Nowwhenyouclickthesetupbuttonyournetworkwillalwayshaveonlysomanyedgesasrequiredtoreachthedesireddensity.Forexample,ifyournetworkhas40nodesandyourdesireddensityis0.5thenyouwillcreate390edges:
0.5 ∗40 ∗ 40 − 40
2= 390
Note:ifyougeta‘RuntimeError’atthispoint,click‘Dismiss’.Wewillresolvethiserrorlater.
However,youdon’tknowhowmanyedgesthereareuntilyoucountthem!Neitherdoweknowwhetherthenetworkactuallyhasthecorrectdensityuntilwecalculateit.Thereareafewwayswecoulddothis:usingtheCommandCenterorusingmonitors.
IntheCommandCentercommandlineatthebottomoftheInterfacetabwritethefollowing:
Show count edges
TheresultwillappearintheCommandCenterwindow:
NetworkSciencewithNetlogo version13/09/2018
19
Amoreconvenientwaytocounttheedgesistoaddamonitorthatwillshowyouthenumberofedges.IntheInterfacetabdothefollowing:
• SelectMonitorfromthedropdownbox.• Clickthe‘Add’button.• Clickanywhereinthewhitespace.Anewwindowwillappearwhereyoucan
determinewhatwillbereported.• Writecount edgesinthe‘Reporter’box,setdecimalplacesto1(thereshouldbeno
decimalsbutitisgoodtoaddthisforerrorchecking:ifyouseeadecimalnumberinareporterwindowwhereyoudon’texpectit,youknowyoudidsomethingwrong).
Whenyouclickthesetupbuttonyouwillautomaticallyseethenumberofedgesinthemonitorboxyoujustcreated.
Nowwewillcreateamonitorforthedensity.IntheInterfacetabdothefollowing:
• SelectMonitorfromthedropdownbox.• Clickthe‘Add’button.• Clickanywhereinthewhitespace.Anewwindowwillappearwhereyoucan
determinewhatwillbereported.• Writecount edges / (((num-nodes * num-nodes) - num-nodes) / 2)inthe
‘Reporter’box,setdecimalplacesto2,andsettheDisplayNameto‘density’(otherwisethedisplaynameofthismonitorwillbetheentirecommandweenteredintheReporterbox).Thiscommandcalculatesthefractionofthenumberofedgesthatarepresentoverthemaximumnumberofedges.Thenumberthatthismonitorgivesyoushouldthereforebethesameasthesettingofthetarget-densityvariable.Ifitisnot,thenyouknowyoudidsomethingwrongsoyoucansearchfortheproblemandfixit.
NetworkSciencewithNetlogo version13/09/2018
20
However,thereisaproblemwiththiscode.Whenyouputthetarget-densityvariablehighthenyouwilloftengeta‘RuntimeError’.ThisErrorisveryinformativeandwillhelpusresolveit.Ithighlightsthepartofthecodewheretheproblemliesandtellsusitcannotfindanotherturtle(i.e.node)thatfitsthecriteria:
Theerrortellsusthatweareaskinganodetoidentifyanothernodeitisnotyetconnectedto,whensuchanodedoesnotexist:i.e.theaskingnodeisalreadyconnectedtoallothernodes.
NetworkSciencewithNetlogo version13/09/2018
21
Weresolvethiserrorbyspecifyingthatwewillonlyasknodesthatarenotyetconnectedtoallothernodes,byaddingthefollowingcode:
ask one-of nodes with [count edge-neighbors < (num-nodes - 1)]
Theconnect-nodesprocedurewillnowlooklikethis:to connect-nodes repeat (target-density * (((num-nodes * num-nodes) - num-nodes)) / 2) [ ask one-of nodes with [count edge-neighbors < (num-nodes - 1)] [create-edge-with one-of other nodes with [edge-with myself = nobody]] ] end
Note:inNetlogowecallapairofnodesthatareconnectedlink-neighbors,butsincewecreatedabreedcallededgeswecallcanusethecommandedge-neighbors.
Saveyourmodel!
10. ProbabilityofedgecreationInordertogetanERmodelweneedtochangeonefinalthing:edgesneedtobecreatedwithacertainprobability.Inourcurrentcodeapairofnodesisrandomlyselectedandconnected,whereasinanERmodelthispairisonlyconnectedwithacertainprobability.Beingabletoattachprobabilitiestothecreationofedgesisveryimportantandusefulwhenyouwanttoexpressyourownhypothesesofnetworkcreation.Forexample,inthefriendshipnetworkhypothesismentionedabovewestatedthattheprobabilityofsomeedgesbeingcreatedishigherthanthatofothers:peoplewithmutualfriendswillbemorelikelytobecomefriendsthemselves.
Herewewillintroduceasimplemethodofcreatingedgeswithaprobabilityvariablethatyoucanmanipulatetorepresentyourhypothesisofnetworkcreation.
First,wemodifytheconnect-nodesproceduretoonlycreateanedgeifarandomfloatingpointnumberbetween0and1issmallerthanthenewvariableedge-probability: repeat (target-density * (((num-nodes * num-nodes) - num-nodes)) / 2) [
ask one-of nodes with [count edge-neighbors < (num-nodes - 1)] [if random-float 1 < edge-probability [create-edge-with one-of other nodes with [edge-with myself = nobody]] ] ]
Wenowgetanerrormessagebecausethenewvariabledoesnotexistyet,sodothefollowingintheInterfacetab:
• SelectSliderfromthedropdownbox.• Clickthe‘Add’button.• Clickanywhereinthewhitespace.Anewwindowwillappearwhereyoucan
determinewhatthesliderwilldo.• Writeedge-probabilityinthe‘Globalvariable’box,settheminimumto0,the
incrementto0.05,themaximumto1andthedefaultvalueto0.5.ClickOK.
NetworkSciencewithNetlogo version13/09/2018
22
Ifthisvariableissetto1thenanedgewillalwaysbecreated,ifitissetto0itwillneverbecreated,ifitissetto0.5itwillbecreated50%oftimes.
Whenyouclickthesetupbuttonnowyouwillnoticesomethingiswrongthankstoyourmonitors:thedensityinthemonitorisnotthesameasthetarget-densitysliderandthecount edgesmonitorreportsadifferentvalueeverytimeyoupressthesetupbutton.Thisisbecausethisprocessisrepeatedafixednumberoftimes,butnoteverytimeanedgeiscreated.
Asecondchangeisneeded,thistimereplacingthecoderepeatingthecreationofedges.Wewillimplementthisbycalculatinghowmanyedgesweneedtohaveattheendoftheprocedure(storedasthevariabletarget-edges),andcountinghowoftenanedgeisactuallycreated(weletavariablecalledcounterstartat0,onlywhenanedgeiscreateddoweaddonetothecounter:set counter counter + 1).Weonlystoptheprocedureifwehavecreatedthedesirednumberofedges(weusethewhile [counter < target-edges]commandtorepeattheprocessuntilthevariablecounterequalsthevariabletarget-edges).
Modifytheconnect-nodesproceduretoreadlikethis:to connect-nodes let target-edges (target-density * (((num-nodes * num-nodes) - num-nodes)) / 2)
let counter 0 while [counter < target-edges] [ ask one-of nodes with [count edge-neighbors < (num-nodes - 1)] [if random-float 1 < edge-probability [ create-edge-with one-of other nodes with [edge-with myself = nobody] set counter counter + 1 ] ] ] End
Whenyoupressthesetupbuttonyouwillnoticethatthemonitorsreportwhattheyshould.
NetworkSciencewithNetlogo version13/09/2018
23
Saveyourmodel!
11. Force-directedlayoutNowthatwehaveasetofnodesandasetofedges,wecanplaceournodesinamoreinterestingwaythanjustacircle:wecanuselayoutalgorithmstohighlightstructuralfeaturesofthenetworktoaidvisualexplorationofthenetwork.Wewilldothisbyusingapopularforce-directedlayoutalgorithmcalledtheFruchterman-Reingoldlayoutalgorithm.Itissometimescalledaspring-embeddedlayoutbecausetheedgesactlikespringsbetweenthenodesthatrepeleachother.Moreonforce-directedlayoutalgorithmscanbefoundhere:https://en.wikipedia.org/wiki/Force-directed_graph_drawing
Netlogomakesitincrediblyeasytoimplementthis.Wewillcreateanewprocedurecalledlayout,usingtheNetlogocommand layout-spring.Addthefollowingcodebelowtheconnect-nodesprocedure:
to layout layout-spring nodes edges 0.2 5 1 end
Right-clickthelayout-springcommandtoaccesstheNetlogodictionaryandfindoutwhatthiscodedoes.Itwillperformthelayoutconsideringtheagent-setnodesasthenodesandthelink-setedgesastheedges.Thethreenumbersarevariablesofthealgorithmdeterminingfeaturesofthe“springs”:theirresistance,lengthandrepulsion.
InordertousethisnewlayoutprocedureweneedtoaddabuttontotheInterfacetab:
• SelectButtonfromthedropdownbox.• Clickthe‘Add’button.• Clickanywhereinthewhitespace.Anewwindowwillappearwhereyoucan
determinewhatthebuttonwilldo.• Writelayoutinthe‘Commands’box.ClickOK.
Nowyoucanpressthelayoutbuttontoperformthelayout.
NetworkSciencewithNetlogo version13/09/2018
24
Notethatthisalgorithmworksdifferentlyfromthecircularlayout.Itdoesnothaveonesingle‘best’outcome,butinsteadwilliterativelychangethepositionofonenodeafteranothertakingintoaccountthe“springs”thatconnectnodes.Themoreyouclickthelayoutbutton,themorethenodeswillfindasuitableposition.
Thisalgorithmismostusefulforvisualexplorationwithlowdensitynetworks.Trytosetyourtarget-densitysliderlowandperformthelayout:thealgorithmwillrevealinterestingstructuralfeaturesthatarehiddeninthecircularlayout,suchasisolatednodes,nodeswithonlyoneconnection,andsetsofnodesthatarealltightlyconnectedwitheachother.
Randomlycreatednetworksaretypicallyverydenseandrarelyshowstrikingstructuralfeaturesinforce-directedlayouts.However,thisgroupoflayoutalgorithmisgreatatrevealingstructuralfeaturesthatarecommoninsocialnetworks:denseclustersand“bridging”nodesconnectingdifferentclusters.
Trychangingthevaluesofthethreenumbersinthelayout-springcommand.Youwillnoticethattheeffectofthespringsworksdifferently.Bychangingthesevariablesyouwillbeabletotailoryourlayoutalgorithmtomostappropriatelyhighlightthosestructuralfeaturesofyournetworkyouwanttoexploreorvisualise.Trychangingthevaluesinsuchawaythatitprovidesamoreinterestingrepresentationofaverydenserandomnetwork.
Saveyourmodel!
12. NetworkmeasuresWealreadyintroducedthreeimportantmeasuresofyournetworkstructure:thenumberofnodes,thenumberofedgesandthenetworkdensity.Nowwewillcalculateandreporttwomoremeasures:averagedegreeandaverageshortestpathlength.
Thedegreeofanodeisdefinedasthenumberofedgesconnectedtothisnode.Theaveragedegreeofanetworkisthesumofthedegreesofallnodesinthisnetworkdividedbythenumberofnodes.
Ashortestpathbetweenapairofnodesistheshortestnumberofedgesthatneedtobecrossedinorderforthetwonodestobeconnected.Theaverageshortestpathlengthistheaverageoftheshortestpathsbetweenallpairsofnodesinthenetwork.
Thesemeasureswillrevealaspectsofthestructureofyournetworkandcanbelinkedtofeaturesofthenetworkthatmightinterestyouinyourresearch:e.g.informationissharedmuchfastertoallindividualsinasocialnetworkiftheaverageshortestpathlengthislow.
WewilluseareportertocalculatetheaveragedegreeintheCodetabandthendisplayitintheInterfacetab.
AddthefollowingcodetotheCodetabattheverybottom:to-report report-av-degree let av-degree sum([count edge-neighbors] of nodes) / num-nodes report av-degree end
Inthiscodewecalculatethevariableav-degreeasthesumofallnumbersofconnections([count edge-neighbors] of nodes)ofallnodesdividedbythenumberofnodes(num-nodes),andwethenreportthevariableav-degreesothatwecanuseitinamonitorontheInterfacetab:
• SelectMonitorfromthedropdownbox.
NetworkSciencewithNetlogo version13/09/2018
25
• Clickthe‘Add’button.• Clickanywhereinthewhitespace.Anewwindowwillappearwhereyoucan
determinewhatthemonitorwilldo.• Writereport-av-degreeinthe‘Reporter’box,write‘AverageDegree’inthe‘Display
Name’box,includetwodecimalplaces.ClickOK.
TocalculatetheaverageshortestpathlengthwewilluseaNetlogoextensioncalled‘nw’.InordertouseanextensioninaNetlogomodelweneedtoaddthefollowingattheverytopofthecode:
extensions [ nw ]
The‘nw’extensionneedstoknowexactlywhichsetsofagentsarethenodesandwhicharethelinks.Wehavecreatedabreedofnodesandabreedofedgesandwewillworkwiththese.Youcanspecifythisbysettingtheso-called‘context’ofthenetworkintheCodetab.Addthefollowingtothesetupprocedurejustbelowthelinecreatingthenodes:
nw:set-context nodes edges
WewillnowcreateareporterintheCodetabthatreportsanewvariableaverage-shortest-path-lengthbyusingthecommandfromthe‘nw’extensionnw:mean-path-length:
to-report average-shortest-path-length report nw:mean-path-length end
WecannowaddamonitortotheInterfacetab:
• SelectMonitorfromthedropdownbox.• Clickthe‘Add’button.• Clickanywhereinthewhitespace.Anewwindowwillappearwhereyoucan
determinewhatthemonitorwilldo.• Writeaverage-shortest-path-lengthinthe‘Reporter’box,includetwodecimal
places.ClickOK.
NetworkSciencewithNetlogo version13/09/2018
26
Nowyouwillbeabletomeasuretheaveragedegreeandaverageshortestpathlengthofanynetworkyoucreateinyourmodel.
Notethattheaverageshortestpathlengthmonitorwillsometimesreport‘false’.Thishappenswhenyournetworkhasisolatednodes,i.e.nodesthatarenotconnectedtoanyothernodes.Itwilltypicallyoccurinrandomnetworkswithalowdensity.Insuchcases,thealgorithmcannotcalculatetheshortestpathbetweenallnodepairsbecausesomenodesarenotconnected.
The‘nw’extensionwashereusedinaverysimpleexampletoillustratehowextensionscanbeimplementedinaNetlogomodel.The‘nw’extensionoffersahugerangeofothertechniquesthatwillenableyoutoperformthemostcommonnetworksciencetasks,includingsomeofthethingswehaveimplementedmanuallyabove.Fulldocumentationfortheextensioncanbefoundhere:
https://github.com/NetLogo/NW-Extension
Advancedtask:innetworkswithisolatednodesyoucouldstillcalculatetheaverageshortestpathlengthofallnodesthatareconnectedinthelargestsingleconnectedcomponent,bycreatingasubsetofnodesthatonlyincludesthenodesinlargestconnectedcomponentandcalculatingtheaverageshortestpathlengthfortheseonly.Giveitatry!UsetheNetlogodictionaryandthe‘nw’extensiondocumentation.
Saveyourmodel!
13. TradingpotsonanetworkWhenperformingappliednetworkscienceresearch,youarenotjustinterestedincreatingacertainnetworkstructurebutratherinunderstandingwhatitsconsequencesarewithinyourresearchcontext.Whatisenabledbytherelationships?Whataretheprocessestakingplaceontherelationships?Theflowofmaterialsorideas?Howdoesthestructureofthenetworkinfluencethisflow?Doesitleadtoaparticularpattern,likedistributionsof
NetworkSciencewithNetlogo version13/09/2018
27
materialsortherapidspreadofanidea?Theseareagainquestionsthatyouneedtoaskyourselfattheoutsetandanswerinlightofyourresearchcontext.
Inthissectionwewillintroduceaverysimpleresearchcontextandprocess:tradeandthedistributionofpotsoveranetwork.
Wewillassumeallournodesaretradersinvolvedinthetradeofpottery,andtheyareabletotradewitheachotheriftheyareconnectedinthenetwork.Wewillgivealltradersacertainamountofpotsandeverytick(Netlogojargonfortimestep)allpotsinthemodelwillbeconsideredfortrade.Tokeepitsimple,wewilljustassumethatalltraderswanttosellthepotstheyown,wanttoobtainnewitems,andthatatransactionissuccessfulwithacertainprobability.
First,wewillcreateavariableforthenodes(thetraders)called‘pots’byaddingthefollowingtothetopoftheCode,justbelowwherewedefinethebreeds:
nodes-own [pots]
Second,wewillgiveallnodespotsduringthesetupprocedurebyaddingthefollowingcodejustafterthecreationofnodes:
ask nodes [set pots num-pots]
Notethatwejustmentionedanewvariablecallednum-pots,soNetlogowillgiveusanerrorandwewillneedtoaddaslidertocontrolthisvariableintheInterfacetab:
• SelectSliderfromthedropdownbox.• Clickthe‘Add’button.• Clickanywhereinthewhitespace.Anewwindowwillappearwhereyoucan
determinewhatthesliderwilldo.• Writenum-potsinthe‘Globalvariable’box,settheminimumto0,theincrementto
1,themaximumto100andthevalueto50.ClickOK.
Nowwhenyouclickthesetupbuttonallnodeswillbegivenasmanypotsasdefinedbythevariablenum-pots.
NetworkSciencewithNetlogo version13/09/2018
28
Third,wewillcreateanewprocedurethatdetermineswhatprocesseswilltakeplacewhenthemodelruns.Sofarwehaverestrictedourselvestodetermininghowthemodelissetup,andnowwewilldeterminewhathappensafterthatforeverytick(timestep).
Addaprocedurecalledgobywritingatthebottomofyourcodethefollowing:to go tick end
Thecommandtickwillincreasethenumberoftimestepsofthemodelbyoneeverytimethegoprocedurehappens.TousethegoprocedurewewilladdabuttonforitontheInterfacetab:
• SelectButtonfromthedropdownbox.• Clickthe‘Add’button.• Clickanywhereinthewhitespace.Anewwindowwillappearwhereyoucan
determinewhatthebuttonwilldo.• Writegointhe‘Commands’boxand‘goonce’inthe‘Displayname’box.ClickOK.
Youhavejustaddedabuttonthatwillrunthegoprocedureonceeverytimeyouclickit.Ifyoudoso,youwillnoticethatthenumberofticksintheInterfacewindowwillincreasebyoneeachtime.Youmightalsowanttocreateasecondbuttonthatrunsthegoprocedurecontinuouslyuntilyouaskittostop:
• SelectButtonfromthedropdownbox.• Clickthe‘Add’button.• Clickanywhereinthewhitespace.Anewwindowwillappearwhereyoucan
determinewhatthebuttonwilldo.• Writegointhe‘Commands’boxand‘go’inthe‘Displayname’box.Makesurethe
‘Forever’boxisticked.ClickOK.
Youhavenowcreatedabuttonthatwillcontinuouslyrunthegoprocedure.
NetworkSciencewithNetlogo version13/09/2018
29
Fourth,wewillstartaddingmoreinterestingtrade-relatedcommandstothegoprocedure,beginningwithacountofthetotalnumberofpotsduringanyonetick.Inthismodelthissumwillbethesameforeverytickwithinasinglesetup,butwewilladdthissumincaseyoudecidetomodifythemodelbyallowingpotstobeaddedorremovedfromthemodel.Writethefollowinginthegoprocedurebeforetick:
let total-pots sum [pots] of nodes
Fifth,nowthatweknowhowmanypotsthereareinthistickwecanrepeattradeasmanytimesastherearepotsbyaddingthefollowingcodeinthegoprocedureimmediatelyafterthesumofallpots:
repeat total-pots [ ]
Everycommandthatwenowaddwithinthesebracketswillberepeatedasmanytimesastherearepotsatthestartofthattick.
Sixth,wewillrandomlyselectanodewhichhasatleastonepotandisconnectedtoatleastoneothernode,i.e.anodethatcantrade:
repeat total-pots [ ask one-of nodes with [pots > 0 and count edge-neighbors > 0] [] ]
Seventh,wewillaskthisnodetoperformatransaction(sellapottoanothernodeitisconnectedto)withacertainprobability.Wewillusethesametechniqueasweusedearlierforimplementingprobability:checkingwhetherarandomlyselectednumberishigherorlowerthanavariablerepresentingthetradeprobability.Addthefollowingtotheaskcommandwejustwrote:
ask one-of nodes with [pots > 0 and count edge-neighbors > 0] [if random-float 1 < trade-probability [] ]
Thiscodewillperformanactiononlyifarandomlyselectedfloatingpointnumberbetween0and1issmallerthanthevaluewesetforthevariabletrade-probability.Let’screateasliderforthisnewvariableintheInterfacetab:
• SelectSliderfromthedropdownbox.• Clickthe‘Add’button.• Clickanywhereinthewhitespace.Anewwindowwillappearwhereyoucan
determinewhatthesliderwilldo.• Writetrade-probabilityinthe‘Globalvariable’box,settheminimumto0,the
incrementto0.05,themaximumto1andthedefaultvalueto0.5.ClickOK.
NetworkSciencewithNetlogo version13/09/2018
30
Finally,wewilladdthetransactionthatwilltakeplaceifarandomlyselectednumberislowerthanthethresholddeterminedbythetrade-probabilityvariable.Addthefollowingtotheifcommandwejustwrote:
[if random-float 1 < trade-probability [set pots pots - 1 ask one-of edge-neighbors [set pots pots + 1] ] ]
Thiscodewillperformatransactionbyfirstreducingthenumberofpotsoftheseller(therandomlyselectednode),thenitwillrandomlyselectoneoftheothernodesthisnodeisconnectedto(thissecondnodebecomesthebuyer),andfinallyitwillincreasethenumberofpotsthebuyerownsby1.
Yourcompletegoprocedureshouldnowlooklikethis:to go let total-pots sum [pots] of nodes repeat total-pots [ ask one-of nodes with [pots > 0 and count edge-neighbors > 0] [if random-float 1 < trade-probability [set pots pots - 1 ask one-of edge-neighbors [set pots pots + 1] ] ] ] tick end
Younowhaveamodelwhereyoucancreatearandomlyconstructednetworkwithcertainfeatures,youcanapplyalayoutalgorithmtoit,andyoucanhavethenodestradepotswitheachother.
Saveyoumodel!
NetworkSciencewithNetlogo version13/09/2018
31
14. PlotsofpotsAtthemomentwecannotexplorethetradeprocedurewejustcreatedveryeasily,becausewedonothaveanythingthatreportsitseffects.Let’saddtwoplotsthattellussomethingaboutthenetworkandthetradeprocesses.
First,let’smakeaplotshowingthefrequencydistributionofnodes’degreesintheInterfacetab:
• SelectPlotfromthedropdownbox.• Clickthe‘Add’button.• Clickanywhereinthewhitespace.Anewwindowwillappearwhereyoucan
determinewhatthePlotwilldo.• Write‘Degreedistribution’inthe‘name’box.• Clickontheyellowpenciltomodifythe‘defaultpen’.Anewwindowwillopen
whereyoucandeterminewhatthispenwillplot.• Setthe‘Mode’dropdownboxto‘Bar’,setthe‘Interval’to1.0,andwritethe
followingcodeinthe‘Penupdatecommands’box:let max-degree max [count edge-neighbors] of nodes set-plot-x-range 0 (max-degree + 1) histogram [count edge-neighbors] of nodes
• ClickOKtwice.
Thisplotwillcreateahistogram,displayingthefrequencydistributionofthedegree(thenumberofedges)ofnodes.OntheXaxisweseethedegree,andontheYaxisweseethenumberofnodesthathaveacertaindegree.
Oneofthemostinterestingthingstoexplorewouldbetoseehowmanypotseachtraderhas:thedistributionofpots.WewillcreateaplotthatshowsusthisintheInterfacetab:
• SelectPlotfromthedropdownbox.• Clickthe‘Add’button.• Clickanywhereinthewhitespace.Anewwindowwillappearwhereyoucan
determinewhatthePlotwilldo.• Write‘Distributionofpots’inthe‘name’box.
NetworkSciencewithNetlogo version13/09/2018
32
• Clickontheyellowpenciltomodifythe‘defaultpen’.Anewwindowwillopenwhereyoucandeterminewhatthispenwillplot.
• Setthe‘Mode’dropdownboxto‘Bar’,setthe‘Interval’to1.0,andwritethefollowingcodeinthe‘Penupdatecommands’box:
let max-pots max [pots] of nodes set-plot-x-range 0 (max-pots + 1) histogram [pots] of nodes
• ClickOKtwice.
Thisplotwillcreateahistogram,displayingthedistributionofpotsamongnodes.OntheXaxisweseethenumberofpots,andontheYaxisweseethenumberofnodesthatownacertainnumberofpots.
Nowyoucanstartexploringtheinterestingbehaviourofthismodel:theinteractionbetweenthenetworkstructureandthetradeprocess.
Whatshapedoesthedistributionofpotshaveforadensenetwork?Whatdoesitlooklikeforasparsenetwork?Doesthischangeoverlongtimeperiods?Howdoestheprobabilityoftradeaffectthisdistribution?
Ifyouconsidertheamountofpotsatraderhasastheirwealth,howwouldyouinterpretthesedifferentresults?Underwhatconditionsdoyouseeamoreequalwealthdistribution?Underwhatconditionsdoyouseealessequalwealthdistribution?Dothesedifferentdistributionscorrelatewithcertainnetworkstructuresasdefinedbytheaveragedegree,thedegreedistribution,andtheaverageshortestpathlength?Isthewealthofanodedependentonitspositioninthenetwork,suchasitsdegree?
Additionaladvancedexercise:Trychangingthewaynodesaregivenpots,bygivingsomenodesmorepotsthanothers,orlettingthedistributionofpotsovernodesfollowanormal,uniformorexponentialdistribution.Howdoesthisaffecttherunningofthemodel?Canyouidentifyacorrelationbetweenthenumberofpotsanodestartsoutwithinlifeandhowmanypotstheymanagetokeepandobtain?