network science with netlogo tutorial · network science with netlogo version 05/07/2017 7 • make...

31
Network Science with Netlogo version 05/07/2017 1 Network Science with Netlogo Tutorial By Tom Brughmans First version: March 2016 This version created 05/07/2017 Netlogo version used: 6.0.1 Extension used: nw (pre-packaged with Netlogo 6.0.1) https://github.com/NetLogo/NW-Extension Cite this tutorial as: Brughmans, T. (2016). Network Science with Netlogo Tutorial, https://archaeologicalnetworks.wordpress.com/resources/#netlogo . 1. Introduction This tutorial provides an introduction to creating agent-based network models with Netlogo. By working through this tutorial you will learn how to create nodes, create edges, perform layouts introduce probability in edge creation, create a trade process working on the network and how to derive network measures. 2. Conventions, tips and assumed knowledge This tutorial assumes basic knowledge of Netlogo and of simulation. It is recommended to walk through the introductory tutorials on the Netlogo website or the tutorial on Netlogo for archaeologists on the Simulating Complexity blog: https://simulatingcomplexity.files.wordpress.com/2014/07/dispersal_tutorial.pdf https://ccl.northwestern.edu/netlogo/docs/ This tutorial will also refer to some network science jargon, concepts and techniques. You can get a basic definition of all of these from the glossary on my blog: https://archaeologicalnetworks.wordpress.com/resources/#glossary Good introductions to network science include the following: Brandes, U., Robins, G., McCranie, A., & Wasserman, S. 2013. What is network science? Network Science 1(01): p.1–15. Newman, M.E.J., 2010. Networks: an introduction, Oxford: Oxford University Press. Code written in this tutorial will be formatted as in the following example: breed [nodes node] Save your project! Do this regularly and use multiple versions throughout the tutorial so that you can fall back on an earlier version at any time. I will remind you regularly throughout the tutorial to save your project.

Upload: dinhhanh

Post on 07-Mar-2019

217 views

Category:

Documents


0 download

TRANSCRIPT

NetworkSciencewithNetlogo version05/07/2017

1

NetworkSciencewithNetlogoTutorialByTomBrughmans

Firstversion:March2016

Thisversioncreated05/07/2017

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.

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 version05/07/2017

2

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 version05/07/2017

3

WhenyouopenNetlogoitshouldlooksomethinglikethis:

Ithasthreetabs:Interface,Info,Code.

TheInterfacetabiswhereyouwatchyourmodelrun.Throughoutthetutorialyouwilladdbuttonsandsliderstocontrolthevariablesofyourmodel,andyouwilladdmonitorsandplotstoinspectwhatyourmodelisdoing.Youcanspeeduporslowdownthesimulationusingthespeedslideratthetopoftheinterface.Thecommandcenteratthebottomwilldisplaymessagesyouaskthemodeltoproduce,andyoucanalsouseittogivetocommandstothemodelfromtheinterfacetab.

NetworkSciencewithNetlogo version05/07/2017

4

TheInfotabiswhereyoudescribeyourmodelusingastandardizedsetofquestions.Addingthisinformationwhenyoushareyourmodelwithotheriscrucialtoenablethemtoworkwithyourmodel.WewillnotworkwiththeInfotabinthistutorial.

TheCodetabiswhereyouwriteandstorethecodeforthemodel.InthistutorialwewillbemainlyworkingintheCodetab.AusefulfeatureistheCheckfunctionatthetopofthistab:clickthistoletNetlogocheckyourcodeforerrors.Ifitfindserrorsthenyouwillbeguided

NetworkSciencewithNetlogo version05/07/2017

5

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 version05/07/2017

6

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 version05/07/2017

7

• Makesurethedropdownboxnexttothegreenplussignhas‘Button’selected.• Clickthegreenplussigncalled‘Add’(seefigurebelow).Yourcursorwillbecomea

bigplussign.• Clickanywhereinthewhitespacenexttotheblackinterfacewindow.Abuttonwill

appearandanewwindowwillopenwhereyoucandeterminewhatthisbuttonwillbeusedfor.

• WritesetupinthecommandsboxofthisnewwindowandclickOK(seefigurebelow).

NetworkSciencewithNetlogo version05/07/2017

8

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 version05/07/2017

9

• 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 version05/07/2017

10

However,youmightwantmorecontrolovertheorderinwhichthenodesareplaced,andnotjustletthembeplacedinarandomorder.Toachievethis,reworkthelayoutlineintheCodetabtoreadlikethis:

layout-circle sort nodes 10

IfyouclickthesetupbuttonintheInterfacetabnow,youwillgetacircularpositioningofallnodes,buttheyareorderedaccordingtotheir‘Who’number(theuniqueIDofaturtleassignedbyNetlogowhenitiscreated)clockwisestartingfromthetopmiddlenodeinthecircle.Youcancheckthisbyrightclickingthenodesinorderandyouwillnoticethattheorderofnodesis0,1,2,3,….(seefigurebelow).

NetworkSciencewithNetlogo version05/07/2017

11

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 version05/07/2017

12

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.processescreatingedgeswithprobabilitiesdependentonotheredges.Forexample,acommonhypothesisforsocialnetworksoffriendshipistheideathatapairofunrelatedindividualshasahigherprobabilityofbecomingfriends(i.e.ofcreatinganedgebetweenapairofnodes)iftheyhaveafriendincommon(i.e.theprobabilityofthenewedgeisdependentontheexistenceofotheredges).NodesAandBinthefigurebelowhavenodeCasamutualfriend,soaccordingtothishypothesistheedgebetweenAandBwillbemorelikelytoappear:

NetworkSciencewithNetlogo version05/07/2017

13

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 version05/07/2017

14

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 version05/07/2017

15

ThishappensbecausebydefaulttheNetlogo‘World’willwraparoundthehorizontalandverticaledges.Thisdoesnotmakemuchsensewhenmakinganetworkmodel!Attheveryleastitisnothelpfulforvisualexploration.Toavoidtheedgesfromcrossingtheseboundaries,right-clicktheinterfacewindow,selectEdit,andintheModelsettingswindowunchecktheboxesfor‘Worldwrapshorizontally’and‘Worldwrapsvertically’:

Whenyoudothis,thenetworkwilllooksomethinglikethis(notethatyournetworkwilllookdifferentbecausetheedgesarerandomlycreated):

NetworkSciencewithNetlogo version05/07/2017

16

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 version05/07/2017

17

• 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 version05/07/2017

18

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 version05/07/2017

19

However,thereisaproblemwiththiscode.Whenyouputthetarget-densityvariablehighthenyouwilloftengeta‘RuntimeError’.ThisErrorisveryinformativeandwillhelpusresolveit.Ithighlightsthepartofthecodewheretheproblemliesandtellsusitcannotfindanotherturtle(i.e.node)thatfitsthecriteria:

Theerrortellsusthatweareaskinganodetoidentifyanothernodeitisnotyetconnectedto,whensuchanodedoesnotexist:i.e.theaskingnodeisalreadyconnectedtoallothernodes.

NetworkSciencewithNetlogo version05/07/2017

20

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:

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 version05/07/2017

21

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 version05/07/2017

22

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 version05/07/2017

23

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 link-neighbors] of nodes) / num-nodes report av-degree end

Inthiscodewecalculatethevariableav-degreeasthesumofallnumbersofconnections([count link-neighbors] of nodes)ofallnodesdividedbythenumberofnodes(num-nodes),andwethenreportthevariableav-degreesothatwecanuseitinamonitorontheInterfacetab:

• SelectMonitorfromthedropdownbox.

NetworkSciencewithNetlogo version05/07/2017

24

• 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 version05/07/2017

25

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?Doesitleadtoparticularpattern,likedistributionsofmaterials

NetworkSciencewithNetlogo version05/07/2017

26

ortherapidspreadofanidea?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 version05/07/2017

27

Third,wewillcreateanewprocedurethatdetermineswhatprocesseswilltakeplacewhenthemodelruns.Sofarwehaverestrictedourselvestodetermininghowthemodelissetup,andnowwewilldeterminewhathappensafterthatforeverytick(timestep).

Addaprocedurecalledgobywritingatthebottomofyourcodethefollowing:to go tick end

Thecommandtickwillincreasethenumberoftimestepofthemodelbyoneeverytimethegoprocedurehappens.TousethegoprocedurewewilladdabuttonforitontheInterfacetab:

• SelectButtonfromthedropdownbox.• Clickthe‘Add’button.• Clickanywhereinthewhitespace.Anewwindowwillappearwhereyoucan

determinewhatthebuttonwilldo.• Writegointhe‘Commands’boxand‘goonce’inthe‘display’box.ClickOK.

Youhavejustaddedabuttonthatwillrunthegoprocedureonceeverytimeyouclickit.Ifyoudoso,youwillnoticethatthenumberofticksintheInterfacewindowwillincreasebyoneeachtime.Youmightalsowanttocreateasecondbuttonthatrunsthegoprocedurecontinuouslyuntilyouaskittostop:

• SelectButtonfromthedropdownbox.• Clickthe‘Add’button.• Clickanywhereinthewhitespace.Anewwindowwillappearwhereyoucan

determinewhatthebuttonwilldo.• Writegointhe‘Commands’boxand‘go’inthe‘display’box.Makesurethe‘Forever’

boxisticked.ClickOK.

Youhavenowcreatedabuttonthatwillcontinuouslyrunthegoprocedure.

NetworkSciencewithNetlogo version05/07/2017

28

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 link-neighbors > 0] [] ]

Seventh,wewillaskthisnodetoperformatransaction(sellapottoanothernodeitisconnectedto)withacertainprobability.Wewillusethesametechniqueasweusedearlierforimplementingprobability:checkingwhetherarandomlyselectednumberishigherorlowerthanavariablerepresentingthetradeprobability.Addthefollowingtotheaskcommandwejustwrote:

ask one-of nodes with [pots > 0 and count link-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 version05/07/2017

29

Finally,wewilladdthetransactionthatwilltakeplaceifarandomlyselectednumberislowerthanthethresholddeterminedbythetrade-probabilityvariable.Addthefollowingtotheifcommandwejustwrote:

[if random-float 1 < trade-probability [set pots pots - 1 ask one-of link-neighbors [set pots pots + 1] ] ]

Thiscodewillperformatransactionbyfirstreducingthenumberofpotsoftheseller(therandomlyselectednode),thenitwillrandomlyselectoneoftheothernodesthisnodeisconnectedto(thissecondnodebecomesthebuyer),andfinallyitwillincreasethenumberofpotsthebuyerownsby1.

Yourcompletegoprocedureshouldnotlooklikethis:to go let total-pots sum [pots] of nodes repeat total-pots [ ask one-of nodes with [pots > 0 and count link-neighbors > 0] [if random-float 1 < trade-probability [set pots pots - 1 ask one-of link-neighbors [set pots pots + 1] ] ] ] tick end

Younowhaveamodelwhereyoucancreatearandomlyconstructednetworkwithcertainfeatures,youcanapplyalayoutalgorithmtoit,andyoucanhavethenodestradepotswitheachother.

Saveyoumodel!

NetworkSciencewithNetlogo version05/07/2017

30

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 link-neighbors] of nodes set-plot-x-range 0 (max-degree + 1) histogram [count link-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 version05/07/2017

31

• 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?