NetLogo 6.0 User Manual
Transcript of NetLogo 6.0 User Manual
![Page 1: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/1.jpg)
TheNetLogo6.0.2UserManual
![Page 2: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/2.jpg)
226262828282828282929292930303030313132323333333434343535353536
37373737373738383839393939404041414242424343444445
TableofContents
TableofContentsWhatisNetLogo?
FeaturesCopyrightandLicenseInformation
HowtoreferenceAcknowledgmentsNetLogolicenseCommerciallicensesNetLogoUserManuallicenseOpensourceThirdpartylicenses
ScalaMersenneTwisterFastColtConfigApacheCommonsCodec(TM)FlexmarkJHotDrawJOGLMatrix3DASMLog4jPicoContainerParboiledRSyntaxTextAreaJCodecJava-Objective-CBridgeWebcam-captureGuavaGephiRExtensionJNA
What'sNew?Version6.0.2(August2017)
FeatureChangesBugfixesExtensionChangesDocumentationChangesModelChanges
Version6.0.1(March2017)FeatureChangesBugfixesExtensionChangesDocumentationChangesModels
Version6.0(December2016)FeatureChangesBugfixesLanguageChangesExtensionChangesOperatingSystemSupportDocumentationChangesInternationalizationChangesModels
Version5.3.1(February2016)FeatureChangesExtensionChanges
![Page 3: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/3.jpg)
45454545454545464646464747474748484949494949495050505050505151515151515153535353535454565657585859596062626262
BugfixesVersion5.3(December2015)
FeatureChangesExtensionChanges
Version5.2.1(September2015)ExtensionsNewfeaturesBugfixesModelchanges
Version5.2.0(April2015)ExtensionsNewfeaturesBugfixesModelchanges
Version5.1.0(July2014)Version5.0.4(March2013)Version5.0(February2012)Version4.1.3(April2011)Version4.1(December2009)Version4.0(September2007)Version3.1(April2006)Version3.0(September2005)Version2.1(December2004)Version2.0.2(August2004)Version2.0(December2003)Version1.3(June2003)Version1.2(March2003)Version1.1(July2002)Version1.0(April2002)
SystemRequirementsApplicationRequirements
WindowsMacOSXLinux
3DRequirements32-bitor64-bit?
ContactingUsWebsiteFeedback,questions,etc.ReportingbugsOpensource
SampleModel:PartyAtaPartyChallengeThinkingwithmodelsWhat'snext?
Tutorial#1:ModelsSampleModel:WolfSheepPredationControllingtheModel:ButtonsControllingspeed:SpeedSliderAdjustingSettings:SlidersandSwitchesGatheringInformation:PlotsandMonitors
PlotsMonitors
ControllingtheView
![Page 4: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/4.jpg)
666666666767686868717276777777797980808182838485868787888989899393939494
9595969798
100100101101101101102103103105105106106
ModelsLibrarySampleModelsCurricularModelsCodeExamplesHubNetActivities
What'sNext?Tutorial#2:Commands
SampleModel:TrafficBasicCommandCenterWorkingwithcolorsAgentMonitorsandAgentCommandersWhat'sNext?
Tutorial#3:ProceduresAgentsandproceduresMakingthesetupbuttonSwitchingtotick-basedviewupdatesMakingthegobuttonExperimentingwithcommandsPatchesandvariablesTurtlevariablesMonitorsSwitchesandlabelsMoreproceduresPlottingTickcounterSomemoredetailsWhat'snext?Appendix:Completecode
InterfaceGuideMenus
Chart:NetLogomenusTabsInternationalUsage
CharactersetsLanguagesSupportfortranslators
InterfaceTabGuideWorkingwithinterfaceelementsChart:InterfaceToolbarThe2Dand3Dviews
Manipulatingthe3DViewCommandCenter
ReportersAccessingpreviouscommandsClearingArranging
PlotsPlotPens
SlidersAgentMonitors
InfoTabEditingHeadings
Input
![Page 5: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/5.jpg)
107107107107107107107107107108108108108108108109109109110110111111111111111111112112112112112113113113114115116117117118119120121121121123125126126127128128130134135136136
ParagraphsExampleFormatted
ItalicizedandboldtextExampleFormatted
OrderedlistsExampleFormatted
UnorderedlistsExampleFormatted
LinksAutomaticlinksLinkswithtextLocallinks
ImagesExampleFormattedLocalimages
BlockquotationsExampleFormatted
CodeExampleFormatted
CodeblocksExampleFormatted
SuperscriptsandsubscriptsExampleFormatted
NotesonusageOtherfeatures
CodeTabGuideIncludedFilesMenuAutomaticindentation
ProgrammingGuideAgentsProceduresVariablesTickcounter
WhentotickFractionalticks
ColorsAskAgentsets
SpecialagentsetsAgentsetsandlists
BreedsLinkbreeds
ButtonsListsMathRandomnumbers
AuxiliarygeneratorLocalrandomness
![Page 6: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/6.jpg)
136137137137138138139139139139140140141141141142142142143143144145146146147150152152152152153153153153153154154154156156156156157157157157157157157157158158
160160160161162163163
TurtleshapesLinkshapesViewupdates
ContinuousupdatesTick-basedupdatesChoosingamodeFramerate
PlottingPlottingpointsPlotcommandsOtherkindsofplotsHistogramsClearingandresettingRangesandautoscalingUsingaLegendTemporaryplotpensset-current-plotandset-current-plot-penConclusion
StringsOutputFileI/OMoviesPerspectiveDrawingTopologyLinksAnonymousprocedures
AnonymousprocedureprimitivesAnonymousprocedureinputsAnonymousproceduresandstringsConcisesyntaxAnonymousproceduresasclosuresNonlocalexitsAnonymousproceduresandextensionsLimitationsWhatisOptional?Codeexample
Ask-ConcurrentUserInteractionPrimitives
Whatdoes"Halt"mean?TieMultiplesourcefilesSyntax
ColorsNoticeKeywordsIdentifiersScopeCommentsStructureCommandsandreportersComparedtootherLogos
TransitionGuideChangesforNetLogo6.0
TasksreplacedbyAnonymousProceduresLinkreportersoverhauledtobemoreconsistentandflexibleRemovalofAppletsChangestotheNetLogoUserInterfaceNobodyNotPermittedasaChooserValue
![Page 7: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/7.jpg)
163163164164164165165165165165165166167167168168168169169170170170170171171172173173174175175176176177177177177177
179179179181181181182182182182182182182183183185185185186186186188
BreedsmusthavesingularandpluralnamesRemovalof"Movie"PrimsImprovedNameCollisionDetectionRemovalofhubnet-set-client-interfaceImproved&UpdatedExtensionsAPIAddrangeprimitive
ChangesforNetLogo5.2hsbprimitivesGoGoextension
ChangesforNetLogo5.0PlottingTickcounterUnicodecharactersInfotabsModelspeedListperformanceExtensionsAPI
ChangesforNetLogo4.1Combiningsetandof
ChangesforNetLogo4.0WhonumberingTurtlecreation:randomizedvs."ordered"AddingstringsandlistsThe-atprimitivesLinksNew"of"syntaxSerialaskTickcounterViewupdatemodesSpeedsliderNumbersAgentsetbuildingRGBColorsTie
ChangesforNetLogo3.1AgentsetsWrappingRandomturtlecoordinates
ShapesEditorGuideGettingstarted
ImportingshapesCreatingandeditingturtleshapes
ToolsPreviewsOverlappingshapesUndoColorsOtherbuttonsShapedesignKeepingashape
CreatingandeditinglinkshapesChanginglinkshapeproperties
UsingshapesinamodelBehaviorSpaceGuide
WhatisBehaviorSpace?WhyBehaviorSpace?
HowItWorksManagingexperimentsetupsCreatinganexperimentsetupSpecialprimitivesforBehaviorSpaceexperiments
![Page 8: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/8.jpg)
188190190192193193
194194194194195195197197197197200201
203203203203203203204204204205205206207207207207208208208209210211211212212212213214214214214215216216
218218218218218
RunninganexperimentAdvancedusage
RunningfromthecommandlineSettingupexperimentsinXMLAdjustingJVMParametersControllingAPI
SystemDynamicsGuideWhatistheNetLogoSystemDynamicsModeler?
BasicConceptsSampleModels
HowitWorksDiagramTabCodeTabTheSystemDynamicsModelerandNetLogo
Tutorial:Wolf-SheepPredationStep1:SheepReproductionStep2:NetLogoIntegrationStep3:WolfPredation
HubNetGuideUnderstandingHubNet
NetLogoHubNetArchitecture
ComputerHubNetActivitiesClientsRequirementsStartinganactivityHubNetControlCenterTroubleshootingKnownLimitations
TeacherworkshopsHubNetAuthoringGuideRunningHubNetinheadlessmodeGettinghelp
HubNetAuthoringGuideCodingHubNetactivities
SetupReceivingmessagesfromclientsSendingmessagestoclientsExamples
HowtomakeaclientinterfaceViewupdatesontheclientsClickingintheviewonclientsCustomizingtheclient'sviewPlotupdatesontheclients
ModelingCommonsGuideIntroductionModelingCommonsAccountsUploadingModels
UploadANewModelUploadAChildOfAnExistingModel("forking")UpdatingAnExistingModel
LoggingStartinglogging
MacOSXorWindowsLinuxandothers
Usinglogging
![Page 9: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/9.jpg)
218220221222223223223223224225225225226226226227227228228230232233233234234234234235235235236236236236237237237238238238239239239240240240240241241241242242242242243
244244244
245
WherelogsarestoredHowtoconfiguretheloggingoutput
AdvancedConfigurationControllingGuideMathematicaLink
Whatisit?WhatcanIdowithit?InstallationUsageKnownIssuesSourcecodeCredits
NetLogo3DIntroduction
3DWorldsTheobserverandthe3DviewCustomShapes
TutorialStep1:DepthStep2:TurtleMovementStep3:ObserverMovement
DictionaryCommandsandReportersBuilt-InVariablesPrimitivesat-points4.1distancexyz4.1distancexyz-nowrap4.1dz4.1facefacexyz4.1left4.1link-pitch4.1.2load-shapes-3d4.1max-pzcor4.1min-pzcor4.1neighbors4.1neighbors64.1orbit-down4.1orbit-left4.1orbit-right4.1orbit-up4.1__oxcor__oycor__ozcorpatch4.1patch-at4.1patch-at-heading-pitch-and-distance4.1pitchpzcorrandom-pzcor4.1random-zcor4.1right4.1rollroll-left4.1roll-right4.1setxyz4.1tilt-down4.1tilt-up4.1towards-pitch4.1towards-pitch-nowrap4.1towards-pitch-xyz4.1towards-pitch-xyz-nowrap4.1turtles-at4.1<breeds>-atworld-depth4.1zcorzoom4.1
ExtensionsGuideUsingExtensions
Whereextensionsarelocated
NetLogoArduinoExtension
![Page 10: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/10.jpg)
245245246246246246246246246247247247247247
248248248248248248249249249249
250250250250250250250251251251251251251251251252252
253253253253254254254255255256256
257257257257257257257
UsingNotesCompatibilityQuestions
Primitivesarduino:primitivesarduino:portsarduino:openarduino:closearduino:getarduino:write-stringarduino:write-intarduino:write-bytearduino:is-open?
NetLogoArrayExtensionUsing
WhentoUseExampleuseofArrayExtension
Primitivesarray:from-listarray:itemarray:setarray:lengtharray:to-list
NetLogoBitmapExtensionUsing
WhatdoestheBitmapExtensiondo?Gettingstarted
Primitivesbitmap:average-colorbitmap:channelbitmap:copy-to-drawingbitmap:copy-to-pcolorsbitmap:difference-rgbbitmap:exportbitmap:from-viewbitmap:to-grayscalebitmap:heightbitmap:importbitmap:scaledbitmap:width
NetLogoCfExtensionUsingCasesPrimitives
cf:whencf:selectcf:matchcf:matchingcf:casecf:case-iscf:else
NetLogoCsvExtensionCommonusecasesandexamples
ReadafileallatonceReadafileonelineatatimeReadafileonelinepertickWriteafile
Primitives
![Page 11: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/11.jpg)
257257257258258259259259
261261261262262262262262262263263263263264264264265265265266266266267267267267267267268268268268268268269269269269269270270270270270271271271271272273274274275275275
FormattingNetLogodataasCSVParsingCSVinputtoNetLogodatacsv:from-rowcsv:from-stringcsv:from-filecsv:to-rowcsv:to-stringcsv:to-file
NetLogoGisExtensionUsing
HowtouseKnownIssuesCredits
PrimitivesRasterDatasetPrimitivesDatasetPrimitivesVectorDatasetPrimitivesCoordinateSystemPrimitivesDrawingPrimitivesgis:set-transformationgis:set-transformation-dsgis:set-world-envelopegis:set-world-envelope-dsgis:world-envelopegis:envelope-ofgis:envelope-union-ofgis:load-coordinate-systemgis:set-coordinate-systemgis:load-datasetgis:store-datasetgis:type-ofgis:patch-datasetgis:turtle-datasetgis:link-datasetgis:shape-type-ofgis:property-namesgis:feature-list-ofgis:vertex-lists-ofgis:centroid-ofgis:location-ofgis:property-valuegis:find-featuresgis:find-one-featuregis:find-less-thangis:find-greater-thangis:find-rangegis:property-minimumgis:property-maximumgis:apply-coveragegis:coverage-minimum-thresholdgis:set-coverage-minimum-thresholdgis:coverage-maximum-thresholdgis:set-coverage-maximum-thresholdgis:intersects?gis:contains?gis:contained-by?gis:have-relationship?gis:relationship-ofgis:intersectinggis:width-ofgis:height-ofgis:raster-valuegis:set-raster-value
![Page 12: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/12.jpg)
275275275276276277277277277278278278278279279279
280280280280280280280280281281281281281281281282282282282282282282283283
284284284284284285285286286286286286286286287287287287288288288
gis:minimum-ofgis:maximum-ofgis:sampling-method-ofgis:set-sampling-methodgis:raster-samplegis:raster-world-envelopegis:create-rastergis:resamplegis:convolvegis:apply-rastergis:drawing-colorgis:set-drawing-colorgis:drawgis:fillgis:paintgis:import-wms-drawing
NetLogoGogoExtensionUsageChangesPrimitives
OtherOutputsUtilitiesGeneralSensorsOutputsandServosgogo:primitivesgogo:howmany-gogosgogo:talk-to-output-portsgogo:set-output-port-powergogo:output-port-ongogo:output-port-offgogo:output-port-clockwisegogo:output-port-counterclockwisegogo:set-servogogo:ledgogo:beepgogo:read-sensorsgogo:read-sensorgogo:read-allgogo:send-bytes
NetLogoLsExtensionLevelSpacefundamentals
HeadlessandInteractiveModelsKeepingTrackofModelsAgeneralusecase:AskingandReportingAgeneralusecase:Inter-ModelInteractionsAgeneralUsecase:Tidyingup“Dead”ChildModels
CitingLevelSpaceinResearchPrimitives
CommandingandReportingLogicandControlOpeningandClosingModelsls:create-modelsls:create-interactive-modelsls:closels:resetls:askls:ofls:reportls:withls:let
![Page 13: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/13.jpg)
289290290290290290290290
291291291291291291291291292292292292292292292292292293293293293293293293293293294294294294294294295295295295295295295296296296296296296296296296297297297298
299299
ls:modelsls:showls:show-allls:hidels:hide-allls:path-ofls:name-ofls:model-exists?
NetLogoMatrixExtensionUsing
WhentoUseHowtoUseExample
PrimitivesMatrixcreationandconversionto/fromlistsAdvancedfeaturesMatrixdataretrievalandmanipulationMathoperationsmatrix:make-constantmatrix:make-identitymatrix:from-row-listmatrix:from-column-listmatrix:to-row-listmatrix:to-column-listmatrix:copymatrix:pretty-print-textmatrix:getmatrix:get-rowmatrix:get-columnmatrix:setmatrix:set-rowmatrix:set-columnmatrix:swap-rowsmatrix:swap-columnsmatrix:set-and-reportmatrix:dimensionsmatrix:submatrixmatrix:mapmatrix:times-scalarmatrix:timesmatrix:*matrix:times-element-wisematrix:plus-scalarmatrix:plusmatrix:+matrix:minusmatrix:-matrix:inversematrix:transposematrix:real-eigenvaluesmatrix:imaginary-eigenvaluesmatrix:eigenvectorsmatrix:detmatrix:rankmatrix:tracematrix:solvematrix:forecast-linear-growthmatrix:forecast-compound-growthmatrix:forecast-continuous-growthmatrix:regress
NetLogoNwExtensionUsage
![Page 14: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/14.jpg)
299301301301301301301301301301301302302303303304304304304305305305306306306307307307307307308308308308309309309309310310310310311311311311312313314315
316316316316316316316317317317317318
SpecialagentsetsvsnormalagentsetsAnoteregardingfloatingpointcalculationsPerformancePrimitives
GeneratorsPathandDistanceClusterer/CommunityDetectionContextManagementImportandExportCentralityMeasuresClusteringMeasuresnw:set-contextnw:get-contextnw:with-contextnw:turtles-in-radiusnw:turtles-in-reverse-radiusnw:distance-tonw:weighted-distance-tonw:path-tonw:turtles-on-path-tonw:weighted-path-tonw:turtles-on-weighted-path-tonw:mean-path-lengthnw:mean-weighted-path-lengthnw:betweenness-centralitynw:eigenvector-centralitynw:page-ranknw:closeness-centralitynw:weighted-closeness-centralitynw:clustering-coefficientnw:modularitynw:bicomponent-clustersnw:weak-component-clustersnw:louvain-communitiesnw:maximal-cliquesnw:biggest-maximal-cliquesnw:generate-preferential-attachmentnw:generate-randomnw:generate-watts-strogatznw:generate-small-worldnw:generate-lattice-2dnw:generate-ringnw:generate-starnw:generate-wheelnw:save-matrixnw:load-matrixnw:save-graphmlnw:load-graphmlnw:loadnw:save
NetLogoPaletteExtensionUsingthePaletteExtensionGettingStarted
WhatcolorsshouldIuse?ShouldIuseacontinuouscolorgradientorjustadiscretecolorset?ExampleModelsFurtherReading
Primitivespalette:scale-gradientpalette:scale-schemepalette:scheme-colorspalette:scale-gradient
![Page 15: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/15.jpg)
318319319319319319319319320320320320320
322322322324324324325325325326326326326326327327327327328328328328329329329329329329329330330330331331331331331332332333333
335335335335335
ReferencesNetLogoProfilerExtension
UsingtheProfilerExtensionHowtouseExample
Primitivesprofiler:callsprofiler:exclusive-timeprofiler:inclusive-timeprofiler:startprofiler:stopprofiler:resetprofiler:report
NetLogoRExtensionUsing
SomeTipsInstalling
InstallingRConfiguringtheRextensionDeterminingr.homeandjri.home.paths
Primitivesr:clearr:clearLocalr:evalr:__evaldirectr:gcr:getr:interactiveShellr:putr:putagentr:putagentdfr:putdataframer:putlistr:putnamedlistr:setPlotDevicer:stop
TroubleshootingLoadingRpackagesfailsAfterchangingtheworkingdirectoryinR(e.g.withsetwd())NetLogodoesn’tfindtheextensionSpecificerrorcodelist
CitationCopyrightandLicense
NetLogoRndExtensionUsageAnoteaboutperformancePrimitives
AgentSetPrimitivesListPrimitivesrnd:weighted-one-ofrnd:weighted-n-ofrnd:weighted-n-of-with-repeatsrnd:weighted-one-of-listrnd:weighted-n-of-listrnd:weighted-n-of-list-with-repeats
NetLogoSoundExtensionUsing
HowtoUseMIDIsupport
Primitives
![Page 16: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/16.jpg)
335336336336336336337339339339339339339339340340340340340340340340340340340341341341341
342342342342342342342342343343343344344344344345345345346346346347347347348348
349349349349349
sound:drumssound:instrumentssound:play-drumsound:play-notesound:play-note-later
DrumNamesInstrumentNames
NetLogoTableExtensionUsing
WhentoUseExampleManipulatingTablesKeyRestrictions
Primitivestable:cleartable:countstable:group-agentstable:group-itemstable:from-listtable:gettable:get-or-defaulttable:has-key?table:keystable:lengthtable:maketable:puttable:removetable:to-listtable:values
NetLogoVidExtensionConcepts
VideoSourceSourceLifecycleVideoRecorder
Primitivesvid:camera-namesvid:camera-openvid:camera-selectvid:movie-selectvid:movie-openvid:movie-open-remotevid:closevid:startvid:stopvid:statusvid:capture-imagevid:set-timevid:show-playervid:hide-playervid:record-viewvid:record-interfacevid:record-sourcevid:recorder-statusvid:start-recordervid:save-recording
NetLogoView2.5dExtensionHowtoUse
IncorporatingIntoModelsFeedback
Primitives
![Page 17: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/17.jpg)
349349350350350350351351351351351351351351352352352352352352352
353353353353353353354354354354354354354355355355355355356356356356357357357357358358358358358358358359359359360360360361361
view2.5d:patch-viewview2.5d:decorate-patch-viewview2.5d:undecorate-patch-viewview2.5d:turtle-viewview2.5d:update-all-patch-viewsview2.5d:update-patch-viewview2.5d:update-turtle-viewview2.5d:get-z-scaleview2.5d:set-z-scaleview2.5d:set-turtle-stem-thicknessview2.5d:get-observer-anglesview2.5d:set-observer-anglesview2.5d:get-observer-xy-focusview2.5d:set-observer-xy-focusview2.5d:get-observer-distanceview2.5d:set-observer-distanceview2.5d:remove-patch-viewview2.5d:remove-turtle-viewview2.5d:remove-all-patch-viewsview2.5d:remove-all-turtle-viewsview2.5d:count-windows
FAQ(FrequentlyAskedQuestions)Questions
GeneralDownloadingRunningUsageProgrammingBehaviorSpaceNetLogo3DExtensions
GeneralWhyisitcalledNetLogo?HowdoIciteNetLogoorHubNetinapublication?HowdoIciteamodelfromtheModelsLibraryinapublication?WhereandwhenwasNetLogocreated?WhatprogramminglanguagewasNetLogowrittenin?What'stherelationshipbetweenStarLogoandNetLogo?UnderwhatlicenseisNetLogoreleased?Isthesourcecodeavailable?DoyouofferanyworkshopsorothertrainingopportunitiesforNetLogo?ArethereanyNetLogotextbooks?IsNetLogoavailableinotherlanguagesbesidesEnglish?IsNetLogocompiledorinterpreted?Hasanyonebuiltamodelof<x>?AreNetLogomodelsrunsscientificallyreproducible?WillNetLogoandNetLogo3Dremainseparate?CanIrunNetLogoonmyphoneortablet?
DownloadingCanIhavemultipleversionsofNetLogoinstalledatthesametime?I'monaUNIXsystemandIcan'tuntarthedownload.Why?HowdoIinstallNetLogounattended
RunningCanIrunNetLogofromaCD,anetworkdrive,oraUSBdrive?WhyisNetLogosomuchslowerwhenIunplugmyWindowslaptop?WhydoesNetLogobundleJava?HowcomeNetLogowon'tstartuponmyLinuxmachine?WhenItrytoinstallNetLogoonWindows,Isee"WindowsprotectedyourPC"WhenItrytostartNetLogoonWindowsIgetanerror"TheJVMcouldnotbestarted".Help!NetLogowon'tstartonMacOSSierra(orlater)NetLogowon'tstartonWindowsorcrashessuddenlyonMacOSSierraCanIrunNetLogofromthecommandline,withouttheGUI?DoesNetLogotakeadvantageofmultipleprocessors?
![Page 18: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/18.jpg)
361361362362362
363364364364364
362
364364365365365365366366366366
367367367367367368368368
366
368368369369369369369369
370370370370370370370370370370370370370371371371371371371371371371371371
CanIdistributeNetLogomodelrunsacrossaclusterorgridofcomputers?IsthereanywaytorecoverlostworkifNetLogocrashesorfreezes?
UsageWhenImovethespeedsliderallthewaytotheright,whydoesmymodelseemtostop?CanIusethemouseto"paint"intheview?Howbigcanmymodelbe?Howmanyturtles,patches,procedures,buttons,andsooncanmymodelcontain?CanIuseGISdatainNetLogo?Mymodelrunsslowly.HowcanIspeeditup?CanIhavemorethanonemodelopenatatime?CanIchangethechoicesinachooseronthefly?CanIdividethecodeformymodelupintoseveralfiles?
ProgrammingHowdoestheNetLogolanguagedifferfromotherLogos?HowcomemymodelfromanearlierNetLogodoesn'tworkright?HowdoItakethenegativeofanumber?Myturtlemovedforward1,butit'sstillonthesamepatch.Why?HowdoIkeepmyturtlesonpatchcenters?patch-ahead1isreportingthesamepatchmyturtleisalreadystandingon.Why?HowdoIgivemyturtles"vision"?Canagentssensewhat'sinthedrawinglayer?I'mgettingnumberslike0.10000000004and0.799999999999insteadof0.1and0.8.Why?Thedocumentationsaysthatrandom-float1mightreturn0butwillneverreturn1.WhatifIwant1tobeincluded?HowcanIkeeptwoturtlesfromoccupyingthesamepatch?HowcanIfindoutifaturtleisdead?DoesNetLogohavearrays?DoesNetLogohavehashtablesorassociativearrays?HowcanIusedifferentpatch"neighborhoods"(circular,VonNeumann,Moore,etc.)?HowcanIconvertanagentsettoalistofagents,orviceversa?HowdoIstopforeach?I'mtryingtomakealist.WhydoIkeepgettingtheerror"Expectedaconstant"?
BehaviorSpaceWhyaretherowsinmyBehaviorSpacetableresultsoutoforder?HowdoImeasurerunseverynticks?I'mvaryingaglobalvariableIdeclaredintheCodetab,butitdoesn'twork.Why?
NetLogo3DDoesNetLogoworkwithmystereoscopicdevice?
ExtensionsI'mwritinganextension.Whydoesthecompilersayitcan'tfindorg.nlogo.api?
NetLogoDictionaryCategories
Turtle-relatedPatch-relatedLink-relatedAgentsetColorControlflowandlogicAnonymousProceduresWorldPerspectiveHubNetInput/outputFileListStringMathematicalPlottingBehaviorSpaceSystem
Built-InVariablesTurtlesPatchesLinks
![Page 19: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/19.jpg)
371371371371371371372372372372372372373373373374374374374374375375375375375375375375376376376376377377377377377377377377378378378378378378378379379379
379380380381381381381381381382
OtherKeywordsConstants
MathematicalConstantsBooleanConstantsColorConstants
Aabs1.0acos1.3all?4.0and1.0any?2.0approximate-hsb4.0approximate-rgb4.0ArithmeticOperators+1.0*1.0-1.0/1.0^1.0<1.0>1.0=1.0!=1.0<=1.0>=1.0asin1.3ask1.0ask-concurrent4.0at-points1.0atan1.0autoplot?1.0auto-plot-off1.0auto-plot-on1.0
Bback1.0bk1.0base-colors4.0beep2.1behaviorspace-experiment-name5.2behaviorspace-run-number4.1.1both-ends4.0breedbreedbut-first1.0butfirst1.0bf1.0but-last1.0butlast1.0bl1.0
Ccan-move?3.1carefully2.1ceiling1.0clear-all1.0ca1.0clear-all-plots1.0clear-drawing3.0cd3.0clear-globals5.2clear-links4.0clear-output1.0clear-patches1.0cp1.0clear-plotclear-ticks5.0clear-turtles1.0ct1.0colorcos1.0count1.0create-ordered-turtles4.0cro4.0create-<breed>-tocreate-<breeds>-tocreate-<breed>-fromcreate-<breeds>-fromcreate-<breed>-withcreate-<breeds>-withcreate-link-to4.0create-links-to4.0create-link-from4.0create-links-from4.0create-link-with4.0create-links-with4.0create-turtles1.0crt1.0create-temporary-plot-pen1.1
Ddate-and-time3.0die1.0diffuse1.0diffuse41.0directed-link-breeddisplay1.0
![Page 20: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/20.jpg)
382382383383383383383383383384384384384384385385385385385386386386386386386386387387387387388388388388388388389389389389389390390390390390390390391391391391391391391392392392392392392392392
distance1.0distancexy1.0downhill1.0downhill41.0dx1.0dy1.0
Eempty?1.0endend14.0end24.0error5.0error-message2.1every1.0exp1.0export-view3.0export-interface2.0export-output1.0export-plot1.0export-all-plots1.2.1export-world1.0extensionsextract-hsb1.0extract-rgb1.0
Fface3.0facexy3.0file-at-end?2.0file-close2.0file-close-all2.0file-delete2.0file-exists?2.0file-flush4.0file-open2.0file-print2.0file-read2.0file-read-characters2.0file-read-line2.0file-show2.0file-type2.0file-write2.0filter1.3first1.0floor1.0follow3.0follow-me3.0foreach1.3forward1.0fd1.0fput1.0
Gglobals
Hhatch1.0headinghidden?hide-link4.0hide-turtle1.0ht1.0histogram1.0home1.0hsb1.0hubnet-broadcast1.1hubnet-broadcast-clear-output4.1hubnet-broadcast-message4.1hubnet-clear-override4.1hubnet-clear-overrides4.1hubnet-clients-list5.0hubnet-enter-message?1.2.1hubnet-exit-message?1.2.1hubnet-fetch-message1.1hubnet-kick-client5.0hubnet-kick-all-clients5.0
![Page 21: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/21.jpg)
392393393393393393393393393394394394394394394394395395395395395396396396396396397397397
397398398398398398398398399399399399400400400400400401401401401401401402402402402402402402403403
hubnet-message1.1hubnet-message-source1.1hubnet-message-tag1.1hubnet-message-waiting?1.1hubnet-reset1.1hubnet-reset-perspective4.1hubnet-send1.1hubnet-send-clear-output4.1hubnet-send-follow4.1hubnet-send-message4.1hubnet-send-override4.1hubnet-send-watch4.1
Iif1.0ifelse1.0ifelse-value2.0import-drawing3.0import-pcolors3.0import-pcolors-rgb4.0import-world1.0in-cone3.0in-<breed>-neighbor?in-link-neighbor?4.0in-<breed>-neighborsin-link-neighbors4.0in-<breed>-fromin-link-from4.0__includes4.0in-radius1.0insert-item6.0.2inspect1.1int1.0is-agent?1.2.1is-agentset?1.2.1is-anonymous-command?6.0is-anonymous-reporter?6.0is-boolean?1.2.1is-directed-link?4.0is-link?4.0is-link-set?4.0is-list?1.0is-number?1.2.1is-patch?1.2.1is-patch-set?4.0is-string?1.0is-turtle?1.2.1is-turtle-set?4.0is-undirected-link?4.0item1.0
Jjump1.0
Llabellabel-colorlast1.0layout-circle4.0layout-radial4.0layout-spring4.0layout-tutte4.0left1.0lt1.0length1.0let2.1link4.0link-heading4.0link-length4.0link-set4.0link-shapes4.0links4.0links-ownlist1.0ln1.0log1.0loop1.0lput1.0
Mmap1.3max1.0max-n-of4.0max-one-of1.0
![Page 22: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/22.jpg)
403403403404404404404404405405405405405405406406406406407407407407407408408408408408408409409409409409409409410410410410410411411411411411411412412412412412413413413413413413413413414414414
max-pxcor3.1max-pycor3.1mean1.0median1.0member?1.0min1.0min-n-of4.0min-one-of1.0min-pxcor3.1min-pycor3.1mod1.0modes2.0mouse-down?1.0mouse-inside?3.0mouse-xcor1.0mouse-ycor1.0move-to4.0my-<breeds>my-links4.0my-in-<breeds>my-in-links4.0my-out-<breeds>my-out-links4.0myself1.0
Nn-of3.1n-values2.0neighbors1.1neighbors41.1<breed>-neighborslink-neighbors4.0<breed>-neighbor?link-neighbor?4.0netlogo-version3.0netlogo-web?5.2new-seed3.0no-display1.0nobodyno-links4.0no-patches4.0not1.0no-turtles4.0
Oof4.0one-of1.0or1.0other4.0other-end4.0out-<breed>-neighbor?out-link-neighbor?4.0out-<breed>-neighborsout-link-neighbors4.0out-<breed>-toout-link-to4.0output-print2.1output-show2.1output-type2.1output-write2.1
Ppatch1.0patch-ahead2.0patch-at1.0patch-at-heading-and-distance2.0patch-here1.0patch-left-and-ahead2.0patch-right-and-ahead2.0patch-set4.0patch-size4.1patches1.0patches-ownpcolorpen-down1.0pd1.0pen-erase3.0pe3.0pen-up1.0pu1.0pen-modepen-sizeplabelplabel-colorplot1.0plot-name1.0plot-pen-exists?4.0
![Page 23: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/23.jpg)
414414414414414415415415415415415416416416416417417417418418418418418418419419419419419419419420420420420420421421421421421421422422422422422423423423423423423423423424424424424424425425425
plot-pen-down1.0plot-pen-up1.0plot-pen-reset1.0plotxy1.0plot-x-min1.0plot-x-max1.0plot-y-min1.0plot-y-max1.0position1.0precision1.0print1.0pxcorpycor
Rrandom1.0random-float2.0random-exponential1.2.1random-gamma2.0random-normal1.2.1random-poisson1.2.1random-pxcor3.1random-pycor3.1random-seed1.0random-xcor3.1random-ycor3.1range6.0read-from-string1.1reduce1.3remainder1.2.1remove1.0remove-duplicates1.0remove-item2.0repeat1.0replace-item1.0report1.0reset-perspective3.0rp3.0reset-ticks4.0reset-timer1.0resize-world4.1reverse1.0rgb1.0ride3.0ride-me3.0right1.0rt1.0round1.0run1.3runresult1.3
Sscale-color1.0self1.3;(semicolon)sentence1.0se1.0set1.0set-current-directory2.0set-current-plot1.0set-current-plot-pen1.0set-default-shape1.0set-histogram-num-bars1.0__set-line-thicknessset-patch-size4.1set-plot-background-color6.0.2set-plot-pen-color1.0set-plot-pen-interval1.0set-plot-pen-mode1.0setup-plots5.0set-plot-x-range1.0set-plot-y-range1.0setxy1.0shade-of?1.0shapeshapes2.1show1.0show-turtle1.0st1.0show-link4.0shuffle2.0
![Page 24: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/24.jpg)
425425425426426426426427427427427427427427428428428428428428428428429429429429429430430430430430431431431431431432432432432432432433433433433433434434434434434434434435435435435435436436436
sin1.0sizesort1.0sort-by1.3sort-on5.0sprout1.0sqrt1.0stamp1.0stamp-erase3.1standard-deviation1.0startupstop1.0stop-inspecting5.2stop-inspecting-dead-agents5.2subject3.0sublist2.1substring1.0subtract-headings2.1sum1.0
Ttan1.0thicknesstick4.0tick-advance4.0ticks4.0tie4.0tie-modetimer1.0toto-reporttowards1.0towardsxy1.0turtle1.0turtle-set4.0turtles1.0turtles-at1.0turtles-here1.0turtles-on2.0turtles-owntype1.0
Uundirected-link-breeduntie4.0update-plots5.0uphill1.0uphill41.0user-directory3.1user-file3.1user-new-file3.1user-input1.1user-message1.1user-one-of3.1user-yes-or-no?2.0
Vvariance1.0
Wwait1.0watch3.0watch-me3.0while1.0whowith1.0<breed>-withlink-with4.0with-max2.1with-min2.1
![Page 25: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/25.jpg)
436436437437437437437437438438438438438
with-local-randomness4.0without-interruption1.1word1.0world-width3.1world-height3.1wrap-color1.0write2.0
Xxcorxor1.0
Yycor
->->6.0
![Page 26: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/26.jpg)
WhatisNetLogo?
NetLogoisaprogrammablemodelingenvironmentforsimulatingnaturalandsocialphenomena.ItwasauthoredbyUriWilenskyin1999andhasbeenincontinuousdevelopmenteversinceattheCenterforConnectedLearningandComputer-BasedModeling.
NetLogoisparticularlywellsuitedformodelingcomplexsystemsdevelopingovertime.Modelerscangiveinstructionstohundredsorthousandsof"agents"alloperatingindependently.Thismakesitpossibletoexploretheconnectionbetweenthemicro-levelbehaviorofindividualsandthemacro-levelpatternsthatemergefromtheirinteraction.
NetLogoletsstudentsopensimulationsand"play"withthem,exploringtheirbehaviorundervariousconditions.Itisalsoanauthoringenvironmentwhichenablesstudents,teachersandcurriculumdeveloperstocreatetheirownmodels.NetLogoissimpleenoughforstudentsandteachers,yetadvancedenoughtoserveasapowerfultoolforresearchersinmanyfields.
NetLogohasextensivedocumentationandtutorials.ItalsocomeswiththeModelsLibrary,alargecollectionofpre-writtensimulationsthatcanbeusedandmodified.Thesesimulationsaddresscontentareasinthenaturalandsocialsciencesincludingbiologyandmedicine,physicsandchemistry,mathematicsandcomputerscience,andeconomicsandsocialpsychology.Severalmodel-basedinquirycurriculausingNetLogoareavailableandmoreareunderdevelopment.
NetLogoisthenextgenerationoftheseriesofmulti-agentmodelinglanguagesincludingStarLogoandStarLogoT.NetLogorunsontheJavavirtualmachine,soitworksonallmajorplatforms(Mac,Windows,Linux,etal).Itisrunasadesktopapplication.Commandlineoperationisalsosupported.
Features
System:Free,opensourceCross-platform:runsonMac,Windows,Linux,etalInternationalcharactersetsupport
Programming:Fullyprogrammable
![Page 27: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/27.jpg)
ApproachablesyntaxLanguageisLogodialectextendedtosupportagentsMobileagents(turtles)moveoveragridofstationaryagents(patches)Linkagentsconnectturtlestomakenetworks,graphs,andaggregatesLargevocabularyofbuilt-inlanguageprimitivesDoubleprecisionfloatingpointmathFirst-classfunctionvalues(akaanonymousprocedures,closures,lambda)Runsarereproduciblecross-platform
Environment:Commandcenterforon-the-flyinteractionInterfacebuilderw/buttons,sliders,switches,choosers,monitors,textboxes,notes,outputareaInfotabforannotatingyourmodelwithformattedtextandimagesHubNet:participatorysimulationsusingnetworkeddevicesAgentmonitorsforinspectingandcontrollingagentsExportandimportfunctions(exportdata,saveandrestorestateofmodel,makeamovie)BehaviorSpace,anopensourcetoolusedtocollectdatafrommultipleparallelrunsofamodelSystemDynamicsModelerNetLogo3Dformodeling3DworldsHeadlessmodeallowsdoingbatchrunsfromthecommandline
Displayandvisualization:Line,bar,andscatterplotsSpeedsliderletsyoufastforwardyourmodelorseeitinslowmotionViewyourmodelineither2Dor3DScalableandrotatablevectorshapesTurtleandpatchlabels
APIs:controllingAPIallowsembeddingNetLogoinascriptorapplicationextensionsAPIallowsaddingnewcommandsandreporterstotheNetLogolanguage;opensourceexampleextensionsareincluded
![Page 28: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/28.jpg)
CopyrightandLicenseInformation
Howtoreference
IfyouuseorrefertoNetLogoinapublication,weaskthatyouciteit.Thecorrectcitationis:Wilensky,U.(1999).NetLogo.http://ccl.northwestern.edu/netlogo/.CenterforConnectedLearningandComputer-BasedModeling,NorthwesternUniversity,Evanston,IL.
ForHubNet,cite:Wilensky,U.&Stroup,W.,1999.HubNet.http://ccl.northwestern.edu/netlogo/hubnet.html.CenterforConnectedLearningandComputer-BasedModeling,NorthwesternUniversity.Evanston,IL.
FormodelsintheModelsLibrary,thecorrectcitationisincludedinthe"CreditsandReferences"sectionofeachmodel'sInfotab.
Acknowledgments
TheCCLgratefullyacknowledgestwodecadesofsupportforourNetLogowork.TheoriginalsupportcamefromtheNationalScienceFoundation--grantnumbersREC-9814682andREC-0126227.FurthersupporthascomefromREC-0003285,REC-0115699,DRL-0196044,CCF-ITR-0326542,DRL-REC/ROLE-0440113,SBE-0624318,EEC-0648316,IIS-0713619,DRL-RED-9552950,DRL-REC-9632612,andDRL-DRK12-1020101,IIS-1441552,CNS-1441016,CNS-1441041,CNS-1138461,IIS-1438813,IIS-1147621,DRL-REC-1343873,IIS-1438813,IIS-1441552,CNS-1441041,IIS-1546120,DRL-1546122,DRL-1614745andDRL-1640201.AdditionalsupportcamefromtheSpencerFoundation,TexasInstruments,theBradyFund,theMurphyfund,andtheNorthwesternInstituteonComplexSystems.
NetLogolicense
Copyright1999-2016byUriWilensky.
Thisprogramisfreesoftware;youcanredistributeitand/ormodifyitunderthetermsoftheGNUGeneralPublicLicenseaspublishedbytheFreeSoftwareFoundation;eitherversion2oftheLicense,or(atyouroption)anylaterversion.
Thisprogramisdistributedinthehopethatitwillbeuseful,butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyofMERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNUGeneralPublicLicenseformoredetails.
YoushouldhavereceivedacopyoftheGNUGeneralPublicLicensealongwiththisprogram;ifnot,writetotheFreeSoftwareFoundation,Inc.,51FranklinStreet,FifthFloor,Boston,MA02110-1301,USA.
Commerciallicenses
Commerciallicensesarealsoavailable.Toinquireaboutcommerciallicenses,[email protected].
NetLogoUserManuallicense
Copyright1999-2016byUriWilensky.
![Page 29: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/29.jpg)
TheNetLogoUserManualbyUriWilenskyislicensedunderaCreativeCommonsAttribution-ShareAlike3.0UnportedLicense.
Opensource
TheNetLogosourcecodeishostedathttps://github.com/NetLogo/NetLogo.Contributionsfrominterestedusersarewelcome.
Thirdpartylicenses
Scala
MuchofNetLogoiswrittenintheScalalanguageandusestheScalastandardlibraries.ThelicenseforScalaisasfollows:
Copyright (c) 2002 - EPFL
Copyright (c) 2011 - Lightbend, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or withoutmodification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice,this list of conditions and the following disclaimer.Redistributions in binary form must reproduce the above copyright notice,this list of conditions and the following disclaimer in the documentationand/or other materials provided with the distribution.Neither the name of the EPFL nor the names of its contributors may beused to endorse or promote products derived from this software withoutspecific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THEIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE AREDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLEFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIALDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS ORSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVERCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USEOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
MersenneTwisterFast
Forrandomnumbergeneration,NetLogousestheMersenneTwisterFastclassbySeanLuke.Thecopyrightforthatcodeisasfollows:
Copyright (c) 2003 by Sean Luke. Portions copyright (c) 1993 by Michael Lecuyer. All rights reserved.
Redistribution and use in source and binary forms, with or withoutmodification, are permitted provided that the following conditions are met:
![Page 30: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/30.jpg)
Redistributions of source code must retain the above copyright notice,this list of conditions and the following disclaimer.Redistributions in binary form must reproduce the above copyright notice,this list of conditions and the following disclaimer in the documentationand/or other materials provided with the distribution.Neither the name of the copyright owners, their employers, nor the namesof its contributors may be used to endorse or promote products derivedfrom this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THEIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE AREDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNERS OR CONTRIBUTORS BE LIABLEFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIALDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS ORSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVERCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USEOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Colt
PartsofNetLogo(specifically,therandom-gammaprimitive)arebasedoncodefromtheColtlibrary(http://acs.lbl.gov/~hoschek/colt/).Thecopyrightforthatcodeisasfollows:
Copyright 1999 CERN - European Organization for Nuclear Research. Permissionto use, copy, modify, distribute and sell this software and its documentationfor any purpose is hereby granted without fee, provided that the abovecopyright notice appear in all copies and that both that copyright notice andthis permission notice appear in supporting documentation. CERN makes norepresentations about the suitability of this software for any purpose. It isprovided "as is" without expressed or implied warranty.
Config
NetLogousestheTypesafe"Config"library.Copyright(C)2011-2012TypesafeInc.http://typesafe.comTheConfiglibraryislicensedundertheApache2.0License.Youmayobtainacopyofthelicenseathttp://www.apache.org/licenses/LICENSE-2.0.
ApacheCommonsCodec(TM)
TheNetLogocompilerusesadigestmethodfromtheApacheCommonsCodec(TM)library.ApacheCommonsCodec(TM)iscopyrightandtrademark2002-2014theApacheSoftwareFoundation.ItislicensedundertheApache2.0License.Youmayobtainacopyofthelicenseathttp://www.apache.org/licenses/LICENSE-2.0.
Flexmark
NetLogousestheFlexmarklibrary(andextensions)fortheinfotab.Thecopyrightandlicenseareasfollows:
Copyright (c) 2015-2016, Atlassian Pty Ltd All rights reserved. Copyright (c)2016, Vladimir Schneider, All rights reserved. Redistribution and use in
![Page 31: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/31.jpg)
source and binary forms, with or without modification, are permitted providedthat the following conditions are met: * Redistributions of source code mustretain the above copyright notice, this list of conditions and the followingdisclaimer. * Redistributions in binary form must reproduce the abovecopyright notice, this list of conditions and the following disclaimer in thedocumentation and/or other materials provided with the distribution. THISSOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANYEXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIEDWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE AREDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLEFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIALDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS ORSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVERCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USEOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
JHotDraw
Forthesystemdynamicsmodeler,NetLogousestheJHotDrawlibrary,whichisCopyright(c)1996,1997byIFAInformatikandErichGamma.ThelibraryiscoveredbytheGNULGPL(LesserGeneralPublicLicense).Thetextofthatlicenseisincludedinthe"docs"folderwhichaccompaniestheNetLogodownload,andisalsoavailablefromhttp://www.gnu.org/copyleft/lesser.html.
JOGL
For3Dgraphicsrendering,NetLogousesJOGL,aJavaAPIforOpenGL,andGluegen,anautomaticcodegenerationtool.FormoreinformationaboutJOGLandGluegen,seejogamp.org/.BothlibrariesaredistributedundertheBSDlicense:
Copyright 2010 JogAmp Community. All rights reserved.
Redistribution and use in source and binary forms, with or withoutmodification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, thislist of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,this list of conditions and the following disclaimer in the documentationand/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS ORIMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OFMERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NOEVENT SHALL JogAmp Community OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORYOF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDINGNEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation arethose of the authors and should not be interpreted as representing officialpolicies, either expressed or implied, of JogAmp Community.
You can address the JogAmp Community via: Web http://jogamp.org/Forum/Mailinglist http://forum.jogamp.org Chatrooms IRC irc.freenode.net#jogamp Jabber conference.jabber.org room: jogamp (deprecated!) Repositoryhttp://jogamp.org/git/ Email mediastream _at_ jogamp _dot_ org
![Page 32: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/32.jpg)
Matrix3D
For3Dmatrixoperations,NetLogousestheMatrix3Dclass.Itisdistributedunderthefollowinglicense:
Copyright (c) 1994-1996 Sun Microsystems, Inc. All Rights Reserved.
Sun grants you ("Licensee") a non-exclusive, royalty free, license to use,modify and redistribute this software in source and binary code form, providedthat i) this copyright notice and license appear on all copies of thesoftware; and ii) Licensee does not utilize the software in a manner which isdisparaging to Sun.
This software is provided "AS IS," without a warranty of any kind. ALL EXPRESSOR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANY IMPLIEDWARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE LIABLEFOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING ORDISTRIBUTING THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITSLICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT,INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVERCAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF ORINABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OFSUCH DAMAGES.
This software is not designed or intended for use in on-line control ofaircraft, air traffic, aircraft navigation or aircraft communications; or inthe design, construction, operation or maintenance of any nuclear facility.Licensee represents and warrants that it will not use or redistribute theSoftware for such purposes.
ASM
ForJavabytecodegeneration,NetLogousestheASMlibrary.Itisdistributedunderthefollowinglicense:
Copyright (c) 2000-2011 INRIA, France Telecom. All rights reserved.
Redistribution and use in source and binary forms, with or withoutmodification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, thislist of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,this list of conditions and the following disclaimer in the documentationand/or other materials provided with the distribution.
3. Neither the name of the copyright holders nor the names of its contributorsmay be used to endorse or promote products derived from this software withoutspecific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THEIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE AREDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLEFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIALDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS ORSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVERCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USEOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
![Page 33: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/33.jpg)
Log4j
Forlogging,NetLogousestheLog4jlibrary.Thecopyrightandlicenseforthelibraryareasfollows:
Copyright 2007 The Apache Software Foundation
Licensed under the Apache License, Version 2.0 (the "License"); you may notuse this file except in compliance with the License. You may obtain a copy ofthe License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, softwaredistributed under the License is distributed on an "AS IS" BASIS, WITHOUTWARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See theLicense for the specific language governing permissions and limitations underthe License.
PicoContainer
Fordependencyinjection,NetLogousesthePicoContainerlibrary.Thecopyrightandlicenseforthelibraryareasfollows:
Copyright (c) 2004-2011, PicoContainer Organization All rights reserved.
Redistribution and use in source and binary forms, with or withoutmodification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice,this list of conditions and the following disclaimer.Redistributions in binary form must reproduce the above copyright notice,this list of conditions and the following disclaimer in the documentationand/or other materials provided with the distribution.Neither the name of the PicoContainer Organization nor the names of itscontributors may be used to endorse or promote products derived from thissoftware without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THEIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE AREDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLEFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIALDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS ORSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVERCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USEOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Parboiled
Forreadingmodels,NetLogousestheParboiledlibrary.ThecopyrightandlicenseforParboiledareasfollows:
This software is licensed under the Apache 2 license, quoted below. Copyright
![Page 34: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/34.jpg)
© 2009-2013 Mathias Doenitz http://parboiled2.org Copyright © 2013 AlexanderMyltsev Licensed under the Apache License, Version 2.0 (the "License"); youmay not use this file except in compliance with the License. You may obtain acopy of the License at [http://www.apache.org/licenses/LICENSE-2.0] Unlessrequired by applicable law or agreed to in writing, software distributed underthe License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES ORCONDITIONS OF ANY KIND, either express or implied. See the License for thespecific language governing permissions and limitations under the License.
RSyntaxTextArea
TheNetLogoeditorusestheRSyntaxTextArealibrary.Thecopyrightandlicenseareasfollows:
Redistribution and use in source and binary forms, with or withoutmodification, are permitted provided that the following conditions are met: *Redistributions of source code must retain the above copyright notice, thislist of conditions and the following disclaimer. * Redistributions in binaryform must reproduce the above copyright notice, this list of conditions andthe following disclaimer in the documentation and/or other materials providedwith the distribution. * Neither the name of the author nor the names of itscontributors may be used to endorse or promote products derived from thissoftware without specific prior written permission. THIS SOFTWARE IS PROVIDEDBY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIEDWARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OFMERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NOEVENT SHALL ©RIGHT HOLDER& BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; ORBUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHERIN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THEPOSSIBILITY OF SUCH DAMAGE.
JCodec
TheNetLogovidextensionmakesuseoftheJCodeclibrary.ThecopyrightandlicenseforJCodecareasfollows:
Redistribution and use in source and binary forms, with or withoutmodification, are permitted provided that the following conditions are met:Redistributions of source code must retain the above copyright notice, thislist of conditions and the following disclaimer. Redistributions in binaryform must reproduce the above copyright notice, this list of conditions andthe following disclaimer in the documentation and/or other materials providedwith the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ANDCONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOTLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR APARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER ORCONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; ORBUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHERIN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THEPOSSIBILITY OF SUCH DAMAGE.
Java-Objective-CBridge
![Page 35: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/35.jpg)
NetLogoonMacOSXmakesuseoftheJava-Objective-CBridgelibrary.ThislibrarywascreatedbySteveHannahandisdistributedundertheApache2.0license,availableathttps://www.apache.org/licenses/LICENSE-2.0.
Webcam-capture
TheNetLogovidextensionmakesuseoftheWebcam-capturelibrary.ThecopyrightandlicenseforWebcam-captureareasfollows:
The MIT License (MIT) Copyright (c) 2012 - 2015 Bartosz Firyn and ContributorsPermission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions: The above copyrightnotice and this permission notice shall be included in all copies orsubstantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS",WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TOTHE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE ANDNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLEFOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE ORTHE USE OR OTHER DEALINGS IN THE SOFTWARE.
Guava
TheNetLogolsextensionmakesuseoftheGuavalibrary.GuavaisreleasedundertheApacheLicense2.0(http://www.apache.org/licenses/LICENSE-2.0)
Gephi
ThenwextensionmakesuseoftheGephilibrary.Gephiislicensedunderthefollowingterms:
Gephi Dual License Header and License Notice
The Gephi Consortium elects to use only the GNU General Public License version3 (GPL) for any software where a choice of GPL license versions are madeavailable with the language indicating that GPLv3 or any later version may beused, or where a choice of which version of the GPL is applied is unspecified.
For more information on the license please see: the Gephi License FAQs.
License headers are available on http://www.opensource.org/licenses/CDDL-1.0and http://www.gnu.org/licenses/gpl.html.
RExtension
TheNetLogoRExtensionislicensedunderthefollowingterms:
The R extension is Copyright (C) 2009-2016 Jan C. Thiele and Copyright (C)2016 Uri Wilensky / The Center for Connected Learning. NetLogo-R-Extension isfree software; you can redistribute it and/or modify it under the terms of theGNU General Public License as published by the Free Software Foundation;either version 2 of the License, or (at your option) any later version. This
![Page 36: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/36.jpg)
program is distributed in the hope that it will be useful, but WITHOUT ANYWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FORA PARTICULAR PURPOSE. See the GNU General Public License for more details. Youshould have received a copy of the GNU General Public License along withNetLogo-R-Extension (located in GPL.txt). If not, seehttp://www.gnu.org/licenses.
JNA
TheNetLogoRExtensionmakesuseoftheJNAlibrary.TheJNAlibraryislicensedunderthefollowingterms:
This copy of JNA is licensed under the Apache (Software) License, version 2.0("the License"). See the License for details about distribution rights, andthe specific rights regarding derivate works. You may obtain a copy of theLicense at: http://www.apache.org/licenses/
![Page 37: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/37.jpg)
What'sNew?NetLogo6.0.2UserManual
Thefollowingisacondensedhistory.DetailedreleasenotesareonGitHub.
Forhelprunningmodelsmadeinoldversions,seetheTransitionGuide.
Version6.0.2(August2017)
FeatureChanges
TheautosuggestfunctionalityintroducedinNetLogo6willnowdisplayextensionprimitivenames.Anewinsert-itemprimitivewasaddedtothelanguage.Itworkssimilarlytoreplace-item,butwithoutremovingtheitematthespecifiedindex.Anewset-plot-background-colorprimitivewasaddedtothelanguage.Itcanbeusedinplottingcodetosetthebackgroundcoloroftheplot.Behaviorsearch'suserinterfacehasbeenupdated.ItnowusestheJavaFXUItoolkitforamoremodernlookandfeel.
Bugfixes
The6.0.1autoconverterwoulderrorwhenconvertingtaskswithexactlyoneargument(from5.3.1andearliermodelsonly).Theconversionwouldbecorrect,butitwasconfusing.Thishasnowbeenremediedandtheautoconverterwillcorrectlyconvertmodelsfrom5.3.1andearlierwithouterroringonsingle-argumenttasks.Fixabugwhereextensionsweren'tlocatedproperlywheninapathrelativetothemodel.Helpbrowsernowopensin64-bitWindows.Fixaspeedregressionfortheimport-worldprimitiveintroducedin6.0.Ifanunexpectedreporterblockispassedtowithwhenusedwithother,theerrorwillnowreflectthattheblockisunsuitableforwithinsteadofother.Whensort-byreceivesanunsuitablereporterblockfromtheuseritnowshowsausefulerrorinsteadofacrypticstacktrace.StringrepresentationsofanonymousproceduresnowshowtheargumentsofthoseanonymousproceduresWhenworkinginannlsfile,switchingtoadifferenttabwillcompilethenlsfile.Displayerrorlabelonnlsfilewhenthecodeitcontainscausesanerror.SomeuserswereunabletoopenNetLogo6and6.0.1inMacOSSierra.We'vechangedoursigningprocessin6.0.2toattempttofixthisproblem.Wearecontinuingtotrackthisissuetodeterminewhetherourfixwaseffective.Moreinformation(includingapartialworkaroundfortheproblem)isavailablehere.
ExtensionChanges
Fixedabugingis:patch-datasetintroducedinNetLogo6.Thetableextensionhasnewtable:group-agentsandtable:group-itemsprimitiveswhichcanbeusedtobuildatableofgroupedagentsanditemsbysupplyingananonymousreporter.
DocumentationChanges
![Page 38: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/38.jpg)
Clarifywhenvariouspartsoftheanonymousproceduresyntaxareoptional.Fixafewsmalldocumentationbugsaroundforeach.Clarifyrelationshipbetweenspeedandupdatemodalityinthe"ViewUpdates"sectionoftheprogrammingguide.
ModelChanges
NewSampleModels:
ChaosinaBoxFairyCirclesSmoothLife
NewCurricularModels:
LatticeLandCurriculumLatticeLand-TrianglesExploreLatticeLand-TrianglesDissection
RevisedSampleModels:
Anisogamy:Newcolorscheme.AddsBehaviorSpaceexperiments.Ethnocentrism:Nowcross-listedasanEvolutionarymodel.Fireworks:Renamefireworkstomax-fireworksandenforceaminimumof1.GenJam-Duple:Minorinfotabupdates.WolfSheepPredation:Revisedtobetterclarifythegrass?constructandcode.
RevisedCurricularModels:
ConnectedChemistry:ConnectedChemistry1:FixNetLogoWebincompatibility.ConnectedChemistry3:Updateminimumnumberofparticlesto2.ConnectedChemistry8:Minorcodeupdates.Smallchangetodefaultvalues.
RevisedHubNetActivities:
GridlockHubNet:Minorcodeupdates.
RevisedCodeExamples:
InfoTabExample:Correctedformattingofun/orderedlistsexample.LSExtension–ModelVisualizerandPlotterExample:UpdatedcodedependenciesforWSP.LSExtension–ModelInteractionsExample:UpdatedcodedependenciesforWSP.
Version6.0.1(March2017)
FeatureChanges
![Page 39: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/39.jpg)
Bracketsarerequiredaroundanonymousprocedurereportersonlywhentherearetwoormorearguments.Forinstance[ [x] -> x ] cannowbewritten[ x -> x ] .NotethischangemakesitpossibletocreatemodelsinNetLogo6.0.1thatwillnotruninNetLogo6.0.IfyouplantouseyourmodelinNetLogo6.0,besuretoincludebracketsaroundanonymousprocedurearguments.Forashortperiodaftertherelease,modelswhichuseunbracketedlambdaargumentsmaynotworkonnetlogoweb.org.
Bugfixes
TheNetLogocodeeditornavigatesandindentsmodelsmuchmorequicklyandefficientlythaninNetLogo6.0.TheNetLogo5-to-6autoconverternowignorescommented-outcode.Thebehavioroflayout-radialinNetLogo6didnotmatchthe5.3.1behavior.Thishasbeencorrectedandlayout-radialshouldbeidenticalbetweenNetLogo6.0.1andNetLogo5.3.1NetLogo6raisedaNullPointerExceptionwhennumbersbecametoolargeforNetLogotohandle.Thisisnowproperlydisplayedtotheuserasanumberoutofboundserror.Improvedperformanceofmodelswhichuseletandanonymousprocedurestogether.Reloadingamodelnowclearsglobalvariables.ClearerwarningdialogswhenopeninganolderversionofaNetLogo2DfileinNetLogo3D.UsingforeachimproperlyintheCommandCenterwilldisplaythesameerrorasitwouldifusedimproperlyinthecodetab.Extremelylonganonymousproceduresnolongercauseanexceptionwhencompiled.in-radiusisnolongerpathologicallyslowonagentsetscreatedusingwith.
ExtensionChanges
Anewprimitive,table:valueshasbeenaddedtothetableextension.TheRextensionhasbeenupdatedtotakefulladvantageoftheJavaGDRlibraryusingr:setPlotDevice.UserscannowsupplyapathtotheRextensionbyconfiguringthevalueofr.lib.pathsintheuser.propertiesfile.FixedaLevelSpacebugpreventinginteractivemodelsfromusingnlsfiles.FixedaLevelSpacebugcausingNetLogotolockupwhentryingtoloadanonexistentfileasaninteractivemodel.
DocumentationChanges
ThesystemdynamicstutorialnowinstructstheusertosetthedttoavaluewhichgivesstablebehaviorThedocumentationforfollow,ride,andwatchhasbeenclarifiedtoindicatethatcallingoneundoeshighlightsandperspectivechangescausedbytheotherThedocumentationfor=and!=indicatesthattheyworkwithextensionobjects.Severalexampleshavebeenaddedtosortclarifyingthebehaviorofsortonlistsfeaturingdifferenttypesofobjects.AnewsectiononUserInterfaceprimitiveshasbeenaddedtotheprogrammingguidewhichdiscussesthebehaviorofthe"Halt"buttoninthevarioususerinteractiondialogs.Incorrectexamplecodeforforeachandreducehasbeencorrected.
Models
Allmodelshavebeenupdatedtoreflectthenewoptionalnatureofbracketsforzero/one
![Page 40: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/40.jpg)
argumentanonymousprocedures.Thisresultedinchangesto108models.
Allmodelshavebeenupdatedtoreflecttheavailabilityofthenewrangeprimitive.Thisresultedinchangesto12models.
NewSampleModel
GenJam-Duple
NewCurricularModel
LatticeLandcurriculum:LatticeLandExplore
RevisedSampleModels
PD2PersonIterated:infotabupdatesandextensivefixesforthecode.Party:fixedbugwhereamonitorcoveredaplot.SignalingGame:infotabupdates.
RevisedCurricularModels
GenEvocurriculum:GenEvo1GeneticSwitch:infotabupdatesandnewgraduatedmethodofdisplayinglacZconcentration.GenEvo2GeneticDrift:infotabupdatesandinterfacetweaks.Newmodelpreview.GenEvo3GeneticDriftandNaturalSelection:infotabupdatesandinterfacetweaks.GenEvo4Competition:infotabupdates.GeneticSwitch-SyntheticBiologyhasbeenrenamedandisnowSyntheticBiology-GeneticSwitch.Italsoreceivedinfotabupdatesandafewinterfacechanges.
Version6.0(December2016)
FeatureChanges
TheNetLogocodeeditornowoffersautocompletionsupport.SimplypresstheControlkeyandthespacebaratthesametimewhiletypingawordandyouwillseealistofsimilarNetLogoprimitivesassuggestions.TheNetLogocodeeditorofferstheoptionto"fold"procedurestomakenavigatinglargemodelssimpler.NetLogosupportsmulti-levelagent-basedmodelingwiththeLevelSpaceextensionLinenumberingcanbeenabledintheNetLogocodeeditorbychoosing"ShowLineNumbers"fromthe"Preferences"dialog.Thisdialogcanbeopenedbyselecting"NetLogo">"Preferences"inMac,or"Tools">"Preferences"onLinuxorWindows.Theviewresizingarrowshavebeenremovedandthetickcounterhasbeenrelocatedunderthespeedslider.WheneditingNetLogocode,userscanright-clickavariablenameorprimitiveandchoose"ShowUsage"toseeallusagesofthatnameinthefile.
![Page 41: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/41.jpg)
WheneditingNetLogocode,userscanright-clickavariablenameandchoose"JumptoDeclaration"toseewhereinthefilethatvariableisdeclared.TheNetLogointerfaceeditornowsupports"Undo"forwidgetaddition,deletion,andmovement.NetLogocanexportcodetoHTMLwithcode-colorizationbychoosing"ExportCode"inthe"Export"sectionofthe"File"menu.ThelookandfeelofNetLogoonMacOSXhaschangedsignificantly.NetLogoisnowusingtheOracle-suppliedJavalookandfeelasopposedtoathird-partylookandfeelusedinpriorversions.Plotsusearandomnumbergeneratorindependentofthemain-modelrandomnumbergenerator.ModelPreviewCommandscanbeeditedthroughtheGUIbychoosing"PreviewCommandsEditor"inthe"Tools"menu.ThosecommandsgeneratethepreviewimagethatappearswhenyouuploadyourmodeltotheModelingCommons.NetLogodisplaysamorehelpfulerrormessagewhenaprogramfailsduetoan"outofmemory"error.NetLogoanditsbundledextensionsarenowcompiledagainstJava8andScala2.12.NetLogohasupgradedtheASMbytecodelibrarytoenablegenerationofJava8bytecode.
Bugfixes
*-link-neighbor?primitivesnowworkthesamewayforbreededandunbreededlinks.ResizingtheworldinNetLogo3Dnolongercausesablackview.Fixederrorcausedbyright-clickingawidgetwhiledragging.Improvederrormessagewhenauser-definedprocedureshadowsabreedprocedure.neighbors4andneighborsnolongerreportagentsetscontainingthesamepatchmorethanonce.
LanguageChanges
Supportforplural-onlybreednames(e.g.,breed [mice])hasbeenremoved.Writebreed[mice mouse]instead.Taskshavebeenreplacedbyanonymousprocedures.Tasksmadeuseof?variableswhichwereconfusingfornovicesanddifficulttoreadforexperts.Additionally,taskscouldnotrefertothetaskvariablesofacontainingtask.Anonymousproceduresmayhavenamedargumentswhichcanbeaccessedbyinneranonymoustasks.UponfirstopeningaNetLogo5modelinNetLogo6,tasksliketask [ ?1 + ?2 ] willbeautomaticallyconvertedto[ [?1 ?2] -> ?1 + ?2 ] .Seethethetransitionguideformoreinformation.LinkreportershavebeenoverhauledtobemoreconsistentandflexibleThetaskprimitiveisnolongersupported.Breednamesthatconflictwithlanguageprimitivesarenowdisallowed.Forinstance,breed [strings string]isnowdisallowedsinceitmakesis-string?ambiguous.Thecompilererrorsonduplicatedbreedsingularnames.Thecompilerdetectsagreaternumberoftypeerrors,forinstancenot pxcornowraisesacompilererrorinsteadoferroringatruntime.set-plot-pen-colornowacceptsRGBlistsasarguments.Thehubnet-set-client-interfaceprimitivehasbeenremoved.Thevariousprimitivesstartingwithmovie-havebeenremoved,ashasthemovieencoder.Theyhavebeenreplacedwiththenewvidextension.Thetransitionguideprovidesmoredetailsandinformation.The__change-languageprimitivehasbeenremoved.YoucannowchangetheUserInterfaceLanguagethroughthepreferencesdialog,whichcanbefoundbychoosing
![Page 42: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/42.jpg)
"Preferences..."inthe"NetLogo"menu(MacOSX)orinthe"Tools"menu(allotherplatforms).Thestringrepresentationofanonymousproceduresdisplaysthebodyoftheanonymousprocedure.
ExtensionChanges
NetLogo6.0comeswiththreenew,bundledextensions:LevelSpacels,thevidextensionforvideomanipulation,andtheenhancedvisualizationextensionview2.5d.lsenablesmulti-levelagent-basedmodelinginNetLogo.TheExtensionsAPIhasbeenupdatedfrom5.0to6.0.Thismeansthatallnon-bundledextensionswillneedtobeupdatedtousethenewAPI.ExtensionswrittenforNetLogo5willnotworkinNetLogo6.Ifyou'reanextensionauthor,seetheextensionauthortransitionguidefor6.0formoreinformation.IfyouregularlyuseextensionsyoumaywanttocontacttheirauthorstoinformthemanewversionofNetLogoisonthewayandtheymaywanttoupdatetheirextensions.arduino:get(inthearduinoextension)correctlyreportsvaluesfromWindows64-bitmachines.Inpriorversionsitwouldonlyreportsomevaluescorrectly.Severalnewfeatureshavebeenaddedtothenwextension:
AddedcommunitydetectionusingtheLouvainmethodAddedmodularitymeasurementAddedWatts-Strogatzsmall-worldnetworkgenerationMadeothernetworkgenerationalgorithmseasiertolayoutWeightedprimitivesnowtakesymbolicvariablenamesinsteadofstrings.Seethetransitionguideformoreinformation.
TheqtjextensionisnolongerbundledwithNetLogo.Usersareencouragedtomakeuseofthenewvidextension.ThenewvidextensionisnowbundledwithNetLogo,combiningfeaturesofthelateqtjextensionandthemovieprimitives.ThenetworkextensionisnolongerbundledwithNetLogo.Usersareencouragedtousethenwextension(https://ccl.northwestern.edu/netlogo/docs/nw.html),whichhasbeenbundledwithNetLogoforsometime.Thegogo-serialextensionisnolongerbundledwithNetLogo.Usersareencouragedtotransitiontothenewergogoextension,whichusesHIDtocommunicatewiththeGoGoboard.
OperatingSystemSupport
NetLogowillnowbeusedtoopen.nlogolinksinPowerPointandotherprogramsonMicrosoftWindows.TheNetLogobinariesonMacOSXareinstalledasrunnablebyanyuser.NetLogoinMacOSXwillnotuse"AppNap"whilerunning.ThiskeepssimulationsrunningatfullspeedwhenNetLogoisinthebackground.TheNetLogocontrollingAPIhaschangedsinceNetLogo5.ProgramsthatrelyonthecontrollingAPI(suchasBehaviorSearch)willnotworkuntiltheyhavebeenchangedtomatchthenewAPI.
DocumentationChanges
NewdocumentationforanonymousproceduresTheNetLogotutorialscreenshotshavebeenupdatedtocorrespondtothenewMacOSXLookandFeel.TheNetLogodictionarydisplaystheversioninwhicheachprimitivewasintroducednexttothatprimitive.
![Page 43: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/43.jpg)
ASpanishtranslationoftheNetLogodictionaryisavailablehere
InternationalizationChanges
AnewSpanishtranslationoftheNetLogodictionaryisavailableaspartoftheNetLogomanual.Languagepreferencescanbechangedbyusingthenew"Preferences"menuinsteadofthe__change-languageprimitive.AJapaneselocalizationforNetLogoisnowavailableandincludedwiththestandarddownload.TheChinesetranslationforNetLogohasbeenupdated.
Models
NewSampleModels:
KickedRotatorKickedRotatorsMammoths,alegacyStarLogoTmodel,hasbeenconvertedtoNetLogo.
NewCurricularModels:
GenEvo1GeneticSwitchGenEvo2GeneticDriftGenEvo3GeneticDriftandNaturalSelectionGenEvo4Competition
NewCodeExamples:
MoviePlayingExample(vidextension)MovieRecordingExample(vidextension)VideoCameraExample(vidextension)NetworkExtensionGeneralDemo(nwextension)ModelInteractionsExample(lsextension)ModelLoaderExample(lsextension)ModelVisualizerandPlotterExample(lsextension)
PromotedModels(improvedandnolonger"unverified"):
ProbLabGeneticsTraffic2Lanes
RevisedSampleModels:
GiantComponent:addedtextintheinfotab.TeamAssembly:removedunusedswitchwidget.TrafficBasic,TrafficGrid,TrafficIntersection:revisedinfotab.Voting:stoppedthemodelwhenvotingstabilizes.WealthDistribution:fixedtyposininfotab,improvedcodeformatting.
![Page 44: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/44.jpg)
RevisedHubNetActivities:
BugHuntersCompetitionHubNet,CritterDesignersHubNet,FishSpottersHubNet:removedunnecessarycalltohubnet-set-client-interface.GridlockHubNet,GridlockAlternateHubNet:revisedinfotab.
RevisedCurricularModels:
DNAReplicationFork:fixedaamonitorandruntimeerrorwhenusingatimelimit.
RevisedIABMmodels:
AgentsetEfficiency:clarifieddescriptionofgo-2ininfotab.AgentsetOrdering:fixedtyposinintotab.ArduinoExample:improvedmodeltodemonstratebothdirectionsofcommunicationwiththeArduino.HeroesandCowards:removedextratextininfotab.PreferentialAttachmentSimple:removedextrapeninplotandextra"layout"button.RandomNetwork:madesurethatthenumberoflinksisnevertoobigforthenumberofnodes.SegregationSimpleExtension1,2and3:fixednumber-of-ethnicitiesslidertoavoidruntimeerrors.TrafficBasicAdaptiveIndividuals,TrafficBasicUtility,TrafficGridGoal:revisedinfotab.TrafficBasicAdaptive:revisedinfotab,clarifiedcommentinadaptive-goprocedure.VotingComponentVerification:stoppedthemodelwhenvotingstabilizes.VotingSensitivityAnalysis:improvedcodeforstoppingthemodelwhenvotingstabilizes.
RevisedCodeExamples:
GoGoMonitorSerial,GoGoMonitorSimpleSerial:removedthemodels,asthegogo-serialandqtjextensionsarenolongerbundled.RandomNetworkExample:madesurethatthenumberoflinksisnevertoobigforthenumberofnodes.SincetheQuickTimeextension(qtj)hasbeenreplacedbythevidextension,thefollowingmodelshavebeenconvertedtousethevidextension:
MovieExample,replacedbyMovieRecordingExampleQuickTimeMovieExample,replacedbyMoviePlayingExampleQuickTimeCameraExample,replacedbyVideoCameraExample
Demotedmodel:
ElFarolNetworkCongestion,apreviously"unverified"model,hasbeenmovedtotheNetLogoUserCommunityModels
Version5.3.1(February2016)
FeatureChanges
MathematicaLinkisnowincludedandhasbeentestedtoworkwithMathematica10.
![Page 45: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/45.jpg)
AlinktoIntroductiontoAgent-BasedModellinghasbeenaddedtothe"Help"menu.
ExtensionChanges
ThegogoextensionnowpromptstheuserforthelocationofJavauponopening.ThisversionofJavaisusedtolaunchthegogohiddaemon.Thecorrectversionofthenetworkextensionisnowbundled,whichwillopenproperlyBundlesthecfextension,whichaddsmatch,case,andselectprimitives.
Bugfixes
Correctsabugwhereturtleswrappingaroundatorus-shapedworldwithpendownwouldsometimescauseNetLogotoloopinfinitely.FixesabugwherebuttonswouldappeartoremainpressedafterarightclickonMac.Fixesabugwherepressingtherightmousebuttonwhiledraggingwouldconfusethemouse-down?primitive.Fixesagenttype-checkingoftasks(bugappearedin5.2.1).link-neighbor?nowreturnstrueifandonlyiftheneighborisconnectedthroughanundirectedlink.Documentationfixesformy-linksandmeanprimitives.
Version5.3(December2015)
FeatureChanges
Java8isnowbundledwithallversionsofNetLogo,thisremovestheneedforaseparateJava6installationonMacOSXSeparate32-bitand64-bitversionsareavailableforbothWindowsandLinuxTheWindowsinstallerisnowanmsiinsteadofanexejavax.media.openglisnolongersupportedinJava8,ithasbeenreplacedbycom.jogamp.openglMathematicaLinkisnotdistributedduetoJavaversionchanges
ExtensionChanges
Aminorupdatetothenwextensionmakesnw:weighted-path-tobehaveasdocumented.Mostextensionsshouldcontinuetoworkwithoutchangeunlesstheyrelyonjavax.media.opengl,whichwasrenamedintheupdatedversionofJOGL.
Version5.2.1(September2015)
Extensions
AnincludedArduinoextensionforusewithArduinoboards
Newfeatures
NewfilemenuitemtoexportmodelstoNetLogoWeb
![Page 46: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/46.jpg)
Bugfixes
BehaviorSpaceoutputtypepreferenceisnowrememberedOutputwidgetfontisnowsavedatthepropersizewhenzoomedReportertasksarenowevaluatedinvariablecontextrunresultargumentsnowonlygetevaluatedonceThelastuseddirectoryisnowrememberedonLinuxWhitespaceisnowstrippedfrommodelswhensaving
NewSampleModels:ArtificialAnasazi,BacteriaFoodHunt,BacteriaHuntSpeeds,BeeSmart-HiveFinding,BugHuntDisruptions,BugHuntEnvironmentalChanges,BugHuntPredatorsandInvasiveSpecies-TwoRegions,HydrogenDiffusion3D,Lennard-Jones,PathsThereare46newmodelsinthenewIABMTextbookfolder:TurtlesCirclingSimple,AntsSimple,HeroesandCowards,LifeSimple,SimpleEconomy,4DLAextensions,4ElFarolExtensions,4FireExtensions,4SegregationExtensions,5WolfSheepExtensions,AgentsetEfficiency,AgentsetOrdering,Communication-T-TNetworkExample,PreferentialAttachmentSimple,RandomNetwork,TrafficBasicAdaptive,TrafficBasicUtility,TrafficGridGoal,SpreadofDisease,VotingComponentVerification,VotingSensitivityAnalysis,ArduinoExample,DiseaseWithAndroidAvoidanceHubNet,ExampleHubNet,RunExample,RunResultExample,SimpleMachineLearning,SimpleViralMarketing,TicketSales,SandpileSimpleNewmodelsinthenewAlternateVisualizationsfolder:Ethnocentrism-AlternativeVisualization,Flocking-AlternativeVisualizations,HeatDiffusion-Alternativevisualization,Virus-AlternativeVisualization,Virus-CircleVisualizationPromotedmodels:Honeycomb,MinorityGameManyotherbugfixesandupgrades
Modelchanges
ImprovedSampleModels:Altruism,AntLines,ArtificialAnasazi,Cooperation,Daisyworld,DividetheCake,HeatDiffusion,HydrogenDiffusion3D,Lennard-Jones,N-Bodies,PDBasicEvolutionary,Sandpile,RobbytheRobot,Segregation,SimpleKinetics2and3,TrafficGrid,GridLockHubNet,GridLockHubNetAlternateRevisedCurricularModels:4BlockStalagmites,4BlockTwoStalagmites,BugHunterCompetitionHubNet,FishSpottersHubNet,Ising,TijuanaBordertowns,UrbanSuite-TijuanaBordertowns,RevisedCodeExamples:LotteryExample,selfExample,NetworkImportExampleRevisedIABMTextbookmodels:SimpleEconomy,FireSimpleExtension2and3,SegregationSimple,1,2and3,AgentsetEfficiency,PreferentialAttachmentSimple,RandomNetwork,TrafficBasicAdaptive,RunExample,TrafficGridGoal,NewIABMTextbookmodel:TrafficBasicAdaptiveIndividuals
Version5.2.0(April2015)
Extensions
AnincludedCSVextensiontoreadandwriteCSVfilesAnincludedPaletteextensiontomapdifferentvaluestocolorsThepreviousgogoextensionhasbeenremoved.Ithasbeenreplacedwithtwodifferentgogoextensions,gogoandgogo-serial.Theextensionsworkwithdifferenthardware.ThegogoextensionworkswiththenewstyleHID-interfacegogoboardsandthegogo-serialextensionworkswiththeold-styleserial-interfacegogoboards
![Page 47: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/47.jpg)
Upgradetothenetworkextensionincludingthefollowingchanges:Supportformanymorefiletypes,includingGEXF,GDF,GML,PajekNET,UCINETDL,andNetdrawVNAFixedbugswithGraphMLsupportImproveddocumentation
Newfeatures
Newprimitivenetlogo-web?addedtotestwhetheryouarecurrentlyrunninginNetLogoWebNewprimitivebehaviorspace-experiment-nameaddedallowingyoutogetthenameofthecurrentlyrunningexperimentNewprimitivestop-inspectingtostopinspectingagentsNewprimitivestop-inspecting-dead-agentsandmenuitemtostopinspectingdeadagents__includeskeywordnowenablestheIncludesbuttonwhengivenanemptyhooksaddedforextensionstowritecustomlogmessages
Bugfixes
user-one-ofwillnowsignalanerrorearlierwhenprovidedanemptylistofchoiceshsb,extract-hsb,andapproximate-hsbhavebeenupdatedtorepresenttruehsbconventionsnewdeprecatedprimitives__hsb-old,__extract-hsb-old,and__approximate-hsb-oldworkastheoldhsbprimitivesdidwhenoldermodelsusingthehsbprimitivesareopenedinNetLogo5.2,theywillbeauto-convertedtousethedeprecatedprimitivesextract-hsb--fixedbugwhereitdidn'tworkcorrectlyonrgblists
Modelchanges
NewSampleModels:ArtificialAnasazi,BacteriaFoodHunt,BacteriaHuntSpeeds,BeeSmart-HiveFinding,BugHuntDisruptions,BugHuntEnvironmentalChanges,BugHuntPredatorsandInvasiveSpecies-TwoRegions,HydrogenDiffusion3D,Lennard-Jones,PathsThereare46newmodelsinthenewIABMTextbookfolder:TurtlesCirclingSimple,AntsSimple,HeroesandCowards,LifeSimple,SimpleEconomy,4DLAextensions,4ElFarolExtensions,4FireExtensions,4SegregationExtensions,5WolfSheepExtensions,AgentsetEfficiency,AgentsetOrdering,Communication-T-TNetworkExample,PreferentialAttachmentSimple,RandomNetwork,TrafficBasicAdaptive,TrafficBasicUtility,TrafficGridGoal,SpreadofDisease,VotingComponentVerification,VotingSensitivityAnalysis,ArduinoExample,DiseaseWithAndroidAvoidanceHubNet,ExampleHubNet,RunExample,RunResultExample,SimpleMachineLearning,SimpleViralMarketing,TicketSales,SandpileSimpleNewmodelsinthenewAlternateVisualizationsfolder:Ethnocentrism-AlternativeVisualization,Flocking-AlternativeVisualizations,HeatDiffusion-Alternativevisualization,Virus-AlternativeVisualization,Virus-CircleVisualizationPromotedmodels:Honeycomb,MinorityGameManyotherbugfixesandupgrades
Version5.1.0(July2014)
bundlenewnetworkextensionFilemenuincludesrecentlyopenedfiles
![Page 48: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/48.jpg)
deprecateappletssupportretinadisplayonnewMacBooks
Version5.0.4(March2013)
uploadmodelstotheModelingCommons
Version5.0(February2012)
features:opensource(GPLlicense;sourcecodeonlineathttps://github.com/NetLogo/NetLogo)newlicenseforSampleModelsandCurricularModelsisCreativeCommonsAttribution-NonCommercial-ShareAlikeinternationalcharacters(Unicode)supportedthroughoutapplicationGUIislocalizedinSpanish,Russian,andChinese(volunteertranslatorswanted)richformattingandimagesinInfotabsusingMarkdownplottingcodegoesinsideplotsinsteadofincodetabauthorablemodelspeed(targetframeratesetting)buttonsoptionallydisableuntilticksstarttranslucentcolorsin3DviewandNetLogo3D(forRGBcolorsonly)
languagechanges:"tasks"storecodetoberunlater
akafirst-classfunctions,closures,lambdanewprimitives:task,is-command-task?,is-reporter-task?theseprimitivesaccepttasks:run,runresult,foreach,map,reduce,filter,n-values,sort-by
improvedoveralllistperformance(manyoperationstakenear-constanttimeinsteadoflineartime)youmustusereset-tickstostartthetickcounterbeforeusingtickortick-advancenewprimitivessetup-plotsandupdate-plotsnewprimitivesort-onletsyousaye.g.,sort-on [size] turtlesnewprimitiveerrorcausesaruntimeerrorrandom-normalrejectsnegativestandarddeviations
HubNet:activitiescanrunheadlessnewprimitiveshubnet-clients-list,hubnet-kick-client,hubnet-kick-all-clientshubnet-set-client-interfacenolongerrequired
otherfixesandchanges:tabsrenamedtoInterface/Info/CodeCommandCenterallowsreporters,addsshowcommandautomaticallyNetLogo3Duses.nlogo3dsuffix,not.nlogoimport-worldismuchfasterstartupnolongerrunsheadlessorinbackgroundBehaviorSpacerunsfixed3DrenderingbugwheresmallturtlesweretoobrightMacapprunsin64bitmodebydefaultupgradedWindowsinstallerGoGoextensiongetting-startedexperiencenowsmootheronallplatforms
models:newSampleModels:Sandpile,Lightning,OsmoticPressure,RobbytheRobot,PreferentialAttachment3DnewCurricularModels:BugHuntConsumers,BugHuntPredatorsandInvasiveSpecies,PlantSpeciation,epiDEMBasic,epiDEMTravelandControl,Connected
![Page 49: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/49.jpg)
ChemistryAtmospherenewCodeExamples:InfoTabExample,GoGoMonitorSimple
Version4.1.3(April2011)
matrixextensionbehaviorspace-run-number
Version4.1(December2009)
parallelBehaviorSpacecontrollingAPIallowsembeddingautomaticcodeindentersearchableModelsLibrarytranslucentcolorsmini-viewsinagentmonitorsresize-world,set-patch-sizebitmap,QuickTimeextensionsindividualizedHubNetclientviewsbrowser-basedHubNetclient
Version4.0(September2007)
linkagentstickcounterviewupdatemodes(tick-based,continuous)speedsliderfastforwardsinputboxesininterfacetabincludemultiplesourcefilesRGBcolorssliderboundsmaybereportersHubNetclienteditorMathematica-NetLogolinkarray,table,profiler,GISextensionsmodelsrunfaster(partialcompilationtoJVMbytecode)logging
Version3.1(April2006)
topologies(optionalwrappingatworldedges)randomizedagentsetordering
Version3.0(September2005)
3Dview(for2Dmodels)formattedInfotabsSystemDynamicsModelerfollow,ride,watchdrawinglayerGoGoextension
Version2.1(December2004)
![Page 50: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/50.jpg)
"headless"modeforcommandlineoperation"actionkeys"totriggerbuttonsbykeypressesmakesQuickTimemoviesofmodelslet,carefully
Version2.0.2(August2004)
extensionsandcontrollingAPIssoundextension
Version2.0(December2003)
fast,flicker-free,non-grid-basedgraphics
Version1.3(June2003)
run,runresult,map,foreach,filter,reduce
Version1.2(March2003)
computersasHubNetclients
Version1.1(July2002)
Applets
Version1.0(April2002)
firstfullrelease(afteraseriesofbetas)
![Page 51: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/51.jpg)
SystemRequirements
NetLogorunsonalmostanycurrentcomputer.
IfyouhaveanytroublewithNetLogonotworking,seeContactingUs.
ApplicationRequirements
Windows
NetLogorunsonWindows10,Windows8,Windows7andVista.NetLogo5.2.1wasthelastversiontosupportWindowsXPandWindows2000.
TheNetLogoinstallerforWindowsincludesJava8forNetLogo'sprivateuseonly.Otherprogramsonyourcomputerarenotaffected.
MacOSX
MacOSX10.8.3ornewerisrequired.(NetLogo5.1wasthelastversiontosupport10.5and10.4;NetLogo5.2.1wasthelastversiontosupport10.6and10.7)
TheNetLogoapplicationcontainsadistributionoftheJava8runtimeforNetLogo'sprivateuseonly.Otherprogramsonyourcomputerwillnotbeaffected.
Linux
NetLogoshouldworkonstandardDebian-basedandRedHat-basedLinuxdistributions.TheNetLogotarballincludesacopyoftheJava8runtime.
StartNetLogobyrunningtheprovidedNetLogoexecutable.
3DRequirements
Occasionallyanolder,lesspowerfulsystemisnotabletousethe3DvieworNetLogo3D.Tryitandsee.
Somesystemscanuse3Dbutcan'tswitchtofull-screenmode.Itdependsonthegraphicscardorcontroller.(Forexample,theATIRadeonIGP345andIntel82845probablywillnotwork.)
32-bitor64-bit?
FormostusersonLinuxorWindows,the32-bitversionofNetLogoisthesimplestwaytoaworkingNetLogoinstallation.Advanceduserswillwanttounderstandtheadvantagesof64-bitNetLogoaswellashowtodeterminewhethertheirmachinemeetstherequirements.
Theprimaryadvantageofthe64-bitversionistheabilitytoaddadditionalheapspacebychangingthe"-Xmx"JVMoption.Formoreinformation,seeHowbigcanmymodelbe.YoumayalsofindithelpfultobrowseOracle'sdocumentationontheperformancecharacteristicsofthe64-bitJVM
![Page 52: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/52.jpg)
Torun64-bitNetLogo,youmustberunning64-bitWindows.TodeterminewhetheryourversionofWindowsis64-bit,seeIsmyPCrunningthe32-bitor64-bitversionofWindowsifyou'reusingWindowsVista,orWindows7,orWhichWindowsoperatingsystemamIrunning?ifyouarerunninganyotherversionofWindows.
ForLinuxusers,theeasiestwaytodeterminewhetheryouroperatingsystemis64-bitischeckingtheoutputof
uname -m
Iftheoutputshows"x86_64"or"amd64",youshouldbeabletorunthe64-bitversion.
![Page 53: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/53.jpg)
ContactingUs
FeedbackfromusersisessentialtousindesigningandimprovingNetLogo.We'dliketohearfromyou.
Website
Ourwebsiteatccl.northwestern.eduincludesourmailingaddressandphonenumber.Italsohasinformationaboutourstaffandourvariousresearchactivities.
Feedback,questions,etc.
ForhelpusingNetLogo,trythisgroup:http://groups.yahoo.com/group/netlogo-users/.
Ifyouhavefeedback,suggestions,orquestions,[email protected].
Reportingbugs
OurpublicbugtrackerisonGitHubathttps://github.com/NetLogo/NetLogo/issues.Youcanlookheretoreportanewbug,checkifabughasalreadybeenreported,andsoon.
Whensubmittingabugreport,pleasetrytoincludeasmuchofthefollowinginformationaspossible:
Acompletedescriptionoftheproblemandhowitoccurred.TheNetLogomodelorcodeyouarehavingtroublewith.Ifpossible,attachacompletemodel.(It'sbestifyoucanreducetheamountofcodeinthemodeltotheminimumnecessarytodemonstratethebug.)Yoursysteminformation:NetLogoversion,OSversion,Javaversion,andsoon.ThisinformationisavailablefromNetLogo's"AboutNetLogo"menuitem,thenclickingtheSystemtab.Anyerrormessagesthatweredisplayed.Pleasecopyandpastetheentireerrormessageintoyouremail,ormakeascreencaptureifyouareunabletocopyandpaste.
Opensource
NetLogoisfree,opensourcesoftware.Thesourcecodeishostedathttps://github.com/NetLogo/NetLogo.Contributionsfrominterestedusersarewelcome.
FordiscussionofNetLogoAPI'sandthedevelopmentofNetLogoitself,tryhttp://groups.google.com/group/netlogo-devel.
![Page 54: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/54.jpg)
SampleModel:Party
Thisactivitygetsyouthinkingaboutcomputermodelingandhowyoucanuseit.ItalsogivesyouinsightintoNetLogoitself.Weencouragebeginninguserstostarthere.
AtaParty
Haveyoueverbeenatapartyandnoticedhowpeopleclusteringroups?Youmayhavealsonoticedthatpeopledon'tjuststayinagroup.Astheycirculate,thegroupschange.Ifyouwatchedthesechangesovertime,youmightnoticepatterns.
Forexample,insocialsettings,peoplemayexhibitdifferentbehaviorthanatworkorhome.Individualswhoareconfidentwithintheirworkenvironmentmaybecomeshyandtimidatasocialgathering.Andotherswhoarereservedatworkmaybethe"partystarter"withfriends.
Thesepatternscandependonthetypeofgathering.Insomesettings,peoplearetrainedtoorganizethemselvesintomixedgroups;forexample,partygamesorschool-likeactivities.Butinanon-structuredatmosphere,peopletendtogroupinamorerandommanner.
Isthereanytypeofpatterntothiskindofgrouping?
Let'stakeacloserlookatthisquestionbyusingthecomputertomodelhumanbehaviorataparty.NetLogo's"Party"modellooksspecificallyatthequestionofgroupingbygenderatparties:whydogroupstendtoformthataremostlymen,ormostlywomen?
Let'suseNetLogotoexplorethisquestion.
Whattodo:
1. StartNetLogo.2. Choose"ModelsLibrary"fromtheFilemenu.
3. Openthe"SocialScience"folder.4. Clickonthemodelcalled"Party".5. Pressthe"open"button.6. Pressthe"setup"button.
Intheviewofthemodel,youwillseepinkandbluegroupswithnumbers:
![Page 55: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/55.jpg)
Theselinesrepresentminglinggroupsataparty.Menareshownasblue,womenpink.Thenumbersarethesizesofthegroups.
Doallthegroupshaveaboutthesamenumberofpeople?
Doallthegroupshaveaboutthesamenumberofeachsex?
Let'ssayyouarehavingapartyandinvited150people.Youarewonderinghowpeoplewillgathertogether.Suppose10groupsformattheparty.
Howdoyouthinktheywillgroup?
Insteadofasking150ofyourclosestfriendstogatherandrandomlygroup,let'shavethecomputersimulatethissituationforus.
Whattodo:
1. Pressthe"go"button.(Pressing"go"againwillstopthemodelmanually.)2. Observethemovementofpeopleuntilthemodelstops.3. Watchtheplotstoseewhat'shappeninginanotherway.4. Usethespeedsliderifyouneedtoslowthemodeldown.
Nowhowmanypeopleareineachgroup?
Originally,youmayhavethought150peoplesplittinginto10groups,wouldresultinabout15peopleineachgroup.Fromthemodel,weseethatpeopledidnotdivideupevenlyintothe10groups.Instead,somegroupsbecameverysmall,whereasothergroupsbecameverylarge.Also,thepartychangedovertimefromallmixedgroupsofmenandwomentoallsingle-sexgroups.
Whatcouldexplainthis?
Therearelotsofpossibleanswerstothisquestionaboutwhathappensatrealparties.Thedesignerofthissimulationthoughtthatgroupsatpartiesdon'tjustformrandomly.Thegroupsaredeterminedbyhowtheindividualsatthepartybehave.Thedesignerchosetofocusonaparticularvariable,called"tolerance":
Toleranceisdefinedhereasthepercentageofpeopleoftheoppositesexanindividualis"comfortable"with.Iftheindividualisinagroupthathasahigherpercentageofpeopleoftheoppositesexthantheirtoleranceallows,thentheybecome"uncomfortable"andleavethegrouptofindanothergroup.
Forexample,ifthetolerancelevelissetat25%,thenmalesareonly"comfortable"ingroupsthatarelessthan25%female,andfemalesareonly"comfortable"ingroupsthatareless
![Page 56: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/56.jpg)
than25%male.
Asindividualsbecome"uncomfortable"andleavegroups,theymoveintonewgroups,whichmaycausesomepeopleinthatgrouptobecome"uncomfortable"inturn.Thischainreactioncontinuesuntileveryoneatthepartyis"comfortable"intheirgroup.
Notethatinthemodel,"tolerance"isnotfixed.You,theuser,canusethetolerance"slider"totrydifferenttolerancepercentagesandseewhattheoutcomeiswhenyoustartthemodeloveragain.
Howtostartover:
1. Ifthe"go"buttonispressed(black),thenthemodelisstillrunning.Pressthebuttonagaintostopit.
2. Adjustthe"tolerance"slidertoanewvaluebydraggingitsredhandle.3. Pressthe"setup"buttontoresetthemodel.4. Pressthe"go"buttontostartthemodelrunningagain.
Challenge
Asthehostoftheparty,youwouldliketoseebothmenandwomenminglingwithinthegroups.Adjustthetoleranceslideronthesideoftheviewtogetallgroupstobemixedasanendresult.
Tomakesureallgroupsof10havebothsexes,atwhatlevelshouldwesetthetolerance?
Testyourpredictionsonthemodel.
Canyouseeanyotherfactorsorvariablesthatmightaffectthemaletofemaleratiowithineachgroup?
Makepredictionsandtestyourideaswithinthismodel.
Asyouaretestingyourhypotheses,youwillnoticethatpatternsareemergingfromthedata.Forexample,ifyoukeepthenumberofpeopleatthepartyconstantbutgraduallyincreasethetolerancelevel,moremixedgroupsappear.
Howhighdoesthetolerancevaluehavetobebeforeyougetmixedgroups?
Whatpercenttolerancetendstoproducewhatpercentageofmixing?
Thinkingwithmodels
UsingNetLogotomodelasituationlikeapartyallowsyoutoexperimentwithasysteminarapidandflexiblewaythatwouldbedifficulttodointherealworld.Modelingalsogivesyoutheopportunitytoobserveasituationorcircumstancewithlessprejudice,asyoucanexaminetheunderlyingdynamicsofasituation.Youmayfindthatasyoumodelmoreandmore,manyofyourpreconceivedideasaboutvariousphenomenawillbechallenged.Forexample,asurprisingresultofthePartymodelisthateveniftoleranceisrelativelyhigh,agreatdealofseparationbetweenthesexesoccurs.
Thisisaclassicexampleofan"emergent"phenomenon,whereagrouppatternresultsfrom
![Page 57: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/57.jpg)
theinteractionofmanyindividuals.Thisideaof"emergent"phenomenacanbeappliedtoalmostanysubject.
Whatotheremergentphenomenacanyouthinkof?
ToseemoreexamplesandgainadeeperunderstandingofthisconceptandhowNetLogohelpslearnersexploreit,youmaywishtoexploreNetLogo'sModelsLibrary.Itcontainsmodelsthatdemonstratetheseideasinsystemsofallkinds.
ForalongerdiscussionofemergenceandhowNetLogohelpslearnersexploreit,see"ModelingNature'sEmergentPatternswithMulti-agentLanguages"(Wilensky,2001).
What'snext?
ThesectionoftheUserManualcalledTutorial#1:RunningModelsgoesintomoredetailabouthowtousetheothermodelsintheModelsLibrary.
Ifyouwanttolearnhowtoexplorethemodelsatadeeperlevel,Tutorial#2:CommandswillintroduceyoutotheNetLogomodelinglanguage.
Eventually,you'llbereadyforTutorial#3:Procedures.Thereyoucanlearnhowtoalterandextendexistingmodelstogivethemnewbehaviors,andyoucanstarttobuildyourownmodels.
![Page 58: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/58.jpg)
Tutorial#1:Models
IfyoureadtheSampleModel:Partysection,yougotabriefintroductiontowhatit'sliketoexploreaNetLogomodel.Thissectionwillgointomoredepthaboutthefeaturesthatareavailablewhileyou'reexploringthemodelsintheModelsLibrary.
Throughoutallofthetutorials,we'llbeaskingyoutomakepredictionsaboutwhattheeffectsofmakingchangestothemodelswillbe.Keepinmindthattheeffectsareoftensurprising.Wethinkthesesurprisesareexcitingandprovideexcellentopportunitiesforlearning.
Youmaywanttoprintoutthetutorialstomakethemeasiertorefertowhileyou'reusingNetLogo.
SampleModel:WolfSheepPredation
We'llopenoneoftheSampleModelsandexploreitindetail.Let'stryabiologymodel:WolfSheepPredation,apredator-preypopulationmodel.
OpentheModelsLibraryfromtheFilemenu.
Choose"WolfSheepPredation"fromtheBiologysectionandpress"Open".
TheInterfacetabwillfillupwithlotsofbuttons,switches,slidersandmonitors.Theseinterfaceelementsallowyoutointeractwiththemodel.Buttonsareblue;theysetup,start,andstopthemodel.Slidersandswitchesaregreen;theyaltermodelsettings.Monitorsandplotsarebeige;theydisplaydata.
Ifyou'dliketomakethewindowlargersothateverythingiseasiertosee,youcanusetheZoommenu.
Whenyoufirstopenthemodel,youwillnoticethatthe"view"(thegraphicaldisplayoftheagentsinthemodel)isempty(allblack).Tobeginthemodel,youwillfirstneedtosetitup.
Pressthe"setup"button.
Whatdoyouseeappearintheview?
![Page 59: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/59.jpg)
Pressthe"go"buttontostartthesimulation.
Asthemodelisrunning,whatishappeningtothewolfandsheeppopulations?
Pressthe"go"buttontostopthemodel.
ControllingtheModel:Buttons
Whenabuttonispressed,themodelrespondswithanaction.Abuttoncanbea"once"button,ora"forever"button.Youcantellthedifferencebetweenthesetwotypesofbuttonsbyasymbolonthefaceofthebutton.Foreverbuttonshavetwoarrowsinthebottomrightcorners,likethis:
Oncebuttonsdon'thavethearrows,likethis:
Oncebuttonsdooneactionandthenstop.Whentheactionisfinished,thebuttonpopsbackup.
Foreverbuttonsdoanactionoverandoveragain.Whenyouwanttheactiontostop,pressthebuttonagain.Itwillfinishthecurrentaction,thenpopbackup.
Mostmodels,includingWolfSheepPredation,haveaoncebuttoncalled"setup"andaforeverbuttoncalled"go".Manymodelsalsohaveaoncebuttoncalled"goonce"or"steponce"whichislike"go"exceptthatitadvancesthemodelbyonetick(timestep)insteadofoverandover.Usingaoncebuttonlikethisletsyouwatchtheprogressofthemodelmoreclosely.
Stoppingaforeverbuttonisthenormalwaytopauseorstopamodel.Afterpausingyoucanmakeitresumebypressingthebuttonagain.(Youcanalsostopamodelwiththe"Halt"itemontheToolsmenu,butyoushouldonlydothisifthemodelisstuckforsomereason.Using"Halt"mayinterruptthemodelinthemiddleofanaction,andastheresultthemodelcouldgetconfused.)
Ifyoulike,experimentwiththe"setup"and"go"buttonsintheWolfSheepPredationmodel.
Doyouevergetdifferentresultsifyourunthemodelseveraltimeswiththesamesettings?
Controllingspeed:SpeedSlider
Thespeedsliderallowsyoutocontrolthespeedofamodel,thatis,thespeedatwhichturtlesmove,patcheschangecolor,andsoon.
![Page 60: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/60.jpg)
Whenyoumovetheslidertotheleftthemodelslowsdownsotherearelongerpausesbetweeneachtick(timestep).Thatmakesiteasiertoseewhatishappening.Youmightevenslowthemodeldownsofarastoseeexactlywhatasingleturtleisdoing.
Whenyoumovethespeedslidertotherightthemodelspeedsup.NetLogowillstartskippingframes,thatis,itwon'tupdatetheviewattheendofeverytick,onlysometicks.Updatingtakestime,sofewerviewupdatesmeansthemodelprogressesfaster.
Notethatifyoupushthespeedsliderwelltotheright,theviewmayupdatesoinfrequentlythatthemodelappearstohavesloweddown.Ithasn't,asyoucanseebywatchingthetickcounterraceahead.Onlythefrequencyofviewupdateshaslessened.
AdjustingSettings:SlidersandSwitches
Amodel'ssettingsletyouexploredifferentscenariosorhypotheses.Alteringthesettingsandthenrunningthemodeltoseehowitreactscangiveyouadeeperunderstandingofthephenomenabeingmodeled.
Switchesandslidersgiveyouaccesstoamodel'ssettings.HerearetheswitchesandslidersinWolfSheepPredation:
Let'sexperimentwiththeireffectonthebehaviorofthemodel.
OpenWolfSheepPredationifit'snotopenalready.Press"setup"and"go"andletthemodelrunforabout100ticks.(Thetickcountisshownabovetheview.)Stopthemodelbypressingthe"go"button.
Whathappenedtothesheepovertime?
Let'stakealookandseewhatwouldhappentothesheepifwechangeasetting.
Turnthe"grass?"switchon.Press"setup"and"go"andletthemodelrunforasimilaramountoftimeasbefore.
![Page 61: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/61.jpg)
Whatdidtheswitchdo?Wastheoutcomethesameasyourpreviousrun?
Turningthe"grass?"switchonaffectedtheoutcomeofthemodel.Withtheswitchoff,theamountofgrassavailablealwaysstayedthesame.Thisisnotarealisticlookatthepredator-preyrelationship;sobysettingandturningonagrassregrowthrate,wewereabletomodelallthreefactors:sheep,wolfandgrasspopulations.
Anothertypeofsettingiscalledaslider.
Besidesswitches,amodelmayalsohavesliders.Whileaswitchhasonlytwovalues,onandoff,asliderhasawholerangeofnumericvalues.Forexample,the"initial-number-sheep"sliderhasaminimumvalueof0andamaximumvalueof250.Themodelcouldrunwith0sheeporitcouldrunwith250sheep,oranywhereinbetween.Trythisoutandseewhathappens.Asyoumovethemarkerfromtheminimumtothemaximumvalue,thenumberontherightsideofthesliderchanges;thisisthenumbertheslideriscurrentlysetto.
Let'sinvestigateWolfSheepPredation'ssliders.
ChangefromtheInterfacetotheInfotabtolearnwhateachofthismodels'slidersrepresents.
TheInfotaboffersguidanceandinsightintothemodel.Withinthistabyouwillfindanexplanationofthemodel,suggestionsonthingstotry,andotherinformation.YoumaywanttoreadtheInfotabbeforerunningamodel,oryoumightwanttojuststartexperimenting,thenlookattheInfotablater.
Whatwouldhappentothesheeppopulationifthereweremoresheepandlesswolvesinitially?
Turnthe"grass?"switchoff.Setthe"initial-number-sheep"sliderto100.Setthe"initial-number-wolves"sliderto20.Press"setup"andthen"go".Letthemodelrunforabout100ticks.
Tryrunningthemodelseveraltimeswiththesesettings.
Whathappenedtothesheeppopulation?
Didthisoutcomesurpriseyou?Whatotherslidersorswitchescanbeadjustedtohelpoutthesheeppopulation?
Set"initial-number-sheep"to80and"initial-number-wolves"to50.(Thisisclosetohowtheywerewhenyoufirstopenedthemodel.)Set"sheep-reproduce"to10.0%.Press"setup"andthen"go".Letthemodelrunforabout100timeticks.
Whathappenedtothewolvesinthisrun?
![Page 62: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/62.jpg)
Whenyouopenamodel,alltheslidersandswitchesareonadefaultsetting.Ifyouopenanewmodelorexittheprogram,yourchangedsettingswillnotbesaved,unlessyouchoosetosavethem.
(Note:inadditiontoslidersandswitches,somemodelshavechoosersandinputboxes.TheWolfSheepPredationdoesn'thaveanyofthese,though.)
GatheringInformation:PlotsandMonitors
Theviewletsyouseewhat'sgoingoninamodel.NetLogoalsoprovideshasotherwaysofgivingyouinformationaboutmodelrun,suchasplotsandmonitors.
Plots
TheplotinWolfSheepPredationcontainsthreelines:sheep,wolves,andgrass/4.(Thegrasscountisdividedbyfoursoitdoesn'tmaketheplottootall.)Thelinesshowwhat'shappeninginthemodelovertime.Theplotlegendshowswhateachlineindicates.Inthiscase,it'sthepopulationcounts.
Whenaplotgetsclosetobecomingfilledup,thehorizontalaxisiscompressedandallofthedatafrombeforegetssqueezedintoasmallerspace.Inthisway,moreroomismadefortheplottogrow.
Ifyouwanttosavethedatafromaplottovieworanalyzeitinanotherapplication,usethe"ExportPlot"itemontheFilemenu.ItsavestheplotdatainaformatthatcanbyreadbackbyspreadsheetanddatabaseprogramssuchasExcel.Youcanalsoexportaplotbyright-clickingitandchoosing"Export..."fromthepopupmenu.
Monitors
Monitorsareanothermeansofdisplayinginformationfromamodel.HerearethemonitorsinWolfSheepPredation:
Themonitorsshowusthepopulationofsheepandwolves,andtheamountofgrass.(Remember,theamountofgrassisdividedbyfourtokeeptheplotfromgettingtootall.)
Thenumbersdisplayedinthemonitorschangeasthemodelruns,whereastheplotsshowyoudatafromthewholecourseofthemodelrun.
ControllingtheView
IntheInterfacetab,you'llseeatoolbarofcontrols.Someofthesecontrolaspectsoftheview.
Let'sexperimentwiththeeffectofthesecontrols.
Press"setup"andthen"go"tostartthemodelrunning.Asthemodelruns,movethespeedslidertotheleft.
Whathappens?
![Page 63: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/63.jpg)
Thissliderishelpfulifamodelisrunningtoofastforyoutoseewhat'sgoingonindetail.
Movethespeedslidertothemiddle.Trymovingthespeedslidertotheright.Nowtrycheckinganduncheckingthe"viewupdates"checkbox.
Whathappens?
Fastforwardingthemodelandturningoffviewupdatesareusefulifyou'reimpatientandwantamodeltorunfaster.Fastforwarding(movingthespeedslidertotheright)dropsviewupdatessothemodelcanrunfast,sinceupdatingtheviewtakestimethatcouldbeusedforrunningthemodelitself.
Whenviewupdatesareoffcompletely,themodelcontinuestoruninthebackground,andplotsandmonitorsstillupdate.Butifyouwanttoseewhat'shappening,youneedtoturnviewupdatesbackonbyrecheckingthebox.Manymodelsrunmuchfasterwhenviewupdatesareoff.Forothers,itmakeslittledifference.
Thesizeoftheviewisdeterminedbyfiveseparatesettings:min-pxcor,max-pxcor,min-pycor,max-pycor,andpatchsize.Let'stakealookatwhathappenswhenwechangethesizeoftheviewinthe"WolfSheepPredation"model.
Therearemoremodelsettingsthanthere'sroomforinthetoolbar.The"Settings..."buttonletsyougettotherestofthesettings.
Pressthe"Settings..."buttoninthetoolbar.
Adialogwillopencontainingallthesettingsfortheview:
![Page 64: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/64.jpg)
Whatarethecurrentsettingsformin-pxcor,max-pxcor,min-pycor,max-pycor,andpatchsize?
Press"cancel"tomakethiswindowgoawaywithoutchangingthesettings.Placeyourmousepointernextto,butstilloutsideof,theview.
Youwillnoticethatthepointerturnsintoacrosshair.
Holddownthemousebuttonanddragthecrosshairovertheview.
Theviewisnowselected,whichyouknowbecauseitisnowsurroundedbyagrayborder.
Dragoneofthesquareblack"handles".Thehandlesarefoundontheedgesandatthecornersoftheview.UnselecttheviewbyclickinganywhereinthewhitebackgroundoftheInterfacetab.Pressthe"Settings..."buttonagainandlookatthesettings.
Whatnumberschanged?
Whatnumbersdidn'tchange?
![Page 65: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/65.jpg)
TheNetLogoworldisatwodimensionalgridof"patches".Patchesaretheindividualsquaresinthegrid.InWolfSheepPredation,whenthe"grass?"switchisontheindividualpatchesareeasilyseen,becausesomearegreen,othersbrown.
Thinkofthepatchesasbeinglikesquaretilesinaroomwithatilefloor.Bydefault,exactlyinthemiddleoftheroomisatilelabeled(0,0);meaningthatiftheroomwasdividedinhalfonewayandthentheotherway,thesetwodividinglineswouldintersectonthistile.Wenowhaveacoordinatesystemthatwillhelpuslocateobjectswithintheroom:
Howmanytilesawayisthe(0,0)tilefromtherightsideoftheroom?
Howmanytilesawayisthe(0,0)tilefromtheleftsideoftheroom?
InNetLogo,thenumberoftilesfromrighttoleftiscalledworld-width.Andthenumberoftilesfromtoptobottomisworld-height.Thesenumbersaredefinedbytop,bottom,leftandrightboundaries.
![Page 66: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/66.jpg)
Inthesediagrams,max-pxcoris3,min-pxcoris-3,max-pycoris2andmin-pycoris-2.
Whenyouchangethepatchsize,thenumberofpatches(tiles)doesn'tchange,thepatchesonlygetlargerorsmallerintheview.
Let'slookattheeffectofchangingtheminimumandmaximumcoordinatesintheworld.
UsingtheSettingsdialogthatisstillopen,changemax-pxcorto30andmax-pycorvalueto10.Noticethatmin-pxcorandmin-pycorchangetoo.That'sbecausebydefaulttheorigin(0,0)isinthecenteroftheworld.
Whathappenedtotheshapeoftheview?
Pressthe"setup"button.
Nowyoucanseethenewpatchesyouhavecreated.
Edittheviewbypressingthe"Settings..."buttonagain.Changethepatchsizeto20andpress"OK".
Whathappenedtothesizeoftheview?Diditsshapechange?
Editingtheviewalsoletsyouchangeothersettings.Feelfreetoexperimentwiththese.
OnceyouaredoneexploringtheWolfSheepPredationmodel,youmaywanttotakesometimejusttoexploresomeoftheothermodelsavailableintheModelsLibrary.
ModelsLibrary
Thelibrarycontainsfoursections:SampleModels,CurricularModels,CodeExamples,andHubNetActivities.
SampleModels
TheSampleModelssectionisorganizedbysubjectareaandcurrentlycontainsmorethan200models.Wearecontinuouslyworkingonaddingnewmodelstoit,socomevisitthissectionatalaterdatetoviewthenewadditionstothelibrary.
SomeofthefoldersinSampleModelshavefoldersinsidethemlabeled"(unverified)".Thesemodelsarecompleteandfunctional,butarestillintheprocessofbeingreviewedforcontent,accuracy,andqualityofcode.
CurricularModels
ThesearemodelsdesignedtobeusedinschoolsinthecontextofcurriculadevelopedbytheCCLatNorthwesternUniversity.SomeofthesearemodelsarealsolistedunderSampleModels;othersareuniquetothissection.SeetheInfotabsofthemodelsformoreinformationonthecurriculatheygowith.
CodeExamples
![Page 67: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/67.jpg)
ThesearesimpledemonstrationsofparticularfeaturesofNetLogo.They'llbeusefultoyoulaterwhenyou'reextendingexistingmodelsorbuildingnewones.Forexample,ifyouwantedtoaddahistogramtoyourmodel,you'dlookat"HistogramExample"tofindouthow.
HubNetActivities
Thissectioncontainsparticipatorysimulationsforusewithgroups.FormoreinformationaboutHubNet,seetheHubNetGuide.
What'sNext?
Ifyouwanttolearnhowtoexploremodelsatadeeperlevel,Tutorial#2:CommandswillintroduceyoutotheNetLogomodelinglanguage.
InTutorial#3:Proceduresyoucanlearnhowtoalterandextendexistingmodelsandbuildnewones.
![Page 68: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/68.jpg)
Tutorial#2:Commands
Sofaryou'vesuccessfullynavigatedyourwaythroughopeningandrunningmodels,pressingbuttons,changingslidersandswitches,andgatheringinformationfromamodelusingplotsandmonitors.
Inthissection,thefocuswillstarttoshiftfromobservingmodelstomanipulatingmodels.Youwillstarttoseetheinnerworkingsofthemodelsandbeabletochangehowtheylook.
SampleModel:TrafficBasic
OpentheModelsLibrary(fromtheFilemenu).OpenTrafficBasic,foundinthe"SocialScience"section.Runthemodelforawhiletogetafeelforit.ConsulttheInfotabforanyquestionsyoumayhave.
Inthismodel,youwillnoticeoneredcarinastreamofbluecars.Thestreamofcarsareallmovinginthesamedirection.Everysooftenthey"pileup"andstopmoving.Thisismodelinghowtrafficjamscanformwithoutaspecificcauselikeanaccident.
Youmayalterthesettingsandobserveafewrunstogetafullerunderstandingofthemodel.
AsyouareusingtheTrafficBasicmodel,haveyounoticedanyadditionsyouwouldliketomaketothemodel?
LookingattheTrafficBasicmodel,youmaynoticetheenvironmentisfairlysimple;ablackbackgroundwithawhitestreetandnumberofbluecarsandoneredcar.Changesthatcouldbemadetothemodelinclude:changingthecolorandshapeofthecars,addingahouseorstreetlight,creatingastoplight,orevencreatinganotherlaneoftraffic.Someofthesesuggestedchangesarevisual,toenhancethelookofthemodel,whileothersaremorebehavioral.Wewillbefocusingmoreonthesimplerorcosmeticchangesthroughoutmostofthistutorial.(Tutorial#3willgointogreaterdetailaboutbehavioralchanges,whichrequirechangingtheCodetab.)
TomakethesesimplechangeswewillbeusingtheCommandCenter.
CommandCenter
TheCommandCenterisfoundintheInterfacetab.Itallowsyoutoentercommandsordirectionstoamodel.CommandsareinstructionsyoucangivetoNetLogo'sagents:turtles,patches,links,andtheobserver.
InTrafficBasic:
Pressthe"setup"button.LocatetheCommandCenter.
![Page 69: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/69.jpg)
ClickthemouseinthewhiteboxatthebottomoftheCommandCenter.Typethetextshownhere:
Pressthereturnkey.
WhathappenedtotheView?
YoumayhavenoticedthebackgroundoftheViewhasturnedallyellowandthestreethasdisappeared.
Whydidn'tthecarsturnyellowtoo?
Lookingbackatthecommandthatwaswritten,weaskedonlythepatchestochangetheircolor.Inthismodel,thecarsarerepresentedbyadifferentkindofagent,called"turtles".Therefore,thecarsdidnotreceivetheseinstructionsandthusdidnotchange.
WhathappenedintheCommandCenter?
YoumayhavenoticedthatthecommandyoujusttypedisnowdisplayedintheCommandCenterasshownbelow:
TypeinthebottomoftheCommandCenterthetextshownbelow:
Wastheresultwhatyouexpected?
Theviewshouldhaveayellowbackgroundwithalineofbrowncarsinthemiddle:
![Page 70: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/70.jpg)
TheNetLogoworldisatwodimensionalworldthatismadeupofturtles,patches,links,andanobserver.Thepatchesarethegroundoverwhichtheturtlesmove.Linksareconnectionsbetweenturtles.Andtheobserverisabeingthatoverseeseverythingthatisgoingon.(Formorespecifics,refertotheNetLogoProgrammingGuide.)
IntheCommandCenteryoucangivecommandstoanyofthesetypesofagents.Youchoosewhichtypetotalktobyusingthepopupmenulocatedinthebottomleftcorner.Youcanalsousethetabkeyonyourkeyboardtocyclethroughthedifferenttypes.
IntheCommandCenter,clickonthe"observer>"inthebottomleftcorner:
Choose"turtles"fromthepopupmenu.Typeset color pinkandpressreturn.Pressthetabkeyuntilyousee"patches>"inthebottomleftcorner.Typeset pcolor whiteandpressreturn.
WhatdoestheViewlooklikenow?
Doyounoticeanydifferencesbetweenthesetwocommandsandtheobservercommandsfromearlier?
Theobserveroverseestheworldandthereforecangiveacommandtothepatchesorturtlesusingask.Likeinthefirstexample(observer>ask patches [set pcolor yellow]),theobserverhastoaskthepatchestosettheirpcolortoyellow.Butwhenacommandisdirectlygiventoagroupofagentslikeinthesecondexample(patches>set pcolor white),youonlyhavetogivethecommanditself.
Press"setup".
Whathappened?
WhydidtheViewrevertbacktotheoldversion,withtheblackbackgroundandwhiteroad?Uponpressingthe"setup"button,themodelwillreconfigureitselfbacktothesettingsoutlinedintheCodetab.TheCommandCenterdoesn'tpermanentlychangethemodel.ItallowsyoutomanipulatetheNetLogoworlddirectlytofurtheranswerthose"Whatif"questionsthatpop
![Page 71: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/71.jpg)
upasyouareinvestigatingthemodels.(TheCodetabisexplainedinthenexttutorial,andintheProgrammingGuide.)
NowthatwehavefamiliarizedourselveswiththeCommandCenter,let'slookatsomemoredetailsabouthowcolorsworkinNetLogo.
Workingwithcolors
Youmayhavenoticedintheprevioussectionthatweusedtwodifferentwordsforchangingcolor:colorandpcolor.
Whatisthedifferencebetweencolorandpcolor?
Choose"turtles"fromthepopupmenuintheCommandCenter(orusethetabkey).Typeset color blueandpressreturn.
Whathappenedtothecars?
Thinkaboutwhatyoudidtomakethecarsturnblue,andtrytomakethepatchesturnred.
Ifyoutrytoaskthepatchestoset color red,anerrormessageoccurs:
Typeset pcolor redinsteadandpressreturn.
Wecallcolorandpcolor"variables".Somecommandsandvariablesarespecifictoturtlesandsomearespecifictopatches.Forexample,thecolorvariableisaturtlevariable,whilethepcolorvariableisapatchvariable.
Goaheadandpracticealteringthecolorsoftheturtlesandpatchesusingthesetcommandandthesetwovariables.
Tobeabletomakemorechangestothecolorsofturtlesandpatches,orshallwesaycarsandbackgrounds,weneedtogainalittleinsightintohowNetLogodealswithcolors.
InNetLogo,colorshaveanumericvalue.Inalloftheexerciseswehavebeenusingthenameofthecolor.ThisisbecauseNetLogorecognizes16differentcolornames.ThisdoesnotmeanthatNetLogoonlyrecognizes16colors.Therearemanyshadesinbetweenthesecolorsthatcanbeusedtoo.Here'sachartthatshowsthewholeNetLogocolorspace:
![Page 72: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/72.jpg)
Togetanintermediateshade,yourefertoitbyanumberinstead,orbyaddingorsubtractinganumberfromaname.Forexample,whenyoutypeset color red,thisdoesthesamethingasifyouhadtypedset color 15.Andyoucangetalighterordarkerversionofthesamecolorbyusinganumberthatisalittlelargeroralittlesmaller,asfollows.
Choose"patches"fromthepopupmenuintheCommandCenter(orusethetabkey).Typeset pcolor red - 2(Thespacingaroundthe"-"isimportant.)
Bysubtractingfromred,youmakeitdarker.
Typeset pcolor red + 2
Byaddingtored,youmakeitlighter.
Youcanusethistechniqueonanyofthecolorslistedinthechart.
AgentMonitorsandAgentCommanders
Inthepreviousactivity,weusedthesetcommandtochangethecolorsofallthecars.Butifyourecall,theoriginalmodelcontainedoneredcaramongstagroupofbluecars.Let'slookathowtochangeonlyonecar'scolor.
Press"setup"togettheredcartoreappear.Right-clickontheredcar.
![Page 73: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/73.jpg)
Ifthereisanotherturtleclosetotheredturtleyou'llseemorethanoneturtlelistedatthebottomofthemenu.Moveyourmouseovertheturtleselections,noticewhenyourmousehighlightsaturtlemenuitemthatturtleishighlightedintheview.Select"inspectturtle"fromthesub-menufortheredturtle.
Aturtlemonitorforthatcarwillappear:
Themini-viewatthetopoftheagentmonitorwillalwaysstaycenteredonthisagent.Youcanzoomtheviewinandoutusingthesliderbelowtheviewandyoucanwatchthisturtleinthemainviewbypressingthe"watch-me"button.
Takingacloserlookatthisturtlemonitor,wecanseeallofthevariablesthatbelongtotheredcar.Avariableisalocationthatholdsavalue.
Let'stakeacloserlookattheturtlemonitor:
![Page 74: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/74.jpg)
Whatisthisturtle'swhonumber?
Whatcoloristhisturtle?
Whatshapeisthisturtle?
Thisturtlemonitorisshowingaturtlewhothathasawhonumberof0,acolorof15(red--seechartabove),andtheshapeofacar.
Therearetwootherwaystoopenaturtlemonitorbesidesright-clicking.Onewayistochoose"TurtleMonitor"fromtheToolsmenu,thentypethewhonumberoftheturtleyouwanttoinspectintothe"who"fieldandpressreturn.Theotherwayistotypeinspect turtle0(orotherwhonumber)intotheCommandCenter.
Youcloseaturtlemonitorbyclickingthecloseboxintheupperlefthandcorner(Mac)orupperrighthandcorner(otheroperatingsystems).
NowthatweknowmoreaboutAgentMonitors,wehavethreewaystochangeanindividualturtle'scolor.
OnewayistousetheboxcalledanAgentCommanderfoundatthebottomofanAgentMonitor.Youtypecommandshere,justlikeintheCommandCenter,butthecommandsyoutypehereareonlydonebythisparticularturtle.
IntheAgentCommanderoftheTurtleMonitorforturtle0,typeset colorpink.
WhathappensintheView?
DidanythingchangeintheTurtleMonitor?
Asecondwaytochangeoneturtle'scoloristogodirectlytothecolorvariableintheTurtleMonitorandchangethevalue.
Selectthetexttotherightof"color"intheTurtleMonitor.Typeinanewcolorsuchasgreen + 2.
Whathappened?
Thethirdwaytochangeanindividualturtle'sorpatch'scoloristousetheobserver.Since,theobserveroverseestheNetLogoworld,itcangivecommandsthataffectindividualturtles,aswellasgroupsofturtles.
IntheCommandCenter,select"observer"fromthepopupmenu(orusethetabkey).Typeask turtle 0 [set color blue]andpressreturn.
![Page 75: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/75.jpg)
Whathappens?
JustasthereareTurtleMonitors,therearealsoPatchMonitors.PatchmonitorsworkverysimilarlytoTurtleMonitors.
Canyoumakeapatchmonitoranduseittochangethecolorofasinglepatch?
Ifyoutrytohavetheobserverask patch 0 [set pcolor blue],you'llgetanerrormessage:
Toaskanindividualturtletodosomething,weuseitswhonumber.Butpatchesdon'thavewhonumbers,thereforeweneedtorefertothemsomeotherway.
Remember,patchesarearrangedonacoordinatesystem.Twonumbersareneededtoplotapointonagraph:anx-axisvalueanday-axisvalue.Patchlocationsaredesignatedinthesamewayasplottingapoint.
Openapatchmonitorforanypatch.
![Page 76: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/76.jpg)
Themonitorshowsthatforthepatchinthepicture,itspxcorvariableis-19anditspycorvariableis0.Ifwegobacktotheanalogyofthecoordinateplaneandwantedtoplotthispoint,thepointwouldbefoundonthexaxisleftoftheorigin,wherex=-19andy=0.
Totellthisparticularpatchtochangecolor:
Inthebottomofthepatchmonitor,enterset pcolor blueandpressreturn.
Typingacommandinaturtleorpatchmonitoraddressesonlythatturtleorpatch.
YoucanalsotalktoasinglepatchfromtheCommandCenter:
IntheCommandCenter,enterask patch -19 0 [set pcolor green]andpressreturn.
What'sNext?
Atthispoint,youmaywanttotakesometimetotryoutthetechniquesyou'velearnedonsomeoftheothermodelsintheModelsLibrary.
InTutorial#3:Proceduresyoucanlearnhowtoalterandextendexistingmodelsandbuildyourownmodels.
![Page 77: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/77.jpg)
Tutorial#3:Procedures
Thistutorialleadsyouthroughtheprocessofbuildingacompletemodel,builtupinstages,witheverystepexplainedalongtheway.
Agentsandprocedures
InTutorial#2,youlearnedhowtousethecommandcenterandagentmonitorstoinspectandmodifyagentsandmakethemdothings.Nowyou'rereadytolearnabouttherealheartofaNetLogomodel:theCodetab.
You'veseenthatagentsinNetLogoaredividedintopatches,turtles,links,andtheobserver.Patchesarestationaryandarrangedinagrid.Turtlesmoveoverthatgrid.Linksconnecttwoturtles.Theobserveroverseeseverythingthat'sgoingonanddoeswhatevertheturtles,patchesandlinkscan'tdoforthemselves.
AllfourtypesofagentscanrunNetLogocommands.Allfourcanalsorun"procedures".AprocedurecombinesaseriesofNetLogocommandsintoasinglenewcommandthatyoudefine.
Youwillnowlearntowriteproceduresthatmaketurtlesmove,eat,reproduce,anddie.Youwillalsolearnhowtomakemonitors,sliders,andplots.Themodelwe'llbuildisasimpleecosystemmodelnotunlikeWolfSheepPredationfromTutorial#1.
Makingthesetupbutton
Tostartanewmodel,select"New"fromtheFilemenu.Thenbeginbycreatingasetupbutton:
Clickthe"Add"iconinthetoolbaratthetopoftheInterfacetab.OnthemenunexttoAdd,selectButton(ifitisn'talreadyselected).ClickwhereveryouwantthebuttontoappearintheemptywhiteareaoftheInterfacetab.Adialogboxforeditingthebuttonopens.Typesetupintheboxlabeled"Commands".PresstheOKbuttonwhenyou'redone;thedialogboxcloses.
Nowyouhaveasetupbutton.Pressingthebuttonrunsaprocedurecalled"setup".AprocedureisasequenceofNetLogocommandsthatweassignanewname.We'lldefinethatproceduresoon,butwehaven'tyet.Thebuttonreferstoaprocedurethatdoesn'texist,sothebuttonturnsred:
Ifyouwanttoseetheactualerrormessage,clickthebutton.
Nowwe'llcreatethe"setup"procedure,sotheerrormessagewillgoaway:
SwitchtotheCodetab.Typethefollowing:
to setup clear-all create-turtles 100 [ setxy random-xcor random-ycor ] reset-ticksend
Whenyou'redone,theCodetablookslikethis:
![Page 78: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/78.jpg)
Notethatsomelinesareindented.Mostpeoplefindithelpfultoindenttheircode.Itisn'tmandatory,butitmakesthecodeeasiertoreadandchange.
Yourprocedurebeginswithtoandendswithend.Everyprocedurebeginsandendswiththesewords.
Let'slookatwhatyoutypedinandseewhateachlineofyourproceduredoes:
to setupbeginsdefiningaprocedurenamed"setup".clear-allresetstheworldtoaninitial,emptystate.Allthepatchesturnblackandanyturtlesyoumighthavecreateddisappear.Basically,itwipestheslatecleanforanewmodelrun.create-turtles 100creates100turtles.Theystartoutstandingattheorigin,thatis,thecenterofpatch0,0.Aftercreate-turtleswecanputcommandsforthenewturtlestorun,enclosedbysquarebrackets.setxy random-xcor random-ycorisacommandusing"reporters".Areporter,asopposedtoacommand,reportsaresult.Firsteachturtlerunsthereporterrandom-xcorwhichwillreportarandomnumberfromtheallowablerangeofturtlecoordinatesalongtheXaxis.Theneachturtlerunsthereporterrandom-ycor,samefortheYaxis.Finallyeachturtlerunsthesetxycommandwiththosetwonumbersasinputs.Thatmakestheturtlemovetothepointwiththosecoordinates.reset-ticksstartsthetickcounter,nowthatsetupisotherwisecomplete.endcompletesthedefinitionofthe"setup"procedure.
Whenyou'redonetyping,switchtotheInterfacetabandpressthesetupbuttonyoumadebefore.Youwillseetheturtlesscatteredaroundtheworld:
Presssetupacouplemoretimes,andseehowthearrangementofturtlesisdifferenteachtime.Notethatsometurtlesmayberightontopofeachother.
Thinkabitaboutwhatyouneededtodotomakethishappen.Youneededtomakeabuttonintheinterfaceandmakeaprocedurethatthebuttonuses.Thebuttononlyworkedonceyoucompletedbothoftheseseparatesteps.Intheremainderofthistutorial,youwilloftenhavetocompletetwoormoresimilarstepstoaddanotherfeaturetothemodel.Ifsomethingdoesn'tappeartoworkafteryoucompletedwhatyouthoughtisthefinalstepforthatnewfeature,continuetoreadaheadtoseeifthereisstillmoretodo.Afterreadingaheadforacoupleofparagraphs,youshouldthengobackoverthedirectionstoseeifthereisanystepyoumighthavemissed.
![Page 79: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/79.jpg)
Switchingtotick-basedviewupdates
Nowthatwe'reusingthetickcounter(withreset-ticks),weshouldtellNetLogothatitonlyneedstoupdatetheviewoncepertick,insteadofcontinuouslyupdatingit.
Findtheviewupdatesmenu.It'sabovetheviewandbydefaultsays"continuous".Choose"onticks"instead.
Thismakesyourmodelrunfasterandensuresaconsistentappearance(sincetheupdateswillhappenatconsistenttimes).SeetheProgrammingGuideforafullerdiscussionofviewupdates.
Makingthegobutton
Nowmakeabuttoncalled"go".Followthesamestepsyouusedtomakethesetupbutton,except:
ForCommandsentergoinsteadofsetup.Checkthe"Forever"checkboxintheeditdialog.Checkthe"Disableuntilticksstart"checkboxtoo.
The"Forever"checkboxmakesthebuttonstaydownoncepressed,soitscommandsrunoverandoveragain,notjustonce.
The"Disableuntilticksstart"preventsyoufrompressinggobeforesetup.
ThenaddagoproceduretotheCodetab:
to go move-turtles tickend
tickisaprimitivethatadvancesthetickcounterbyonetick.
Butwhatismove-turtles?Isitaprimitive(inotherwords,built-intoNetLogo)?No,it'sanotherprocedurethatyou'reabouttoadd.Sofar,youhaveintroducedtwoproceduresthatyouaddedyourself:setupandgo.
Addthemove-turtlesprocedureafterthegoprocedure:
to go
![Page 80: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/80.jpg)
move-turtles tickend
to move-turtles ask turtles [ right random 360 forward 1 ]end
Notetherearenospacesaroundthehypheninmove-turtles.InTutorial#2weusedred - 2,withspaces,inordertosubtracttwonumbers,butherewewantmove-turtles,withoutspaces.The"-"combines"move"and"turtles"intoasinglename.
Hereiswhateachcommandinthemove-turtlesproceduredoes:
ask turtles [ ... ]saysthateachturtleshouldrunthecommandsinthebrackets.right random 360isanothercommandthatusesareporter.First,eachturtlepicksarandomwholenumberbetween0and359.(randomdoesn'tincludethenumberyougiveitasapossibleresult.)Thentheturtleturnsrightthisnumberofdegrees.forward 1makestheturtlemoveforwardonestep.
Whycouldn'twehavejustwrittenallofthesecommandsingoinsteadofinaseparateprocedure?Wecouldhave,butduringthecourseofbuildingyourproject,it'slikelythatyou'lladdmanyotherparts.We'dliketokeepgoassimpleaspossible,sothatitiseasytounderstand.Eventually,itwillincludemanyotherthingsyouwanttohavehappenasthemodelruns,suchascalculatingsomethingorplottingtheresults.Eachofthesethingstodowillhaveitsownprocedureandeachprocedurewillhaveitsownuniquename.
The'go'buttonyoumadeintheInterfacetabisaforeverbutton,meaningthatitwillcontinuallyrunitscommandsuntilyoushutitoff(byclickingonitagain).Afteryouhavepressed'setup'once,tocreatetheturtles,pressthe'go'button.Watchwhathappens.Turnitoff,andyou'llseethatalltheturtlesstopintheirtracks.
Notethatifaturtlemovesofftheedgeoftheworld,it"wraps",thatis,itappearsontheotherside.(Thisisthedefaultbehavior.Itcanbechanged;seetheTopologysectionoftheProgrammingGuideformoreinformation.)
Experimentingwithcommands
Wesuggestyoustartexperimentingwithotherturtlecommands.
TypecommandsintotheCommandCenter(liketurtles> set color red),oraddcommandstosetup,go,ormove-turtles.
NotethatwhenyouentercommandsintheCommandCenter,youmustchooseturtles>,patches>,links>,orobserver>inthepopupmenuontheleft,dependingonwhichagentsaregoingtorunthecommands.It'sjustlikeusingask turtlesorask patches,butsavestyping.Youcanalsousethetabkeytoswitchagenttypes,whichyoumightfindmoreconvenientthanusingthemenu.
Youmighttrytypingturtles>pen-downintotheCommandCenterandthenpressingthegobutton.
Also,insidethemove-turtlesprocedureyoucantrychangingright random 360toright random 45.
Playaround.It'seasyandtheresultsareimmediateandvisible--oneofNetLogo'smanystrengths.
Whenyoufeelyou'vedoneenoughexperimentingfornow,you'rereadytocontinueimprovingthemodelyouarebuilding.
Patchesandvariables
Nowwe'vegot100turtlesaimlesslymovingaround,completelyunawareofanythingelsearoundthem.Let'smakethingsalittlemoreinterestingbygivingtheseturtlesanicebackgroundagainstwhichtomove.
Gobacktothesetupprocedure.Wecanrewriteitasfollows:
to setup clear-all setup-patches setup-turtles reset-ticksend
Thenewdefinitionofsetupreferstotwonewprocedures.Todefinesetup-patches,addthis:
to setup-patches ask patches [ set pcolor green ]end
Thesetup-patchesproceduresetsthecolorofeverypatchtogreentostartwith.(Aturtle'scolorvariableiscolor;apatch'sispcolor.)
Theonlypartremaininginournew'setup'thatisstillundefinedissetup-turtles.
Addthisproceduretoo:
to setup-turtles create-turtles 100 ask turtles [ setxy random-xcor random-ycor ]
![Page 81: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/81.jpg)
end
Didyounoticethatthenewsetup-turtlesprocedurehasmostofthesamecommandsastheoldsetupprocedure?
SwitchbacktotheInterfacetab.Pressthesetupbutton.
Voila!AlushNetLogolandscapecompletewithturtlesandgreenpatchesappears:
Afterseeingthenewsetupprocedureworkafewtimes,youmayfindithelpfultoreadthroughtheproceduredefinitionsagain.
Turtlevariables
Sowehavesometurtlesrunningaroundonalandscape,buttheyaren'tdoinganythingwithit.Let'saddsomeinteractionbetweentheturtlesandthepatches.
We'llmaketheturtleseat"grass"(thegreenpatches),reproduce,anddie.Thegrasswillgraduallygrowbackafteritiseaten.
We'llneedawayofcontrollingwhenaturtlereproducesanddies.We'lldeterminethatbykeepingtrackofhowmuch"energy"eachturtlehas.Todothatweneedtoaddanewturtlevariable.
You'vealreadyseenbuilt-inturtlevariableslikecolor.Tomakeanewturtlevariable,weaddaturtles-owndeclarationatthetopoftheCodetab,beforealltheprocedures.Callitenergy:
turtles-own [energy]
to go move-turtles eat-grass tickend
Let'susethisnewlydefinedvariable(energy)toallowtheturtlestoeat.
SwitchtotheCodetab.Rewritethegoprocedureasfollows:
to go move-turtles eat-grass tickend
Addaneweat-grassprocedure:
to eat-grass ask turtles [ if pcolor = green [ set pcolor black set energy energy + 10 ] ]end
![Page 82: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/82.jpg)
Weareusingtheifcommandforthefirsttime.Lookatthecodecarefully.Eachturtle,whenitrunsthesecommands,comparesthevalueofthepatchcoloritison(pcolor)tothevalueforgreen.(Aturtlehasdirectaccesstothevariablesofthepatchitisstandingon.)Ifthepatchcolorisgreen,thecomparisonreportstrue,andonlythenwilltheturtlerunthecommandsinsidethebrackets(otherwiseitskipsthem).Thecommandsmaketheturtlechangethepatchcolortoblackandincreaseitsownenergyby10.Thepatchturnsblacktosignifythatthegrassatthatspothasbeeneaten.Andtheturtleisgivenmoreenergy,fromhavingjusteaten.
Next,let'smakethemovementofturtlesuseupsomeoftheturtle'senergy.
Rewritemove-turtlesasfollows:
to move-turtles ask turtles [ right random 360 forward 1 set energy energy - 1 ]end
Aseachturtlewanders,itwillloseoneunitofenergyateachstep.
SwitchtotheInterfacetabnowandpressthesetupbuttonandthegobutton.
You'llseethepatchesturnblackasturtlestraveloverthem.
Monitors
NextyouwillcreatetwomonitorsintheInterfacetabwiththetoolbar.(Youmakethemjustlikebuttonsandsliders,usingtheAddicononthetoolbar.)Let'smakethefirstmonitornow.
CreateamonitorbyclickingtheAddicononthetoolbar,selectingMonitornexttoit,andclickingonanopenspotintheInterface.
Adialogboxwillappear.
Inthedialogtype:count turtles(seeimagebelow).PresstheOKbuttontoclosethedialog.
![Page 83: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/83.jpg)
turtlesisan"agentset",thesetofallturtles.counttellsushowmanyagentsareinthatset.
Let'smakethesecondmonitornow:
CreateamonitorbyclickingtheAddicononthetoolbar,selectingMonitornexttoit,andclickingonanopenspotintheInterface.
Adialogboxwillappear.
IntheReportersectionofthedialogboxtype:count patches with [pcolor = green](seeimagebelow).IntheDisplaynamesectionofthedialogboxtype:green patchesPresstheOKbuttontoclosethedialogbox.
Herewe'reusingcountagaintoseehowmanyagentsareinanagentset.patchesisthesetofallthepatches,butwedon'tjustwanttoknowhowmanypatchestherearetotal,wewanttoknowhowmanyofthemaregreen.That'swhatwithdoes;itmakesasmalleragentsetofjustthoseagentsforwhomtheconditioninthebracketsistrue.Theconditionispcolor = green,sothatgivesusjustthegreenpatches.
Nowwehavetwomonitorsthatwillreporthowmanyturtlesandgreenpatcheswehave,tohelpustrackwhat'sgoingoninourmodel.Asthemodelruns,thenumbersinthemonitorswillautomaticallychange.
Usethesetupandgobuttonsandwatchthenumbersinthemonitorschange.
Switchesandlabels
Theturtlesaren'tjustturningthepatchesblack.They'realsogainingandlosingenergy.Asthemodelruns,tryusingaturtlemonitortowatchoneturtle'senergygoupanddown.
Itwouldbenicerifwecouldseeeveryturtle'senergyallthetime.Wewillnowdoexactlythat,andaddaswitchsowecanturntheextravisualinformationonandoff.
ClickontheAddicononthetoolbar(intheInterfacetab).SelectSwitchfromthemenunexttoAdd.Clickonanopenspotintheinterface.
Adialogwillappear.
![Page 84: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/84.jpg)
IntotheGlobalvariablefield,typeshow-energy?Don'tforgettoincludethequestionmarkinthename.(Seeimagebelow.)
Nowgobacktothe'go'procedureusingtheCodetabwiththeToolbar.Rewritetheeat-grassprocedureasfollows:
to eat-grass ask turtles [ if pcolor = green [ set pcolor black set energy energy + 10 ] ifelse show-energy? [ set label energy ] [ set label "" ] ]end
Theeat-grassprocedureintroducestheifelsecommand.Lookatthecodecarefully.Eachturtle,whenitrunsthesenewcommands,checksthevalueofshow-energy?(determinedbytheswitch).Iftheswitchison,comparisonistrueandtheturtlewillrunthecommandsinsidethefirstsetofbrackets.Inthiscase,itassignsthevaluefortheenergytothelabeloftheturtle.Ifthecomparisonisfalse(theswitchisoff)thentheturtlerunsthecommandsinsidethesecondsetofbrackets.Inthiscase,itremovesthetextlabels(bysettingthelabeloftheturtletobenothing).
(InNetLogo,apieceoftextiscalleda"string",shortforstringofcharacters.Astringisasequenceoflettersorothercharacters,writtenbetweendoublequotes.Herewehavetwodoublequotesrightnexttoeachother,withnothinginbetweenthem.That'sanemptystring.Ifaturtle'slabelisanemptystring,notextisattachedtotheturtle.)
TestthisintheInterfacetab,byrunningthemodel(usingthesetupandgobuttons)switchingtheshow-energy?switchbackandforth.
Whentheswitchison,you'llseetheenergyofeachturtlegoupeachtimeiteatsgrass.You'llalsoseeitsenergygoingdownwheneveritmoves.
Moreprocedures
Nowourturtlesareeating.Let'smakethemreproduceanddie,too.Andlet'smakethegrassgrowback.We'lladdallthreeoftheseofthesebehaviorsnow,bymakingthreeseparateprocedures,oneforeachbehavior.
![Page 85: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/85.jpg)
GototheCodetab.Rewritethegoprocedureasfollows:
to go move-turtles eat-grass reproduce check-death regrow-grass tickend
Addtheproceduresforreproduce,check-death,andregrow-grassasshownbelow:
to reproduce ask turtles [ if energy > 50 [ set energy energy - 50 hatch 1 [ set energy 50 ] ] ]end
to check-death ask turtles [ if energy <= 0 [ die ] ]end
to regrow-grass ask patches [ if random 100 < 3 [ set pcolor green ] ]end
Eachoftheseproceduresusestheifcommand.Eachturtle,whenitrunscheck-deathitwillchecktoseeifitsenergyislessorequalto0.Ifthisistrue,thentheturtleistoldtodie(dieisaNetLogoprimitive).
Wheneachturtlerunsreproduce,itchecksthevalueoftheturtle'senergyvariable.Ifitisgreaterthan50,thentheturtlerunsthecommandsinsidethefirstsetofbrackets.Inthiscase,itdecreasestheturtle'senergyby50,then'hatches'anewturtlewithanenergyof50.ThehatchcommandisaNetLogoprimitivewhichlookslikethis:hatchnumber[commands].Thisturtlecreatesnumbernewturtles,eachidenticaltoitsparent,andasksthenewturtle(s)thathavebeenhatchedtoruncommands.Youcanusethecommandstogivethenewturtlesdifferentcolors,headings,orwhatever.Inourcasewerunonecommand.Wesettheenergyforthenewlyhatchedturtletobe50.
Wheneachpatchrunsregrow-grassitwillchecktoseeifarandomintegerfrom0to99islessthan3.Ifso,thepatchcolorissettogreen.Thiswillhappen3%ofthetime(onaverage)foreachpatch,sincetherearethreenumbers(0,1,and2)outof100possiblethatarelessthan3.
SwitchtotheInterfacetabnowandpressthesetupandgobuttons.
Youshouldseesomeinterestingbehaviorinyourmodelnow.Someturtlesdieoff,somenewturtlesarecreated(hatched),andsomegrassgrowsback.Thisisexactlywhatwesetouttodo.
Ifyoucontinuetowatchyourmonitorsinyourmodel,youwillseethatthecountturtlesandgreenpatchesmonitorsbothfluctuate.Isthispatternoffluctuationpredictable?Istherearelationshipbetweenthevariables?
It'dbeniceifwehadaeasierwaytotrackthechangesinthemodelbehaviorovertime.NetLogoallowsustoplotdataaswegoalong.Thatwillbeournextstep.
Plotting
Tomakeplottingwork,we'llneedtocreateaplotintheInterfacetabandputsomecommandsinsideit.
Thecommandsweputintheplotswillrunautomaticallywhenoursetupprocedurecallsreset-ticksandwhenourgoprocedurecallstick.
CreateaplotbyclickingtheAddicononthetoolbar,selectingPlotnexttoit,andclickingonanopenspotintheInterface.SetitsNameto"Totals"(seeimagebelow)SettheXaxislabelto"time"SettheYaxislabelto"totals"Changethenameofthe"default"pento"turtles".Enterplot count turtlesunderPenUpdateCommands.Pressthe"AddPen"button.Changethenameofthenewpento"grass".Enterplot count patches with [pcolor = green] underPenUpdateCommands.
![Page 86: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/86.jpg)
Whenyou'redone,thedialogshouldlooklikethis:
PressOKinthePlotdialogtofinishediting.
NotethatwhenyoucreatetheplotyoucanalsosettheminimumandmaximumvaluesontheXandYaxes.You'llwanttoleavethe"AutoScale"checkboxchecked,sothatifanythingyouplotexceedstheminimumandmaximumvaluesfortheaxes,theaxeswillautomaticallygrowsoyoucanseeallthedata.
Notethatweusedtheplotcommandtoaddthenextpointtoaplot.ThiscommandmovesthecurrentplotpentothepointthathasanXcoordinateequalto1greaterthanthepreviouslyplottedXcoordinateandaYcoordinateequaltothevaluegivenintheplotcommand(inthefirstcase,thenumberofturtles,andinthesecondcase,thenumberofgreenpatches).Asthepensmovetheyeachdrawaline.
Setupandrunthemodelagain.
Youcannowwatchtheplotbeingdrawnasthemodelisrunning.Yourplotshouldhavethegeneralshapeoftheonebelow,thoughyourplotmightnotlookexactlythesame.
Rememberthatweleft"AutoScale?"on.Thisallowstheplottoreadjustitselfwhenitrunsoutofroom.
Ifyouforgetwhichpeniswhich,youcanedittheplotandcheckthe"Showlegend?"checkbox.
Youmighttryrunningthemodelseveraltimestoseewhataspectsoftheplotarethesameandwhicharedifferentfromruntorun.
Tickcounter
Tomakecomparisonsbetweenplotsfromonemodelrunandanother,itisoftenusefultodothecomparisonforthesamelengthofmodelrun.Learninghowtostoporstartanactionataspecifictimecanhelpmakethishappenbystoppingthemodelatthesamepointeachmodelrun.Keepingtrackofhowmanytimesthegoprocedureisrunisausefulwaytocuetheseactions.That'swhatthetickcounterdoes.
You'realreadyusingthetickcounterinyourmodel,withthereset-ticksandtickcommands,whichalsotriggerplotting.
Youcanalsousethetickcounterforotherthings,suchastosetalimitonthetotallengthofarun.
Changethegoprocedure:
![Page 87: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/87.jpg)
to go if ticks >= 500 [ stop ] move-turtles eat-grass check-death reproduce regrow-grass tickend
Nowsetupandrunthemodel.
Thegraphandmodelwon'tkeeprunningforever.TheyshouldstopautomaticallywhenthetickcounterintheInterfacetab'stoolbarreaches500.
Thetickcommandadvancesthetickcounterby1.ticksisareporterwhichreportsthecurrentvalueofthetickcounter.reset-ticks,inyoursetupprocedure,takescareofrestartingthetickcounterat0whenanewrunissetupandreadytobegin.
Somemoredetails
First,insteadofalwaysusing100turtles,youcanhaveavaryingnumberofturtles.
Createaslidernamed"number":clicktheAddicononthetoolbar,selectSlidernexttoit,andclickonanopenspotintheinterface.Trychangingtheminimumandmaximumvaluesintheslider.Theninsideofsetup-turtles,insteadofcreate-turtles 100youcantype:
to setup-turtles create-turtles number [ setxy random-xcor random-ycor ]end
Testthischangeandcomparehowhavingmoreorfewerturtlesinitiallyaffecttheplotsovertime.
Second,wouldn'titbenicetoadjusttheenergytheturtlesgainandloseastheyeatgrassandreproduce?
Makeaslidercalledenergy-from-grass.Makeanotherslidercalledbirth-energy.Then,insideofeat-grass,makethischange:
to eat-grass ask turtles [ if pcolor = green [ set pcolor black set energy (energy + energy-from-grass) ] ifelse show-energy? [ set label energy ] [ set label "" ] ]end
And,insideofreproduce,makethischange:
to reproduce ask turtles [ if energy > birth-energy [ set energy energy - birth-energy hatch 1 [ set energy birth-energy ] ] ]end
Finally,whatotherslidercouldyouaddtovaryhowoftengrassgrowsback?Arethererulesyoucanaddtothemovementoftheturtlesortothenewlyhatchedturtlesthathappenonlyatcertaintimes?Trywritingthem.
What'snext?
Sonowyouhaveasimplemodelofanecosystem.Patchesgrowgrass.Turtleswander,eatthegrass,reproduce,anddie.
Youhavecreatedaninterfacecontainingbuttons,sliders,switches,monitors,andaplot.You'veevenwrittenaseriesofprocedurestogivetheturtlessomethingtodo.
That'swherethistutorialleavesoff.
Ifyou'dliketolookatsomemoredocumentationaboutNetLogo,theInterfaceGuidesectionofthemanualwalksyouthrougheveryelementoftheNetLogointerfaceinorderandexplainsitsfunction.Foradetaileddescriptionandspecificsaboutwritingprocedures,
![Page 88: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/88.jpg)
refertotheProgrammingGuide.AlloftheprimitivesarelistedanddescribedintheNetLogoDictionary.
Also,youcancontinueexperimentingwithandexpandingthismodelifyou'dlike,experimentingwithdifferentvariablesandbehaviorsfortheagents.
Alternatively,youmaywanttorevisitthefirstmodelinthetutorial,WolfSheepPredation.ThisisthemodelyouusedinTutorial #1.IntheWolfSheepPredationmodel,yousawsheepmovearound,consumeresourcesthatarereplenishedoccasionally(grass),reproduceundercertainconditions,anddieiftheyranoutofresources.Butthatmodelhadanothertypeofcreaturemovingaround--wolves.Theadditionofwolvesrequiressomeadditionalproceduresandsomenewprimitives.Wolvesandsheeparetwodifferent"breeds"ofturtle.Toseehowtousebreeds,studyWolfSheepPredation.
Alternatively,youcanlookatothermodels(includingthemanymodelsintheCodeExamplessectionoftheModelsLibrary)orevengoaheadandbuildyourownmodel.Youdon'tevenhavetomodelanything.Itcanbeinterestingjusttowatchpatchesandturtlesformingpatterns,totrytocreateagametoplay,orwhatever.
Hopefullyyouhavelearnedsomethings,bothintermsoftheNetLogolanguageandabouthowtogoaboutbuildingamodel.Theentiresetofproceduresthatwascreatedaboveisshownbelow.
Appendix:Completecode
ThecompletemodelisalsoavailableinNetLogo'sModelsLibrary,intheCodeExamplessection.It'scalled"Tutorial3".
Noticethatthislistingisfullof"comments",whichbeginwithsemicolons.Commentsletyoumixanexplanationthecoderightinwiththecodeitself.Youmightusecommentstohelpothersunderstandyourmodel,oryoumightusethemasnotestoyourself.
IntheCodetab,commentsaregray,soyoureyescanpickthemouteasily.
turtles-own [energy] ;; for keeping track of when the turtle is ready ;; to reproduce and when it will die
to setup clear-all setup-patches setup-turtles reset-ticksend
to setup-patches ask patches [ set pcolor green ]end
to setup-turtles create-turtles number ;; uses the value of the number slider to create turtles ask turtles [ setxy random-xcor random-ycor ]end
to go if ticks >= 500 [ stop ] ;; stop after 500 ticks move-turtles eat-grass check-death reproduce regrow-grass tick ;; increase the tick counter by 1 each time throughend
to move-turtles ask turtles [ right random 360 forward 1 set energy energy - 1 ;; when the turtle moves it looses one unit of energy ]end
to eat-grass ask turtles [ if pcolor = green [ set pcolor black ;; the value of energy-from-grass slider is added to energy set energy energy + energy-from-grass ] ifelse show-energy? [ set label energy ] ;; the label is set to be the value of the energy [ set label "" ] ;; the label is set to an empty text value ]end
to reproduce ask turtles [ if energy > birth-energy [ set energy energy - birth-energy ;; take away birth-energy to give birth hatch 1 [ set energy birth-energy ] ;; give this birth-energy to the offspring ] ]end
to check-death ask turtles [ if energy <= 0 [ die ] ;; removes the turtle if it has no energy left ]end
to regrow-grass ask patches [ ;; 3 out of 100 times, the patch color is set to green if random 100 < 3 [ set pcolor green ] ]end
![Page 89: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/89.jpg)
InterfaceGuide
ThissectionofthemanualexplainsthefunctionofeachelementinNetLogo'suserinterface.
InNetLogo,youhavethechoiceofviewingmodelsfoundintheModelsLibrary,addingtoexistingmodels,orcreatingyourownmodels.TheNetLogointerfacewasdesignedtomeetalltheseneeds.
Theinterfacecanbedividedintotwomainparts:NetLogomenus,andthemainNetLogowindow.Themainwindowisdividedintotabs.
MenusTabsInternationalusage
Menus
OnaMac,ifyouarerunningtheNetLogoapplication,themenubarislocatedatthetopofthescreen.Onotherplatforms,themenubarisfoundatthetopoftheNetLogowindow.
Thefunctionsavailablefromthemenusinthemenubararelistedinthefollowingchart.
Chart:NetLogomenus
File
New Startsanewmodel.
Open… OpensanyNetLogomodelonyourcomputer.
ModelsLibrary Acollectionofdemonstrationmodels.
RecentFiles Re-opensanypreviouslymodelopenedwith"File->Open"
Save Savethecurrentmodel,orthecurrentlyselectedsourcefile.
SaveAs… Savethecurrentmodel,orthecurrentlyselectedsourcefile,usingadifferentname.
SaveAll Savethecurrentmodelandallopensourcefiles.Thisoptionisonlyavailablewhenoneormoresourcefilesareopen.
UploadtoModelingCommons
UploadsthemodeltoModelingCommons.SeeModelingCommons
SaveAsNetLogo
Savesawebpage,inHTMLformat,containingNetLogowebrunning
![Page 90: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/90.jpg)
NetLogoWeb… yourmodel.
ExportWorld…Savesallvariables,thecurrentstateofallturtlesandpatches,thedrawing,theplots,theoutputareaandtherandomstateinformationtoafile.
ExportPlot… Savesthedatainaplottoafile.
ExportAllPlots… Savesthedatainalltheplotstoafile.
ExportView… Saveapictureofthecurrentview(2Dor3D)toafile(inPNGformat).
ExportInterface… SaveapictureofthecurrentInterfacetab.(inPNGformat)
ExportOutput…
Savethecontentsoftheoutputareaortheoutputsectionofthecommandcentertoafile.
ExportCode… Savethemodel'scodetoanHTMLfile,preservingcolors.
ImportWorld…LoadafilethatwassavedbyExportWorld.
ImportPatchColors… Loadanimageintothepatches;seetheimport-pcolorscommand.
ImportPatchColorsRGB…
LoadanimageintothepatchesusingRGBcolors;seetheimport-pcolors-rgbcommand.
ImportDrawing… Loadanimageintothedrawing,seetheimport-drawingcommand.
ImportHubNetClientInterface…
LoadtheinterfacefromanothermodelintotheHubNetClientEditor.
Print… Sendsthecontentsofthecurrentlyshowingtabtoyourprinter.
Quit ExitsNetLogo.OnaMac,thisitemisontheNetLogomenuinstead.
Edit
Undo Undolasttexteditingactionyouperformed.
Redo Redolastundoactionyouperformed.
Cut Cutsoutorremovestheselectedtextandtemporarilysavesittotheclipboard.
Copy Copiestheselectedtext.
![Page 91: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/91.jpg)
Paste Placestheclipboardtextwherecursoriscurrentlylocated.
Delete Deletesselectedtext.
SelectAll Selectallthetextintheactivewindow.
Find… FindsawordorsequenceofcharacterswithintheInfoorCodetabs.
FindNext FindthenextoccurrenceofthewordorsequenceyoulastusedFindwith.
Comment/Uncomment
UsedintheCodetabtoaddorremovesemicolonsfromcode(semicolonsareusedinNetLogocodetoindicatecomments).
ShiftLeft/ShiftRight UsedintheCodetabtochangetheindentationlevelofcode.
Format UsedintheCodetabtocorrecttheindentationofthecurrentlyselectedcode.
SnaptoGridAvailableonlyintheInterfaceTab.Whenenablednewwidgetsstayona5pixelgridsoitiseasiertolinethemup.(Note:thisfeatureisdisabledwhenzoomedinorout.)
Convertfrom5.3.1to6.0
Availableonlyinan".nls"codetab.Treatsthecodeinthistabasthoughitwerewrittenin5.3.1andconvertsittoruninNetLogo6.Notethatthiswillnottakeintoaccountcodedefinedinthemaincodetab."Undo"doesn'ttakethisoperationintoaccount,soyouwon'twanttosaveunlessyou'resatisfiedwiththechanges.
Tools
Preferences… Opensthepreferencesdialog,whereyoucancustomizevariousNetLogosettings.OnaMac,thisitemisontheNetLogomenuinstead.
Halt
Stopsallrunningcode,includingbuttonsandthecommandcenter.(Warning:sincethecodeisinterruptedinthemiddleofwhateveritwasdoing,youmaygetunexpectedresultsifyoutrytocontinuerunningthemodelwithoutfirstpressing"setup"tostartthemodelrunover.)
GlobalsMonitor Displaysthevaluesofallglobalvariables.
TurtleMonitor
Displaysthevaluesofallofthevariablesinaparticularturtle.Youcancanalsoeditthevaluesoftheturtle'svariablesandissuecommandstotheturtle.(YoucanalsoopenaturtlemonitorviatheView;seetheViewsectionbelow.)
PatchMonitor
Displaysthevaluesofallofthevariablesinaparticularpatch.Youcancanalsoeditthevaluesofthepatch'svariablesandissuecommandstothepatch.(YoucanalsoopenapatchmonitorviatheView;seetheViewsectionbelow.)
![Page 92: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/92.jpg)
LinkMonitor
Displaysthevaluesofallofthevariablesinaparticularlink.Youcancanalsoeditthevaluesofthelink'svariablesandissuecommandstothelink.(YoucanalsoopenalinkmonitorviatheView;seetheViewsectionbelow.)
CloseAllAgentMonitorsClosesallopenagentmonitorwindows.
CloseMonitorsforDeadAgents
Closesallopenagentmonitorwindowstargetingdeadagents.
Hide/ShowCommandCenter
Makesthecommandcentervisibleorinvisible.(Notethatthecommandcentercanalsobeshownorhidden,orresized,withthemouse.)ThisoptionisonlyavailablewhentheInterfaceTabisactive
3DView Opensthe3Dview.SeetheViewssectionformoreinformation.
ColorSwatches
OpenstheColorSwatches.SeetheColorSectionoftheProgrammingGuidefordetails.
TurtleShapesEditor Drawturtleshapes.SeetheShapesEditorGuideformoreinformation.
LinkShapesEditor Drawlinkshapes.SeetheShapesEditorGuideformoreinformation.
BehaviorSpaceRunsthemodeloverandoverwithdifferentsettings.SeetheBehaviorSpaceGuideformoreinformation.
SystemDynamicsModeler
OpenstheSystemDynamicsModeler.SeetheSystemDynamicsModelerGuideformoredetails.
PreviewCommandsEditor
Allowsforeasyeditingofthecommandssequenceusedtocreatepreviewimagesformodels.Givesawaytospecifywhatcodewillbeused(orspecifythattheimageismanuallymade)andpreviewtheresultingimage.
HubNetClientEditor
OpenstheHubNetClientEditor.SeetheHubNetAuthoringGuideformoredetails.
HubNetControlCenter
DisabledifnoHubNetactivityisopen.SeetheHubNetGuideformoreinformation.
Zoom
Larger Increasetheoverallscreensizeofthemodel.Usefulonlargemonitorsorwhenusingaprojectorinfrontofagroup.
NormalSize Resetthescreensizeofthemodeltothenormalsize.
![Page 93: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/93.jpg)
Smaller Decreasetheoverallscreensizeofthemodel.
TabsThismenuofferskeyboardshortcutsforeachofthetabs.OnaMac,it'sCommand1throughCommand3.OnWindows,it'sControl1throughControl3.Additionalnumbersareusedfortabscontaining".nls"files.
Help
LookUpInDictionary
Opensabrowserwiththedictionaryentryfortheselectedcommandorreporter.(YoumayalsousetheF1keyforthis.)
NetLogoUserManual Opensthismanualinawebbrowser.
NetLogoDictionary OpenstheNetLogoDictionaryinawebbrowser.
NetLogoUsersGroup OpenstheNetLogoUsersGroupsiteinawebbrowser.
IntroductiontoAgent-BasedModeling
OpenstheMITPresspagefor"IntroductiontoAgent-BasedModeling"(byUriWilenskyandWilliamRand)inawebbrowser.
Donate OpenstheNetLogodonationpageinawebbrowser.
AboutNetLogo6.0.2…
InformationonthecurrentNetLogoversionyouarerunning.OnaMac,thismenuitemisontheNetLogomenuinstead.
Tabs
AtthetopofNetLogo'smainwindowarethreetabslabeled"Interface","Info"and"Code".Onlyonetabatatimecanbevisible,butyoucanswitchbetweenthembyclickingonthetabsatthetopofthewindow.
Rightbelowtherowoftabsisatoolbarcontainingarowofcontrols.Thecontrolsavailablevaryfromtabtotab.
InternationalUsage
Charactersets
NetLogoalwayssavesandloadsmodelsintheUTF-8characterencoding,whichincludesawiderangeofinternationalcharacters.
IfyouareinalocaleotherthanU.S.English,letusknowifyouhaveanytroubleusingyourlocal
![Page 94: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/94.jpg)
characterset.
TheTransitionGuidehasadviceonconvertingmodelscontaininginternationalcharactersfromearlierNetLogoversions.
Languages
MostofNetLogo'sGUI,andsomeofitserrormessages,arenow"internationalized".ThismeansthatitisnowpossibletodisplayNetLogoindifferentlanguages.
Wesay"possible"herebecausethecurrentreleaseofNetLogoonlysupportsEnglish,Spanish,Chinese,Russian,andJapanese.
Theworkoninternationalizationisnotcomplete.Weareaskingforhelpfromtheusercommunityinhelpinguslocalizeitemssuchasthemenusanderrormessages.
Defaultlanguage
Bydefault,NetLogousesthesamelanguageyouroperatingsystemissetto,ifavailable.(Ifunavailable,yougetEnglish.)
Youcanrecordapreferenceforadifferentlanguagebychangingthe"UserInterfaceLanguage"optioninthepreferencesdialog.OnceanewlanguageischosenyouwillhavetorestartNetLogo.
Supportfortranslators
WehopeNetLogowillbecomeavailableinmanydifferentlanguages.IfyouwouldliketotranslateNetLogotoyourlanguage,seethiswikipageforinstructions.
![Page 95: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/95.jpg)
InterfaceTabGuide
TheInterfacetabiswhereyouwatchyourmodelrun.Italsohastoolsyoucanusetoinspectandalterwhat'sgoingoninsidethemodel.
WhenyoufirstopenNetLogo,theInterfacetabisemptyexceptfortheview,wheretheturtlesandpatchesappear,andtheCommandCenter,whichallowsyoutoissueNetLogocommands.
WorkingwithinterfaceelementsThe2Dand3DviewsCommandCenterPlotsSlidersAgentmonitors
Workingwithinterfaceelements
ThetoolbarontheInterfacetabcontainsbuttonsthatletyouedit,delete,andcreateitemsintheInterfacetabandamenuthatletsyouselectdifferentinterfaceitems(suchasbuttonsandsliders).
Thebuttonsinthetoolbararedescribedbelow.
Adding:Toaddaninterfaceelement,selecttheelementfromthedropdownmenu.NotethattheAddbuttonstaysdown.Thenclickonthewhiteareabelowthetoolbar.(Ifthemenuisalreadyshowingtherighttype,youcanjustpresstheAddbuttoninsteadofusingthemenuagain.)
Selecting:Toselectaninterfaceelement,dragarectanglearounditwithyourmouse.Agrayborderwithblackhandleswillappeararoundtheelementtoshowitisselected.
Selectingmultipleitems:Youcanselectmultipleinterfaceelementsatthesametimebyincludingthemintherectangleyoudrag.Ifmultipleelementsareselected,oneofthemisthe"key"item,whichmeansthatifyouusethe"Edit"or"Delete"buttonsontheInterfaceToolbar,onlythekeyitemisaffected.Thekeyitem'sborderisdarkergray.
Unselecting:Tounselectallinterfaceelements,clickthemouseonthewhitebackgroundoftheInterfacetab.Tounselectanindividualelement,right-clicktheelementandchoose"Unselect"fromthepopupmenu.
Editing:Tochangethecharacteristicsofaninterfaceelement,selecttheelement,thenpressthe"Edit"buttonontheInterfacetoolbar.Youmayalsodoubleclicktheelementonceitisselected.Athirdwaytoeditanelementistoright-clickitandchoose"Edit"fromthepopupmenu.Ifyouusethislastmethod,itisnotnecessarytoselecttheelementfirst.
Moving:Selecttheinterfaceelement,thendragitwithyourmousetoitsnewlocation.Ifyouholddowntheshiftkeywhiledragging,theelementwillmoveonlystraightupanddownorstraightleftandright.
Resizing:Selecttheinterfaceelement,thendragtheblack"handles"intheselectionborder.
Deleting:Selecttheelementorelementsyouwanttodelete,thenpressthe"Delete"buttononthe
![Page 96: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/96.jpg)
Interfacetoolbar.Youmayalsodeleteanelementbyright-clickingitandchoosing"Delete"fromthepopupmenu.Ifyouusethislattermethod,itisnotnecessarytoselecttheelementfirst.
Tolearnmoreaboutthedifferentkindsofinterfaceelements,refertothechartbelow.
Chart:InterfaceToolbar
Icon&Name DescriptionAbuttoniseitheronceorforever.Whenyouclickonaoncebutton,itexecutesitsinstructionsonce.Theforeverbuttonexecutestheinstructionsoverandover,untilyouclickonthebuttonagaintostoptheaction.Ifyouhaveassignedanactionkeytothebutton,pressingthecorrespondingkeyboardkeywillactjustlikeabuttonpresswhenthebuttonisinfocus.Buttonswithactionkeyshavealetterintheupperrightcornerofthebuttontoshowwhattheactionkeyis.IfthekeyboardfocusisinanotherinterfaceelementsuchastheCommandCenter,pressingtheactionkeywon'ttriggerthebutton.Theletterintheupperrighthandcornerofthebuttonwillbedimmedinthissituation.Toenableactionkeys,clickinthewhitebackgroundoftheInterfacetab.
Slidersareglobalvariables,whichareaccessiblebyallagents.Theyareusedinmodelsasaquickwaytochangeavariablewithouthavingtorecodetheprocedureeverytime.Instead,theusermovestheslidertoavalueandobserveswhathappensinthemodel.
Switchesareavisualrepresentationforatrue/falseglobalvariable.Youmaysetthevariabletoeitheron(true)oroff(false)byflippingtheswitch.
Choosersletyouchooseavalueforaglobalvariablefromalistofchoices,presentedinadropdownmenu.Thechoicesmaybestrings,numbers,booleans,orlists.
InputBoxesareglobalvariablesthatcontainstringsornumbers.Themodelauthorchooseswhattypesofvaluesyoucanenter.Inputboxescanbesettocheckthesyntaxofastringforcommandsorreporters.Numberinputboxesreadanytypeofconstantnumberreporterwhichallowsamoreopenwaytoexpressnumbersthanaslider.ColorinputboxesofferaNetLogocolorchooser.
Monitorsdisplaythevalueofanyreporter.Thereportercouldbeavariable,acomplexreporter,oracalltoareporterprocedure.Monitorsautomaticallyupdateseveraltimespersecond.
Plotsshowdatathemodelisgenerating.
Theoutputareaisascrollingareaoftextwhichcanbeusedtocreatealogofactivityinthemodel.Amodelmayonlyhaveoneoutputarea.
NotesletsyouaddinformativetextlabelstotheInterfacetab.Thecontentsofnotesdonotchangeasthemodelruns.
TheothercontrolsintheInterfacetoolbarallowyoutocontroltheviewupdatesandvariousothermodelproperties.
Thesliderletsyoucontrolhowfastthemodelruns.Slowercanbevaluablesincesomemodelsrunsofastthey'rehardtofollow.Youcanalsofast-forwardthemodelbymovingtheslidertotheright,reducingthefrequencyofviewupdates.Theviewupdatescheckboxcontrolswhetherviewupdateshappenatall.Theupdatemodemenuallowsyoutoswitchbetweencontinuousandtick-basedupdates.The"Settings..."buttonallowsyoutochangemodelsettings.
"Continuous"updatesmeansthatNetLogoupdates(thatis,redraws)theviewmanytimesasecond,
![Page 97: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/97.jpg)
regardlessofwhatisgoingoninthemodel."Tick-based"updatesmeansthattheviewonlyupdateswhenthetickcounteradvances.(Forafullerdiscussionofviewupdates,seetheProgrammingGuide.)
The2Dand3Dviews
ThelargeblacksquareintheInterfacetabisthe2Dview.It'savisualrepresentationoftheNetLogoworldofturtlesandpatches.Initiallyit'sallblackbecausethepatchesareblackandtherearenoturtlesyet.Youcanopenthe3DView,analternatevisualrepresentationoftheworld,byrightclicking(ctrl-clickingonMac)ontheViewandchoosing"Switchto3DView"(thisoptionisalsoavailableinthe"Tools"menu).
ThereareanumberofsettingsfortheView(accessiblebyeditingtheView,orbypressingthe"Settings..."buttonintheInterfaceToolbar):
Noticethatthesettingsarebrokenupintothreegroups.Thereareworld,view,andtickscountersettings.Worldsettingsaffectthepropertiesoftheworldthattheturtleslivein(changingthemmayrequireresettingtheworld).Viewandtickcountersettingsonlyaffecttheappearance,changingthemwillnotaffecttheoutcomeofthemodel.
![Page 98: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/98.jpg)
Theworldsettingsallowyoutodefinetheboundariesandtopologyoftheworld.Atthetopoftheleftsideoftheworldpanelyoucanchoosealocationfortheoriginoftheworldeither"Center","Corner","Edge",or"Custom".Bydefaulttheworldhasacenterconfigurationwhere(0,0)isatthecenteroftheworldandyoudefinethenumberofpatchesfromthecentertotherightandleftboundariesandthenumberofpatchesfromthecentertothetopandbottomboundaries.Forexample:ifyousetMax-Pxcor=10,thenMin-Pxcorwillautomaticallybesetto-10,thusthereare10patchestotheleftoftheoriginand10patchestotherightofpatch00,foratotalof21patchesineachrow.
ACornerconfigurationallowsyoutodefinethelocationoftheoriginasoneofthecornersoftheworld,upperleft,upperright,lowerleft,orlowerright.Thenyoudefinethefarboundaryinthexandydirections.Forexampleifyouchoosetoputtheorigininthelowerleftcorneroftheworldyoudefinetherightandtop(positive)boundaries.
Edgemodeallowsyoutoplacetheoriginalongoneoftheedges(xory)thendefinethefarboundaryinthatdirectionandbothboundariesintheother.Forexampleifyouselectedgemodealongthebottomoftheworld,youmustalsodefinethetopboundary,aswellastheleftandtheright.
Finally,Custommodeallowsyoutoplacetheoriginatanylocationintheworld,thoughpatch00muststillexistintheworld.
Asyouchangethesettingsyouwillnoticethatthechangesyoumakearereflectedinthepreviewontherightsideofthepanelwhichshowstheoriginandtheboundaries.Thewidthandheightoftheworldaredisplayedbelowthepreview.
Alsobelowthepreviewtherearetwocheckboxes,theworldwrapsettings.Theseallowyoutocontrolthetopologyoftheworld.Noticewhenyouclickthecheckboxesthepreviewindicateswhichdirectionsallowwrapping,andthenameofthetopologyisdisplayednexttotheworlddimensions.SeetheTopologysectionoftheProgrammingGuideformoreinformation.
Theviewsettingsallowyoutocustomizethelookoftheviewwithoutchangingtheworld.Changingviewsettingswillneverforceaworldreset.Tochangethesizeofthe2DViewadjustthe"PatchSize"setting,measuredinpixels.Thisdoesnotchangethenumberofpatches,onlyhowlargethepatchesappearinthe2DView.(Notethatthepatchsizedoesnotaffectthe3DView,asyoucansimplymakethe3DViewlargerbymakingthewindowlarger.)
Thefontsizesettingletsyoucontrolthesizeofturtle,patch,andlinklabels.
Theframeratecontrolshowoftentheviewgetsupdated.Thiscanhaveadramaticeffectonthedefaultspeedatwhichamodelruns.Formoredetails,seetheviewupdatessectionoftheProgrammingGuide.
The"Smoothedges"checkboxcontrolstheuseofanti-aliasinginthe3Dviewonlyandonlyappearswheneditingfromthe3Dview.Uncheckingitmakeslinesappearmorejaggedbutmayspeeduprendering.
Tickcountersettingscontroltheappearanceofthetickcounterwhichisvisible(ornot)intheviewcontrolstrip.
Turtle,patchandlinkmonitorsareeasilyavailablethroughtheView,justright-clickontheturtleorpatchyouwanttoinspect,andchoose"inspectturtle..."or"inspectpatch..."fromthepopupmenu.Youcanalsowatch,followorrideaturtlebyselectingtheappropriateitemintheturtlesub-menu.(Turtle,patchandlinkmonitorscanalsobeopenedfromtheToolsmenuorbyusingtheinspectcommand.)
SomeNetLogomodelsletyouinteractwiththeturtlesandpatcheswithyourmousebyclickinganddraggingintheView.
Manipulatingthe3DView
Atthebottomofthewindowtherearebuttonstomovetheobserver,orchangetheperspectivefromwhichyouarelookingattheworld.
![Page 99: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/99.jpg)
Abluecrossappearsatthecurrentfocuspointasyouadjustthesesettings.Thelittlebluetrianglewillalwayspointalongthey-axisinthepositivedirection,soyoucanorientyourselfincaseyougetlost.
Tolookattheworldfromadifferentangle,pressthe"rotate"button,thenclickanddragthemouse.Theobserverwillcontinuetofacethesamepointasbefore(wherethebluecrossis)butitspositionintherelationtothexy-planewillchange.
Tomovecloserorfartherawayfromtheworldortheagentyouarewatching,followingorriding,pressthe"zoom"buttonanddragupanddown.Notewhenyouareinfolloworridemodezoomingwillswitchyoubetweenrideandfollow,sincerideisjustaspecialcaseoffollowwherethedistanceatwhichyouarefollowingis0.
Tochangethepositionoftheobserverwithoutchangingthedirectionitisfacingselectthe"move"buttonanddragthemouseinsidethe3DViewwhileholdingdownthemousebutton.
Toallowthemousepositionandstatetobepassedtothemodelselectthe"interact"buttonanditwillfunctionjustasthemousedoesinthe2Dview.
Toreturntheobserverandfocuspointtotheirdefaultpositionspressthe"ResetPerspective"button(orusethereset-perspectivecommand).
FullscreenMode
Toenterfullscreenmode,pressthe"FullScreen"button,toexitfullscreenmode,presstheEsckey.
Note:Fullscreenmodedoesn'tworkoneverycomputer.Itdependsonyourgraphicscard.SeetheSystemRequirementsfordetails.
3DShapes
Someshapesareautomaticallymappedtotrue3Dcounterpartsinthe3Dview.Forexample,the2Dcircleshapebecomesasphereinthe3Dview.Shapename 3Dshapedefault 3Dturtleshapecircle spheredot smallspheresquare cubetriangle coneline 3Dlinecylinder 3Dcylinderline-half 3Dline-halfcar 3Dcar
Allothershapesarebasedontheir2Dforms.Ifashapeisarotatableshape,itisassumedtobeatopviewanditisextrudedasifthroughacookiecutterandorientedparalleltothexy-plane,asinAnts.
![Page 100: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/100.jpg)
Or,ifashapeisnon-rotatable,itisassumedtobeasideview,anditisdrawnalwaysfacingtheobserver,asinWolfSheepPredation.
CommandCenter
TheCommandCenterallowsyoutoissuecommandsdirectly,withoutaddingthemtothemodel'sprocedures.Thisisusefulforinspectingandmanipulatingagentsonthefly.
(Tutorial#2:CommandsisanintroductiontousingcommandsintheCommandCenter.)
Let'stakealookatthedesignoftheCommandCenter.
Thesmallerbox,belowthelargebox,iswhereyoutypeacommand.AftertypingitpresstheReturnorEnterkeytorunit.
Totheleftofwhereyoutypeisapopupmenuthatinitiallysays"observer>".Youcanchooseeitherobserver,turtles,orpatches,tospecifywhichagentsrunthecommandyoutype.
Tip:aquickerwaytochangeagenttypesistousetheTabkey.
Reporters
IfyouenterareporterintotheCommandCenter,theshowcommandwillbeinsertedbeforeitautomatically.
![Page 101: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/101.jpg)
Accessingpreviouscommands
Afteryoutypeacommand,itappearsinthelargescrollingboxabovethecommandline.YoucanuseCopyontheEditmenuinthisareatocopycommandsandthenpastethemelsewhere,suchastheCodetab.
Youcanalsoaccesspreviouscommandsusingthehistorypopup,whichisthesmalldownwardpointingtriangletotherightofwhereyoutypecommands.Clickonthetriangleandamenuofpreviouslytypedcommandsappears,soyoucanpickonetouseagain.
Tip:aquickerwaytoaccesspreviouscommandsiswiththeupanddownarrowkeysonyourkeyboard.
Clearing
Toclearthelargescrollingareacontainingpreviouscommandsandoutput,click"clear"inthetoprightcorner.
Toclearthehistorypopupmenu,choose"ClearHistory"onthatmenu.
Arranging
YoucanhideandshowthecommandcenterusingtheHideCommandCenterandShowCommandCenteritemsontheToolsmenu.
Toresizethecommandcenter,dragthebarthatseparatesitfromthemodelinterface.Or,clickoneofthelittlearrowsontherightendofthebartomakethecommandcentereitherverybigorhiddenaltogether.
Toswitchbetweenaverticalcommandcenterandahorizontalone,clickthebuttonwiththedouble-headedarrow,justtotheleftof"Clear".
Plots
Whenthemousepointerisoverthewhiteareaofaplot,thexandycoordinatesofthemouselocationappear.(Notethatthemouselocationmightnotcorrespondexactlytoanyactualdatapointsintheplot.Ifyouneedtoknowtheexactcoordinatesofplottedpoints,usetheExportPlotmenuitemandinspecttheresultingfileinanotherprogram.)
Whenyoucreateaplot,aswithallwidgets,theeditdialogautomaticallyappears.
![Page 102: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/102.jpg)
Manyofthefieldsarefairlyself-explanatory,suchasthenameoftheplot,labelsforthexandyaxes,rangesfortheaxes,andthe"Showlegend?"checkbox.
IfAutoScale?ischeckedthexandychangeswillautomaticallyreadjustaspointsareaddedtotheplotiftheyareoutsidethecurrentrange.
Under"Plotsetupcommands"and"Plotupdatecommands"youcanentercommandsthatwillautomaticallyberunatappropriatetimes.Clickthelittletriangletoopenthetextboxforthecommands.PlotcommandsareexplainedinmoredetailinthePlottingsectionoftheProgrammingGuide.
PlotPens
Intheplotpenssectionofthedialog,youcancreateandcustomizeyourplot'spens.Eachtablerowrepresentsapen.Bydefaultthereisonepennamed"default".(Youmaywishtochangeittoanamethathasmeaninginyourmodel.)
Toeditthecolorofapenclickthecoloredrectangletotheleftofthepen'sname.ThiswillbringupadialogthatallowsyoutosetthecolortooneoftheNetLogobasehuesoracustomcolorusingthecolorswatches.
Toeditthepen'sname,doubleclickthename.
Inthe"PenUpdateCommands"columnyoucanentercommandsthatwillberunwhenreset-ticks,tick,orupdate-plotscommandsarerun.ThisisexplainedinmoredetailinthePlottingsectionoftheProgrammingGuide.
Thelastcolumnhastwobuttons.Clickingthepenciliconwillbringupaneditdialogwithadditionalpensettings.Thetrashcanbuttondeletesthepen.
PlotPenAdvancedSettings
Clickingapen'seditbuttonwillopenthisdialog:
![Page 103: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/103.jpg)
Modeallowsyoutochangetheappearanceoftheplotpen:line,bar(forabarchart),orpoint(ascatterplotofindividualpoints).Intervalistheamountbywhichxadvanceseverytimeyouusetheplotcommand.Ifthe"Showinlegend"checkboxischeckedtheselectedpenwillbeapartofthelegendintheupperrighthandcorneroftheplot.Inthe"Setupcommands"fieldyoucanentercommandsthatwillberunwhenreset-ticksorsetup-plotsruns.Inthe"Updatecommands"fieldyoucanentercommandsthatwillberunwhentickorupdate-plotsruns.Thisfieldreappearsintheadvanceddialogtoprovidespaceforeditinglengthiersetsofcommands.
FormoredetailedinformationonhoweachofthesefeaturesworksyoucanseethePlottingSectionoftheProgrammingGuide.
Sliders
Asliderhasanassociatedglobalvariable.Movingthesliderchangesthevariable'svalue.
WhenyouplaceasliderintheInterfacetabtheeditdialogautomaticallyopens,aswithallwidgets.Mostofthefieldswillbefamiliar.However,itisimportanttonoticetheminimum,maximumandincrementfieldswilltakeanyreporter,notjustconstants.So,forexample,youcouldmaketheminimummin-pxcorandthemaximummax-pxcorandthesliderboundswillautomaticallyadjustwhenyouchangethesizeoftheworld.
AgentMonitors
Agentmonitorsdisplayboththevaluesofallthevariablesforaparticularagentandamini-viewthat
![Page 104: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/104.jpg)
showstheagentandasmallareaaroundit.
YoucanopenagentmonitorsthroughtheToolsmenuortheinspectcommand.
Youcanzoominoroutusingthesliderbeneaththeviewandyoucanwatchtheagentinthemainviewusingthewatch-mebutton.
Belowthesliderthecurrentvalueofeachagentvariableisdisplayed.Youcanenteranewvalue.Itwillbeasif,forexample,thecodeset pcolor ...hadrun.
Belowtheagentvariableareathereisamini-commandcenter.Ratherthanrunningcodeastheobserver,ortalkingtoalloftheturtles,patches,orlinks,thecodeenteredinthiscommandcenterisrunonlybythisagent.
Youcancloseanagentmonitorbyclickingtheboxintheupperleftcorner,orbypressingtheEsckey.Ifyouholddownshiftwhileyouclicktheboxallopenagentmonitorswillcloseoryoucanclosealltheagentmonitorsusingthe"CloseAllMonitors"optionintheToolsMenu.
![Page 105: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/105.jpg)
InfoTab
TheInfotabprovidesanintroductiontoamodel.Itexplainswhatsystemisbeingmodeled,howthemodelwascreated,andandhowtouseit.Itmayalsosuggestthingstoexploreandwaystoextendthemodel,orcallyourattentiontoparticularNetLogofeaturesthemodeluses.
YoumaywishtoreadtheInfotabbeforestartingamodel.
Editing
Thenormal,formattedviewoftheInfotabisnoteditable.Tomakeedits,clickthe"Edit"button.Whendoneediting,clickthe"Edit"buttonagain.
![Page 106: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/106.jpg)
YouedittheInfotabasunformattedplaintext.Whenyou'redoneediting,theplaintextyouenteredisdisplayedinamoreattractiveformat.
Tocontrolhowtheformatteddisplaylooks,youusea"markuplanguage"calledMarkdown.YoumayhaveencounteredMarkdownelsewhere;itisusedonanumberofwebsites.(Thereareothermarkuplanguagesinuseontheweb;forexample,WikipediausedamarkuplanguagecalledMediaWiki.Markuplanguagesdifferindetails.)
TheremainderofthisguideisatourofMarkdown.
HeadingsParagraphsItalicizedandboldtextOrderedlistsUnorderedlistsLinksImagesBlockquotationsCodeCodeblocksSuperscriptsandsubscriptsNotesonusageOtherfeatures
Headings
Aheadingbeginswithoneormorehashmarks(#).Firstlevelheadingsgetonehash,secondlevelheadingsgettwo,andsoonuptofourlevels.
Input
# First-level heading
## Second-level heading
### Third-level heading
#### Fourth-level heading
![Page 107: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/107.jpg)
Paragraphs
Example
This is a paragraph. There are no spaces before the word 'This'.
This is another paragraph. The first line has two sentences.The entire paragraph has two lines and three sentences.
Line breaks in the input,Make line breaks in the output,Like this.
Formatted
Thisisaparagraph.Therearenospacesbeforetheword'This'.
Thisisanotherparagraph.Thefirstlinehastwosentences.Theentireparagraphhastwolinesandthreesentences.
Linebreaksintheinput,Makelinebreaksintheoutput,Likethis.
Italicizedandboldtext
Example
For italics, surround text with underscores:_hello, world_.
For bold, surround text with two asterisks:**hello, world**.
You can also combine them:_**hello**_ and **_goodbye_**
Formatted
Foritalics,surroundtextwithunderscores:hello,world.
Forbold,surroundtextwithtwoasterisks:hello,world.
Youcanalsocombinethem:helloandgoodbye
Orderedlists
Example
We are about to start an ordered list.
1. Ordered lists are indented 2 spaces. 1. Subitems are indented 2 more spaces (4 in all). 2. The next item in the list starts with the next number. 3. And so on...
Formatted
![Page 108: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/108.jpg)
Weareabouttostartanorderedlist.
1. Orderedlistsareindented2spaces.1. Subitemsareindented2morespaces(4inallforasecondlevelitem).
2. Thenextitemintheliststartswiththenextnumber.3. Andsoon…
Unorderedlists
Example
We are about to start an unordered list.
* Like ordered lists, unordered lists are also indented 2 spaces. * Unlike ordered lists, unordered lists use stars instead of numbers. * Sub items are indented 2 more spaces. * Here's another sub item.
Formatted
Weareabouttostartanunorderedlist.
Likeorderedlists,unorderedlistsarealsoindented2spaces.Unlikeorderedlists,unorderedlistsusestarsinsteadofnumbers.
Subitemsareindented2morespaces.Here'sanothersubitem.
Links
Automaticlinks
Thesimplestwaytocreatealinkistojusttypeitin:
Example
http://ccl.northwestern.edu/netlogo/
Formatted
http://ccl.northwestern.edu/netlogo/
Linkswithtext
Ifyouwanttouseyourowntextforthelink,here'show:
[link text here](link.address.here)
Example
[NetLogo](http://ccl.northwestern.edu/netlogo/)
![Page 109: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/109.jpg)
Formatted
NetLogo
Locallinks
Itisalsopossibletolinktoapageonyourcomputer,insteadofapagesomewhereontheInternet.
Locallinkshavethisform:
[alt text](file:path)
Anyspacesinthepathmustbeconvertedto%20.Forexample,this:
file:my page.html
mustbewrittenas:
file:my%20page.html
Thepathisrelativetothedirectorythatthemodelfileisin.
Example
Theeasiestwaytolinktofilesonyourcomputeristoputthemintothesamedirectoryasyourmodel.Assumingyouhaveafilenamedindex.htmlinthesamedirectoryasyourmodel,thelinkwouldlooklikethis:
[Home](file:index.html)
Example
Hereisanotherexamplewherethefilelivesinadirectorycalleddocs,anddocsisinthesamedirectoryasyourmodel:
[Home](file:docs/index.html)
Images
Imagesareverysimilartolinks,buthaveanexclamationpointinfront:
![alt text](http://location/of/image)
(Thealternatetextisthetextthatgetsdisplayediftheimageisnotfound.)
Example
![NetLogo](http://ccl.northwestern.edu/netlogo/images/netlogo-title-new.jpg)
![Page 110: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/110.jpg)
Formatted
Localimages
Alsoverysimilartolinks,itispossibletodisplayanimageonyourcomputerinsteadofanimagesomewhereontheInternet.Assumingyouhaveanimagenamedimage.jpg,localimageslooklikethis:
![alt text](file:path)
Thepathisrelativetothedirectorythatthemodelfileisin.
Aswithlocallinks,anyspacesinthenameofthefileorthepathmustbeconvertedto%20.
Example
Likelocallinks,theeasiestwaytodisplayimagesonyourcomputeristoputthemintothesamedirectoryasyourmodel.Thisexampledisplaystheimage"PerspectiveExample.png",whichresidesinthesamedirectoryasthismodel(InfoTabExample).
![Example](file:Perspective%20Example.png)
Formatted
![Page 111: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/111.jpg)
Blockquotations
Consecutivelinesstartingwith>willbecomeblockquotations.Youcanputwhatevertextyoulikeinsideofitandyoucanalsostyleit.
Example
> Let me see: four times five is twelve, and four times six is thirteen,> and four times seven is --- _oh dear!_> I shall never get to twenty at that rate!
Formatted
Letmesee:fourtimesfiveistwelve,andfourtimessixisthirteen,andfourtimessevenis--ohdear!Ishallnevergettotwentyatthatrate!
Code
Toincludeashortpieceofcodeinasentence,surrounditwithbackticks(`).
Example
You can create a single turtle with the `crt 1` command.
Formatted
![Page 112: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/112.jpg)
Youcancreateasingleturtlewiththecrt 1command.
Codeblocks
Itisalsopossibletohaveblocksofcode.Tocreateacodeblock,indenteverylineoftheblockby4spaces.Anotherwayistosurrounditwithathreebacktickslinebeforeandaftertheblock.(Ifyoudon'twantyourcodetobecoloredasNetLogocode,addtextafterthefirstthreebackticks.)
Example
About to start the code block.Leave a blank line after this one, and then put the code block:
; a typical go procedure to go ask turtles [ fd 1 ] tick end
or:
About to start the code block.Leave a blank line after this one, and then put the code block:
```; a typical go procedureto go ask turtles [ fd 1 ] tickend```
Formatted
Abouttostartthecodeblock.Leaveablanklineafterthisone,andthenputthecodeblock:
; a typical go procedureto go ask turtles [ fd 1 ] tickend
Superscriptsandsubscripts
Superscriptsandsubscriptsareusefulforwritingformulas,equations,footnotesandmore.Subscriptsappearhalfacharacterbelowthebaseline,andarewrittenusingtheHTMLtag<sub>.Superscriptsappearhalfacharacterabovethebaseline,andarewrittenusingtheHTMLtag<sup>.
Example
H<sub>2</sub>O
2x<sup>4</sup> + x<sup>2</sup>
WWW<sup>[1]</sup>
![Page 113: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/113.jpg)
Formatted
H2O
2x4+x2+42
WWW[1]
Notesonusage
Paragraphs,lists,codeblocksandotherfeaturesshouldbeseparatedfromeachotherwithablankline.Ifyoufindthatsomethingisn'tformattedthewayyouexpected,itmightbebecauseyouneedtoaddablanklinebeforeit.
Topreventaspecialcharacterfrombeingtreatedasmarkup,putabackslash(\)beforeit.
WeuseGitHubflavorednewlines(https://github.github.com/github-flavored-markdown/)insteadoftraditionalMarkdownhandlingofnewlines.Thismeansthatnewlinesaretreatedasreallinebreaks,insteadofbeingcombinedwiththepreviouslineintoasingleparagraph.
Otherfeatures
Markdownhasadditionalfeaturesthatwehavenotshownhere.
Wehavetestedthefeaturesshownaboveonavarietyofsystems.IfyouuseotherMarkdownfeatures,youmayfindthattheyworkonyourcomputer,ornot.Evenafeaturethatworksonyourcomputermightworkdifferently,ornotworkatall,forsomeonewithadifferentoperatingsystemorJavavirtualmachine.
IfyouwantallNetLogouserstobeabletoreadyourInfotab,useonlythefeaturesshownabove.
MoreinformationaboutMarkdownisathttp://daringfireball.net/projects/markdown/.ForrenderingMarkdown,NetLogousestheFlexmark-javalibrary.
![Page 114: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/114.jpg)
CodeTabGuide
TheCodetabiswherethecodeforthemodelisstored.CommandsyouonlywanttouseimmediatelygointheCommandCenter;commandsyouwanttosaveanduselater,overandoveragain,arefoundintheCodetab.
Todetermineifthecodehasanyerrors,youmaypressthe"Check"button.Ifthereareanysyntaxerrors,theCodetabwillturnred,thecodethatcontainstheerrorwillbehighlighted,andanerrormessagewillappear.
Switchingtabsalsocausesthecodetobechecked,soifyoujustswitchtabs,pressingtheCheckbuttonfirstisn'tnecessary.
Tofindafragmentofcodeintheprocedures,clickonthe"Find"buttonintheCodetoolbarandtheFinddialogwillappear.
![Page 115: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/115.jpg)
Youmayenterawordorphrasetofind,andoptionallyalsoanewwordorphrasetoreplaceitwith.The"Ignorecase"checkboxcontrolswhetherthecapitalizationmustbethesametoindicateamatch.
Ifthe"Wraparound"checkboxischecked,theentireCodetabwillbecheckedforthephrase,startingatthecursorposition.Whenitreachestheenditwillreturntothetop,otherwiseonlytheareafromthecursorpositiontotheendoftheCodetabwillbesearched.The"Next"and"Previous"buttonswillmovedownanduptofindanotheroccurrenceofthesearchphrase.
"Replace"changesthecurrentlyselectedphrasewiththereplacephraseand"Replace&Find"changestheselectedphraseandmovestothenextoccurrence."ReplaceAll"willchangeallinstancesofthefindphraseinthesearchareawiththereplacephrase.
Tofindaparticularproceduredefinitioninyourcode,usethe"Procedures"popupmenuintheCodetab.Themenulistsallproceduresinalphabeticalorder.
The"ShiftLeft","ShiftRight","Comment",and"Uncomment"itemsontheEditmenuareusedintheCodetabtochangetheindentationlevelofyourcodeoraddandremovesemicolons,whichmarkcomments,fromsectionsofcode.
Formoreinformationaboutwritingprocedures,readTutorial#3:ProceduresandtheProgrammingGuide.
IncludedFilesMenu
Caution:Theincludesfacilityisnewandexperimental.
Whenyouaddthe__includeskeywordtoamodelamenutotherightoftheproceduresmenuappears.Thisisthe"IncludedFiles"menuwhichlistsalltheNetLogosourcefiles(.nls)includedinthisfile.YoucanmakethismenualwaysvisibleusingthePreferencesdialog.
Youcanchooseafilenamefromthemenutoopenatabforthatfile,oryoucanopenaneworexistingfileusingNewSourceFileandOpenSourceFile,respectively.
![Page 116: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/116.jpg)
Onceyou'veopenednewtabstheybecomeaccessiblefromtheTabsmenu,andyoucanusethekeyboardtomovefromtabtotab(Command+numberonMac,Control+numberonotheroperatingsystems).
Automaticindentation
WhentheIndentAutomaticallycheckboxisselected,NetLogowillautomaticallyattempttoalignyourcodeinalogicallystructuredformat.Forexample,whenyouopenasetofsquarebrackets"["(perhapsafteranifstatement),NetLogowillautomaticallyaddspacessothatthefollowinglinesofcodearetwospacesfurtherindentedthanthebracket.Whenyouclosethesquarebracketstheclosingbracketwillbelinedupwiththematchingopenbracket.
NetLogowilltrytoindentthecodeasyoutype,butyoucanalsopressthetabkeyanywhereonanylinetoaskNetLogotoindentthelineimmediately.Or,youcanselectawholeregionofcodeandpressthetabkeytore-indentallofit.
![Page 117: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/117.jpg)
ProgrammingGuide
ThissectiondescribestheNetLogoprogramminglanguageindetail.
TheCodeExamplemodelsmentionedthroughoutcanbefoundintheCodeExamplessectionoftheModelsLibrary.
AgentsProceduresVariablesTickcounterColorsAskAgentsetsBreedsButtonsListsMathRandomnumbersTurtleshapesLinkshapesViewupdatesPlottingStringsOutputFileI/OMoviesPerspectiveDrawingTopologyLinksAnonymousproceduresAsk-ConcurrentUserInteractionPrimitivesTieMultiplesourcefilesSyntax
Agents
TheNetLogoworldismadeupofagents.Agentsarebeingsthatcanfollowinstructions.
InNetLogo,therearefourtypesofagents:turtles,patches,links,andtheobserver.
Turtlesareagentsthatmovearoundintheworld.Theworldistwodimensionalandisdividedupintoagridofpatches.Eachpatchisasquarepieceof"ground"overwhichturtlescanmove.Linksareagentsthatconnecttwoturtles.Theobserverdoesn'thavealocation--youcanimagineitaslookingoutovertheworldofturtlesandpatches.
Theobserverdoesn'tobservepassively--itgivesinstructionstotheotheragents.
WhenNetLogostartsup,therearenoturtles.Theobservercanmakenewturtles.Patchescanmakenewturtlestoo.(Patchescan'tmove,butotherwisethey'rejustas"alive"asturtles.)
Patcheshavecoordinates.Thepatchatcoordinates(0,0)iscalledtheoriginandthecoordinatesoftheotherpatchesarethehorizontalandverticaldistancesfromthisone.Wecallthepatch'scoordinatespxcorandpycor.Justlikeinthestandardmathematicalcoordinateplane,pxcorincreasesasyoumovetotherightandpycorincreasesasyoumoveup.
Thetotalnumberofpatchesisdeterminedbythesettingsmin-pxcor,max-pxcor,min-pycor,andmax-pycorWhenNetLogostartsup,min-pxcor,max-pxcor,min-pycor,andmax-pycorare-16,16,-16,and16respectively.Thismeansthatpxcorandpycorbothrangefrom-16to16,sothereare33times33,or
![Page 118: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/118.jpg)
1089patchestotal.(YoucanchangethenumberofpatcheswiththeSettingsbutton.)
Turtleshavecoordinatestoo:xcorandycor.Apatch'scoordinatesarealwaysintegers,butaturtle'scoordinatescanhavedecimals.Thismeansthataturtlecanbepositionedatanypointwithinitspatch;itdoesn'thavetobeinthecenterofthepatch.
Linksdonothavecoordinates.Everylinkhastwoends,andeachendisaturtle.Ifeitherturtledies,thelinkdiestoo.Alinkisrepresentedvisuallyasalineconnectingthetwoturtles.
Procedures
InNetLogo,commandsandreporterstellagentswhattodo.Acommandisanactionforanagenttocarryout,resultinginsomeeffect.Areporterisinstructionsforcomputingavalue,whichtheagentthen"reports"towhoeveraskedit.
Typically,acommandnamebeginswithaverb,suchas"create","die","jump","inspect",or"clear".Mostreporternamesarenounsornounphrases.
CommandsandreportersbuiltintoNetLogoarecalledprimitives.TheNetLogoDictionaryhasacompletelistofbuilt-incommandsandreporters.
Commandsandreportersyoudefineyourselfarecalledprocedures.Eachprocedurehasaname,precededbythekeywordtoorto-report,dependingonwhetheritisacommandprocedureorareporterprocedure.Thekeywordendmarkstheendofthecommandsintheprocedure.Onceyoudefineaprocedure,youcanuseitelsewhereinyourprogram.
Manycommandsandreporterstakeinputs--valuesthatthecommandorreporterusesincarryingoutitsactionsorcomputingitsresult.
Herearetwocommandprocedures:
to setup clear-all create-turtles 10 reset-ticksend
to go ask turtles [ fd 1 ;; forward 1 step rt random 10 ;; turn right lt random 10 ;; turn left ] tickend
Notetheuseofsemicolonstoadd"comments"totheprogram.Commentscanmakeyourcodeeasiertoreadandunderstand,buttheydon'taffectitsbehavior.
Inthisprogram,
setupandgoareuser-definedcommands.clear-all,create-turtles,reset-ticks,ask,lt("leftturn"),rt("rightturn")andtick,areallprimitivecommands.randomandturtlesareprimitivereporters.randomtakesasinglenumberasaninputandreportsarandomintegerthatislessthantheinput(inthiscase,between0and9).turtlesreportstheagentsetconsistingofalltheturtles.(We'llexplainaboutagentsetslater.)
setupandgocanbecalledbyotherprocedures,orbybuttons,orfromtheCommandCenter.
ManyNetLogomodelshaveaoncebuttonthatcallsaprocedurecalledsetupandaforeverbuttonthatcallsaprocedurecalledgo.
InNetLogo,youmayspecifywhichagents--turtles,patches,orlinks--aretoruneachcommand.Ifyoudon'tspecify,thecodeisrunbytheobserver.Inthecodeabove,theobserverusesasktomakethesetofallturtlesrunthecommandsbetweenthesquarebrackets.
![Page 119: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/119.jpg)
clear-allandcreate-turtlescanonlyberunbytheobserver.fd,ontheotherhand,canonlyberunbyturtles.Someothercommandsandreporters,suchassetandticks,canberunbydifferentagenttypes.
Herearesomemoreadvancedfeaturesyoucantakeadvantageofwhendefiningyourownprocedures.
Procedureswithinputs
Procedurescantakeinputs,justlikemanyprimitivesdo.Tocreateaprocedurethatacceptsinputs,puttheirnamesinsquarebracketsaftertheprocedurename.Forexample:
to draw-polygon [num-sides len] ;; turtle procedure pen-down repeat num-sides [ fd len rt 360 / num-sides ]end
Elsewhereintheprogram,youmightusetheprocedurebyaskingtheturtlestoeachdrawanoctagonwithasidelengthequaltoitswhonumber:
ask turtles [ draw-polygon 8 who ]
Reporterprocedures
Justlikeyoucandefineyourowncommands,youcandefineyourownreporters.Youmustdotwospecialthings.First,useto-reportinsteadoftotobeginyourprocedure.Then,inthebodyoftheprocedure,usereporttoreportthevalueyouwanttoreport.
to-report absolute-value [number] ifelse number >= 0 [ report number ] [ report (- number) ]end
Variables
Agentvariables
Agentvariablesareplacestostorevalues(suchasnumbers)inanagent.Anagentvariablecanbeaglobalvariable,aturtlevariable,apatchvariable,oralinkvariable.
Ifavariableisaglobalvariable,thereisonlyonevalueforthevariable,andeveryagentcanaccessit.Youcanthinkofglobalvariablesasbelongingtotheobserver.
Turtle,patch,andlinkvariablesaredifferent.Eachturtlehasitsownvalueforeveryturtlevariable.Thesamegoesforpatchesandlinks.
SomevariablesarebuiltintoNetLogo.Forexample,allturtlesandlinkshaveacolorvariable,andallpatcheshaveapcolorvariable.(Thepatchvariablebeginswith"p"soitdoesn'tgetconfusedwiththeturtlevariable,sinceturtleshavedirectaccesstopatchvariables.)Ifyousetthevariable,theturtleorpatchchangescolor.(Seenextsectionfordetails.)
Otherbuilt-inturtlevariablesincludingxcor,ycor,andheading.Otherbuilt-inpatchvariablesincludepxcorandpycor.(Thereisacompletelisthere.)
Youcanalsodefineyourownvariables.Youcanmakeaglobalvariablebyaddingaswitch,slider,chooser,orinputboxtoyourmodel,orbyusingtheglobalskeywordatthebeginningofyourcode,likethis:
globals [score]
![Page 120: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/120.jpg)
Youcanalsodefinenewturtle,patchandlinkvariablesusingtheturtles-own,patches-ownandlinks-ownkeywords,likethis:
turtles-own [energy speed]patches-own [friction]links-own [strength]
Thesevariablescanthenbeusedfreelyinyourmodel.Usethesetcommandtosetthem.(Anyvariableyoudon'tsethasastartingvalueofzero.)
Globalvariablescanbereadandsetatanytimebyanyagent.Aswell,aturtlecanreadandsetpatchvariablesofthepatchitisstandingon.Forexample,thiscode:
ask turtles [ set pcolor red ]
causeseveryturtletomakethepatchitisstandingonred.(Becausepatchvariablesaresharedbyturtlesinthisway,youcan'thaveaturtlevariableandapatchvariablewiththesamename.)
Inothersituationswhereyouwantanagenttoreadadifferentagent'svariable,youcanuseof.Example:
show [color] of turtle 5;; prints current color of turtle with who number 5
Youcanalsouseofwithamorecomplicatedexpressionthanjustavariablename,forexample:
show [xcor + ycor] of turtle 5;; prints the sum of the x and y coordinates of;; turtle with who number 5
Localvariables
Alocalvariableisdefinedandusedonlyinthecontextofaparticularprocedureorpartofaprocedure.Tocreatealocalvariable,usetheletcommand.Ifyouuseletatthetopofaprocedure,thevariablewillexistthroughouttheprocedure.Ifyouuseitinsideasetofsquarebrackets,forexampleinsidean"ask",thenitwillexistonlyinsidethosebrackets.
to swap-colors [turtle1 turtle2] let temp [color] of turtle1 ask turtle1 [ set color [color] of turtle2 ] ask turtle2 [ set color temp ]end
Tickcounter
InmanyNetLogomodels,timepassesindiscretesteps,called"ticks".NetLogoincludesabuilt-intickcountersoyoucankeeptrackofhowmanytickshavepassed.
Thecurrentvalueofthetickcounterisshownabovetheview.(YoucanusetheSettingsbuttontohidethetickcounter,orchangetheword"ticks"tosomethingelse.)
Incode,toretrievethecurrentvalueofthetickcounter,usetheticksreporter.Thetickcommandadvancesthetickcounterby1.Theclear-allcommandclearsthetickcounteralongwitheverythingelse.
Whenthetickcounterisclear,it'sanerrortotrytoreadormodifyit.Usethereset-tickscommandwhenyourmodelisdonesettingup,tostartthetickcounter.
Ifyourmodelissettousetick-basedupdates,thenthetickcommandwillusuallyalsoupdatetheview.Seethelatersection,ViewUpdates.
![Page 121: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/121.jpg)
Whentotick
Usereset-ticksattheendofyoursetupprocedure.
Usetickattheendofyourgoprocedure.
to setup clear-all create-turtles 10 reset-ticksend
to go ask turtles [ fd 1 ] tickend
Fractionalticks
Inmostmodels,thetickcounterstartsat0andgoesup1atatime,fromintegertointeger.Butit'salsopossibleforthetickcountertotakeonin-betweenfloatingpointvalues.
Toadvancethetickcounterbyafractionalamount,usethetick-advancecommand.Thiscommandtakesanumericinputspecifyinghowfartoadvancethetickcounter.
Atypicaluseoffractionalticksistoapproximatecontinuousorcurvedmotion.See,forexample,theGasLabmodelsintheModelsLibrary(underChemistry&Physics).Thesemodelscalculatetheexacttimeatwhichafutureeventistooccur,thenadvancethetickcountertoexactlythattime.
Colors
NetLogorepresentscolorsindifferentways.Acolorcanbenumberintherange0to140,withtheexceptionof140itself.BelowisachartshowingtherangeofsuchcolorsyoucanuseinNetLogo.
Thechartshowsthat:
![Page 122: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/122.jpg)
Someofthecolorshavenames.(Youcanusethesenamesinyourcode.)Everynamedcolorexceptblackandwhitehasanumberendingin5.Oneithersideofeachnamedcoloraredarkerandlightershadesofthecolor.0ispureblack.9.9ispurewhite.10,20,andsoonareallsodarktheyareverynearlyblack.19.9,29.9andsoonareallsolighttheyareverynearlywhite.
CodeExample:ThecolorchartwasmadeinNetLogowiththeColorChartExamplemodel.
Ifyouuseanumberoutsidethe0to140range,NetLogowillrepeatedlyaddorsubtract140fromthenumberuntilitisinthe0to140range.Forexample,25isorange,so165,305,445,andsoonareorangetoo,andsoare-115,-255,-395,etc.Thiscalculationisdoneautomaticallywheneveryousettheturtlevariablecolororthepatchvariablepcolor.Shouldyouneedtoperformthiscalculationinsomeothercontext,usethewrap-colorprimitive.
Ifyouwantacolorthat'snotonthechart,moreexistbetweentheintegers.Forexample,26.5isashadeoforangehalfwaybetween26and27.Thisdoesn'tmeanyoucanmakeanycolorinNetLogo;theNetLogocolorspaceisonlyasubsetofallpossiblecolors.Itcontainsonlyafixedsetofdiscretehues(onehueperrowofthechart).Startingfromoneofthosehues,youcaneitherdecreaseitsbrightness(darkenit)ordecreaseitssaturation(lightenit),butyoucannotdecreasebothbrightnessandsaturation.Also,onlythefirstdigitafterthedecimalpointissignificant.Thus,colorvaluesareroundeddowntothenext0.1,soforexample,there'snovisibledifferencebetween26.5and26.52or26.58.
Colorprimitives
Thereareafewprimitivesthatarehelpfulforworkingwithcolors.
Wehavealreadymentionedthewrap-colorprimitive.
Thescale-colorprimitiveisusefulforconvertingnumericdataintocolors.
shade-of?willtellyouiftwocolorsareboth"shades"ofthesamebasichue.Forexample,shade-of?orange 27istrue,because27isalightershadeoforange.
CodeExample:Scale-colorExampledemonstratesthescale-colorreporter.
RGBandRGBAColors
NetLogoalsorepresentscolorsasRGB(red/green/blue)listsandRGBA(red/green/blue/alpha)lists.WhenusingRGBcolorsthefullrangeofcolorsisavailabletoyou.RGBAcolorsallowallthecolorsthatRGBallowsandyoucanalsovarythetransparencyofacolor.RGBandRGBAlistsaremadeupofthreeorfourintegers,respectively,between0and255ifanumberisoutsidethatrange255isrepeatedlysubtracteduntilitisintherange.YoucansetanycolorvariablesinNetLogo(colorforturtlesandlinksandpcolorforpatches)toanRGBlistandthatagentwillberenderedappropriately.Soyoucansetthecolorofpatch00topureredusingthefollowingcode:
set pcolor [255 0 0]
Turtles,links,andlabelscanallcontainRGBAlistsastheircolorvariables,however,patchescannothaveRGBApcolorsYoucansetthecolorofaturtletobeapproximatelyhalftransparentpureredwiththefollowingcode:
set color [255 0 0 125]
YoucanconvertfromaNetLogocolortoRGBorHSB(hue/saturation/brightness)usingextract-hsbandextract-rgb.YoucanusergbtogeneratergblistsandhsbtoconvertfromanHSBcolortoRGB.
SincemanycolorsaremissingfromtheNetLogocolorspace,approximate-hsbandapproximate-rgb
![Page 123: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/123.jpg)
oftencan'tgiveyoutheexactcoloryouaskfor,buttheytrytocomeascloseaspossible.
Example:youcanchangeanyturtlefromit'sexistingNetLogocolortoahalftransparentversionofthatcolorusing:
set color lput 125 extract-rgb color
CodeExamples:HSBandRGBExample(letsyouexperimentwiththeHSBandRGBcolorsystems),TransparencyExample
ColorSwatchesdialog
TheColorSwatchesdialoghelpsyouexperimentwithandchoosecolors.OpenitbychoosingColorSwatchesontheToolsMenu.
Whenyouclickonacolorswatch(oracolorbutton),thatcolorwillbeshownagainstothercolors.Inthebottomleft,thecodeforthecurrentlyselectedcolorisdisplayed(forexample,red + 2)soyoucancopyandpasteitintoyourcode.Onthebottomrighttherearethreeincrementoptions,1,0.5,and0.1.Thesenumbersindicatethedifferencebetweentwoadjacentswatches.Whentheincrementis1thereare10differentshadesineachrow;whentheincrementis0.1thereare100differentshadesineachrow.0.5isanintermediatesetting.
Ask
NetLogousestheaskcommandtogivecommandstoturtles,patches,andlinks.Allcodetoberunbyturtlesmustbelocatedinaturtle"context".Youcanestablishaturtlecontextinanyofthreeways:
Inabutton,bychoosing"Turtles"fromthepopupmenu.Anycodeyouputinthebuttonwillberunbyallturtles.IntheCommandCenter,bychoosing"Turtles"fromthepopupmenu.Anycommandsyouenterwillberunbyalltheturtles.Byusingask turtles,hatch,orothercommandswhichestablishaturtlecontext.
Thesamegoesforpatches,links,andtheobserver,exceptthatyoucannotasktheobserver.Anycodethatisnotinsideanyaskisbydefaultobservercode.
![Page 124: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/124.jpg)
Here'sanexampleoftheuseofaskinaNetLogoprocedure:
to setup clear-all create-turtles 100 ;; create 100 turtles with random headings ask turtles [ set color red ;; turn them red fd 50 ] ;; spread them around ask patches [ if pxcor > 0 ;; patches on the right side [ set pcolor green ] ] ;; of the view turn green reset-ticksend
ThemodelsintheModelsLibraryarefullofotherexamples.AgoodplacetostartlookingisintheCodeExamplessection.
Usually,theobserverusesasktoaskallturtles,allpatchesoralllinkstoruncommands.Youcanalsouseasktohaveanindividualturtle,patchorlinkruncommands.Thereportersturtle,patch,linkandpatch-atareusefulforthistechnique.Forexample:
to setup clear-all crt 3 ;; make 3 turtles ask turtle 0 ;; tell the first one... [ fd 1 ] ;; ...to go forward ask turtle 1 ;; tell the second one... [ set color green ] ;; ...to become green ask turtle 2 ;; tell the third one... [ rt 90 ] ;; ...to turn right ask patch 2 -2 ;; ask the patch at (2,-2) [ set pcolor blue ] ;; ...to become blue ask turtle 0 ;; ask the first turtle [ ask patch-at 1 0 ;; ...to ask patch to the east [ set pcolor red ] ] ;; ...to become red ask turtle 0 ;; tell the first turtle... [ create-link-with turtle 1 ] ;; ...make a link with the second ask link 0 1 ;; tell the link between turtle 0 and 1 [ set color blue ] ;; ...to become blue reset-ticksend
Everyturtlecreatedhasawhonumber.Thefirstturtlecreatedisnumber0,thesecondturtlenumber1,andsoforth.
Theturtleprimitivereportertakesawhonumberasaninput,andreportstheturtlewiththatwhonumber.Thepatchprimitivereportertakesvaluesforpxcorandpycorandreportsthepatchwiththosecoordinates.Thelinkprimitivetakestwoinputs,thewhonumbersofthetwoturtlesitconnects.Andthepatch-atprimitivereportertakesoffsets:distances,inthexandydirections,fromthefirstagent.Intheexampleabove,theturtlewithwhonumber0isaskedtogetthepatcheast(andnopatchesnorth)ofitself.
Youcanalsoselectasubsetofturtles,orasubsetofpatches,orasubsetoflinksandaskthemtodosomething.Thisinvolvesusingagentsets.Thenextsectionexplainsthemindetail.
Whenyouaskasetofagentstorunmorethanonecommand,eachagentmustfinishbeforethenextagentstarts.Oneagentrunsallofthecommands,thenthenextagentrunsallofthem,andsoon.Forexample,ifyouwrite:
ask turtles [ fd 1 set color red ]
firstoneturtlemovesandturnsred,thenanotherturtlemovesandturnsred,andsoon.
Butifyouwriteitthisway:
ask turtles [ fd 1 ]ask turtles [ set color red ]
![Page 125: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/125.jpg)
firstalltheturtlesmove,thentheyallturnred.
Agentsets
Anagentsetisexactlywhatitsnameimplies,asetofagents.Anagentsetcancontaineitherturtles,patchesorlinks,butnotmorethanonetypeatonce.
Anagentsetisnotinanyparticularorder.Infact,it'salwaysinarandomorder.Andeverytimeyouuseit,theagentsetisinadifferentrandomorder.Thishelpsyoukeepyourmodelfromtreatinganyparticularturtles,patchesorlinksdifferentlyfromanyothers(unlessyouwantthemtobe).Sincetheorderisrandomeverytime,nooneagentalwaysgetstogofirst.
You'veseentheturtlesprimitive,whichreportstheagentsetofallturtles,thepatchesprimitive,whichreportstheagentsetofallpatchesandthelinksprimitivewhichreportstheagentsetofalllinks.
Butwhat'spowerfulabouttheagentsetconceptisthatyoucanconstructagentsetsthatcontainonlysometurtles,somepatchesorsomelinks.Forexample,alltheredturtles,orthepatcheswithpxcorevenlydivisiblebyfive,ortheturtlesinthefirstquadrantthatareonagreenpatchorthelinksconnectedtoturtle0.Theseagentsetscanthenbeusedbyaskorbyvariousreportersthattakeagentsetsasinputs.
Onewayistouseturtles-hereorturtles-at,tomakeanagentsetcontainingonlytheturtlesonmypatch,oronlytheturtlesonsomeotherpatchatsomexandyoffsets.There'salsoturtles-onsoyoucangetthesetofturtlesstandingonagivenpatchorsetofpatches,orthesetofturtlesstandingonthesamepatchasagiventurtleorsetofturtles.
Herearesomemoreexamplesofhowtomakeagentsets:
;; all other turtles:other turtles;; all other turtles on this patch:other turtles-here;; all red turtles:turtles with [color = red];; all red turtles on my patchturtles-here with [color = red];; patches on right side of viewpatches with [pxcor > 0];; all turtles less than 3 patches awayturtles in-radius 3;; the four patches to the east, north, west, and southpatches at-points [[1 0] [0 1] [-1 0] [0 -1]];; shorthand for those four patchesneighbors4;; turtles in the first quadrant that are on a green patchturtles with [(xcor > 0) and (ycor > 0) and (pcolor = green)];; turtles standing on my neighboring four patchesturtles-on neighbors4;; all the links connected to turtle 0[my-links] of turtle 0
Notetheuseofothertoexcludethisagent.Thisiscommon.
Onceyouhavecreatedanagentset,herearesomesimplethingsyoucando:
UseasktomaketheagentsintheagentsetdosomethingUseany?toseeiftheagentsetisemptyUseall?toseeifeveryagentinanagentsetsatisfiesacondition.Usecounttofindoutexactlyhowmanyagentsareintheset
Andherearesomemorecomplexthingsyoucando:
Pickarandomagentfromthesetusingone-of.Forexample,wecanmakearandomlychosenturtleturngreen:
![Page 126: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/126.jpg)
ask one-of turtles [ set color green ]
Ortellarandomlychosenpatchtosproutanewturtle:
ask one-of patches [ sprout 1 ]
Usethemax-one-oformin-one-ofreporterstofindoutwhichagentisthemostorleastalongsomescale.Forexample,toremovetherichestturtle,youcouldsay
ask max-one-of turtles [sum assets] [ die ]
Makeahistogramoftheagentsetusingthehistogramcommand(incombinationwithof).Useoftomakealistofvalues,oneforeachagentintheagentset.ThenuseoneofNetLogo'slistprimitivestodosomethingwiththelist.(Seethe"Lists"sectionbelow.)Forexample,tofindouthowrichturtlesareontheaverage,youcouldsay
show mean [sum assets] of turtles
Useturtle-set,patch-setandlink-setreporterstomakenewagentsetsbygatheringtogetheragentsfromavarietyofpossiblesources.Useno-turtles,no-patchesandno-linksreporterstomakeemptyagentsets.Checkwhethertwoagentsetsareequalusing=or!=.Usemember?toseewhetheraparticularagentisamemberofanagentset.
Thisonlyscratchesthesurface.SeetheModelsLibraryformanymoreexamples,andconsulttheNetLogoDictionaryformoreinformationaboutalloftheagentsetprimitives.
MoreexamplesofusingagentsetsareprovidedintheindividualentriesfortheseprimitivesintheNetLogoDictionary.
Specialagentsets
Theagentsetsturtlesandlinkshavespecialbehaviorbecausetheyalwaysholdthesetsofallturtlesandalllinks.Therefore,theseagentsetscangrow.
Thefollowinginteractionshowsthespecialbehavior.AssumetheCodetabhasglobals [g].Then:
observer> clear-allobserver> create-turtles 5observer> set g turtlesobserver> print count g5observer> create-turtles 5observer> print count g10observer> set g turtle-set turtlesobserver> print count g10observer> create-turtles 5observer> print count g10observer> print count turtles15
Theturtlesagentsetgrowswhennewturtlesareborn,butotheragentsetsdon'tgrow.IfIwriteturtle-set turtles,Igetanew,normalagentsetcontainingjusttheturtlesthatcurrentlyexist.Newturtlesdon'tjoinwhenthey'reborn.
Breedagentsetsarespecialinthesamewayasturtlesandlinks.Breedsareintroducedandexplainedbelow.
Agentsetsandlists
![Page 127: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/127.jpg)
Earlier,wesaidthatagentsetsarealwaysinrandomorder,adifferentrandomordereverytime.Ifyouneedyouragentstodosomethinginafixedorder,youneedtomakealistoftheagentsinstead.SeetheListssectionbelow.
CodeExample:AskOrderingExample
Breeds
NetLogoallowsyoutodefinedifferent"breeds"ofturtlesandbreedsoflinks.Onceyouhavedefinedbreeds,youcangoonandmakethedifferentbreedsbehavedifferently.Forexample,youcouldhavebreedscalledsheepandwolves,andhavethewolvestrytoeatthesheeporyoucouldhavelinkbreedscalledstreetsandsidewalkswherefoottrafficisroutedonsidewalksandcartrafficisroutedonstreets.
Youdefineturtlebreedsusingthebreedkeyword,atthetopoftheCodetab,beforeanyprocedures:
breed [wolves wolf]breed [sheep a-sheep]
Youcanrefertoamemberofthebreedusingthesingularform,justliketheturtlereporter.Whenprinted,membersofthebreedwillbelabeledwiththesingularname.
Somecommandsandreportershavethepluralnameofthebreedinthem,suchascreate-<breeds>.Othershavethesingularnameofthebreedinthem,suchas<breed>
Theorderinwhichbreedsaredeclaredisalsotheorderinwhichtheyarelayeredintheview.Sobreedsdefinedlaterwillappearontopofbreedsdefinedearlier;inthisexample,sheepwillbedrawnoverwolves.
Whenyoudefineabreedsuchassheep,anagentsetforthatbreedisautomaticallycreated,sothatalloftheagentsetcapabilitiesdescribedaboveareimmediatelyavailablewiththesheepagentset.
Thefollowingnewprimitivesarealsoautomaticallyavailableonceyoudefineabreed:create-sheep,hatch-sheep,sprout-sheep,sheep-here,sheep-at,sheep-on,andis-a-sheep?.
Also,youcanusesheep-owntodefinenewturtlevariablesthatonlyturtlesofthegivenbreedhave.(It'sallowedformorethanonebreedtoownthesamevariable.)
Aturtle'sbreedagentsetisstoredinthebreedturtlevariable.Soyoucantestaturtle'sbreed,likethis:
if breed = wolves [ ... ]
Notealsothatturtlescanchangebreeds.Awolfdoesn'thavetoremainawolfitswholelife.Let'schangearandomwolfintoasheep:
ask one-of wolves [ set breed sheep ]
Theset-default-shapeprimitiveisusefulforassociatingcertainturtleshapeswithcertainbreeds.Seethesectiononshapesbelow.
Whonumbersareassignedirrespectiveofbreeds.Ifyoualreadyhaveafrog 0,thenthefirstmousewillbemouse 1,notmouse 0,sincethewhonumber0isalreadytaken.
Hereisaquickexampleofusingbreeds:
breed [mice mouse]breed [frogs frog]mice-own [cheese]to setup clear-all create-mice 50
![Page 128: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/128.jpg)
[ set color white set cheese random 10 ] create-frogs 50 [ set color green ] reset-ticksend
CodeExample:BreedsandShapesExample
Linkbreeds
Linkbreedsareverysimilartoturtlebreeds,however,thereareafewdifferences.
Whenyoudeclarealinkbreedyoumustdeclarewhetheritisabreedofdirectedorundirectedlinksbyusingthedirected-link-breedandundirected-link-breedkeywords.
directed-link-breed [streets street]undirected-link-breed [friendships friendship]
Onceyouhavecreatedabreededlinkyoucannotcreateunbreededlinksandviceversa.(Youcan,however,havedirectedandundirectedlinksinthesameworld,justnotinthesamebreed)
Unlikewithturtlebreedsthesingularbreednameisrequiredforlinkbreeds,asmanyofthelinkcommandsandreportsusethesingularname,suchas<link-breed>-neighbor?.
Thefollowingprimitivesarealsoautomaticallyavailableonceyoudefineadirectedlinkbreed:create-street-fromcreate-streets-fromcreate-street-tocreate-streets-toin-street-neighbor?in-street-neighborsin-street-frommy-in-streetsmy-out-streetsout-street-neighbor?out-street-neighborsout-street-to
Andthefollowingareautomaticallyavailablewhenyoudefineanundirectedlinkbreed:create-friendship-withcreate-friendships-withfriendship-neighbor?friendship-neighborsfriendship-withmy-friendships
Multiplelinkbreedsmaydeclarethesame-ownvariable,butavariablemaynotbesharedbetweenaturtlebreedandalinkbreed.
Justaswithturtlebreedstheorderinwhichlinkbreedsaredeclareddefinestheorderinwhichthelinksaredrawn,sothefriendshipswillalwaysbeontopofstreets(ifforsomereasonthesebreedswereinthesamemodel).Youcanalsouse<link-breeds>-owntodeclarevariablesofeachlinkbreedseparately.
Youcanchangethebreedofalinkwithset breed.(However,youcannotchangeabreededlinktoanunbreededone,topreventhavingbreededandunbreededlinksinthesameworld.)
ask one-of friendships [ set breed streets ]ask one-of friendships [ set breed links ] ;; produces a runtime error
set-default-shapemayalsobeusedwithlinkbreedstoassociateitwithaparticularlinkshape.
CodeExample:LinkBreedsExample
Buttons
Buttonsintheinterfacetabprovideaneasywaytocontrolthemodel.Typicallyamodelwillhaveatleasta"setup"button,tosetuptheinitialstateoftheworld,anda"go"buttontomakethemodelruncontinuously.Somemodelswillhaveadditionalbuttonsthatperformotheractions.
![Page 129: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/129.jpg)
AbuttoncontainssomeNetLogocode.Thatcodeisrunwhenyoupressthebutton.
Abuttonmaybeeithera"oncebutton",ora"foreverbutton".Youcancontrolthisbyeditingthebuttonandcheckingoruncheckingthe"Forever"checkbox.Oncebuttonsruntheircodeonce,thenstopandpopbackup.Foreverbuttonskeeprunningtheircodeoverandoveragain.
Aforeverbuttonstopsiftheuserpressesthebuttonagaintostopit.Thebuttonwaitsuntilthecurrentiterationhasfinished,thenpopsup.
Aforeverbuttoncanalsobestoppedfromcode.Iftheforeverbuttondirectlycallsaprocedure,thenwhenthatprocedurestops,thebuttonstops.(Inaturtleorpatchforeverbutton,thebuttonwon'tstopuntileveryturtleorpatchstops--asingleturtleorpatchdoesn'thavethepowertostopthewholebutton.)
Normally,abuttonislabeledwiththecodethatitruns.Forexample,abuttonthatsays"go"onitusuallycontainsthecode"go",whichmeans"runthegoprocedure".(ProceduresaredefinedintheCodetab;seebelow.)Butyoucanalsoeditabuttonandentera"displayname"forthebutton,whichisatextthatappearsonthebuttoninsteadofthecode.Youmightusethisfeatureifyouthinktheactualcodewouldbeconfusingtoyourusers.
Whenyouputcodeinabutton,youmustalsospecifywhichagentsyouwanttorunthatcode.Youcanchoosetohavetheobserverrunthecode,orallturtles,orallpatches,oralllinks.(Ifyouwantthecodetoberunbyonlysometurtlesorsomepatches,youcouldmakeanobserverbutton,andthenhavetheobserverusetheaskcommandtoaskonlysomeoftheturtlesorpatchestodosomething.)
Whenyoueditabutton,youhavetheoptiontoassignan"actionkey".Thismakesthatkeyonthekeyboardbehavejustlikeabuttonpress.Ifthebuttonisaforeverbutton,itwillstaydownuntilthekeyispressedagain(orthebuttonisclicked).Actionkeysareparticularlyusefulforgamesoranymodelwhererapidtriggeringofbuttonsisneeded.
Buttonstaketurns
Morethanonebuttoncanbepressedatatime.Ifthishappens,thebuttons"taketurns",whichmeansthatonlyonebuttonrunsatatime.Eachbuttonrunsitscodeallthewaythroughoncewhiletheotherbuttonswait,thenthenextbuttongetsitsturn.
Inthefollowingexamples,"setup"isaoncebuttonand"go"isaforeverbutton.
Example#1:Theuserpresses"setup",thenpresses"go"immediately,beforethe"setup"haspoppedbackup.Result:"setup"finishesbefore"go"starts.
Example#2:Whilethe"go"buttonisdown,theuserpresses"setup".Result:the"go"buttonfinishesitscurrentiteration.Thenthe"setup"buttonruns.Then"go"startsrunningagain.
Example#3:Theuserhastwoforeverbuttonsdownatthesametime.Result:firstonebuttonrunsitscodeallthewaythrough,thentheotherrunsitscodeallthewaythrough,andsoon,alternating.
Notethatifonebuttongetsstuckinaninfiniteloop,thennootherbuttonswillrun.
Turtle,patch,andlinkforeverbuttons
Thereisasubtledifferencebetweenputtingcommandsinaturtle,patchorlinkforeverbutton,andputtingthesamecommandsinanobserverbuttonthatdoesask turtles,ask patchesorask links.An"ask"doesn'tcompleteuntilalloftheagentshavefinishedrunningallofthecommandsinthe"ask".Sotheagents,astheyallrunthecommandsconcurrently,canbeoutofsyncwitheachother,buttheyallsyncupagainattheendoftheask.Thesameisn'ttrueofturtle,patchandlinkforeverbuttons.Sinceaskwasnotused,eachturtleorpatchrunsthegivencodeoverandoveragain,sotheycanbecome(andremain)outofsyncwitheachother.
Atpresent,thiscapabilityisveryrarelyusedinthemodelsinourModelsLibrary.AmodelthatdoesusethecapabilityistheTermitesmodel,intheBiologysectionofSampleModels.The"go"buttonisaturtleforeverbutton,soeachtermiteproceedsindependentlyofeveryothertermite,andtheobserverisnotinvolvedatall.Thismeansthatif,forexample,youwantedtoaddticksand/oraplottothemodel,youwouldneedtoaddasecondforeverbutton(anobserverforeverbutton),andrunbothforeverbuttonsat
![Page 130: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/130.jpg)
thesametime.NotealsothatamodellikethiscannotbeusedwithBehaviorSpace.
CodeExample:StateMachineExampleshowshowTermitescanberecodedinatick-basedway,withoutusingaturtleforeverbutton.
Atpresent,NetLogohasnowayforoneforeverbuttontostartanother.Buttonsareonlystartedwhenyoupressthem.
Lists
Inthesimplestmodels,eachvariableholdsonlyonepieceofinformation,usuallyanumberorastring.Listsletyoustoremultiplepiecesofinformationinasinglevaluebycollectingthatinformationinalist.Eachvalueinthelistcanbeanytypeofvalue:anumber,orastring,anagentoragentset,orevenanotherlist.
ListsallowfortheconvenientpackagingofinformationinNetLogo.Ifyouragentscarryoutarepetitivecalculationonmultiplevariables,itmightbeeasiertohavealistvariable,insteadofmultiplenumbervariables.Severalprimitivessimplifytheprocessofperformingthesamecomputationoneachvalueinalist.
TheNetLogoDictionaryhasasectionthatlistsallofthelist-relatedprimitives.
Constantlists
Youcanmakealistbysimplyputtingthevaluesyouwantinthelistbetweenbrackets,likethis:setmylist [2 4 6 8].Notethattheindividualvaluesareseparatedbyspaces.Youcanmakeliststhatcontainnumbersandstringsthisway,aswellaslistswithinlists,forexample[[2 4] [3 5]].
Theemptylistiswrittenbyputtingnothingbetweenthebrackets,likethis:[].
Buildinglistsonthefly
Ifyouwanttomakealistinwhichthevaluesaredeterminedbyreporters,asopposedtobeingaseriesofconstants,usethelistreporter.Thelistreporteracceptstwootherreporters,runsthem,andreportstheresultsasalist.
IfIwantedalisttocontaintworandomvalues,Imightusethefollowingcode:
set random-list list (random 10) (random 20)
Thiswillsetrandom-listtoanewlistoftworandomintegerseachtimeitruns.
Tomakelongerorshorterlists,youcanusethelistreporterwithfewerormorethantwoinputs,butinordertodoso,youmustenclosetheentirecallinparentheses,e.g.:
(list random 10)(list random 10 random 20 random 30)
Formoreinformation,seeVaryingnumberofinputs.
Somekindsoflistsaremosteasilybuiltusingthen-valuesreporter,whichallowsyoutoconstructalistofaspecificlengthbyrepeatedlyrunningagivenreporter.Youcanmakealistofthesamevaluerepeated,orallthenumbersinarange,oralotofrandomnumbers,ormanyotherpossibilities.Seedictionaryentryfordetailsandexamples.
Theofprimitiveletsyouconstructalistfromanagentset.Itreportsalistcontainingeachagent'svalueforthegivenreporter.(Thereportercouldbeasimplevariablename,oramorecomplexexpression--evenacalltoaproceduredefinedusingto-report.)Acommonidiomis
![Page 131: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/131.jpg)
max [...] of turtlessum [...] of turtles
andsoon.
Youcancombinetwoormorelistsusingthesentencereporter,whichconcatenateslistsbycombiningtheircontentsintoasingle,largerlist.Likelist,sentencenormallytakestwoinputs,butcanacceptanynumberofinputsifthecallissurroundedbyparentheses.
Changinglistitems
Technically,listscan'tbemodified,butyoucanconstructnewlistsbasedonoldlists.Ifyouwantthenewlisttoreplacetheoldlist,useset.Forexample:
set mylist [2 7 5 Bob [3 0 -2]]; mylist is now [2 7 5 Bob [3 0 -2]]set mylist replace-item 2 mylist 10; mylist is now [2 7 10 Bob [3 0 -2]]
Thereplace-itemreportertakesthreeinputs.Thefirstinputspecifieswhichiteminthelististobechanged.0meansthefirstitem,1meanstheseconditem,andsoforth.
Toaddanitem,say42,totheendofalist,usethelputreporter.(fputaddsanitemtothebeginningofalist.)
set mylist lput 42 mylist; mylist is now [2 7 10 Bob [3 0 -2] 42]
Butwhatifyouchangedyourmind?Thebut-last(blforshort)reporterreportsallthelistitemsbutthelast.
set mylist but-last mylist; mylist is now [2 7 10 Bob [3 0 -2]]
Supposeyouwanttogetridofitem0,the2atthebeginningofthelist.
set mylist but-first mylist; mylist is now [7 10 Bob [3 0 -2]]
Supposeyouwantedtochangethethirditemthat'snestedinsideitem3from-2to9?Thekeyistorealizethatthenamethatcanbeusedtocallthenestedlist[30-2]isitem 3 mylist.Thenthereplace-itemreportercanbenestedtochangethelist-within-a-list.Theparenthesesareaddedforclarity.
set mylist (replace-item 3 mylist (replace-item 2 (item 3 mylist) 9)); mylist is now [7 10 Bob [3 0 9]]
Iteratingoverlists
Ifyouwanttodosomeoperationoneachiteminalistinturn,theforeachcommandandthemapreportermaybehelpful.
foreachisusedtorunacommandorcommandsoneachiteminalist.Ittakesaninputlistandacommandnameorblockofcommands,likethis:
foreach [1 2 3] show=> 1=> 2=> 3foreach [2 4 6] [ n -> crt n
![Page 132: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/132.jpg)
show (word "created " n " turtles") ]=> created 2 turtles=> created 4 turtles=> created 6 turtles
Intheblock,thevariablenholdsthecurrentvaluefromtheinputlist.
Herearesomemoreexamplesofforeach:
foreach [1 2 3] [ steps -> ask turtles [ fd steps ] ];; turtles move forward 6 patchesforeach [true false true true] [ should-move? -> ask turtles [ if should-move? [ fd 1 ] ] ];; turtles move forward 3 patches
mapissimilartoforeach,butitisareporter.Ittakesaninputlistandareporternameorreporterblock.Notethatunlikeforeach,thereportercomesfirst,likethis:
show map round [1.2 2.2 2.7];; prints [1 2 3]
mapreportsalistcontainingtheresultsofapplyingthereportertoeachitemintheinputlist.Again,usethevariablenamedintheanonymousprocedure(xintheexamplesbelow)torefertothecurrentiteminthelist.
Hereareacouplemoreexamplesofmap:
show map [ x -> x < 0 ] [1 -1 3 4 -2 -10];; prints [false true false false true true]show map [ x -> x * x ] [1 2 3];; prints [1 4 9]
Besidesmapandforeach,otherprimitivesforprocessingwholelistsinaconfigurablewayincludefilter,reduce,andsort-by.
Theseprimitivesaren'talwaysthesolutionforeverysituationinwhichyouwanttooperateonanentirelist.Insomesituations,youmayneedtousesomeothertechniquesuchasaloopusingrepeatorwhile,orarecursiveprocedure.
Theblocksofcodewe'regivingtomapandforeachintheseexamplesareactuallyanonymousprocedures.AnonymousproceduresareexplainedinmoredetailinAnonymousprocedures,below.
Varyingnumberofinputs
Somecommandsandreportersinvolvinglistsandstringsmaytakeavaryingnumberofinputs.Inthesecases,inordertopassthemanumberofinputsotherthantheirdefault,theprimitiveanditsinputsmustbesurroundedbyparentheses.Herearesomeexamples:
show list 1 2=> [1 2]show (list 1 2 3 4)=> [1 2 3 4]show (list)=> []
Notethateachofthesespecialprimitiveshasadefaultnumberofinputsforwhichnoparenthesesarerequired.Theprimitiveswhichhavethiscapabilityarelist,word,sentence,map,foreach,run,andrunresult.
Listsofagents
Earlier,wesaidthatagentsetsarealwaysinrandomorder,adifferentrandomordereverytime.Ifyouneedyouragentstodosomethinginafixedorder,youneedtomakealistoftheagentsinstead.
Therearetwoprimitivesthathelpyoudothis,sortandsort-by.
![Page 133: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/133.jpg)
Bothsortandsort-bycantakeanagentsetasinput.Theresultisalwaysanewlist,containingthesameagentsastheagentsetdid,butinaparticularorder.
Ifyouusesortonanagentsetofturtles,theresultisalistofturtlessortedinascendingorderbywhonumber.
Ifyouusesortonanagentsetofpatches,theresultisalistofpatchessortedleft-to-right,top-to-bottom.
Ifyouusesortonanagentsetoflinks,theresultisalistoflinks,sortedinascendingorderfirstbyend1thenbyend2anyremainingtiesareresolvedbybreedintheordertheyaredeclaredintheCodetab.
Ifyouneeddescendingorderinstead,youcancombinereversewithsort,forexamplereverse sortturtles.
Ifyouwantyouragentstobeorderedbysomeothercriterionthanthestandardonessortuses,you'llneedtousesort-byinstead.
Here'sanexample:
sort-by [ [a b] -> [size] of a < [size] of b ] turtles
Thisreturnsalistofturtlessortedinascendingorderbytheirturtlevariablesize.
There'sacommonpatterntogetalistofagentsinarandomorder,usingacombinationofofandself,intherarecasethatyoucannotjustuseask:
[self] of my-agentset
Askingalistofagents
Onceyouhavealistofagents,youmightwanttoaskthemeachtodosomething.Todothis,usetheforeachandaskcommandsincombination,likethis:
foreach sort turtles [ the-turtle -> ask the-turtle [ ... ]]
Thiswillaskeachturtleinascendingorderbywhonumber.Substitute"patches"for"turtles"toaskpatchesinleft-to-right,top-to-bottomorder.
Notethatyoucan'tuseaskdirectlyonalistofturtles.askonlyworkswithagentsetsandsingleagents.
Performanceoflists
ThedatastructureunderlyingNetLogo'slistsisasophisticatedtree-baseddatastructureonwhichmostoperationsruninnear-constanttime.Thatincludesfput,lput,butfirst,butlast,length,item,andreplace-item.
Oneexceptiontothefast-performanceruleisthatconcatenatingtwolistswithsentencerequirestraversingandcopyingthewholesecondlist.(Thismaybefixedinafutureversion.)
Technically,"near-constanttime"isactuallylogarithmictime,proportionaltothedepthoftheunderlyingtree,butthesetreeshavelargenodesandahighbranchingfactor,sotheyarenevermorethanafewlevelsdeep.Thismeansthatchangescanbemadeinatmostafewsteps.Thetreesareimmutable,buttheysharestructurewitheachother,sothewholetreedoesn'tneedtobecopiedtomakeachangedversion.
TheactualdatastructureusedistheimmutableVectorclassfromtheScalacollectionslibrary.Theseare32-widehasharraymappedtries,asimplementedbyTiarkRompf,basedinpartonworkbyPhilBagwellandRichHickey.
![Page 134: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/134.jpg)
Math
AllnumbersinNetLogoarestoredinternallyasdoubleprecisionfloatingpointnumbers,asdefinedintheIEEE754standard.Theyare64bitnumbersconsistingofonesignbit,an11-bitexponent,anda52-bitmantissa.SeetheIEEE754standardfordetails.
An"integer"inNetLogoissimplyanumberthathappenstohavenofractionalpart.Nodistinctionismadebetween3and3.0;theyarethesamenumber.(Thisisthesameashowmostpeopleusenumbersineverydaycontexts,butdifferentfromsomeprogramminglanguages.Somelanguagestreatintegersandfloatingpointnumbersasdistincttypes.)
IntegersarealwaysprintedbyNetLogowithoutthetrailing".0":
show 1.5 + 1.5observer: 3
Ifanumberwithafractionalpartissuppliedinacontextwhereanintegerisexpected,thefractionalpartissimplydiscarded.Soforexample,crt 3.5createsthreeturtles;theextra0.5isignored.
Therangeofintegersis+/-9007199254740992(2^53,about9quadrillion).Calculationsthatexceedthisrangewillnotcauseruntimeerrors,butprecisionwillbelostwhentheleastsignificant(binary)digitsareroundedoffinorderfitthenumberinto64bits.Withverylargenumbers,thisroundingcanresultinimpreciseanswerswhichmaybesurprising:
show 2 ^ 60 + 1 = 2 ^ 60=> true
Calculationswithsmallernumberscanalsoproducesurprisingresultsiftheyinvolvefractionalquantities,sincenotallfractionscanbepreciselyrepresentedandroundoffmayoccur.Forexample:
show 1 / 6 + 1 / 6 + 1 / 6 + 1 / 6 + 1 / 6 + 1 / 6=> 0.9999999999999999show 1 / 9 + 1 / 9 + 1 / 9 + 1 / 9 + 1 / 9 + 1 / 9 + 1 / 9 + 1 / 9 + 1 / 9=> 1.0000000000000002
Anyoperationwhichproducesthespecialquantities"infinity"or"notanumber"willcausearuntimeerror.
Scientificnotation
VerylargeorverysmallfloatingpointnumbersaredisplayedbyNetLogousing"scientificnotation".Examples:
show 0.000000000001=> 1.0E-12show 50000000000000000000=> 5.0E19
NumbersinscientificnotationaredistinguishedbythepresenceoftheletterE(for"exponent").Itmeans"timestentothepowerof",soforexample,1.0E-12means1.0times10tothe-12power:
show 1.0 * 10 ^ -12=> 1.0E-12
YoucanalsousescientificnotationyourselfinNetLogocode:
show 3.0E6=> 3000000show 8.123456789E6=> 8123456.789show 8.123456789E7
![Page 135: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/135.jpg)
=> 8.123456789E7show 3.0E16=> 3.0E16show 8.0E-3=> 0.0080show 8.0E-4=> 8.0E-4
Theseexamplesshowthatnumberswithfractionalpartsaredisplayedusingscientificnotationiftheexponentislessthan-3orgreaterthan6.NumbersoutsideofNetLogo'sintegerrangeof-9007199254740992to9007199254740992(+/-2^53)arealsoalwaysshowninscientificnotation:
show 2 ^ 60=> 1.15292150460684698E18
Whenenteringanumber,theletterEmaybeeitherupperorlowercase.Whenprintinganumber,NetLogoalwaysusesanuppercaseE:
show 4.5e20=> 4.5E20
Floatingpointaccuracy
BecausenumbersinNetLogoaresubjecttothelimitationsofhowfloatingpointnumbersarerepresentedinbinary,youmaygetanswersthatareslightlyinaccurate.Forexample:
show 0.1 + 0.1 + 0.1=> 0.30000000000000004show cos 90=> 6.123233995736766E-17
Thisisaninherentissuewithfloatingpointarithmetic;itoccursinallprogramminglanguagesthatusefloatingpointnumbers.
Ifyouaredealingwithfixedprecisionquantities,forexampledollarsandcents,acommontechniqueistouseonlyintegers(cents)internally,thendivideby100togetaresultindollarsfordisplay.
Ifyoumustusefloatingpointnumbers,theninsomesituationsyoumayneedtoreplaceastraightforwardequalitytestsuchasif x = 1 [ ... ]withatestthattoleratesslightimprecision,forexampleif abs (x - 1) < 0.0001 [ ... ] .
Also,theprecisionprimitiveishandyforroundingoffnumbersfordisplaypurposes.NetLogomonitorsroundthenumberstheydisplaytoaconfigurablenumberofdecimalplaces,too.
Randomnumbers
TherandomnumbersusedbyNetLogoarewhatiscalled"pseudo-random".(Thisistypicalincomputerprogramming.)Thatmeanstheyappearrandom,butareinfactgeneratedbyadeterministicprocess."Deterministic"meansthatyougetthesameresultseverytime,ifyoustartwiththesamerandom"seed".We'llexplaininaminutewhatwemeanby"seed".
Inthecontextofscientificmodeling,pseudo-randomnumbersareactuallydesirable.That'sbecauseit'simportantthatascientificexperimentbereproducible--soanyonecantryitthemselvesandgetthesameresultthatyougot.SinceNetLogousespseudo-randomnumbers,the"experiments"thatyoudowithitcanbereproducedbyothers.
Here'showitworks.NetLogo'srandomnumbergeneratorcanbestartedwithacertainseedvalue,whichmustbeanintegerintherange-2147483648to2147483647.Oncethegeneratorhasbeen"seeded"withtherandom-seedcommand,italwaysgeneratesthesamesequenceofrandomnumbersfromthenon.Forexample,ifyourunthesecommands:
random-seed 137
![Page 136: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/136.jpg)
show random 100show random 100show random 100
Youwillalwaysgetthenumbers79,89,and61inthatorder.
Note,however,thatyou'reonlyguaranteedtogetthosesamenumbersifyou'reusingthesameversionofNetLogo.SometimeswhenwemakeanewversionofNetLogotherandomnumbergeneratorchanges.(Presently,weuseageneratorknownastheMersenneTwister.)
Tocreateanumbersuitableforseedingtherandomnumbergenerator,usethenew-seedreporter.new-seedcreatesaseed,evenlydistributedoverthespaceofpossibleseeds,basedonthecurrentdateandtime.Itneverreportsthesameseedtwiceinarow.
CodeExample:RandomSeedExample
Ifyoudon'tsettherandomseedyourself,NetLogosetsittoavaluebasedonthecurrentdateandtime.Thereisnowaytofindoutwhatrandomseeditchose,soifyouwantyourmodelruntobereproducible,youmustsettherandomseedyourselfaheadoftime.
TheNetLogoprimitiveswith"random"intheirnames(random,random-float,andsoon)aren'ttheonlyonesthatusepseudo-randomnumbers.Manyotheroperationsalsomakerandomchoices.Forexample,agentsetsarealwaysinrandomorder,one-ofandn-ofchooseagentsrandomly,thesproutcommandcreatesturtleswithrandomcolorsandheadings,andthedownhillreporterchoosesarandompatchwhenthere'satie.Alloftheserandomchoicesaregovernedbytherandomseedaswell,somodelrunscanbereproducible.
Inadditiontotheuniformlydistributedrandomintegersandfloatingpointnumbersgeneratedbyrandomandrandom-float,NetLogoalsooffersseveralotherrandomdistributions.Seethedictionaryentriesforrandom-normal,random-poisson,random-exponential,andrandom-gamma.
Auxiliarygenerator
Coderunbybuttonsorfromthecommandcenterusesthemainrandomnumbergenerator.
Codeinmonitorsusesanauxiliaryrandomgenerator,soevenifamonitordoesacalculationthatusesrandomnumbers,theoutcomeofthemodelisnotaffected.Thesameistrueofcodeinsliders.
Localrandomness
Youmaywanttoexplicitlyspecifythatasectionofcodedoesnotaffectthestateofthemainrandomgenerator,sotheoutcomeofthemodelisnotaffected.Thewith-local-randomnesscommandisprovidedforthispurpose.SeeitsentryintheNetLogoDictionaryformoreinformation.
Turtleshapes
InNetLogo,turtleshapesarevectorshapes.Theyarebuiltupfrombasicgeometricshapes;squares,circles,andlines,ratherthanagridofpixels.Vectorshapesarefullyscalableandrotatable.NetLogocachesbitmapimagesofvectorshapessize1,1.5,and2inordertospeedupexecution.
Aturtle'sshapeisstoredinitsshapevariableandcanbesetusingthesetcommand.
Newturtleshaveashapeof"default".Theset-default-shapeprimitiveisusefulforchangingthedefaultturtleshapetoadifferentshape,orhavingadifferentdefaultturtleshapeforeachbreedofturtle.
Theshapesprimitivereportsalistofcurrentlyavailableturtleshapesinthemodel.Thisisusefulif,forexample,youwanttoassignarandomshapetoaturtle:
ask turtles [ set shape one-of shapes ]
![Page 137: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/137.jpg)
UsetheTurtleShapesEditortocreateyourownturtleshapes,ortoaddshapestoyourmodelfromourshapeslibrary,ortotransfershapesbetweenmodels.Formoreinformation,seetheShapesEditorsectionofthismanual.
Thethicknessofthelinesusedtodrawthevectorshapescanbecontrolledbythe__set-line-thicknessprimitive.
CodeExamples:BreedsandShapesExample,ShapeAnimationExample
Linkshapes
LinkShapesaresimilartoturtleshapes,onlyyouusetheLinkShapeEditortocreateandeditthem.Linkshapesconsistofbetween0and3lineswhichcanhavedifferentpatternsandadirectionindicatorthatiscomposedofthesameelementsasturtleshapes.Linksalsohaveashapevariablethatcanbesettoanylinkshapethatisinthemodel.Bydefaultlinkshavethe"default"shape,thoughyoucanchangethatusingset-default-shape.Thelink-shapesreporterreportsallthelinkshapesincludedinthecurrentmodel.
Thethicknessofthelinesinthelinkshapeiscontrolledbythethicknesslinkvariable.
Viewupdates
The"view"inNetLogoletsyouseetheagentsinyourmodelonyourcomputer'sscreen.Asyouragentsmoveandchange,youseethemmovingandchangingintheview.
Ofcourse,youcan'treallyseeyouragentsdirectly.TheviewisapicturethatNetLogopaints,showingyouhowyouragentslookataparticularinstant.Oncethatinstantpassesandyouragentsmoveandchangesomemore,thatpictureneedstoberepaintedtoreflectthenewstateoftheworld.Repaintingthepictureiscalled"updating"theview.
Whendoestheviewgetupdated?ThissectiondiscusseshowNetLogodecideswhentoupdatetheview,andhowyoucaninfluencewhenitgetsupdated.
NetLogoofferstwoupdatesmodes,"continuous"updatesand"tick-based"updates.YoucanswitchbetweenNetLogo'stwoviewupdatemodesusingapopupmenuatthetopoftheInterfacetab.
ContinuousupdatesarethedefaultwhenyoustartupNetLogoorstartanewmodel.NearlyeverymodelinourModelsLibrary,however,usestick-basedupdates.
Continuousupdatesaresimplest,buttick-basedupdatesgiveyoumorecontroloverwhenandhowoftenupdateshappen.
It'simportantexactlywhenanupdatehappens,becausewhenupdateshappendetermineswhatyouseeonthescreen.Ifanupdatecomesatanunexpectedtime,youmayseesomethingunexpected--perhapssomethingconfusingormisleading.
It'salsoimportanthowoftenupdateshappen,becauseupdatestaketime.ThemoretimeNetLogospendsupdatingtheview,thesloweryourmodelwillrun.Withfewerupdates,yourmodelrunsfaster.
Continuousupdates
Continuousupdatesareverysimple.Withcontinuousupdates,NetLogoupdatestheviewacertainnumberoftimespersecond--bydefault,30timesasecondwhenthespeedsliderisinthedefault,middlesetting.
Ifyoumovethespeedslidertoaslowersetting,NetLogowillupdatemorethan30timesasecond,effectivelyslowingdownthemodel.Onafastersetting,NetLogowillupdatelessthan30timesasecond.Onthefastestsetting,updateswillbeseparatedbyseveralseconds.
![Page 138: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/138.jpg)
Atextremelyslowsettings,NetLogowillbeupdatingsooftenthatyouwillseeyouragentsmoving(orchangingcolor,etc.)oneatatime.
Ifyouneedtotemporarilyshutoffcontinuousupdates,usetheno-displaycommand.Thedisplaycommandturnsupdatesbackon,andalsoforcesanimmediateupdate(unlesstheuserisfast-forwardingthemodelusingthespeedslider).
Tick-basedupdates
AsdiscussedaboveintheTickCountersection,inmanyNetLogomodels,timepassesindiscretesteps,called"ticks".Typically,youwanttheviewtoupdateoncepertick,betweenticks.That'sthedefaultbehaviorwithtick-basedupdates.
Ifyouwantadditionalviewupdates,youcanforceanupdateusingthedisplaycommand.(Theupdatemaybeskippediftheuserisfast-forwardingthemodelusingthespeedslider.)
Youdon'thavetousethetickcountertousetick-basedupdates.Ifthetickcounterneveradvances,theviewwillupdateonlywhenyouusethedisplaycommand.
Ifyoumovethespeedslidertoafastenoughsetting,eventuallyNetLogowillskipsomeoftheupdatesthatwouldordinarilyhavehappened.Movingthespeedslidertoaslowersettingdoesn'tcauseadditionalupdates;rather,itmakesNetLogopauseaftereachupdate.Theslowerthesetting,thelongerthepause.
Evenundertick-basedupdates,theviewalsoupdateswheneverabuttonintheinterfacepopsup(bothonceandforeverbuttons)andwhenacommandenteredintheCommandCenterfinishes.Soit'snotnecessarytoaddthedisplaycommandtooncebuttonsthatdon'tadvancethetickcounter.Manyforeverbuttonsthatdon'tadvancethetickcounterdoneedtousethedisplaycommand.AnexampleintheModelsLibraryistheLifemodel(underComputerScience->CellularAutomata).Theforeverbuttonsthatlettheuserdrawintheviewusethedisplaycommandsotheusercanseewhattheyaredrawing,eventhoughthetickcounterisnotadvancing.
Choosingamode
Advantagesoftick-basedupdatesovercontinuousupdatesinclude:
1. Consistent,predictableviewupdatebehaviorwhichdoesnotvaryfromcomputertocomputerorfromruntorun.
2. Continuousupdatescanconfusetheuserofyourmodelbylettingthemseemodelstatestheyaren'tsupposedtosee,whichmaybemisleading.
3. Sincesetupbuttonsdon'tadvancethetickcounter,theyareunaffectedbythespeedslider;thisisnormallythedesiredbehavior.
NearlyeverymodelinourModelsLibraryusestick-basedupdates.
Continuousupdatesareoccasionallyusefulforthoseraremodelsinwhichexecutionisnotdividedintoshort,discretephases.AnexampleintheModelsLibraryisTermites.(Seealso,however,theStateMachineExamplemodel,whichshowshowtore-codeTermitesusingticks.)
Evenformodelsthatwouldnormallybesettotick-basedupdates,itmaybeusefultoswitchtocontinuousupdatestemporarilyfordebuggingpurposes.Seeingwhat'sgoingonwithinatick,insteadofonlyseeingtheendresultofatick,couldhelpwithtroubleshooting.Afterswitchingtocontinuousupdates,youmaywanttousethespeedslidertoslowthemodeldownuntilyouseeyouragentsmovingoneatatime.Don'tforgettochangebacktotick-basedupdateswhenyouaredone,asthechoiceofupdatemodeissavedwiththemodel.
Changingtheupdatemodealsoaffectsmodelspeed.Updatingtheviewtakestime;oftenenforcingasingleupdatepertick(byusingtick-basedupdates)willmakeyourmodelfaster.Ontheotherhand,continuousupdateswillbefasterwhenrunningasingletickisfasterthandrawingaframeofthemodel.Mostmodelsrunfasterundertick-basedupdates,butforanexampleofamodelwhichisfasterwithcontinuousupdatesseethe"HeroesandCowards"librarymodel.
![Page 139: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/139.jpg)
Framerate
OneofthemodelsettingsinNetLogo's"Settings..."dialogis"Framerate"whichdefaultsto30framespersecond.
Theframeratesettingaffectsbothcontinuousupdatesandtick-basedupdates.
Withcontinuousupdates,thesettingdirectlydeterminesthefrequencyofupdates.
Withtick-basedupdates,thesettingisaceilingonhowmanyupdatespersecondyouget.Iftheframerateis30,thenNetLogowillensurethatthemodelneverrunsfasterthanthatwhenthespeedsliderisinthedefaultposition.Ifanyframetakeslessthan1/30ofasecondtocomputeanddisplay,NetLogowillpauseandwaituntilthefull1/30ofasecondhaspassedbeforecontinuing.
Theframeratesettingsletsyousetwhatyouconsidertobeanormalspeedforyourmodel.Thenyou,ortheuserofyourmodel,canusethespeedslidertotemporarilygetafasterorslowerspeed.
Plotting
NetLogo'splottingfeaturesletyoucreateplotstohelpyouunderstandwhat'sgoingoninyourmodel.
Beforeyoucanplot,youneedtocreateoneormoreplotsintheInterfacetab.FormoreinformationonusingandeditingplotsintheInterfacetab,seetheInterfaceGuide.
Plottingpoints
Thetwobasiccommandsforactuallyplottingthingsareplotandplotxy.
Withplotyouneedonlyspecifytheyvalueyouwantplotted.Thexvaluewillautomaticallybe0forthefirstpointyouplot,1forthesecond,andsoon.(That'siftheplotpen's"interval"isthedefaultvalueof1;youcanchangetheinterval.)
Theplotcommandisespeciallyhandywhenyouwantyourmodeltoplotanewpointateverytimestep.Example:
plot count turtles
Ifyouneedtospecifyboththexandyvaluesofthepointyouwantplotted,thenuseplotxyinstead.Thisexampleassumesthataglobalvariablecalledtimeexists:
plotxy time count-turtles
Plotcommands
Eachplotanditspenshavesetupandupdatecodefieldsthatmaycontaincommands(usuallycontainingplotorplotxy).ThesecommandsarerunautomaticallytriggeredbyothercommandsinNetLogo.
Plotsetupcommandsandpensetupcommandsarerunwhentheeitherreset-ticksorsetup-plotscommandsarerun.Ifthestopcommandisruninthebodyoftheplotsetupcommandsthenthepensetupcommandswillnotrun.
Plotupdatecommandsandpenupdatecommandsarerunwhentheeitherreset-ticks,tickorupdate-plotscommandsarerun.Ifthestopcommandisruninthebodyoftheplotupdatecommandsthenthepenupdatecommandswillnotrun.
Herearethefourcommandsthattriggerplottingexplainedinmoredetail.
![Page 140: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/140.jpg)
setup-plotsexecutescommandsforoneplotatatime.Foreachplot,theplot'ssetupcommandsareexecuted.Ifthestopcommandisnotencounteredwhilerunningthosecommands,theneachoftheplot'spenswillhavetheirsetupcodeexecuted.update-plotsisverysimilartosetup-plots.Foreachplot,theplot'supdatecommandsareexecuted.Ifthestopcommandisnotencounteredwhilerunningthosecommands,theneachoftheplot'spenswillhavetheirupdatecodeexecuted.tickisexactlythesameasupdate-plotsexceptthatthetickcounterisincrementedbeforetheplotcommandsareexecuted.reset-ticksfirstresetsthetickcounterto0,andthendoestheequivalentofsetup-plotsfollowedbyupdate-plots.
Atypicalmodelwillusereset-ticksandticklikeso:
to setup clear-all ... reset-ticksend
to go ... tickend
Notethatinthisexampleweplotfromboththesetupandgoprocedures(becausereset-ticksrunsplotsetupandplotupdatecommands).Wedothisbecausewewantourplottoincludetheinitialstateofthesystemattheendofsetup.Weplotattheendofthegoprocedure,notthebeginning,becausewewanttheplotalwaystobeuptodateafterthegobuttonstops.
Modelsthatdon'tuseticksbutstillwanttodoplottingwillinsteadusesetup-plotsandupdate-plots.Inthepreviouscode,replacereset-tickswithsetup-plots update-plotsandreplacetickwithupdate-plots.
CodeExample:PlottingExample
Otherkindsofplots
Bydefault,NetLogoplotpensplotinlinemode,sothatthepointsyouplotareconnectedbyaline.
Ifyouwanttomovethepenwithoutplotting,youcanusetheplot-pen-upcommand.Afterthiscommandisissued,theplotandplotxycommandsmovethepenbutdonotactuallydrawanything.Oncethepeniswhereyouwantit,useplot-pen-downtoputthepenbackdown.
Ifyouwanttoplotindividualpointsinsteadoflines,oryouwanttodrawbarsinsteadoflinesorpoints,youneedtochangetheplotpen's"mode".Threemodesareavailable:line,bar,andpoint.Lineisthedefaultmode.
Normally,youchangeapen'smodebyeditingtheplot.Thischangesthepen'sdefaultmode.It'salsopossibletochangethepen'smodetemporarilyusingtheset-plot-pen-mode command.Thatcommandtakesanumberasinput:0forline,1forbar,2forpoint.
Histograms
Ahistogramisaspecialkindofplotthatmeasureshowfrequentlycertainvalues,orvaluesincertainranges,occurinacollectionofnumbersthatariseinyourmodel.
Forexample,supposetheturtlesinyourmodelhaveanagevariable.Youcouldcreateahistogramofthedistributionofagesamongyourturtleswiththehistogramcommand,likethis:
histogram [age] of turtles
![Page 141: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/141.jpg)
Thenumbersyouwanttohistogramdon'thavetocomefromanagentset;theycouldbeanylistofnumbers.
Notethatusingthehistogramcommanddoesn'tautomaticallyswitchthecurrentplotpentobarmode.Ifyouwantbars,youhavetosettheplotpentobarmodeyourself.(Aswesaidbefore,youcanchangeapen'sdefaultmodebyeditingtheplotintheInterfacetab.)
Likeothertypesofplots,histogramscanbesettoautoscale.However,autoscaledhistogramsdonotautomaticallyresizethemselveshorizontallylikeotherplottypesdo.Tosettherangeprogrammatically,youcanusetheset-plot-x-rangeprimitive.
Thewidthofthebarsinahistogramiscontrolledbytheplotpen'sinterval.Youcansetaplotpen'sdefaultintervalbyeditingtheplotintheInterfacetab.Youcanalsochangetheintervaltemporarilywiththeset-plot-pen-intervalcommandortheset-histogram-num-bars.Ifyouusethelattercommand,NetLogowillsettheintervalappropriatelysoastofitthespecifiednumberofbarswithintheplot'scurrentxrange.
CodeExample:HistogramExample
Clearingandresetting
Youcanclearthecurrentplotwiththeclear-plotcommand,orcleareveryplotinyourmodelwithclear-all-plots.Theclear-all commandalsoclearsallplots,inadditiontoclearingeverythingelseinyourmodel.
Ifyouwanttoremoveonlythepointsthataparticularpenhasdrawn,useplot-pen-reset.
Whenawholeplotiscleared,orwhenapenisreset,thatdoesn'tjustremovethedatathathasbeenplotted.Italsorestorestheplotorpentoitsdefaultsettings,astheywerespecifiedintheInterfacetabwhentheplotwascreatedorlastedited.Therefore,theeffectsofsuchcommandsasset-plot-background-color,set-plot-x-range,andset-plot-pen-colorareonlytemporary.
Rangesandautoscaling
Thedefaultxandyrangesforaplotarefixednumbers,buttheycanbechangedatsetuptimeorasthemodelruns.
Tochangetherangesatanytime,useset-plot-x-rangeandset-plot-y-range.Or,youcanlettherangesgrowautomatically.Eitherway,whentheplotisclearedtherangeswillreturntotheirdefaultvalues.
Bydefault,allNetLogoplotshavetheautoscalingfeatureenabled.Thismeansthatifthemodeltriestoplotapointwhichisoutsidethecurrentdisplayedrange,therangeoftheplotwillgrowalongoneorbothaxessothatthenewpointisvisible.Histogramplots,however,donotautoscalehorizontally.
Inthehopethattherangeswon'thavetochangeeverytimeanewpointisadded,whentherangesgrowtheyleavesomeextraroom:25%ifgrowinghorizontally,10%ifgrowingvertically.
Ifyouwanttoturnoffthisfeature,edittheplotandunchecktheAutoScale?checkbox.Atpresent,itisnotpossibletoenableordisablethisfeatureonlyononeaxis;italwaysappliestobothaxes.
UsingaLegend
Youcanshowthelegendofaplotbycheckingthe"Showlegend"checkboxintheeditdialog.Ifyoudon'twantaparticularpentoshowupinthelegendyoucanuncheckthe"ShowinLegend"checkboxforthatpenalsointheadvancedplotpensettings(theadvancedplotpensettingscanbeopenedbyclickingthepencilbuttonforthatpenintheplotpenstableintheploteditdialog).
![Page 142: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/142.jpg)
Temporaryplotpens
Mostplotscangetalongwithafixednumberofpens.Butsomeplotshavemorecomplexneeds;theymayneedtohavethenumberofpensvarydependingonconditions.Insuchcases,youcanmake"temporary"plotpensfromcodeandthenplotwiththem.Thesepensarecalled"temporary"becausetheyvanishwhentheplotiscleared(bytheclear-plot,clear-all-plots,orclear-allcommands).
Tocreateatemporaryplotpen,usethecreate-temporary-plot-pencommand.Typically,thiswouldbedoneintheCodetab,butitisalsopossibletousethiscommandfromplotsetuporplotupdatecode(intheeditdialog).Bydefault,thenewpenisdown,isblackincolor,hasanintervalof1,andplotsinlinemode.Commandsareavailabletochangeallofthesesettings;seethePlottingsectionoftheNetLogoDictionary.
Beforeyoucanusethepen,you'llhavetousetheusetheset-current-plotandset-current-plot-pencommands.Theseareexplainedinthenextsection.
set-current-plotandset-current-plot-pen
BeforeNetLogo5,itwasnotpossibletoputplotcommandsintheplotitself.AlloftheplotcodewaswrittenintheCodetabwiththerestofthecode.Forbackwardscompatibility,andfortemporaryplotpens,thisisstillsupported.ModelsinpreviousversionsofNetLogo(andthoseusingtemporaryplotpens)havetoexplicitlystatewhichplotisthecurrentplotwiththeset-current-plotcommandandwhichpenisthecurrentpenwiththeset-current-plot-pencommand.
Tosetthecurrentplotusetheset-current-plotcommandwiththenameoftheplotenclosedindoublequotes,likethis:
set-current-plot "Distance vs. Time"
Thenameoftheplotmustbeexactlyasyoutypeditwhenyoucreatedtheplot.Notethatlaterifyouchangethenameoftheplot,you'llalsohavetoupdatetheset-current-plotcallsinyourmodeltousethenewname.(Copyandpastecanbehelpfulhere.)
Foraplotwithmultiplepens,youcanmanuallyspecifywhichpenyouwanttoplotwith.Ifyoudon'tspecifyapen,plottingwilltakeplacewiththefirstpenintheplot.Toplotwithadifferentpen,theset-current-plot-pencommandwasusedwiththenameofthepenenclosedindoublequotes,likethis:
set-current-plot-pen "distance"
Oncethecurrentpenisset,thencommandslikeplot count turtlescanbeexecutedforthatpen.
Oldermodelswithplotsusuallyhadtheirowndo-plottingprocedurethatlookedsomethinglikethis:
to do-plotting set-current-plot "populations" set-current-plot-pen "sheep" plot count sheep set-current-plot-pen "wolves" plot count wolves
set-current-plot "next plot" ...end
Onceagain,thisisnolongernecessaryinNetLogo5,unlessyouareusingtemporaryplotpens.
Conclusion
NoteveryaspectofNetLogo'splottingsystemhasbeenexplainedhere.SeethePlottingsectionoftheNetLogoDictionaryforinformationonadditionalcommandsandreportersrelatedtoplotting.
![Page 143: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/143.jpg)
ManyoftheSampleModelsintheModelsLibraryillustratevariousadvancedplottingtechniques.Alsocheckoutthefollowingcodeexamples:
CodeExamples:PlotAxisExample,PlotSmoothingExample,RollingPlotExample
Strings
StringsmaycontainanyUnicodecharacters.
ToinputaconstantstringinNetLogo,surrounditwithdoublequotes.
Theemptystringiswrittenbyputtingnothingbetweenthequotes,likethis:"".
Mostofthelistprimitivesworkonstringsaswell:
but-first "string" => "tring"but-last "string" => "strin"empty? "" => trueempty? "string" => falsefirst "string" => "s"item 2 "string" => "r"last "string" => "g"length "string" => 6member? "s" "string" => truemember? "rin" "string" => truemember? "ron" "string" => falseposition "s" "string" => 0position "rin" "string" => 2position "ron" "string" => falseremove "r" "string" => "sting"remove "s" "strings" => "tring"replace-item 3 "string" "o" => "strong"reverse "string" => "gnirts"
Afewprimitivesarespecifictostrings,suchasis-string?,substring,andword:
is-string? "string" => trueis-string? 37 => falsesubstring "string" 2 5 => "rin"word "tur" "tle" => "turtle"
Stringscanbecomparedusingthe=,!=,<,>,<=,and>=operators.
Ifyouneedtoembedaspecialcharacterinastring,usethefollowingescapesequences:
\n=newline\t=tab\"=doublequote\\=backslash
Output
Thissectionisaboutoutputtothescreen.Outputtothescreencanalsobelatersavedtoafileusingtheexport-outputcommand.Ifyouneedamoreflexiblemethodofwritingdatatoexternalfiles,seethenextsection,FileI/O.
ThebasiccommandsforgeneratingoutputtothescreeninNetLogoareprint,show,type,andwrite.ThesecommandssendtheiroutputtotheCommandCenter.
Forfulldetailsonthesefourcommands,seetheirentriesintheNetLogoDictionary.Hereishowtheyaretypicallyused:
printisusefulinmostsituations.showletsyouseewhichagentisprintingwhat.
![Page 144: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/144.jpg)
typeletsyouprintseveralthingsonthesameline.writeletsyouprintvaluesinaformatwhichcanbereadbackinusingfile-read.
ANetLogomodelmayoptionallyhavean"outputarea"initsInterfacetab,separatefromtheCommandCenter.TosendoutputthereinsteadoftheCommandCenter,usetheoutput-print,output-show,output-type,andoutput-writecommands.
Theoutputareacanbeclearedwiththeclear-outputcommandandsavedtoafilewithexport-output.Thecontentsoftheoutputareawillbesavedbytheexport-worldcommand.Theimport-worldcommandwillcleartheoutputareaandsetitscontentstothevalueinimportedworldfile.Itshouldbenotedthatlargeamountsofdatabeingsenttotheoutputareacanincreasethesizeofyourexportedworlds.
Ifyouuseoutput-print,output-show,output-type,output-write,clear-output,orexport-outputinamodelwhichdoesnothaveaseparateoutputarea,thenthecommandsapplytotheoutputportionoftheCommandCenter.
FileI/O
InNetLogo,thereisasetofprimitivesthatgiveyouthepowertointeractwithoutsidefiles.Theyallbeginwiththeprefixfile-.
Therearetwomainmodeswhendealingwithfiles:readingandwriting.Thedifferenceisthedirectionoftheflowofdata.Whenyouarereadingininformationfromafile,datathatisstoredinthefileflowsintoyourmodel.Ontheotherhand,writingallowsdatatoflowoutofyourmodelandintoafile.
Whenworkingwithfiles,alwaysbeginbyusingtheprimitivefile-open.Thisspecifieswhichfileyouwillbeinteractingwith.Noneoftheotherprimitivesworkunlessyouopenafilefirst.
Thenextfile-primitiveyouusedictateswhichmodethefilewillbeinuntilthefileisclosed,readingorwriting.Toswitchmodes,closeandthenreopenthefile.
Thereadingprimitivesincludefile-read,file-read-line,file-read-characters,andfile-at-end?Notethatthefilemustexistalreadybeforeyoucanopenitforreading.
CodeExamples:FileInputExample
TheprimitivesforwritingaresimilartotheprimitivesthatprintthingsintheCommandCenter,exceptthattheoutputgetssavedtoafile.Theyincludefile-print,file-show,file-type,andfile-write.Notethatyoucannever"overwrite"data.Inotherwords,ifyouattempttowritetoafilewithexistingdata,allnewdatawillbeappendedtotheendofthefile.(Ifyouwanttooverwriteafile,usefile-deletetodeleteit,thenopenitforwriting.)
CodeExamples:FileOutputExample
Whenyouarefinishedusingafile,youcanusethecommandfile-closetoendyoursessionwiththefile.Ifyouwishtoremovethefileafterwards,usetheprimitivefile-deletetodeleteit.Toclosemultipleopenedfiles,oneneedstofirstselectthefilebyusingfile-openbeforeclosingit.
;; Open 3 filesfile-open "myfile1.txt"file-open "myfile2.txt"file-open "myfile3.txt"
;; Now close the 3 filesfile-closefile-open "myfile2.txt"file-closefile-open "myfile1.txt"file-close
![Page 145: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/145.jpg)
Or,ifyouknowyoujustwanttocloseeveryfile,youcanusefile-close-all.
Twoprimitivesworthnotingarefile-writeandfile-read.TheseprimitivesaredesignedtoeasilysaveandretrieveNetLogoconstantssuchasnumbers,lists,booleans,andstrings.file-writewillalwaysoutputthevariableinsuchamannerthatfile-readwillbeabletointerpretitcorrectly.
file-open "myfile.txt" ;; Opening file for writingask turtles [ file-write xcor file-write ycor ]file-close
file-open "myfile.txt" ;; Opening file for readingask turtles [ setxy file-read file-read ]file-close
CodeExamples:FileInputExampleandFileOutputExample
Lettingtheuserchoose
Theuser-directory,user-file,anduser-new-fileprimitivesareusefulwhenyouwanttheusertochooseafileordirectoryforyourcodetooperateon.
Movies
Thissectiondescribeshowtocapturean".mp4"movieofaNetLogomodel.
First,usethevid:start-recordercommandtostartthevideorecorder.
Toaddaframetoyourmovie,useeithervid:record-vieworvid:record-interface,dependingonwhetheryouwantthemovietoshowjustthecurrentview,ortheentireInterfacetab.Inasinglemovie,theresolutionwillbeoneofthefollowing:
theresolutionspecifiedinthecalltovid:start-recorder width heightifyouspecifiedtheresolution.Theseareoptionalparameters.Theresolutionoftheviewifyoudidnotspecifyaresolutioninthecalltovid:start-recorderandcallvid:record-viewbeforecallingvid:record-interfaceTheresolutionoftheinterfaceifyoudidnotspecifyaresolutioninthecalltovid:start-recorderandcallvid:record-interfacebeforecallingvid:record-view
Notethatiftheresolutionofarecordedimagedoesn'tmatchtheresolutionoftherecordingitwillbescaledtofitwhichcanresultinimageswhichlookblurryorout-of-focus.
Whenyou'redoneaddingframes,usevid:save-recording.Thefilenameyouprovideshouldendwith.mp4,theextensionforMP4-encodedmovies(playableinQuickTimeandotherprograms).
;; export a 30 frame movie of the viewextensions [vid]
;...
setupvid:start-recordervid:record-view ;; show the initial staterepeat 30[ go vid:record-view ]vid:save-recording "out.mp4"
Amoviewillplaybackat25framespersecond.Tomakethemovieplaybackfasterorslower,considerusingavideopostprocessingtool.
Tocheckwhetherornotyouarerecording,callvid:recorder-status,whichreportsastringthatdescribesthestateofthecurrentrecorder.
![Page 146: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/146.jpg)
Tothrowawaythemoviecurrentlybeingrecorded,callvid:reset-recorder.
CodeExample:MovieExample
Moviesgeneratedwhenrunningheadless,orbybackgroundrunsinaparallelBehaviorSpaceexperimentmayuseonlyvid:record-viewprimitive.MoviesgeneratedinNetLogoGUImayalsousevid:record-interfaceandvid:record-source.
NetLogomoviesareexportedasH.264-encodedMP4files.ToplayanMP4movie,youcanusetheVLCPlayer,afreedownloadfromtheVideoLANorganization.
Moviescantakeupalotofdiskspace.Youwillprobablywanttocompressyourmovieswiththird-partysoftware.Thesoftwaremaygiveyouachoiceofdifferentkindsofcompression.Somekindsofcompressionarelossless,whileothersarelossy."Lossy"meansthatinordertomakethefilessmaller,someofthedetailinthemovieislost.Dependingonthenatureofyourmodel,youmaywanttoavoidusinglossycompression,forexampleiftheviewcontainsfinepixel-leveldetail.
Perspective
The2Dandthe3Dviewshowtheworldfromtheperspectiveoftheobserver.Bydefaulttheobserverislookingdownontheworldfromthepositivez-axisattheorigin.Youcanchangetheperspectiveoftheobserverbyusingthefollow,rideandwatchobservercommandsandfollow-me,ride-meandwatch-meturtlecommands.Wheninfolloworridemodetheobservermoveswiththesubjectagentaroundtheworld.Thedifferencebetweenfollowandrideisonlyvisibleinthe3Dview.Inthe3Dviewtheusercanchangethedistancebehindtheagentusingthemouse.Whentheobserverisfollowingatzerodistancefromtheagentitisactuallyridingtheagent.Whentheobserverisinwatchmodeittracksthemovementsofoneturtlewithoutmoving.Inbothviewsyouwillseeaspotlightappearonthesubjectandinthe3Dviewtheobserverwillturntofacethesubject.Todeterminewhichagentisthefocusyoucanusethesubjectreporter.
CodeExample:PerspectiveExample
Drawing
Thedrawingisalayerwhereturtlescanmakevisiblemarks.
Intheview,thedrawingappearsontopofthepatchesbutunderneaththeturtles.Initially,thedrawingisemptyandtransparent.
Youcanseethedrawing,buttheturtles(andpatches)can't.Theycan'tsensethedrawingorreacttoit.Thedrawingisjustforpeopletolookat.
Turtlescandrawanderaselinesinthedrawingusingthepen-downandpen-erasecommands.Whenaturtle'spenisdown(orerasing),theturtledraws(orerases)alinebehinditwheneveritmoves.Thelinesarethesamecolorastheturtle.Tostopdrawing(orerasing),usepen-up.
Linesdrawnbyturtlesarenormallyonepixelthick.Ifyouwantadifferentthickness,setthepen-sizeturtlevariabletoadifferentnumberbeforedrawing(orerasing).Innewturtles,thevariableissetto1.
Linesmadewhenaturtlemovesinawaythatdoesn'tfixadirection,suchaswithsetxyormove-to,theshortestpathlinethatobeysthetopologywillbedrawn.
Here'ssometurtleswhichhavemadeadrawingoveragridofrandomlyshadedpatches.Noticehowtheturtlescoverthelinesandthelinescoverthepatchcolors.Thepen-sizeusedherewas2:
![Page 147: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/147.jpg)
Thestampcommandletsaturtleleaveanimageofitselfbehindinthedrawingandstamp-eraseletsitremovethepixelsbelowitinthedrawing.
Toerasethewholedrawing,usetheobservercommmandclear-drawing.(Youcanalsouseclear-all,whichclearseverythingelsetoo.)
Importinganimage
Theobservercommandimport-drawingcommandallowsyoutoimportanimagefilefromdiskintothedrawing.
import-drawingisusefulonlyforprovidingabackdropforpeopletolookat.Ifyouwantturtlesandpatchestoreacttotheimage,youshoulduseimport-pcolorsorimport-pcolors-rgbinstead.
ComparisontootherLogos
DrawingworkssomewhatdifferentlyinNetLogothansomeotherLogos.
Notabledifferencesinclude:
Newturtles'pensareup,notdown.Insteadofusingafencecommandtoconfinetheturtleinsideboundaries,inNetLogoyouedittheworldandturnwrappingoff.Thereisnoscreen-color,bgcolor,orsetbg.Youcanmakeasolidbackgroundbycoloringthepatches,e.g.ask patches [ set pcolor blue ] .
DrawingfeaturesnotsupportedbyNetLogo:
Thereisnowindowcommand.ThisisusedinsomeotherLogostolettheturtleroamoveraninfiniteplane.Thereisnofloodorfillcommandtofillanenclosedareawithcolor.
Topology
Thewaytheworldofpatchesisconnectedcanchange.Bydefaulttheworldisatoruswhichmeansitisn'tbounded,but"wraps"--sowhenaturtlemovespasttheedgeoftheworld,itdisappearsandreappearsontheoppositeedgeandeverypatchhasthesamenumberof"neighbor"patches.Ifyou'reapatchontheedgeoftheworld,someofyour"neighbors"areontheoppositeedge.
However,youcanchangethewrapsettingswiththeSettingsbutton.Ifwrappingisnotallowedinagivendirectiontheninthatdirection(xory)theworldisbounded.Patchesalongthatboundarywillhavefewerthan8neighborsandturtleswillnotmovebeyondtheedgeoftheworld.
ThetopologyoftheNetLogoworldhasfourpotentialvalues,torus,box,verticalcylinder,orhorizontalcylinder.Thetopologyiscontrolledbyenablingordisablingwrappinginthexorydirections.Thedefaultworldisatorus.
Atoruswrapsinbothdirections,meaningthatthetopandbottomedgesoftheworldareconnectedand
![Page 148: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/148.jpg)
theleftandrightedgesareconnected.Soifaturtlemovesbeyondtherightedgeoftheworlditappearsagainontheleftandthesameforthetopandbottom.
Aboxdoesnotwrapineitherdirection.Theworldisboundedsoturtlesthattrytomoveofftheedgeoftheworldcannot.Notethatthepatchesaroundedgeoftheworldhavefewerthaneightneighbors;thecornershavethreeandtheresthavefive.
Horizontalandverticalcylinderswrapinonedirectionbutnottheother.Ahorizontalcylinderwrapsvertically,sothetopoftheworldisconnectedtothebottom.buttheleftandrightedgesarebounded.Averticalcylinderistheopposite;itwrapshorizontallysotheleftandrightedgesareconnected,butthetopandbottomedgesarebounded.
CodeExample:NeighborsExample
Whencoordinateswrap,turtlesandlinkswrapvisuallyintheview,too.Ifaturtleshapeorlinkextendspastanedge,partofitwillappearattheotheredge.(Turtlesthemselvesarepointsthattakeupnospace,sotheycannotbeonbothsidesoftheworldatonce,butintheview,theyappeartotakeupspacebecausetheyhaveashape.)
Wrappingalsoaffectshowtheviewlookswhenyouarefollowingaturtle.Onatorus,wherevertheturtlegoes,youwillalwaysseethewholeworldaroundit:
Whereasinaboxorcylindertheworldhasedges,sotheareaspastthoseedgesshowupintheviewasgray:
![Page 149: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/149.jpg)
CodeExample:TermitesPerspectiveDemo(torus),AntsPerspectiveDemo(box)
Thetopologysettingsalsocontrolthebehaviorofthedistance(xy),in-radius,in-cone,face(xy),andtowards(xy)primitives.Thetopologycontrolswhethertheprimitiveswrapornot.Theyalwaysusetheshortestpathallowedbythetopology.Forexample,thedistancefromthecenterofthepatchesinthebottomrightcorner(min-pxcor,min-pycor)andtheupperleftcorner(max-pxcor,max-pycor)willbeasfollowsforeachtopologygiventhattheminandmaxpxcorandpycorare+/-2:
Torus-sqrt(2)~1.414(thiswillbethesameforallworldsizessincethepatchesaredirectlydiagonaltoeachotherinatorus.)Box-sqrt(world-width^2+world-height^2)~7.07VerticalCylinder-sqrt(world-height^2+1)~5.099HorizontalCylinder-sqrt(world-width^2+1)~5.099
Alltheotherprimitiveswillactsimilarlytodistance.Ifyouformerlyused-nowrapprimitivesinyourmodelwerecommendremovingthemandchangingthetopologyoftheworldinstead.
Ifyourmodelhasturtlesthatmovearoundyou'llneedtothinkaboutwhathappenstothemwhentheyreachtheedgeoftheworld,ifthetopologyyou'reusinghassomenon-wrappingedges.Thereareafewcommonoptions:theturtleisreflectedbackintotheworld(eithersystematicallyorrandomly),theturtleexitsthesystem(dies),ortheturtleishidden.Itisnolongernecessarytochecktheboundsusingturtlecoordinates,insteadwecanjustaskNetLogoifaturtleisattheedgeoftheworld.Thereareacouplewaysofdoingthis,thesimplestistousethecan-move?primitive.
if not can-move? distance [ rt 180 ]
can-move?merelyreturnstrueifthepositiondistanceinfrontoftheturtleisinsidetheNetLogoworld,falseotherwise.Inthiscase,iftheturtleisattheedgeoftheworlditsimplegoesbackthewayitcame.Youcanalsousepatch-ahead 1 != nobodyinplaceofcan-move?.Ifyouneedtodosomethingsmarterthatsimplyturningarounditmaybeusefultousepatch-atwithdxanddy.
if patch-at dx 0 = nobody [ set heading (- heading)]if patch-at 0 dy = nobody [ set heading (180 - heading)]
Thistestswhethertheturtleishittingahorizontalorverticalwallandbouncesoffthatwall.
Insomemodelsifaturtlecan'tmoveforwarditsimplydies(exitsthesystem,likeinConductororMousetraps).
if not can-move? distance[ die ]
Ifyouaremovingturtlesusingsetxyratherthanforwardyoushouldtesttomakesurethepatchyouareabouttomovetoexistssincesetxythrowsaruntimeerrorifitisgivencoordinatesoutsidetheworld.Thisisacommonsituationwhenthemodelissimulatinganinfiniteplaneandturtlesoutsidetheviewshouldsimplybehidden.
let new-x new-value-of-xcorlet new-y new-value-of-ycor
ifelse patch-at (new-x - xcor) (new-y - ycor) = nobody [ hide-turtle ] [ setxy new-x new-y show-turtle ]
SeveralmodelsintheModelsLibraryusethistechnique,Gravitation,N-Bodies,andElectrostaticsaregoodexamples.
![Page 150: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/150.jpg)
Thediffuseanddiffuse4commandsbehavecorrectlyinalltopologies.Eachpatchdiffusesandequalamountofthediffusevariabletoeachofitsneighbors,ifithasfewerthan8neighbors(or4ifyouareusingdiffuse4),theremainderstaysonthediffusingpatch.Thismeansthattheoverallsumofpatch-variableacrosstheworldremainsconstant.However,ifyouwantthediffusemattertostillfallofftheedgesoftheworldasitwouldonaninfiniteplaneyoustillneedtocleartheedgeseachstepasintheDiffuseOffEdgesExample.
Links
Alinkisanagentthatconnectstwoturtles.Theseturtlesaresometimesalsocallednodes.
Thelinkisalwaysdrawnasalinebetweenthetwoturtles.Linksdonothavealocationasturtlesdo,theyarenotconsideredtobeonanypatchandyoucannotfindthedistancefromalinktoanotherpoint.
Therearetwolinkdesignations:undirectedanddirected.Adirectedlinkisoutof,orfrom,onenodeandinto,orto,anothernode.Therelationshipofaparenttoachildcouldbemodeledasadirectedlink.Anundirectedlinkappearsthesametobothnodes,eachnodehasalinkwithanothernode.Therelationshipbetweenspouses,orsiblings,couldbemodeledasanundirectedlink.
Thereisaglobalagentsetofalllinks,justaswithturtlesandpatches.Youcancreateundirectedlinksusingthecreate-link-withandcreate-links-withcommands;anddirectedlinksusingthecreate-link-to,create-links-to,create-link-from,andcreate-links-fromcommands.Oncethefirstlinkhasbeencreateddirectedorundirected,allunbreededlinksmustmatch(linksalsosupportbreeds,muchliketurtles,whichwillbediscussedshortly);it'simpossibletohavetwounbreededlinkswhereoneisdirectedandtheotherisundirected.Aruntimeerroroccursifyoutrytodoit.(Ifallunbreededlinksdie,thenyoucancreatelinksofthatbreedthataredifferentindesignationfromthepreviouslinks.)
Ingeneral,linkprimitivenamesindicatewhatkindoflinkstheydealwith:
Primitivesthathave"out"intheirnameutilizeoutgoingandundirectedlinks.Youcanthinkoftheseas"thelinksIcanusetogetfromthecurrentnodetoothernodes."Ingeneral,theseareprobablytheprimitivesyouwanttouse.Primitivesthathave"in"intheirnameutilizeincomingandundirectedlinks.Youcanthinkoftheseas"thelinksIcanusetogettothecurrentnodefromothernodes."Primtivesthatdonotspecify"in"or"out",orhave"with"intheirnameutilizealllinks,bothundirectedanddirected,incomingandoutgoing.
Alink'send1andend2variablescontainthetwoturtlesthelinkconnects.Ifthelinkisdirected,itgoesfromend1toend2.Ifthelinkisundirected,end1isalwaystheolderofthetwoturtles,thatis,theturtlewiththesmallerwhonumber.
Linkbreeds,liketurtlebreeds,allowyoutodefinedifferenttypesoflinksinyourmodel.Linkbreedsmusteitherbedirectedorundirected,unlikeunbreededlinksthisisdefinedatcompiletimeratherthanruntime.Youdeclarelinkbreedsusingthekeywordsundirected-link-breedanddirected-link-breed.Breededlinkscanbecreatedusingthecommandscreate-<breed>-withandcreate-<breeds>-withforundirectedbreedsandthecommandscreate-<breed>-to,create-<breeds>-to,create-<breed>-from,andcreate-<breeds>-fromfordirectedlinks.
Therecannotbemorethanoneundirectedlinkofthesamebreed(ormorethanoneunbreededundirectedlink)betweenapairofagents,normorethanonedirectedlinkofthesamebreedinthesamedirectionbetweenapairofagents.Youcanhavetwodirectedlinksofthesamebreed(ortwounbreededdirectedlinks)betweenapairiftheyareinoppositedirections.
Layouts
Aspartofournetworksupportwehavealsoaddedseveraldifferentprimitivesthatwillhelpyoutovisualizethenetworks.Thesimplestislayout-circlewhichevenlyspacestheagentsaroundthecenteroftheworldgivenaradius.
![Page 151: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/151.jpg)
layout-radialisagoodlayoutifyouhavesomethinglikeatreestructure,thougheveniftherearesomecyclesinthetreeitwillstillwork,thoughastherearemoreandmorecyclesitwillprobablynotlookasgood.layout-radialtakesarootagenttobethecentralnodeplacesitat(0,0)andarrangesthenodesconnectedtoitinaconcentricpattern.Nodesonedegreeawayfromtherootwillbearrangedinacircularpatternaroundthecentralnodeandthenextlevelaroundthosenodesandsoon.layout-radialwillattempttoaccountforasymmetricalgraphsandgivemorespacetobranchesthatarewider.layout-radialalsotakesabreedasaninputsoyouuseonebreedoflinkstolayoutthenetworkandnotanother.
Givenasetofanchornodeslayout-tutteplacesalltheothernodesatthecenterofmassofthenodesitislinkedto.Theanchorsetisautomaticallyarrangedinacirclelayoutwithauserdefinedradiusandtheothernodeswillconvergeintoplace(thisofcoursemeansthatyoumayhavetorunitseveraltimesbeforethelayoutisstable.)
layout-springisusefulformanykindsofnetworks.Thedrawbackisthatisrelativelyslowsinceittakesmanyiterationstoconverge.Inthislayoutthelinksactasspringsthatpullthenodestheyconnecttowardeachotherandthenodesrepeleachother.Thestrengthoftheforcesiscontrolledbyinputstotheprimitives.Theseinputswillalwayshaveavaluebetween0and1;keepinmindthatverysmallchangescanstillaffecttheappearanceofthenetwork.Thespringsalsohavealength(inpatchunits),
![Page 152: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/152.jpg)
however,becauseofalltheforcesinvolvedthenodeswillnotendupexactlythatdistancefromeachother.
CodeExamples:NetworkExample,NetworkImportExample,GiantComponent,SmallWorlds,PreferentialAttachment
Anonymousprocedures
Anonymousproceduresletyoustorecodetoberunlater.JustlikeregularNetLogoprocedures,ananonymousprocedurescanbeeitheracommand(anonymouscommand)orareporter(anonymousreporter).
Anonymousproceduresarevalues,whichmeanstheymaybepassedasinput,reportedasaresult,orstoredinavariable.
Ananonymousproceduremightberunonce,multipletimes,ornotatall.
Inotherprogramminglanguagesanonymousproceduresareknownasfirst-classfunctions,closures,orlambda.
Anonymousprocedureprimitives
Primitivesspecifictoanonymousproceduresare->,is-anonymous-command?,andis-anonymous-reporter?.
The->createsananonymousprocedure.Theanonymousprocedureitreportsmightbeacommandorareporter,dependingonwhatkindofblockyoupassit.Forexample[ -> fd 1 ] reportsananonymouscommand,becausefdisacommand,while[ -> count turtles ] reportsananonymousreporter,becausecountisareporter.
Theseprimitivesrequireanonymousproceduresasinput:foreach,map,reduce,filter,n-values,sort-by.Whencallingtheseprimitives,usingan->isoptionalifyouranonymousprocedurecontainsasingleprimitivewhichhasrequiresnomoreinputsthanareareprovidedbytheprimitive.Forexampleonemaywritesimplyforeach mylist printinsteadofforeach mylist [ [x] -> print x ] ,thoughthelatterisalsoaccepted.Dependingontheanonymousprocedure,variouspartsoftheanonymousproceduresyntaxcanbeomitted.Forasummaryofoptionalsyntax,seethetablebelow.
Theruncommandacceptsanonymouscommandsaswellasstrings.
Therunresultreporteracceptsanonymousreportersaswellasstrings.
runandrunresultallowpassinginputstoananonymousprocedure.Aswithallprimitivesacceptingvaryingnumberofinputs,thewholecallmustbesurroundedwithparentheses,soforexample(run my-anonymous-command 5)or(runresult my-anonymous-reporter "foo" 2).Whennotpassinginput,noparenthesesarerequired.
Anonymousprocedureinputs
Ananonymousproceduremaytakezeroormoreinputs.Theinputsarereferencedthevariablesdeclaredbeforethearrow.Forinstance,intheanonymousreporter[ [a b] -> a + b ] ,aandbareinputs.
Anonymousproceduresandstrings
Creatingandrunninganonymousproceduresisfast.Touserunorrunresultonanewstringforthefirsttimeisabout100xslowerthanrunningananonymousprocedure.Modelersshouldnormallyuseanonymousproceduresinsteadofrunningstrings,exceptwhenrunningstringsenteredbytheuser.
![Page 153: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/153.jpg)
Concisesyntax
Simpleusesofforeach,map,reduce,filter,n-values,andsort-bycanbewrittenwithanespeciallyconcisesyntax.Youcanwrite:
map abs [1 -2 3 -4];; => [1 2 3 4]reduce + [1 2 3 4];; => 10filter is-number? [1 "x" 3];; => [1 3]foreach [1 2 3 4] print;; prints 1 through 4
InolderNetLogoversions(4andearlier),thesehadtobewritten:
map [abs ?] [1 -2 3 -4];; => [1 2 3 4]reduce [?1 + ?2] [1 2 3 4];; => 10filter [is-number? ?] [1 "x" 3];; => [1 3]foreach [1 2 3 4] [ print ? ];; prints 1 through 4
Anonymousproceduresasclosures
Anonymousproceduresare"closures";thatmeanstheycaptureor"closeover"thebindings(notjustthecurrentvalues)oflocalvariablesandprocedureinputs.Theydonotcaptureagentvariablesanddonotcapturetheidentity(oreventheagenttype)ofthecurrentagent.
Nonlocalexits
Thestopandreportcommandsexitfromthedynamicallyenclosingprocedure,nottheenclosinganonymousprocedure.(Thisisbackward-compatiblewitholderNetLogoversions.)
Anonymousproceduresandextensions
TheextensionsAPIsupportswritingprimitivesthatacceptanonymousproceduresasinput.Writeusforsamplecode.
Limitations
WehopetoaddressatleastsomeofthefollowinglimitationsinfutureNetLogoversions:
import-worlddoesnotsupportanonymousprocedures.Anonymousprocedurescan'tbevariadic(acceptavaryingnumberofinputs).Anonymousreporterscan'tcontaincommands,onlyasinglereporterexpression.Soforexampleyoumustuseifelse-valuenotif,andyoudon'tusereportatall.Ifyourcodeistoocomplextobewrittenasonereporter,you'llneedtomovethecodetoaseparatereporterprocedure,andthencallthatprocedurefromyouranonymousreporter,passingitanyneededinputs.Anonymousproceduresarenotinterchangeablewithcommandblocksandreporterblocks.Onlytheprimitiveslistedaboveacceptanonymousproceduresasinput.Controlprimitivessuchasifelseandwhileandagentprimitivessuchasofandwithdon'tacceptanonymousprocedures.SoforexampleifIhaveananonymousreporterlet r [ -> if random 2 == 0 ] andtwoanonymouscommandslet c1 [ -> tick ] andlet c2 [ -> stop ] ,Ican'twriteifelse r c1 c2,Imustwriteifelse runresult r [ run c1 ] [ run c2 ].Theconcisesyntaxwhere->maybeomittedisonlyavailabletoprimitivesandextensionprimitives,notordinaryprocedures.SoforexampleifIhaveaprocedurepthatacceptsananonymousprocedureasinput,itmustbecalledase.g.p [ -> ... ]notp [ ... ].
![Page 154: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/154.jpg)
WhatisOptional?
Thereareseveraldifferentwaysofwritinganonymousprocedureswhichallowuserstoomitpartoralloftheanonymousproceduresyntax.Thesearesummarizedinthetablebelow.
Whatistheanonymousprocedurelike?
Whatcanbeleftout? Examples
Theanonymousprocedureisasingleprimitive
inputnamesarrowblockbrackets
foreach mylist stamp ; no inputsforeach mylist print ; single input(foreach xs ys setxy) ; multipleinputsmap round [1.3 2.4 3.5] ; reporter,single input(map + [1 2 3] [4 5 6]) ; reporter,multiple inputs
Theanonymousproceduretakesnoinputs
inputnamesarrow
foreach mylist [ print "abc" ]map [ 4 ] mylist
Theanonymousprocedurehaszerooroneinput(s)
bracketsaroundinputnames
foreach mylist [ -> stamp ] ; noinputsforeach mylist [ x -> print x ] ;single inputforeach mylist [ x -> rt x fd x ] ;multiple primitives, single inputmap [ -> world-width ] mylist ;reporter, no inputsmap [ x -> x ^ 2 ] mylist ; reporter,single input
Anonymousproceduretakesmorethanoneinput nothing
(foreach xs ys [ [ x y ] -> setx x +y ])(map [ [ x y ] -> x mod round y ] xsys)
Note:bracketsaroundinputnameswerealwaysrequiredinNetLogo6.0.0.IfyoucopyandpastecodeintoNetLogo6.0.0usinganonymousprocedureswithunbracketedinputnames,thecodewillnotcompileuntilyouaddthebrackets.
Codeexample
CodeExample:StateMachineExample
Ask-Concurrent
NOTE:Thefollowinginformationisincludedonlyforbackwardscompatibility.Wedon'trecommendusingtheask-concurrentprimitiveatallinnewmodels.
InveryoldversionsofNetLogo,askhadsimulatedconcurrentbehaviorbydefault.SinceNetLogo4.0(2007),askisserial,thatis,theagentsrunthecommandsinsidetheaskoneatatime.
Thefollowinginformationdescribesthebehavioroftheask-concurrentcommand,whichbehavesthewaytheoldaskbehaved.
![Page 155: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/155.jpg)
ask-concurrentproducessimulatedconcurrencyviaamechanismofturn-taking.Thefirstagenttakesaturn,thenthesecondagenttakesaturn,andsoonuntileveryagentintheaskedagentsethashadaturn.Thenwegobacktothefirstagent.Thiscontinuesuntilalloftheagentshavefinishedrunningallofthecommands.
Anagent's"turn"endswhenitperformsanactionthataffectsthestateoftheworld,suchasmoving,orcreatingaturtle,orchangingthevalueofaglobal,turtle,patch,orlinkvariable.(Settingalocalvariabledoesn'tcount.)
Theforward(fd)andback(bk)commandsaretreatedspecially.Whenusedinsideask-concurrent,thesecommandscantakemultipleturnstoexecute.Duringitsturn,theturtlecanonlymovebyonestep.Thus,forexample,fd 20isequivalenttorepeat 20 [ fd 1 ] ,wheretheturtle'sturnendsaftereachrunoffd.Ifthedistancespecifiedisn'taninteger,thelastfractionofsteptakesafullturn.Soforexamplefd 20.3isequivalenttorepeat 20 [ fd 1 ] fd 0.3.
Thejumpcommandalwaystakesexactlyoneturn,regardlessofdistance.
Tounderstandthedifferencebetweenaskandask-concurrent,considerthefollowingtwocommands:
ask turtles [ fd 5 ]ask-concurrent turtles [ fd 5 ]
Withask,thefirstturtletakesfivestepsforward,thenthesecondturtletakesfivestepsforward,andsoon.
Withask-concurrent,alloftheturtlestakeonestepforward.Thentheyalltakeasecondstep,andsoon.Thus,thelattercommandisequivalentto:
repeat 5 [ ask turtles [ fd 1 ] ]
CodeExample:Ask-ConcurrentExampleshowsthedifferencebetweenaskandask-concurrent.
Thebehaviorofask-concurrentcannotalwaysbesosimplyreproducedusingask,asinthisexample.Considerthiscommand:
ask-concurrent turtles [ fd random 10 ]
Inordertogetthesamebehaviorusingask,wewouldhavetowrite:
turtles-own [steps]ask turtles [ set steps random 10 ]while [any? turtles with [steps > 0]] [ ask turtles with [steps > 0] [ fd 1 set steps steps - 1 ]]
Toprolonganagent's"turn",usethewithout-interruptioncommand.(Thecommandblocksinsidesomecommands,suchascreate-turtlesandhatch,haveanimpliedwithout-interruptionaroundthem.)
Notethatthebehaviorofask-concurrentiscompletelydeterministic.Giventhesamecodeandthesameinitialconditions,thesamethingwillalwayshappen(ifyouareusingthesameversionofNetLogoandbeginyourmodelrunwiththesamerandomseed).
Ingeneral,wesuggestyounotuseask-concurrentatall.Ifyoudo,wesuggestyouwriteyourmodelsothatitdoesnotdependontheexactdetailsofhowask-concurrentworks.WemakenoguaranteesthatitssemanticswillremainthesameinfutureversionsofNetLogo,orthatitwillcontinuetobesupported
![Page 156: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/156.jpg)
atall.
UserInteractionPrimitives
NetLogofeaturesseveralprimitiveswhichallowamodeltointeractwiththeuser.Theseprimitivesincludeuser-directory,user-file,user-new-file,user-input,user-message,user-one-of,anduser-yes-or-no?.
Theseprimitivesdifferinpreciselywhatinteractiontheytakewiththeuser.user-directory,user-file,anduser-new-fileareallreporterswhichprompttheusertoselectanitemfromthefilesystemandreportthepathoftheselecteditemtoNetLogo.user-yes-or-no?,user-one-of,anduser-inputallprompttheusertoprovideinputintheformoftextoraselection.user-messagesimplypresentsamessagetotheuser.
Notethatallactiveforeverbuttonswillpausewhenoneoftheseprimitivesisusedandwillresumeonlywhentheusercompletestheinteractionwiththebutton.
Whatdoes"Halt"mean?
Theprimitiveswhichprompttheuserforinput,aswellasuser-messageallprovidea"Halt"button.Theeffectofthisbuttonisthesameforalloftheseprimitives-ithaltsthemodel.Whenthemodelishaltedallrunningcodeisstopped,includingbuttonsandthecommandcenter.Sincehaltingstopscodeinthemiddleofwhateverithappenedtobedoingatthetimeitwashalted,youmayseestrangeresultsifyoucontinuetorunthemodelafterahaltwithoutsettingitupagain.
Tie
Tieconnectstwoturtlessothatthemovementofoneturtlesaffectsthelocationandheadingofanother.Tieisapropertyoflinkssotheremustbealinkbetweentwoturtlestocreateatierelationship.
Whenalink'stie-modeissetto"fixed"or"free"end1andend2aretiedtogether.Ifthelinkisdirectedend1isthe"rootagent"andend2isthe"leafagent".Thatiswhenend1moves(usingfd,jump,setxy,etc.)end2alsomovesthesamedistanceanddirection.Howeverwhenend2movesitdoesnotaffectend1.
Ifthelinkisundirecteditisareciprocaltierelationship,meaning,ifeitherturtlemovestheotherturtlewillalsomove.Sodependingonwhichturtleismovingeitherturtlecanbeconsideredtherootortheleaf.Therootturtleisalwaystheturtlethatinitiatesthemovement.
Whentherootturtleturnsrightorleft,theleafturtlerotatesaroundtherootturtlethesameamountasifastiffwereattachingtheturtles.Whentie-modeissetto"fixed"theheadingoftheleafturtlechangesbythesameamount.Ifthetie-modeissetto"free"theheadingoftheleafturtleisunchanged.
Thetie-modeofalinkcanbesetto"fixed"usingthetiecommandandsetto"none"(meaningtheturtlesarenolongertied)usinguntietosetthemodeto"free"youneedto:set tie-mode "free".
CodeExample:TieSystemExample
Multiplesourcefiles
The__includeskeywordallowsyoutousemultiplesourcefilesinasingleNetLogomodel.
ThekeywordbeginswithtwounderscorestoindicatethatthefeatureisexperimentalandmaychangeinfutureNetLogoreleases.
Whenyouopenamodelthatusesthe__includeskeyword,orifyouaddittothetopofamodelandhittheCheckbutton,theincludesmenuwillappearinthetoolbar.Fromtheincludesmenuyoucanselectfromthefilesincludedinthismodel.
Whenyouopenincludedfilestheyappearinadditionaltabs.SeetheInterfaceGuideformoredetails.
![Page 157: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/157.jpg)
Youcanhaveanythinginexternalsourcefiles(.nls)thatyouwouldnormallyputintheCodetab:globals,breed,turtles-own,patches-own,breeds-own,proceduredefinitions,etc.Notethoughthatthesedeclarationsallsharethesamenamespace.Thatis,ifyoudeclareaglobalmy-globalintheCodetabyoucannotdeclareaglobal(oranythingelse)withthenamemy-globalinanyfilethatisincludedinthemodel.my-globalwillbeaccessiblefromalltheincludedfiles.Thesamewouldbetrueifmy-globalweredeclaredinoneoftheincludedfiles.
Syntax
Colors
IntheCodetabandelsewhereintheNetLogouserinterface,programcodeiscolor-codedbythefollowingscheme:
KeywordsaregreenConstantsareorangeCommentsaregrayPrimitivecommandsarebluePrimitivereportersarepurpleEverythingelseisblack
Notice
Theremainderofthissectioncontainstechnicalterminologywhichwillbeunfamiliartosomereaders.
Keywords
Theonlykeywordsinthelanguageareglobals,breed,turtles-own,patches-own,to,to-report,andend,plusextensionsandtheexperimental__includeskeyword.(Built-inprimitivenamesmaynotbeshadowedorredefined,sotheyareeffectivelyakindofkeywordaswell.)
Identifiers
Allprimitives,globalandagentvariablenames,andprocedurenamesshareasingleglobalcase-insensitivenamespace;localnames(letvariablesandthenamesofprocedureinputs)maynotshadowglobalnamesoreachother.IdentifiersmaycontainanyUnicodeletterordigitandthefollowingASCIIcharacters:
.?=*!<>:#+/%$_^'&-
SomeprimitivenamesbeginwithtwounderscorestoindicatethattheyareexperimentalandareespeciallylikelytochangeorberemovedinfutureNetLogoreleases.
Scope
NetLogoislexicallyscoped.Localvariables(includinginputstoprocedures)areaccessiblewithintheblockofcommandsinwhichtheyaredeclared,butnotaccessiblebyprocedurescalledbythosecommands.
Comments
Thesemicoloncharacterintroducesacomment,whichlastsuntiltheendoftheline.Thereisnomulti-linecommentsyntax.
Structure
![Page 158: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/158.jpg)
Aprogramconsistsofoptionaldeclarations(globals,breed,turtles-own,patches-own,<BREED>-own,extensions)inanyorder,followedbyzeroormoreproceduredefinitions.Multiplebreedsmaybedeclaredwithseparatebreeddeclarations;theotherdeclarationsmayappearonceonly.
Everyproceduredefinitionbeginswithtoorto-report,theprocedurename,andanoptionalbracketedlistofinputnames.Everyproceduredefinitionendswithend.Inbetweenarezeroormorecommands.
Commandsandreporters
Commandstakezeroormoreinputs;theinputsarereporters,whichmayalsotakezeroormoreinputs.Nopunctuationseparatesorterminatescommands;nopunctuationseparatesinputs.Identifiersmustbeseparatedbywhitespaceorbyparenthesesorsquarebrackets.(Soforexample,a+bisasingleidentifier,buta(b[c]d)econtainsfiveidentifiers.)
Allcommandsareprefix.Alluser-definedreportersareprefix.Mostprimitivereportersareprefix,butsome(arithmeticoperators,booleanoperators,andsomeagentsetoperatorslikewithandin-points)areinfix.
Allcommandsandreporters,bothprimitiveanduser-defined,takeafixednumberofinputsbydefault.(That'swhythelanguagecanbeparsedthoughthereisnopunctuationtoseparateorterminatecommandsand/orinputs.)Someprimitivesarevariadic,thatis,mayoptionallytakeadifferentnumberofinputsthanthedefault;parenthesesareusedtoindicatethis,e.g.(list 1 2 3) (sincethelistprimitiveonlytakestwoinputsbydefault).Parenthesesarealsousedtooverridethedefaultoperatorprecedence,e.g.(1 + 2) * 3 ,asinotherprogramminglanguages.
Sometimesaninputtoaprimitiveisacommandblock(zeroormorecommandsinsidesquarebrackets)orareporterblock(asinglereporterexpressioninsidesquarebrackets).User-definedproceduresmaynottakeacommandorreporterblockasinput.
Operatorprecedencesareasfollows,hightolow:
with,at-points,in-radius,in-cone(allotherprimitivesanduser-definedprocedures)^*,/,mod+,-<,>,<=,>==,!=and,or,xor
ComparedtootherLogos
Thereisnoagreed-uponstandarddefinitionofLogo;itisaloosefamilyoflanguages.WebelievethatNetLogohasenoughincommonwithotherLogostoearntheLogoname.Still,NetLogodiffersinsomerespectsfrommostotherLogos.Themostimportantdifferencesareasfollows.
Surfacedifferences
Theprecedenceofmathematicaloperatorsisdifferent.Infixmathoperators(like+,*,etc.)havelowerprecedencethanreporterswithnames.Forexample,inmanyLogos,ifyouwritesin x + 1,itwillbeinterpretedassin (x + 1).NetLogo,ontheotherhand,interpretsitthewaymostotherprogramminglanguageswould,andthewaythesameexpressionwouldbeinterpretedinstandardmathematicalnotation,namelyas(sin x) + 1.Theandandorreportersarespecialforms,notordinaryfunctions,andthey"shortcircuit",thatis,theyonlyevaluatetheirsecondinputifnecessary.ProcedurescanonlybedefinedintheCodetab,notinteractivelyintheCommandCenter.Reporterprocedures,thatis,proceduresthat"report"(return)avalue,mustbedefinedwithto-reportinsteadofto.Thecommandtoreportavaluefromareporterprocedureisreport,notoutput.
![Page 159: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/159.jpg)
Whendefiningaprocedure,theinputstotheproceduremustbeenclosedinsquarebrackets,e.g.to square [x].Variablenamesarealwaysusedwithoutanypunctuation:alwaysfoo,never:fooor"foo.(Tomakethiswork,insteadofamakecommandtakingaquotedargumentwesupplyasetspecialformwhichdoesnotevaluateitsfirstinput.)Asaresult,proceduresandvariablesoccupyasinglesharednamespace.
Thelastthreedifferencesareillustratedinthefollowingproceduredefinitions:
mostLogos NetLogo
to square :xoutput :x * :xend
to-report square [x]report x * xend
Deeperdifferences
NetLogo'slocalvariablesandinputstoproceduresarelexicallyscoped,notdynamicallyscoped.NetLogohasno"word"datatype(whatLispcalls"symbols").Eventually,wemayaddone,butsinceitisseldomrequested,itmaybethattheneeddoesn'tarisemuchinagent-basedmodeling.Wedohavestrings.InmostsituationswheretraditionalLogowouldusewords,wesimplyusestringsinstead.ForexampleinLogoyoucouldwrite[see spot run](alistofwords),butinNetLogoyoumustwrite"see spot run"(astring)or["see" "spot" "run"](alistofstrings)instead.NetLogo'sruncommandworksonanonymousproceduresandstrings,notlists(sincewehaveno"word"datatype),anddoesnotpermitthedefinitionorredefinitionofprocedures.Controlstructuressuchasifandwhilearespecialforms,notordinaryfunctions.Youcan'tdefineyourownspecialforms,soyoucan'tdefineyourowncontrolstructures.(Youcandosomethingsimilarusinganonymousprocedures,butyoumustusethe->,run,andrunresultprimitivesforthat,youcannotmakethemimplicit.)Anonymousprocedures(akafunctionvaluesorlambda)aretruelexically-scopedclosures.ThisfeatureisavailableinNetLogoandinmodernLisps,butnotinstandardLogo.
Ofcourse,theNetLogolanguagealsocontainsotherfeaturesnotfoundinmostLogos,mostimportantlyagentsandagentsets.
![Page 160: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/160.jpg)
TransitionGuide
ManymodelscreatedinearlierversionsofNetLogoalsoworkinNetLogo5.0.However,somemodelswillneedchanges.Ifanoldmodelisn'tworking,thissectionoftheUserManualmaybeabletohelpyou.
WhatissuesmayarisedependsonwhatversionofNetLogothemodelwascreatedwith.
Thisguideonlycoverschangesmostlikelytocauseissuesforusers.SeetheReleasenotesformorecompletedetailsondifferencesbetweenversions.
ChangesforNetLogo6.0ChangesforNetLogo5.2ChangesforNetLogo5.0ChangesforNetLogo4.1ChangesforNetLogo4.0ChangesforNetLogo3.1
ChangesforNetLogo6.0
TasksreplacedbyAnonymousProcedures
InNetLogo6.0,taskshavebeenreplacedbyanonymousprocedures.Thismeansthattaskisnolongeraprimitive,it'sbeenreplacedbythenewarrowsyntaxforcreatinganonymousprocedures.Similarly,questionmarkvariableslike?,?1,and?2arenowjustordinarynamesinNetLogoandcanbeusedtonameprocedurevariables,letvariables,oranonymousprocedurevariables.Finally,is-reporter-task?andis-command-task?havebeenreplacedbyis-anonymous-reporter?andis-anonymous-command?.
Tomakethistransitioneasier,we'veaddedanautomaticconversionstepwhichshouldallowmostmodelssavedinNetLogo5tobeconvertedtousethenewsyntaxautomatically.Theautoconverterhasbeenasubstantialpieceofeffortandwe'vetesteditonallthemodelsinthemodelslibrary.Touseit,ensurethemodelcompilesandrunproperlyinNetLogo5orlater,thensaveitfromNetLogo5orlater.Then,simplyopenthemodelinNetLogo6.Ifallgoeswell,you'llseetheconverterhaschangedcodeliketask [?1 + ?2] to[ [?1 ?2] -> ?1+ ?2 ].Thequestionmarksaremeanttoserveastemporaryplaceholdersforconversion.Theyenableyourmodeltorun,butyoucan(andshould)replacethesevariableswithmeaningfulnames.Ifyouopenamodelwithtasksandithasnotbeenconverted,theautoconverterwasn'tabletoconvertyourmodel.Ratherthanattempttoautoconvertyourmodelandbreaksomething,themodelwillopen,youwillbeshowntheappropriateerrorsandgivenachancetoedityourmodel.
Whilewehavetestedtheautoconverterthoroughly,weexpecttheretobesomecasesitdoesn'tcover.
Ifyoumakeuseofextensionsthataren'tyetcompiledforNetLogo6,theautoconverterwillnotworkuntilthoseextensionshavebeenupdated.Ifyourcodeusesrunorrunresulttoevaluatestringscontainingtasks,theautoconverterwillnotchangethosestringstobeanonymousprocedures.Tomakerunandrunresultworkasexpected,lookatstringsinyourmodelandchangeanywhichrelyontaskor?-variablestoinsteadrelyonanonymousprocedures
Ifyourmodeldoesn'tfallintotheabovecategoriesanddoesn'tconvertorconvertsincorrectly,pleaseemailourfeedbackaddressandwe'llbehappytoofferwhateverassistancewecan.
![Page 161: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/161.jpg)
Linkreportersoverhauledtobemoreconsistentandflexible
InpreviousversionsofNetLogo,linkreportershavehadanumberofinconsistenciesregardingdirectedandundirectedlinks.Forexample,my-linkswouldreportalllinksconnectedtoaturtle,whereaslink-neighborswouldonlyreportneighborsconnectedbyundirectedlinks.Furthermore,itwasquitedifficulttoworkwithmodelswherethelinkscouldeitherbedirectedorundirected.
Toalleviatetheseissues,thelinkprimitiveshavebeenoverhauledin6.0.Thesechangesonlyaffectexistingmodelsthatusebothdirectedandundirectedlinkswhilealsousingtheunbreededlinkprimitives.
Thechangesareasfollows:
Linkreportersthatcontaintheword"out"nowutilizebothdirected,outgoinglinksandundirectedlinks.Thatis,theynowspecifylinksthatcanbeusedtogetfromthecurrentnodetoothernodes.Forexample,out-link-neighbor?willreporttrueifthecurrentturtleisconnectedtothegiventurtlebyeitheranoutgoingdirectedlinkoranundirectedlink.Ifyouonlywantdirected,outgoinglinks,youcanuseabreed-specificreporterormy-out-links with [ is-directed? self ].Generally,whenworkingwithmodelsthathavebothdirectedandundirectedlinks,youwillprobablywanttousethe"out"primitivesformostthingsnow.Linkreportersthatcontaintheword"in"nowutilizebothdirected,incominglinksandundirectedlinks.Thatis,theynowspecifylinksthatcanbeusedtogettothecurrentnodefromothernodes.Forexample,in-link-neighbor?willreporttrueifthecurrentturtleisconnectedtothegiventurtlebyeitheranincomingdirectedlinkoranundirectedlink.Ifyouonlywantdirected,incominglinks,youcanuseabreed-specificreporterormy-in-links with [ is-directed? self ].Linkreportersthatdonotspecify"out"or"in"utilizealllinks.
Furthermore,therearenolongerrestrictionsregardingwhichreporterscanbeusedwithwhichbreeds.Forunbreededlinks,thismakesitpossibletousethesameprimitivesregardlessofwhetheryournetworkendsupbeingdirectedorundirected.
Thenewbehavior(includingallchangedprimitives)issummarizedbythefollowingtable,where"un"referstoundirectedlinks,"out"referstodirected,outgoinglinks,and"in"referstodirected,incominglinks.
Newlinkreporterbehavior
![Page 162: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/162.jpg)
Oldlinkreporterbehavior
RemovalofApplets
Oracle,thecompanybehindJava,hasannouncedthatJavaappletsaredeprecated(seethisblogpostformoreinformation).Thiscomesasthemajorbrowsershaveremovedsupportforplug-ins(likejavaapplets)orannouncedthattheyplantodoso.
![Page 163: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/163.jpg)
Insteadofusingappletstodistributeyourmodel,NetLogoofferstheoptiontoexporttoNetLogoWeb.WhileNetLogoWebdoesn'tyetofferthefullfunctionalityofdesktopNetLogo(inparticular,extensionsaren'tsupported),itisnowcapableofrunningmostofthemodelsintheNetLogomodelslibraryandwehopethatmostmodeldistributorswillfindthatitmeetstheirneeds.ToexporttoNetLogoWeb,choosethe"SaveAsNetLogoWeb"optionfromthe"File"menu.
ChangestotheNetLogoUserInterface
UserswillnoticeseveraltweakstotheNetLogoUserinterfacewhenopeningNetLogo6forthefirsttime.We'veremovedthebarborderabovetheview.Toopenthe3DViewin6.0,youcanrightclickontheviewandchoose"Switchto3DView",orchoosethesameoptionfromthe"Tools"menu.Ticksarenowdisplayedintheinterfacetabtoolbarbeneaththespeedslider.Toadjustthelabelusedfor"ticks"andotherviewproperties,youcanchoosethe"Settings"buttonatthefarrightoftheinterfacetabtoolbarorright-clickontheviewandchoose"Edit..."fromthecontextmenuthatappears.
NobodyNotPermittedasaChooserValue
InNetLogo6.0,nobodyisnolongeravalidchooservalue.Justasyoucan'tputturtle 0orturtles,nobodyreferstoanon-literalvaluewhichisn'tsupportedinchoosers.Aspartofthistransition,chooserscontainingnobody(ornobodywithinanestedlist)willhaveallusesofnobodychangedto"nobody"whenopenedinNetLogo6.0.
Breedsmusthavesingularandpluralnames
InNetLogo6.0,youmustspecifybothpluralandsingularbreednames.Inpriorversions,declarationslikebreed [mice]werelegal,butthissupporthasbeenremovedin6.0.Ifyouhavemodelswhichuseonlypluralbreednames,itisrecommendedthatyouconvertthemtospecifybothnamesbeforeopeningin6.0sincedoingsowillpermittheNetLogoconvertertoworkmosteffectivelyonanyothercodeinyourmodelwhichneedsconversion.
Removalof"Movie"Prims
TheNetLogomovieprimshadn'tbeenupdatedinquitesometimeandgeneratedinvalidquicktimemoviefiles.Theyhavebeenreplacedbyprimsinthenewvidextension.ThefulldocumentationforthevidextensionisavailableintheVidExtensionsectionofthemanual.Aswithallextensions,userswillneedtoincludevidintheextensionssectionoftheirNetLogomodel.
Manyofthemovieprimitiveshavedirectparallelsinthevidextensionwhichcanbefoundinthefollowingtable:
movieprim vidprimmovie-cancel vid:reset-recorder
movie-close vid:save-recording file-name
movie-grab-view vid:record-view
movie-grab-interface vid:record-interface
movie-start file-name vid:start-recorder optional-width optional-height
movie-status vid:recorder-status
WhenyoufirstopenafileinNetLogo6.0,yourfilewillbeautomaticallyconvertedtousethe
![Page 164: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/164.jpg)
newprimitives.Thiswillincludeaddinganewglobalvariable-_recording-save-file-nametotrackthenameoftheactiverecording,aswellasaddingthevidextensiontothemodel.Youshouldverifythattheconversiontookplacecorrectly.Thereisnoreplacementformovie-set-frame-rate.Thevidextensionrecordsframesat25persecond,slightlymorethanthedefault15frames-per-secondofthemovieprims.Ifyourrecordingissensitivetoframerate,considerrecordingeachexistingframetwice(2/25isfairlycloseto1/15)orconsiderusingapostprocessingtool(likegstreamerorffmpeg)toadjustthevideoplaybackspeed.
ImprovedNameCollisionDetection
InNetLogo6.0,expandederror-checkingintheNetLogocompilercausesmodelswhichdefineundirected-link-breed [ undirected-links undirected-link ] and/ordirected-link-breed [ directed-links directed-link ]toerrorforredefiningaprimitivereporter(eitheris-directed-link?oris-undirected-link?).Ifyourmodeldoesn'tuseis-directed-link?oris-undirected-link?atall,simplychangingthebreednamesshouldresolvetheerror.
Ifyouusedeitheroftheis-<directedness>-link?prim,thereareseveralwaysyoumightmodifyyourmodeltoaccountforthischange.Ifyourmodelhasnootherbreededlinks,considerremovingthelinkbreedandusingthebuilt-inlinkprimitives.Ifyourmodelhasotherbreededlinks,butonlyofdifferentdirectedness,simplychangingthebreedname(andallrelatedprimitivenames)shouldresolvetheproblem.Notethatinthiscaseis-directed-link?and/oris-undirected-link?continuetobehavethesameasbefore.Ifyourmodelhasotherbreededlinksofthesamedirectedness,thechangewillvarydependingonyourmodel.Thebreedname(s)mustbechanged,butyoumustdecidewhetheryouusedis-directed-link?/is-undirected-link?tochecklinkdirectedneessortocheckthatlinkbreedmembership.Ifyouusedittochecklinkdirectednessleavingitas-isshouldkeepthecurrentbehaviorofthemodel.Otherwise,itcansimplybereplacedbyis-<breed>?.
Removalofhubnet-set-client-interface
Thehubnet-set-client-interfaceprimitivewasrenderedobsoletebytheintroductionoftheHubNetclienteditorandendofsupportforcalculatorHubNet.Wehavefounditusedinveryfewmodelsandhavedecidedtoremoveitfromthelanguage.Onopeninganexistingmodelin6.0,theautoconvertershouldremoveallusesofhubnet-set-client-interfacefromyourcode.
Improved&UpdatedExtensionsAPI
OneofourgoalsinNetLogo6.0hasbeentomakeiteasiertodevelopextensionsandeasytodevelopmorepowerfulextensions.Tothatend,we'vebumpedtheextensionAPIfrom5.0to6.0.Existingextensionswillneedtorecompilechangingthe"NetLogo-Extension-API-Version"intheirjar'sMANIFEST.MFfrom5.0to6.0.
Someofthechangeswe'vemadetotheextensionsAPIinclude:
org.nlogo.api.Contextnowallowsaccesstothecurrentworldandworkspaceobjectswithoutrequiringacasttoanorg.nlogo.nvm.ExtensionContext.org.nlogo.api.WorkspacehasbeenintroducedasastableAPIforextensionstodependon.ANetLogojarisnowavailablefromBinTray.
Forafulllistofchangesbetween5.0and6.0,pleasevisitourExtensionTransitionGuideonGitHub.
![Page 165: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/165.jpg)
Inserviceofmakingiteasiertobuildextensions,we'veexpandedandimprovedtheNetLogoExtensionPluginforsbt,theScalaBuildTool.SbtisapowerfultoolforbuildingJVMprojectsandcanbeusedinprojectsthatuseScala,Java,oracombinationofthetwo.We'renowusingtheExtensionPlugintobuildallofthebundledextensionsandwestronglyrecommendextensionauthorstakeadvantageofthepluginasitmakesconfiguringaNetLogoextensionbuildextremelystraightforward.ThepluginhandlesfetchingtheNetLogojarwhichextensionscompileagainstaswellasgenerationofajarfortheextensioncontainingtheappropriatemetadata.
Addrangeprimitive
AnewrangeprimitivewasaddedinNetLogo6.As"range"mayappearinexistingmodelsasaprocedureorvariablename,wehaveaddedanautoconversionstepwhichwillensurethatthesemodelscontinuetooperateimmediatelyuponopeninginNetLogo6.ExistingusesofrangeinmodelsauthoredbeforeNetLogo6willbeconvertedto_rangeuponfirstopeninginNetLogo6.Oncethemodelopens,youcanrename_rangetosuityourmodel.
ChangesforNetLogo5.2
hsbprimitives
In5.2,thehsbprimitiveshavebeenchangedtoworkwiththestandardscalevaluesof360forhue,and100forsaturationandbrightness.Thisaffectstheprimitiveshsb,extract-hsbandapproximate-hsb.
Theoldprimitives,scaledto255,areautomaticallytransitionedtoandhavebeenrenamed__hsb-old,__extract-hsb-oldand__approximate-hsb-old.
GoGoextension
TheGoGoextensionhasbeenupgradedtousenewerGoGoboardswiththeHIDinterface.Manyoftheolderprimitivesnolongerwork,andwillalertyoutoupgradingyourGoGoboard'sfirmware.
Ifyouneedtocontinuetouseaserialinterface,youcanusethebundledgogo-serialextension.Changeyourmodeltousegogo-serialasopposedtogogo.Moredetails[here](https://github.com/NetLogo/NetLogo/wiki/GoGo-Upgrade).
IfyoucannotupgradetousethenewHIDextensionnorthenewserialextension,theoriginalextensioncanbefoundathttps://github.com/NetLogo/GoGo-RXTX-Extension
ChangesforNetLogo5.0
Plotting
In5.0,youdon'thavetoputyourplottingcodeintheCodetabanymore.Instead,youcanputitinsidetheplotsthemselves,intheInterfacetab.
Nonetheless,theoldstyleandalloftheexistingplottingprimitivesarestillsupported.Werecommendchangingyourmodeltousethenewstyle,butifyoudon't,itshouldstillwork.
![Page 166: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/166.jpg)
Thefollowingexampleshowshowtochangeamodeltousethenewstyle.SupposeyouhaveatypicalNetLogo4.1modelwithoneplotcalled"populations"andtwopenscalled"robots"and"humans".Theoldcodemightlooklike:
to setup clear-all ... do-plottingend
to go ... tick do-plottingend
to do-plotting set-current-plot "populations" set-current-plot-pen "robots" plot count robots set-current-plot-pen "humans" plot count humansend
Herearethestepstomakethetransition:
Copytheplot count robotscommandandpasteitintotheUpdateCommandsfieldfortherobotspenintheploteditdialog.Removeitfromthedo-plottingprocedure.Theplot count humanscommandcanbemovedinthesamewayforthehumanspen.Afterthoselinesareremovedfromthedo-plottingprocedure,itdoesn'tactuallydoanythinganymore!Removeit.Thefinalstepistoreplacethedo-plottingprocedurecallsinsetupandgo.Insetup,thedo-plottingcallshouldbechangedtoreset-ticks.Ingo,thedo-plottingcallshouldbechangedtotick.reset-ticksandtickwillbothcauseplottingtohappenautomatically.
Theresulting(muchsimpler)codelookslikethis:
to setup clear-all ... reset-ticksend
to go ... tickend
FormoredetailsonhowplottingworksinNetLogo5.0,seethePlottingSectionsoftheProgrammingGuideandtheInterfaceGuide.Fordetailsonhowplottinginteractswiththetickcounter,readon.
Tickcounter
Thewaythetickcounterworkshaschangedin5.0.Insteadofbeinginitiallysetto0,thetickcounterisinitiallyblank.
reset-ticks
Youmustusereset-tickstostartthetickcounterat0beforeusingticks,tickortick-
![Page 167: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/167.jpg)
advanceforthefirsttime.
reset-ticksshouldgoattheendofyoursetupprocedure.Puttingittherewillallowyourmodeltoworkwith5.0'snewplottingfeatures.
reset-ticksandplotting
In5.0,youdon'thavetoputyourplottingcodeintheCodetabanymore.Instead,youcanputitinsidetheplotsthemselves,intheInterfacetab.Codeinsideplotsistriggeredbyreset-ticksandtick.Resettingthetickcounterrunsplotsetupcode,andthenitalsorunsplotupdatecodetoplottheinitialstateofthemodel.Theinitialstateofthemodelwon'tbeinplaceuntiltheendofsetup,sothat'swhyreset-ticksshouldgoattheend.
__clear-all-and-reset-ticks
InorderformodelsfrompreviousNetLogoversionstoworkin5.0withoutchanges,whenanoldmodelisopenedin5.0,anyoccurrencesofclear-all(orca)areautomaticallychangedto__clear-all-and-reset-ticks,whichcombinestheeffectsofclear-allandreset-ticks.Thetwounderscoresonthenameindicatethatthisisnotanormalprimitive,butexistsonlyforbackwardscompatibility.
Youshouldremove__clear-all-and-reset-ticksfromyourcode,replaceitwithclear-all,andputreset-ticksattheendofyoursetupprocedure.(Thisdoesn'thappenautomaticallybecausethestructureofNetLogomodelsistoofree-formforanautomaticconvertertoreliablymakethechangeforyou.)
Unicodecharacters
NetLogo5.0fullysupportsinternationalcharacterscross-platform,usingtheUnicodecharacterset.NetLogo5.0modelfilesalwaysrepresentUnicodecharactersusingtheUTF-8encoding.
PreviousversionsofNetLogoallowedUnicodecharacterstobeusedinsomecontexts.However,modelfilesweresavedintheplatform'sdefaultencoding,whichonmostsystemswassomethingotherthanUTF-8.Characterswerehandledcorrectlyonthesameplatform(e.g.twoWindowsmachines),butcouldbealteredifthemodelwasmovedbetweenplatforms(e.g.fromWindowstoMacorviceversa).
WhenopeninganexistingmodelinNetLogo5.0,ifthemodelcontainsinternationalorothernon-ASCIIcharacters,thecharactersmaybeinterpretedincorrectly,becausetheywereoriginallywritteninaplatform-specificencoding,butthenreadbackininUTF-8.
Ifonlyafewcharactersareaffected,youmightfinditeasiestjusttofixthemmanually.
Butifyouexpectalargenumberofcharacterstobeaffected,andyouwantthemtranslatedautomatically,youcanuseathirdpartyutilitytore-encodeyour.nlogofilefromitsoriginalencodingintoUTF-8.Afterconversion,openthemodelinNetLogo5.0andallcharactersshouldbecorrect.
Infotabs
NetLogo5.0usestheMarkdownmarkuplanguagetoallowyoutoformatyourInfotab,includingheaders,boldanditalics,images,andsoforth.
![Page 168: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/168.jpg)
EarlierversionsofNetLogousedacustommarkuplanguagewithmuchmorelimitedcapabilities.
Whenopeningamodelfromanolderversion,NetLogo5.0translatesyouroldmarkupintoMarkdown.Mostofthetimethisproducesgoodresults,butyoumaywanttochecktheresultsyourselfandmakesurethatyourInfotabstilllooksgood.
Modelspeed
InNetLogo5.0everymodelhasa"targetframerate"whichaffectsthedefaultspeedatwhichthemodelruns,whenthespeedsliderisinthemiddle,onthe"normalspeed"setting.
Thedefaulttargetframeratefornewmodels,andformodelsthatwerecreatedinearlierversionsofNetLogo,is30framespersecond.Ifyouareusingtick-basedupdates,aswerecommendformostmodels,thenthattranslatesto30tickspersecond.
Ifyourmodelrunsslowerin5.0thanitranin4.1,it'sprobablyjustbecauseitsspeedisbeinglimitedbythisrate.Ifyouwant,youcanpresstheSettingsbuttonintheInterfacetabandchangetheframeratetoahighernumber.
Someoldmodelsusedtheeverycommandtosetadefaultspeed.Inmostcasethiscanbenowremovedfromthecode,andthetargetframeratesettingusedinstead.
Listperformance
TheunderlyingdatastructureforNetLogolistshaschanged.
InNetLogo4.1,aNetLogolistwasrepresentedinternallyasasinglylinkedlist.Someoperationsonsinglylinkedlistsarefast(suchasfirstandbutfirst)butothersareslowbecausetheycouldrequiretraversingthewholelist(suchasitemandlast).
InNetLogo5.0,listsarenowactuallytreesinternally.Asaresult,someoperationsarealittleslower,butotheroperationsaredrasticallyfasteronlonglists.SeetheListssectionoftheProgrammingGuidefordetails.
Somemodelsmayrunalittleslowerwiththenewdatastructure,especiallyifyoumakeheavyuseofshortlists.Butothermodelswillrunfaster--perhapsdramaticallyfaster.
Somespecialwaysofwritinglist-processingcodethatwereusefulinNetLogo4.1arenolongerneededin5.0.Forexample,sincein4.1fputwasfastandlputwasslow,modelerssometimesbuiltuplistsinreverseorderusingfput,perhapscallingreverselatertorestoretheintendedorder.InNetLogo5.0,youdon'tneedtocodethatwayanymore.fputandlputarethesamespeed.
ExtensionsAPI
Ifyouaretheauthorofanextension,youwillneedtorecompileitagainstthe5.0NetLogo.jarandlibdirectoryforittoworkwith5.0.
Youmayalsoneedtobeawareofthefollowingchanges:
Syntaxconstants
Thecodeforspecifyingthesyntaxofaprimitivehaschangedslightly,forexample
![Page 169: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/169.jpg)
Syntax.TYPE_STRINGisnowSyntax.StringType().(FromJava,thepairofparenthesesattheendisrequired.InScala,youcanomitthem.)
LogoListconstruction
Onesignificantchangeisthatorg.nlogo.api.LogoListnolongerhasapublicconstructor.Instead,therearetwonewwaystoconstructaLogoList.
Ifyouhaveajava.lang.Iterable,youcancopythecontentsintoafreshLogoListbypassingittothestaticmethodLogoList.fromJava().Seethearrayextensionsourcecodeforasampleusage.
Or,tobuildupanewlistoneitematime,useorg.nlogo.api.LogoListBuilder.TheExtensionsGuidehassamplecodeshowingtheuseofLogoListBuilder.
Primitiveclasses
InpriorNetLogoversions,theextensionsAPIrequiredthateachextensionprimitivehaveitsownseparatetop-levelclasswithano-argumentconstructor.Theselimitationshavenowbeenlifted.Also,api.Primitiveobjectsarenowmadeonlyonce,whentheextensionisloaded,insteadofeverytimetheCodetabwasrecompiled.
ChangesforNetLogo4.1
Combiningsetandof
Thefollowingsyntaxisnolongersupported:
set [<variable>] of <agent> <value>
Commandsofthisformmustberewrittenusingask:
ask <agent> [ set <variable> <value> ]
Or,ifthenewvaluemustbecomputedbytheaskingagentandnotbytheagentwhosevariableisbeingset:
;; OPTION #1 (using let):let new-value <value>ask <agent> [ set <variable> new-value ]
;; OPTION #2 (using myself):ask <agent> [ set <variable> [value] of myself ]
Soforexample,this:
set [color] of turtle 0 red
Canberewrittenas:
![Page 170: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/170.jpg)
ask turtle 0 [ set color red ]
Itisnotnecessarytouseletormyselfsinceredisredfromthepointofviewofbothagents.
However,this:
set [color] of turtle 0 color
Mustberewrittenas:
let new-color colorask turtle 0 [ set color new-color ]
or
ask turtle 0 [ set color [color] of myself ]
inordernottochangethemeaning,sincethetwoagentsmayhavedifferentstartingvaluesforcolor.Theformusingmyselfisbriefer,buttheformerusingletmaybeconsideredclearer,dependingoncontextandindividualpreference.
ChangesforNetLogo4.0
Whonumbering
PriortoNetLogo4.0,adeadturtle'swhonumber(storedinthewhoturtlevariable)couldbereassignedtoalaternewbornturtle.InNetLogo4.0,whonumbersareneverreuseduntilwhonumberingisresetto0bytheclear-allorclear-turtlescommand.Thischangeinbehaviormaybreakafewoldmodels.
Turtlecreation:randomizedvs."ordered"
NetLogo4.0providestwodifferentobservercommandsforcreatingturtles,create-turtles(crt)andcreate-ordered-turtles(cro).
crtgivesthenewturtlesrandomcolorsandrandomintegerheadings.croassignscolorssequentiallyandgivestheturtlessequentialequallyspacedheadings,withthefirstturtlefacingnorth(headingof0).
PriortoNetLogo4.0,thecrtcommandbehavedthewaycrodoesnow.Ifyouroldmodeldependsonthe"ordered"behavior,youwillneedtochangeyourcodetousecroinsteadofcrt.
Itiscommonforoldmodelsthatusedcrttocontainextracommandstorandomizethenewturtles'headings,forexamplert random 360orset heading random 360.Thesecommandsarenolongernecessarywhenusedinsidecrt.
Addingstringsandlists
PriortoNetLogo4.0,the+(addition)operatorcouldbeusedtoconcatenatestringsandjoin
![Page 171: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/171.jpg)
lists.IncurrentNetLogo,+onlyworksonnumbers.Toconcatenatestrings,usethewordprimitive;tojoinliststogether,usethesentenceprimitive.Thislanguagechangewasmadetoincreasethespeedofcodethatuses+.
Oldcode:
print "There are " + count turtles + " turtles."
Newcode:
print (word "There are " count turtles " turtles.")
Likewise,ifyouneedtoconcatenatelists,useSENTENCE.
Thischangeisnothandledautomaticallywhenconvertingoldmodels;userswillneedtochangetheircodebyhand.
Weknowthischangewillbeawkwardforuserswhoareusedtotheoldsyntax.Wehavemadethischangeforefficiencyandconsistency.Wecanimplementanadditionoperatorthatonlyaddsnumbersmuchmoreefficientlythanonethathandlesseveraldifferentdatatypes.Becauseadditionissuchacommonoperation,NetLogo'soverallspeedisaffected.
The-atprimitives
Theobservermaynolongerusepatch-at,turtles-at,andBREEDS-at.Usepatch,turtles-onpatch,andBREEDS-on patchinstead.Notethatpatchnowroundsitsinputs(beforeitonlyacceptedintegerinputs).
Links
NetLogo3.1hadsupportsforusinglinkstoconnectturtlestomakenetworks,graphs,andgeometricfigures.Thelinkswerethemselvesturtles.
InNetLogo4.0,insteadoflinksbeingturtles,linksarenowanindependentfourthagenttype,rightalongsideobserver,turtles,patches.Theprimitivesinvolvinglinksarenolongerconsideredexperimental;theyarenowfullypartofthelanguage.
Modelsthatusetheold,experimentalturtle-basedlinkprimitiveswillneedtobeupdatedtouselinkagents.Thedifferencesarenothuge,buthandupdatingisrequired.
LinksaredocumentedintheLinkssectionoftheProgrammingGuide,andintheNetLogoDictionaryentriesforthelinkprimitives.SeetheNetworkssectionoftheModelsLibraryforexamplemodelsthatuselinks.Therearealsosomelink-basedCodeExamples.
Firstyouwillneedtoremoveanybreedscalled"links"ifyouareonlyusingonetypeoflinksthenyouwillnothavetousebreedsatall.Ifyouareusingmultipletypesoflinksseeundirected-link-breedanddirected-link-breed.Commandsandreportersthatcontaintheword"links"(like__create-links-with,etc.)willautomaticallybeconvertedtothenewformwithoutunderscores(create-links-with).However,primitivesthatuseadifferentbreedname(suchas"edges")willnotbeconverted.Youwillneedtoremovetheunderscoresbyhandandunlessyouaredeclaringalinkbreedwiththatnameyouwillneedtochangethebreeddesignationto"links".
![Page 172: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/172.jpg)
Thecommandsremove-link(s)-with/from/tonolongerexist.Insteadyoushouldaskthelinksinquestiontodie.
Forexample:
ask turtle 0 [ __remove-links-with link-neighbors ]
becomes
ask turtle 0 [ ask my-links [ die ] ]
Severalofthelayoutcommandshaveslightlydifferentinputs,thefirsttwoinputsaregenerallyaturtleagentsetandalinkagentsettoperformthelayouton.Seethedictionaryentriesfordetails.layout-spring,layout-radiallayout-tutte
Youmayalsoneedtorearrangethedeclarationofturtles-ownvariables,sincelinkswereonceactuallyturtles.Anyvariablesthatapplytolinksshouldbemovedintoalinks-ownblock.
Sincelinksarenolongerturtlestheynolongerhavethebuilt-inturtlevariables(thoughsomeofthelinkvariablesarethesamesuchascolorandlabel.Ifyouformerlyusedthelocationoflinkturtlesyouwillnowneedtocalculatethemidpointofthelink.Thisisfairlysimpleinanon-wrappingworld.
to-report link-xcor report mean [xcor] of both-endsend
to-report link-ycor report mean [ycor] of both-endsend
itisalittlebittrickierinawrappingworldbutstillfairlystraightforward.
to-report link-xcor let other-guy end2 let x 0 ask end1 [ hatch 1 [ face other-guy fd [distance other-guy] of myself / 2 set x xcor die ] ] report xend
andsimilarlyforycor.
Ifyouusedeitherthesizeorheadingofthelinkturtlesyoucanusethereporterslink-lengthandlink-headinginstead.
New"of"syntax
Wehavereplacedthreedifferentlanguageconstructs,-of(withhyphen),value-from,andvalues-fromwithasingleofconstruct(nohyphen).
![Page 173: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/173.jpg)
old newcolor-of turtle 0 [color] of turtle 0
value-from turtle 0 [size * size] [size * size] of turtle 0
mean values-from turtles [size] mean [size] of turtles
Whenofisusedwithasingleagent,itreportsasinglevalue.Whenusedwithanagentset,itreportsalistofvalues(inrandomorder,sinceagentsetsarealwaysinrandomorder).
Notethatwhenopeningoldmodelsinthenewversion,-of,value-from,andvalues-fromwillautomaticallybeconvertedtouse"of"instead,butsomenestedusesoftheseconstructsaretoocomplexfortheconverterandmustbeconvertedbyhand.
Serialask
Theaskcommandisnowserialratherthanconcurrent.Inotherwords,theaskedagentswillrunoneatatime.Notuntiloneagentcompletelyfinishestheentirebodyoftheaskdoesthenextagentstart.
Notethateventheoldaskwasnevertrulyconcurrent;wesimulatedconcurrentexecutionbyinterleavingexecutionamongtheagentsusingaturn-takingmechanismdescribedintheNetLogoFAQ.
Wehavemadethischangebecauseinourexperience,usersoftenwrotemodelsthatbehavedinunexpectedwaysduetothesimulatedconcurrency,butrarelywrotemodelsthatbenefitedfromthesimulatedconcurrency.Modelsexhibitingunexpectedbehaviorcouldusuallybefixedbyaddingthewithout-interruptioncommandintherightplaces,butitwasdifficultforuserstoknowwhetherthatcommandwasneededandifso,where.
InNetLogo4.0,without-interruptionisnolongernecessaryunlessyourmodelusesask-concurrent(oraturtleorpatchforeverbuttoncontainingcodethatdependsonsimulatedconcurrency).Inmostmodels,allusesofwithout-interruptioncanberemoved.
Thesimulatedconcurrencyformerlyemployedby"ask"isstillaccessibleinthreeways:
Youmayusetheask-concurrentprimitiveinsteadofasktogettheoldsimulatedconcurrency.(Wedon'trecommendthis,though.)CommandsissuedintheCommandCenterdirectlytoturtles,patches,orlinkshaveanimpliedask-concurrent.Turtle,patch,andlinkforeverbuttonshaveanimpliedask-concurrentaswell.
Notethataskitselfisalwaysserialregardlessofthecontextinwhichitisused,however.
InourownModelsLibrary,modelsthatmakeuseofthisconcurrencyarerare.Aprominentexample,though,isTermites,whichusesaconcurrentturtleforeverbutton.
Tickcounter
NetLogonowhasabuilt-intickcounterforrepresentingthepassageofsimulatedtime.
Youadvancethecounterbyoneusingthetickcommand.Ifyouneedtoreaditsvalue,there'sareportercalledticks.Theclear-allcommandresetsthetickcounter;sodoesreset-ticks.
Inmostmodelsthetickcounterwillbeinteger-valued,butifyouwanttousesmallerincrementsoftime,youcanusethetick-advancecommandtoadvancethetickcounterby
![Page 174: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/174.jpg)
anypositiveamount,includingfractionalamounts.SomeModelsLibrarymodelsthatusetick-advanceareVectorFieldsandtheGasLabmodels.
ThevalueofthetickcounterisdisplayedinthetoolbaratthetopoftheInterfacetab.(YoucanusetheSettings...buttoninthetoolbartohidethetickcounter,orchangetheword"ticks"tosomethingelse.)
Viewupdatemodes
Inthepast,NetLogoalwaystriedtoupdatetheviewabout20timesasecond.We'renowcallingthat"continuous"viewupdates.Thebiggestproblemwithitwasthatyouusuallywantupdatestohappenbetweenmodelticks,notinthemiddleofatick,sowehadacheckboxonbuttonsthat(bydefault)forcedadisplayupdateaftereverybuttoniteration.Thatmadesureupdateshappenedbetweenticks,butitdidn'tgetridoftheintermediateupdates.Youhadtouseno-displayanddisplaytolockthemout.
Westillsupportcontinuousupdates.TheyarethedefaultwhenyoustartupNetLogo.ButmostModelsLibrarymodelsnowusetick-basedupdates.Withtick-basedupdates,updateshappenonlywhenthetickcounteradvances.(Thedisplaycommandcanbeusedtoforceadditionalupdates;seebelow.)
Theadvantagesoftick-basedupdatesasweseethemareasfollows:
1. Consistent,predictableviewupdatebehaviorwhichdoesnotvaryfromcomputertocomputerorfromruntorun.
2. Intermediateupdatescanconfusetheuserofyourmodelbylettingthemseethingstheyaren'tsupposedtosee,whichmaybemisleading.
3. Increasedspeed.Updatingtheviewtakestime,soifoneupdatepertickisenough,thenenforcingthanthereisonlyoneupdatepertickwillmakeyourmodelfaster.
4. Insteadofhavinga"forceviewupdate"checkboxineverybuttonlikeinNetLogo3.1,weonlyneedonechoicewhichappliestotheentiremodel.
5. Usingthespeedslidertoslowdownamodelnowjustinsertspausesbetweenticks.Sowithtick-basedupdates,setupbuttonsarenolongeraffectedbythespeedslider.Thiswasarealannoyancewiththeoldspeedslider.(Theannoyancepersistsformodelsthatusecontinuousupdates,though.)
Asmentionedabove,mostmodelsinourModelsLibrarynowusetick-basedupdates.
Evenformodelsthatwouldnormallybesettotick-basedupdates,itmaybeusefultoswitchtocontinuousupdatestemporarilyfordebuggingpurposes.Seeingwhat'sgoingonwithinatick,insteadofonlyseeingtheendresultofatick,couldhelpwithtroubleshooting.
Ifyouswitchyourmodeltousetick-basedupdates,you'llalsoneedtoaddthetickcommandtoyourcode,otherwisetheviewwon'tupdate.(Notethattheviewstillalwaysupdateswhenabuttonpopsuporacommandenteredinthecommandcenterfinishes,though.Soit'snotliketheviewwilljuststayfrozenindefinitely.)
Howtomakeamodeluseticksandtick-basedupdates
Herearethestepstofollowtoconvertyourmodeltouseticksandtick-basedupdatesinNetLogo4.0:
1. IntheInterfacetabtoolbar,ontherighthandsidewhereitsays"updateview:",changethesettingfrom"continuously"to"onticks".
2. Addthetickcommandtoyourgoprocedure,atorneartheend.InModelsLibrary
![Page 175: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/175.jpg)
modelswealwaysputtickaftertheagentsmovebutbeforeanyplottingcommands.That'sbecausetheplottingcommandsmightcontainsomethinglikeplotxy ticks ...andwewantthenewvalueofthetickcounterused,nottheoldone.Mostmodelsdon'trefertothetickcounterintheirplottingcommands,butnonetheless,forconsistencyandtoavoidmistakeswesuggestalwaysputtingtickbeforetheplottingcommands.
Somemodelswillrequiresomeadditionalchanges:
1. Ifyourmodelalreadyhasaglobal"ticks"or"clock"or"time"variable,getridofit.Usethetickcommandandticksreporterinstead.(Ifyourmodelusesfractionalincrementsoftime,usetick-advanceinsteadoftick.)Ifyouhadamonitorforthatvariable,youcangetridofit;there'snowatickcounterinthetoolbar.
2. clear-allresetsthetickcountertozero.Ifyoudon'tuseclear-allinyoursetupprocedure,thenyoumayneedtoaddreset-tickstoresetthecountertozero.
3. Ifyouusedno-displayanddisplaytopreventviewupdatesfromhappeninginthemiddleofgo,youcangetridofthem.
4. Ifyourmodelneedstoupdatetheviewwithoutadvancingthetickcounter(examples:Party,DiceStalagmite,networkmodelswithanimatedlayout,modelswithmouseinteractionbuttons),usethedisplaycommandtoforceadditionalviewupdatessotheusercanseewhatisgoingon.
Speedslider
PreviousversionsofNetLogohadaspeedsliderthatcouldbeusedtomakemodelsrunslower,soyoucanseewhat'sgoingon.
InNetLogo4.0,theslidercanbeusedtospeedupmodelsaswell.Itdoesthisbyupdatingtheviewlessfrequently.Updatingtheviewtakestime,sothefewerupdates,thefasterthemodelruns.
Thedefaultpositionofthesliderisinthecenter.Whenyou'reatthecenter,theslidersays"normalspeed".
Asyoumovethesliderawayfromthecenterposition,themodelwillgraduallyrunfasterorslower.
Atveryhighspeeds,viewupdatesbecomeveryinfrequentandmaybeseparatedbyseveralseconds.Itmayfeellikethemodelisactuallyrunningslower,sincetheupdatesaresoinfrequent.Butwatchthetickcounter,orotherindicatorssuchasplots,andyou'llseethatyes,themodelreallyisrunningfaster.Iftheinfrequentupdatesaredisconcerting,don'tpushtheslidersofarover.
Whenusingtick-basedupdates,slowingthemodeldowndoesnotcauseadditionalviewupdates.Rather,NetLogosimplypausesaftereachtick.
Whenusingcontinuousupdates,slowingthemodeldownmeansviewupdatesbecomemorecloselyspaced.Ifyoupushthespeedslidermorethanhalfwaytotheleft,themodelwillberunningsoslowlythatyoucanwatchturtlesmovingoneatatime!ThisisnewinNetLogo4.0;inpreviousNetLogoversions,nomatterhowslowlyyouranamodel,youwouldneverseetheagentsinanaskmovingoneatatime;alltheagentsinanaskalwaysappearedtomovetogether.
Numbers
NetLogonolongermaintainsaninternaldistinctionbetweenintegersandfloatingpoint
![Page 176: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/176.jpg)
numbers.Soforexample:
Old:
observer> print 33observer> print 3.03.0observer> print 1 + 23observer> print 1.5 + 1.53.0observer> print 3 = 3.0true
(Thelastlineshowsthatalthoughthedistinctionbetweeninteger3andfloatingpoint3.0wasmaintained,thetwonumberswerestillconsideredequal.)
New:
observer> print 33observer> print 3.03observer> print 1 + 23observer> print 1.5 + 1.53observer> print 3 = 3.0true
Weexpectthatonlyraremodelswillbenegativelyimpactedbythischange.
AbenefitofthischangeisthatNetLogonowsupportsamuchlargerrangeofintegers.Theoldrangewas-2,147,483,648to2,147,483,647(around+/-2billion);thenewrangeis+/-9,007,199,254,740,992(around+/-9quadrillion).
Agentsetbuilding
NetLogo3.1(andsomeearlierversions)includedprimitivescalledturtles-fromandpatches-fromthatwereoccasionallyusefulforbuildingagentsets.InNetLogo4.0,theseprimitiveshavebeenreplacedwithnewprimitivescalledturtle-setandpatch-setthataremuchmoreflexibleandpowerful.(link-setexistsaswell.)SeetheentriesfortheseprimitivesintheNetLogoDictionary.Modelsthatusetheoldturtles-fromandpatches-fromwillneedtobealteredbyhandtousethenewprimitives.
RGBColors
InNetLogo3.1RGBandHSBcolorscouldbeapproximatedasNetLogocolorsusingthergbandhsbprimitives.Thesehavebeenrenamedtoapproximate-rgbandapproximate-hsbandnowexpectinputsintherange0-255,not0-1.
ThefullRGBspectrumisnowavailableinNetLogosoitmaynolongerbenecessarytousetheseprimitivesatall.Youcansetanycolorvariabletoathree-itemRGBlist,withvaluesinthe0-255range,andgetthatexactcolor.SeetheColorsectionoftheProgrammingGuidefordetails.
![Page 177: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/177.jpg)
Tie
Inpreviousversions__tiewasprovidedasanexperimentalfeature.AsofNetLogo4.0linkshaveatie-modevariablewhichcanbesetto"none","free",or"fixed".In4.0tieisnowalink-onlyprimitive.Thismeansthattotieturtle1toturtle0youwrite:
ask turtle 0 [ create-link-to turtle 1 [ tie ] ]
SeetheTiesectionoftheprogrammingguidefordetails.
ChangesforNetLogo3.1
Agentsets
Ifyourmodelisbehavingstrangelyorincorrectly,itmaybebecausesinceNetLogo3.1,agentsetsarenowalwaysinrandomorder.InpriorversionsofNetLogo,agentsetswerealwaysinafixedorder.Ifyourcodedependedonthatfixedorder,thenitwon'tworkanymore.Howtofixyourmodeltoworkwithrandomizedagentsetsdependsonthedetailsofwhatyourcodeisdoing.Insomesituations,itishelpfultousethesortorsort-byprimitivestoconvertanagentset(randomorder)intoalistofagents(fixedorder).See"Listsofagents"intheListssectionoftheProgrammingGuide.
Wrapping
Ifyouareseeingpiecesofturtleshapeswrappingaroundtheviewedges,it'sbecauseNetLogo3.0allowedyoutoturnoffsuchwrappingintheviewwithoutaffectingthebehaviorofthemodel.SinceNetLogo3.1,ifyoudon'twanttheviewtowrapyoumustmakeitsotheworlddoesn'twrap,usingthenewtopologyfeature.Makingthischangemayrequireotherchangestoyourmodel,though.SeetheTopologysectionoftheProgrammingGuideforathoroughdiscussionofhowtoconvertyourmodeltotakeadvantageofthisnewfeature.
Randomturtlecoordinates
ManymodelsmadeinNetLogo3.0orearlierusesetxy random world-width random world-heighttoscatterturtlesrandomly,usingeitherrandomorrandom-float.Itonlyworksifworldwrappingison.
(Why?Becausewhenwrappingison,youcansetcoordinatesofturtlestonumbersbeyondtheedgeoftheworldandNetLogowillwraptheturtletotheotherside.Butinworldsthatdon'twrapsettingthexorycoordinatesofaturtletoapointoutsidetheboundsoftheworldcausesaruntimeerror.TheworldwrapsettingswereaddedinNetLogo3.1.SeetheTopologysectionoftheProgrammingGuideformoreinformation.)
Tofixyourmodelsothatitworksregardlessofthewrappingsettings,useoneofthesetwocommandsinstead:
setxy random-xcor random-ycorsetxy random-pxcor random-pycor
Thetwocommandsareabitdifferent.Thefirstcommandputstheturtleonarandompointin
![Page 178: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/178.jpg)
theworld.Thesecondcommandputstheturtleonthecenterofarandompatch.Anevenmoreconcisewaytoputaturtleonthecenterofarandompatchis:
move-to one-of patches
![Page 179: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/179.jpg)
ShapesEditorGuide
TheTurtleandLinkShapeEditorsallowsyoutocreateandsaveturtleandlinkdesigns.
NetLogousesfullyscalableandrotatablevectorshapes,whichmeansyoucancreatedesignsbycombiningbasicgeometricelements,whichcanappearon-screeninanysizeororientation.
Gettingstarted
Tobeginmakingshapes,chooseTurtleShapesEditororLinkShapesEditorintheToolsmenu.Anewwindowwillopenlistingalltheshapescurrentlyinthemodel,beginningwithdefault,thedefaultshape.TheShapesEditorallowsyoutoeditshapes,createnewshapes,andborrowfromanothermodel.Youcanalsoimportturtleshapesfromalibraryofpre-existingshapes.
Importingshapes
EverynewmodelinNetLogostartsoffcontainingasmallcoresetoffrequentlyusedshapes.ManymoreturtleshapesareavailablebyusingtheImportfromlibrary...button.Thisbringsupadialogwhereyoucanselectoneormoreshapesandbringthemintoyourmodel.Selecttheshapes,thenpresstheImportbutton.
Similarly,youcanusetheImportfrommodel...buttontoborrowshapesfromanothermodel.
Defaultshapes
HerearetheturtleshapesthatareincludedbydefaultineverynewNetLogomodel:
Firstrow:default,airplane,arrow,box,bug,butterfly,carSecondrow:circle,circle2,cow,cylinder,dot,facehappy,faceneutralThirdrow:facesad,fish,flag,flower,house,leaf,lineFourthrow:linehalf,pentagon,person,plant,sheep,square,square2
![Page 180: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/180.jpg)
Fifthrow:star,target,tree,triangle,triangle2,truck,turtleSixthrow:wheel,x
Shapeslibrary
Andherearetheshapesintheshapeslibrary(includingallofthedefaultshapes,too):
BydefaultthereisonlyoneLinkshapeinamodel,thatis"default".Thisshapeissimplyasinglestraightlinewithasimplearrowhead(ifthelinkhappenstobedirected).
![Page 181: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/181.jpg)
Creatingandeditingturtleshapes
PressingtheNewbuttonwillmakeanewshape.Or,youmayselectanexistingshapeandpressEdit.
Tools
Intheupperleftcorneroftheeditingwindowisagroupofdrawingtools.Thearrowistheselectiontool,whichselectsanalreadydrawnelement.
Todrawanewelement,useoneoftheotherseventools:
Thelinetooldrawslinesegments.Thecircle,square,andpolygontoolscomeintwoversions,solidandoutline.
Whenusingthepolygontool,clickthemousetoaddanewsegmenttothepolygon.Whenyou'redoneaddingsegments,doubleclick.
Afteryoudrawanewelement,itisselected,soyoucanmove,delete,orreshapeitifyouwant:
Tomoveit,dragitwiththemouseTodeleteit,presstheDeletebutton.Toreshapeit,dragthesmall"handles"thatappearontheelementonlywhenitisselected.Tochangeitscolor,clickonthenewcolor.
Previews
Asyoudrawyourshape,youwillalsoseeitinfivesmallersizesinthefivepreviewareasfoundnearthebottomoftheeditingwindow.Thepreviewsshowyourshapeasitmightappearinyourmodel,includinghowitlooksasitrotates.Thenumberbeloweachpreviewisthesizeofthepreviewinpixels.Whenyouedittheview,patchsizeisalsomeasuredinpixels.Soforexample,thepreviewwith"20"belowitshowsyouhowyourshapewouldlookonaturtle(ofsize1)onpatchesofsize20pixels.
![Page 182: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/182.jpg)
Therotatablefeaturecanbeturnedoffifyouwantashapethatalwaysfacesthesameway,regardlessoftheturtle'sheading.
Overlappingshapes
Newelementsgoontopofpreviouselements.YoucanchangethelayeringorderbyselectinganelementandthenusingtheBringtofrontandSendtobackbuttons.
Undo
AtanypointyoucanusetheUndobuttontoundotheedityoujustperformed.
Colors
ElementswhosecolormatchestheColorthatchanges(selectedfromadrop-downmenu--thedefaultisgray)willchangecoloraccordingtothevalueofeachturtle'scolorvariableinyourmodel.Elementsofothercolorsdon'tchange.Forexample,youcouldcreatecarsthatalwayshaveyellowheadlightsandblackwheels,butdifferentbodycolors.
Otherbuttons
The"RotateLeft"and"RotateRight"buttonsrotateelementsby90degrees.The"FlipHorizontal"and"FlipVertical"buttonsreflectelementsacrosstheaxes.
Thesefourbuttonswillrotateorfliptheentireshape,unlessanelementisselected,inwhichcaseonlythatelementisaffected.
Thesebuttonsareespeciallyhandyinconjunctionwiththe"Duplicate"buttonifyouwanttomakeshapesthataresymmetrical.Forexample,ifyouweremakingabutterfly,youcoulddrawthebutterfly'sleftwingwiththepolygontool,thenduplicatethewingwiththe"Duplicate"button,thenturnthecopyintoarightwingwiththe"FlipHorizontal"button.
Shapedesign
It'stemptingtodrawcomplicated,interestingshapes,butrememberthatinmostmodels,thepatchsizeissosmallthatyouwon'tbeabletoseeverymuchdetail.Simple,bold,iconicshapesareusuallybest.
Keepingashape
Whentheshapeisdone,giveitanameandpresstheDonebuttonatthebottomoftheeditingwindow.Theshapeanditsnamewillnowbeincludedinthelistofshapesalongwiththe"default"shape.
Creatingandeditinglinkshapes
Managinglinkshapesisverysimilartomanagingturtleshapes.So,youcancreateanewshapebypressingtheNewbuttonoryoucaneditexistingshapes.WhenyouaredoneeditingashapepressDoneifyouwanttokeepit.
![Page 183: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/183.jpg)
Changinglinkshapeproperties
Thereareseveraldifferentpropertiesforeachlinkshapethatyouareallowedtochange:
Name-linkshapescanhavethesamenameasturtleshapesbutmustbeuniqueamonglinkshapes.DirectionIndicator-thedirectionindicator(thelittlearrowondirectedlinks)isjustliketheturtlevectorshapes,youcanedititusingthesameeditorbypressingtheEditbutton.Curviness-thisistheamountofbendinalinkexpressedinpatches(thisisparticularlyusefulifyouhavedirectedlinksgoinginbothdirectionssoyoucandiscernbothlinks)Numberoflines:Youcanhave1,2,or3linesineachlinkshape,youcontrolthisbyselectinglinepatternsinthe"leftline","middleline",and"rightline"selectionboxes.Dashpatternoflines:Thereareseveraldashedlinepatternsavailableintheselectionboxessonotalllinesneedbesolid.
Herearesomelinkshapeswithvariousproperties:
Usingshapesinamodel
Inthemodel'scodeorinthecommandcenter,youcanuseanyoftheshapesthatareinthemodel(thoughonlyturtlescanhaveturtleshapesandonlylinkscanhavelinkshapes).Forexample,supposeyouwanttocreate50turtleswiththeshape"rabbit".Providedthereissometurtleshapecalledrabbitinthismodel,givethiscommandtotheobserverinthecommandcenter:
observer> crt 50
Andthengivethesecommandstotheturtlestospreadthemout,thenchangetheirshape:
turtles> fd random 15turtles> set shape "rabbit"
![Page 184: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/184.jpg)
Voila!Rabbits!Notetheuseofdoublequotesaroundtheshapename.Shapenamesarestrings.
Similarly,youcansettheshapevariableoflinks.Assumingthereisalinkshapecalled"road"inthismodel:
observer> crt 5 [ create-links-with other turtles ]turtles> fd 5links> set shape "road"
Theset-default-shapecommandisalsousefulforassigningshapestoturtlesandlinks.
![Page 185: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/185.jpg)
BehaviorSpaceGuide
Thisguidehasthreeparts:
WhatisBehaviorSpace?:Ageneraldescriptionofthetool,includingtheideasandprinciplesbehindit.HowItWorks:Walksyouthroughhowtousethetoolandhighlightsitsmostcommonlyusedfeatures.AdvancedUsage:HowtouseBehaviorSpacefromthecommandline,orfromyourownJavacode.
WhatisBehaviorSpace?
BehaviorSpaceisasoftwaretoolintegratedwithNetLogothatallowsyoutoperformexperimentswithmodels.
BehaviorSpacerunsamodelmanytimes,systematicallyvaryingthemodel'ssettingsandrecordingtheresultsofeachmodelrun.Thisprocessissometimescalled"parametersweeping".Itletsyouexplorethemodel's"space"ofpossiblebehaviorsanddeterminewhichcombinationsofsettingscausethebehaviorsofinterest.
Ifyourcomputerhasmultipleprocessorcores,thenbydefault,modelrunswillhappeninparallel,onepercore.
WhyBehaviorSpace?
Theneedforthistypeofexperimentisrevealedbythefollowingobservations.Modelsoftenhavemanysettings,eachofwhichcantakearangeofvalues.Togethertheyformwhatinmathematicsiscalledaparameterspaceforthemodel,whosedimensionsarethenumberofsettings,andinwhicheverypointisaparticularcombinationofvalues.Runningamodelwithdifferentsettings(andsometimeseventhesameones)canleadtodrasticallydifferentbehaviorinthesystembeingmodeled.So,howareyoutoknowwhichparticularconfigurationofvalues,ortypesofconfigurations,willyieldthekindofbehavioryouareinterestedin?Thisamountstothequestionofwhereinitshuge,multi-dimensionparameterspacedoesyourmodelperformbest?
Forexample,supposeyouwantspeedysynchronizationfromtheagentsintheFirefliesmodel.Themodelhasfoursliders--number,cycle-length,flash-lengthandnumber-flashes--thathaveapproximately2000,100,10and3possiblevalues,respectively.Thatmeansthereare2000*100*10*3=600,000possiblecombinationsofslidervalues!Tryingcombinationsoneatatimeishardlyanefficientwaytolearnwhichonewillevokethespeediestsynchronization.
BehaviorSpaceoffersyouamuchbetterwaytosolvethisproblem.Ifyouspecifyasubsetofvaluesfromtherangesofeachslider,itwillrunthemodelwitheachpossiblecombinationofthosevaluesand,duringeachmodelrun,recordtheresults.Indoingso,itsamplesthemodel'sparameterspace--notexhaustively,butenoughsothatyouwillbeabletoseerelationshipsformbetweendifferentslidersandthebehaviorofthesystem.Afteralltherunsareover,adatasetisgeneratedwhichyoucanopeninadifferenttool,suchasaspreadsheet,database,orscientificvisualizationapplication,andexplore.
Byenablingyoutoexploretheentire"space"ofbehaviorsamodelcanexhibit,BehaviorSpacecanbeapowerfulassistanttothemodeler.
![Page 186: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/186.jpg)
HowItWorks
TobeginusingBehaviorSpace,openyourmodel,thenchoosetheBehaviorSpaceitemonNetLogo'sToolsmenu.
Managingexperimentsetups
Thedialogthatopensletsyoucreate,edit,duplicate,delete,andrunexperimentsetups.Experimentsarelistedbynameandhowbymodelrunstheexperimentwillconsistof.
ExperimentsetupsareconsideredpartofaNetLogomodelandaresavedaspartofthemodel.
Tocreateanewexperimentsetup,pressthe"New"button.
Creatinganexperimentsetup
Inthenewdialogthatappears,youcanspecifythefollowinginformation.Notethatyoudon'talwaysneedtospecifyeverything;somepartscanbeleftblank,orleftwiththeirdefaultvalues,dependingonyourneeds.
Experimentname:Ifyouhavemultipleexperiments,givingthemdifferentnameswillhelpyoukeepthemstraight.
Varyvariablesasfollows:Thisiswhereyouspecifywhichsettingsyouwantvaried,andwhatvaluesyouwantthemtotake.Variablescanincludesliders,switches,choosers,andanyglobalvariablesinyourmodel.
Variablescanalsoincludemax-pxcor,min-pxcor,max-pycorandmin-pycor,world-width,world-heightandrandom-seed.Thesearenot,strictlyspeaking,variables,butBehaviorSpaceletsyouvarythemasiftheywere.Varyingtheworlddimensionsletsyouexploretheeffectofworldsizeuponyourmodel.Sincesettingworld-widthandworld-heightdoesnotnecessarilydefinetheboundsoftheworldhowtheyarevarieddependsonthelocationoftheorigin.Iftheoriginiscentered,BehaviorSpacewillkeepitcenteredsothevaluesworld-widthorworld-heightmustbeodd.Ifoneoftheboundsisatzerothatboundwillbekeptatzeroandtheotherboundwillmove,forexampleifyoustartwithaworldwithmin-pxcor = 0max-pxcor= 10andyouvaryworld-widthlikethis:
["world-width" [11 1 14]]
min-pxcorwillstayatzeroandmax-pxcorwillsetto11,12,and13foreachoftheruns.Ifneitheroftheseconditionsaretrue,theoriginisnotcentered,norattheedgeoftheworldyoucannotvaryworld-heightorworld-widthdirectlybutyoushouldvarymax-pxcor,max-pycor,min-pxcorandmin-pycorinstead.
Varyingrandom-seedletsyourepeatrunsbyusingaknownseedfortheNetLogorandomnumbergenerator.Notethatyou'realsofreetousetherandom-seedcommandinyourexperiment'ssetupcommands.Formoreinformationonrandomseeds,seetheRandomNumberssectionoftheProgrammer'sGuide.
Youmayspecifyvalueseitherbylistingthevaluesyouwantused,orbyspecifyingthatyouwanttotryeveryvaluewithinagivenrange.Forexample,togiveaslidernamednumbereveryvaluefrom100to1000inincrementsof50,youwouldenter:
![Page 187: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/187.jpg)
["number" [100 50 1000]]
Or,togiveitonlythevaluesof100,200,400,and800,youwouldenter:
["number" 100 200 400 800]
Becarefulwiththebracketshere.Notethattherearefewersquarebracketsinthesecondexample.IncludingornotincludingthisextrasetofbracketsishowyoutellBehaviorSpacewhetheryouarelistingindividualvalues,orspecifyingarange.
Alsonotethatthedoublequotesaroundthevariablenamesarerequired.
Youcanvaryasmanysettingsasyouwant,includingjustone,ornoneatall.Anysettingsthatyoudonotvarywillretaintheircurrentvalues.Notvaryinganysettingsisusefulifyoujustwanttodomanyrunswiththecurrentsettings.
Whatorderyoulistthevariablesindetermineswhatordertherunswillbedonein.Allvaluesforalatervariablewillbetriedbeforemovingtothenextvalueforanearliervariable.Soforexampleifyouvarybothxandyfrom1to3,andxislistedfirst,thentheorderofmodelrunswillbe:x=1y=1,x=1y=2,x=1y=3,x=2y=1,andsoon.
Repetitions:Sometimesthebehaviorofamodelcanvaryalotfromruntorunevenifthesettingsdon'tchange,ifthemodelusesrandomnumbers.Ifyouwanttorunthemodelmorethanonceateachcombinationofsettings,enterahighernumber.
Measurerunsusingthesereporters:Thisiswhereyouspecifywhatdatayouwanttocollectfromeachrun.Forexample,ifyouwantedtorecordhowthepopulationofturtlesroseandfellduringeachrun,youwouldenter:
count turtles
Youcanenteronereporter,orseveral,ornoneatall.Ifyouenterseveral,eachreportermustbeonalinebyitself,forexample:
count frogs count mice count birds
Ifyoudon'tenteranyreporters,therunswillstilltakeplace.Thisisusefulifyouwanttorecordtheresultsyourselfyourownway,suchaswiththeexport-worldcommand.
Measurerunsateverystep:NormallyNetLogowillmeasuremodelrunsateverystep,usingthereportersyouenteredinthepreviousbox.Ifyou'redoingverylongmodelruns,youmightnotwantallthatdata.Uncheckthisboxifyouonlywanttomeasureeachrunafteritends.
Setupcommands:Thesecommandswillbeusedtobegineachmodelrun.Typically,youwillenterthenameofaprocedurethatsetsupthemodel,typicallysetup.Butitisalsopossibletoincludeothercommandsaswell.
![Page 188: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/188.jpg)
Gocommands:Thesecommandswillberunoverandoveragaintoadvancetothemodeltothenext"step".Typically,thiswillbethenameofaprocedure,suchasgo,butyoumayincludeanycommandsyoulike.
Stopcondition:Thisletsyoudomodelrunsofvaryinglength,endingeachrunwhenacertainconditionbecomestrue.Forexample,supposeyouwantedeachruntolastuntiltherewerenomoreturtles.Thenyouwouldenter:
not any? turtles
Ifyouwantthelengthofrunstoallbeofafixedlength,justleavethisblank.
Therunmayalsostopbecausethegocommandsusethestopcommand,inthesamewaythatstopcanbeusedtostopaforeverbutton.Thestopcommandmaybeuseddirectlyinthegocommands,orinaprocedurecalleddirectlybythegocommands.(TheintentisthatthesamegoprocedureshouldworkbothinabuttonandinaBehaviorSpaceexperiment.)Notethatthestepinwhichstopisusedisconsideredtohavebeenaborted,sonoresultswillberecordedforthatstep.Therefore,thestoppingtestshouldbeatthebeginningofthegocommandsorprocedure,notattheend.
Finalcommands:Theseareanyextracommandsthatyouwantrunonce,whentherunends.Usuallythisisleftblank,butyoumightuseittocalltheexport-worldcommandorrecordtheresultsoftheruninsomeotherway.
Timelimit:Thisletsyousetafixedmaximumlengthforeachrun.Ifyoudon'twanttosetanymaximum,butwantthelengthoftherunstobecontrolledbythestopconditioninstead,enter0.
SpecialprimitivesforBehaviorSpaceexperiments
Currentlythereareonlytwo,behaviorspace-run-numberandbehaviorspace-experiment-name.TherunnumberreportedbytheformerprimitivematchestherunnumberusedintheresultsfilesgeneratedbyBehaviorSpace.Theexperimentnamereportedbythelattermatchesthenamewithwhichtheexperimentwassetup.
Runninganexperiment
Whenyou'redonesettingupyourexperiment,pressthe"OK"button,followedbythe"Run"button.Adialogtitled"Runoptions"willappear.
Runoptions:formats
Therunoptionsdialogletsyouselecttheformatsyouwouldlikethedatafromyourexperimentsavedin.Dataiscollectedforeachrunorstep,accordingtothesettingofMeasurerunsateverystepoption.Ineithercase,theinitialstateofthesystemisrecorded,afterthesetupcommandsrunbutbeforethegocommandsrunforthefirsttime.
Tableformatlistseachintervalinarow,witheachmetricinaseparatecolumn.Tabledataiswrittentotheoutputfileaseachruncompletes.Tableformatissuitableforautomatedprocessingofthedata,suchasimportingintoadatabaseorastatisticspackage.
Spreadsheetformatcalculatesthemin,mean,max,andfinalvaluesforeachmetric,andthenlistseachintervalinarow,witheachmetricinaseparatecolumn.Spreadsheetdataismore
![Page 189: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/189.jpg)
human-readablethanTabledata,especiallyifimportedintoaspreadsheetapplication.
(Notehoweverthatspreadsheetdataisnotwrittentotheresultsfileuntiltheexperimentfinishes.Sincespreadsheetdataisstoredinmemoryuntiltheexperimentisdone,verylargeexperimentscouldrunoutofmemory.Soyoushoulddisablespreadsheetoutputunlessyoureallywantit.Ifyoudowantspreadsheetoutput,notethatifanythinginterruptstheexperiment,suchasaruntimeerror,runningoutofmemory,oracrashorpoweroutage,nospreadsheetresultswillbewritten.Forlongexperiments,youmaywanttoalsoenabletableformatasaprecautionsothatifsomethinghappensandyougetnospreadsheetoutputyou'llatleastgetpartialtableoutput.)
Afterselectingyouroutputformats,BehaviorSpacewillpromptyouforthenameofafiletosavetheresultsto.Thedefaultnameendsin".csv".Youcanchangeittoanynameyouwant,butdon'tleaveoffthe".csv"part;thatindicatesthefileisaCommaSeparatedValues(CSV)file.Thisisaplain-textdataformatthatisreadablebyanytexteditoraswellasbymostpopularspreadsheetanddatabaseprograms.
Runoptions:parallelruns
Therunoptionsdialogalsoletsyouselectwhetheryouwantmultiplemodelrunstohappeninparallel,andifso,howmanyareallowedtobesimultaneouslyactive.Thisnumberwilldefaulttothenumberofprocessorcoresinyourcomputer.
Thereareafewcautionsassociatedwithparallelruns.
First,ifmultiplerunsareactive,onlyoneofthemwillbeinthe"foreground"andcausetheviewandplotstoupdate.Theotherrunswillhappeninvisiblyinthebackground.
Second,invisiblebackgroundrunscan'tuseprimitivesthatonlyworkintheGUI.Forexample,abackgroundruncan'tmakeamovie.
Third,sinceparallelrunsprogressindependentlyofeachother,tableformatoutputmaycontaininterleaved,out-of-orderresults.Whenyouanalyzeyourtabledata,youmaywishtosortitbyrunnumberfirst.(Spreadsheetformatoutputisnotaffectedbythisissue,sinceitisnotwrittenuntiltheexperimentcompletesorisaborted.)
Fourth,usingallavailableprocessorcoresmaymakeyourcomputerslowtouseforothertaskswhiletheexperimentisrunning.
Fifth,doingrunsinparallelwillmultiplytheexperiment'smemoryrequirementsaccordingly.YoumayneedtoincreaseNetLogo'smemoryceiling(seethisFAQentry).
Observingruns
Afteryoucompletetherunoptionsdialog,anotherdialogwillappear,titled"RunningExperiment".Inthisdialog,you'llseeaprogressreportofhowmanyrunshavebeencompletedsofarandhowmuchtimehaspassed.Ifyouenteredanyreportersformeasuringtheruns,andifyouleftthe"Measurerunsateverystep"boxchecked,thenyou'llseeaplotofhowtheyvaryoverthecourseofeachrun.
YoucanalsowatchtherunsinthemainNetLogowindow.(Ifthe"RunningExperiment"dialogisintheway,justmoveittoadifferentplaceonthescreen.)Theviewandplotswillupdateasthemodelruns.Ifyoudon'tneedtoseethemupdate,thenusethecheckboxesinthe"RunningExperiment"dialogtoturntheupdatingoff.Thiswillmaketheexperimentgofaster.
Ifyouwanttostopyourexperimentbeforeit'sfinished,pressthe"Abort"button.Anyresults
![Page 190: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/190.jpg)
generatedsofarwillstillbesaved.
Whenalltherunshavefinished,theexperimentiscomplete.
Advancedusage
Runningfromthecommandline
ItispossibletorunBehaviorSpaceexperiments"headless",thatis,fromthecommandline,withoutanygraphicaluserinterface(GUI).Thisisusefulforautomatingrunsonasinglemachineoraclusterofmachines.
NoJavaprogrammingisrequired.ExperimentsetupscanbecreatedintheGUIandthenrunlaterfromthecommandline,or,ifyouprefer,youcancreateoreditexperimentsetupsdirectlyusingXML.
Howtouseit
RunNetLogousingtheincludedcommandlinescript.ThisisfoundintherootdirectoryofyourNetLogoinstallationandisnamednetlogo-headless.shonMacandLinuxandnetlogo-headless.batonWindows.Thenetlogo-headlessscriptsupportsthefollowingarguments:
--model <path>:pathnameofmodeltoopen(required)--setup-file <path>:readexperimentsetupsfromthisfileinsteadofthemodelfile--experiment <name>:nameofexperimenttorun--table <path>:pathnametosendtableoutputto(or-forstandardoutput)--spreadsheet <path>:pathnametosendtableoutputto(or-forstandardoutput)--threads <number>:usethismanythreadstodomodelrunsinparallel,or1todisableparallelruns.defaultstoonethreadperprocessor.--min-pxcor <number>:overrideworldsizesettinginmodelfile--max-pxcor <number>:overrideworldsizesettinginmodelfile--min-pycor <number>:overrideworldsizesettinginmodelfile--max-pycor <number>:overrideworldsizesettinginmodelfile
--modelisrequired.Ifyoudon'tspecify--experiment,youmustspecify--setup-file.Bydefaultnoresultsaregenerated,soyou'llusuallywanttospecifyeither--tableor--spreadsheet,orboth.Ifyouspecifyanyoftheworlddimensions,youmustspecifyallfour.
Note:Theremainderofthisguideusesnetlogo-headless.shtorefertotheNetLogoHeadlesslaunchscript.IfyouareusingWindows,pleasesubstitutenetlogo-headless.batfornetlogo-headless.shineachexample.
Examples
ItiseasiestifyoucreateyourexperimentsetupaheadoftimeintheGUI,soitissavedaspartofthemodel.Torunanexperimentsetupsavedinamodel,hereisanexamplecommandline:
netlogo-headless.sh \ --model Fire.nlogo \ --experiment experiment1 \ --table -
![Page 191: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/191.jpg)
Forthistowork,Java(version1.8orlater)mustbeavailable.YoucanmakeJavaavailabletoheadlessineitheroftwoways
1. SettheJAVA_HOMEenvironmentvariabletothepathtotheJavainstallation.ThisisthedirectoryoftheJavainstallationwhichcontainsa"bin"directory.
2. AddthedirectorycontainingtheJavaexecutabletothePATHenvironmentvariable
IfJAVA_HOMEisdefined,netlogo-headlesswillrunNetLogousingtheJavathatitpointsto,ignoringtheversionofJavaavailableonthepath.
Afterthenamedexperimenthasrun,theresultsaresenttostandardoutputintableformat,asCSV.("-"ishowyouspecifystandardoutputinsteadofoutputtoafile.)
Whenrunningnetlogoheadless,itforcesthesystempropertyjava.awt.headlesstobetrue.ThistellsJavatoruninheadlessmode,allowingNetLogotorunonmachineswhenagraphicaldisplayisnotavailable.
Therequired--modelargumentisusedtospecifythemodelfileyouwanttoopen.
The--experimentargumentisusedtospecifythenameoftheexperimentyouwanttorun.(AtthetimeyoucreateanexperimentsetupintheGUI,youassignitaname.)
Here'sanotherexamplethatshowssomeadditional,optionalarguments:
netloog-headless.sh \ --model Fire.nlogo \ --experiment experiment2 \ --max-pxcor 100 \ --min-pxcor -100 \ --max-pycor 100 \ --min-pycor -100
Notetheuseoftheoptional--max-pxcor,--max-pycor,etc.argumentstospecifyadifferentworldsizethanthatsavedinthemodel.(It'salsopossiblefortheexperimentsetuptospecifyvaluesfortheworlddimensions;iftheyarespecifiedbytheexperimentsetup,thenthereisnoneedtospecifythemonthecommandline.)
Sinceneither--tablenor--spreadsheetisspecified,noresultswillbegenerated.Thisisusefuliftheexperimentsetupgeneratesalltheoutputyouneedbysomeothermeans,suchasexportingworldfilesorwritingtoatextfile.
Yetanotherexample:
netlogo-headless.sh \ --model Fire.nlogo \ --experiment experiment2 \ --table table-output.csv \ --spreadsheet spreadsheet-output.csv
Theoptional--table <filename>argumentspecifiesthatoutputshouldbegeneratedinatableformatandwrittentothegivenfileasCSVdata.If-isspecifiedasthefilename,thantheoutputissenttothestandardsystemoutputstream.Tabledataiswrittenasitisgenerated,witheachcompleterun.
Theoptional--spreadsheet <filename>argumentspecifiedthatspreadsheetoutputshouldbegeneratedandwrittentothegivenfileasCSVdata.If-isspecifiedasthefilename,thantheoutputissenttothestandardsystemoutputstream.Spreadsheetdataisnotwrittenoutuntilallrunsintheexperimentarefinished.
![Page 192: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/192.jpg)
Notethatitislegaltospecifyboth--tableand--spreadsheet,andifyoudo,bothkindsofoutputfilewillbegenerated.
HereisonefinalexamplethatshowshowtorunanexperimentsetupwhichisstoredinaseparateXMLfile,insteadofinthemodelfile:
netlogo-headless.sh \ --model Fire.nlogo \ --setup-file fire-setups.xml \ --experiment experiment3
IftheXMLfilecontainsmorethanoneexperimentsetup,itisnecessarytousethe--experimentargumenttospecifythenameofthesetuptouse.
InordertorunaNetLogo3Dexperiment,runheadlesswiththe--3Dargument,forexample:
netlogo-headless.sh \ --3D \ --model "Mousetraps 3D.nlogo3d" \ --experiment experiment1 \ --table -
Notethatyoushouldsupplya3Dmodelandtherearealso3Darguments--max-pzcor<number>and--min-pzcor <number>.
ThenextsectionhasinformationonhowtocreatestandaloneexperimentsetupfilesusingXML.
SettingupexperimentsinXML
Wedon'tyethavedetaileddocumentationonauthoringexperimentsetupsinXML,butifyoualreadyhavesomefamiliaritywithXML,thenthefollowingpointersmaybeenoughtogetyoustarted.
ThestructureofBehaviorSpaceexperimentsetupsinXMLisdeterminedbyaDocumentTypeDefinition(DTD)file.TheDTDisstoredinNetLogo.jar,assystem/behaviorspace.dtd.(JARfilesarealsozipfiles,soyoucanextracttheDTDfromtheJARusingJava's"jar"utilityorwithanyprogramthatunderstandszipformat.)
TheeasiestwaytolearnwhatsetupslooklikeinXML,though,istoauthorafewoftheminBehaviorSpace'sGUI,savethemodel,andthenexaminetheresulting.nlogofileinatexteditor.Theexperimentsetupsarestoredtowardstheendofthe.nlogofile,inasectionthatbeginsandendswithaexperimentstag.Example:
<experiments> <experiment name="experiment" repetitions="10" runMetricsEveryStep="true"> <setup>setup</setup> <go>go</go> <exitCondition>not any? fires</exitCondition> <metric>burned-trees</metric> <enumeratedValueSet variable="density"> <value value="40"/> <value value="0.1"/> <value value="70"/> </enumeratedValueSet> </experiment></experiments>
![Page 193: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/193.jpg)
Inthisexample,onlyoneexperimentsetupisgiven,butyoucanputasmanyasyouwantbetweenthebeginningandendingexperimentstags.
BetweenlookingattheDTD,andlookingatexamplesyoucreateintheGUI,itwillhopefullybeapparenthowtousethetagstospecifydifferentkindofexperiments.TheDTDspecifieswhichtagsarerequiredandwhichareoptional,whichmayberepeatedandwhichmaynot,andsoforth.
WhenXMLforexperimentsetupsisincludedinamodelfile,itdoesnotbeginwithanyXMLheaders,becausenotthewholefileisXML,onlypartofit.Ifyoukeepexperimentsetupsintheirownfile,separatefromthemodelfile,thentheextensiononthefileshouldbe.xmlnot.nlogo,andyou'llneedtobeginthefilewithproperXMLheaders,asfollows:
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE experiments SYSTEM "behaviorspace.dtd">
Thesecondlinemustbeincludedexactlyasshown.Inthefirstline,youmayspecifyadifferentencodingthanUTF-8,suchasISO-8859-1.
AdjustingJVMParameters
OpeningtheNetLogoHeadlesslauncherscriptwillshowtheoptionsusedtolaunchjavawhenrunningNetLogoHeadless.YoucanadjustvariousJVMparametersinthisscript.YoumayalsopassinJavapropertiesstartingwith-Dtothelauncher.
Notetheuseof-Xmxtospecifyamaximumheapsizeofonegigabyte.Ifyoudon'tspecifyamaximumheapsize,youwillgetyourVM'sdefaultsize,whichmaybeunusablysmall.(Onegigabyteisanarbitrarysizewhichshouldbemorethanlargeenoughformostmodels;youcanspecifyadifferentlimitifyouwant.)
Notetheuseof-Dfile.encoding=UTF-8.ThisforcesallfileI/OtouseUTF-8encoding.DoingsoensuresthatNetLogocanloadallmodelsconsistently,andthatfile-*primitivesworkconsistentlyonallplatforms,includingmodelscontainingUnicodecharacters.
ControllingAPI
IfBehaviorSpaceisnotsufficientforyourneeds,apossiblealternativeistouseourControllingAPI,whichletsyouwriteJavacodethatcontrolsNetLogo.TheAPIletsyourunBehaviorSpaceexperimentsfromJavacode,or,youcanwritecustomcodethatcontrolsNetLogomoredirectlytodoBehaviorSpace-likethings.SeetheControllingsectionoftheUserManualforfurtherdetailsonbothpossibilities.
![Page 194: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/194.jpg)
SystemDynamicsGuide
Thisguidehasthreeparts:
WhatistheSystemDynamicsModeler?:Ageneraldescriptionofthetool,includingtheideasandprinciplesbehindit.HowItWorks:Describestheinterfaceandhowyouuseit.Tutorial:Wolf-SheepPredation(aggregate):WalksyouthroughcreatingamodelwiththeSystemDynamicsModeler.
WhatistheNetLogoSystemDynamicsModeler?
SystemDynamicsisatypeofmodelingwhereyoutrytounderstandhowthingsrelatetooneanother.Itisalittledifferentfromtheagent-basedapproachwenormallyuseinNetLogomodels.
Withtheagent-basedapproachweusuallyuseinNetLogo,youprogramthebehaviorofindividualagentsandwatchwhatemergesfromtheirinteraction.InamodelofWolf-SheepPredation,forexample,youproviderulesforhowwolves,sheepandgrassinteractwitheachother.Whenyourunthesimulation,youwatchtheemergentaggregate-levelbehavior:forexample,howthepopulationsofwolvesandsheepchangeovertime.
WiththeSystemDynamicsModeler,youdon'tprogramthebehaviorofindividualagents.Instead,youprogramhowpopulationsofagentsbehaveasawhole.Forexample,usingSystemDynamicstomodelWolf-SheepPredation,youspecifyhowthetotalnumberofsheepwouldchangeasthetotalnumberofwolvesgoesupordown,andviceversa.Youthenrunthesimulationtoseehowbothpopulationschangeovertime.
TheSystemDynamicsModelerallowsyoutodrawadiagramthatdefinesthesepopulations,or"stocks",andhowtheyaffecteachother.TheModelerreadsyourdiagramandgeneratestheappropriateNetLogocode--globalvariables,proceduresandreporters--torunyourSystemDynamicsmodelinsideofNetLogo.
BasicConcepts
ASystemDynamicsdiagramismadeoffourkindsofelements:Stocks,Variables,FlowsandLinks.
AStockisacollectionofstuff,anaggregate.Forexample,aStockcanrepresentapopulationofsheep,thewaterinalake,orthenumberofwidgetsinafactory.
AFlowbringsthingsinto,oroutofaStock.Flowslooklikepipeswithafaucetbecausethefaucetcontrolshowmuchstuffpassesthroughthepipe.
AVariableisavalueusedinthediagram.ItcanbeanequationthatdependsonotherVariables,oritcanbeaconstant.
ALinkmakesavaluefromonepartofthediagramavailabletoanother.AlinktransmitsanumberfromaVariableoraStockintoaStockoraFlow.
TheSystemDynamicsModelerfiguresouthowthevalueofyourStockschangeovertimebyestimatingthemoverandover.Theestimationisn'talwaysperfect,butyoucanaffectitsaccuracybychangingthevalueofdt.Asdtdecreases,youestimatethemodelmorefrequently,soitgetsmoreaccurate.However,decreasingdtalsomakesthemodelslower.
SampleModels
TherearefourbasicmodelsintheSampleModelssectionoftheNetLogoModelsLibrarythatdemonstratetheuseoftheSystemDynamicsModeler.Allfourbasicmodelsexplorepopulationgrowth(and,inmodelswithpredation,populationdecline).
ExponentialGrowthandLogisticGrowtharesimpleexamplesofgrowthinonestock.
WolfSheepPredation(SystemDynamics)isanexampleofasystemwithmultiplestocksinfluencingoneanother.Itmodelsapredator-preyecosystemusingtheSystemDynamicsModeler.
WolfSheepPredation(DockedHybrid)isanexampleofamodelthatrunsboththeaSystemDynamicsmodelandanagent-basedmodelside-by-side.ItrunstheSystemDynamicsimplementationofWolf-SheepPredationnexttotheagent-basedWolfSheepPredationmodelfromtheBiologysectionofSampleModels.
![Page 195: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/195.jpg)
HowitWorks
ToopentheSystemDynamicsModeler,choosetheSystemDynamicsModeleritemintheToolsmenu.TheSystemDynamicsModelerwindowwillappear.
DiagramTab
TheDiagramtabiswhereyoudrawyourSystemDynamicsdiagram.
Thetoolbarcontainsbuttonstoedit,deleteandcreateitemsinyourdiagram.
CreatingDiagramElements
ASystemDynamicsdiagramismadeupoffourkindsofcomponents:Stocks,Variables,FlowsandLinks.
Stock
TocreateaStock,presstheStockbuttoninthetoolbarandclickinthediagramareabelow.AnewStockappears.EachStockrequiresauniquename,whichbecomesaglobalvariable.StocksalsorequireanInitialvalue.Itcanbeanumber,avariable,acomplexNetLogoexpression,oracalltoaNetLogoreporter.
Variable
TocreateaVariable,presstheVariablebuttonandclickonthediagram.EachVariableintheSystemDynamicsModelrequiresauniquename,whichbecomesthenameofaprocedure,oraglobalvariable.VariablesalsorequireanExpression.Thisexpressioncanbeanumber,avariable,acomplexNetLogoexpression,oracalltoaNetLogoreporter.
Flow
TocreateaFlow,presstheFlowbutton.ClickandholdwhereyouwanttheFlowtobegin--eitheronaStockorinanemptyarea--anddragthemousetowhereyouwanttheFlowtoend--onaStockorinanemptyarea.EachFlowrequiresauniquename,whichbecomesaNetLogoreporter.FlowsrequireanExpression,whichistherateofflowfromtheinputtotheoutput.Thisexpressioncanbeanumber,avariable,acomplexNetLogoexpression,oracalltoaNetLogoreporter.Ifthevalueisnegative,theflowisintheoppositedirection.
WhenmorethanoneFlowisconnectedtoaStock,itisimportanttoconsiderhowtheyshouldinteractwithoneanother.NetLogowillnotenforcethattheFlowsoutofastockoccurinanyparticularorder.Also,NetLogowillnotensurethatthesumofFlowsoutofaStockarelessthanorequaltothevalueoftheStock.ThesebehaviorscanbeimplementedexplicitlywhencreatingtheExpressionforaFlow.
![Page 196: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/196.jpg)
Forexample,iftheFlowisdefinedasaconstantvalue,10,youcanensureitneverdrawsmorethanthevalueoftheStockbyusingtheminprimitive:min (list stock 10).IfIwantFlowAtodepleteaStockbeforeFlowBiscalculated,IcanlinkFlowAtoFlowBandmodifyFlowBtosubtractFlowA'svaluefromthestock:min (list (max (list 0 (stock - flow-a))) 10).
Link
TocreateaLink,clickandholdonthestartingpointforthelink--aVariable,StockorFlow--anddragthemousetothedestinationVariableorFlow.
WorkingwithDiagramElements
WhenyoucreateaStock,Variable,orFlow,youseearedquestion-markontheelement.Thequestion-markindicatesthattheelementdoesn'thaveanameyet.TheredcolorindicatesthattheStockisincomplete:it'smissingoneormorevaluesrequiredtogenerateaSystemDynamicsmodel.Whenadiagramelementiscomplete,thenameturnsblack.
Selecting:Toselectadiagramelement,clickonit.Toselectmultipleelements,holdtheshiftkey.Youcanalsoselectoneormoreelementsbydraggingaselectionbox.
Editing:Toeditadiagramelement,selecttheelementandpressthe"Edit"buttononthetoolbar.Orjustdouble-clicktheelement.(YoucaneditStocks,FlowsandVariables,butyoucan'teditLinks).
Moving:Tomoveadiagramelement,selectitanddragthemousetoanewlocation.
Editingdt
Ontherightsideofthetoolbaristhedefaultdt,theintervalusedtoapproximatetheresultsofyourSystemDynamicsmodel.Tochangethevalueofthedefaultdtforyouraggregatemodel,presstheEditbuttonnexttothedtdisplayandenteranewvalue.
Errors
Whenyouclickthe"check"buttonorwhenyoueditastock,flow,orvariablethemodelerwillautomaticallygeneratetheNetLogocodethecorrespondstoyourdiagramandtrytocompilethatcode.IfthereisanerrortheCodetabwillturnredandamessagewillappear,andtheportionofthegeneratedcodethatiscausingthetroublewillbehighlighted.
Thisshouldgiveyouabetterideawhichelementinthediagramiscausingtheproblem.
![Page 197: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/197.jpg)
CodeTab
TheSystemDynamicsModelergeneratesNetLogovariablesandproceduresbasedonthecontentsofyourdiagram.Theseproceduresarewhatmakethediagramactuallyperformcalculations.TheCodetabintheSystemDynamicsModelerwindowdisplaystheNetLogoproceduresgeneratedfromyourdiagram.
Youcan'teditthecontentsoftheCodetab.TomodifyyourSystemDynamicsmode,editthediagram.
Let'stakeacloserlookathowthegeneratedcoderelatestothediagram.:
StockscorrespondtoaglobalvariablethatisinitializedtothevalueorexpressionyouprovidedintheInitialvaluefield.EachStockwillbeupdatedeverystepbasedontheFlowsinandout.
FlowscorrespondtoaprocedurethatcontainstheexpressionyouprovidedintheExpressionfield.
Variablescaneitherbeglobalvariablesorprocedures.IftheExpressionyouprovidedisaconstantitwillbeaglobalvariableandinitializedtothatvalue.IfyouusedamorecomplicatedExpressiontodefinetheVariableitwillcreateaprocedurelikeaFlow.
ThevariablesandproceduresdefinedinthistabareaccessibleinthemainNetLogowindow,justlikethevariablesandproceduresyoudefineyourselfinthemainNetLogoCodetab.YoucancalltheproceduresfromthemainCodetab,fromtheCommandCenter,orfrombuttonsintheInterfacetab.Youcanrefertotheglobalvariablesanywhere,includinginthemainCodetabandinmonitors.
Therearethreeimportantprocedurestonotice:system-dynamics-setup,system-dynamics-go,andsystem-dynamics-do-plot.
system-dynamics-setupinitializestheaggregatemodel.Itsetsthevalueofdt,callsreset-ticks,andinitializesyourstocksandyourconverters.Converterswithaconstantvalueareinitializedfirst,followedbythestockswithconstantvalues.Theremainingstocksareinitializedinalphabeticalorder.
system-dynamics-gorunstheaggregatemodelfordttimeunits.ItcomputesthevaluesofFlowsandVariablesandupdatesthevalueofStocks.Italsocallstick-advancewiththevalueofdt.ConvertersandFlowswithnon-constantExpressionswillbecalculatedonlyoncewhenthisprocedureiscalled,however,theirorderofevaluationisundefined
system-dynamics-do-plotplotsthevaluesofStocksintheaggregatemodel.Tousethis,firstcreateaplotinthemainNetLogowindow.YouthenneedtodefineaplotpenforeachStockyouwanttobeplotted.Thisprocedurewillusethecurrentplot,whichyoucanchangeusingtheset-current-plotcommand.
TheSystemDynamicsModelerandNetLogo
ThediagramyoucreatewiththeSystemDynamicsModeler,andtheproceduresgeneratedfromyourdiagram,arepartofyourNetLogomodel.WhenyouasavetheNetLogomodel,yourdiagramissavedwithit,inthesamefile.
Tutorial:Wolf-SheepPredation
Let'screateamodelofWolf-SheepPredationwiththeSystemDynamicsModeler.
Step1:SheepReproduction
![Page 198: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/198.jpg)
OpenanewmodelinNetLogo.LaunchtheSystemDynamicsModelerintheToolsmenu.
Ourmodelwillhaveapopulationofwolvesandapopulationofsheep.Let'sstartwiththesheep.First,createaStockthatholdsapopulationofSheep.
PresstheStockbuttoninthetoolbar.
Clickinthediagramarea.
YouseeaStockwitharedquestion-markinthemiddle.
Double-clicktheStocktoedit.NamethestocksheepSettheinitialvalueto100.DeselecttheAllowNegativeValuescheckbox.Itdoesn'tmakesensetohavenegativesheep!
![Page 199: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/199.jpg)
Oursheeppopulationcanincreaseifnewsheepareborn.Toaddthistoourdiagram,wecreateaFlowintothestockofsheep.
ClickontheFlowbuttoninthetoolbarandpressthemousebuttoninanemptyareatotheleftofthesheepStock.DragtheFlowtotherightuntilitconnectstothesheepStockandletgo.EdittheFlowandnameitsheep-births.Fornow,enteraconstant,suchas1,intotheExpressionfield.
Thenumberofsheepbornduringaperiodoftimedependsonthenumberofsheepthatarealive:moresheepmeansmorereproduction.
DrawaLinkfromthesheepStocktothesheep-birthsFlow.
Therateofsheepbirthsalsodependsonsomeconstantfactorsthatarebeyondthescopeofthismodel:therateofreproduction,etc.
CreateaVariableandnameitsheep-birth-rate.Setitsvalueto0.04DrawaLinkfromthesheep-birth-rateVariabletothesheep-births.
Yourdiagramshouldlooksomethinglikethis:
Ourdiagramhasthecorrectstructurebutwearen'tyetfinishedbecauseittheamountofsheepflowingintothestockdoesn'tdependuponthenumberofsheepandsheepbirthrate.
Editthesheep-birthsFlowandsettheexpressiontosheep-birth-rate * sheep.
Wenowhaveacompletediagram.ToseetheNetLogocodegeneratedbyourdiagram,youcanclickontheCodetaboftheSystemDynamicsModelerwindow.Itlookslikethis:
![Page 200: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/200.jpg)
Step2:NetLogoIntegration
OnceyoucreateanaggregatemodelwiththeSystemDynamicsModeler,youcaninteractwiththemodelthroughthemainNetLogointerfacewindow.Let'sbuildourNetLogomodeltorunthecodegeneratedbyourdiagram.We'llneedasetupandgobuttonswhichcallthesystem-dynamics-setupandsystem-dynamics-goprocedurescreatedbytheSystemDynamicsModeler.Andwe'llwantamonitorandaplottowatchthechangesinsheeppopulation.
SelectthemainNetLogowindowIntheCodetab,write:
to setup ca system-dynamics-setupend
to go system-dynamics-go system-dynamics-do-plotend
MovetotheInterfacetabCreateasetupbuttonCreateagobutton(don'tforgettomakeitforever)Createasheepmonitor.Createaplotcalled"populations"withapennamed"sheep".
Nowwe'rereadytorunourmodel.
Pressthesetupbutton.Don'tpressthe"go"buttonyet.Instead,typegofourorfivetimesintotheCommandCenter
Noticewhathappens.Thesheeppopulationincreasesexponentially.Afterfourorfiveiterations,wehaveanenormousnumberofsheep.That'sbecausewehavesheepreproduction,butoursheepneverdie.
![Page 201: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/201.jpg)
Tofixthat,let'sfinishourdiagrambyintroducingapopulationofwolveswhicheatsheep.
Step3:WolfPredation
MovebacktotheSystemDynamicswindowAddastockofwolvesAddFlows,VariablesandLinkstomakeyourdiagramlooklikethis:
AddonemoreFlowfromthewolvesStocktotheFlowthatgoesoutoftheSheepstock.Fillinthenamesofthediagramelementssoitlookslikethis:
whereinitial-valueofwolvesis30,wolf-deathsiswolves * wolf-death-rate,wolf-death-rateis0.15,predator-efficiencyis.8,wolf-birthsiswolves * predator-efficiency * predation-rate * sheep,predation-rateis3.0E-4,andsheep-deathsissheep * predation-rate * wolves.
Adjustthedtofthesystemdynamicsmodelbyselecting"Edit"nexttodtinthetoolbarofthesystemdynamicsmodeler.Inthedialogthatappears,enter0.01.
![Page 202: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/202.jpg)
Nowwe'rereallydone.
GobacktothemainNetLogowindowAddaplotpennamed"wolves"tothepopulationplotPresssetupandgotoseeyourSystemDynamicsModelerdiagraminaction.
Youseeaplotofthepopulationsthatlookslikethis:
![Page 203: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/203.jpg)
HubNetGuide
ThissectionoftheUserManualintroducestheHubNetsystemandincludesinstructionstosetupandrunaHubNetactivity.
HubNetisatechnologythatletsyouuseNetLogotorunparticipatorysimulationsintheclassroom.Inaparticipatorysimulation,awholeclasstakespartinenactingthebehaviorofasystemaseachstudentcontrolsapartofthesystembyusinganindividualdevice,suchasanetworkedcomputer.
Forexample,intheGridlocksimulation,eachstudentcontrolsatrafficlightinasimulatedcity.Theclassasawholetriestomaketrafficflowefficientlythroughthecity.Asthesimulationruns,dataiscollectedwhichcanafterwardsbeanalyzedonacomputer.
Formoreinformationonparticipatorysimulationsandtheirlearningpotential,pleasevisittheParticipatorySimulationsProjectwebsite.
UnderstandingHubNet
NetLogo
NetLogoisaprogrammablemodelingenvironment.Itcomeswithalargelibraryofexistingsimulations,bothparticipatoryandtraditional,thatyoucanuseandmodify.Contentareasincludesocialscienceandeconomics,biologyandmedicine,physicsandchemistry,andmathematicsandcomputerscience.Youandyourstudentscanalsouseittobuildyourownsimulations.
IntraditionalNetLogosimulations,thesimulationrunsaccordingtorulesthatthesimulationauthorspecifies.HubNetaddsanewdimensiontoNetLogobylettingsimulationsrunnotjustaccordingtorules,butbydirecthumanparticipation.
SinceHubNetbuildsuponNetLogo,werecommendthatbeforetryingHubNetforthefirsttime,youbecomefamiliarwiththebasicsofNetLogo.TogetstartedusingNetLogomodels,seeTutorial#1:RunningModelsintheNetLogoUsersManual.
HubNetArchitecture
HubNetsimulationsarebasedonaclient/serverarchitecture.TheactivityleaderusestheNetLogoapplicationtorunaHubNetactivity.WhenNetLogoisrunningaHubNetactivity,werefertoitasaHubNetserver.ParticipantsuseaclientapplicationtologinandinteractwiththeHubNetserver.
WhileHubNetisonlysupportedviatheJavaDesktopclientsatthemoment,wehopetoaddsupportforothertypesofclientssuchastabletsandphonesinthefuture.
ComputerHubNet
Activities
ThefollowingactivitiesareavailableintheModelsLibrary,intheHubNetActivitiesfolder.InformationonhowtorunthemodelsandactivitiescanbefoundintheInfotabofeach
![Page 204: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/204.jpg)
model.AdditionaldiscussionofeducationalgoalsandwaystoincorporatemanyoftheactivitiesintoyourclassroomintheParticipatorySimulationsGuideontheParticipatorySimulationsProjectwebsite.
BugHuntersCamouflage-studentshuntbugsandcamouflagingemerges.DiceStalagmiteHubNet-studentsrolldiceandexplorethespaceofdependentandindependentevents.Disease-Adiseasespreadsthroughthesimulatedpopulationofstudents.DiseaseDoctors-AslightmodificationtotheDiseaseactivitywheresomestudentscanrecoverfromthedisease.Gridlock-Studentsusetrafficlightstocontroltheflowoftrafficthroughacity.Polling-Askstudentsquestionsandplottheiranswers.RootBeerGame-AnadaptationofapopulargamecreatedatMITintheearly1960sthatshowshowsmalldelaysinadistributionsystemcancreatebigproblems.Sampler-Studentsengageinstatisticalanalysisasindividualsandasaclassroom.Throughtheseactivities,studentsdiscoverthemeaninganduseofbasicconceptsinstatistics.TragedyoftheCommons-Studentsworkasfarmerssharingacommonresource.
Clients
TousetheclientapplicationyousimplyneedtolaunchtheHubNetclientapplicationthatisbundledwithNetLogo.
Requirements
TouseComputerHubNet,youneedanetworkedcomputerwithNetLogoinstalledfortheserver.WhenusingtheclientapplicationyouwillalsoneedanetworkedcomputerwithNetLogoinstalledforeachparticipant.Whenusinginclassroomsettingswealsosuggestanattachedprojectorfortheleadertoprojecttheentiresimulationtotheparticipants.
Startinganactivity
You'llfindtheHubNetactivitiesinNetLogo'sModelsLibrary,intheHubNetActivitiesfolder.Wesuggestdoingafewpracticerunsofanactivitybeforetryingitinfrontofaclass.
OpenaComputerHubNetmodel.NetLogowillpromptyoutoenterthenameofyournewHubNetsession.Thisisthenamethatparticipantswillusetoidentifythisactivity.EnteranameandpressStart.
NetLogowillopentheHubNetControlCenter,whichletsyouinteractwiththeHubNetserver.
You,astheleader,shouldthennotifyeveryonethattheymayjoin.Tojointheactivity,
![Page 205: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/205.jpg)
participantslaunchtheHubNetClientapplicationandentertheirname.TheyshouldseeyouractivitylistedandcanjoinyouractivitybyselectingitandpressingEnter.IftheactivityyoustartedisnotlistedthestudentcanentertheserveraddressmanuallywhichcanbefoundintheHubNetControlCenter.
HubNetControlCenter
TheHubNetControlCenterletsyouinteractwiththeHubNetserver.Itdisplaysthename,activity,addressandportnumberofyourserver.The"Mirror2DViewonclients"checkboxcontrolswhethertheHubNetparticipantscanseetheviewontheirclients,assumingthereisaviewintheclientsetup.The"Mirrorplotsonclients"checkboxcontrolswhetherparticipantswillreceiveplotinformation.
Theclientlistontherightdisplaysthenamesofclientsthatarecurrentlyconnectedtoyouactivity.Toremoveaparticipantfromtheactivity,selecttheirnameinthelistandpresstheKickbutton.TolaunchyourownHubNetclientpresstheLocalbutton,thisisparticularlyusefulwhenyouaredebugginganactivity.The"Reset"buttonkicksoutallcurrentlyloggedinclientsandreloadstheclientinterface.
ThelowerpartoftheControlCenterdisplaysmessageswhenaparticipantjoinsorleavestheactivity.Tobroadcastamessagetoalltheparticipants,clickonthefieldatthebottom,typeyourmessageandpressBroadcastMessage.
Troubleshooting
IstartedaHubNetactivity,butwhenparticipantsopenaHubNetClient,myactivityisn'tlisted.
Onsomenetworks,theHubNetClientcannotautomaticallydetectaHubNetserver.TellyourparticipantstomanuallyentertheserveraddressandportofyourHubNetserver,which
![Page 206: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/206.jpg)
appearintheHubNetControlCenter.
Note:Thetechnicaldetailsonthisareasfollows.Inorderfortheclienttodetecttheserver,multicastroutingmustbeavailablebetweenthem.Notallnetworkssupportmulticastrouting.Inparticular,networksthatusetheIPsecprotocoltypicallydonotsupportmulticast.TheIPsecprotocolisusedonmanyvirtualprivatenetworks(VPNs).
Whenaparticipanttriestoconnecttoanactivity,nothinghappens(theclientappearstohangorgivesanerrorsayingthatnoserverwasfound).
Ifyourcomputerornetworkhasafirewall,itmaybeimpedingtheHubNetserverfromcommunicating.MakesurethatyourcomputerandnetworkarenotblockingportsusedbytheHubNetserver(ports9173-9180).
TheviewontheHubNetclientisgray.
Verifythatthe"Mirror2Dviewonclients"checkboxintheHubNetControlCenterisselected.Makesurethatthedisplayswitchinthemodelison.Ifyouhavemadechangestothesizeoftheviewontheserveryoumayneedtopressthe"Reset"buttonintheControlCentertoensuretheclientsgetthenewsize.
ThereisnoviewontheHubNetclient.
Someactivitiesdon'thaveaviewontheclient.Ifyouwanttoaddaviewsimplyselect"HubNetClientEditor"fromtheToolsMenuandaddaviewlikeanyotherwidget.Makesuretopressthe"Reset"buttonbeforehavingclientslogin.
Ican'tquitaHubNetclient.
Youwillhavetoforcetheclienttoquit.OnOSX,forcequittheapplicationbyselectingForceQuit...intheApplemenu.OnWindows,pressCtrl-Alt-DeletetoopentheTaskManager,selectHubNetClientandpressEndTask.
MycomputerwenttosleepwhilerunningaHubNetactivity.WhenIwokethecomputerup,IgotanerrorandHubNetwouldn'tworkanymore.
TheHubNetservermaystopworkingifthecomputergoestosleep.Ifthishappens,quittheNetLogoapplicationandstartover.Changethesettingsonyourcomputersoitwon'tsleepagain.
Myproblemisnotaddressedonthispage.
SeeContactingUs.
KnownLimitations
IfHubNetmalfunctions,seethebugreportinginformationatContactingUs.
Pleasenotethat:
![Page 207: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/207.jpg)
HubNethasnotyetbeenextensivelytestedwithlargenumbersofclients(i.e.morethanabout25).Unexpectedresultsmayoccurwithmoreclients.Out-of-memoryconditionsarenothandledgracefullySendinglargeamountsofplottingmessagestotheclientscantakealongtime.NetLogodoesnothandlemaliciousclientsinarobustmanner(inotherwords,itislikelyvulnerabletodenial-of-servicetypeattacks).Performancedoesnotdegradegracefullyoversloworunreliablenetworkconnections.Ifyouareonawirelessnetworkorsub-LAN,theIPaddressintheHubNetControlCenterisnotalwaystheentireIPaddressoftheserver.ComputerHubNethasonlybeentestedonLANs,andnotondial-upconnectionsorWANs.
Teacherworkshops
ForinformationonupcomingworkshopsandNetLogoandHubNetuseintheclassroom,pleasecontactus.
HubNetAuthoringGuide
TolearnaboutauthoringormodifyingHubNetactivities,seetheHubNetAuthoringGuide.
RunningHubNetinheadlessmode
TolearnaboutrunningHubNetactivitiesfromthecommandline,withnoGUIontheserver,seetheHubNetsectionintheControllingGuide.
Gettinghelp
IfyouhaveanyquestionsaboutHubNetorneedhelpgettingstarted,contactus.
![Page 208: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/208.jpg)
HubNetAuthoringGuide
ThisguideshowshowtounderstandandmodifythecodeofexistingHubNetactivitiesandwriteyourownnewones.ItassumesyouarefamiliarwithrunningHubNetactivities,basicNetLogocodeandNetLogointerfaceelements.FormoregeneralinformationaboutHubNetseetheHubNetGuide.
CodingHubNetactivitiesSetupReceivinginformationfromclientsSendinginformationtoclientsExamples
HowtomakeaclientinterfaceViewupdatesontheclientsClickingintheviewonclientsCustomizingtheclient'sviewPlotupdatesontheclients
CodingHubNetactivities
ManyHubNetactivitieswillsharebitsofthesamecode.Thatisthecodethatitusedtosetupthenetworkandthecodethatisusedtoreceiveinformationfromandsendinformationtotheclients.Ifyouunderstandthiscodeyoushouldbeabletoeasilymakemodificationstoexistingactivitiesandyoushouldhaveagoodstartonwritingyourownactivities.TogetyoustartedwehaveprovidedaTemplatemodel(inHubNetActivities->CodeExamples)thatcontainsthemostbasiccomponentsthatwillbeinthemajorityofHubNetactivities.Youshouldbeabletousethisactivityasastartingpointformostprojects.
CodeExample:Template
Setup
TomakeaNetLogomodelintoaHubNetactivityyoumustfirstinitializethenetwork.InmostHubNetactivitiesyouwillusethestartupproceduretoinitializethenetwork.startupisaspecialprocedurethatNetLogorunsautomaticallywhenyouopenanymodel.Thatmakesitagoodplacetoputcodethatyouwanttorunonceandonlyonce(nomatterhowmanytimestheuserrunsthemodel).ForHubNetweputthecommandthatinitializesthenetworkinstartupbecauseoncethenetworkissetupwedon'tneedtodosoagain.Weinitializethesystemusinghubnet-reset,whichwillasktheuserforasessionnameandopenuptheHubNetControlCenter.Hereisthestartupprocedureinthetemplatemodel:
to startup hubnet-resetend
Nowthatthenetworkisallsetupyoudon'tneedtoworryaboutcallinghubnet-resetagain.Takealookatthesetupprocedureinthetemplatemodel:
to setup cp cd clear-output
![Page 209: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/209.jpg)
ask turtles [ set step-size 1 hubnet-send user-id "step-size" step-size ]end
Forthemostpartitlookslikemostothersetupprocedures,however,youshouldnoticethatitdoesnotcallclear-all.Inthismodel,andinthegreatmajorityofHubNetactivitiesintheModelsLibrary,wehaveabreedofturtlesthatrepresentthecurrentlyloggedinclients.Inthiscasewe'vecalledthisbreedstudents.Wheneveraclientlogsinwecreateastudentandrecordanyinformationwemightneedlateraboutthatclientinaturtlevariable.Sincewedon'twanttorequireuserstologoutandlogbackineverytimewesetuptheactivitywedon'twanttokillalltheturtles,instead,wewanttosetallthevariablesbacktoinitialvaluesandnotifytheclientsofanychangeswemake(moreonthatlater).
Receivingmessagesfromclients
DuringtheactivityyouwillbetransferringdatabetweentheHubNetclientsandtheserver.MostHubNetactivitieswillcallaprocedureinthegoloopthatchecksfornewmessagesfromclientsinthiscaseit'scalledlistenclients:
to listen-clients while [ hubnet-message-waiting? ] [ hubnet-fetch-message ifelse hubnet-enter-message? [ create-new-student ] [ ifelse hubnet-exit-message? [ remove-student ] [ execute-command hubnet-message-tag ] ] ]end
Aslongastherearemessagesinthequeuethisloopfetcheseachmessageoneatatime.hubnet-fetch-messagemakesthenextmessageinthequeuethecurrentmessageandsetsthereportershubnet-message-source,hubnet-message-tag,andhubnet-messagetotheappropriatevalues.Theclientssendmessageswhentheusersloginandlogoutanytimetheusermanipulatesoneoftheinterfaceelements,thatis,pushesabutton,movesaslider,clicksintheview,etc.Westepthrougheachmessageanddecidewhatactiontotakedependingonthetypeofmessage(enter,exit,orother),thehubnet-message-tag(thenameoftheinterfaceelement),andthehubnet-message-sourceofthemessage(thenameoftheclientthemessagecamefrom).
Onanentermessagewecreateaturtlewithauser-idthatmatchesthehubnet-message-sourcewhichisthenamethateachuserentersuponenteringtheactivity,itisguaranteedtobeunique.
to create-new-student create-students 1 [ set user-id hubnet-message-source set label user-id set step-size 1 send-info-to-clients ]end
![Page 210: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/210.jpg)
Atthispointwesetanyotherclientvariablestodefaultvaluesandsendthemtotheclientsifappropriate.Wedeclaredastudents-ownvariableforeveryinterfaceelementontheclientthatholdsstate,thatis,anythingthatwouldbeaglobalvariableontheserver,sliders,choosers,switchesandinputboxes.Itisimportanttomakesurethatthesevariablesstaysynchronizedwiththevaluesvisibleontheclient.
Whentheclientslogouttheysendanexitmessagetotheserverwhichgivesyouachancetocleanupanyinformationyouhavebeenstoringabouttheclient,inthiscasewemerelyhavetoasktheappropriateturtletodie.
to remove-student ask students with [user-id = hubnet-message-source] [ die ]end
Allothermessagesareinterfaceelementsidentifiedbythehubnet-message-tagwhichisthenamethatappearsintheclientinterface.Everytimeaninterfaceelementchangesamessageissenttotheserver.Unlessyoustorethestateofthevaluescurrentlydisplayedintheclientinterfacewillnotbeaccessibleinotherpartsofthemodel.That'swhywe'vedeclaredastudents-ownvariableforeveryinterfaceelementthathasastate(sliders,switches,etc).Whenwereceivethemessagefromtheclientwesettheturtlevariabletothecontentofthemessage:
if hubnet-message-tag = "step-size"[ ask students with [user-id = hubnet-message-source] [ set step-size hubnet-message ]]
Sincebuttonsdon'thaveanyassociateddatathereisgenerallynoassociatedturtlevariable,insteadtheyindicateanactiontakenbytheclient,justaswitharegularbuttonthereisoftenprocedureassociatedwitheachbuttonthatyoucallwheneveryoureceiveamessageindicatingthebuttonhasbeenpressed.Thoughitiscertainlynotrequired,theprocedureisoftenaturtleprocedure,thatis,somethingthatthestudentturtleassociatedwiththemessagesourcecanexecute:
if command = "move left"[ set heading 270 fd 1 ]
Sendingmessagestoclients
Asmentionedearlieryoucanalsosendvaluestoanyinterfaceelementsthatdisplayinformation:monitors,sliders,switches,choosers,andinputboxes(notethatplotsandtheviewarespecialcasesthathavetheirownsections).
Therearetwoprimitivesthatallowyoutosendinformationhubnet-sendandhubnet-broadcast.Broadcastsendstheinformationtoalltheclients;sendsendstooneclient,oraselectedgroup.
Assuggestedearlier,nothingontheclientupdatesautomatically.Ifavaluechangesontheserver,itisyourresponsibilityastheactivityauthortoupdatemonitorsontheclient.
Forexample,sayyouhaveasliderontheclientcalledstep-sizeandamonitorcalledStepSize(notethatthenamesmustbedifferent)youmightwriteupdatingcodelikethis:
![Page 211: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/211.jpg)
if hubnet-message-tag = "step-size"[ ask student with [ user-id = hubnet-message-source ] [ set step-size hubnet-message hubnet-send user-id "Step Size" step-size ]]
Youcansendanytypeofdatayouwant,numbers,strings,lists,listsoflists,listsofstrings,however,ifthedataisnotappropriateforthereceivinginterfaceelement(say,ifyouweretosendastringtoaslider)themessagewillbeignored.Hereareafewcodeexamplesfordifferenttypesofdata:
datatype hubnet-broadcastexample hubnet-sendexample
number hubnet-broadcast "A" 3.14 hubnet-send "jimmy" "A" 3.14
string hubnet-broadcast "STR1" "HI THERE"hubnet-send ["12" "15"] "STR1" "HITHERE"
listofnumbers hubnet-broadcast "L2" [1 2 3]
hubnet-send hubnet-message-source "L2"[1 2 3]
matrixofnumbers
hubnet-broadcast "[A]" [[1 2] [34]]
hubnet-send "susie" "[A]" [[1 2] [34]]
listofstrings
hubnet-broadcast "user-names"[["jimmy" "susie"] ["bob""george"]]
hubnet-send "teacher" "user-names"[["jimmy" "susie"] ["bob" "george"]]
Examples
Studythemodelsinthe"HubNetActivities"sectionoftheModelsLibrarytoseehowtheseprimitivesareusedinpracticeintheCodetab.Diseaseisagoodonetostartwith.
Howtomakeaclientinterface
OpentheHubNetClientEditor,foundintheToolsMenu.Addanybuttons,sliders,switches,monitors,plots,choosers,ornotesthatyouwantjustasyouwouldintheinterfacetab.You'llnoticethattheinformationyouenterforeachofthewidgetsisslightlydifferentthanintheInterfacepanel.Widgetsontheclientdon'tinteractwiththemodelinthesameway.Insteadofadirectlinktocommandsandreportersthewidgetssendmessagesbacktotheserverandthemodelthendetermineshowthosemessagesaffectthemodel.Allwidgetsontheclienthaveatagwhichisanamethatuniquelyidentifiesthewidget.Whentheserverreceivesamessagefromthatwidgetthetagisfoundinhubnet-message-tag
Forexample,ifyouhaveabuttoncalled"moveleft",aslidercalled"step-size",aswitchcalled"all-in-one-step?",andamonitorcalled"Location:",thetagsfortheseinterfaceelementswillbeasfollows:
interfaceelement tag
moveleft moveleftstep-size step-sizeall-in-one-step? all-in-one-step?
![Page 212: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/212.jpg)
Location: Location:
Notethatyoucanonlyhaveoneinterfaceelementwithaspecificname.Havingmorethanoneinterfaceelementwiththesametagintheclientinterfacewillresultinunpredictablebehaviorsinceitisnotclearwhichelementyouintendedtosendtheinformationto.
Viewupdatesontheclients
Viewmirroringletsviewsoftheworldbedisplayedinclientsaswellontheserver.ViewmirroringisenabledusingacheckboxintheHubNetControlCenter.
Whenmirroringisenabled,clientviewsupdatewhenevertheviewontheserverdoes.Toavoidexcessivenetworktraffic,theviewshouldnotupdatemoreoftenthannecessary.Thereforewestronglyrecommendusingtick-basedupdates,ratherthancontinuousupdates.SeetheViewUpdatessectionoftheProgrammingGuideforanexplanationofthetwotypesofupdates.
Withtick-basedupdates,updateshappenwhenatickordisplaycommandruns.Werecommendusingthesecommandsonlyinsideaneveryblock,tolimitthefrequencyofviewupdatesandthusalsolimitnetworktraffic.Forexample:
every 0.1[ display]
IfthereisnoViewintheclientsoriftheMirror2DViewonClientscheckboxintheHubNetControlCenterisnotchecked,thennoviewupdatesaresenttotheclients.
Clickingintheviewonclients
IftheViewisincludedintheclient,twomessagesaresenttotheservereverytimetheuserclicksintheview.Thefirstmessage,whentheuserpressesthemousebutton,hasthetag"View".Thesecondmessage,sentwhentheuserreleasesthemousebutton,hasthetag"MouseUp".Bothmessagesconsistofatwoitemlistofthexandycoordinates.Forexample,toturnanypatchthatwasclickedonbytheclientred,youwouldusethefollowingNetLogocode:
if hubnet-message-tag = "View"[ ask patches with [ pxcor = (round item 0 hubnet-message) and pycor = (round item 1 hubnet-message) ] [ set pcolor red ]]
Customizingtheclient'sview
Whenviewmirroringisenabled,bydefaultclientsseethesameviewtheactivityleaderseesontheserver.Butyoucanchangethissothateachclientseessomethingdifferent,notjustaliteral"mirror".
Youcanchangewhataclientseesintwodistinctways.Wecallthem"clientperspectives"and"clientoverrides".
Changingaclient'sperspectivemeansmakingit"watch"or"follow"aparticularagent,much
![Page 213: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/213.jpg)
likethewatchandfollowcommandsthatworkwithordinaryNetLogomodels.Seethedictionaryentriesforhubnet-send-watch,hubnet-send-follow,andhubnet-reset-perspective.
CodeExample:ClientPerspectiveExample
Clientoverridesletyouchangetheappearanceofpatches,turtles,andlinksintheclientviews.Youcanoverrideanyofthevariablesaffectinganagent'sappearance,includingthehidden?variablecausingaturtleorlinktobevisibleorinvisible.Seethedictionaryentriesforhubnet-send-override,hubnet-clear-override,andhubnet-clear-overrides.
CodeExample:ClientOverridesExample
Plotupdatesontheclients
Ifplotmirroringisenabled(intheHubNetControlCenter)andaplotintheNetLogomodelchangesandaplotwiththeexactsamenameexistsontheclients,amessagewiththatchangeissenttotheclientscausingtheclient'splottomakethesamechange.Forexample,let'spretendthereisaHubNetmodelthathasaplotcalledMilkSupplyinNetLogoandtheclients.MilkSupplyisthecurrentplotinNetLogoandintheCommandCenteryoutype:
plot 5
Thiswillcauseamessagetobesenttoalltheclientstellingthemthattheyneedtoplotapointwithayvalueof5inthenextpositionoftheplot.Notice,ifyouaredoingalotofplottingallatonce,thiscangeneratealotofplottingmessagestobesenttotheclients.
![Page 214: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/214.jpg)
ModelingCommonsGuide
Introduction
TheModelingCommons(http://modelingcommons.org/)isaWeb-basedcollaborationsystemforNetLogomodelers.UsersoftheModelingCommonscanshare,download,modify,createvariationsof,commenton,andrunNetLogomodels--boththosethatareapartoftheNetLogomodelslibrary,andalsothosethathavebeenuploadedbyotherNetLogousers.
ByuploadingyourNetLogomodelstotheModelingCommons,youmakeiteasyforotherstosee,review,andcommentonyourwork.Youcanoptionallykeepthemodelprivate,eithertoyourselfortoagroupofyourchoice,ifyouaren'tcomfortablewithlettingeveryoneseethemodel.Youcanalwayschangethepermissionsassociatedwithamodel,ifyouchangeyourmindlateron.
NetLogonowmakesitpossibletosavemodelstotheModelingCommons,justasyoucansavethemto.nlogofilesonyourowncomputer.Youcanaccessthisfunctionalitybyselecting"UploadtoModelingCommons"fromthe"File"menu.
UseoftheModelingCommonsisfreeofcharge.Youmayuseitforyourownpersonalwork,foryourresearchgrouporcompany,orforaclassinwhichyouareastudentorteacher.TheModelingCommonsissponsoredbytheCCL,thesamegroupthatdevelopsanddistributesNetLogo.
ModelingCommonsAccounts
InordertouploadmodelstotheModelingCommons,youmustfirstbearegistereduser.Unregistereduserscanviewanddownloadmodels,butcannotupload,edit,orcommentonthem.
Thefirsttimethatyouinvoke"SavetoModelingCommons"inNetLogo,youwillbepromptedtoenteryoure-mailaddressandpassword.Ifyoualreadyhaveanaccount,thenyoucanenterthisinformationandclickonthe"Login"button.
Ifyoudon'tyethaveanaccountwiththeModelingCommons,thenyouwillneedtocreateone.Clickonthe"CreateAccount"button,andentertherequestedinformation.Onceyouhavedoneso,clickonthe"CreateAccount"button.Iftherearenoerrors,thenyouwillbepromptedtouploadaNetLogomodel.Alternatively,youmaygototheModelingCommonsitselfandregisterwithyourWebbrowser.
UploadingModels
![Page 215: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/215.jpg)
TherearethreewaystouploadamodeltotheModelingCommons:Uploading,updating,andcreatingachild("forking").Thefollowingsectionsdescribetheseindetail.
UploadANewModel
AnewmodelwillbecreatedintheModelingCommons,withitsownpage,description,andforum.YoushouldusethisfunctionthefirsttimethatyousaveamodeltotheModelingCommons.
Youmustgiveyourmodelaname.Modelnamesarenotrequiredtobeunique;youcouldhave2ormoremodelswiththesamename,thoughwerecommendthatyounotdothis.
Bydefault,anyonecanview,fork,andupdateyourmodel.Youcanrestricttheabilitytoviewandforkyourmodelbychangingthevisibilitypermission.Youcanrestricttheabilitytoupdateyourmodelbychangingthechangeabilitypermission.Inordertosetpermissionsformultiplepeople,assignyourmodeltoagroup,andthenrestrictvisibilityorchangeabilitytomembersofthatgroup.GroupscanbecreatedfromtheModelingCommons.Onceyouhaveuploadedyourmodel,youcaneditthepermissionsfromthemodel'sModelingCommonspage.
Youcanoptionallyuploadapreviewimagetoyourmodel.ThepreviewimagewillbedisplayedalongsideyourmodelwheneveritisshownontheModelingCommons.Whileuploadingapreviewimageisoptional,wehighlyrecommendthatyoudoso,inoneofthefollowingthreeways:
The"Usecurrentimage"optiontellsNetLogotousethecurrentviewasyourpreview.Werecommendthatyoufirstrunthemodel,suchthatitshowsoffthekeyvisualfeatures.The"Auto-generateimage"featureauto-generatesapreviewimagebyrunningrandom-seed 0
![Page 216: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/216.jpg)
setup repeat 75 [ go ].ThisoptionwillonlybeenabledifyouhavedefinedsetupandgoproceduresforNetLogotorun.The"Imagefromfile"featureallowsyoutouploadanyPNGimage.Previewimagesworkbestwhentheyaresquare.
UploadAChildOfAnExistingModel("forking")
Savingamodelinthisway,sometimesknownas"forking,"doesnotchangeoroverwritetheoriginalmodel.Rather,itcreatesanewmodelontheModelingCommons,muchasaplain"save"woulddo,simultaneouslycreatingaparent-childrelationshipbetweentheoldmodelandthenewone.Thisrelationshipcanbeseenonthe"family"tabforagivenmodel.Youmayforkanymodelforwhichyouhave"view"permissions,includingonethatyoucannotchange.Youmaywish,forexample,tocreateavariationonamodelintheNetLogomodelslibrary.
Toforkamodel,youmustgiveyournewchildaname,aswellasselectanexistingmodeltofork.Toindicatetheexistingmodel,starttypingthenameofthemodelthatyouwouldliketofork.Selectitsnamefromamongthesearchresults.
Finally,youmustenteradescriptionaboutwhatyouarechanginginyourchildmodel,andhowitrelatestoitsparent.
UpdatingAnExistingModel
UsethisoptionifyouhaveimprovedamodelthatalreadyexistsintheModelingCommons.Existing
![Page 217: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/217.jpg)
attachments,discussions,andsocialtagswillbepreserved,butthemodelthatuserscandisplay,run,anddownloadwillbeupdated.Youmayonlyupdateamodelforwhichyouhave"write"permissions.
AllversionsofamodelaresavedintheModelingCommons,soyoushouldfeelfreetoexperimentwithnewideas.Ifsomethinggoeswrong,youcanalwaysrefertoanoldversionfromthe"history"tabonamodel'spage.
Toindicatewhichmodelshouldbeupdated,starttypingthenameofthemodel.Selectthenamethatpopsupwiththesearchresults.Finally,enteradescriptionaboutwhatyouarechanginginyournewversion.
![Page 218: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/218.jpg)
Logging
NetLogo'sloggingfacilityallowsresearcherstorecordstudentactionsforlateranalysis.
LogginginNetLogo,onceinitiated,isinvisibletothestudent.Theresearchercanchoosethetypeofeventsloggedthroughaconfigurationfile.
NetLogousesthelog4jpackageforlogging.Ifyouhavepreviousexperiencewiththispackageyou'llfindlogginginNetLogofamiliar.
LoggingissupportedonlybythespecialNetLogoLoggingapplication.
Startinglogging
Thisdependsonwhatoperatingsystemyouareusing.
MacOSXorWindows
ThereisaspeciallogginglauncherintheNetLogodirectorycalledNetLogoLogging.Doubleclickontheicon.
OnWindows,theNetLogodirectorycanbefoundatC:\Program Files,unlessyouchoseadifferentlocationwhenyouinstalledNetLogo.
Linuxandothers
Toenablelogging,invokethenetlogo.shscriptasfollows:
netlogo.sh --logging netlogo_logging.xml
Youcouldalsomodifythescripttoincludetheseflags,orcopythescriptandmodifythecopy.
Youcanreplacenetlogo_logging.xmlwithanyvalidlog4jXMLconfigurationfile,whichwillbediscussedinmoredetaillater.
Usinglogging
WhenNetLogostartsupitwillaskforausername.Thisnamewillappearinallthelogsgeneratedduringthissession.
Wherelogsarestored
LogsarestoredintheOS-specifictempdirectory.OnmostUnix-likesystemsthatis/tmp.OnWindowsVistathelogscanbefoundinc:\Users\<user>\AppData\Local\Temp,where<user>istheloggedinuser.OnMacOSX,thetempdirectoryvariesforeachuser.YoucandetermineyourtempdirectorybyopeningtheTerminalapplicationandtypingecho $TMPDIRattheprompt.
Therearetwoconveniencecommandsthatwillhelpyoumanagethelogs.__zip-log-filesfilenamewillgatherallthelogsinthetempdirectoryandputtheminonezipfile,atthelocationspecified.Afterdoing__zip-log-filestheexistinglogsarenotdeleted,youcandoso
![Page 219: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/219.jpg)
explicitlybyusing__delete-log-files.
Thefollowingisachartdescribingthenameoftheloggersavailable,thetypeofeventseachlogs,atwhatlevel,andprovidesasampleoutputusingtheXMLLayout.Alltheloggersarefoundinorg.nlogo.log.Logger.Whenreferringtotheloggersintheconfigurationfileyoushouldusethefullyqualifiedname.So,forexample,theloggerGLOBALSwouldactuallybeorg.nlogo.log.Logger.GLOBALS
Logger Events Level Example
GLOBALSaglobalvariablechanges
info,debug
<event logger="org.nlogo.log.Logger.GLOBALS" timestamp="1177341065988" level="INFO" type="globals"> <name>FOO</name> <value>51.0</value></event>
GREENS
sliders,switches,choosers,inputboxesarechangedthroughtheinterface
info
<event logger="org.nlogo.log.Logger.GREENS" timestamp="1177341065988" level="INFO" type="slider"> <action>changed</action> <name>foo</name> <value>51.0</value> <parameters> <min>0.0</min> <max>100.0</max> <inc>1.0</inc> </parameters></event>
CODE
codeiscompiled,including:commandcenter,Codetab,sliderbounds,andbuttons
info
<event logger="org.nlogo.log.Logger.CODE" timestamp="1177341072208" level="INFO" type="command center"> <action>compiled</action> <code>crt 1</code> <agentType>O</agentType> <errorMessage>success</errorMessage></event>
WIDGETS
awidgetisaddedorremovedfromtheinterface
info
<event logger="org.nlogo.log.Logger.WIDGETS" timestamp="1177341058351" level="INFO" type="slider"> <name></name> <action>added</action></event>
BUTTONSabuttonispressedorreleased
info
<event logger="org.nlogo.log.Logger.BUTTONS" timestamp="1177341053679" level="INFO" type="button"> <name>show 1</name> <action>released</action> <releaseType>once</releaseType>
![Page 220: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/220.jpg)
</event>
SPEEDthespeedsliderchanges info
<event logger="org.nlogo.log.Logger.SPEED" timestamp="1177341042202" level="INFO" type="speed"> <value>0.0</value></event>
TURTLESturtlesdieorareborn info
<event logger="org.nlogo.log.Logger.TURTLES" timestamp="1177341094342" level="INFO" type="turtle"> <name>turtle 1</name> <action>born</action> <breed>TURTLES</breed></event>
LINKSlinksdieorareborn info
<event logger="org.nlogo.log.Logger.LINKS" timestamp="1177341094342" level="INFO" type="link"> <name>link 2 7</name> <action>born</action> <breed>LINKS</breed></event>
Howtoconfiguretheloggingoutput
Thedefaultloggingconfiguration(netlogo_logging.xml)lookssomethinglikethis:
NetLogodefines8loggers,alldescenddirectlyfromtherootlogger,whichmeansunlessyouexplicitlysettheproperties(appender,layout,andoutputlevel)intheconfigurationtheywillinheritthemfromtheroot.InthedefaultconfigurationtherootissettolevelINFO,theappenderisorg.nlogo.log.XMLFileAppenderandlayoutisorg.nlogo.log.XMLLayout.TogetherthesegenerateanicelyformattedXMLfileasdefinedinthenetlogo_logging.dtdwhichisbasedonthelog4jdtd.IftheappenderisaFileAppender(includingtheXMLFileAppender)anewfileisstarteachtimetheuseropensamodel.
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration debug="false" xmlns:log4j='http://jakarta.apache.org/log4j/'>
<appender name="A1" class="org.nlogo.log.XMLFileAppender"> <layout class="org.nlogo.log.XMLLayout"/> </appender>
<category name="org.nlogo.log.Logger.WIDGETS"> <priority value="off" /> </category>
<category name="org.nlogo.log.Logger.TURTLES"> <priority value="off" /> </category>
<category name="org.nlogo.log.Logger.LINKS">
![Page 221: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/221.jpg)
<priority value="off" /> </category>
<root> <priority value ="info" /> <appender-ref ref="A1" /> </root>
</log4j:configuration>
Thisconfiguration,firstdefinesanappendernamed"A1"oftypeXMLFileAppenderwithanXMLLayout.Theappenderdefineswheretheloggingdatagoes,inthiscasethedatagoesintoafile.Infact,ifNetLogoisgivenaFileAppenderitwillautomaticallystartanewfileeverytimetheuseropensanewmodel.TheXMLFileAppenderalsodoessomeformattingandwritestheappropriateheaderstothefile.Thelayoutdefineshowtowriteeachindividualmessage.Unlessyouareanadvanceduserthereisnoneedchange(orworryabout)theappenderorthelayout.
Attheendoftheconfigurationnoticethedefinitionoftherootlogger.Alloftheotherloggersdescendfromtherootloggerand,thus,inheritthepropertiesoftherootunlessexplicitlyset.Thiscaseisfairlysimple,havingsetuptheappenderA1wemakethatthedefaultappenderfortheroot(andallotherloggers)andmakethedefaultpriority"INFO".MessagesthatareloggedattheINFOlevelorhigherwillbewritten,messagesloggedatlowerlevelswillnot.NotethatwithonlyoneexceptionNetLogoalwayslogsatlevelINFO.Setstoglobalsthatdon'tchangethevalueoftheglobalareloggedatlevelDEBUG.Whichmeansthatthesemessagesaredisabledbydefault,sincedebugislowerlevelthaninfo.Therestofthebodyoftheconfigurationfileoverridespropertiesoftherootloggerinafewspecificloggers(orcategoriesastheyareknownintheconfigurationfile,thetermscanbeassumedtobesynonymousfortheproposesofthisdocument).ThatisitturnsofftheWIDGET,TURTLES,andLINKSloggers,bydefault.Tore-enablethemyoucanchangesthepriorityfromofftoinfo,likethis:
<category name="org.nlogo.log.Logger.TURTLES"> <priority value="info" /> </category>
oryoucansimplyremovetheentirereferencetothecategoryfromtheconfigurationfile,asitisnotservinganyotherpurpose.
AdvancedConfiguration
ThisisonlyabasicintroductiontoconfigurationfilesforlogginginNetLogo.Therearemanymoreconfigurationoptionsavailablethroughthelog4jframework.Seethelog4jdocumentation.
![Page 222: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/222.jpg)
ControllingGuide
NetLogocanbeinvokedandcontrolledbyanotherprogramrunningontheJavaVirtualMachine.Forexample,youmightwanttocallNetLogofromasmallprogramthatdoessomethingsimplelikeautomateaseriesofmodelruns.Or,youmightwanttoembedNetLogomodelsinalargerapplication.
Formoreinformation,gohere.
![Page 223: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/223.jpg)
MathematicaLink
Whatisit?
TheNetLogo-Mathematicalinkprovidesmodelerswithaneasytouse,real-timelinkbetweenNetLogoandMathematica.Together,thesetoolscanprovideuserswithahighlyinteractive,self-documentingworkflowthatneithercanprovidealone.
Mathematicaincludesmanyofthetoolsthatagent-basedmodelersrelyonthroughouttheresearchprocess:advancedimportcapabilities,statisticalfunctions,datavisualization,anddocumentcreation.WiththeNetLogo-Mathematicalink,youcanrunallofthesetoolsside-by-sidewithNetLogo.
BecauseallMathematicadocuments,ornotebooks,containcomments,code,images,annotations,andinteractiveobjects,theintegrationofNetLogoandMathematicaprovidesamorecompletesolutionforcomplexmodelexplorationforstudentsandresearchersalike.
ThebasicfunctionalityofthelinkismuchliketheNetLogoControllingAPI:youcanloadmodels,executecommands,andreportbackdatafromNetLogo.UnliketheControllingAPI,whichisbasedonJava,allinteractionswiththelinkareinterpreted,makingitidealnotonlyforrapidlydesigningcustomBehaviorSpace-likeexperiments,butalsoasacompaniontoNetLogoindebuggingyourmodel.
FormoreinformationaboutMathematica,pleasevisittheWolframResearchwebsite.
WhatcanIdowithit?
HereareafewexamplesofwhatyoucandowiththeMathematica-NetLogolink.
Analyzeyourmodelinreal-timewithseamlesstwo-waydataconversionDevelophighquality,customvisualizationsofmodeldataCollectdetailedsimulationdataacrosslargemulti-dimensionalparameterspacesRapidlydevelopinteractiveinterfacesforexploringmodelbehaviorHavedirectaccesstopatchesandnetworkdatawithbuilt-infunctions
Installation
TheNetLogo-MathematicalinksupportsMathematica10orgreater.ToinstalltheNetLogo-Mathematicalink:
GotothemenubarinMathematicaClickonFileandselectInstall...IntheInstallMathematicaItemdialogSelectPackageforTypeofitemtoinstallClickSource,andselectFromfile...Inthefilebrowser,gotothelocationofyourNetLogoinstallation,clickontheMathematicaLinksubfolder,andselectNetLogo.m.ForInstallName,enterNetLogo.
YoucaneitherinstalltheNetLogolinkinyouruserbasedirectoryorinthesystem-widedirectory.IftheNetLogolinkisinstalledintheuserbasedirectory,otherusersonthesystemmustalsogothroughtheNetLogo-Mathematicalinkinstallationprocesstouseit.Thisoptionmightbepreferableifyoudonothavepermissiontomodifyfilesoutsideofyourhomedirectory.Otherwise,youcaninstallNetLogo-Mathematicalinkinthesystem-wide
![Page 224: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/224.jpg)
Mathematicabasedirectory.
Usage
ThissectionwillverybrieflyintroducehowtousetheNetLogo-MathematicaLink.ItwillshowyouhowtoloadtheNetLogo-Mathematicalinkpackage,startNetLogo,executecommands,andretrievedatafromNetLogo.
Loadingthepackage:OncetheNetLogo-Mathematicalinkisinstalled,youcanloadthepackagebyenteringthefollowingintoyourMathematicanotebook:
<<NetLogo`
LaunchingNetLogofromMathematica:TobeginyourNetLogosessioninMathematica,typethefollowingintoyournotebook:
NLStart["your netlogo path"];
where"yournetlogopath"isthedirectorythatnetlogoislocatedin.TypicallyonaMacthiswillbe"/Applications/NetLogo6.0.2/"
Loadingamodel:Toloadamodel,youmustspecifythefullpathofthemodel.InthisexamplewewillloadtheForestFiremodel,andthepathwillbegivenusingthetypicalMacinstalllocation.
NLLoadModel["/Applications/NetLogo 6.0.2/models/Sample Models/EarthScience/Fire.nlogo"];
ExecutingaNetLogocommand:CommandscanbeexecutedbypassingastringofcommandstoNLCommand[].TheNLCommand[]functionautomaticallysplicescommonMathematicadatatypesintostringssuitableforNetLogo.Thefollowingcommandssetthedensityusingasinglestring,orsetthedensityusingaMathematicadefinedvariable,myDensity.
NLCommand["set density 50"]; myDensity = 60; NLCommand["set density", myDensity];
ReportinginformationfromNetLogo:NetLogodatacanbereportedbacktoMathematicausingNLReport[].Thisincludesnumbers,strings,booleanvalues,andlists.
NLReport["count turtles"]; NLReport["[(list pxcor pycor)] of n-of 10 patches"]
Formoreinformation,seetheNetLogo-MathematicaTutorialnotebookincludedwithNetLogo.Thenotebookwalksyouthroughtheprocessofusingthelink,withmanyexamplesalongtheway.IfyoudonothaveMathematica,butareconsideringusingthelink,youcanfindaPDFofthenotebookincludedwithNetLogointhe"MathematicaLink"directory.
![Page 225: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/225.jpg)
KnownIssues
ANetLogosessioncannotbequitwithoutexitingJ/Link(theJava-Mathematicalink)entirely.ThismaydisruptotherpackagesthatmakeuseofJ/Link.IfamodelloadedwiththeNetLogo-MathematicalinkusesaNetLogoextension,theextensionmustbelocatedinthesamedirectoryasthemodelitself.IftheextensionislocatedinNetLogo'sapplication-wideextensionsdirectory,itwillnotbefound.CallstoNetLogo,suchasNLCommand[]andNLReport[],cannotbeaborted.
Sourcecode
ThesourcecodefortheNetLogo-Mathematicalinkisinthepublicdomain.Itishostedonlineathttps://github.com/NetLogo/Mathematica-Link.
Credits
TheprimarydeveloperoftheNetLogo-MathematicalinkwasEytanBakshy.
Torefertothispackageinacademicpublications,pleaseuse:Bakshy,E.,Wilensky,U.(2007).NetLogo-MathematicaLink.http://ccl.northwestern.edu/netlogo/mathematica.html.CenterforConnectedLearningandComputer-BasedModeling,NorthwesternUniversity,Evanston,IL.
![Page 226: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/226.jpg)
NetLogo3D
NetLogoincludestheNetLogo3Dapplicationthatallowsyoutocreate3Dworlds.
Notice:NetLogo'ssupportfor3DislessdevelopedthanNetLogo2D.Modelscreatedwiththisreleasemaynotbecompatiblewithfutureversions.Whilewe'vemadeeffortstoensureaqualityproduct,NetLogo3Dhasnotbeensubjecttothesamelevelofqualitycontrolasthemainapplication.
IntroductionTutorialDictionary
Introduction
TogetstartedusingNetLogo3D,launchtheNetLogo3DapplicationandcheckouttheSampleModelsinthe3DsectionoftheModelsLibrary.
Whenyou'rereadytowriteyourown3Dmodel,lookattheCodeExamplesinthe3DsectionoftheModelsLibrary.
CodeExample:TurtlePerspectiveExample3Dhelpsyoulearnaboutthedifferentperspectives.
CodeExample:TurtleandObserverMotionExample3Dhelpsyouunderstandhowturtlesandtheobservermovein3D.Youcanalsostepthroughthismodelwiththetutorialbelow.
3DWorlds
Anunspeakablehorrorseizedme.Therewasadarkness;thenadizzy,sickeningsensationofsightthatwasnotlikeseeing;IsawaLinethatwasnoLine;SpacethatwasnotSpace:Iwasmyself,andnotmyself.WhenIcouldfindvoice,Ishriekedloudinagony,"EitherthisismadnessoritisHell."
"Itisneither,"calmlyrepliedthevoiceoftheSphere,"itisKnowledge;itisThreeDimensions:openyoureyeonceagainandtrytolooksteadily."--EdwinA.Abbott,Flatland:Aromanceinmanydimensions
NetLogo3D'sworldhaswidth,heightanddepth.Patchesarecubes.Inadditiontopxcorandpycor,patcheshavepzcor.
TurtleshavethreeCartesiancoordinates,insteadoftwo,todescribeposition.Inadditiontoxcorandycor,turtleshavezcor.
Aturtle'sorientationisdefinedbythreeturtlevariables,heading,pitchandroll.Youcanimaginetheturtleashavingtwovectorstodefineitsorientationin3Dspace.Onevectorcomesstraightoutofthenoseoftheturtle,thisisthedirectiontheturtlewilltravelwhenitmovesforward.Thesecondvectorisperpendiculartotheforwardvectorandcomesoutoftherightsideoftheturtle(asiftheturtleweretostickitsrightarmstraightoutfromitsbody).Headingistheanglebetweentheforwardvectoroftheturtleprojectedontothexy-planeandthevector[010].Pitchistheanglebetweentheforwardvectoroftheturtleandthexy-planeandfinallyrollistheanglebetweentherightvectoroftheturtleandthexy-
![Page 227: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/227.jpg)
plane.Whenturtleturnsrightorleftin3Dspaceitrotatesaroundthedownvector,thatisthevectorthatisperpendiculartoboththeforwardandrightvectors.Dependingontheorientationoftheturtlemorethanoneoftheinternalturtlevariablesmaychangeastheresultofaturn.
Theobserverandthe3Dview
Thepointofviewthatyouseetheworldfromisconsideredthelocationandorientationoftheobserver.Thisissimilartothe3DviewinNetLogo2D.However,thereareafewmorewaystocontroltheobserver.Youcansetthepointthattheobserverisfacingbyusingfaceandfacexyzwhichworkthesamewayastheturtlecommands,theobserverturnssothecenteroftheviewisonthegivenpointorthelocationofthegivenagentatthetimeitiscalled.Youcanchangethelocationoftheobserverusingsetxyz.Theobserverwillmovetoviewtheworldasifstandingonthegivenlocation,thepointtheobserverfaceswillstaythesame.Forexamplecreateanewmodelandobserverwillbelocatedat(0,0,49.5),thatis,onthez-axis49.5patchunitsawayfromtheoriginandtheobserverisfacingtheorigin,(0,0,0).Ifyousetxyz 0 49.5 0theobserverwillmovesoitisonthepositivey-axisbutitwillkeeptheoriginatthecenteroftheview.Youcanalsomovetheobserverusingtherotationprimitivesthatwillallowyoutomovetheobserveraroundtheworldasifonthesurfaceofaspherewherethecenteristhelocationtheobserverisfacing.Youmaynoticefromtheaboveexamplesthattheobserverisnotconstrainedtobewithintheboundsoftheworld.
CustomShapes
NetLogoautomaticallyinterprets2Dshapessotheyareextruded,likeacookiecuttershapeinthe3Dview.Youcanalsousetheprimitiveload-shapes-3dtoloadshapesdescribedinanexternalfileinacustomformatdescribedhere.Currentlywedonotimportshapesinanystandardformats.
Foreachshapeinacustom3Dshapefile,a2Dshapeofthesamenamemustexistaswell.Youcancreatethe2DshapeintheTurtleShapesEditor.
Theinputfilemaycontainanynumberofshapeswithanynumberofrectangularortriangularsurfaces.Theformatoftheinputfileshouldbeasfollows:
number of shapes in filename of first shapetype of surface ( quads or tris )surface1surface2...stoptype of surfacesurfaceA...stopend-shape
Eachsurfaceisdefinedbyaunitnormalvectorandtheverticeslistedinclockwiseorder,trisshouldhavethreeverticesandquadsshouldhavefour.
normal: xn yn znx1 y1 z1
![Page 228: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/228.jpg)
x2 y2 z2x3 y3 z3x4 y4 z4
Afiledeclaringjustatwodimensional,patch-sized,squareinthexy-planecenteredattheoriginwouldlooklikethis:
1squarequadsnormal: 0 0 10.15 0.15 0-0.15 0.15 0-0.15 -0.15 00.15 -0.15 0normal: 0 0 -10.15 0.15 00.15 -0.15 0-0.15 -0.15 0-0.15 0.15 0stopend-shape
Tutorial
Step1:Depth
OneofthefirstthingsyouwillnoticewhenyouopenNetLogo3Disthattheworldisacubeinsteadofasquare.
YoucanopenuptheModelSettings,byclickingonthe"Settings..."buttonatthetopofthe3DView.You'llnoticeinadditiontomax-pxcor,min-pxcor,max-pycor,andmin-pycor,thereisalsomax-pzcorandmin-pzcor.
![Page 229: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/229.jpg)
Thez-axisisperpendiculartoboththex-axisandthey-axis,whenyoureset-perspectiveitistheaxisthatcomesstraightoutofthescreen.Inthedefaultpositionmax-pzcoristhefaceofthecubenearesttoyouandmin-pzcoristhefacefarthestfromyou.Asalwaysmin-pxcorisontheleft,max-pxcorontheright,min-pycoronthebottom,andmax-pycoronthetop.
You'llalsonoticeontheleftsideoftheModelSettingsthatthereareoptionsforwrappinginallthreedirections,however,theyareallcheckedandgrayedout.TopologiesarenotyetsupportedinNetLogo3D,sotheworldalwayswrapsinalldimensions.
MovetotheCommandCenterandtypeprint count patches.
Isthenumbersmallerorlargerthanyouexpected?
![Page 230: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/230.jpg)
Ina3Dworldthenumberofpatchesgrowsveryquicklysincecount patches = world-width * world-height * world-depth.It'simportanttokeepthisinmindwhenyouarebuildingyourmodel.LotsofpatchescanslowyourmodeldownorevencauseNetLogotorunoutofmemory.
Typeask patch 1 2 3 [ set pcolor red ] intotheCommandCenter.Usethemouseinthe3Dviewtorotatetheworld.
Noticetheshapeofthepatchanditspositioninrelationtotheedgesoftheworld.You'llalsonoticethatyounowneedthreecoordinatestoaddresspatchesina3Dworld.
Step2:TurtleMovement
OpentheModelsLibraryintheFilemenu.(IfyouareonaMacandyoudon'thaveaFilemenu,clickonthemainNetLogowindowfirstanditshouldreappear.)OpenTurtleandObserverMotionExample3Din3D/CodeExamples
Takeamomenttolookforthecontrolsandmonitors.Inthebottomleftyou'llnoticeagroupofmonitorsthatdescribethelocationandorientationoftheturtle,thoughuntilyoupressthesetupbuttonthey'llallsay"N/A".
Pressthe"setup"button
Heading,pitch,androllareturtlevariablesthatrepresenttheorientationoftheturtle.Headingisabsoluteinrelationtothex/yplane;itistherotationoftheturtlearoundthez-axis.
Pitchistheanglebetweenthenoseoftheturtleandthexy-plane.Itisrelativetoheading.
![Page 231: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/231.jpg)
Rollistherotationaroundtheturtle'sforwardvector.Itisrelativetoheadingandpitch.
Whenturtlesarecreatedwithcreate-turtlesorcreate-ordered-turtles,theirinitialheadingsvarybuttheirinitialpitchandrollarealwayszero.
Takealookatthe"TurtleMovement"buttons.
Pressthe"left1"button.
Howdoestheturtlemove?Isisthesameordifferentfrom2DNetLogo?Whichoftheturtlevariableschange?
Pressthe"pitch-down1"button.
Howdoestheturtlemove?Whichoftheturtlevariableschange?
Pressthe"left1"buttonagain.
Howdoestheturtlemove?Isitdifferentthanthelasttimeyoupressedthe"left1"button?
TakealittletimetoplaywiththeTurtleMovementbuttons,watchingbothhowtheturtlemovesandwhichoftheturtlevariableschange.
Youprobablynoticedthatoftenmorethanoneoftheturtlevariablesmaychangeforasingleturn.Forthisreasonwesuggestthatyouusetheturtlecommandsratherthan
![Page 232: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/232.jpg)
settingtheorientationvariablesdirectly.
Step3:ObserverMovement
AtthebottomoftheinterfaceyouwillseeOrbit,Zoom,andMovebuttons.Ifyouhaveeverusedthe3DviewinNetLogo2Dorifyouhavebeenusingthemousecontrolsinthe3Dviewthroughthistutorialyouhavebeenmovingtheobserver.Changingthepointofviewinthe3Dviewisactuallymovingandchangingtheorientationoftheobserver.Theobserverhasx,yandzcoordinates,justlikeaturtleorpatch,whileturtlesandpatchesareconstrainedtobeinsidetheworldtheobservercanbeanywhere.Likeaturtletheobserverhasaheading,pitchandroll,thesevariablescontrolwheretheobserverislooking,thatis,whatyouseeintheview.
Movetothe3Dview,andmakesure"Orbit"isselectedinthebottomleftcorneroftheview.Clickandholdthemousebuttoninthemiddleoftheview,movethemouseleft,right,up,anddown.
Howdoesthepositionandorientationoftheobserverchange?
Pressthereset-perspectivebuttoninthelowerrightcorneroftheviewandselect"Zoom"inthelowerleftcorner.Clickandholdthemousebuttoninthemiddleoftheviewandmovethemouseupanddown.
Whichoftheobservervariableschange?Whichstaythesame?
Tryrotatingtheworldabitandthenzoomagain.Pressthe"Move"buttoninthelowerleftcorneroftheview.Clickandholdthemousebuttoninthemiddleoftheviewandmovethemouseup,down,leftandright.
Howdoestheviewchange?Howdotheobservervariableschange?
Afteryouaredoneexploringtheworldusingthemousecontrolsyoucantakealookattheobservercontrolbuttonsinthelowerleftportionoftheinterface.
YoumayalreadybefamiliarwiththefirstthreebuttonsintheobservergroupfromyourexperiencewithNetLogo2D.Watch,follow,andride,arespecialmodesthatautomaticallyupdatethepositionandorientationoftheobserver.Wheninfolloworridemode,theobserverpositionandorientationarethesameastheturtle's.Notethatfollowandridearefunctionallyexactlythesame,thedifferenceisonlyvisualinthe3Dview.Wheninwatchmodetheobserverdoesnotmovebutupdatestofacethetargetagent.
Pressthe"setup"buttonagainsoyouarebacktothedefaultorientation.Pressthe"orbit-right"button.
Howdidtheviewchange?Wasitwhatyouexpected?Howisitsimilarordifferentfromusingthemousecontrols?
Takealittletimetoexperimentwithorbit,rollandzoombuttons;notice
![Page 233: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/233.jpg)
similaritiesanddifferencestothemousecontrols.
Thedirectionoftheorbitcommandsrefertothedirectionthattheobservermoves.Thatis,imaginethattheobserverisonthesurfaceofasphere,thecenterofthesphereisthepointthattheobserverisfacingrepresentedbythebluecross,bydefault(0,0,0).Theobserverwillalwaysfacethecenterofthesphereandtheradiusofthespherewillremainconstant.Thedirections,up,down,left,andright,refertomovingalongthelinesoflatitudeandthelinesoflongitudeofthesphere.Whenyouzoomtheradiusofthespherechangesbutthecenterandtheobserver'sorientationinrelationtothecenterofthespherewillremainthesame.
Pressoneofthe"setxyz"buttons.
Howdoestheviewchange?Howdotheobservervariableschange?
Pressthe"facexyz"button.
Howdoestheviewchange?Howdotheobservervariableschange?
Whenyousetxyzthecenterofthesphereremainsthesame(sotheobserverautomaticallykeepsthatpointinthecenteroftheview.)However,theradiusofthespheremaychangeaswellastheobserver'sorientationinrelationtothecenter.Whenyoufacexyzorface,thecenterofthespherechangesbuttheobserverdoesnotmove.Theradiusofthespheremaychange,aswellastheorientationoftheobserver.
Dictionary
CommandsandReporters
Turtle-relatedprimitives
distancexyzdistancexyz-nowrapdzleftpatch-atpatch-at-heading-pitch-and-distancetilt-downtilt-uprightroll-leftroll-rightsetxyztowards-pitchtowards-pitch-nowraptowards-pitch-xyztowards-pitch-xyz-nowrapturtles-at
Patch-relatedprimitives
distancexyzdistancexyz-nowrapneighborsneighbors6patchpatch-atpatch-at-heading-pitch-and-distance
Agentsetprimitives
at-pointsbreeds-atturtles-at
Worldprimitives
![Page 234: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/234.jpg)
Since4.1
Since4.1Since4.1
max-pzcormin-pzcorrandom-pzcorrandom-zcorworld-depthload-shapes-3d
Observerprimitives
facefacexyzorbit-downorbit-leftorbit-rightorbit-up__oxcor__oycor__ozcorsetxyzzoom
Linkprimitives
link-pitch
Built-InVariables
Turtles
zcorpitchroll
Patches
pzcor
Primitives
at-points
agentsetat-points[[x1y1z1][x2y2z2]...]
Reportsasubsetofthegivenagentsetthatincludesonlytheagentsonthepatchesthegivendistancesawayfromthisagent.Thedistancesarespecifiedasalistofthree-itemlists,wherethethreeitemsarethex,y,andzoffsets.
Ifthecalleristheobserver,thenthepointsaremeasuredrelativetotheorigin,inotherwords,thepointsaretakenasabsolutepatchcoordinates.
Ifthecallerisaturtle,thepointsaremeasuredrelativetotheturtle'sexactlocation,andnotfromthecenterofthepatchundertheturtle.
ask turtles at-points [[2 4 0] [1 2 1] [10 15 10]][ fd 1 ] ;; only the turtles on the patches at the ;; distances (2,4,0), (1,2,1) and (10,15,10), ;; relative to the caller, move
distancexyzdistancexyz-nowrap
distancexyzxcorycorzcordistancexyz-nowrapxcorycorzcor
![Page 235: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/235.jpg)
Since4.1
Since4.1
Since4.1
3Dversionsofdistancexy.
Reportsthedistancefromthisagenttothepoint(xcor,ycor,zcor).
Thedistancefromapatchismeasuredfromthecenterofthepatch.
distancexyz-nowrapalwaysreportstheinworlddistance,neveradistancethatwouldrequirewrappingaroundtheedgesoftheworld.Withdistancexyzthewrappeddistance(aroundtheedgesoftheworld)isusedifthatdistanceisshorterthantheinworlddistance.
if (distancexyz 0 0 0) < 10 [ set color green ];; all turtles less than 10 units from;; the center of the screen turn green.
dz
dz
Reportsthez-increment(theamountbywhichtheturtle'szcorwouldchange)iftheturtleweretotakeonestepforwardatitscurrentheadingandpitch.
NOTE:dzissimplythesineoftheturtle'spitch.Bothdxanddyhavechangedinthiscase.So,dx=cos(pitch)*sin(heading)anddy=cos(pitch)*cos(heading).
Seealsodx,dy.
facefacexyz
faceagentfacexyzxyz
Setthecaller'sheadingandpitchtowardsagentortowardsthepoint(x,y,z).
Ifthecallerandthetargetareatthesamexandycoordinatesthecaller'sheadingwillnotchange.Ifthecallerandthetargetarealsoatthesamezcoordinatethepitchwillnotchangeeither.
left
leftnumber
Theturtleturnsleftbynumberdegrees,relativetoitscurrentorientation.Whileleftina2Dworldonlymodifiestheturtle'sheading,leftina3Dworldmayalsomodifytheturtle'spitchandroll.
![Page 236: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/236.jpg)
Since4.1.2
Since4.1
Since4.1Since4.1
Since4.1Since4.1
Seealsoleft,tilt-up,tilt-down
link-pitch
link-pitch
Reportsthepitchfromend1toend2ofthislink.
ask link 0 1 [ print link-pitch ];; prints [[towards-pitch other-end] of end1] of link 0 1
Seealsolink-heading,pitch
load-shapes-3d
load-shapes-3dfilename
Loadscustom3Dshapesfromthegivenfile.Seethe3Dguideformoredetails.Youmustalsoadda2DshapeofthesamenametothemodelusingtheTurtleShapesEditor.Customshapesoverridebuilt-in3Dshapesandconverted2Dshapes.
max-pzcormin-pzcor
max-pzcormin-pzcor
Thesereportersgivethemaximumandminimumz-coordinates(respectively)forpatches,whichdeterminesthesizeoftheworld.
UnlikeinolderversionsofNetLogotheorigindoesnothavetobeatthecenteroftheworld.However,theminimumz-coordinatehastobelessthanorequalto0andthemaximumz-coordinatehastobegreaterthanorequalto0.
Note:Youcansetthesizeoftheworldonlybyeditingtheview--thesearereporterswhichcannotbeset.
Seealsomax-pxcor,max-pycor,min-pxcor,min-pycor,andworld-depth.
neighborsneighbors6
neighborsneighbors6
![Page 237: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/237.jpg)
Since4.1Since4.1Since4.1Since4.1
Since4.1
3Dversionsofneighborsandneighbors4.
Reportsanagentsetcontainingthe26surroundingpatches(neighbors)or6surroundingpatches(neighbors6).
show sum values-from neighbors [count turtles-here] ;; prints the total number of turtles on the twenty-six ;; patches around this turtle or patchask neighbors6 [ set pcolor red ] ;; turns the six neighboring patches red
orbit-downorbit-leftorbit-rightorbit-up
orbit-downnumberorbit-leftnumberorbit-rightnumberorbit-upnumber
Rotatetheobserveraroundthelastpointfaced.Imaginetheobserverisonthesurfaceofasphere,thelastpointfaceisthecenterofthatsphere.Upanddownorbitalongthelinesoflongitudeandrightandleftorbitalongthelinesoflatitude.Theobserverwillremainfacingthelastpointfacedsotheheadingandpitchmaychangeasresultoforbiting.However,becauseweassumeanabsolutenorthpole(paralleltothepositivez-axis)therollwillneverchange.
Seealsosetxyz,faceandzoom
__oxcor__oycor__ozcor
__oxcor__oycor__ozcor
Reportsthex-,y-,orz-coordinateoftheobserver.
Seealsosetxyz
patch
patchpxcorpycorpzcor
3Dversionofpatch.
![Page 238: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/238.jpg)
Since4.1
Since4.1
Giventhreeintegers,reportsthesinglepatchwiththegivenpxcor,pycorandpzcor.pxcor,pycorandpzcormustbeintegers.
ask (patch 3 -4 2) [ set pcolor green ];; patch with pxcor of 3 and pycor of -4 and pzcor of 2 turns green
Seealsopatch
patch-at
patch-atdxdydz
3Dversionofpatch-at.
Reportsthesinglepatchat(dx,dy,dz)fromthecaller,thatis,dxpatcheseast,dypatchesnorthanddzpatchesupfromthecaller.
ask patch-at 1 -1 1 [ set pcolor green ];; turns the patch just southeast and up from the caller green
patch-at-heading-pitch-and-distance
patch-at-heading-pitch-and-distanceheadingpitchdistance
3Dversionofpatch-at-heading-and-distance.
patch-at-heading-pitch-and-distancereportsthesinglepatchthatisthegivendistancefromthisturtleorpatch,alongthegivenabsoluteheadingandpitch.(Incontrasttopatch-left-and-aheadandpatch-right-and-ahead,thisturtle'scurrentheadingisnottakenintoaccount.)
ask patch-at-heading-pitch-and-distance 0 90 1 [ set pcolor green ];; turns the patch directly above the caller green.
pitch
pitch
Thisisabuilt-inturtlevariable.Pitchistheanglebetweenthe"nose"oftheturtleandthexy-plane.Headingandpitchtogetherdefinetheforwardvectoroftheturtleorthedirectionthattheturtleisfacing.
Thisisanumbergreaterthanorequalto0andlessthan360.0isparalleltothexy-plane,90isparalleltothez-axis.Whileyoucansetpitchwerecommendthatyouusetheprimitivestoturntheturtle.Dependingonthepositionmorethanonerelativeangle
![Page 239: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/239.jpg)
Since4.1
Since4.1
(heading,pitchandroll)maychangeatonce.
Example:
;; assume roll and heading are 0set pitch 45 ;; turtle is now north and upset heading heading + 10 ;; same effect as "tilt-up 10"
Seealsoheading,roll,tilt-up,tilt-down,right,left
pzcor
pzcor
Thisisabuilt-inpatchvariable.Itholdsthezcoordinateofthepatch.Itisalwaysaninteger.Youcannotsetthisvariable,becausepatchesdon'tmove.
pzcorisgreaterthanorequaltomin-pzcorandlessthanorequaltomax-pzcor.
Allpatchvariablescanbedirectlyaccessedbyanyturtlestandingonthepatch.
Seealsopxcor,pycor,zcor.
random-pzcor
random-pzcor
Reportsarandomintegerrangingfrommin-pzcortomax-pxcorinclusive.
ask turtles [ ;; move each turtle to the center of a random patch setxyz random-pxcor random-pycor random-pzcor]
Seealsorandom-pxcor,random-pycor.
random-zcor
random-zcor
Reportsarandomfloatingpointnumberfromtheallowablerangeofturtlecoordinatesalongthezaxis.
Turtlecoordinatesrangefrommin-pzcor-0.5(inclusive)tomax-pzcor+0.5(exclusive).
ask turtles [ ;; move each turtle to a random point setxyz random-xcor random-ycor random-zcor]
![Page 240: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/240.jpg)
Since4.1
Since4.1
Since4.1
Seealsorandom-xcor,random-ycor.
right
rightnumber
Theturtleturnsrightbynumberdegrees,relativetoitscurrentorientation.Whilerightina2Dworldonlymodifiestheturtle'sheading,rightina3Dworldmayalsomodifytheturtle'spitchandroll.
Seealsorightandleft
roll
roll
Thisisabuilt-inturtlevariable.Rollistheanglebetweenthe"wing-tip"oftheturtleandthexy-plane.
Thisisanumbergreaterthanorequalto0andlessthan360.Youcansetthisvariabletomakeaturtleroll.Sincerollisalwaysfromtheturtle'spointofview,rollingrightandleftonlyonlychangerollregardlessofturtleorientation.
Example:
set roll 45 ;; turtle rotated rightset roll roll + 10 ;; same effect as "roll-right 10"
Seealsoheading,pitch,roll-left,roll-right.
roll-left
roll-leftnumber
Thewingtipoftheturtlerotatestotheleftnumberdegreeswithrespecttothecurrentheadingandpitch.
roll-right
roll-rightnumber
Thewingtipoftheturtlerotatestotherightnumberdegreeswithrespecttothecurrentheadingandpitch.
![Page 241: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/241.jpg)
Since4.1
Since4.1Since4.1
Since4.1Since4.1
setxyz
setxyzxyz
3Dversionofsetxy.
Theagent,aturtleortheobserver,setsitsx-coordinatetox,itsy-coordinatetoyanditsz-coordinatetoz.Whentheobserverusessetxyzitremainsfacingthesamepointsotheheading,pitch,androll,mayalsochange.
Forturtlesequivalenttoset xcor x set ycor y set zcor z,exceptithappensinonetimestepinsteadofthree.
setxyz 0 0 0;; agent moves to the middle of the center patch
Seealsoface
tilt-downtilt-up
tilt-downnumbertilt-upnumber
Thenoseoftheturtlerotatesbynumberdegrees,relativetoitscurrentorientation.Dependingontheorientationoftheturtlemorethanoneoftherelativeangles(heading,pitch,androll)maychangewhenaturtleturns.
towards-pitchtowards-pitch-nowrap
towards-pitchagenttowards-pitch-nowrapagent
Reportsthepitchfromthisagenttothegivenagent.
Ifthewrappeddistance(aroundtheedgesofthescreen)isshorterthantheon-screendistance,towards-pitchwillreportthepitchofthewrappedpath.towards-pitch-nowrapneverusesthewrappedpath.
Note:Inordertogetoneturtletofaceanotheryouneedtousebothtowards-pitchandtowards.
Note:askingforthepitchfromanagenttoitself,oranagentonthesamelocation,willcausearuntimeerror.
Seealsotowards
![Page 242: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/242.jpg)
Since4.1Since4.1
Since4.1
Since4.1
towards-pitch-xyztowards-pitch-xyz-nowrap
towards-pitch-xyzxyztowards-pitch-xyz-no-wrapxyz
Reportsthepitchfromthisagenttothecoordinatesx,y,z
Ifthewrappeddistance(aroundtheedgesofthescreen)isshorterthantheon-screendistance,towards-pitchwillreportthepitchofthewrappedpath.towards-pitch-nowrapneverusesthewrappedpath.
Note:Inordertogetaturtletofaceagivenlocationyouneedtousebothtowards-pitch-xyzandtowardsxy.
Note:askingforthepitchfromanagenttothelocationitisstandingonwillcausearuntimeerror.
Seealsotowardsxy
turtles-at<breeds>-at
turtles-atdxdydz<breeds>-atdxdydz
3Dversionsofturtles-atandbreeds-at.
Reportsanagentsetcontainingtheturtlesonthepatch(dx,dy,dz)fromthecaller(includingthecalleritselfifit'saturtle).
;; suppose I have 40 turtles at the originshow [count turtles-at 0 0 0] of turtle 0=> 40
world-depth
world-depth
ReportsthetotaldepthoftheNetLogoworld.
Thedepthoftheworldisthesameasmax-pzcor-min-pzcor+1.
Seealsomax-pzcor,min-pzcor,world-width,andworld-height
zcor
![Page 243: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/243.jpg)
Since4.1
zcor
Thisisabuilt-inturtlevariable.Itholdsthecurrentzcoordinateoftheturtle.Thisisafloatingpointnumber,notaninteger.Youcansetthisvariabletochangetheturtle'slocation.
Thisvariableisalwaysgreaterthanorequalto(-screen-edge-z)andstrictlylessthanscreen-edge-z.
Seealsosetxy,xcor,ycor,pxcor,pycor,pzcor
zoom
zoomnumber
Movetheobservertowardthepointitisfacing,numbersteps.Theobserverwillnevermovebeyondthepointitisfacingsoifnumberisgreaterthanthedistancetothatpointitwillonlymoveasfarasthepointitisfacing.
![Page 244: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/244.jpg)
ExtensionsGuide
NetLogoallowsuserstowritenewcommandsandreportersinJavaandotherlanguagesandusethemintheirmodels.ThissectionoftheUserManualintroducesthisfacilityandshowshowtouseanextensioninyourmodelonceyouhaveobtainedormadeone.
ExtensionscreatedbymembersoftheNetLogocommunityareavailablefromhttps://github.com/NetLogo/NetLogo/wiki/Extensions.
Forinformationoncreatingyourownextensions,gohere.
UsingExtensions
Touseanextensioninamodel,addtheextensionskeywordatthebeginningoftheCodetab,beforedeclaringanybreedsorvariables.
Afterextensionscomesalistofextensionnamesinsquarebrackets.Forexample:
extensions [sound speech]
UsingextensionstellsNetLogotofindandopenthespecifiedextensionandmakesthecustomcommandsandreportersfoundintheextensionavailabletothecurrentmodel.Youcanusethesecommandsandreportersjustasiftheywerebuilt-inNetLogoprimitives.
Whereextensionsarelocated
NetLogowilllookforextensionsinseveralplaces:
1. Inthefolderofthecurrentmodel.2. TheextensionsfolderlocatedwiththeNetLogoinstallation.FortypicalNetLogo
installations:OnMacOSX:/Applications/NetLogo 6.0.2/extensionsOn64-bitWindowswith64-bitNetLogoor32-bitWindowswith32-bitNetLogo:C:\Program Files\NetLogo 6.0.2\app\extensionsOn64-bitWindowswith32-bitNetLogo:C:\Program Files (x86)\NetLogo6.0.2\app\extensionsOnLinux:theapp/extensionssubdirectoryoftheNetLogodirectoryextractedfromtheinstallation.tgz
EachNetLogoextensionconsistsofafolderwiththesamenameastheextension,entirelyinlowercase.ThisfoldermustcontainaJARfilewiththesamenameasthefolder.Forexamplethesoundextensionisstoredinafoldercalledsoundwithafileinsidecalledsound.jar.
ToinstallaNetLogoextensionforusebyanymodel,puttheextension'sfolderintheNetLogoextensionsdirectory.Or,youcanjustkeeptheextension'sfolderinthesamefolderasthemodelthatusesit.
Someextensionsdependonadditionalfiles.Thesefileswillbeintheextension'sfolderalongwiththeJARfile.Thefoldermayalsocontainotherfilessuchasdocumentationandexamplemodels.
![Page 245: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/245.jpg)
NetLogoArduinoExtension
Using
Forafirstusewithoutcompilingcode,dothefollowing:
1. AcquiretheNetLogosoftware.TheArduinoextensioncomespre-installedwithNetLogo5.2.1andlater.
2. AcquireanArduinoboardandinstallthearduinoIDE
3. UsetheArduinoIDEtoedittheSketch(ifdesired)andsendtotheboard.(Seeelaboratecommentsinthesketchforrecommendationsaboutwhattocommentout/leaveindependingonyoursetup&circuitontheboard.)
4. OncetheArduinohasthesketchloadedonit,itwillrunthatsketchwheneveritispoweredon.
5. Openthetest“ArduinoExample”modelintheNetLogoModelslibrary(it’sinthe“IABMTextbook”>“Chapter8”folder)
6. ConnecttheArduinotoaUSBportonthecomputerifitisnotstillconnectedfromstep3.
7. PressOPENtochoosetheporttocommunicatewithandestablishtheconnection.
8. Usethebuttonstosendbytecommands;usetheinterfacetoinspectvariablevalue(s)thatyoursketchissending.
9. Notethatbytypingarduino:primitivesyoucangetalistoftheavailablecommandsintheextension.
Notes
ANetLogomodelusingthisextensionmustworkinconjunctionwithanArduinoSketch.Thesetwoendpointscommunicatebywayofanapplicationprotocolthattheydefine.Forexample,iftheNetLogomodelsendsabyte‘1’overthewirethismaymeansomethingtotheArduinoSketch,whichwillrespondaccordingly.TheArduinoSketchforitsownpartmaysendname-valuepairsovertheserialport,whichthencanbelookedupasynchronouslybytheNetLogomodel.
Themodelerisfreetobuildassimpleorascomplexanapplicationprotocolontopofthisrawcommunicationmechanism.
Theasynchronousnatureoftheboard-to-computercommunicationshasonenotablelimitation.Ifyouchoosetotrytosimulateasynchronous,BLOCKINGREADcommunicationspattern,(e.g.,bysendingabyte-basedsignaltotheboard,whichtriggersaresponseinaknownname-valuepair),thenyouarelikelytobe‘offbyone’response.Thatis,ifyoudothefollowinginNetLogocode:
arduino:write-byte bshow arduino:get "varname"
YouarelikelytogetthevalueofvarnamefromthePRIORcommandrepresentedby
![Page 246: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/246.jpg)
writingthebyteb.ThisisbecausethesecondlineofNetLogocodewillexecutewhiletheArduinoisoffgeneratinganewvalueforvarname.
Therearewaysofgettingaroundthis(simulatingablockinginterfacebypollingonavaluetoindicatefresh“news”onvarname).ButthisextensionworksbestinsettingswheretheArduinoSketchis“chatty”andtheNetLogomodelsamplesthisstreamwhenitneedsdata.
Compatibility
ThiscodehasbeentestedonWindows7and10with32-bitNetLogoandonMacOSX.Youarelikelytoencounterissueswhenrunningthiswith64-bitNetLogoinWindows8orWindows10,soifyouhaveWindows8or10,pleasedownloadthe32-BitversionofNetLogoifyouplanonusingtheArduinoextension.Westriveforcross-platformcompatibilityacrossMac,Win,andLinux.Soifyouhavetroubles,pleaseletusknow.
Questions
Ifyourunintoproblemsorhavequestionsabouttheextension,[email protected].
Primitives
arduino:primitivesarduino:portsarduino:openarduino:closearduino:getarduino:write-stringarduino:write-intarduino:write-bytearduino:is-open?
arduino:primitives
arduino:primitives
Reportsalistofprimitivesavailableintheextension,withbasichintsabouttheirsyntax.
arduino:ports
arduino:ports
Reportsalistofportnames
arduino:open
arduino:openport-name
Openstheportnamedport-name.
arduino:close
arduino:close
Closesthecurrentlyopenport.
![Page 247: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/247.jpg)
arduino:get
arduino:getvar-name
Readsandreportsthevalueassociatedwithvar-nameontheArduinoboard.Note:var-nameiscaseinsensitive.
arduino:write-string
arduino:write-stringstring-message
Writesastringmessagetothecurrentlyopenport.
arduino:write-int
arduino:write-intint-message
Writesaintegermessagetothecurrentlyopenport.
arduino:write-byte
arduino:write-bytebyte-message
Writesabytemessagetothecurrentlyopenport.
arduino:is-open?
arduino:is-open?
Reportsabooleanvalue(trueorfalse)indicatingifaportisopen.
![Page 248: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/248.jpg)
NetLogoArrayExtension
Using
Thearrayextensionispre-installedinNetLogo.
Tousethearrayextensioninyourmodel,addalinetothetopofyourCodetab:
extensions [array]
Ifyourmodelalreadyusesotherextensions,thenitalreadyhasanextensionslineinit,sojustaddarraytothelist.
FormoreinformationonusingNetLogoextensions,seetheExtensionsGuide
WhentoUse
Ingeneral,anythingyoucandowithanarrayinNetLogo,youcouldalsojustusealistfor.Butyoumaywanttoconsiderusinganarrayinsteadforspeedreasons.Listsandarrayshavedifferentperformancecharacteristics,soyoumaybeabletomakeyourmodelrunfasterbyselectingtheappropriatedatastructure.
Arraysareusefulwhenyouneedacollectionofvalueswhosesizeisfixed.Youcanquicklyaccessoralteranyiteminanarrayifyouknowitsposition.
UnlikeNetLogo’slistsandstrings,arraysare“mutable”.Thatmeansthatyoucanactuallymodifythemdirectly,ratherthanconstructinganalteredcopyaswithlists.Ifthearrayisusedinmorethanoneplaceinyourcode,anychangesyoumakewillshowupeverywhere.It’strickytowritecodeinvolvingmutablestructuresandit’seasytomakesubtleerrorsorgetsurprisingresults,sowesuggeststickingwithlistsandstringsunlessyou’recertainyouwantandneedmutability.
ExampleuseofArrayExtension
let a array:from-list n-values 5 [0]print a=> {{array: 0 0 0 0 0}}print array:length a=> 5foreach n-values 5 [ i -> i ] [ i -> array:set a i i * i ]print a=> {{array: 0 1 4 9 16}}print array:item a 0=> 0print array:item a 3=> 9array:set a 3 50print a=> {{array: 0 1 4 50 16}}
Primitives
array:from-listarray:itemarray:setarray:lengtharray:to-list
array:from-list
![Page 249: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/249.jpg)
array:from-list
array:from-listlist
Reportsanewarraycontainingthesameitemsinthesameorderastheinputlist.
array:item
array:itemarrayindex
Reportstheiteminthegivenarraywiththegivenindex(rangingfromzerotothelengthofthearrayminusone).
array:set
array:setarrayindexvalue
Setstheiteminthegivenarraywiththegivenindex(rangingfromzerotothelengthofthearrayminusone)tothegivenvalue.
Notethatunlikethereplace-itemprimitiveforlists,anewarrayisnotcreated.Thegivenarrayisactuallymodified.
array:length
array:lengtharray
Reportsthelengthofthegivenarray,thatis,thenumberofitemsinthearray.
array:to-list
array:to-listarray
Reportsanewlistcontainingthesameitemsinthesameorderasthegivenarray.
![Page 250: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/250.jpg)
NetLogoBitmapExtension
Using
Thebitmapextensionispre-installedinNetLogo.Forinstructionsonusingit,orformoreinformationaboutNetLogoextensions,seetheNetLogoUserManual.
WhatdoestheBitmapExtensiondo?
TheBitmapExtensionallowsyoutomanipulateandimportimagesintothedrawingandpatches.ItoffersfeaturesnotprovidedbytheNetLogocoreprimitives,suchas:scaling,manipulationofdifferentcolorchannels,andwidthandheightreporters.
Gettingstarted
ToimportandmanipulateimagesyouwillneedtoincludethebitmapextensioninyourNetLogomodel.
extensions[ bitmap ]
TheimagefileformatssupportedaredeterminedbyyourJavavirtualmachine’simageiolibrary.TypicallythisisPNG,JPG,GIF,andBMP.PNGisagood,standardchoicethatislikelytoworkeverywhere.
Iftheimageformatsupportstransparency(alpha),thatinformationwillbeimportedaswell.
Primitives
bitmap:average-colorbitmap:channelbitmap:copy-to-drawingbitmap:copy-to-pcolorsbitmap:difference-rgbbitmap:exportbitmap:from-viewbitmap:to-grayscalebitmap:heightbitmap:importbitmap:scaledbitmap:width
bitmap:average-color
bitmap:average-colorimage
Reportsa3-elementlistdescribingtheamountofR,G,andBinimage,bysummingacrossallpixels,andnormalizingeachcomponentbythenumberofpixelsintheimage,soeachcomponentrangesfrom0to255.
bitmap:channel
bitmap:channelimagechannel
Extractseitherthealpha,red,green,orbluechannelfromanimage.Theinputchannelshouldbeaninteger0-3indicatingthechanneltoremove(alpha=0,red=1,green=2,blue=3).Theresultingimageisagrayscaleimagerepresentingspecifiedchannel.
![Page 251: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/251.jpg)
bitmap:copy-to-drawing
bitmap:copy-to-drawingimagexy
Importsthegivenimageintothedrawingwithoutscalingtheimageatthegivenpixelcoordinates.
bitmap:copy-to-pcolors
bitmap:copy-to-pcolorsimageboolean
Importsthegivenimageintothepcolors,scaledtofittheworld.ThesecondinputindicateswhetherthecolorsshouldbeinterpretedasNetLogocolorsorleftasRGBcolors.falsemeansRGBcolors.
bitmap:difference-rgb
bitmap:difference-rgbimage1image2
Reportsanimagethatistheabsolutevalueofthepixel-wiseRGBdifferencebetweentwoimages.Notethatimage1andimage2MUSTbethesamewidthandheightaseachother,orerrorswillensue.
bitmap:export
bitmap:exportimagefilename
Writesimagetofilename.
bitmap:from-view
bitmap:from-view
Reportsanimageofthecurrentview.
bitmap:to-grayscale
bitmap:to-grayscaleimage
Convertsthegivenimagetograyscale.
bitmap:height
bitmap:heightimage
Reportstheheightofgivenimage
bitmap:import
![Page 252: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/252.jpg)
bitmap:importfilename
ReportsaLogoBitmapcontainingtheimageatfilename.
bitmap:scaled
bitmap:scaledimagewidthheight
Reportsanewimagethatisimagescaledtothegivenwidthandheight
bitmap:width
bitmap:widthimage
Reportsthewidthofthegivenimage
![Page 253: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/253.jpg)
NetLogoCfExtension
Using
TheCFextensioncurrentlyincludesprimitivesthatallowyoutodothingssimilartoif-elseif-elsechainsyouseeinotherlanguages,aswellasthingssimilartoswitchesinotherlanguages.However,itdoesitinamoreflexiblewaythanmanylanguages.Afewquickexamplestogetyoustarted:
let x 5let y 7cf:whencf:case [ x > y ] [ print "x is bigger than y!" ]cf:case [ x < y ] [ print "x is less than y!" ]cf:else [ print "x is the same as y!" ]
let my-awesome-number 5cf:match my-awesome-numbercf:case [ [n] -> n > 7 ] [ print "The number is greater than 7!" ]cf:case [ [n] -> n < 3 ] [ print "The number is less than 3!" ]cf:else [ print "The number is somewhere in between 3 and 7!" ]
Cases
Centraltothisextensionistheconceptofacase.Acaseissimplyalistoftwoelements,wherethefirstelementisareporterandthesecondelementiseitherareporteroracommand.Thefirstelement,calledthecondition,mustreporteithertrueorfalse.Thesecondargumentiscalledtheconsequent.Ifyou’recuriousabouthowCFworks,keepreadingthissection.Otherwise,feelfreetoskiptothelistofprimitives;youdon’tneedtounderstandtheinternalstostartusingCF.
AlmostallprimitivesintheCFextensiontakealistofcasesasanargument.Typically,theygothroughthecases,lookingforatruecondition.Whentheyfindone,theythenruntheconsequent.AlthoughCFprovidesprimitivesthatmakeconstructingalistofcaseseasy,youcouldactuallyjustbuildsuchalistwithprimitivesalreadyinNetLogo,likeso:
let x 5let y 7let list-of-cases (list (list task [ x > y ] task [ print "x is greater than y!" ]) (list task [ x < y ] task [ print "x is less than y!" ]) (list task [ true ] task [ print "x is the same as y!" ]))
However,thisisnotverynicelooking.WithCF,youcanwriteitlikethisinstead:
let x 5let y 7
let list-of-casescf:case [ x > y ] [ print "x is greater than y!" ]cf:case [ x < y ] [ print "x is less than y!" ]cf:else [ print "x is the same as y!" ]
Primitives
![Page 254: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/254.jpg)
cf:whencf:selectcf:matchcf:matchingcf:casecf:case-iscf:else
cf:when
cf:whenlist-of-cases
Runsthecommandtaskfromthefirstcaseinthelistwithatruecondition.Forinstance:
let x 3cf:whencf:case [ x < 2 ] [ print "x is less than 2!" ]cf:case [ x < 4 ] [ print "x is less than 4!" ]cf:case [ x < 6 ] [ print "x is less than 6!" ]cf:else [ print "x is greater than or equal to 6!" ]
Theabovecodewillprintoutx is less than 4! sincethat’sthefirstcasewithatruecondition.
Ifnotruecaseisfound,andnocf:elsegiven,cf:whenwillerrorwithasuggestionforafix.
cf:select
cf:selectlist-of-cases
Picksthefirstcaseinthelistwithatrueconditionandreportstheresultofitsconsequent.Theconsequentsofthecasesinacf:selectmustbereportertasks.Thus,cf:selectisexactlylikecf:when,exceptthatitreportsthevaluefromthetruecase,ratherthanjustrunningit.Forexample:
let x 3print cf:selectcf:case [ x < 2 ] [ "x is less than 2!" ]cf:case [ x < 4 ] [ "x is less than 4!" ]cf:case [ x < 6 ] [ "x is less than 6!" ]cf:else [ "x is greater than or equal to 6!" ]
Theabovecodewillprintoutx is less than 4! sincethat’sthefirstcasewithatruecondition.
Ifnotruecaseisfound,andnocf:elsegiven,cf:selectwillerrorwithasuggestionforafix.
cf:match
cf:matchvaluelist-of-cases
cf:matchislikecf:when,exceptthatitappliestheconditionsinitscasestothegivenvalue.Forinstance:
ask patch 0 0 [ set pcolor red ]cf:match ([ pcolor ] of patch 0 0)cf:case [ [c] -> c = green ] [ print "The center patch is green!" ]cf:case [ [c] -> c = red ] [ print "The center patch is red!" ]cf:case [ [c] -> c = blue ] [ print "The center patch is blue!" ]cf:else [ print "I don't know what color the center patch is!" ]
![Page 255: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/255.jpg)
TheabovecodewillprintoutThe center patch is green! sincethat’sthefirstcasewithatruecondition.
Thevalueisalsopassedtotheconsequentofthecase.Forinstance:
cf:match one-of turtlescf:case [ [t] -> [color] of t = red ] [ [t] -> ask t [ show "I'm red!" ] ]cf:case [ [t] -> [color] of t = blue ] [ [t] -> ask t [ show "I'm blue!" ] ]cf:else [ [t] -> ask t [ show "I'm some other color!" ] ]
Ifnomatchingcaseisfound,cf:matchwillerrorwithasuggestionforafix.
cf:matching
valuecf:matchinglist-of-cases
cf:matchingislikecf:match,exceptthatitreportstheresultofthematchingcase.cf:matchingistocf:matchascf:selectistocf:when.Forinstance:
let my-awesome-number 3print my-awesome-number cf:matchingcf:case [ [num] -> num < 2 ] [ "The number is less than 2!" ]cf:case [ [num] -> num < 4 ] [ "The number is less than 4!" ]cf:case [ [num] -> num < 6 ] [ "The number is less than 6!" ]cf:else [ "The number is greater than or equal to 6!" ]
TheabovecodewillprintoutThe number is less than 4! sincethat’sthefirstcasewithatruecondition.cf:matchingalsoappliestheconsequentofthematchingcasetothegivenvalue,justlikecf:match:
print (one-of turtles) cf:matchingcf:case [ [t] -> [color] of t = red ] [ [t] -> [ "I'm red!" ] of t ]cf:case [ [t] -> [color] of t = blue ] [ [t] -> [ "I'm blue!" ] of t ]cf:else [ [t] -> [ "I'm some other color!" ] of t ]
Ifnomatchingcaseisfound,cf:matchingwillerrorwithasuggestionforafix.
cf:case
cf:caseconditionconsequentlist-of-remaining-cases
cf:caseallowsyoutoconstructalistofcasesthattheotherprimitiveswillthenpickfrom.Itconstructsanewcasefromthethetwogiventasksandaddsittothefrontofthelistofremainingcases.Thus,youcanchainittogetherwithotherinstancesofcf:casetocreateanarbitrarilylonglistofcases.
Notethatbecausetheconditioninacaseisjustananonymousreporter,youcancheckformanycommonconditionsinaveryconcisemanner.Forinstance,ifwewanttodosomethingdependingonthebreedofaturtle,youcando:
cf:match my-turtlecf:case is-wolf? [ show "Growl!" ]cf:case is-a-sheep? [ show "Baah!" ]cf:case is-dog? [ show "Bark!" ]cf:case is-cat? [ show "Meow!" ]cf:else [ show "I'm not sure what sound to make..." ]
![Page 256: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/256.jpg)
cf:case-is
cf:case-isrelationshipconsequentlist-of-remaining-cases
cf:case-isallowsyoutowritesomecommonusesofcf:caseincf:matchorcf:matchinginamoreconcise,readableway.Thegivenreportershouldbearelationshipsuchas=,<,ormember?.cf:case-isthenfillsinthesecondargumentofthereporterwiththegivenvalue.Thisismucheasiertounderstandinanexample:
let x 5print x cf:matchingcf:case-is = 0 [ "x is 0!" ]cf:case-is = 1 [ "x is 1!" ]cf:case-is > 2 [ "x is greater than 2!" ]cf:case-is member? [ -1 -2 -3] [ "x is either -1, -2, or -3" ]cf:else [ "x is something else" ]
Thus,cf:case-isallowsyoutodosomethingquitesimilartoswitchinsomeotherlanguages,butisalsomuchmoreflexible.
cf:else
cf:elsecommand/reporter
cf:elsecreatesacasewheretheconditionisalwaystrue.Thus,itallowsyoutocreateacasethatwillberunifalltheothercasesfail.Youshouldalmostalwaysfinishupachainofcaseswithcf:else.However,ifyou’dprefertoerrorratherthanhaveadefaultcase,youcanreplacecf:elsewith[],likeso:
let x -5cf:whencf:case [ 0 < x and x < 10 ] [ print "x is between 0 and 10!" ]cf:case [ x < 100 ] [ print "x is less than 100!" ][]
Theabovecodewillerror,sincenomatchingcasewillbefound.
![Page 257: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/257.jpg)
NetLogoCsvExtension
Commonusecasesandexamples
Readafileallatonce
Justusecsv:from-file "/path/to/myfile.csv"!Seefrom-fileformoreinformation.
Readafileonelineatatime
Forreallybigfiles,youmaynotwanttostoretheentirefileinmemory,butratherjustprocessitalineatatime.Forinstance,ifyouwanttosumeachofthecolumnsofanumericCSVfile,youcando:
to-report sum-columns [ file ] file-open file set result csv:from-row file-read-line while [ not file-at-end? ] [ let row csv:from-row file-read-line set result (map [?1 + ?2] result row) ] file-close report resultend
Youcanalsousethistechniqueto…
Readafileonelinepertick
Here’sanexamplemodelthatreadsinafileonelinepertick:
globals [ data ]
to setup clear-all file-close-all % Close any files open from last run file-open "data.csv" % other setup goes here reset-ticksend
to go if file-at-end? [ stop ] set data csv:from-row file-read-line % model update goes here tickend
Writeafile
Justusecsv:to-file "/path/to/myfile.csv" my-data!Seeto-fileformoreinformation.
Primitives
FormattingNetLogodataasCSV
csv:to-rowcsv:to-stringcsv:to-file
ParsingCSVinputtoNetLogodata
csv:from-rowcsv:from-stringcsv:from-file
csv:from-row
csv:from-rowstringcsv:from-rowstringdelimiter
![Page 258: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/258.jpg)
ParsesthegivenstringasthoughitwerearowfromaCSVfileandreturnsitasalistofvalues.Forexample:
observer> show csv:from-row "one,two,three"observer: ["one" "two" "three"]
Quotescanbeusedwhenitemscontaincommas:
observer> show csv:from-row "there's,a,comma,\"in,here\""observer: ["there's" "a" "comma" "in,here"]
Youcanputtwoquotesinarowtoputanactualquoteinanentry.Iftheentryisnotquoted,youcanjustuseonequote:
observer> foreach (csv:from-row "he said \"hi there\",\"afterwards, she said \"\"hello\"\"\"") printhe said "hi there"afterwards, she said "hello"
Number-like-entrieswillbeparsedasnumbers:
observer> show csv:from-row "1,-2.5,1e3"observer: [1 -2.5 1000]
trueandfalsewithanycapitalizationwillbeparsedasbooleans:
observer> show csv:from-row "true,TRUE,False,falsE"observer: [true true false false]
Touseadifferentdelimiter,youcanspecifyasecond,optionalargument.Onlysinglecharacterdelimitersaresupported:
observer> show (csv:from-row "1;2;3" ";")observer: [1 2 3]
Differenttypesofvaluescanbemixedfreely:
observer> show csv:from-row "one,2,true"observer: ["one" 2 true]
csv:from-string
csv:from-stringstringcsv:from-stringstringdelimiter
ParsesastringrepresentationofoneormoreCSVrowsandreturnsitasalistoflistsofvalues.Forexample:
observer> show csv:from-string "1,two,3\nfour,5,true"observer: [[1 "two" 3] ["four" 5 true]]
csv:from-file
csv:from-filecsv-filecsv:from-filecsv-filedelimiter
ParsesanentireCSVfiletoalistoflistsofvalues.Forexample,ifwehaveafileexample.csvthatcontains:
1,2,34,5,67,8,910,11,12
Then,weget:
![Page 259: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/259.jpg)
observer> show csv:from-file "example.csv"observer: [[1 2 3] [4 5 6] [7 8 9] [10 11 12]]
Theparserdoesn’tcareiftherowshavedifferentnumbersofitemsonthem.Thenumberofitemsintherowslistwillalwaysbe<number of delimiters> + 1 ,thoughblanklinesareskipped.Thismakeshandlingfileswithheadersquiteeasy.Forinstance,ifwehaveheader.csvthatcontains:
My Data2/1/2015
Parameters:start,stop,resolution,population,birth?0,4,1,100,true
Data:time,x,y0,0,01,1,12,4,83,9,27
Thisgives:
observer> foreach csv:from-file "header.csv" showobserver: ["My Data"]observer: ["2/1/2015"]observer: ["Parameters:"]observer: ["start" "stop" "resolution" "population" "birth?"]observer: [0 4 1 100 true]observer: ["Data:"]observer: ["time" "x" "y"]observer: [0 0 0]observer: [1 1 1]observer: [2 4 8]observer: [3 9 27]
csv:to-row
csv:to-rowlistcsv:to-rowlistdelimiter
ReportsthegivenlistasaCSVrow.Forexample:
observer> show csv:to-row ["one" 2 true]observer: "one,2,true"
csv:to-string
csv:to-stringlistcsv:to-stringlistdelimiter
ReportsthegivenlistoflistsasaCSVstring.Forexample:
observer> show csv:to-string [[1 "two" 3] [4 5]]observer: "1,two,3\n4,5"
csv:to-file
csv:to-filecsv-filelistcsv:to-filecsv-filelistdelimiter
WritesthegivenlistofliststoanewCSVfile.Forexample:
observer> csv:to-file "myfile.csv" [[1 "two" 3] [4 5]]
willresultinafilemyfile.csvcontaining:
![Page 260: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/260.jpg)
1,two,34,5
![Page 261: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/261.jpg)
NetLogoGisExtension
Using
ThisextensionaddsGIS(GeographicInformationSystems)supporttoNetLogo.ItprovidestheabilitytoloadvectorGISdata(points,lines,andpolygons),andrasterGISdata(grids)intoyourmodel.
TheextensionsupportsvectordataintheformofESRIshapefiles.Theshapefile(.shp)formatisthemostcommonformatforstoringandexchangingvectorGISdata.TheextensionsupportsrasterdataintheformofESRIASCIIGridfiles.TheASCIIgridfile(.ascor.grd)isnotascommonastheshapefile,butissupportedasaninterchangeformatbymostGISplatforms.
Howtouse
Ingeneral,youfirstdefineatransformationbetweenGISdataspaceandNetLogospace,thenloaddatasetsandperformvariousoperationsonthem.TheeasiestwaytodefineatransformationbetweenGISspaceandNetLogospaceistotaketheunionofthe“envelopes”orboundingrectanglesofallofyourdatasetsinGISspaceandmapthatdirectlytotheboundsoftheNetLogoworld.SeeGISGeneralExamplesforanexampleofthistechnique.
YoumayalsooptionallydefineaprojectionfortheGISspace,inwhichcasedatasetswillbere-projectedtomatchthatprojectionastheyareloaded,aslongaseachofyourdatafileshasanassociated.prjfilethatdescribestheprojectionorgeographiccoordinatesystemofthedata.Ifnoassociated.prjfileisfound,theextensionwillassumethatthedatasetalreadyusesthecurrentprojection,regardlessofwhatthatprojectionis.
Oncethecoordinatesystemisdefined,youcanloaddatasetsusinggis:load-dataset.ThisprimitivereportseitheraVectorDatasetoraRasterDataset,dependingonwhattypeoffileyoupassit.
AVectorDatasetconsistsofacollectionofVectorFeatures,eachoneofwhichisapoint,line,orpolygon,alongwithasetofpropertyvalues.AsingleVectorDatasetmaycontainonlyoneofthethreepossibletypesoffeatures.
ThereareseveralthingsyoucandowithaVectorDataset:askitforthenamesofthepropertiesofitsfeatures,askitforits“envelope”(boundingrectangle),askforalistofallVectorFeaturesinthedataset,searchforasingleVectorFeatureorlistofVectorFeatureswhosevalueforaparticularpropertyislessthanorgreaterthanaparticularvalue,orlieswithinagivenrange,ormatchesagivenstringusingwildcardmatching(“*”,whichmatchesanynumberofoccurrencesofanycharacters).IftheVectorFeaturesarepolygons,youcanalsoapplythevaluesofaparticularpropertyofthedataset’sfeaturestoagivenpatchvariable.
TherearealsoseveralthingsyoucandowithaVectorFeaturefromaVectorDataset:askitforalistofvertexlists,askitforapropertyvaluebyname,askitforitscentroid(centerofgravity),andaskforasubsetofagivenagentsetwhoseagentsintersectthegivenVectorFeature.Forpointdata,eachvertexlistwillbeaone-elementlist.Forlinedata,eachvertexlistwillrepresenttheverticesofalinethatmakesupthatfeature.Forpolygondata,eachvertexlistwillrepresentone“ring”ofthepolygon,andthefirstandlastvertexofthelistwillbethesame.ThevertexlistsaremadeupofvaluesoftypeVertex,andthecentroidwillbeavalueoftypeVertexaswell.
![Page 262: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/262.jpg)
ThereareanumberofoperationsdefinedforRasterDatasetsaswell.Mostlytheseinvolvesamplingthevaluesinthedataset,orre-samplingarastertoadifferentresolution.Youcanalsoapplyarastertoagivenpatchvariable,andconvolvearasterusinganarbitraryconvolutionmatrix.
CodeExample:GISGeneralExampleshasgeneralexamplesofhowtousetheextension
CodeExample:GISGradientExampleisamoreadvancedexampleofrasterdatasetanalysis.
KnownIssues
ValuesoftypeRasterDataset,VectorDataset,VectorFeature,andVertexarenothandledproperlybyexport-worldandimport-world.Tosavedatasets,youmustusethegis:store-datasetprimitive.
Thereiscurrentlynowaytodistinguishpositive-area“shell”polygonsfromnegative-area“hole”polygons,ortodeterminewhichholesareassociatedwithwhichshells.
Credits
TheprimarydeveloperoftheGISextensionwasEricRussell.
TheGISextensionmakesuseofseveralopen-sourcesoftwarelibraries.Forcopyrightandlicenseinformationonthose,seethecopyrightsectionofthemanual.TheextensionalsocontainselementsborrowedfromMyWorldGIS.
ThisdocumentationandtheexampleNetLogomodelsareinthepublicdomain.TheGISextensionitselfisfreeandopensourcesoftware.SeetheREADME.mdfileintheextension/gisdirectoryfordetails.
WewouldlovetohearyoursuggestionsonhowtoimprovetheGISextension,orjustaboutwhatyou’reusingitfor.PostquestionsandcommentsattheNetLogoUsersGroup,orwritedirectlytoEricRussellandtheNetLogoteamatccl-gis@ccl.northwestern.edu
Primitives
RasterDatasetPrimitives
gis:width-ofgis:height-ofgis:raster-valuegis:set-raster-valuegis:minimum-ofgis:maximum-ofgis:sampling-method-ofgis:set-sampling-methodgis:raster-samplegis:raster-world-envelopegis:create-rastergis:resamplegis:convolvegis:apply-raster
DatasetPrimitives
gis:load-datasetgis:store-datasetgis:type-ofgis:patch-datasetgis:turtle-datasetgis:link-dataset
VectorDatasetPrimitives
gis:shape-type-ofgis:property-namesgis:feature-list-ofgis:vertex-lists-of
![Page 263: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/263.jpg)
gis:centroid-ofgis:location-ofgis:property-valuegis:find-featuresgis:find-one-featuregis:find-less-thangis:find-greater-thangis:find-rangegis:property-minimumgis:property-maximumgis:apply-coveragegis:coverage-minimum-thresholdgis:set-coverage-minimum-thresholdgis:coverage-maximum-thresholdgis:set-coverage-maximum-thresholdgis:intersects?gis:contains?gis:contained-by?gis:have-relationship?gis:relationship-ofgis:intersecting
CoordinateSystemPrimitives
gis:set-transformationgis:set-transformation-dsgis:set-world-envelopegis:set-world-envelope-dsgis:world-envelopegis:envelope-ofgis:envelope-union-ofgis:load-coordinate-systemgis:set-coordinate-system
DrawingPrimitives
gis:drawing-colorgis:set-drawing-colorgis:drawgis:fillgis:paintgis:import-wms-drawing
gis:set-transformation
gis:set-transformationgis-envelopenetlogo-envelope
DefinesamappingbetweenGIScoordinatesandNetLogocoordinates.Thegis-envelopeandnetlogo-envelopeparametersmusteachbefour-elementlistsconsistingof:
[minimum-x maximum-x minimum-y maximum-y]
Thescaleofthetransformationwillbeequaltotheminimumofthescalenecessarytomakethemappingbetweentherangesofxvaluesandthescalenecessarytomakethemappingbetweentherangesofyvalues.TheGISspacewillbecenteredinNetLogospace.
Forexample,thefollowingtwolistswouldmapallofgeographic(latitudeandlongitude)spaceindegreestoNetLogoworldspace,regardlessofthecurrentdimensionsoftheNetLogoworld:
(list -180 180 -90 90)(list min-pxcor max-pxcor min-pycor max-pycor)
However,ifyou’resettingtheenvelopeoftheNetLogoworld,youshouldprobablybeusingset-world-envelope.
gis:set-transformation-ds
gis:set-transformation-dsgis-envelopenetlogo-envelope
Doesthesamethingasset-transformationabove,exceptthatitallowsthescaleformappingtherangeofxvaluestobedifferentthanthescaleforyvalues.The“-ds”ontheendstandsfor“differentscales”.UsingdifferentscaleswillcausedistortionoftheshapeofGISfeatures,andsoitisgenerallynotrecommended,butitmaybeusefulforsomemodels.
![Page 264: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/264.jpg)
Hereisanexampleofthedifferencebetweenset-transformationandset-transformation-ds:
Using[set-transformation](#gisset-transformation),the
scalealongthexandyaxisisthesame,preservingtheround
shapeoftheEarthinthisOrthographicprojection.
Using[set-transformation-ds](#gisset-transformation-ds),thescalealongthexaxisisstretchedsothatthe
earthcoverstheentireNetLogoView,whichinthiscasedistortstheshape
oftheEarth.
gis:set-world-envelope
gis:set-world-envelopegis-envelope
AshorthandforsettingthetransformationbymappingtheenvelopeoftheNetLogoworldtothegivenenvelopeinGISspace,whilekeepingthescalesalongthexandyaxisthesame.Itisequivalentto:
set-transformation gis-envelope (list min-pxcor max-pxcor min-pycor max-pycor)
Thisprimitiveissuppliedbecausemostofthetimeyou’llwanttosettheenvelopeoftheentireNetLogoworld,ratherthanjustapartofit.
gis:set-world-envelope-ds
gis:set-world-envelope-dsgis-envelope
AshorthandforsettingthetransformationbymappingtheenvelopeoftheNetLogoworldtothegivenenvelopeinGISspace,usingdifferentscalesalongthexandyaxisifnecessary.Itisequivalentto:
set-transformation-ds gis-envelope (list min-pxcor max-pxcor min-pycor max-pycor)
Seethepicturesaboveforthedifferencebetweenusingequalscalesforxandycoordinatesandusingdifferentscales.
gis:world-envelope
gis:world-envelope
Reportstheenvelope(boundingrectangle)oftheNetLogoworld,transformedintoGISspace.Anenvelopeconsistsofafour-elementlistoftheform:
![Page 265: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/265.jpg)
[minimum-x maximum-x minimum-y maximum-y]
gis:envelope-of
gis:envelope-ofthing
Reportstheenvelope(boundingrectangle)ofthinginGIScoordinates.ThethingmaybeanAgent,anAgentSet,aRasterDataset,aVectorDataset,oraVectorFeature.Anenvelopeconsistsofafour-elementlistoftheform:
[minimum-x maximum-x minimum-y maximum-y]
gis:envelope-union-of
gis:envelope-union-ofenvelope1envelope2gis:envelope-union-ofenvelope1...
Reportsanenvelope(boundingrectangle)thatentirelycontainsthegivenenvelopes.Anenvelopeconsistsofafour-elementlistoftheform
[minimum-x maximum-x minimum-y maximum-y]
Noassumptionismadeaboutthecoordinatesystemofthearguments,thoughiftheyarenotinthesamecoordinatesystem,resultswillbeunpredictable.
gis:load-coordinate-system
gis:load-coordinate-systemfile
Loadsanewglobalprojectionusedforprojectingorre-projectingGISdataasitisloadedfromafile.ThefilemustcontainavalidWell-KnownText(WKT)projectiondescription.
WKTprojectionfilesarefrequentlydistributedalongsideGISdatafiles,andusuallyhavea“.prj”filenameextension.
Relativepathsareresolvedrelativetothelocationofthecurrentmodel,ortheuser’shomedirectoryifthecurrentmodelhasn’tbeensavedyet.
TheGISextensiondoesnotsupportallWKTcoordinatesystemsandprojections.Onlygeographic("GEOGCS")andprojected("PROJCS")coordinatesystemsaresupported.Forprojectedcoordinatesystems,onlythefollowingprojectionsaresupported:
Albers_Conic_Equal_AreaLambert_Conformal_Conic_2SPPolyconicLambert_Azimuthal_Equal_AreaMercator_1SPRobinsonAzimuthal_EquidistantMillerStereographic
![Page 266: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/266.jpg)
Cylindrical_Equal_AreaOblique_MercatorTransverse_MercatorEquidistant_Conichotine_oblique_mercatorGnomonicOrthographic
Seeremotesensing.orgforacompletelistofWKTprojectionsandtheirparameters.
gis:set-coordinate-system
gis:set-coordinate-systemsystem
Setstheglobalprojectionusedforprojectingorre-projectingGISdataasitisloaded.ThesystemmustbeeitherastringinWell-KnownText(WKT)format,oraNetLogolistthatconsistsofWKTconvertedtoalistbymovingeachkeywordinsideitsassociatedbracketsandputtingquotesaroundit.Thelatterispreferredbecauseitmakesthecodemuchmorereadable.
ThesamelimitationsonWKTsupportapplyasdescribedaboveinthedocumentationforload-coordinate-system
gis:load-dataset
gis:load-datasetfile
Loadsthegivendatafile,re-projectingthedataasnecessaryifaglobalprojectionisdefinedandifthedatafileitselfhasanassociated.prjfile,thenreportstheresultingdataset.
Ifno“.prj”fileispresent,thenload-datasetassumesthattheprojectionofthedatabeingloadedisthesameasthecurrentglobalcoordinatesystem.
Relativepathsareresolvedrelativetothelocationofthecurrentmodel,ortheuser’shomedirectoryifthecurrentmodelhasn’tbeensavedyet.
Currently,twotypesofdatafilearesupported:
“.shp”(ESRIshapefile):containsvectordata,consistingofpoints,lines,orpolygons.Whenthetargetfileisashapefile,load-datasetreportsaVectorDataset.“.asc”or“.grd”(ESRIASCIIgrid):containsrasterdata,consistingofagridofvalues.WhenthetargetfileisanASCIIgridfile,load-datasetreportsaRasterDataset.
gis:store-dataset
gis:store-datasetdatasetfile
Savesthegivendatasettothegivenfile.Ifthenameofthefiledoesnothavetheproperfileextension,theextensionwillbeautomaticallyappendedtothename.Relativepathsareresolvedrelativetothelocationofthecurrentmodel,ortheuser’shomedirectoryifthecurrentmodelhasn’tbeensavedyet.
Currently,thisprimitiveonlyworksforRasterDatasets,anditcanonlysavethosedatasets
![Page 267: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/267.jpg)
asESRIASCIIgridfiles.
gis:type-of
gis:type-ofdataset
ReportsthetypeofthegivenGISdataset:either“VECTOR”or“RASTER”
gis:patch-dataset
gis:patch-datasetpatch-variable
ReportsanewrasterwhosecellscorresponddirectlytoNetLogopatches,andwhosecellvaluesconsistofthevaluesofthegivenpatchvariable.Thisprimitiveisbasicallytheinverseofapply-raster;apply-rastercopiesvaluesfromarasterdatasettoapatchvariable,whilethisprimitivecopiesvaluesfromapatchvariabletoarasterdataset.
gis:turtle-dataset
gis:turtle-datasetturtle-set
Reportsanew,pointVectorDatasetbuiltfromtheturtlesinthegivenagentset.Thepointsarelocatedatlocationsoftheturtles,translatedfromNetLogospaceintoGISspaceusingthecurrentcoordinatetransformation.Andthedataset’spropertiesconsistofalloftheturtlevariablescommontoeveryturtleintheagentset.
gis:link-dataset
gis:link-datasetlink-set
Reportsanew,lineVectorDatasetbuiltfromthelinksinthegivenagentset.Theendpointsofeachlineareatthelocationoftheturtlesconnectedbyeachlink,translatedfromNetLogospaceintoGISspaceusingthecurrentcoordinatetransformation.Andthedataset’spropertiesconsistofallofthelinkvariablescommontoeverylinkintheagentset.
gis:shape-type-of
gis:shape-type-ofVectorDataset
Reportstheshapetypeofthegivendataset.Thepossibleoutputvaluesare“POINT”,“LINE”,and“POLYGON”.
gis:property-names
gis:property-namesVectorDataset
ReportsalistofstringswhereeachstringisthenameofapropertypossessedbyeachVectorFeatureinthegivenVectorDataset,suitableforuseingis:property-value.
![Page 268: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/268.jpg)
gis:feature-list-of
gis:feature-list-ofVectorDataset
ReportsalistofallVectorFeaturesinthegivendataset.
gis:vertex-lists-of
gis:vertex-lists-ofVectorFeature
ReportsalistoflistsofVertexvalues.Forpointdatasets,eachvertexlistwillcontainexactlyonevertex:thelocationofapoint.Forlinedatasets,eachvertexlistwillcontainatleasttwopoints,andwillrepresenta“polyline”,connectingeachadjacentpairofverticesinthelist.Forpolygondatasets,eachvertexlistwillcontainatleastthreepoints,representingapolygonconnectingeachvertex,andthefirstandlastverticesinthelistwillbethesame.
gis:centroid-of
gis:centroid-ofVectorFeature
ReportsasingleVertexrepresentingthecentroid(centerofgravity)ofthegivenfeature.Forpointdatasets,thecentroidisdefinedastheaveragelocationofallpointsinthefeature.Forlinedatasets,thecentroidisdefinedastheaverageofthelocationsofthemidpointsofalllinesegmentsinthefeature,weightedbysegmentlength.Forpolygondatasets,thecentroidisdefinedastheweightedsumofthecentroidsofadecompositionoftheareainto(possiblyoverlapping)triangles.SeethisFAQformoredetailsonthepolygoncentroidalgorithm.
gis:location-of
gis:location-ofVertex
Reportsatwo-elementlistcontainingthexandyvalues(inthatorder)ofthegivenvertextranslatedintoNetLogoworldspaceusingthecurrenttransformation,oranemptylistifthegivenvertexliesoutsidetheNetLogoworld.
gis:property-value
gis:property-valueVectorFeatureproperty-name
ReportsthevalueofthepropertywiththegivennameforthegivenVectorDataset.Thereportedvaluemaybeanumber,astring,orabooleanvalue,dependingonthetypeofthefieldintheunderlyingdatafile.
Forshapefiles,valuesfromdBaseCHARACTERandDATEfieldsarereturnedasstrings,valuesfromNUMBERandFLOATfieldsarereturnedasnumbers,andvaluesfromLOGICALfieldsarereturnedasbooleanvalues.MEMOfieldsarenotsupported.DATEvaluesareconvertedtostringsusingISO8601format(YYYY-MM-DD).
gis:find-features
![Page 269: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/269.jpg)
gis:find-featuresVectorDatasetproperty-namespecified-value
ReportsalistofallVectorFeaturesinthegivendatasetwhosevalueforthepropertyproperty-namematchesspecified-value(astring).Valuecomparisonisnotcasesensitive,andthewildcardcharacter“*”willmatchanynumberofoccurrences(includingzero)ofanycharacter.
gis:find-one-feature
gis:find-one-featureVectorDatasetproperty-namespecified-value
ReportsthefirstVectorFeatureinthedatasetwhosevalueforthepropertyproperty-namematchesthegivenstring.Valuecomparisonisnotcasesensitive,andthewildcardcharacter“*”willmatchanynumberofoccurrences(includingzero)ofanycharacter.Featuresaresearchedintheorderthattheyappearinthedatafilethatwasthesourceofthedataset,andsearchingstopsassoonasamatchisfound.ReportsnobodyifnomatchingVectorFeatureisfound.
gis:find-less-than
gis:find-less-thanVectorDatasetproperty-namevalue
ReportsalistofallVectorFeaturesinthegivendatasetwhosevalueforthepropertyproperty-nameislessthanthegivenvalue.Stringvaluesarecomparedusingcase-sensitivelexicographicorderasdefinedintheJavaDocumentation.Usingastringvalueforanumericpropertyoranumericvalueforastringpropertywillcauseanerror.
gis:find-greater-than
gis:find-greater-thanVectorDatasetproperty-namevalue
ReportsalistofallVectorFeaturesinthegivendatasetwhosevalueforthepropertyproperty-nameisgreaterthanthegivenvalue.Stringvaluesarecomparedusingcase-sensitivelexicographicorderasdefinedintheJavaDocumentation.Usingastringvalueforanumericpropertyoranumericvalueforastringpropertywillcauseanerror.
gis:find-range
gis:find-rangeVectorDatasetproperty-nameminimum-valuemaximum-value
ReportsalistofallVectorFeaturesinthegivendatasetwhosevalueforthepropertyproperty-nameisstrictlygreaterthanminimum-valueandstrictlylessthanmaximum-value.Stringvaluesarecomparedusingcase-sensitivelexicographicorderasdefinedintheJavaDocumentation.Usingastringvalueforanumericpropertyoranumericvalueforastringpropertywillcauseanerror.
gis:property-minimum
gis:property-minimumVectorDatasetproperty-name
ReportsthesmallestvalueforthegivenpropertyoveralloftheVectorFeaturesinthe
![Page 270: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/270.jpg)
givendataset.Stringvaluesarecomparedusingcase-sensitivelexicographicorderasdefinedintheJavaDocumentation.
gis:property-maximum
gis:property-maximumVectorDatasetproperty-name
ReportsthelargestvalueforthegivenpropertyoveralloftheVectorFeaturesinthegivendataset.Stringvaluesarecomparedusingcase-sensitivelexicographicorderasdefinedintheJavaDocumentation.
gis:apply-coverage
gis:apply-coverageVectorDatasetproperty-namepatch-variable
CopiesvaluesfromthegivenpropertyoftheVectorDataset’sfeaturestothegivenpatchvariable.Thedatasetmustbeapolygondataset;pointsandlinesarenotsupported.
Foreachpatch,itfindsallVectorFeaturesthatintersectthatpatch.Then,ifthepropertyisastringproperty,itcomputesthemajorityvaluebycomputingthetotalareaofthepatchcoveredbyVectorFeatureshavingeachpossiblevalueoftheproperty,thenreturningthevaluewhichrepresentsthelargestproportionofthepatcharea.Ifthepropertyisanumericproperty,itcomputesaweightedaverageofpropertyvaluesfromallVectorFeatureswhichintersectthepatch,weightedbytheproportionofthepatchareatheycover.
Therearetwoexceptionstothisdefaultbehavior:
Ifapercentageofapatches’areagreaterthanthecoverage-maximum-thresholdiscoveredbyasingleVectorFeature,thenthepropertyvaluefromthatVectorFeatureiscopieddirectly.IfmorethanoneVectorFeaturecoversapercentageofareagreaterthanthethreshold,onlythefirstwillbeused.
Ifthetotalpercentageofapatches’areacoveredbyVectorFeaturesislessthanthecoverage-minimum-threshold,thetargetpatchvariableissettoNotANumber.
Bydefault,theminimumthresholdis10%andthemaximumthresholdis33%.Thesevaluesmaybemodifiedusingthefourprimitivesthatfollow.
gis:coverage-minimum-threshold
gis:coverage-minimum-threshold
Reportsthecurrentcoverageminimumthresholdusedbygis:apply-coverage.
gis:set-coverage-minimum-threshold
gis:set-coverage-minimum-thresholdnew-threshold
Setsthecurrentcoverageminimumthresholdtobeusedbygis:apply-coverage.
gis:coverage-maximum-threshold
![Page 271: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/271.jpg)
gis:coverage-maximum-threshold
Reportsthecurrentcoveragemaximumthresholdusedbygis:apply-coverage.
gis:set-coverage-maximum-threshold
gis:set-coverage-maximum-thresholdnew-threshold
Setsthecurrentcoveragemaximumthresholdtobeusedbygis:apply-coverage.
gis:intersects?
gis:intersects?xy
Reportstrueifthegivenobjects’spatialrepresentationsshareatleastonepointincommon,andfalseotherwise.Theobjectsxandymaybeanyoneof:
aVectorDataset,inwhichcasetheobject’sspatialrepresentationistheunionofallthepoints,lines,orpolygonsthedatasetcontains.aVectorFeature,inwhichcasetheobject’sspatialrepresentationisdefinedbythepoint,line,orpolygonthefeaturecontains.Aturtle,inwhichcasethespatialrepresentationisapoint.Alink,whosespatialrepresentationisalinesegmentconnectingthetwopointsrepresentedbytheturtlesthelinkisconnecting.Apatch,whosespatialrepresentationisarectangularpolygon.Anagentset,whosespatialrepresentationistheunionoftherepresentationsofalloftheagentsitcontains.Alistcontainingofanyoftheitemslistedhere,includinganotherlist.Thespatialrepresentationofsuchalististheunionofthespatialrepresentationsofitscontents.
gis:contains?
gis:contains?xy
Reportstrueifeverypointofy’sspatialrepresentationisalsoapartofx’sspatialrepresentation.Notethatthismeansthatpolygonsdocontaintheirboundaries.Theobjectsxandymaybeanyoneof
aVectorDataset,inwhichcasetheobject’sspatialrepresentationistheunionofallthepoints,lines,orpolygonsthedatasetcontains.aVectorFeature,inwhichcasetheobject’sspatialrepresentationisdefinedbythepoint,line,orpolygonthefeaturecontains.Aturtle,inwhichcasethespatialrepresentationisapoint.Alink,whosespatialrepresentationisalinesegmentconnectingthetwopointsrepresentedbytheturtlesthelinkisconnecting.Apatch,whosespatialrepresentationisarectangularpolygon.Anagentset,whosespatialrepresentationistheunionoftherepresentationsofalloftheagentsitcontains.Alistcontainingofanyoftheitemslistedhere,includinganotherlist.Thespatialrepresentationofsuchalististheunionofthespatialrepresentationsofitscontents.
gis:contained-by?
![Page 272: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/272.jpg)
gis:contained-by?xy
Reportstrueifeverypointofx’sspatialrepresentationisalsoapartofy’sspatialrepresentation.Theobjectsxandymaybeanyoneof:
aVectorDataset,inwhichcasetheobject’sspatialrepresentationistheunionofallthepoints,lines,orpolygonsthedatasetcontains.aVectorFeature,inwhichcasetheobject’sspatialrepresentationisdefinedbythepoint,line,orpolygonthefeaturecontains.Aturtle,inwhichcasethespatialrepresentationisapoint.Alink,whosespatialrepresentationisalinesegmentconnectingthetwopointsrepresentedbytheturtlesthelinkisconnecting.Apatch,whosespatialrepresentationisarectangularpolygon.Anagentset,whosespatialrepresentationistheunionoftherepresentationsofalloftheagentsitcontains.Alistcontainingofanyoftheitemslistedhere,includinganotherlist.Thespatialrepresentationofsuchalististheunionofthespatialrepresentationsofitscontents.
gis:have-relationship?
gis:have-relationship?xy
Reportstrueifthespatialrepresentationsofthetwoobjectshavethegivenspatialrelationship,andfalseotherwise.ThespatialrelationshipisspecifiedusingaDimensionallyExtendedNine-IntersectionModel(DE-9IM)matrix.Thematrixconsistsof9elements,eachofwhichspecifiestherequiredrelationshipbetweenthetwoobjects’interiorspace,boundaryspace,orexteriorspace.Theelementsmusthaveoneofsixpossiblevalues:
“T”,meaningthespacesmustintersectinsomeway“F”,meaningthespacesmustnotintersectinanyway“0”,meaningthedimensionofthespaces’intersectionmustbezero(i.e.,itmustbeapointornon-emptysetofpoints).“1”,meaningthedimensionofthespaces’intersectionmustbeone(i.e.,itmustbealineornon-emptysetoflinesegments).“2”,meaningthedimensionofthespaces’intersectionmustbetwo(i.e.,itmustbeapolygonorsetofpolygonswhoseareaisgreaterthanzero).“*”,meaningthatthetwospacesmayhaveanyrelationship.
Forexample,thismatrix:
xInterior Boundary Exterior
yInterior T * *
Boundary * * *Exterior F F *
wouldreturntrueifandonlyifsomepartofobjectx’sinteriorliesinsideobjecty’sinterior,andnopartofobjectx’sinteriororboundaryintersectsobjecty’sexterior.Thisisessentiallyamorerestrictiveformofthecontains?primitive;oneinwhichpolygonsarenotconsideredtocontaintheirboundaries.
Thematrixisgiventothehave-relationship?primitiveasastring,whoseelementsaregiveninthefollowingorder:
![Page 273: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/273.jpg)
1 2 34 5 67 8 9
Sotousetheexamplematrixabove,youwouldwrite:
gis:have-relationship? x y "T*****FF*"
AmuchmoredetailedandformaldescriptionoftheDE-9IMmatrixandtheassociatedpoint-settheorycanbefoundintheOpenGISSimpleFeaturesSpecificationforSQL.
Theobjectsxandymaybeanyoneof:
aVectorDataset,inwhichcasetheobject’sspatialrepresentationistheunionofallthepoints,lines,orpolygonsthedatasetcontains.aVectorFeature,inwhichcasetheobject’sspatialrepresentationisdefinedbythepoint,line,orpolygonthefeaturecontains.Aturtle,inwhichcasethespatialrepresentationisapoint.Alink,whosespatialrepresentationisalinesegmentconnectingthetwopointsrepresentedbytheturtlesthelinkisconnecting.Apatch,whosespatialrepresentationisarectangularpolygon.Anagentset,whosespatialrepresentationistheunionoftherepresentationsofalloftheagentsitcontains.Alistcontainingofanyoftheitemslistedhere,includinganotherlist.Thespatialrepresentationofsuchalististheunionofthespatialrepresentationsofitscontents.
gis:relationship-of
gis:relationship-ofxy
ReportstheDimensionallyExtendedNine-IntersectionModel(DE-9IM)matrixthatdescribesthespatialrelationshipofthetwoobjects.Thematrixconsistsof9elements,eachofwhichdescribestherelationshipbetweenthetwoobjects’interiorspace,boundaryspace,orexteriorspace.Eachelementwilldescribethedimensionoftheintersectionoftwospaces,meaningthatitmayhaveoneoffourpossiblevalues:
“-1”,meaningthespacesdonotintersect“0”,meaningthedimensionofthespaces’intersectioniszero(i.e.,theyintersectatapointorsetofpoints).“1”,meaningthedimensionofthespaces’intersectionisone(i.e.,theyintersectalongoneormorelines).“2”,meaningthedimensionofthespaces’intersectionistwo(i.e.,theirintersectionisanon-emptypolygon).
Forexample,thetwopolygonsxandyshownhere:
![Page 274: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/274.jpg)
havethefollowingDE-9IMmatrix:
xInterior Boundary Exterior
yInterior 2 1 2
Boundary 1 0 1Exterior 2 1 2
Whichwouldbereportedbytherelationship-ofprimitiveasthestring“212101212”.
AmuchmoredetailedandformaldescriptionoftheDE-9IMmatrixandtheassociatedpoint-settheorycanbefoundintheOpenGISSimpleFeaturesSpecificationforSQL.
Theobjectsxandymaybeanyoneof:
aVectorDataset,inwhichcasetheobject’sspatialrepresentationistheunionofallthepoints,lines,orpolygonsthedatasetcontains.aVectorFeature,inwhichcasetheobject’sspatialrepresentationisdefinedbythepoint,line,orpolygonthefeaturecontains.Aturtle,inwhichcasethespatialrepresentationisapoint.Alink,whosespatialrepresentationisalinesegmentconnectingthetwopointsrepresentedbytheturtlesthelinkisconnecting.Apatch,whosespatialrepresentationisarectangularpolygon.Anagentset,whosespatialrepresentationistheunionoftherepresentationsofalloftheagentsitcontains.Alistcontainingofanyoftheitemslistedhere,includinganotherlist.Thespatialrepresentationofsuchalististheunionofthespatialrepresentationsofitscontents.
gis:intersecting
patch-setgis:intersectingdata
ReportsanewagentsetcontainingonlythosemembersofthegivenagentsetwhichintersectgivenGISdata,whichmaybeanyoneof:aVectorDataset,aVectorFeature,anAgent,anAgentSet,oralistcontaininganyoftheabove.
gis:width-of
gis:width-ofRasterDataset
Reportsthenumberofcolumnsinthedataset.Notethatthisisthenumberofcellsfromlefttoright,notthewidthofthedatasetinGISspace.
![Page 275: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/275.jpg)
gis:height-of
gis:height-ofRasterDataset
Reportsthenumberofrowsinthedataset.Notethatthisisthenumberofcellsfromtoptobottom,nottheheightofthedatasetinGISspace.
gis:raster-value
gis:raster-valueRasterDatasetxy
Reportsthevalueofthegivenrasterdatasetinthegivencell.Cellcoordinatesarenumberedfromlefttoright,andfromtoptobottom,beginningwithzero.Sotheupperleftcellis(0,0),andthebottomrightcellis(gis:width-of dataset-1,gis:height-of dataset-1).
gis:set-raster-value
gis:set-raster-valueRasterDatasetxyvalue
Setsthevalueofthegivenrasterdatasetatthegivencelltoanewvalue.Cellcoordinatesarenumberedfromlefttoright,andfromtoptobottom,beginningwithzero.Sotheupperleftcellis(0,0),andthebottomrightcellis(gis:width-of dataset-1,gis:height-ofdataset-1).
gis:minimum-of
gis:minimum-ofRasterDataset
Reportsthehighestvalueinthegivenrasterdataset.
gis:maximum-of
gis:maximum-ofRasterDataset
Reportsthelowestvalueinthegivenrasterdataset.
gis:sampling-method-of
gis:sampling-method-ofRasterDataset
Reportsthesamplingmethodusedtocomputethevalueofthegivenrasterdatasetatasinglepoint,oroveranareasmallerthanasinglerastercell.SamplingisperformedbytheGISextensionprimitivesraster-sample,resample,convolve,andapply-raster.Thesamplingmethodwillbeoneofthefollowing:
"NEAREST_NEIGHBOR":thevalueofthecellnearestthesamplinglocationisused."BILINEAR":thevalueofthefournearestcellsaresampledbylinearweighting,accordingtotheirproximitytothesamplingsite."BICUBIC":thevalueofthesixteennearestcellsaresampled,andtheirvaluesare
![Page 276: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/276.jpg)
combinedbyweightaccordingtoapiecewisecubicpolynomialrecommendedbyRifman(seeDigitalImageWarping,GeorgeWolberg,1990,pp129-131,IEEEComputerSocietyPress)."BICUBIC_2":thevalueissampledusingthesameprocedureandthesamepolynomialaswithBICUBICabove,butusingadifferentcoefficient.ThismethodmayproducesomewhatsharperresultsthanBICUBIC,butthatresultisdatadependent.
Formoreinformationonthesesamplingmethodsandonrastersamplingingeneral,seethiswikipediaarticle.
gis:set-sampling-method
gis:set-sampling-methodRasterDatasetsampling-method
Setsthesamplingmethodusedbythegivenrasterdatasetatasinglepoint,oroveranareasmallerthanasinglerastercell.SamplingisperformedbytheGISextensionprimitivesraster-sample,resample,convolve,andapply-raster.Thesamplingmethodmustbeoneofthefollowing:
"NEAREST_NEIGHBOR""BILINEAR""BICUBIC""BICUBIC_2"
Seesampling-method-ofaboveforamorespecificdescriptionofeachsamplingmethod.
gis:raster-sample
gis:raster-sampleRasterDatasetsample-location
Reportsthevalueofthegivenrasteroverthegivenlocation.Thelocationmaybeanyofthefollowing:
Alistoflength2,whichistakentorepresentapointinnetlogospace([xcor ycor])ofthesortreportedbylocation-ofVertex.Therasterdatasetissampledatthepointofthatlocation.Alistoflength4,whichistakentorepresentanenvelopeinGISspace,ofthesortreportedbyenvelope-of.Therasterdatasetissampledovertheareaofthatenvelope.Apatch,inwhichcasetherasterdatasetissampledovertheareaofthepatch.Aturtle,inwhichcasetherasterdatasetissampledatthelocationofthatturtle.AVertex,inwhichcasetherasterdatasetissampledatthelocationofthatVertex.
Iftherequestedlocationisoutsidetheareacoveredbytherasterdataset,thisprimitivereportsthespecialvaluerepresenting“notanumber”,whichisprintedbyNetLogoas“NaN”.Usingthespecial“notanumber”valueasanargumenttoprimitivesthatexpectanumbermaycauseanerror,butyoucantestthevaluereportedbythisprimitivetofilterout“notanumber”values.Avaluethatisnotanumberwillbeneitherlessthannorgreaterthananumbervalue,soyoucandetect“notanumber”valuesusingthefollowing:
let value gis:raster-sample dataset turtle 0; set color to blue if value is a number, red if value is "not a number"ifelse (value <= 0) or (value >= 0)[ set color blue ][ set color red ]
![Page 277: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/277.jpg)
Iftherequestedlocationisapoint,thesampleisalwayscomputedusingthemethodsetbyset-sampling-method.Iftherequestedlocationisanarea(i.e.,anenvelopeorpatch),thesampleiscomputedbytakingtheaverageofallrastercellscoveredbytherequestedarea.
gis:raster-world-envelope
gis:raster-world-envelopeRasterDatasetxy
ReportstheGISenvelopeneededtomatchtheboundariesofNetLogopatcheswiththeboundariesofcellsinthegivenrasterdataset.Thisenvelopecouldthenbeusedasanargumenttoset-transformation-ds.
TheremaybemorecellsinthedatasetthantherearepatchesintheNetLogoworld.Inthatcase,youwillneedtoselectasubsetofcellsinthedatasetbyspecifyingwhichcellinthedatasetyouwanttomatchwiththeupper-leftcorneroftheNetLogoworld.Cellsarenumberedfromlefttoright,andfromtoptobottom,beginningwithzero.Sotheupperleftcellis(0,0),andthebottomrightcellis(gis:width-of dataset-1,gis:height-of dataset-1).
gis:create-raster
gis:create-rasterwidthheightenvelope
Createsandreportsanew,emptyrasterdatasetwiththegivennumberofcolumnsandrows,coveringthegivenenvelope.
gis:resample
gis:resampleRasterDatasetenvelopewidthheight
ReportsanewdatasetthatconsistsofthegivenRasterDatasetresampledtocoverthegivenenvelopeandtocontainthegivennumberofcolumnsandrows.Ifthenewraster’scellsaresmallerthantheexistingraster’scells,theywillberesampledusingthemethodsetbyset-sampling-method.Ifthenewcellsarelargerthantheoriginalcells,theywillbesampledusingthe"NEAREST_NEIGHBOR"method.
gis:convolve
gis:convolveRasterDatasetkernel-rowskernel-columnskernelkey-columnkey-row
Reportsanewrasterwhosedataconsistsofthegivenrasterconvolvedwiththegivenkernel.
Aconvolutionisamathematicaloperationthatcomputeseachoutputcellbymultiplyingelementsofakernelwiththecellvaluessurroundingaparticularsourcecell.Akernelisamatrixofvalues,withoneparticularvaluedefinedasthe“keyelement”,thevaluethatiscenteredoverthesourcecellcorrespondingtothedestinationcellwhosevalueisbeingcomputed.
Thevaluesofthekernelmatrixaregivenasalist,whichenumeratestheelementsofthematrixfromlefttoright,toptobottom.Sotheelementsofa3-by-3matrixwouldbelisted
![Page 278: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/278.jpg)
inthefollowingorder:
1 2 34 5 67 8 9
Thekeyelementisspecifiedbycolumnandrowwithinthematrix.Columnsarenumberedfromlefttoright,beginningwithzero.Rowsarenumberedfromtoptobottom,alsobeginningwithzero.So,forexample,thekernelforthehorizontalSobeloperator,whichlookslikethis:
1 0 -1
2 0(key)
-2
1 0 -1
wouldbespecifiedasfollows:
let horizontal-gradient gis:convolve dataset 3 3 [1 0 -1 2 0 -2 1 0 -1] 1 1
gis:apply-raster
gis:apply-rasterRasterDatasetpatch-variable
Copiesvaluesfromthegivenrasterdatasettothegivenpatchvariable,resamplingtherasterasnecessarysothatitscellboundariesmatchupwithNetLogopatchboundaries.Thisresamplingisdoneasifusingresampleratherthanraster-sample,forthesakeofefficiency.However,patchesnotcoveredbytherasterareassignedvaluesof“notanumber”inthesamewaythatraster-samplereportsvaluesforlocationsoutsidetheraster.
gis:drawing-color
gis:drawing-color
ReportsthecolorusedbytheGISextensiontodrawvectorfeaturesintotheNetLogodrawinglayer.ColorcanberepresentedeitherasaNetLogocolor(asinglenumberbetweenzeroand140)oranRGBcolor(alistof3numbers).SeedetailsintheColorssectionoftheProgrammingGuide.
gis:set-drawing-color
gis:set-drawing-colorcolor
SetsthecolorusedbytheGISextensiontodrawvectorfeaturesintotheNetLogodrawinglayer.ColorcanberepresentedeitherasaNetLogocolor(asinglenumberbetweenzeroand140)oranRGBcolor(alistof3numbers).SeedetailsintheColorssectionoftheProgrammingGuide.
gis:draw
![Page 279: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/279.jpg)
gis:drawvector-dataline-thickness
DrawsthegivenvectordatatotheNetLogodrawinglayer,usingthecurrentGISdrawingcolor,withthegivenlinethickness.ThedatamayconsisteitherofanentireVectorDataset,orasingleVectorFeature.Thisprimitivedrawsonlytheboundaryofpolygondata,andforpointdata,itfillsacirclewitharadiusequaltothelinethickness.
gis:fill
gis:fillvector-dataline-thickness
FillsthegivenvectordataintheNetLogodrawinglayerusingthecurrentGISdrawingcolor,usingthegivenlinethicknessaroundtheedges.ThedatamayconsisteitherofanentireVectorDataset,orasingleVectorFeature.Forpointdata,itfillsacirclewitharadiusequaltothelinethickness.
gis:paint
gis:paintRasterDatasettransparency
PaintsthegivenrasterdatatotheNetLogodrawinglayer.Thehighestvalueinthedatasetispaintedwhite,thelowestispaintedinblack,andtheothervaluesarepaintedinshadesofgrayscaledlinearlybetweenwhiteandblack.
Thetransparencyinputdetermineshowtransparentthenewimageinthedrawingwillbe.Validinputsrangefrom0(completelyopaque)to255(completelytransparent).
gis:import-wms-drawing
gis:import-wms-drawingserver-urlspatial-referencelayerstransparency
ImportsanimageintotheNetLogodrawinglayerusingtheWebMappingServiceprotocol,asdefinedbytheOpenGeospatialConsortium.
Thespatialreferenceandlayersinputsshouldbegivenasstrings.ThespatialreferenceinputcorrespondstotheSRSparametertotheGetMaprequestasdefinedinsection7.2.3.5ofversion1.1.1oftheWMSstandard.ThelayersinputcorrespondstotheLAYERSparametertotheasdefinedin7.2.3.3ofversion1.1.1oftheWMSstandard.
YoucanfindthelistofvalidspatialreferencecodesandlayernamesbyexaminingtheresponsetoaGetCapabilitiesrequesttotheWMSserver.ConsulttherelevantstandardforinstructionsonhowtoissueaGetCapabilitiesrequesttotheserverandhowtointerprettheresults.
Thetransparencyinputdetermineshowtransparentthenewimageinthedrawingwillbe.Validinputsrangefrom0(completelyopaque)to255(completelytransparent).
![Page 280: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/280.jpg)
NetLogoGogoExtension
Usage
TheGoGoExtensioncomespreinstalledwhenyoudownloadandinstallNetLogo.Tousetheextensioninyourmodel,addthislinetothetopofyourCodetab:
extensions [ gogo ]
Ifyourmodelalreadyusesotherextensions,thenitalreadyhasanextensionslineinit,sojustaddgogotothelist.
Afterloadingtheextension,youcanseewhetheroneormoreHID-basedgogosareonandattachedtothecomputerbytypingthefollowingintothecommandcenter:
gogo:howmany-gogos
Changes
ComparedtopreviousversionsoftheGoGoextension,thisversionoffers:
Improvedrobustness.WithpriorversionsoftheGoGoextension,crasheswerefairlycommonduetoproblemsintheUSB-Serialstackacrossplatforms.TheswitchtoHIDimprovedrobustness,andthenewextensionalsousesa“daemon”architecturewhichshieldsNetLogofromanyproblemsthatmayoccurindirectcommunicationwiththeGoGoboard.TheresultisasubstantialreductioninthenumberofcrashesofNetLogo.NoInstallationofDrivers.BecausethenewGoGofirmwarepresentstheboardasanHIDdevice,theextensioncouldbewrittensoasnottorequireinstallingdrivers.Thismeansthereisnoneedfortheusertohaveadministratorrightsonthecomputer.DirectionalityforMotors.Theboardnowhaspolarity-ensuringoutputconnectors,sothat“counterclockwise”or“clockwise”cannowbespecifiedincode.
Primitives
OtherOutputs
gogo:ledgogo:beep
Utilities
gogo:read-all
General
gogo:primitivesgogo:howmany-gogos
Sensors
gogo:read-sensorsgogo:read-sensor
![Page 281: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/281.jpg)
OutputsandServos
gogo:talk-to-output-portsgogo:set-output-port-powergogo:output-port-ongogo:output-port-offgogo:output-port-clockwisegogo:output-port-counterclockwisegogo:set-servo
gogo:primitives
gogo:primitives
Returnsalistoftheprimitivesofthisextension.
gogo:howmany-gogos
gogo:howmany-gogos
ReportsthenumberofUSBHIDdevicesvisibletothecomputerandhavingthecorrectvendorandproductIDtobeaGoGoboard.Aboardwillonlybedetectedifitisbothconnectedandpoweredon.UsingthisprimitiveisonewaytodeterminequicklywhetheraGoGoboardhastheHIDfirmwareloaded.(AUSB-Serialversionoftheboardwillnotbedetected.).
gogo:talk-to-output-ports
gogo:talk-to-output-portslist-of-portnames
Establishesalistofoutputportsthatwillbecontrolledwithsubsequentoutput-portcommands.Seebelow…
gogo:set-output-port-power
gogo:set-output-port-powerpower-level
power-levelisanumberbetween0and100,reflectingthepercentageofmaximumpower.Setstheamountofpowerthatwillbefedtotheoutputportsindicatedintalk-to-output-ports.Thiswillnotaffecttheon-offstateoftheoutputports.So,forexample,ifamotorisalreadyconnectedtoanoutputportandrunning,changingitspowerwillchangeitsspeed.Ifthemotorisnotrunning,changingthepowerlevelwillnotturniton;instead,itwillaffectthespeedatwhichthemotorstartswhenitisturnedonwithoutput-port-on.
gogo:output-port-on
gogo:output-port-on
Turnsontheoutputportswhichhavebeenindicatedwithtalk-to-output-ports.Ifnonehavebeensetwithtalk-to-output-ports,noportswillbeturnedon.
gogo:output-port-off
gogo:output-port-off
![Page 282: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/282.jpg)
Turnsofftheoutputportswhichhavebeenindicatedwithtalk-to-output-ports.Ifnonehavebeensetwithtalk-to-output-ports,noportswillbeturnedoff.
gogo:output-port-clockwise
gogo:output-port-clockwise
Setsthepolarityoftheoutputport(s)thathavebeenspecifiedwithtalk-to-output-ports,sothatamotorattachedtooneoftheseportswouldturnclockwise.
gogo:output-port-counterclockwise
gogo:output-port-counterclockwise
Setsthepolarityoftheoutputport(s)thathavebeenspecifiedwithtalk-to-output-ports,sothatamotorattachedtooneoftheseportswouldturncounterclockwise.
gogo:set-servo
gogo:set-servonumber
SetsthePulse-WidthModulation(PWM)proportionoftheoutputport(s)thathavebeenspecifiedwithtalk-to-output-ports.Notethattheservoconnectorsarethemalepinsnexttothestandardmotorconnectors.DifferentservosrespondtodifferentPWMranges,butallservosreadPWMproportionsandsetthepositionoftheirmaingearaccordingly.
gogo:led
gogo:ledon-or-off
Turnstheuser-LEDonoroff,dependingontheargument.gogo:led1turnstheLEDon;gogo:led0turnsitoff.
gogo:beep
gogo:beep
CausestheGoGoboardtobeep.
gogo:read-sensors
gogo:read-sensors
ReportsalistcontainingthecurrentreadingsofalleightsensorsportsoftheGoGo.
gogo:read-sensor
gogo:read-sensorwhich-sensor
![Page 283: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/283.jpg)
Reportsthevalueofsensornumberwhich-sensor,wherewhich-sensorisanumberbetween0-7.
gogo:read-all
gogo:read-all
Reportsalldataavailablefromtheboard,inaraw-listformusefulfordebugging.
gogo:send-bytes
gogo:send-byteslist
SendsalistofbytestotheGoGoboard.UsefulfordebuggingorfortestinganyneworfuturefunctionalitythatisaddedtotheGoGoboardwithnewfirmwareupdates.
![Page 284: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/284.jpg)
NetLogoLsExtension
LevelSpacefundamentals
LevelSpacemustbeloadedinamodelusingextensions [ls]atthetopofyourmodel.Oncethisisdone,amodelwillbeabletoloadupothermodelsusingtheLevelSpaceprimitives,runcommandsandreportersinthem,andclosethemdownwhentheyarenolongerneeded.
AskingandreportinginLevelSpaceisconceptuallyprettystraightforward:Youpassblocksofcodetochildmodels,andthechildmodelsrespondasifyouhadtypedthatcodeintotheirCommandCenter.LevelSpaceallowsyoutoreportstrings,numbers,andlistsfromachildtoitsparent.Itisnotpossibletodirectlyreportturtles,patches,links,oranyoftheirrespectivesets.Further,itisnotpossibletopushdatafromachildtoitsparent-parentsmustasktheirchildrentoreport.Thismimicksthewayinwhichturtlescannot“push”datatotheobserver,butrelyontheobservertoaskthemforit.
Ingeneral,theLevelSpacesyntaxhasbeendesignedtoalignwithexistingNetLogoprimitiveswheneverpossible.
HeadlessandInteractiveModels
LevelSpacehastwodifferentchildmodeltypes;headlessmodelsandinteractivemodels.Theyeachhavetheirstrengthsandweaknesses:
Interactivemodels*arefull-fledgedmodelsthatgivefullaccesstotheirinterfaceandwidgets,*runabitslower,andusemorememory*arevisiblebydefault
HeadlessModels*onlygiveyouaccesstotheirviewandcommandcenter*arefasteranduselessmemorythaninteractivemodels.*arehiddenbydefault
Typicallyyouwillwanttouseheadlessmodelswhenyouarerunningalargenumberofmodels,orifyousimplywanttorunthemfaster.Interactivemodelsaregoodifyourunasmallamountofmodels,ifyouarewritingaLevelSpacemodelandneedtobeabletodebug,orifyouneedaccesstowidgetsduringruntime.
KeepingTrackofModels
Childmodelsarekepttrackofintheextensionwithanidnumber,startingwith0,andallcommunicationfromparenttochildisdonebyreferencingthisnumber,henceforthreferredtoasmodel-id.
Theeasiestwaytoworkwithmultiplemodelsistostoretheirmodel-idinalist,anduseNetLogo’slistprimitivestosort,filter,etc.themduringruntime.
Keepingtrackofmodelsisimportant:MostLevelSpaceprimitiveswillfailandcausearuntimeinterruptionifprovidedamodel-idtoanon-existingmodel.Youcanusels:model-exists? model-idtocheckifmodel-idreferstoanexistingmodel.
Ageneralusecase:AskingandReporting
ThisusecaseisbasedontheModelVisualizerandPlotterExample-modelfromtheNetLogoModelsLibrary.
![Page 285: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/285.jpg)
Asimplethingwecandoistoopenupsomemodels,runthemconcurrently,andcalculatetheaverageofsomereporter.Let’ssaythatweareinterestedinfindingthemeannumberofsheepinabunchofWolfSheepPredationmodels.Firstwewouldopenupsomeofthesemodels,andsetthemup:
to setup ls:reset ca ls:create-models 30 "Wolf Sheep Predation.nlogo" ls:ask ls:models [ set grass? true setup ] reset-ticksend
Wethenwanttorunallourchildmodels,andthenfindoutwhatthemeannumberofsheepis:
to go ls:ask ls:models [ go ] show mean [ count sheep ] ls:of ls:modelsend
Ageneralusecase:Inter-ModelInteractions
ThisusecaseisbasedontheModelInteractionsExample-modelfromtheNetLogoModelsLibrary.
Let’simaginethatwehavetwomodels:aWolfSheepPredation-modelcalledWSP,andaClimateChangemodelcalledCC.Nowlet’simaginethatwewanttheregrowthtimeinthewSPmodeltodependonthetemperatureintheCCmodel.UsingLevelSpace’sprimitives,wecoulddosomethinglikethis:
; save new regrowth time in a temporary LevelSpace let-variable ls:let new-regrowth-time 25 + ( abs [ temperature - 55 ] ls:of CC ) / 2
; remove decimals, pass it to the wolf sheep predation model and change the time ls:ask WSP [ set grass-regrowth-time round new-regrowth-time ]
; finally ask both models to go ls:ask ls:models [ go ]
AgeneralUsecase:Tidyingup“Dead”ChildModels
Aspreviouslymentioned,itisimportanttokeeptrackof“living”and“dead”modelswhenyoudynamicallycreateanddisposeofmodels.Letusimaginewehavesomelistsofmodelsofdifferentkinds,andwewanttomakesurethatweonlykeepthemodelsthatarealive.Afterrunningcodethatkillschildmodelswecanusethels:model-exists?primitivetocleanupourlistofmodelslikethis:
to-report remove-dead-models [list-of-models] report filter [ [ model-id ] -> ls:model-exists model-id] list-of-modelsend
Wethenreassigneachlistofmodelswiththis,e.g.
![Page 286: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/286.jpg)
set a-list-of-models remove-dead-models a-list-of-modelsset another-list-of-models remove-dead-models a-list-of-models
CitingLevelSpaceinResearch
IfyouuseLevelSpaceinresearch,weaskthatyouciteus,
Hjorth,A.Head,B.&Wilensky,U.(2015).“LevelSpaceNetLogoextension”.http://ccl.northwestern.edu/rp/levelspace/index.shtmlEvanston,IL:CenterforConnectedLearningandComputerBasedModeling,NorthwesternUniversity.
Primitives
CommandingandReporting
ls:askls:ofls:reportls:withls:let
LogicandControl
ls:modelsls:showls:show-allls:hidels:hide-allls:path-ofls:name-ofls:model-exists?
OpeningandClosingModels
ls:create-modelsls:create-interactive-modelsls:closels:reset
ls:create-models
ls:create-modelsnumberpathls:create-modelsnumberpathanonymouscommand
Createthespecifiednumberofinstancesofthegiven.nlogomodel.Thepathcanbeabsolute,orrelativetothemainmodel.Comparedwithls:create-interactive-models,thisprimitivecreateslightweightmodelsthatarehiddenbydefault.Youshouldusethisprimitiveifyouplanonhavingmanyinstancesofthegivenmodel.Themodelsmaybeshownusingls:show;whenvisible,theywillhaveaviewandcommandcenter,butnootherwidgets,e.g.plotsormonitors.
Ifgivenacommand,LevelSpacewillcallthecommandafterloadingeachinstanceofthemodelwiththemodel-idastheargument.Thisallowsyoutoeasilystoremodelidsinavariableorlistwhenloadingmodels,ordootherinitialization.Forexample,tostoreamodelidinavariable,youcando:
let model-id 0(ls:create-models "My-Model.nlogo" [ [id] -> set model-id id ])
ls:create-interactive-models
ls:create-interactive-modelsnumberpathls:create-interactive-modelsnumberpathanonymouscommand
Likels:create-models,createsthespecifiednumberofinstancesofthegiven.nlogo
![Page 287: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/287.jpg)
model.Unlikels:create-models,ls:create-interactive-modelscreatesmodelsthatarevisiblebydefault,andhaveallwidgets.Youshouldusethisprimitiveifyouplanonhavingonlyahandfulofinstancesofthegivenmodel,andwouldliketobeabletointeractwiththeinstancesthroughtheirinterfacesduringruntime.
ls:close
ls:closemodel-or-list-of-models
Closethemodelormodelswiththegivenmodel-id.
ls:reset
ls:reset
Closedownallchildmodels(and,recursively,theirchildmodels).You’lloftenwanttocallthisinyoursetupprocedure.
Notethatclear-alldoesnotcloseLevelSpacemodels.
ls:ask
ls:askmodel-or-list-of-modelscommandargument
Askthegivenchildmodelorlistofchildmodelstorunthegivencommand.Thisistheprimaryofdoingthingswithchildmodels.Forexample:
ls:ask model-id [ create-turtles 5 ]
Youcanalsoaskalistofmodelstoalldothesamething:
ls:ask ls:models [ create-turtles 5 ]
Youmaysupplythecommandwitharguments,justlikeyouwouldwithanonymouscommands:
let turtle-id 0let speed 5(ls:ask model-id [ [t s] -> ask turtle t [ fd s ] ] turtle-id speed)
Notethatthecommandscannotaccessvariablesintheparentmodeldirectly.Youmusteitherpassinformationinthroughargumentsorusingls:let.
ls:of
reporterls:ofmodel-or-list-of-models
Runthegivenreporterinthegivenmodelandreporttheresult.
ls:ofisdesignedtoworklikeNetLogo’sinbuiltof:Ifyousendls:ofamodel-id,itwillreportthevalueofthereporterfromthatmodel.Ifyousenditalistofmodel-ids,itwill
![Page 288: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/288.jpg)
reportalistofvaluesofthereporterstringfromallmodels.Youcannotpassargumentstols:of,butyoucanusels:let.
[ count turtles ] ls:of model-id
ls:report
ls:reportmodel-or-list-of-modelsreporterargument
Runthegivenreporterinthegivenmodelandreporttheresult.Thisformexiststoallowyoutopassargumentstothereporter.
let turtle-id 0(ls:report model-id [ [a-turtle] -> [ color ] of turtle a-turtle ] turtle-id)
ls:with
list-of-modelsls:withreporter
Reportsanewlistofmodelscontainingonlythosemodelsthatreporttruewhentheyrunthereporterblock.
ls:models ls:with [ count turtles > 100 ]
ls:let
ls:letvariable-namevalue
Createsavariablecontainingthegivendatathatcanbeaccessedbythechildmodels.
ask turtles [ ls:let my-color color ls:ask my-model [ ask turtles [ set color my-color ] ]]
ls:letworksquitesimilartoletinthatthevariableisonlylocallyaccessible:
ask turtles [ ls:let my-color color];; my-color is innaccessible here
ls:letisverysimilartolet,exceptinafewcases.
ls:letwilloverwritepreviousvaluesinthevariable
Ifyoudo
ls:let my-var 5
![Page 289: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/289.jpg)
ls:let my-var 6
my-varwillbesetequalto6.Thereisnols:set.
ls:letsupportsvariableshadowing
Ifyoudo
ls:let my-var 5ask turtles [ ls:let my-var 6 ls:ask child-model [ show my-var ]]ls:ask child-model [ show my-var ]
child-modelwillshow6andthen5.Thisisknownasvariableshadowing.
Theparentmodelcannotdirectlyreadthevalueofanlsvariable
Forexample,thisdoesnotwork.
ls:let my-var 5show my-var
Thisisintentional.lsvariablesaremeanttobeusedforsharingdatawithchildmodels.Theparentmodelalreadyhasaccesstothedata.
Furthermore,changingthevalueofanlsletvariableinachildmodelwillnotaffectitinanyothermodel.Forexample:
ls:let my-var 0ls:ask ls:models [ set my-var my-var + 1 show my-var]
Allmodelswillprint1.
ls:letdoesnotrespectthescopeofif,when,andrepeat
Thisbehaviorshouldbeconsideredabugandnotreliedupon.ItisanunfortunateconsequenceofthewaytheNetLogoengineworks.Hopefully,we’llbeabletocorrectthisinafutureversionofNetLogo.
Forexample,thisisallowable:
if true [ ls:let my-var 5]ls:ask child-model [ create-turtles my-var ]
Thescopeofaskisrespected,however.
ls:models
ls:models
![Page 290: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/290.jpg)
Reportalistofmodel-idsforallexistingmodels.
ls:show
ls:showmodel-or-list-of-models
Makesallofthegivenmodelsvisible.
ls:show-all
ls:show-allmodel-or-list-of-models
Makesallofthegivenmodelsandtheirdescendentsvisible.
ls:hide
ls:hidemodel-or-list-of-models
Hideallofthegivenmodels.Hidingmodelsisagoodwayofmakingyoursimulationrunfaster.
ls:hide-all
ls:hide-allmodel-or-list-of-models
Hideallofthegivenmodelsandtheirdescendents.Hidingmodelsisagoodwayofmakingyoursimulationrunfaster.
ls:path-of
ls:path-ofmodel-or-list-of-models
Reportthefullpath,includingthe.nlogofilename,ofthemodel.Ifalistofmodelsisgiven,alistofpathsisreported.
ls:name-of
ls:name-ofmodel-or-list-of-models
Reportsthenameofthe.nlogofileofthemodel.Thisisthenameofthewindowinwhichthemodelappearswhenvisible.Ifalistofmodelsisgiven,alistofnamesisreported.
ls:model-exists?
ls:model-exists?model-or-list-of-models
Reportabooleanvalueforwhetherthereisamodelwiththatmodel-id.Thisisoftenusefulwhenyouaredynamicallygeneratingmodels,andwanttoensurethatyouarenotaskingmodelsthatnolongerexisttodostuff.
![Page 291: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/291.jpg)
NetLogoMatrixExtension
Using
ThematrixextensionaddsanewmatrixdatastructuretoNetLogo.Amatrixisamutable2-dimensionalarraycontainingonlynumbers.
WhentoUse
Althoughmatricesstorenumbers,muchlikealistoflists,oranarrayofarrays,theprimaryreasontousethematrixdatatypeistotakeadvantageofspecialmathematicaloperationsassociatedwithmatrices.Forinstance,matrixmultiplicationisaconvenientwaytoperformgeometrictransformations,andtherepeatedapplicationofmatrixmultiplicationcanalsobeusedtosimulateotherdynamicprocesses(forinstance,processesongraph/networkstructures).
Ifyou’dliketoknowmoreaboutmatricesandhowtheycanbeused,youmightconsideracourseonlinearalgebra,orsearchthewebfortutorials.Thematrixextensionalsoallowsyoutosolvelinearalgebraicequations(specifiedinamatrixformat),andeventoidentifytrendsinyourdataandperformlinear(ordinaryleastsquares)regressionsondatasetswithmultipleexplanatoryvariables.
HowtoUse
Thematrixextensioncomespreinstalled.
Tousethematrixextensioninyourmodel,addalinetothetopofyourCodetab:
extensions [matrix]
Ifyourmodelalreadyusesotherextensions,thenitalreadyhasanextensionslineinit,sojustaddmatrixtothelist.
Example
let m matrix:from-row-list [[1 2 3] [4 5 6]]print m=> {{matrix: [ [ 1 2 3 ][ 4 5 6 ] ]}}print matrix:pretty-print-text m=>[[ 1 2 3 ] [ 4 5 6 ]]
print matrix:dimensions m=> [2 3];;(NOTE: row & column indexing starts at 0, not 1)print matrix:get m 1 2 ;; what number is in row 1, column 2?=> 6matrix:set m 1 2 10 ;; change the 6 to a 10print m=> {{matrix: [ [ 1 2 3 ][ 4 5 10 ] ]}}
let m2 matrix:make-identity 3print m2=> {{matrix: [ [ 1 0 0 ][ 0 1 0 ][ 0 0 1 ] ]}}print matrix:times m m2 ;; multiplying by the identity changes nothing=> {{matrix: [ [ 1 2 3 ][ 4 5 10 ] ]}}
;; make a new matrix with the middle 1 changed to -1let m3 (matrix:set-and-report m2 1 1 -1)print m3=> {{matrix: [ [ 1 0 0 ][ 0 -1 0 ][ 0 0 1 ] ]}}print matrix:times m m3=> {{matrix: [ [ 1 -2 3 ][ 4 -5 10 ] ]}}
print matrix:to-row-list (matrix:plus m2 m3)=> [[2 0 0] [0 0 0] [0 0 2]]
Primitives
Matrixcreationandconversionto/fromlists
matrix:make-constantmatrix:make-identitymatrix:from-row-listmatrix:from-column-listmatrix:to-row-listmatrix:to-column-listmatrix:copymatrix:pretty-print-text
Advancedfeatures
matrix:solvematrix:forecast-linear-growthmatrix:forecast-compound-growthmatrix:forecast-continuous-growthmatrix:regress
![Page 292: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/292.jpg)
Matrixdataretrievalandmanipulation
matrix:getmatrix:get-rowmatrix:get-columnmatrix:setmatrix:set-rowmatrix:set-columnmatrix:swap-rowsmatrix:swap-columnsmatrix:set-and-reportmatrix:dimensionsmatrix:submatrixmatrix:map
Mathoperations
matrix:times-scalarmatrix:timesmatrix:*matrix:times-element-wisematrix:plus-scalarmatrix:plusmatrix:+matrix:minusmatrix:-matrix:inversematrix:transposematrix:real-eigenvaluesmatrix:imaginary-eigenvaluesmatrix:eigenvectorsmatrix:detmatrix:rankmatrix:trace
matrix:make-constant
matrix:make-constantn-rowsn-colsinitialValue
Reportsanewn-rowsbyn-colsmatrixobject,withallentriesinthematrixcontainingthesamevalue(number).
matrix:make-identity
matrix:make-identitysize
Reportsanewsquarematrixobject(withdimensionsn-sizexn-size),consistingoftheidentitymatrix(1salongthemaindiagonal,0selsewhere).
matrix:from-row-list
matrix:from-row-listnested-list
Reportsanewmatrixobject,createdfromaNetLogolist,whereeachiteminthatlistisanotherlist(correspondingtoeachoftherowsofthematrix.)
print matrix:from-row-list [[1 2] [3 4]]=> {{matrix: [ [ 1 2 ][ 3 4 ] ]}};; Corresponds to this matrix:;; 1 2;; 3 4
matrix:from-column-list
matrix:from-column-listnested-list
Reportsanewmatrixobject,createdfromaNetLogolistcontainingeachofthecolumnsofthematrix.
matrix:to-row-list
matrix:to-row-listmatrix
Reportsalistoflists,containingeachrowofthematrix.
matrix:to-column-list
matrix:to-column-listmatrix
Reportsalistoflists,containingeachcolumnofthematrix.
matrix:copy
matrix:copymatrix
Reportsanewmatrixthatisanexactcopyofthegivenmatrix.Thisprimitiveisimportantbecausethematrixtypeismutable(changeable).Here’sacodeexample:
let m1 matrix:from-column-list [[1 4 7][2 5 8][3 6 9]] ; a 3x3 matrixprint m1=> {{matrix: [ [ 1 2 3 ][ 4 5 6 ][ 7 8 9 ] ]}}let m2 m1 ;; m2 refers to the same matrix object as m1let m3 matrix:copy m1 ;; m3 is a new copy containing m1's data
![Page 293: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/293.jpg)
matrix:set m1 0 0 100 ;; now m1 is changed
print m1=> {{matrix: [ [ 100 2 3 ][ 4 5 6 ][ 7 8 9 ] ]}}
print m2=> {{matrix: [ [ 100 2 3 ][ 4 5 6 ][ 7 8 9 ] ]}};;Notice that m2 was also changed, when m1 was changed!
print m3=> {{matrix: [ [ 1 2 3 ][ 4 5 6 ][ 7 8 9 ] ]}}
matrix:pretty-print-text
matrix:pretty-print-textmatrix
Reportsastringthatisatextualrepresentationofthematrix,inaformatthatisreasonablyhuman-readablewhendisplayed.
matrix:get
matrix:getmatrixrow-icol-j
Reportsthe(numeric)valueatlocationrow-i(secondargument),col-j(thirdargument),inthegivenmatrixgiveninthefirstargument
matrix:get-row
matrix:get-rowmatrixrow-i
Reportsasimple(notnested)NetLogolistcontainingtheelementsofrow-i(secondargument)ofthematrixsuppliedinthefirstargument.
matrix:get-column
matrix:get-columnmatrixcol-j
Reportsasimple(notnested)NetLogolistcontainingtheelementsofcol-jofthematrixsuppliedinthefirstargument.
matrix:set
matrix:setmatrixrow-icol-jnew-value
Changesthegivenmatrixbysettingthevalueatlocationrow-i,col-jtonew-value
matrix:set-row
matrix:set-rowmatrixrow-isimple-list
Changesthegivenmatrixmatrixbyreplacingtherowatrow-iwiththecontentsofthesimple(notnested)NetLogolistsimple-list.Thesimple-listmusthavealengthequaltothenumberofcolumnsinthematrix,i.e.,thematrixrowlength.
matrix:set-column
matrix:set-columnmatrixcol-jsimple-list
Changesthegivenmatrixmatrixbyreplacingthecolumnatcol-jwiththecontentsofthesimple(notnested)NetLogolistsimple-list.Thesimple-listmusthavealengthequaltothenumberofrowsinthematrix,i.e.,thematrixcolumnlengthlength.
matrix:swap-rows
matrix:swap-rowsmatrixrow1row2
Changesthegivenmatrixmatrixbyswappingtherowsatrow1androw2witheachother.
matrix:swap-columns
![Page 294: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/294.jpg)
matrix:swap-columnsmatrixcol1col2
Changesthegivenmatrixmatrixbyswappingthecolumnsatcol1andcol2witheachother.
matrix:set-and-report
matrix:set-and-reportmatrixrow-icol-jnew-value
Reportsanewmatrix,whichisacopyofthegivenmatrixexceptthatthevalueatrow-i,col-jhasbeenchangedtonew-value.ANetLogostatementsuchasset mat matrix:set-and-report mat 2 3 10willresultinmatpointingtothisnewmatrix,acopyoftheoldversionofmatwiththeelementatrow2,column3beingsetto10.Theoldversionofmatwillbe“lost”.
matrix:dimensions
matrix:dimensionsmatrix
Reportsa2-elementlist([num-rows,num-cols]),containingthenumberofrowsandnumberofcolumnsinthegivenmatrix
matrix:submatrix
matrix:submatrixmatrixr1c1r2c2
Reportsanewmatrixobject,consistingofarectangularsubsectionofthegivenmatrix.Therectangularregionisfromrowr1upto(butnotincluding)rowr2,andfromcolumnc1upto(butnotincluding)columnc2.
Hereisanexample:
let m matrix:from-row-list [[1 2 3][4 5 6][7 8 9]]print matrix:submatrix m 0 1 2 3 ; matrix, row-start, col-start, row-end, col-end ; rows from 0 (inclusive) to 2 (exclusive), ; columns from 1 (inclusive) to 3 (exclusive)=> {{matrix: [ [ 2 3 ][ 5 6 ] ]}}
matrix:map
matrix:mapanonymousreportermatrixmatrix:mapanonymousreportermatrixanything
Reportsanewmatrixwhichresultsfromapplyingreporter(ananonymousreporterorthenameofareporter)toeachoftheelementsofthegivenmatrix.Forexample,
matrix:map sqrt matrix
wouldtakethesquarerootofeachelementofmatrix.Ifmorethanonematrixargumentisprovided,thereporterisgiventheelementsofeachmatrixasarguments.Thus,
(matrix:map + matrix1 matrix2)
wouldaddmatrix1andmatrix2.
Thisreporterismeanttobethesameasmap,butformatricesinsteadoflists.
matrix:times-scalar
matrix:times-scalarmatrixfactor
AsofNetLogo5.1,matrix:timescanmultiplymatricesbyscalarsmakingthisfunctionobsolete.Usematrix:timesinstead.
Reportsanewmatrix,whichistheresultofmultiplyingeveryentryintheoriginalmatrixbythegivenscalingfactor.
matrix:times
matrix:timesm1m2matrix:timesm1m2...
![Page 295: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/295.jpg)
Reportsamatrix,whichistheresultofmultiplyingthegivenmatricesandscalars(usingstandardmatrixmultiplication–makesureyourmatrixdimensionsmatchup.)Withoutparentheses,ittakestwoarguments.Withparenthesesittakestwoormore.Theargumentsmayeitherbenumbersormatrices,butatleastonemustbeamatrix.
matrix:*
m1matrix:*m2
Reportsamatrix,whichistheresultofmultiplyingthegivenmatricesand/orscalars(usingstandardmatrixmultiplication–makesureyourmatrixdimensionsmatchup.)Thisisexactlythesameasmatrix:times m1 m2
Takesprecedenceovermatrix:+andmatrix:-,sameasnormalmultiplication.
matrix:times-element-wise
matrix:times-element-wisem1m2
Reportsamatrix,whichistheresultofmultiplyingthegivenmatricestogether,element-wise.Allelementsaremultipliedbyscalarargumentsaswell.Notethatallmatrixargumentsmusthavethesamedimensions.Withoutparentheses,ittakestwoarguments.Withparenthesesittakestwoormore.Theargumentsmayeitherbenumbersormatrices,butatleastonemustbeamatrix.
matrix:plus-scalar
matrix:plus-scalarmatrixnumber
AsofNetLogo5.1,matrix:pluscanaddmatricesandscalarsmakingthisfunctionobsolete.Usematrix:plusinstead.
Reportsamatrix,whichistheresultofaddingtheconstantnumbertoeachelementofthegivenmatrix.
matrix:plus
matrix:plusm1m2matrix:plusm1m2...
Reportsamatrix,whichistheresultofaddingthegivenmatricesandscalars.Scalarsareaddedtoeachelement.Withoutparentheses,ittakestwoarguments.Withparenthesesittakestwoormore.Theargumentsmayeitherbenumbersormatrices,butatleastonemustbeamatrix.
matrix:+
m1matrix:+m2
Reportsamatrix,whichistheresultofaddingthegivenmatricesand/orscalars.Thisisexactlythesameasmatrix:plusm1 m2
Takesprecedenceaftermatrix:*,sameasnormaladdition.
matrix:minus
matrix:minusm1m2matrix:minusm1m2...
Reportsamatrix,whichistheresultofsubtractingallargumentsbesidesm1fromm1.Scalarargumentsaretreatedasmatricesofthesamesizeasthematrixargumentswitheveryelementequaltothatscalar.Withoutparentheses,ittakestwoarguments.Withparenthesesittakestwoormore.Theargumentsmayeitherbenumbersormatrices,butatleastonemustbeamatrix.
matrix:-
m1matrix:-m2
Reportsamatrix,whichistheresultofsubtractingthegivenmatricesand/orscalars.Thisisexactlythesameas
matrix:minus m1 m2
Takesprecedenceaftermatrix:*,sameasnormalsubtraction.
![Page 296: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/296.jpg)
matrix:inverse
matrix:inversematrix
Reportstheinverseofthegivenmatrix,orresultsinanerrorifthematrixisnotinvertible.
matrix:transpose
matrix:transposematrix
Reportsthetransposeofthegivenmatrix.
matrix:real-eigenvalues
matrix:real-eigenvaluesmatrix
Reportsalistcontainingtherealeigenvaluesofthegivenmatrix.
matrix:imaginary-eigenvalues
matrix:imaginary-eigenvaluesmatrix
Reportsalistcontainingtheimaginaryeigenvaluesofthegivenmatrix.
matrix:eigenvectors
matrix:eigenvectorsmatrix
Reportsamatrixthatcontainstheeigenvectorsofthegivenmatrix.(Eacheigenvectorasacolumnoftheresultingmatrix.)
matrix:det
matrix:detmatrix
Reportsathedeterminantofthematrix.
matrix:rank
matrix:rankmatrix
Reportstheeffectivenumericalrankofthematrix,obtainedfromSVD(SingularValueDecomposition).
matrix:trace
matrix:tracematrix
Reportsthetraceofthematrix,whichissimplythesumofthemaindiagonalelements.
matrix:solve
matrix:solveAC
Reportsthesolutiontoalinearsystemofequations,specifiedbytheAandCmatrices.Ingeneral,solvingasetoflinearequationsisakintomatrixdivision.Thatis,thegoalistofindamatrixBsuchthatA*B=C.(Forsimplelinearsystems,CandBcanbothbe1-dimensionalmatrices–i.e.vectors).IfAisnotasquarematrix,thena“leastsquares”solutionisreturned.
;; To solve the set of equations x + 3y = 10 and 7x - 4y = 20;; We make our A matrix [[1 3][7 -4]], and our C matrix [[10][20]]let A matrix:from-row-list [[1 3][7 -4]]let C matrix:from-row-list [[10][20]]print matrix:solve A C=> {{matrix: [ [ 4 ][ 2.0000000000000004 ] ]}};; NOTE: as you can see, the results may be only approximate;; (In this case, the true solution should be x=4 and y=2.)
![Page 297: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/297.jpg)
matrix:forecast-linear-growth
matrix:forecast-linear-growthdata-list
Reportsafour-elementlistoftheform:
[ forecast constant slope R2 ]
Theforecastisthepredictednextvaluethatwouldfollowinthesequencegivenbythedata-listinput,basedonalineartrend-line.Normallydata-listwillcontainobservationsonsomevariable,Y,fromtimet=0totimet=(n-1)wherenisthenumberofobservations.TheforecastisthepredictedvalueofYatt=n.Theconstantandslopearetheparametersofthetrend-line
Y = *constant* + *slope* * t.
TheR2valuemeasuresthegoodnessoffitofthetrend-linetothedata,withanR2=1beingaperfectfitandanR2of0indicatingnodiscernibletrend.LineargrowthassumesthatthevariableYgrowsbyaconstantabsoluteamounteachperiod.
;; a linear extrapolation of the next item in the list.print matrix:forecast-linear-growth [20 25 28 32 35 39]=> [42.733333333333334 20.619047619047638 3.6857142857142824 0.9953743395474031];; These results tell us:;; * the next predicted value is roughly 42.7333;; * the linear trend line is given by Y = 20.6190 + 3.6857 * t;; * Y grows by approximately 3.6857 units each period;; * the R^2 value is roughly 0.9954 (a good fit)
matrix:forecast-compound-growth
matrix:forecast-compound-growthdata-list
Reportsafour-elementlistoftheform:
[ forecast constant growth-proportion R2 ]
Whereasmatrix:forecast-linear-growthassumesgrowthbyaconstantabsoluteamounteachperiod,matrix:forecast-compound-growthassumesthatYgrowsbyaconstantproportioneachperiod.Theconstantandgrowth-proportionaretheparametersofthetrend-line
Y = constant * growth-proportiont.
Notethatthegrowthproportionistypicallyinterpretedasgrowth-proportion=(1.0+growth-rate).Therefore,ifmatrix:forecast-compound-growthreturnsagrowth-proportionof1.10,thatimpliesthatYgrowsby(1.10-1.0)=10%eachperiod.Notethatifgrowthisnegative,matrix:forecast-compound-growthwillreturnagrowth-proportionoflessthanone.E.g.,agrowth-proportionof0.90impliesagrowthrateof-10%.
NOTE:ThecompoundgrowthforecastisachievedbytakingthelnofY.(Seematrix:regress,below.)Becauseitisimpossibletotakethenaturallogofzerooranegativenumber,matrix:forecast-compound-growthwillresultinanerrorifitfindsazeroornegativenumberindata-list.
;; a compound growth extrapolation of the next item in the list.print matrix:forecast-compound-growth [20 25 28 32 35 39]=> [45.60964465307147 21.15254147944863 1.136621034423892 0.9760867518334806];; These results tell us:;; * the next predicted value is approximately 45.610;; * the compound growth trend line is given by Y = 21.1525 * 1.1366 ^ t;; * Y grows by approximately 13.66% each period;; * the R^2 value is roughly 0.9761 (a good fit)
matrix:forecast-continuous-growth
matrix:forecast-continuous-growthdata-list
Reportsafour-elementlistoftheform:
[ forecast constant growth-rate R2 ].Whereasmatrix:forecast-compound-growthassumesdiscretetimewithYgrowingbyagivenproportioneachfiniteperiodoftime(e.g.,amonthorayear),matrix:forecast-continuous-growthassumesthatYiscompoundedcontinuously(e.g.,eachsecondorfractionofasecond).Theconstantandgrowth-ratearetheparametersofthetrend-line
Y = constant * e(growth-rate * t)
![Page 298: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/298.jpg)
matrix:forecast-continuous-growthisthe“calculus”analogofmatrix:forecast-compound-growth.Thetwowillnormallyyieldsimilar(butnotidentical)results,asshownintheexamplebelow.growth-ratemay,ofcourse,benegative.
NOTE:ThecontinuousgrowthforecastisachievedbytakingthelnofY.(Seematrix:regress,below.)Becauseitisimpossibletotakethenaturallogofzerooranegativenumber,matrix:forecast-continuous-growthwillresultinanerrorifitfindsazeroornegativenumberindata-list.
;; a continuous growth extrapolation of the next item in the list.print matrix:forecast-continuous-growth [20 25 28 32 35 39]=> [45.60964465307146 21.15254147944863 0.12805985615332668 0.9760867518334806];; These results tell us:;; * the next predicted value is approximately 45.610;; * the compound growth trend line is given by Y = 21.1525 * e ^ (0.1281 * t);; * Y grows by approximately 12.81% each period if compounding takes place continuously;; * the R^2 value is roughly 0.9761 (a good fit)
matrix:regress
matrix:regressdata-matrix
AllthreeoftheforecastprimitivesabovearejustspecialcasesofperforminganOLS(ordinary-least-squares)linearregression–thematrix:regressprimitiveprovidesaflexible/general-purposeapproach.Theinputisamatrixdata-matrix,withthefirstcolumnbeingtheobservationsonthedependentvariableandeachsubsequentcolumnbeingtheobservationsonthe(1ormore)independentvariables.Thuseachrowconsistsofanobservationofthedependentvariablefollowedbythecorrespondingobservationsforeachindependentvariable.
TheoutputisaLogonestedlistcomposedoftwoelements.Thefirstelementisalistcontainingtheregressionconstantfollowedbythecoefficientsoneachoftheindependentvariables.Thesecondelementisa3-elementlistcontainingtheR2statistic,thetotalsumofsquares,andtheresidualsumofsquares.Thefollowingcodeexampleshowshowthematrix:regressprimitivecanbeusedtoperformthesamefunctionasthecodeexamplesshowninthematrix:forecast-*-growthprimitivesabove.(However,keepinmindthatthematrix:regressprimitiveismorepowerfulthanthis,andcanhavemanymoreindependentvariablesintheregression,asindicatedinthefourthexamplebelow.)
;; this is equivalent to what the matrix:forecast-linear-growth doeslet data-list [20 25 28 32 35 39]let indep-var (n-values length data-list [ x -> x ]) ; 0,1,2...,5let lin-output matrix:regress matrix:from-column-list (list data-list indep-var)let lincnst item 0 (item 0 lin-output)let linslpe item 1 (item 0 lin-output)let linR2 item 0 (item 1 lin-output);;Note the "6" here is because we want to forecast the value at time t=6.print (list (lincnst + linslpe * 6) (lincnst) (linslpe) (linR2))
;; this is equivalent to what the matrix:forecast-compound-growth doeslet com-log-data-list (map ln [20 25 28 32 35 39])let com-indep-var2 (n-values length com-log-data-list [ x -> x ]) ; 0,1,2...,5let com-output matrix:regress matrix:from-column-list (list com-log-data-list com-indep-var2)let comcnst exp item 0 (item 0 com-output)let comprop exp item 1 (item 0 com-output)let comR2 item 0 (item 1 com-output);;Note the "6" here is because we want to forecast the value at time t=6.print (list (comcnst * comprop ^ 6) (comcnst) (comprop) (comR2))
;; this is equivalent to what the matrix:forecast-continuous-growth doeslet con-log-data-list (map ln [20 25 28 32 35 39])let con-indep-var2 (n-values length con-log-data-list [ x -> x ]) ; 0,1,2...,5let con-output matrix:regress matrix:from-column-list (list con-log-data-list con-indep-var2)let concnst exp item 0 (item 0 con-output)let conrate item 1 (item 0 con-output)let conR2 item 0 (item 1 con-output)print (list (concnst * exp (conrate * 6)) (concnst) (conrate) (conR2))
;; example of a regression with two independent variables:;; Pretend we have a dataset, and we want to know how well happiness;; is correlated to snack-food consumption and accomplishing goals.let happiness [2 4 5 8 10]let snack-food-consumed [3 4 3 7 8]let goals-accomplished [2 3 5 8 9]print matrix:regress matrix:from-column-list (list happiness snack-food-consumed goals-accomplished)=> [[-0.14606741573033788 0.3033707865168543 0.8202247191011234] [0.9801718440185063 40.8 0.8089887640449439]];; linear regression: happiness = -0.146 + 0.303*snack-food-consumed + 0.820*goals-accomplished;; (Since the 0.820 coefficient is higher than the 0.303 coefficient, it appears that each goal;; accomplished yields more happiness than does each snack consumed, although both are positively;; correlated with happiness.);; Also, we see that R^2 = 0.98, so the two factors together provide a good fit.
![Page 299: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/299.jpg)
NetLogoNwExtension
Usage
Thefirstthingthatoneneedstounderstandinordertoworkwiththenetworkextensionishowtotelltheextensionwhichnetworktoworkwith.Considerthefollowingexamplesituation:
breed [ bankers banker ]breed [ clients client ]
undirected-link-breed [ friendships friendship ]directed-link-breed [ accounts account ]
Basically,youhavebankersandclients.Clientscanhaveaccountswithbankers.Bankerscanprobablyhaveaccountwithotherbankers,andanyonecanbefriendswithanyone.
Nowwemightwanttoconsiderthiswholethingasonebignetwork.Ifthatisthecase,thereisnothingspecialtodo:bydefault,theNWextensionprimitivesconsiderallturtlesandalllinkstobepartofthecurrentnetwork.
Wecouldalso,however,beonlyinterestedinasubsetofthenetwork.Maybewewanttoconsideronlyfriendshiprelations.Furthermore,maybewewanttoconsideronlythefriendshipsbetweenbankers.Afterall,havingaveryhighcentralityinanetworkofbankerfriendshipsisverydifferentfromhavingahighcentralityinanetworkofclientfriendships.
Tospecifysuchnetworks,weneedtotelltheextensionbothwhichturtlesandwhichlinksweareinterestedin.Alltheturtlesfromthespecifiedsetofturtleswillbeincludedinthenetwork,andonlythelinksfromthespecifiedsetoflinksthatarebetweenturtlesofthespecifiedsetwillbeincluded.Forexample,ifyouaskforbankersandfriendships,eventhelonelybankerswithnofriendswillbeincluded,butfriendshiplinksbetweenbankersandclientswillnotbeincluded.Thewaytotelltheextensionaboutthisiswiththenw:set-contextprimitive,whichyoumustcallpriortodoinganyoperationsonanetwork.
Someexamples:
nw:set-context turtles links willgiveyoueverything:bankersandclients,friendshipsandaccounts,asonebignetwork.nw:set-context turtles friendships willgiveyouallthebankersandclientsandfriendshipsbetweenanyofthem.nw:set-context bankers friendships willgiveyouallthebankers,andonlyfriendshipsbetweenbankers.nw:set-context bankers links willgiveyouallthebankers,andanylinksbetweenthem,whethertheselinksarefriendshipsoraccounts.nw:set-context clients accounts willgiveyoualltheclients,andaccountsbetweeneachother,butsinceinourfictionalexampleclientscanonlyhaveaccountswithbankers,thiswillbeacompletelydisconnectednetwork.
Specialagentsetsvsnormalagentsets
ItmustbenotedthatNetLogohastwotypesofagentsetsthatbehaveslightlydifferently,andthatthishasanimpactonthewaynw:set-contextworks.Wewillsayafewwordsabouttheseconceptsherebut,forathoroughunderstanding,itishighlyrecommendedthatyoureadthesectiononagentsetsintheNetLogoprogrammingguide.
The“special”agentsetsinNetLogoareturtles,linksandthedifferent“breed”agentsets.Whatisspecialaboutthemisthattheycangrow:ifyoucreateanewturtle,itwillbeaddedtotheturtlesagentset.Ifyouhaveabankersbreedandyoucreateanewbanker,itwillbeaddedtothebankersagentsetandtotheturtlesagentset.Samegoesforlinks.Otheragentsets,suchasthosecreatedwiththewithprimitive(e.g.,turtles with [ color = red ] )ortheturtle-setandlink-setprimitives)areneveraddedto.Thecontentofnormalagentsetswillonlychangeiftheagentsthattheycontaindie.
Toshowhowdifferenttypesofagentsetsinteractwithnw:set-context,let’screateaverysimplenetwork:
clear-allcreate-turtles 3 [ create-links-with other turtles ]
Let’ssetthecontexttoturtlesandlinks(whichisthedefaultanyway)andusenw:get-contexttoseewhatwehave:
nw:set-context turtles linksshow map sort nw:get-context
Wegetallthreeturtlesandallthreelinks:
![Page 300: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/300.jpg)
[[(turtle 0) (turtle 1) (turtle 2)] [(link 0 1) (link 0 2) (link 1 2)]]
Nowlet’skilloneturtle:
ask one-of turtles [ die ]show map sort nw:get-context
Asexpected,thecontextisupdatedtoreflectthedeathoftheturtleandofthetwolinksthatdiedwithit:
[[(turtle 0) (turtle 1)] [(link 0 1)]]
Whatifwenowcreateanewturtle?
create-turtles 1show map sort nw:get-context
Sinceourcontextisusingthespecialturtlesagentset,thenewturtleisautomaticallyadded:
[[(turtle 0) (turtle 1) (turtle 3)] [(link 0 1)]]
Nowlet’sdemonstratehowitworkswithnormalagentsets.Westartoverwithanewnetworkofredturtles:
clear-allcreate-turtles 3 [ create-links-with other turtles set color red]
Andwesetthecontexttoturtles with [ color = red ]) andlinks
nw:set-context (turtles with [ color = red ]) linksshow map sort nw:get-context
Sinceallturtlesarered,wegeteverythinginourcontext:
[[(turtle 0) (turtle 1) (turtle 2)] [(link 0 1) (link 0 2) (link 1 2)]]
Butwhatifweaskoneofthemtoturnblue?
ask one-of turtles [ set color blue ]show map sort nw:get-context
Nochange.Theagentsetusedinourcontextremainsunaffected:
[[(turtle 0) (turtle 1) (turtle 2)] [(link 0 1) (link 0 2) (link 1 2)]]
Ifwekilloneofthem,however…
ask one-of turtles [ die ]show map sort nw:get-context
Itgetsremovedfromtheset:
[[(turtle 0) (turtle 2)] [(link 0 2)]]
Whatifweaddanewredturtle?
create-turtles 1 [ set color red ]show map sort nw:get-context
Nope:
[[(turtle 0) (turtle 2)] [(link 0 2)]]
![Page 301: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/301.jpg)
Anoteregardingfloatingpointcalculations
NeitherJGraphTnorJung,thetwonetworklibrariesthatweuseinternally,usestrictfpfloatingpointcalculations.Thisdoesmeanthatexactreproducibilityofresultsinvolvingfloatingpointcalculationsbetweendifferenthardwarearchitecturesisnotfullyguaranteed.(NetLogoitselfalwaysusesstrictmathsothisonlyappliestosomeprimitivesoftheNWextension.)
Performance
Inordertobefastinasmanycircumstancesaspossible,theNWextensiontrieshardtonevercalculatethingstwice.Itremembersallpaths,distances,andcentralitiesthatitcalculates.So,whilethefirsttimeyouaskforthedistancebetweenturtle 0andturtle 3782maytakesometime,afterthat,itshouldbealmostinstantaneous.Furthermore,itkeepstrackofvaluesitjusthappenedtocalculatealongtheway.Forexample,ifturtle 297isclosertoturtle 0thanturtle 3782is,itmayjusthappentofigureoutthedistancebetweenturtle 0andturtle 297whileitfiguresoutthedistancebetweenturtle 0andturtle 3782.Itwillrememberthisvalue,sothatifyouaskitforthedistancebetweenturtle 0andturtle 297,itdoesn’thavetodoallthatworkagain.
ThereareafewcircumstanceswheretheNWextensionhastoforgetthings.Ifthenetworkchangesatall(youaddturtlesorlinks,orremoveturtlesorlinks),ithastoforgeteverything.Forweightedprimitives,ifthevalueoftheweightvariablechangesforanyofthelinksinthenetwork,itwillforgetthevaluesassociatedwiththatweightvariable.
Ifyou’reworkingonanetworkthatcanchangeregularly,trytodoallyournetworkcalculationsatonce,thenallyournetworkchangesatonce.Themoreyourinterweavenetworkcalculationsandnetworkchanges,themoretheNWextensionwillhavetorecalculatethings.Forexample,ifyouhaveatrafficmodel,andcarsneedtofigureouttheshortestpathtotheirdestinationbasedonthetrafficeachtick,haveallthecarsfindtheirshortestpaths,thenchangethenetworkweightstoaccountforhowtraffichaschanged.
Theremayberareoccasionsinwhichyoudon’twanttheNWextensiontoremembervalues.Forexample,ifyou’reworkingonanextremelylargenetwork,rememberingallthosevaluesmaytakemorememorythanyouhave.Inthatcase,youcanjustcallnw:set-context (first nw:get-context) (last nw:get-context) toforcetheNWextensiontoimmediatelyforgeteverything.
Primitives
Generators
nw:generate-preferential-attachmentnw:generate-randomnw:generate-watts-strogatznw:generate-small-worldnw:generate-lattice-2dnw:generate-ringnw:generate-starnw:generate-wheel
PathandDistance
nw:turtles-in-radiusnw:turtles-in-reverse-radiusnw:distance-tonw:weighted-distance-tonw:path-tonw:turtles-on-path-tonw:weighted-path-tonw:turtles-on-weighted-path-tonw:mean-path-lengthnw:mean-weighted-path-length
Clusterer/CommunityDetection
nw:bicomponent-clustersnw:weak-component-clustersnw:louvain-communitiesnw:maximal-cliquesnw:biggest-maximal-cliques
ContextManagement
nw:set-contextnw:get-contextnw:with-context
ImportandExport
nw:save-matrixnw:load-matrixnw:save-graphmlnw:load-graphmlnw:loadnw:save
CentralityMeasures
nw:betweenness-centralitynw:eigenvector-centralitynw:page-ranknw:closeness-centralitynw:weighted-closeness-centrality
ClusteringMeasures
![Page 302: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/302.jpg)
nw:clustering-coefficientnw:modularity
nw:set-context
nw:set-contextturtlesetlinkset
Specifiesthesetofturtlesandthesetoflinksthattheextensionwillconsidertobethecurrentgraph.Alltheturtlesfromturtlesetandallthelinksfromlinksetthatconnecttwoturtlesfromturtlesetwillbeincluded.
Thiscontextisusedbyallotherprimitives(unlessspecifiedotherwise)untilanewcontextisspecified.(Atthemoment,onlythegeneratorprimitivesandthefileinputprimitivesareexceptionstothisrule.)
Seetheusagesectionforamuchmoredetailedexplanationofnw:set-context.
nw:get-context
nw:get-context
Reportsthecontentofthecurrentgraphcontextasalistcontainingtwoagentsets:theagentsetofturtlesthatarepartofthecontextandtheagentsetoflinksthatarepartofthecontext.
Let’ssaywestartwithablankslateandthedefaultcontextconsistingofturtlesandlinks,nw:get-contextwillreportalistthespecialturtlesandlinksbreedagentsets:
observer> clear-allobserver> show nw:get-contextobserver: [turtles links]
Ifweaddsometurtlesandlinkstoourcontext,we’llstillseethesamething,eventhoughturtlesandlinkshaveinternallygrown:
observer> crt 2 [ create-links-with other turtles ]observer> show nw:get-contextobserver: [turtles links]
Ifyouhadsetyourcontexttonormalagentsetsinstead(builtwithturtle-set,link-setorwith)hereiswhatyouwouldsee:
observer> clear-allobserver> nw:set-context turtle-set turtles link-set linksobserver> show nw:get-contextobserver: [(agentset, 0 turtles) (agentset, 0 links)]
Ifyouthencreatenewturtlesandlinks,theyarenotaddedtothecontextbecausenormalagentsetsdon’tgrow(seeSpecialagentsetsvsnormalagentsets):
observer> crt 2 [ create-links-with other turtles ]observer> show nw:get-contextobserver: [(agentset, 0 turtles) (agentset, 0 links)]
Butifyouconstructnewagentsetsandsetthecontexttothem,yournewagentswillbethere:
observer> nw:set-context turtle-set turtles link-set linksobserver> show nw:get-contextobserver: [(agentset, 2 turtles) (agentset, 1 link)]
Ifyouwanttoseetheactualcontentofyourcontext,itiseasytoturnyouragentsetsintoliststhatcanbenicelydisplayed.Justuseacombinationofmapandsort:
observer> show map sort nw:get-contextobserver: [[(turtle 0) (turtle 1)] [(link 0 1)]]
Finally,youcanusenw:get-contexttostoreacontextthatyoueventuallywanttorestore:
extensions [ nw ]to store-and-restore-context clear-all crt 2 [ set color red
![Page 303: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/303.jpg)
create-links-with other turtles with [ color = red ] [ set color yellow ] ] crt 2 [ set color blue create-links-with other turtles with [ color = blue ] [ set color green ] ] nw:set-context turtles with [ color = red ] links with [ color = yellow ] show map sort nw:get-context let old-turtles item 0 nw:get-context let old-links item 1 nw:get-context nw:set-context turtles with [ color = blue ] links with [ color = green ] show map sort nw:get-context nw:set-context old-turtles old-links show map sort nw:get-contextend
Hereistheresult:
observer> store-and-restore-contextobserver: [[(turtle 0) (turtle 1)] [(link 0 1)]]observer: [[(turtle 2) (turtle 3)] [(link 2 3)]]observer: [[(turtle 0) (turtle 1)] [(link 0 1)]]
nw:with-context
nw:with-contextturtlesetlinksetcommand-block
Executesthecommand-blockwiththecontexttemporarilysettoturtlesetandlinkset.Aftercommand-blockfinishesrunning,thepreviouscontextwillberestored.
Forexample:
observer> create-turtles 3 [ create-links-with other turtles ]observer> nw:with-context (turtle-set turtle 0 turtle 1) (link-set link 0 1) [ show nw:get-context ]observer: [(agentset, 2 turtles) (agentset, 1 link)observer> show nw:get-contextobserver: [turtles links]
IfyouhaveNWextensioncoderunningintwoforeverbuttonsorloopblocksthateachneedtousedifferentcontexts,youshouldusenw:with-contextineachtomakesuretheyareoperatinginthecorrectcontext.
nw:turtles-in-radius
nw:turtles-in-radiusradius
Returnsthesetofturtleswithinthegivendistance(numberoflinksfollowed)ofthecallingturtleinthecurrentcontext,includingthecallingturtle.
nw:turtles-in-radiusformwillfollowbothundirectedlinksanddirectedoutlinks.Youcanthinkofturtles-in-radiusas“turtleswhoIcangettoinradiussteps”.
Ifyouwanttheprimitivetofollowonlyundirectedlinksoronlydirectedlinks,youcandoitbysettingthecontextappropriately.Forexample:nw:set-context turtles undir-links (assumingundir-linksisanundirectedlinkbreed)ornw:set-context turtles dir-links (assumingdir-linksisadirectedlinkbreed).
Example:
clear-allcreate-turtles 5ask turtle 0 [ create-link-with turtle 1 ]ask turtle 0 [ create-link-with turtle 2 ]ask turtle 1 [ create-link-with turtle 3 ]ask turtle 2 [ create-link-with turtle 4 ]ask turtle 0 [ show sort nw:turtles-in-radius 1]
Willoutput:
(turtle 0): [(turtle 0) (turtle 1) (turtle 2)]
![Page 304: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/304.jpg)
Asyoumayhavenoticed,theresultincludesthecallingturtle.ThismimicsthebehavioroftheregularNetLogoin-radiusprimitive.
nw:turtles-in-reverse-radius
nw:turtles-in-reverse-radiusradius
Likenw:turtles-in-radius,butfollowsin-linksinsteadofout-links.Alsofollowundirectedlinks.Youcanthinkofturtles-in-reverse-radiusas“turtleswhocangettomeinradiussteps”.
nw:distance-to
nw:distance-totarget-turtle
Findstheshortestpathtothetargetturtleandreportsthetotaldistanceforthispath,orfalseifnopathexistsinthecurrentcontext.Eachlinkcountsforadistanceofone.
Example:
to go clear-all create-turtles 5 ask turtle 0 [ create-link-with turtle 1 ] ask turtle 1 [ create-link-with turtle 2 ] ask turtle 0 [ create-link-with turtle 3 ] ask turtle 3 [ create-link-with turtle 4 ] ask turtle 4 [ create-link-with turtle 2 ] ask turtle 0 [ show nw:distance-to turtle 2 ]end
Willoutput:
(turtle 0): 2
nw:weighted-distance-to
nw:weighted-distance-totarget-turtleweight-variable
Likenw:distance-to,buttakeslinkweightintoaccount.Theweightscannotbenegativenumbers.
Example:
links-own [ weight ]to go clear-all create-turtles 5 ask turtle 0 [ create-link-with turtle 1 [ set weight 2.0 ] ] ask turtle 1 [ create-link-with turtle 2 [ set weight 2.0 ] ] ask turtle 0 [ create-link-with turtle 3 [ set weight 0.5 ] ] ask turtle 3 [ create-link-with turtle 4 [ set weight 0.5 ] ] ask turtle 4 [ create-link-with turtle 2 [ set weight 0.5 ] ] ask turtle 0 [ show nw:weighted-distance-to turtle 2 weight ]end
Willoutput:
(turtle 0): 1.5
nw:path-to
nw:path-totarget-turtle
Findstheshortestpathtothetargetturtleandreportstheactualpathbetweenthesourceandthetargetturtle.Thepathisreportedasthelistoflinksthatconstitutethepath.
Ifnopathexistbetweenthesourceandthetargetturtles,falsewillbereportedinstead.
NotethattheNW-Extensionrememberspathsthatitscalculatedpreviouslyunlessthenetworkchanges.Thus,youdon’tneedtostorepathstoefficientlymoveacrossthenetwork;youcanjustkeepre-callingoneofthepathprimitives.Ifthenetworkchanges,however,thestoredanswersareforgotten.Example:
![Page 305: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/305.jpg)
links-own [ weight ]to go clear-all create-turtles 5 ask turtle 0 [ create-link-with turtle 1 ] ask turtle 1 [ create-link-with turtle 2 ] ask turtle 0 [ create-link-with turtle 3 ] ask turtle 3 [ create-link-with turtle 4 ] ask turtle 4 [ create-link-with turtle 2 ] ask turtle 0 [ show nw:path-to turtle 2 ]end
Willoutput:
(turtle 0): [(link 0 1) (link 1 2)]
nw:turtles-on-path-to
nw:turtles-on-path-totarget-turtle
Likenw:path-to,buttheturtlesonthepatharereported,insteadofthelinks,includingthesourceturtleandtargetturtle.
Example:
to go clear-all create-turtles 5 ask turtle 0 [ create-link-with turtle 1 ] ask turtle 1 [ create-link-with turtle 2 ] ask turtle 0 [ create-link-with turtle 3 ] ask turtle 3 [ create-link-with turtle 4 ] ask turtle 4 [ create-link-with turtle 2 ] ask turtle 0 [ show nw:turtles-on-path-to turtle 2 ]end
Willoutput:
(turtle 0): [(turtle 0) (turtle 1) (turtle 2)]
nw:weighted-path-to
nw:weighted-path-totarget-turtleweight-variable
Likenw:path-to,buttakeslinkweightintoaccount.
Example:
links-own [ weight ]to go clear-all create-turtles 5 ask turtle 0 [ create-link-with turtle 1 [ set weight 2.0 ] ] ask turtle 1 [ create-link-with turtle 2 [ set weight 2.0 ] ] ask turtle 0 [ create-link-with turtle 3 [ set weight 0.5 ] ] ask turtle 3 [ create-link-with turtle 4 [ set weight 0.5 ] ] ask turtle 4 [ create-link-with turtle 2 [ set weight 0.5 ] ] ask turtle 0 [ show nw:weighted-path-to turtle 2 weight ]end
Willoutput:
(turtle 0): [(link 0 3) (link 3 4) (link 2 4)]
nw:turtles-on-weighted-path-to
nw:turtles-on-weighted-path-totarget-turtleweight-variable
Likenw:turtles-on-path-to,buttakeslinkweightintoaccount.
![Page 306: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/306.jpg)
Example:
links-own [ weight ]to go clear-all create-turtles 5 ask turtle 0 [ create-link-with turtle 1 [ set weight 2.0 ] ] ask turtle 1 [ create-link-with turtle 2 [ set weight 2.0 ] ] ask turtle 0 [ create-link-with turtle 3 [ set weight 0.5 ] ] ask turtle 3 [ create-link-with turtle 4 [ set weight 0.5 ] ] ask turtle 4 [ create-link-with turtle 2 [ set weight 0.5 ] ] ask turtle 0 [ show nw:weighted-path-to turtle 2 weight ]end
Willoutput:
(turtle 0): [(turtle 0) (turtle 3) (turtle 4) (turtle 2)]
nw:mean-path-length
nw:mean-path-length
Reportstheaverageshortest-pathlengthbetweenalldistinctpairsofnodesinthecurrentcontext.
Reportsfalseunlesspathsexistbetweenallpairs.
Example:
links-own [ weight ]to go clear-all create-turtles 3 ask turtle 0 [ create-link-with turtle 1 [ set weight 2.0 ] ] ask turtle 1 [ create-link-with turtle 2 [ set weight 2.0 ] ] show nw:mean-path-length create-turtles 1 ; create a new, disconnected turtle show nw:mean-path-lengthend
Willouput:
observer: 1.3333333333333333observer: false
nw:mean-weighted-path-length
nw:mean-weighted-path-lengthweight-variable
Likenw:mean-path-length,buttakesintoaccountlinkweights.
Example:
links-own [ weight ]to go clear-all create-turtles 3 ask turtle 0 [ create-link-with turtle 1 [ set weight 2.0 ] ] ask turtle 1 [ create-link-with turtle 2 [ set weight 2.0 ] ] show nw:mean-path-length show nw:mean-weighted-path-length weight create-turtles 1 ; create a new, disconnected turtle show nw:mean-path-length show nw:mean-weighted-path-length weightend
Willouput:
observer: 2.6666666666666665observer: false
nw:betweenness-centrality
![Page 307: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/307.jpg)
nw:betweenness-centrality
Tocalculatethebetweennesscentralityofaturtle,youtakeeveryotherpossiblepairsofturtlesand,foreachpair,youcalculatetheproportionofshortestpathsbetweenmembersofthepairthatpassesthroughthecurrentturtle.Thebetweennesscentralityofaturtleisthesumofthese.
Asofnow,linkweightsarenottakenintoaccount.
nw:eigenvector-centrality
nw:eigenvector-centrality
TheEigenvectorcentralityofanodecanbethoughtofastheamountofinfluenceanodehasonanetwork.Inpractice,turtlesthatareconnectedtoalotofotherturtlesthatarethemselveswell-connected(andsoon)getahigherEigenvectorcentralityscore.
Inthisimplementation,theeigenvectorcentralityisnormalizedsuchthatthehighesteigenvectorcentralityanodecanhaveis1.ThisimplementationisdesignedtoagreewithGephi’simplementationouttoatleast3decimalplaces.IfyoudiscoverthatitdisagreeswithGephionaparticularnetwork,pleasereportit.
Theprimitiverespectslinkdirection,eveninmixed-directednetworks.ThisistheoneplacewhereitshoulddisagreewithGephi;Gephirefusestotreatdirectedlinksasdirectedinmixed-networks.
Asofnow,linkweightsarenottakenintoaccount.
nw:page-rank
nw:page-rank
Thepagerankofanodecanbethoughtofastheproportionoftimethatanagentwalkingforeveratrandomonthenetworkwouldspendatthisnode.Theagenthasanequalchanceoftakinganyofanodesedges,andwilljumparoundthenetworkcompletelyrandomly15%ofthetime.Inpractice,likewitheigenvectorcentrality,turtlesthatareconnectedtoalotofotherturtlesthatarethemselveswell-connected(andsoon)getahigherpagerank.
Pagerankisoneoftheseveralalgorithmsthatsearchenginesusetodeterminetheimportanceofawebsite.
Thesumofallpagerankvaluesshouldbeapproximatelyone.Unlikeeigenvectorcentrality,pagerankisdefinedforallnetworks,nomattertheconnectivity.Currently,ittreatsalllinksasundirectedlinks.
Asofnow,linkweightsarenottakenintoaccount.
nw:closeness-centrality
nw:closeness-centrality
Theclosenesscentralityofaturtleisdefinedastheinverseoftheaverageofit’sdistancestoallotherturtles.(Somepeopleusethesumofdistancesinsteadoftheaverage,buttheextensionusestheaverage.)
Notethatthisprimitivereportstheintra-componentclosenessofaturtle,thatis,ittakesintoaccountonlythedistancestotheturtlesthatarepartofthesamecomponentasthecurrentturtle,sincedistancetoturtlesinothercomponentsisundefined.Theclosenesscentralityofanisolatedturtleisdefinedtobezero.
nw:weighted-closeness-centrality
nw:weighted-closeness-centralitylink-weight-variable
Thisisidenticaltonw:closeness-centrality,exceptthatweightsprovidedbythegivenvariablearetreatedasthedistancesoflinks.
nw:clustering-coefficient
nw:clustering-coefficient
Reportsthelocalclusteringcoefficientoftheturtle.Theclusteringcoefficientofanodemeasureshowconnecteditsneighborsare.Itisdefinedasthenumberoflinksbetweenthenode’sneighborsdividedbythetotalnumberofpossiblelinksbetweenitsneighbors.
![Page 308: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/308.jpg)
nw:clustering-coefficienttakesthedirectednessoflinksintoaccount.Adirectedlinkcountsasasinglelinkwhereasanundirectedlinkcountsastwolinks(onegoingone-way,onegoingtheother).
Theglobalclusteringcoefficientmeasureshowmuchnodestendtoclustertogetherinthenetworkingeneral.Itisdefinedbasedonthetypesoftripletsinthenetwork.Atripletconsistsofacentralnodeandtwoofitsneighbors.Ifitsneighborsarealsoconnected,it’saclosedtriplet.Ifitsneighborsarenotconnected,it’sanopentriplet.Theglobalclusteringcoefficientissimplythenumberofclosedtripletsinanetworkdividedbythetotalnumberoftriplets.Itcanbecalculatedfromthelocalclusteringcoefficientquiteeasilywiththefollowingcode
to-report global-clustering-coefficient let closed-triplets sum [ nw:clustering-coefficient * count my-links * (count my-links - 1) ] of turtles let triplets sum [ count my-links * (count my-links - 1) ] of turtles report closed-triplets / tripletsend
Notethattheabovewillonlyworkwiththedefaultcontext,andmayneedtotweakedifyou’vesettheturtlesorlinksinthenetworktosomethingotherthanturtlesandlinks.
Theaveragelocalclusteringcoefficientisanotherpopularmethodformeasuringtheamountofclusteringinthenetworkasawhole.Itmaybecalculatedwith
mean [ nw:clustering-coefficient ] of turtles
nw:modularity
nw:modularity
Modularityisameasurementofcommunitystructureinthenetwork.Itisdefinedbasedonthenumberofin-communitylinksversusthenumberofbetween-communitylinks.Thisprimitivetakesasinputalistofagentsets,whereeachoftheagentsetsisonethecommunitiesthatyou’reseparatingthenetworkinto.
Thismeasurementworksonundirected,directed,andmixed-directednessnetworks.Inthecaseofmixed-directedness,undirectedlinksaretreatedessentiallythesameastwoopposingdirectedlinks.Itdoesnottakeweightintoaccount.
Example:
nw:modularity (list (turtles with [ color = blue ]) (turtles with [ color = red ]))
nw:bicomponent-clusters
nw:bicomponent-clusters
Reportsthelistofbicomponentclustersinthecurrentnetworkcontext.Abicomponent(alsoknownasamaximalbiconnectedsubgraph)isapartofanetworkthatcannotbedisconnectedbyremovingonlyonenode(i.e.youneedtoremoveatleasttwotodisconnectit).Theresultisreportedasalistofagentsets,inrandomorder.Notethatoneturtlecanbeamemberofmorethanonebicomponentatonce.
nw:weak-component-clusters
nw:weak-component-clusters
Reportsthelistof“weakly”connectedcomponentsinthecurrentnetworkcontext.Aweaklyconnectedcomponentissimplyagroupofnodeswherethereisapathfromeachnodetoeveryothernode.A“strongly”connectedcomponentwouldbeonewherethereisadirectedpathfromeachnodetoeveryother.Theextensiondoesnotsupporttheidentificationofstronglyconnectedcomponentsatthemoment.
Theresultisreportedasalistofagentsets,inrandomorder.Notethatoneturtlecannotbeamemberofmorethanoneweaklyconnectedcomponentatonce.
nw:louvain-communities
nw:louvain-communities
Detectscommunitystructurepresentinthenetwork.ItdoesthisbymaximizingmodularityusingtheLouvainmethod.Thecommunitiesarereportedasalistofturtle-sets.
![Page 309: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/309.jpg)
Oftenyou’llwanttotellturtlesaboutthecommunitythattheyarein.Youcandothislikeso:
turtles-own [ community ]
...
foreach ls:louvain-communities [ [comm] -> ask comm [ set community comm ]]
Youcangiveeachcommunityitsowncolorwithsomethinglikethis:
let communities ls:louvain-communitieslet colors sublist 0 (length communities) base-colors(foreach communities colors [ [community col] -> ask community [ set color col ]])
nw:maximal-cliques
nw:maximal-cliques
Acliqueisasubsetofanetworkinwhicheverynodehasadirectlinktoeveryothernode.Amaximalcliqueisacliquethatisnot,itself,containedinabiggerclique.
Theresultisreportedasalistofagentsets,inrandomorder.Notethatoneturtlecanbeamemberofmorethanonemaximalcliqueatonce.
TheprimitiveusestheBron–Kerboschalgorithmandonlyworkswithundirectedlinks.
nw:biggest-maximal-cliques
nw:biggest-maximal-cliques
Thebiggestmaximalcliquesare,asthenameimplies,thebiggestcliquesinthecurrentcontext.Often,morethanonecliquearetiedforthetitleofbiggestclique,sotheresultisreportedasalistofagentsets,inrandomorder.Ifyouwantonlyoneclique,useone-of nw:biggest-maximal-cliques.
TheprimitiveusestheBron–Kerboschalgorithmandonlyworkswithundirectedlinks.
nw:generate-preferential-attachment
nw:generate-preferential-attachmentturtle-breedlink-breednum-nodesoptional-command-block
GeneratesanewnetworkusingtheBarabási–Albertalgorithm.Thisnetworkwillhavethepropertyofbeing“scalefree”:thedistributionofdegrees(i.e.thenumberoflinksforeachturtle)shouldfollowapowerlaw.
Inthisversionoftheprimitive,turtlesareadded,onebyone,eachformingonelinktoapreviouslyaddedturtle,untilnum-nodesisreached.Themorelinksaturtlealreadyhas,thegreatertheprobabilitythatnewturtlesformlinkswithitwhentheyareadded.Futureversionsoftheprimitivemightprovidemoreflexibilityinthewaythenetworkisgenerated.
Ifyouspecifyanoptional-command-block,itisexecutedforeachturtleinthenewlycreatednetwork.Forexample:
nw:generate-preferential-attachment turtles links 100 [ set color red ]
nw:generate-random
nw:generate-randomturtle-breedlink-breednum-nodesconnection-probabilityoptional-command-block
Generatesanewrandomnetworkofnum-nodesturtlesinwhicheachonehasaconnection-probability(between0and1)ofbeingconnectedtoeachotherturtles.ThealgorithmusestheG(n,p)variantoftheErdős–Rényimodel.
ThealgorithmisO(n²)fordirectednetworksandO(n²/2)forundirectednetworks,sogeneratingmorethanacouplethousandnodeswilllikelytakeaverylongtime.
Ifyouspecifyanoptional-command-block,itisexecutedforeachturtleinthenewlycreatednetwork.Forexample:
![Page 310: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/310.jpg)
nw:generate-random turtles links 100 0.5 [ set color red ]
nw:generate-watts-strogatz
nw:generate-watts-strogatzturtle-breedlink-breednum-nodesneighborhood-sizerewire-probabilityoptional-command-block
GeneratesanewWatts-Strogatzsmall-worldnetwork.
Thealgorithmbeginsbycreatingaringofnodes,whereeachnodeisconnectedtoneighborhood-sizenodesoneitherside.Then,eachlinkisrewiredwithprobabilityrewire-prob.
Ifyouspecifyanoptional-command-block,itisexecutedforeachturtleinthenewlycreatednetwork.Furthermore,theturtlesaregeneratedintheordertheyappearasincreate-ordered-turtles.So,inordertolaytheringoutasaring,youcandosomethinglike:
nw:generate-watts-strogatz turtles links 50 2 0.1 [ fd 10 ]
nw:generate-small-world
nw:generate-small-worldturtle-breedlink-breedrow-countcolumn-countclustering-exponentis-toroidaloptional-command-block
Generatesanewsmall-worldnetworkusingtheKleinbergModel.Notethatnw:generate-watts-strogatzgeneratesamoretraditionalsmall-worldnetwork.
Thealgorithmproceedsbygeneratingalatticeofthegivennumberofrowsandcolumns(thelatticewillwraparounditselfifis-toroidalistrue).The“smallworldeffect”iscreatedbyaddingadditionallinksbetweenthenodesinthelattice.Thehighertheclustering-exponent,themorethealgorithmwillfavoralreadyclose-bynodeswhenaddingnewlinks.Aclusteringexponentof2.0istypicallyused.
Ifyouspecifyanoptional-command-block,itisexecutedforeachturtleinthenewlycreatednetwork.Forexample:
nw:generate-small-world turtles links 10 10 2.0 false [ set color red ]
Theturtlesaregeneratedintheorderthattheyappearinthelattice.So,forinstance,togenerateakleinberglatticeaccrosstheentireworld,andlayitoutaccordingly,trythefollowing:
nw:generate-small-world turtles links world-width world-height 2.0 false(foreach (sort turtles) (sort patches) [ [t p] -> ask t [ move-to p ] ])
nw:generate-lattice-2d
nw:generate-lattice-2dturtle-breedlink-breedrow-countcolumn-countis-toroidaloptional-command-block
Generatesanew2Dlatticenetwork(basically,agrid)ofrow-countrowsandcolumn-countcolumns.Thegridwillwraparounditselfifis-toroidalistrue.
Ifyouspecifyanoptional-command-block,itisexecutedforeachturtleinthenewlycreatednetwork.Forexample:
nw:generate-lattice-2d turtles links 10 10 false [ set color red ]
Theturtlesaregeneratedintheorderthattheyappearinthelattice.So,forinstance,togeneratealatticeaccrosstheentireworld,andlayitoutaccordingly,trythefollowing:
nw:generate-lattice-2d turtles links world-width world-height false(foreach (sort turtles) (sort patches) [ [t p] -> ask t [ move-to p ] ])
nw:generate-ring
nw:generate-ringturtle-breedlink-breednum-nodesoptional-command-block
Generatesaringnetworkofnum-nodesturtles,inwhicheachturtleisconnectedtoexactlytwootherturtles.
![Page 311: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/311.jpg)
Thenumberofnodesmustbeatleastthree.
Ifyouspecifyanoptional-command-block,itisexecutedforeachturtleinthenewlycreatednetwork.Forexample:
nw:generate-ring turtles links 100 [ set color red ]
nw:generate-star
nw:generate-starturtle-breedlink-breednum-nodesoptional-command-block
Generatesastarnetworkinwhichthereisonecentralturtleandeveryotherturtleisconnectedonlytothiscentralnode.Thenumberofturtlescanbeaslowasone,butitwon’tlookmuchlikeastar.
Ifyouspecifyanoptional-command-block,itisexecutedforeachturtleinthenewlycreatednetwork.Forexample:
nw:generate-star turtles links 100 [ set color red ]
nw:generate-wheel
nw:generate-wheelturtle-breedlink-breednum-nodesoptional-command-block
Variants:
nw:generate-wheel-inwardnw:generate-wheel-outward
Generatesawheelnetwork,whichisbasicallyaringnetworkwithanadditional“central”turtlethatisconnectedtoeveryotherturtle.
Thenumberofnodesmustbeatleastfour.
Thenw:generate-wheelonlyworkswithundirectedlinkbreeds.Thenw:generate-wheel-inwardandnw:generate-wheel-outwardversionsonlyworkwithdirectedlink-breed.Theinwardandoutwardpartoftheprimitivenamesrefertothedirectionthatthe“spokes”ofthewheelpointtorelativetothecentralturtle.
Ifyouspecifyanoptional-command-block,itisexecutedforeachturtleinthenewlycreatednetwork.Forexample:
nw:generate-wheel turtles links 100 [ set color red ]
nw:save-matrix
nw:save-matrixfile-name
Savesthecurrentnetwork,asdefinedbynw:set-context,tofile-name,asatextfile,intheformofasimpleconnectionmatrix.
Hereis,forexample,aundirectedringnetworkwithfournodes:
0.00 1.00 0.00 1.001.00 0.00 1.00 0.000.00 1.00 0.00 1.001.00 0.00 1.00 0.00
Andhereisthedirectedversion:
0.00 1.00 0.00 0.000.00 0.00 1.00 0.000.00 0.00 0.00 1.001.00 0.00 0.00 0.00
Atthemoment,nw:save-matrixdoesnotsupportlinkweights.Everylinkisrepresentedasa“1.00”intheconnectionmatrix.Thiswillchangeinafutureversionoftheextension.
nw:load-matrix
nw:load-matrixfile-nameoptional-command-block
![Page 312: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/312.jpg)
Generatesanewnetworkaccordingtotheconnectionmatrixsavedinfile-name,usingturtle-breedandlink-breedtocreatethenewturtlesandlinks.
Atthemoment,nw:load-matrixdoesnotsupportlinkweights.
Pleasebeawarethatthebreedsthatuseusetoloadthematrixmaybedifferentfromthosethatyouusedwhenyousavedit.
Forexample:
extensions [ nw ]directed-link-breed [ dirlinks dirlink ]to go clear-all crt 5 [ create-dirlinks-to other turtles ] nw:set-context turtles dirlinks nw:save-matrix "matrix.txt" clear-all nw:load-matrix "matrix.txt" turtles links layout-circle turtles 10end
…willgiveyoubackundirectedlinks,evenifyousaveddirectedlinksintothematrix.
Ifyouspecifyanoptional-command-block,itisexecutedforeachturtleinthenewlycreatednetwork.Forexample:
nw:load-matrix "matrix.txt" turtles links [ set color red ]
nw:save-graphml
nw:save-graphmlfile-name
YoucansavethecurrentgraphtoGraphML.ThefollowingNetLogocode:
extensions [ nw ]
breed [ bankers banker ]bankers-own [ bank-name ]breed [ clients client ]clients-own [ hometown ]
undirected-link-breed [ friendships friendship ]
directed-link-breed [ accounts account ]accounts-own [ amount ]
to go clear-all create-bankers 1 [ set bank-name "The Bank" ] create-clients 1 [ set hometown "Turtle City" create-friendship-with banker 0 create-account-to banker 0 [ set amount 9999.99 ] ] nw:set-context turtles links nw:save-graphml "example.graphml"end
WillproducethefollowingGraphMLfile:
<?xml version="1.0" encoding="UTF-8"?><graphml xmlns="http://graphml.graphdrawing.org/xmlns/graphml"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns/graphml"><key id="PEN-MODE" for="node" attr.name="PEN-MODE" attr.type="string"/><key id="YCOR" for="node" attr.name="YCOR" attr.type="double"/><key id="PEN-SIZE" for="node" attr.name="PEN-SIZE" attr.type="double"/><key id="LABEL" for="node" attr.name="LABEL" attr.type="string"/><key id="SHAPE" for="node" attr.name="SHAPE" attr.type="string"/><key id="BREED" for="node" attr.name="BREED" attr.type="string"/><key id="WHO" for="node" attr.name="WHO" attr.type="double"/><key id="HIDDEN?" for="node" attr.name="HIDDEN?" attr.type="boolean"/><key id="LABEL-COLOR" for="node" attr.name="LABEL-COLOR" attr.type="double"/><key id="HEADING" for="node" attr.name="HEADING" attr.type="double"/><key id="BANK-NAME" for="node" attr.name="BANK-NAME" attr.type="string"/><key id="HOMETOWN" for="node" attr.name="HOMETOWN" attr.type="string"/><key id="COLOR" for="node" attr.name="COLOR" attr.type="double"/><key id="XCOR" for="node" attr.name="XCOR" attr.type="double"/>
![Page 313: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/313.jpg)
<key id="SIZE" for="node" attr.name="SIZE" attr.type="double"/><key id="END1" for="edge" attr.name="END1" attr.type="string"/><key id="TIE-MODE" for="edge" attr.name="TIE-MODE" attr.type="string"/><key id="END2" for="edge" attr.name="END2" attr.type="string"/><key id="LABEL-COLOR" for="edge" attr.name="LABEL-COLOR" attr.type="double"/><key id="THICKNESS" for="edge" attr.name="THICKNESS" attr.type="double"/><key id="LABEL" for="edge" attr.name="LABEL" attr.type="string"/><key id="SHAPE" for="edge" attr.name="SHAPE" attr.type="string"/><key id="BREED" for="edge" attr.name="BREED" attr.type="string"/><key id="COLOR" for="edge" attr.name="COLOR" attr.type="double"/><key id="AMOUNT" for="edge" attr.name="AMOUNT" attr.type="double"/><key id="HIDDEN?" for="edge" attr.name="HIDDEN?" attr.type="boolean"/><graph edgedefault="undirected"><node id="client 1"><data key="PEN-MODE">up</data><data key="YCOR">0</data><data key="PEN-SIZE">1</data><data key="LABEL"></data><data key="SHAPE">default</data><data key="BREED">clients</data><data key="WHO">1</data><data key="HIDDEN?">false</data><data key="LABEL-COLOR">9.9</data><data key="HEADING">356</data><data key="HOMETOWN">Turtle City</data><data key="COLOR">115</data><data key="XCOR">0</data><data key="SIZE">1</data></node><node id="banker 0"><data key="PEN-MODE">up</data><data key="YCOR">0</data><data key="PEN-SIZE">1</data><data key="LABEL"></data><data key="SHAPE">default</data><data key="BREED">bankers</data><data key="WHO">0</data><data key="HIDDEN?">false</data><data key="LABEL-COLOR">9.9</data><data key="HEADING">32</data><data key="BANK-NAME">The Bank</data><data key="COLOR">85</data><data key="XCOR">0</data><data key="SIZE">1</data></node><edge source="client 1" target="banker 0"><data key="END1">(client 1)</data><data key="TIE-MODE">none</data><data key="END2">(banker 0)</data><data key="LABEL-COLOR">9.9</data><data key="THICKNESS">0</data><data key="LABEL"></data><data key="SHAPE">default</data><data key="BREED">accounts</data><data key="COLOR">5</data><data key="AMOUNT">9999.99</data><data key="HIDDEN?">false</data></edge><edge source="banker 0" target="client 1"><data key="END1">(banker 0)</data><data key="TIE-MODE">none</data><data key="END2">(client 1)</data><data key="LABEL-COLOR">9.9</data><data key="THICKNESS">0</data><data key="LABEL"></data><data key="SHAPE">default</data><data key="BREED">friendships</data><data key="COLOR">5</data><data key="HIDDEN?">false</data></edge></graph></graphml>
Afewthingstonotice:
Thebreedisstoredasdatafield,bothfornodesandedges.ThedataincludesbothNetLogo’sinternalvariablesandthevariablesthatweredefinedaseitherbreeds-own,turtles-own,linkbreeds-ownorlinks-own.Eachkeygetsanattr.typebasedontheactualtypesofthevaluescontainedintheagentvariables.Thethreepossibletypesare"string","double"and"boolean".Todeterminetheattributetypeofaparticularagentvariable,theextensionwilllookatthefirstagentinthegraph.Toseewhichagentisfirst,youcanlookattheresultofnw:get-context.Notethatvariablescontainingothertypesofvalues,suchasturtles,patches,lists,etc.,willbestoredasstrings.Thisexampleonlyhasadirectedlink,andyouwillnoticethe<graph edgedefault="directed">element.Ifwehadonlyundirectedlinks,wewouldhave<graph edgedefault="undirected">.Whatifwetrytomixbothkindsoflink?Atthemoment,theextensionwillsavesucha“mixed”graphasifitwereanundirectedgraph(seethisissueformoredetails).Theorderofthesourceandtargetwillberespected,however,soifyouknowwhichbreedsrepresentdirectedlinks,youcanfigureitoutaposteriori.
nw:load-graphml
![Page 314: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/314.jpg)
nw:load-graphmlfile-nameoptional-command-block
LoadingaGraphMLfileintoNetLogowiththenetworkextensionshouldbeassimpleascallingnw:load-graphml"example.graphml",butthereisabitofpreparationinvolved.
Thekeyideaisthatnw:load-graphmlwilltrytoassigntheattributevaluesdefinedintheGraphMLfiletoNetLogoagentvariablesofthesamenames(thisisnotcasesensitive).Thefirstoneittriestosetisbreedifitisthere,sotheturtleorlinkwillgettherightbreedand,hence,therightbreedvariables.
Onespecialcaseisthewhonumber,whichisignoredbytheimporterifitispresentasaGraphMLattribute:NetLogodoesnotallowyoutomodifythisnumberonceaturtleiscreatedand,besides,therecouldalreadybeanexistingturtlewiththatnumber.
ThesimplestcasetohandleiswhentheoriginalGraphMLfilehasbeensavedfromNetLogobyusingnw:save-graphml.Inthiscase,allyoushouldhavetodoistomakesurethatyouhavethesamebreedandvariablesdefinitionaswhenyousavedthefileandyoushouldgetbackyouroriginalgraph.Forexample,ifyouwanttoloadthefilefromthenw:save-graphmlexampleabove,youshouldhavethefollowingdefinitions:
breed [ bankers banker ]bankers-own [ bank-name ]breed [ clients client ]clients-own [ hometown ]
undirected-link-breed [ friendships friendship ]
directed-link-breed [ accounts account ]accounts-own [ amount ]
LoadingagraphthatwassavedfromadifferentprogramthanNetLogoisquitepossibleaswell,butitmaytakeabitoftinkeringtogetalltheattribute-variablematchupright.Ifyouencountermajorproblems,pleasedonothesitatetoopenanissue.
Theextensionwilltrytoassignthetypedefinedbyattr.typetoeachvariablethatitloads.Ifit’sunabletoconvertittothattype,itwillloaditasastring.Ifattr.typeisnotdefined,orissettoanunknownvalue,theextensionwillfirsttrytoloadthevalueasadouble,thentryitasaboolean,andfinallyfallbackonastring.
Ifyouspecifyanoptional-command-block,itisexecutedforeachturtleinthenewlycreatednetwork.Forexample:
nw:load-graphml "example.graphml" [ set color red ]
Notethatthiscommandblockcanbeusedtobuildalistoranagentsetcontainingthenewlycreatednodes:
let node-list []nw:load-graphml "example.graphml" [ set node-list lput self node-list]let node-set turtle-set node-list
nw:load
nw:loadfile-namedefault-turtle-breeddefault-link-breedoptional-command-block
Filetypespecificvariants:
nw:loadnw:load-dlnw:load-gdfnw:load-gexfnw:load-gmlnw:load-vna
ImportthegivenfileintoNetLogo.Likenw:load-graphml,theimporterwilldoitsbesttomatchnodeandedgeattributesinthefilewithturtleandlinkvariablesinNetLogo.IfbreedisspecifiedfornodesandedgesinthefileandexistsinNetLogo,itwillbeused.Otherwise,thedefaultturtleandlinkbreedsareused.
Limitations:
Multigraphsarenotsupportedinimporting.Evenifthefileformatsupportsit(andmanydon’t),onlythefirstlinkwillbeusedonimport.ThisisduetoalimitationintheparsinglibrariesNWuses.nw:load-graphmldoessupportmultigraphswiththenormalNetLogolimitationthattwoturtlescansharemorethanonelinkonlyifallthelinksareofdifferentbreeds.
![Page 315: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/315.jpg)
nw:loaddeterminesthefile-typeofgivenfilebasedontheextensionandcallsthecorrespondingload-*primitiveonit.NotethatGraphMLmustbeimportedwithnw:load-graphml.
nw:save
nw:savefile-name
Filetypespecificvariants:
nw:save-dlnw:save-gdfnw:save-gexfnw:save-gmlnw:save-vna
Exportthenetworkcontextinthegivenformattothegivenfile.Turtleandlinkattributeswillbeexportedtoformatsthatsupportnodeandedgeproperties.
Limitations:
xandy(notxcorandycor)canonlybenumbers.xandyarecommonlyusedinformatspertainingtopositionandbehindthescenesNWusesGephi’slibrariesforexporting.Furthermore,xandywillbeaddedeveniftheydidn’texistinthemodel.Again,thisisbecauseNWusesGephi’slibrarieswhichassumethatnodeshavepositionsstoredinxandy.IfyouwishtoexporttoGephispecifically,werecommendcreatingxandyturtlesvariablesandsettingthemtoxcorandycorbeforeexport.ColorwillbeexportedinastandardRGBformat.Thisshouldhopefullyincreasecompatibilitywithotherprograms.Turtleandlinkvariablesthatcontainvaluesofdifferenttypeswillbestoredasstrings.Unfortunately,mostnetworkformatsrequirethatnodeandattributeshaveasingletype.Manyprogramsuselabeltostoretheidofnodes.Thus,ifyou’rehavingtroubleimportingdataexportedfromNetLogointoanotherprogram,youmighttrysettingturtles’labelstotheirwhonumber.Multigraphsarenotsupported.Thus,twoturtlescanshareatmostonelink.nw:save-graphmldoessupportmultigraphs,sousethatifturtlescanhavemorethanonetypeoflinkconnectingthem.
nw:savedeterminesthefile-typeofthegivenfilebasedontheextensionandcallsthecorrespondingsave-*primitiveonit.NotethatGraphMLmustbeexportedwithnw:save-graphml.
![Page 316: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/316.jpg)
NetLogoPaletteExtension
UsingthePaletteExtension
TheNetLogopaletteextensionallowstomapvaluestocolors.ThecolorsgobeyondNetLogocolors,includingColorBrewercolorschemesorarbitraryRGBcolors.Additionally,itprovidesaprimitivetomaptocolorgradientsandaprimitivetolaunchaColorBrewerdialogforeasyschemeselection.
GettingStarted
TogetstartedwithpalettesaddtothetopofyourCodetab:
extensions [palette]
youcanthencallanyoftheprimitivesbyaddingpalette:beforetheprimitive:
palette:scale-gradientpalette:scale-scheme
palette:scheme-colorpalette:scheme-dialog
ThepaletteextensionprimitivesreturnalistcontainingRGBcolors[[r g b][r g b]...[r g b]] ,exceptforpalette:scheme-dialogwhichopensadialog.
WhatcolorsshouldIuse?
ColorBrewerhasmanycolorswheretostart.ColorBrewerhasthreeschemesSequential,DivergentandQualitative.TheuseofColorBrewerformapsisdiscussedatlengthinthispaper(Harrower,Brewer2003).Choosingtherightcolorsisadesignproblem,thus,therearemanyacceptablesolution.However,theseguidelinesmightbeusefulforchoosingcolorsinAgentBasedModels:
Sequentialcolorsarebestforcontinuousnaturalphenomenamodelssuchasasheatdiffusioninphysicsorfireinearthsciences.Divergentcolorsareusefulforhighlightingamiddlevalueinamodel.Itcanbealsoappliedtotheheatdiffusionmodelifthegoalistohighlightthemiddletemperature.Qualitativecolorsarebestforchoosingcolorsinmodelswherecolordenotescategoryandnotvalue.Foragentsthatcoverlargeareasavoidstrongcolorsandtrytousepastelcolors.However,foralownumberofsmallisolatedagentstrytousestrongcolorssuchassuchaaccent.Themaingoalistoavoidhavingalargeareacoveredwithagentswithabrightcolorandorhavingsmallareashavingamutedpastelcolor.Ifyouarecoloringbothturtlesandpatches,makesuretheyhavedifferentrangesofhue,saturationandvalue.E.g.Usedifferenthuesofpastelforpatchesandaccentforturtles
ShouldIuseacontinuouscolorgradientorjustadiscretecolorset?
Theanswerdependsonthetaskthatyourwillbeaskingfromyouruser.
Forexample,gradientsaremoreaestheticthusaremorememorablethandiscretecolors.Consequently,agradientcanbeabetterchoiceforpresentationswherethemaingoaloftheimageistobeattractiveandmemorable.However,binningvaluesinadiscretesetofcolorssimplifiestaskssuchasestimationandcountingbyremovingunnecessarydetailtodisplaythebigpicture.Thus,discretecolorscanbeabetterchoiceforapaperwheretheuserwillhavethetimeandinteresttostudythevisualization.
InordertoseethedifferenceyoucanturnonandoffthegradientintheHeatDiffusionmodel.Youcanobservethatturninggradientonmakesthemodelmoreaesthetic,butitbecomeshardertoestimatethevalueofapatchatagivenposition.
ExampleModels
ThereisanexampleofusingthepaletteprimitivesintheCodeExamplessectionofthemodelslibrary:
PaletteExample
AndoneSampleModelthatusestheextension:
HeatDiffusion-AlternativeGradient
FurtherReading
![Page 317: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/317.jpg)
BesuretochecktheColorBrewerwebpageTogetadeeperunderstandingofhowtousethecolorschemesreadtheColorBrewerpaper(Harrower,Brewer2003)
Primitives
palette:scale-gradientpalette:scale-schemepalette:scheme-colorspalette:scale-gradient
palette:scale-gradient
palette:scale-gradientrgb-color-listnumberrange1range2
ReportsanRGBcolorproportionaltonumberusingagradientgeneratedwithrgb-color-list.Anrgb-color-listconsistofalistcontainingRGBlistwiththreevaluesbetween0and255:[[r1g1b1][r2g2b2][r3g3b3]…]
Ifrange1islessthanrange2,thecolorwillbedirectlymappedtogradientcolors.While,ifrange2islessthanrange1,thecolorgradientisinverted.
Ifnumberislessthanrange1,thenthefirstcolorofisRGB-color-listischosen.
Ifnumberisgraterthanrange2,thenthelastcolorofisRGB-color-listischosen.
Example:
ask patches[ set pcolor palette:scale-gradient [[255 0 0] [0 0 255]] pxcor min-pxcor max-pxcor]
;; colors each patch with a color proportional to the gradient
palette:scale-scheme
palette:scale-schemescheme-typescheme-colornumber-of-classesrange1range2
ReportsanRGBcolorproportionaltonumberusingthecolorbrewerschemes.IttakessixargumentsthefirstthreeargumentsdefinetheColorBrewerlegend.Firtheusershouldselectascheme-typewhichcanbe“Sequential”,“Divergent,Qualitative”.Thenitshouldselectavarietyofscheme-colorswhichdependingonthescheme-colorcanhavenamessuchas“Reds”,“Divergent”,“Set1”.Finallytheusershouldselectthenumberofclasseswithaminimumof3andamaximumbetween9and11.Formoreinformationgotohttp://www.colorbrewer.orgorconsultthescheme-dialogprimitive.
Ifrange1islessthanrange2,thecolorwillbedirectlymappedtoschemecolors.While,ifrange2islessthanrange1,thecolorschemeselectionisinverted.
Ifnumberislessthanrange1,thenthefirstcoloroftheresultingColorBrewerlegendischosen.
Ifnumberisgraterthanrange2,thenthelastcoloroftheresultingColorBrewerlegendischosen.
Example:
ask patches[ set pcolor palette:scale-scheme [[255 0 0] [0 0 255]] pxcor min-pxcor max-pxcor]
;; colors each patch with a color from the Color Brewer Schemes
palette:scheme-colors
palette:scheme-colorsscheme-typescheme-colornumber-of-classes
reportalistofRGBcolorswiththesizespecifiedintheanumberofclasses
Example:
show palette:scheme-colors "Divergent" "Spectral" 3=> [[252 141 89] [255 255 191] [153 213 148]]
; The schemes-color primitive can be used with the scale-gradient primitiveask patches [set pcolor palette:scale-gradient palette:scheme-colors "Divergent" "Spectral" 9 pxcor min-pxcor max-pxcor]
![Page 318: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/318.jpg)
palette:scale-gradient
palette:scale-gradientrgb-color-listnumberrange1range2
ReportsanRGBcolorproportionaltonumberusingagradientgeneratedwithrgb-color-list.Anrgb-color-listconsistofalistcontainingRGBlistwiththreevaluesbetween0and255:[[r1g1b1][r2g2b2][r3g3b3]…]
Ifrange1islessthanrange2,thecolorwillbedirectlymappedtogradientcolors.While,ifrange2islessthanrange1,thecolorgradientisinverted.
Ifnumberislessthanrange1,thenthefirstcolorofisRGB-color-listischosen.
Ifnumberisgraterthanrange2,thenthelastcolorofisRGB-color-listischosen.
Example:
ask patches[ set pcolor palette:scale-gradient [[255 0 0] [0 0 255]] pxcor min-pxcor max-pxcor]
;; colors each patch with a color proportional to the gradient
References
ColorBrewerwww.colorbrewer.org
HARROWER,M.andC.BREWER(2003).ColorBrewer:Anonlinetoolforselectingcolorschemesformaps.TheCartographicJournal40(1):27-37.)
HEALEY,CG(2006)PerceptioninVisualization,(comprehensivereviewupdatedregularly).
HEALEY,CG,BOOTHKS,andENNS,JT(1995).VisualizingReal-TimeMultivariateDataUsingPreattentiveProcessingACMTransactionsonModelingandComputerSimulation5,3,190-221.
TUFTE,E(1983)TheVisualDisplayofQuantitativeInformation,GraphicsPress.
WARE,C(2004)InformationVisualization,2ndEd.,MorganKaufmann.Feedback
![Page 319: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/319.jpg)
NetLogoProfilerExtension
UsingtheProfilerExtension
Ifyou’dlikeyourmodeltorunfaster,theprofilerextensionmaybeusefultoyou.Itincludesprimitivesthatmeasurehowmanytimestheproceduresinyourmodelarecalledduringarunandhowlongeachcalltakes.Youcanusethisinformationtowheretofocusyourspeedupefforts.
Caution:
Theprofilerextensionisexperimental.Itisnotyetwelltestedoruserfriendly.Nonetheless,wethinksomeuserswillfindituseful.
Howtouse
Theprofilerextensioncomespreinstalled.Tousetheextensioninyourmodel,addalinetothetopofyourCodetab:
extensions [profiler]
Ifyourmodelalreadyusesotherextensions,thenitalreadyhasanextensionslineinit,sojustaddprofilertothelist.
FormoreinformationonusingNetLogoextensions,seetheExtensionsGuide
Example
setup ;; set up the modelprofiler:start ;; start profilingrepeat 20 [ go ] ;; run something you want to measureprofiler:stop ;; stop profilingprint profiler:report ;; view the resultsprofiler:reset ;; clear the data
ThankstoRogerPeppeforhiscontributionstothecode.
Primitives
profiler:callsprofiler:exclusive-timeprofiler:inclusive-timeprofiler:startprofiler:stopprofiler:resetprofiler:report
profiler:calls
profiler:callsprocedure-name
Reportsthenumberoftimesthatprocedure-namewascalled.Ifprocedure-nameisnotdefined,thenreports0.
profiler:exclusive-time
![Page 320: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/320.jpg)
profiler:exclusive-timeprocedure-name
Reportstheexclusivetime,inmilliseconds,thatprocedure-namewasrunningfor.Exclusivetimeisthetimefromwhentheprocedurewasentered,untilitfinishes,butdoesnotincludeanytimespentinotheruser-definedprocedureswhichitcalls.
Ifprocedure-nameisnotdefined,thenreports0.
profiler:inclusive-time
profiler:inclusive-timeprocedure-name
Reportstheinclusivetime,inmilliseconds,thatprocedure-namewasrunningfor.Inclusivetimeisthetimefromwhentheprocedurewasentered,untilitfinishes.
Ifprocedure-nameisnotdefined,thenreports0.
profiler:start
profiler:start
Instructstheprofilertobeginrecordinguser-definedprocedurecalls.
profiler:stop
profiler:stop
Instructstheprofilertostoprecordinguser-definedprocedurecalls.
profiler:reset
profiler:reset
Instructstheprofilertoeraseallcollecteddata.
profiler:report
profiler:report
Reportsastringcontainingabreakdownofalluser-definedprocedurecalls.TheCallscolumncontainsthenumberoftimesauser-definedprocedurewascalled.TheInclT(ms)columnisthetotaltime,inmilliseconds,ittookforthecalltocomplete,includingthetimespentinotheruser-definedprocedures.TheExcl T(ms)columnisthetotaltime,inmilliseconds,spentwithinthatuser-definedprocedure,notcountingotheruser-defineproceduresitcalled.TheExcl/callscolumnisanestimateofthetime,inmilliseconds,spentinthatuser-definedprocedureforeachcall.
Hereisexampleoutput:
Sorted by Exclusive TimeName Calls Incl T(ms) Excl T(ms) Excl/calls
![Page 321: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/321.jpg)
CALLTHEM 13 26.066 19.476 1.498CALLME 13 6.413 6.413 0.493REPORTME 13 0.177 0.177 0.014
Sorted by Inclusive TimeName Calls Incl T(ms) Excl T(ms) Excl/callsCALLTHEM 13 26.066 19.476 1.498CALLME 13 6.413 6.413 0.493REPORTME 13 0.177 0.177 0.014
Sorted by Number of CallsName Calls Incl T(ms) Excl T(ms) Excl/callsCALLTHEM 13 26.066 19.476 1.498
![Page 322: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/322.jpg)
NetLogoRExtension
TheR-ExtensionofNetLogoprovidesprimitivestousethestatisticalsoftwareR(GnuS)(seetheRProjectwebsite)withinaNetLogomodel.ThereareprimitivestocreateR-VariableswithvaluesfromNetLogovariablesoragentsandotherstoevaluatecommandsinRwithandwithoutreturnvalues.
Using
Tousetheextensioninyourmodel,addalinetothetopofyourprocedurestab:
extensions [ r ]
Ifyourmodelalreadyusesotherextensions,thenitalreadyhasanextensionslineinit,sojustaddrtothelist.
FormoreinformationonusingNetLogoextensions,seetheExtensionsGuide.
ForexamplesoftheusageoftheR-Extension,modelscanbedownloadedfromtheprojectrepository.ThesemodelsareinstalledwithNetLogointhe“models”directoryoftheRextension.Pleasenotethat(asofNetLogo6.0)thesemodelsarenotincludedintheNetLogomodelslibrary.
SomeTips
Plotting
IfyouwanttousetheplotfunctionofR,youcouldactivatetheJavaGDplotdeviceviar:setPlotDevice,seethe“plot-example1.nlogo”model.Thisisthepreferedmethod!
ButyoucanalsousethestandardRdevice,butthen,youhavetogiveRsomecputime,e.g.byrunanevalulationofsys.sleep(0.01)withaforeverbutton.Seethe“plot-example2.nlogo”.(ManythankstoThomasPetzold!).Thecreationofplotsintofilesisalsopossible.Seethe“plot-into-file-example.nlogo”intheexamplesfolder.
LoadandSavedatafrom/intofile(s)
It’spossibletoloadandsavedatafromfiledirectlyinR.Thiscodesnippetillustrates:
r:eval "dataname <- read.table('<path to file>')" ; read filer:eval "write.table(dataname, file='<filename>')" ; write file
Data.framewithvectorincells
Normally,adata.framecellcontainsonlyasinglevalue.Eachcolumnisrepresentedasavectorandifyouwouldputavectorofvectorstoadata.frame,itwouldbesplittedintoseveralcolumns.WiththeR-Extensionitispossibletoputavectorintoadata.framecell,whenyouassignaNetLogoListtoacolumnwhichcontainsnestedNetLogoListsforeachrow.Ifyouwant,forexample,tousewrite.tableonthisdata.frame,youhavetomarkthiscolumnasclass="AsIs".YoucandothisbyusingtheI(x)-function.
Example:Ifthecolumnofinteresthasthename“col1”ofthedata.frame“df1”youcouldexecuter:eval "df1$col1 <-I(df1$col1)".Callhelp(I)fromwithinanRterminalforfurtherdetails.
LoadanR-Script
Furthermore,youcandefinefunctionsinanR-Script,loadit,andusethefunctions.LoadR-filesviar:eval "source('<pathto r-file>')".
LoadaPackage
It’salsopossibletoloadRpackagesviar:eval "library(<name of package>)".
Whenyoucompileyourcodecontainingextensions [r]youwillcreateanewRworkspace.Untilyoureloadtheextension,openanewmodelorsubmittheprimitive[r:clear](#rclear),allRvariablesassignedinthissessionwillbeavailablelikeyouwoulduseRfromthecommandlineorintheRConsole.
InteractiveShell
YoucanopenanInteractiveRShellviar:interactiveShell.ThisshellisaporttotheunderlayingRinstance.Thisshellworksontheglobalenvironment(seeEnvironmentsintheRExtensionbelow)whiletheextensionitselfworkonacustomlocalenvironment.Butthereisoneautomaticvariable“nl.env”intheglobalenvironment,whichisareferencetothelocalenvironmentoftheextension.Don’tdeletethisvariable!Youcanaccessavariablecreatedbytheextensionviaget("<variable name>",nl.env),forexamplemyvar <-get("myvar",nl.env).IfyouwanttoplotfromtheInteractiveShellyoushouldusetheincludedJavaGDplotdevice(see
![Page 323: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/323.jpg)
r:setPlotDevice).YoucansaveandloadthehistoryofenteredRcommandsviaaright-mousebuttoncontextmenu.
Pleasereadthenotesatthetopoftheoutputtextareaafteropeningtheshell!OnLinuxOSitcanhappenthatyouseeanerrormessagefromX11.Pleasecheck,ifeverythingworkedcorrecly.Ifso,youcanignorethesemessages.Ifnot,[email protected].
EnvironmentsIntheRExtension
WhenyouloadamodeltheR-ExtensioncreatesanewRenvironment.WhenyoucreateanRvariableusingtheR-Extension,thisvariableiscreatedinthelocalRenvironment.Furthermore,allcallsfromtheR-Extensionworkonthislocalenvironment.ThisnewenvironmentconceptenablesyoutousetheextensioninBehaviorSpaceExperiments.Therefore,youdon’thavetocareabouttheenvironmentwhileyou’renotusingtheInteractiveShellorothertools,whichworkontheglobalenvironment.Youcanexplicitlyassignavariabletotheglobalenvironmentbyusingthe<-operatororbyexecutingassign(<name>,<value>,envir=.GlobalEnv).IfyouworkwiththeInteractiveShell,seethenotesatthetopoftheoutputtextareaafteropeningtheshell.
Typehelp(environment)inanRshelltolearnmoreaboutenvironments.
Youcan/shouldclear(i.e.removeallvariableandfreememory)thelocalenvironmentvia[r:clearLocal](#rclearLocal).Ifyouwanttoclearalsotheglobalenvironment(thewholeworkspace),call[r:clear](#rclear).
Memory
WiththeR-ExtensionyoucanloadRintotheprocessofNetLogo.BecauseofthearchitectureofR,bothsoftwareshareonesystemprocessandthereforethememorygiventoNetLogo.
InsomecircumstancesitcanhappenthatyoureceiveanoutofmemoryerrorduetoJava’sheapspace.YoucanincreasetheheapspacebeforestartingNetLogobyadaptingthe-XmxJVM-parameter(seealsotheNetLogomanualsectiononWindowsmemory).Buton32-bitsystems,thisisverylimited.Therefore,itisagoodideatousea64-bitsystemifyouwant/needtousehighamountofRAM.YoucanseethememoryusageofRbystartingtheinteractiveshell(r:interactiveShell)andtypethere:memory.size(max=F)andmemory.size(max=T).Furthermore,youcancheckthememorylimitbytyping:memory.limit().Seealso:
Rmanualpageformemory.profileRmanualpageforobject.sizeRmanualpageformemory.size
Ifyoucallthegarbagecollectorintheinteractiveshellbytypinggc(),youwillgetsomeinformationaboutthecurrentmemoryusage(seealsohttp://stat.ethz.ch/R-manual/R-patched/library/base/html/gc.html).
Ifyoutypegc(nl.env)youwillseethepercentageofmemoryusedforconscellsandvectors.
Don’tforgettocallther:gcprimitiveafterremovinganRvariableanddon’tforgettoremoveRvariableyoudon’tneedanymore!Seehowthememoryusagechangesafterremovingvariableandcallingr:gc.
Ifyouusetoomuchmemory,itcanhappen,thatNetLogowillcloseabruptly.Insuchacase,checkifthereisawaytoreducethememoryused.Ifnot,trytoswitchovertotheRserve-extension.WiththeRserve-Extensionbothsoftware,NetLogoandR,runindependently.Thereis,ofcause,alsoalimitoftransferabledataamountwithonerequest,butitislessrestrictive.
Onelastnotetothistopic:KeepinmindthatRisavector-orientedlanguage.Preventmasscallswithsinglevalueswheneverpossibleandreplacethembyvectoroperations.Thisismuchfasterandmorestable.
Headless
SinceR-Extensionversion1.1itispossibleusetheextensionwhenNetLogoisrunninginheadlessmode.Thisisforexamplethecase,whenyourunBehaviorSpaceexperimentsfromthecommandline(seehere).Thedifferenceis,thattheinteractiveShellisnotinitialized/instanciated.YoucanusetheextensionasyouknowitfromGUImode,butitisnotpossibletoopentheinteractiveShell(r:interactiveShell)andtosettheplotdevice(r:setPlotDevice).Butoneadditionalthingshastobedone:Youhavetocallr:stopfinallywhenrunningNetLogoheadlesstostoptheRengine.OtherwiseNetLogowillnotbeclosedandyouwillnotgetbacktothecommandlineprompt.WhensettingupaBehaviorSpaceexperiment,thereistheoptiontosetfinalcommands.Thisisagoodplacetoaddther:stopcommand(seeimage).
![Page 324: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/324.jpg)
Installing
TheRExtensionisbundledwithNetLogo6.Touseit,youwillneedacompatibleRinstallationandyoumayneedtoconfiguretheextension.
InstallingR
StandardR3installationsshouldwork(sometimeswithoutconfiguration).AsofNetLogo6,thefollowingoperatingsystem/Rversionsweretested:
MacOSX,R3.3.2Windows10,R3.3.2Ubuntu14.04(64-bit),R3.0.2
OnceRisinstalled,youwillneedtoinstalltherJavapackage.CertainfeaturesoftheRextensionrelyontheJavaGDpackage.
Toinstall,starttheRGuifromyourprogramlist,clickontheitem“Packages”inthemenubarandthenon“InstallPackage(s)”.Selectyourfavoriteserverandfind“rJava”,aswellas“JavaGD”and/or“CommonJavaJars”(bothoptional)inthelistofpackages.
Ifyoupreferusingtheconsole,youcaninstallthesamepackagesbyrunningthefollowingcommandsintheconsole(andfollowingthepromptstheygenerate,asappropriate).
install.packages("rJava")install.packages("JavaGD") # Optionalinstall.packages("CommonJavaJars") # Optional
ConfiguringtheRextension
IfyouareusingLinuxorMacOSandoneoftheaboveRversions,youmaynotneedtoperformanyfurtherconfiguration.AneasywaytodeterminewhetheryouneedtoconfiguretheextensionittoopenanewNetLogomodel,addextensions [r ]tothecodetabandpress“Check.”Ifyouseeanerror,youneedtoconfiguretheRextension.TheRextensioncanbeconfiguredbyeditingthe“user.properties”fileinatexteditor(“user.properties”islocatedintherextensiondirectoryaspartoftheNetLogoinstallation).Thefollowingkeysareusedtoconfiguretheextension:
r.home:Controlswhichinstallationofrisused.jri.home.paths:ControlsthepathtothejrisubdirectoryoftherJavalibrary.
NotethatyouwillhavetoexitNetLogoandrestarttoseeconfigurationchangestakeeffect,astheconfigurationfileisonlyloadedonceperNetLogoinstance.Seebelowonhowtodeterminetheappropriatevaluestoforr.homeandjri.home.paths.
![Page 325: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/325.jpg)
ConfiguringtheWindowsPATH
WindowsrequiresanadditionalconfigurationsteptomaketheRextensionfullyfunctional.TheappropriatedirectoryfromyourRinstallationneedstobeaddedtoyourPATH.Todothis,determinewhereyourRinstallationislocated(herewe’llusethelocationC:\ProgramFiles\R\R-),thenfollowthesesteps.
1. OpentheSystemPropertiesdialog.Youcantype“EnvironmentVariable”intoCortanaornavigatetherethrough“ControlPanel”>System>“Advancedsystemsettings”.
2. Clickthe“Environmentvariables…”buttoninthelowerrightofthedialog.3. Clickthe“Path”variableinthelowerpanel,thenclickthelower“Edit…”button.4. Windows10allowsyoutochoose“New”andenteraseparatepath.Ifyou’reusingWindows7,appendthevalue,usinga
semicolontoseparateitfromtheentrybefore.
Ifyou’reusing32-bitNetLogo,enterthelocationC:\Program Files\R\R-<version>\bin\i386\Ifyou’reusing64-bitNetLogo,enterthelocationC:\Program Files\R\R-<version>\bin\x64\
1. ChooseOK,andOKagain2. LogoutofyouruserandbackinorrestartWindowstoletthesettingtakeaffect.
NotethatyouwillneedtoupdatethissettingifyouwishtoupgradetheversionofRusedbyNetLogo.
Notesonediting“user.properties”onWindows
“user.properties”isanewline-delimitedfile.Thismeansifitisopenedin“Notepad”itwilllooklikeallthetextisonasingleline.Forthisreason,itisrecommendedtoopenfirstin“WordPad”andresavebeforeeditinginNotepad.Alternatively,ifyouhaveafull-featuredtexteditor(likeNotepad++,Vim,orEmacs)installed,youcanusethattoeditthefile.
Toreiterateawarninggiveninthe“user.properties”file,thedirectoryseparatorforWindowsmustbeenteredinuser.propertiesasdouble-backslash(“\”)orsingle-forward-slash(“/”).
Determiningr.homeandjri.home.paths
r.homeisthepathtothe“R”installationdirectorywhichcontainsthe“bin”directory.Ifyou’rehavingtroublefindingthis,youcanrunR.home(component = "home") inR,orR RHOMEonthecommandline(ifRisonyourpath).
R.home(component = "home")# Returns "C:/PROGRA~1/R/R-33~1.2/bin/x64" on Windows.# Will return other results on other platforms or configurations
jri.home.pathsisalistofdirectoriestocheckforjri.It’sinthejridirectoryundertherJavalibraryinstallation.YoucanfindthejridirectoryintherJavapackagebyrunningthefollowinginR:
system.file("jri", package = "rJava")# Returns "C:/Users/username/Documents/R/win-library/3.3/rJava/jri" on Windows.# Will return other results on other platforms or configurations
Takethepathandedittheuser.propertiesfile,uncommentingandeditingonesetofr.homeandjri.home.pathstomatchthevaluesobtainedinR.Whenyou’redone,theuser.propertiesfileshouldhavethefollowinglines(giventheaboveresults):
r.home=C:/PROGRA~1/R/R-33~1.2/bin/x64jri.home.paths=C:/Users/username/Documents/R/win-library/3.3/rJava/jri
Saveuser.propertiesandloadamodelusingtheRextension.Youshouldseeitstartandrunproperly.
Primitives
r:clearr:clearLocalr:evalr:__evaldirectr:gcr:getr:interactiveShellr:putr:putagentr:putagentdfr:putdataframer:putlistr:putnamedlistr:setPlotDevicer:stop
r:clear
r:clear
ClearstheR-Workspace.AllvariablesinRwillbedeleted.ItevaluatestheRcommandrm(list=ls())andrm(list=ls(nl.env)).Thisdeletesvariablescreatedinglobalaswellaslocalenvironment(seeREnvironmentsfordetailsaboutenvironments).It’salwaysagoodideatoaddthiscommandtoyoursetupprocedureunderyour“clear-all”call.
;; clear the R workspacer:clear
![Page 326: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/326.jpg)
r:clearLocal
r:clearLocal
ItclearsthelocalRenvironment,whichisusedbytheextension.Allvariableswhichhavebeencreatedinthelocalenvironmentwillbedeleted.ItevaluatestheRcommandrm(list=ls(nl.env)).SeeREnvironmentsfordetailsaboutenvironments.Seer:clearfordeletingallvariables,i.e.theglobalsaswell.
;; delete the local variablesr:clearLocal
r:eval
r:evalR-command
ItevaluatesthesubmittedRcommand.TheRcommandshouldn’treturnavalue.
;; creates a new vector in R with a sequence from 1 to 10r:eval "x <- seq(1,10)"show r:get "x"
r:__evaldirect
r:__evaldirectR-command
EvaluatesthesubmittedRcommandintheglobalenvironment(notinthelocalenvironmentliker:evaldoes)andwithoutacheck(notusingtry-functioninternally).ThiscanbenecessaryforsomeRpackages,likegglopt2.Pleasenote,thatyoucanproducenameclasheswhencreatingnewvariablesusingthisprimitive.Thevariablewillbecreatedintotheglobalenvironmentandwillnotoverwritevariablewiththesamenamethathavebeencreatedintothelocalenvironment.Ifyourequestavariablewithr:getitwillsearchinthelocalenvironmentfirst.Therefore,iftherearevariableswiththesamenameinthelocalandtheglobalenvironment,itwillreportthevariablefromthelocalenvironmentandnotthevariablecreatedviar:__evaldirect.Ifthereisonlyavariablewiththerequestednameintheglobalenvironment,everythingwillbefine-r:getwillreportthevalueofthisvariable.Ifyouwanttoremoveavariablecreatedviar:__evaldirect,i.e.intheglobalenvironment,callr:eval "rm(myvar, envir=.GlobalEnv)",replacemyvarbythenameofyourvariable.TheRcommandshouldn’treturnavalue.Thisprimitiveisexperimental.
;; creates a new vector in R with a sequence from 1 to 10r:__evaldirect "x <- seq(1,10)"show r:get "x"
r:gc
r:gc
CallsthegarbagecollectorofJava(i.e.theR-Extension)andR.CallthisprimitiveafterremovinganRvariabletofreethememory.
;; create a variabler:eval "x <- 1:10";; remove the variabler:eval "rm(x)";; call the garbage collectorr:gc
r:get
r:getR-command
ReportsthereturnvalueofthesubmittedRcommand.ReturntypecouldbeaString,Number,Boolean,NetLogoListoraNetLogoListofLists.
RlistswillbeconvertedintoaNetLogoList.IftheRlistitselfcontainsfurtherlists,itwillbeconvertedintoaNetLogoListwithnestedNetLogolists.Listscontainingvaluesofdifferentdatatypesarealsosupported(e.g.mixedStrings,NumbersandBooleans/Logicals).
Data.frameswillbeconvertedintoaNetLogoListwithnestedListforeachcolumn,butthecolumnnameswillbelost(samefornamedRlists).
Rmatricescanbereceived,buttheyareconvertedintooneNetLogolist.NULLandNAvaluesarenotconvertedandwillthrowanerror,becauseNetLogohasnocorrespondingvalue.
![Page 327: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/327.jpg)
;; returns a list with 10 variablesshow r:get "rnorm(10)"
r:interactiveShell
r:interactiveShell
Opensawindowwithtwotextareas.TheupperoneistheRoutputstreamandintheloweroneyoucantypeRcommands.ThisistheaccesstotheunderlayingRsession.Youcantypemulti-linecommands.TosubmitcommandspressCtrl+Enter.With“PageUp”and“PageDown”intheinputareayoucanbrowsethroughthehistroyofsubmittedcommands.Withright-mouseclickcontextmenu,youcansaveandloadanRHistory(interchangeablewithRterminalandotherRGUIs).
Pleasenote,thattheInteractiveShellworksontheglobalenvironment,whilecommandssubmittedfromNetLogolivesinanlocalenvironment.Areferencetothislocalenvironmentisautomaticallyaddedtotheglobalenvironment(namednl.env,pleasedonotdeletethisvariable.Withacallofr:clearyoucanrestoreitbutthiswillemptyyourworkspace).YoucanusethistohaveaccesstovariableswhichyouhavecreatedfromNetLogobyget("<variable name>",nl.env).Tocopyforexampleanvariablewiththenamevar1fromthelocalenvironmenttotheglobalenvironment,typevar <-get("var",nl.env).SeesectionREnvironmentsfordetails.Ifyoujustwanttoseethecontentsofavariablewhichlivesinthelocalenvironment,youcouldsubmityourcommand,forexampleintheNetLogoCommandCenter,andtheresultwillbeshownintheoutputareaoftheInteractiveShell.Forexample:
r:put "test" (list world-width world-height)r:interactiveShellr:eval "print(test)"r:eval "str(test)"
VariableswhichhavebeencreatedintheInteractiveShellareavailablefromNetLogo,eveniftheyarecreatedintheglobalenvironment.Butifthereisavariablewiththesamenameinthelocalenvironment,youwillgetthisvariableinNetLogoinsteadtheonefromtheglobalenvironment.
IfyouwanttoexecuteplotcommandsfromtheInteractiveShellyoushouldactivatetheintegratedJavaGDplotdeviceviar:setPlotDevicefirst.
;; opens Interactive Shellr:interactiveShell
r:put
r:putnamevalue
CreatesanewvariableinRwiththenamename.ThevaluecanbeaString,Number,BooleanorList.
NetLogoListsareconvertedtoRvectors,ifallentriesareofthesamedatatype.IfaNetLogolistcontainsdifferentdatatypes(mixedStrings,NumbersofBooleans),itwillbeconvertedintoanRlist.IfaNetLogoListcontainsother/nestedNetLogoListsitwillbeconvertedintoanRlistandthenestedListsarehandledbythesamerule(Vectorsifallitemsareofthesamedatatype,…).
;; creates an R variable "testvar" with the size of turtle 0r:put "testvar" [size] of turtle 0show r:get "testvar"
r:putagent
r:putagentnameagentvariablesr:putagentnameagentsetvariables
CreatesanewnamedlistinRwiththenamename.Theargumentvariablesisanynumberofstringswhichlistandvariable(s)oftheagent|agentset.NamesoftheelementsoftheRlistwillbethesameasthenamesoftheagentvariables.Turtleswillbeassignedinascendingorderoftheirwho-variable.Patcheswillbeassignedinlinesfromupperlefttolowerright.Sincetheargumentsofthisprimitivearerepeatable,don’tforgettheparenthesesaroundthestatement.
;; creates an R-list "agentlist1" with the size and the id of turtles, don't forget the parentheses(r:putagent "agentlist1" turtles "size" "who")show r:get "agentlist1$who";; creates an R-list "agentlist2" with the pcolor, pxcor and pycor of patches(r:putagent "agentlist2" patches "pcolor" "pxcor" "pycor")show r:get "agentlist2$pcolor"
r:putagentdf
r:putagentdfnameagentvariables
![Page 328: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/328.jpg)
r:putagentdfnameagentsetvariables
Sameasr:putagentbutcreatesanRdata.frameinsteadalist.Pleasereadthenotesaboutdata.framesifoneofyouragentvariablescontainsNetLogoLists.
;; creates an R-list "agentlist2" with the pcolor, pxcor and pycor of patches, don't forget the parentheses(r:putagentdf "df1" patches "pcolor" "pxcor" "pycor")show r:get "class(df1)"
r:putdataframe
r:putdataframenamevarnamevaluer:putdataframenamevarnamevaluevarname2value2...
Sameasr:putnamedlistbutcreatesanRdata.frameinsteadofalist.IfyousendmorethanonelisttoNetLogoandthelistsareofdifferentlength,thesmalleroneswillbefilledwithNAvalues.
IfyousendnestedLogoLists(e.g.oftype:[[][]…])toonecolumnpleasereadthenotesaboutdataframeswithvectorsincells.
;; creates an R-list "agentlist2" with the pcolor, pxcor and pycor of patches, don't forget the parentheses(r:putdataframe "df1" "v1" [12 13 14 15 16] "v2" ["foo1" "foo2" "foo3" "foo4" "foo5"] "v3" [1.1 2.2 3.3 4.4 5.5])show r:get "df1$v3"
r:putlist
r:putlistnamevalue
CreatesanewlistinRwiththenamename.VariableisrepeatableandcanbeaNumber,BooleanorList.Each“Variable”willgetthenameofitsposition(1,2,3,…).Sincetheargumentsofthisprimitivearerepeatable,don’tforgettheparenthesesaroundthestatement.
;; creates an R-list "list1", don't forget the parentheses(r:putlist "list1" 25.5 [25 43 32 53] "testvalue" [44.3 32.32 321.2 4.2])show r:get "class(list1)"show r:get "list1[[1]]"show r:get "list1$'0'"show r:get "list1[[2]]"
r:putnamedlist
r:putnamedlistnamevarnamevaluer:putnamedlistnamevarnamevaluevarname2value2...
CreatesanewnamedlistinRwiththenamename.Variablenamesandvaluesfollowinalternatingsequenceandmayberepeatedasmanytimesasdesired.ValuescanbeaNumber,BooleanorList.Eachvaluewillgetthenamevarname.Sincetheargumentsofthisprimitivearerepeatable,don’tforgettoputthestatementintoparentheses.
;; creates an R-list "list1" , don't forget the parentheses(r:putnamedlist "list1" "v1" 25.5 "v2" [25 43 32 53] "v3" "testvalue" "v4" [44.3 32.32 321.2 4.2])show r:get "class(list1)"show r:get "list1[[1]]"show r:get "list1$v1"
r:setPlotDevice
r:setPlotDevice
ToopenanRplotinawindowyoucanusetheJavaGDplotdevice.WiththisprimitiveyoucanactivatethisdeviceandallfollowingcallsofRplotswillbeprintedwiththisdevice.
Tousethisdevice,youhavetoinstalltheJavaGDpackageinR.OpenanRterminalortheInteractiveShell(seer:interactiveShell)andtypeinstall.packages("JavaGD").
Withthisplotwindowyoucansavetheplottoanfileofdifferentgraphictypeandyoucancopytheplottotheclipboard.Pleasenote,thatonLinuxOSitcanbenecessarytoallowtoaddimagestotheclipboard(e.g.inKDEyouhavetoconfigureKLIPPERtoallowimages).Theresolutionforrasterimagesdependsonthesizeoftheplotwindow.Ifyouneedhighresolutionmaximazethewindow(anddon’tusejpeg,becausethedriverisbad)orbetteruseavectorimageformat.
Pleaseseethenotesaboutplottingforotherdetails.
![Page 329: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/329.jpg)
;; activate the JavaGD plot devicer:setPlotDevice
r:stop
r:stop
StopstheRengine.Thisisneeded(only)ifNetLogoisrunninginheadlessmode,forexamplewhenrunningBehaviorSpaceexperimentsfromthecommandlinewithsomethinglikethis:
java -cp NetLogo.jar org.nlogo.headless.Main --model mymodel.nlogo --experiment exp1 --table outtab1.csv
Shouldbethelastcallinheadlesssimulation.Seeusagenotesabovefordetails.
r:stop
Troubleshooting
Belowaresomecommonproblemsandsomeideasonhowtoremedythem.PleasekeepinmindthatweplantocontinuetoimprovetheRextensionfollowingthereleaseofNetLogo6.Wewelcomefeedbackonhowtoimprovetheextensionaswellasbugreportspointingustoanynewproblemsyouencounter.
LoadingRpackagesfails
See,forexample,thispost.
AfterchangingtheworkingdirectoryinR(e.g.withsetwd())NetLogodoesn’tfindtheextension
ChangingworkingdirectoryinRdoesn’tworkbecauseitchangesalsoJava’slibrarypaththatNetLogoneedstofinditsextensions.PleaseuseabsolutepathtoanyfilesinRinsteadofchangingtheworkingdirectory.
Specificerrorcodelist
Error#01.InvalidRHome.RhomeisspecifiedviatheR_HOMEenvironmentvariableorapropertiesfile,butcouldn’tbefoundatthespecifiedpath.SeeaboveforhowtospecifyRhome.Error#02:CannotfindrJava/JRI.TheRExtensionwasunabletolocateyourinstallationofrJava.Somestepstoresolve:EnsurethatrJava(0.9-8orlater)isinstalledinR.Ensurethatit’sinstalledeithersystem-wideorforyouasauserEnsurethatyourconfigurationpointstotheproperrJavalocation.Ifyouhaveauser.propertiesfile,ensurethatjri.home.pathsincludesthepathgivenbyRwhenyourunsystem.file("jri",package="rJava")Error#03:CannotloadrJavalibraries.ThismayindicateacorruptedrJavainstallation.TryreinstallingrJava.Error#04:ErrorinR-Extension.Thisisanunknowninitializationerror.EnsurethatyouarerunningR3.0.0orlaterandhavetherJavaextensioninstalled(version0.9-8orlater).Pleasereportthiserrortobugs@ccl.northwestern.eduoropenanewissueontheR-Extensionissuetracker.Error#05:TherewasanerrorsettingR_HOME.Checkyouruser.propertiesfiletoensurethatr.homespecifiesavalidpathtotheRextension.YoumayalsobeabletoworkaroundthiserrorbysettingtheR_HOMEenvironmentvariable.Ifthiserrorpersists,pleasereportit!Error#06:CannotloadRlibraries.ThismayindicateacorruptedorimproperlyconfiguredRinstallation.Ifyou’recertainthatyourRinstallationisfind,pleasereportthisasanissue.
Citation
Thiele,JC;Grimm,V(2010).NetLogomeetsR:Linkingagent-basedmodelswithatoolboxfortheiranalysis.EnvironmentalModellingandSoftware,Volume25,Issue8:972-974[DOI:10.1016/j.envsoft.2010.02.008]
CopyrightandLicense
TheRextensionisCopyright(C)2009-2016JanC.ThieleandCopyright(C)2016UriWilensky/TheCenterforConnectedLearning.
NetLogo-R-Extensionisfreesoftware;youcanredistributeitand/ormodifyitunderthetermsoftheGNUGeneralPublicLicenseaspublishedbytheFreeSoftwareFoundation;eitherversion2oftheLicense,or(atyouroption)anylaterversion.
Thisprogramisdistributedinthehopethatitwillbeuseful,butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyofMERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE.SeetheGNUGeneralPublicLicenseformoredetails.
YoushouldhavereceivedacopyoftheGNUGeneralPublicLicensealongwithNetLogo-R-Extension(locatedinGPL.txt).Ifnot,seehttp://www.gnu.org/licenses/.
![Page 330: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/330.jpg)
NetLogoRndExtension
ThisextensionaddstheabilitytodoroulettewheelselectioninNetLogo.ItprovidesasimplerwaytoaccomplishthesamethingastheLotteryExamplefromtheNetLogoModelsLibrary.
Usage
Whichprimitivetousedependsonwhetheryouwanttoselectanitemfromalistorfromanagenset.Italsodependsonwhetheryouwantoneormanyitemsand,ifyouwantmany,ifrepeatsareallowedornot.Thefollowingtablesummarizesthesituation:
FromanAgentSet FromaListOneitem rnd:weighted-one-of rnd:weighted-one-of-list
Manyitems,withoutrepeats rnd:weighted-n-of rnd:weighted-n-of-list
Manyitems,withrepeats rnd:weighted-n-of-with-repeats
rnd:weighted-n-of-list-with-repeats
(Note:theinitialversionoftheextensionhadasinglesetofprimitivesforbothlistsandagentsets,butitturnedouttobeconfusing,sowechangedit.Ifyouwereusingtheoldversionoftheextension,youwillneedtomodifyyourcodetousethenewprimitives.)
Inallcases,youwillneedtoprovidetwothingstotheprimitive:
The“candidates”:theitemsthattheprimitivewillselectfrom.The“weight”:howlikelyitisforeachcandidatetobeselected.
Ifyouwanttoselectmorethanoneitems,youwillalsoneedtotellit:
Howmanyitemstoselect.
Anoteaboutperformance
TheextensionusesKeithSchwarz’simplementationofVose’sAliasMethod(seeSchwarz’sDarts,Dice,andCoinspage).Assumingyouarechoosingncandidatesforacollectionofsizemwithrepeats,thismethodhasaninitializationcostofO(m)followedbyacostofO(1)foreachitemyoupick,soO(m+n)overall.
Forexample,inthefollowingcode:
let candidates n-values 500 [ [n] -> n ]rnd:weighted-n-of-list-with-repeats 100 candidates [ [w] -> w ]n-values 100 [ rnd:weighted-one-of-list candidates [ [w] -> w ] ]
…thelineusingrnd:weighted-n-of-list-with-repeatswilllikelyrun100timesfasterthanthelineusingacombinationofn-valuesandrnd:weighted-one-of-list.Thisisbecausernd:weighted-n-of-list-with-repeatsonlyinitializesthealgorithmonceandrnd:weighted-one-ofdoesiteachtimeitiscalled.
(Notethatcomposingn-valueswithrnd:weighted-one-of-listdoesnotpreservetheorderoftheoriginalcandidatelist,whilernd:weighted-n-of-list-with-repeatsdoes.)
Thingsareabitmorecomplicatedifyouarechoosingwithoutrepeats,however.Inthiscase,thealgorithmmayhavetodiscardsomepicksbecausethecandidateshavealreadybeenselected.Whenthisstartshappeningtoooften(maybebecausesomeweightsaremuchbiggerthanothers),theextensionre-initializesthealgorithmwiththealready-picked
![Page 331: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/331.jpg)
candidatesexcluded.Thisshouldnothappentoooften,however,sowhilepickingwithoutrepeatshasanupperboundofO(m*n)intheory,itshouldusuallynotbemuchmorethanO(m+n)inpractice.
Thepreviousremarksapplytoagentsetprimitivesasmuchastheyapplytolistprimitives.
Primitives
AgentSetPrimitives
rnd:weighted-one-ofrnd:weighted-n-ofrnd:weighted-n-of-with-repeats
ListPrimitives
rnd:weighted-one-of-listrnd:weighted-n-of-listrnd:weighted-n-of-list-with-repeats
rnd:weighted-one-of
rnd:weighted-one-ofagentsetreporter
Reportsarandomagentfromagentset.
Theprobabilityofeachagentbeingpickedisproportionaltotheweightgivenbythereporterforthatagent.Theweightsmustnotbenegative.
Iftheagentsetisempty,itreportsnobody.
HereisafullrewriteoftheLotteryExamplemodelusingthernd:weighted-one-ofprimitive:
extensions [ rnd ]
to setup clear-all ; create a turtle on every fifth patch ask patches with [ pxcor mod 5 = 0 and pycor mod 5 = 0 ] [ sprout 1 [ set size 2 + random 6 ; vary the size of the turtles set label 0 ; start them out with no wins set color color - 2 ; make turtles darker so the labels stand out ] ] reset-ticksend
to go ask rnd:weighted-one-of turtles [ size ] [ set label label + 1 ] tickend
rnd:weighted-n-of
rnd:weighted-n-ofsizeagentset[reporter]
Reportsanagentsetofthegivensizerandomlychosenfromtheagentset,withnorepeats.
Theprobabilityofeachagentbeingpickedisproportionaltotheweightgivenbythereporterforthatagent.Theweightsmustbenon-negativenumbers.
![Page 332: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/332.jpg)
Itisanerrorforsizetobegreaterthanthesizeoftheagentset.
If,atsomepointduringtheselection,thereremainsonlycandidateswithaweightof0.0,theyallhaveanequalprobabilityofgettingpicked.
rnd:weighted-n-of-with-repeats
rnd:weighted-n-of-with-repeatssizeagentset[reporter]
Reportsalistofthegivensizerandomlychosenfromtheagentset,withrepeats.(Whyalistinsteadofanagentset?Becauseanagentsetcannotcontainthesameagentmorethanonce.)
Theprobabilityofeachagentbeingpickedisproportionaltotheweightgivenbythereporterforthatagent.Theweightsmustbenon-negativenumbers.
Itisnotanerrorforsizetobegreaterthanthesizeoftheagentset,buttherehastobeatleastonecandidate.
If,atsomepointduringtheselection,thereremainsonlycandidateswithaweightof0.0,theyallhaveanequalprobabilityofgettingpicked.
Ifallweightsare0.0,eachcandidatehasanequalprobabilityofbeingpicked.
rnd:weighted-one-of-list
rnd:weighted-one-of-listlistanonymous-reporter
Reportsarandomitemfromlist.
Theprobabilityofeachitembeingpickedisproportionaltotheweightgivenbytheanonymous-reporterforthatitem.Theweightsmustnotbenegative.Thefirstargumentpassedtotheanonymousprocedurereferstothelistitem.(SeetheAnonymousProceduressectionoftheProgrammingGuideformoredetails.)
Itisanerrorforthelisttobeempty.
Acommonwaytousetheprimitiveistohavealistoflists,wherethefirstitemofeachsublististhethingyouwanttochooseandtheseconditemistheweight.Hereisashortexample:
let pairs [ [ "A" 0.2 ] [ "B" 0.8 ] ]repeat 25 [ ; report the first item of the pair selected using ; the second item (i.e., `last p`) as the weight type first rnd:weighted-one-of-list pairs [ [p] -> last p ]]
ThisshouldprintBroughlyfourtimesmoreoftenthanitprintsA.
Ifyouhappentohaveyouritemsandyourweightsintwoseparatelists,youcancombinethemintopairsbyusingacombinationofmapandlist:
let items [ "A" "B" "C" ]let weights [ 0.1 0.2 0.7 ]let pairs (map list items weights)
Sinceweapplymaptoboththeitemslistandtheweightslist,theparenthesesareneededin(map list items weights).Wealsousetheconciseanonymousproceduresyntax(seethe
![Page 333: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/333.jpg)
programmingguide)topasslistasthereporterformap.Thesamethingcouldhavebeenwritten(map [ [a b] -> list a b ] items weights) .
rnd:weighted-n-of-list
rnd:weighted-n-of-listsizelistanonymous-reporter
Reportsalistofthegivensizerandomlychosenfromthelistofcandidates,withnorepeats.
Theprobabilityofeachitembeingpickedisproportionaltotheweightgivenbytheanonymous-reporterforthatitem.Theweightsmustnotbenegative.Thefirstargumentpassedtotheanonymousprocedurereferstothelistitem.(SeetheAnonymousProceduressectionoftheProgrammingGuideformoredetails.)
Itisanerrorforsizetobegreaterthanthesizeofthelist of candidates.
If,atsomepointduringtheselection,thereremainsonlycandidateswithaweightof0.0,theyallhaveanequalprobabilityofgettingpicked.
Theitemsintheresultinglistappearinthesameorderthattheyappearedinthelistofcandidates.(Ifyouwanttheminrandomorder,useshuffleontheresult).
Example:
let candidates n-values 8 [ [n] -> 2 ^ (n + 1) ] ; make a list with the powers of twoprint rnd:weighted-n-of-list 4 candidates [ [w] -> w ]
Thisshouldprintalistoffournumbers,wherethebiggernumbers(32,64,128,256)haveamuchbetterchancetoshowupthanthesmallerones(2,4,8,16).
rnd:weighted-n-of-list-with-repeats
rnd:weighted-n-of-list-with-repeatssizelistanonymous-reporter
Reportsalistofthegivensizerandomlychosenfromthelistofcandidates,withrepeats.
Theprobabilityofeachitembeingpickedisproportionaltotheweightgivenbytheanonymous-reporterforthatitem.Theweightsmustnotbenegative.Thefirstargumentpassedtotheanonymousprocedurereferstothelistitem.(SeetheAnonymousProceduressectionoftheProgrammingGuideformoredetails.)
Itisnotanerrorforsizetobegreaterthanthesizeofthelistofcandidates,buttherehastobeatleastonecandidate.
If,atsomepointduringtheselection,thereremainsonlycandidateswithaweightof0.0,theyallhaveanequalprobabilityofgettingpicked.
Ifallweightsare0.0,eachcandidatehasanequalprobabilityofbeingpicked.
Theitemsintheresultinglistappearinthesameorderthattheyappearedinthelistofcandidates.(Ifyouwanttheminrandomorder,useshuffleontheresult).
Example:
let pairs [ [ "A" 0.2 ] [ "B" 0.8 ] ]print map first rnd:weighted-n-of-list-with-repeats 25 pairs [ [p] -> last p ]
![Page 334: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/334.jpg)
Thisshouldprintalistof25AsandBs,withroughlyfourtimesasmanyBsthanAs.
![Page 335: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/335.jpg)
NetLogoSoundExtension
Using
TheSoundExtensionletsNetLogomodelsmaketwokindsofsounds:MIDIsoundsandplaybackofpre-recordedsoundfiles.
TheJavaAPIsusedarejavax.sound.midiandjava.applet.AudioClip.
HowtoUse
Thesoundextensioncomespreinstalled.Tousetheextensioninyourmodel,addthisatthetopofyourCodetab:
extensions [sound]
Ifyourmodelalreadyusesotherextensions,thenitalreadyhasanextensionslineinit,sojustaddsoundtothelist.
FormoreinformationonusingNetLogoextensions,seetheExtensionsGuide
Forexamplesthatusethesoundextension,seetheSoundsectionunderCodeExamplesintheNetLogoModelsLibrary.
MIDIsupport
TheMIDIpartoftheextensionsimulatesa128-keyelectronickeyboardwith47drumsand128melodicinstruments,asprovidedbyGeneralMIDILevel1specification.
Itsupports15polyphonicinstrumentchannelsandasinglepercussionchannel.Usingmorethan15differentmelodicinstrumentssimultaneouslyinamodelwillcausesomesoundstobelostorcutoff.
Thepitchofamelodicinstrumentisspecifiedbyakeynumber.Thekeysonthekeyboardarenumberedconsecutivelyfrom0to127,where0istheleft-mostkey.MiddleCiskeynumber60.
Theloudnessofaninstrumentisspecifiedbyavelocity,whichrepresentstheforcewithwhichthekeyboardkeyisdepressed.Velocityrangesfrom0to127,where64isthestandardvelocity.Ahighervelocityresultsinaloudersound.
Primitives
sound:drumssound:instrumentssound:play-drumsound:play-notesound:play-note-later
sound:drums
sound:drums
Reportsalistofthenamesofthe47drumsforusewithsound:play-drum.
![Page 336: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/336.jpg)
sound:instruments
sound:instruments
Reportsalistofthenamesofthe128instrumentsforusewithsound:play-note,sound:play-note-later,sound:start-noteandsound:stop-note.
sound:play-drum
sound:play-drumdrumvelocity
Playsadrum.
Example:
sound:play-drum "ACOUSTIC SNARE" 64
sound:play-note
sound:play-noteinstrumentkeynumbervelocityduration
Playsanoteforaspecifiedduration,inseconds.Theagentdoesnotwaitforthenotetofinishbeforecontinuingtonextcommand.
;; play a trumpet at middle C for two secondssound:play-note "TRUMPET" 60 64 2
sound:play-note-later
sound:play-note-laterdelayinstrumentkeynumbervelocityduration
Waitsforthespecifieddelaybeforeplayingthenoteforaspecifiedduration,inseconds.Theagentdoesnotwaitforthenotetofinishbeforecontinuingtonextcommand.
Example:
;; in one second, play a trumpet at middle C for two secondssound:play-note-later 1 "TRUMPET" 60 64 2
DrumNames
35. Acoustic Bass Drum 59. Ride Cymbal 236. Bass Drum 1 60. Hi Bongo37. Side Stick 61. Low Bongo38. Acoustic Snare 62. Mute Hi Conga39. Hand Clap 63. Open Hi Conga40. Electric Snare 64. Low Conga41. Low Floor Tom 65. Hi Timbale42. Closed Hi Hat 66. Low Timbale43. Hi Floor Tom 67. Hi Agogo44. Pedal Hi Hat 68. Low Agogo
![Page 337: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/337.jpg)
45. Low Tom 69. Cabasa47. Open Hi Hat 70. Maracas47. Low Mid Tom 71. Short Whistle48. Hi Mid Tom 72. Long Whistle49. Crash Cymbal 1 73. Short Guiro50. Hi Tom 74. Long Guiro51. Ride Cymbal 1 75. Claves52. Chinese Cymbal 76. Hi Wood Block53. Ride Bell 77. Low Wood Block54. Tambourine 78. Mute Cuica55. Splash Cymbal 79. Open Cuica56. Cowbell 80. Mute Triangle57. Crash Cymbal 2 81. Open Triangle58. Vibraslap
InstrumentNames
*Piano* *Reed*1. Acoustic Grand Piano 65. Soprano Sax2. Bright Acoustic Piano 66. Alto Sax3. Electric Grand Piano 67. Tenor Sax4. Honky-tonk Piano 68. Baritone Sax5. Electric Piano 1 69. Oboe6. Electric Piano 2 70. English Horn7. Harpsichord 71. Bassoon8. Clavi 72. Clarinet
*Chromatic Percussion* *Pipe*9. Celesta 73. Piccolo10. Glockenspiel 74. Flute11. Music Box 75. Recorder12. Vibraphone 76. Pan Flute13. Marimba 77. Blown Bottle14. Xylophone 78. Shakuhachi15. Tubular Bells 79. Whistle16. Dulcimer 80. Ocarina
*Organ* *Synth Lead*17. Drawbar Organ 81. Square Wave18. Percussive Organ 82. Sawtooth Wave19. Rock Organ 83. Calliope20. Church Organ 84. Chiff21. Reed Organ 85. Charang22. Accordion 86. Voice23. Harmonica 87. Fifths24. Tango Accordion 88. Bass and Lead
*Guitar* *Synth Pad*25. Nylon String Guitar 89. New Age26. Steel Acoustic Guitar 90. Warm27. Jazz Electric Guitar 91. Polysynth28. Clean Electric Guitar 92. Choir29. Muted Electric Guitar 93. Bowed30. Overdriven Guitar 94. Metal31. Distortion Guitar 95. Halo32. Guitar harmonics 96. Sweep
*Bass* *Synth Effects*33. Acoustic Bass 97. Rain34. Fingered Electric Bass 98. Soundtrack35. Picked Electric Bass 99. Crystal36. Fretless Bass 100. Atmosphere37. Slap Bass 1 101. Brightness38. Slap Bass 2 102. Goblins39. Synth Bass 1 103. Echoes40. Synth Bass 2 104. Sci-fi
*Strings* *Ethnic*41. Violin 105. Sitar42. Viola 106. Banjo43. Cello 107. Shamisen44. Contrabass 108. Koto45. Tremolo Strings 109. Kalimba47. Pizzicato Strings 110. Bag pipe
![Page 338: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/338.jpg)
47. Orchestral Harp 111. Fiddle48. Timpani 112. Shanai
*Ensemble* *Percussive*49. String Ensemble 1 113. Tinkle Bell50. String Ensemble 2 114. Agogo51. Synth Strings 1 115. Steel Drums52. Synth Strings 2 116. Woodblock53. Choir Aahs 117. Taiko Drum54. Voice Oohs 118. Melodic Tom55. Synth Voice 119. Synth Drum56. Orchestra Hit 120. Reverse Cymbal
*Brass* *Sound Effects*57. Trumpet 121. Guitar Fret Noise58. Trombone 122. Breath Noise59. Tuba 123. Seashore60. Muted Trumpet 124. Bird Tweet61. French Horn 125. Telephone Ring62. Brass Section 126. Helicopter63. Synth Brass 1 127. Applause64. Synth Brass 2 128. Gunshot
![Page 339: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/339.jpg)
NetLogoTableExtension
Using
Thetableextensionispre-installedinNetLogo.
Tousethetableextensioninyourmodel,addalinetothetopofyourCodetab:
extensions [table]
Ifyourmodelalreadyusesotherextensions,thenitalreadyhasanextensionslineinit,sojustaddtabletothelist.
FormoreinformationonusingNetLogoextensions,seetheExtensionsGuide
WhentoUse
Ingeneral,anythingyoucandowithantableinNetLogo,youcouldalsojustusealistfor.Butyoumaywanttoconsiderusingantableinsteadforspeedreasons.Listsandtableshavedifferentperformancecharacteristics,soyoumaybeabletomakeyourmodelrunfasterbyselectingtheappropriatedatastructure.
Tablesareusefulwhenyouneedtodoassociatevalueswithothervalues.Forexample,youmightmakeatableofwordsandtheirdefinitions.Thenyoucanlookupthedefinitionofanyword.Here,thewordsarethe"keys".Youcaneasilyretrievethevalueforanykeyinthetable,butnotviceversa.
UnlikeNetLogo’slistsandstrings,tablesare“mutable”.Thatmeansthatyoucanactuallymodifythemdirectly,ratherthanconstructinganalteredcopyaswithlists.Ifthetableisusedinmorethanoneplaceinyourcode,anychangesyoumakewillshowupeverywhere.It’strickytowritecodeinvolvingmutablestructuresandit’seasytomakesubtleerrorsorgetsurprisingresults,sowesuggeststickingwithlistsandstringsunlessyou’recertainyouwantandneedmutability.
Example
let dict table:maketable:put dict "turtle" "cute"table:put dict "bunny" "cutest"print dict=> {{table: "turtle" -> "cute", "bunny" -> "cutest" }}print table:length dict=> 2print table:get dict "turtle"=> "cute"print table:get dict "leopard"=> (error)print table:keys dict=> ["turtle" "bunny"]
ManipulatingTables
Ifthesamekeyisusedwithtable:putmorethanonceforthesametable,thevalueprovidedtolastcalloftable:putwillbethevalueshownwhentable:getisused.Hereisanexample:
let dict table:maketable:put dict "a" 5table:put dict "a" 3print table:get dict "a"=> 3
Becausetablesaremutable,manipulatingexistingvaluesshouldbedonebycallingtable:getortable:get-or-defaultonakey,transformingthereturnedvalue,andthencallingtable:puttoupdatethetransformedvalueinthetable.Hereisanexampleprocedurewhichincrementsavalueinatableatagivenkey.Ifthekeydoesn’texist,itputsa1atthatkeyinstead.
to increment-table-value [ dict key ] let i table:get-or-default dict key 0 table:put dict key i + 1end
KeyRestrictions
TablekeysarelimitedtothefollowingNetLogotypes:
NumbersStringsBooleansListscontainingonlyelementswhicharethemselvesvalidkeys
Ifyouattempttouseanillegalvalue,thetableextensionwillraiseanexception,asshowninthefollowingexample.
crt 1let dict table:maketable:put dict (one-of turtles) 10;; Errors with the following message:;; (turtle 0) is not a valid table key (a table key may only be a number, a string, true or false, or a list whose items are valid keys)
Primitives
table:cleartable:countstable:group-agentstable:group-itemstable:from-listtable:gettable:get-or-defaulttable:has-key?table:keystable:lengthtable:maketable:puttable:removetable:to-listtable:values
![Page 340: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/340.jpg)
table:clear
table:cleartable
Removesallkey-valuepairsfromtable.
table:counts
table:countslist
Countstheoccurrencesofeachelementofthegivenlistandreportsthecountsinatable.
table:group-agents
table:group-agentsagentsetanonymousreporter
Groupstheagentsintheagentsetbasedonthegivenreporter.Agentsthatreportthesamethingforreporterwillbegroupedtogether.Theresultsofthereporterwillbeusedasthekeysintheresultingtableandthegroupswillbeagentsets.
Forexample:
observer> create-turtles 100 [ set color one-of [ red green blue ] ]observer> show table:group-by turtles [ color ]observer: {{table: [[105 (agentset, 38 turtles)] [55 (agentset, 32 turtles)] [15 (agentset, 30 turtles)]]}}
table:group-items
table:group-itemslistanonymous-reporter
Groupstheitemsofthelistbsaedonthegivenreporter.Thereportershouldtakeasingleargument,whichwillbetheitemsofthelist.Itemsthatreportthesamethingwhenpassedtothereporterwillbegroupedtogether.Theresultsofthereporterwillbeusedasthekeysintheresultingtableandthegroupswillbelists.
Forexample:
observer> show table:group-by range 10 [ num -> num mod 3 ]observer: {{table: [[0 [0 3 6 9]] [1 [1 4 7]] [2 [2 5 8]]]}}
table:from-list
table:from-listlist
Reportsanewtablewiththecontentsoflist.listmustbealistoftwoelementlists,orpairs.Thefirstelementinthepairisthekeyandthesecondelementisthevalue.
table:get
table:gettablekey
Reportsthevaluethatkeyismappedtointhetable.Causesanerrorifthereisnoentryforthekey.
table:get-or-default
table:get-or-defaulttablekeydefault-value
Reportsthevaluethatkeyismappedtointhetable.Reportsthedefault-valueifthereisnoentryforthekey.
table:has-key?
table:has-key?tablekey
Reportstrueifkeyhasanentryintable.
table:keys
table:keystable
Reportsalistofallthekeysintable,inthesameorderthekeyswereinserted.
table:length
table:lengthtable
Reportsthenumberofentriesintable.
table:make
table:make
![Page 341: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/341.jpg)
Reportsanew,emptytable.
table:put
table:puttablekeyvalue
Mapskeytovalueintable.Ifanentryalreadyexistsinthetableforthegivenkey,itisreplaced.
table:remove
table:removetablekey
Removesthemappingintableforkey.
table:to-list
table:to-listtable
Reportsalistwiththecontentoftable.Thelistwillbealistoftwoelementlists,orpairs.Thefirstelementinthepairisthekeyandthesecondelementisthevalue.Thekeysappearinthesameordertheywereinserted.
table:values
table:valuestable
Reportsalistwiththeentriesoftable.Theentrieswillappearinthesameordertheywereinserted,withduplicatesincluded.
![Page 342: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/342.jpg)
NetLogoVidExtension
Concepts
VideoSource
Thevidextensionhasabuilt-inconceptofavideosource.Atthemoment,theonlyvideosourcesavailablearemoviesinthedirectorythemodellivesinandcamerasattachedtothecomputer.Thevidextensionopensanewvideosourcewiththevid:<source>-openandvid:<source>-select.Theseprimitiveschangethesourcetotheselectedsource.Ifasourceisalreadyopen,itclosesitbeforeopeninganewone.
SourceLifecycle
Moviesourcesare“stopped”afterbeingcreatedbyvid:movie-selectorvid:movie-open.Camerasourcesstartoffas“playing”afterbeingcreatedbyvid:camera-selectorvid:camera-open.Ifasourceisinstatus“stopped”itcanbestartedwithvid:start.Conversely,ifthesourceis“playing”itcanbestoppedwithvid:stop.Whenasourceis“stopped”,eachcalltovid:capture-imagewillreturnthesameimage.
VideoRecorder
Thevidextensionalsohastheconceptofarecording,aseriesofframeswhichcanbesewnintoan“mp4”movie.Therecorderstatuscanbequeriedusingvid:recorder-status.Therecorderstatusis“inactive”untilstartedwithvid:start-recorder,whichsetsitto“recording”.Whiletherecorderis“recording”thevid:record-view,vid:record-interface,andvid:record-sourcecanbeusedtosaveframestotherecording.Youcanchoosetosavetherecordingwhilerecordingusingvid:save-recordingwhichsavesthemovietothespecifiedfileandresettherecordingstatusto“inactive”.Ifyouwouldprefertothrowawaytherecordedframeswithoutsaving,usevid:reset-recorder.
Primitives
vid:camera-namesvid:camera-openvid:camera-selectvid:movie-selectvid:movie-openvid:movie-open-remotevid:closevid:startvid:stopvid:statusvid:capture-imagevid:set-timevid:show-playervid:hide-playervid:record-viewvid:record-interfacevid:record-sourcevid:recorder-statusvid:start-recordervid:save-recording
vid:camera-names
vid:camera-names
Providesalistofallavailablecameras.
Example:
vid:camera-names => []vid:camera-names => ["Mac Camera"]vid:camera-names => ["Logitech Camera"]
vid:camera-open
vid:camera-open
Opensthenamedcameraasavideosource.Ifnonameisprovided,opensthefirstcamerathat
![Page 343: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/343.jpg)
wouldbelistedbycamera-names.
Example:
vid:camera-open ; opens first camera(vid:camera-open "Logitech Camera")
Errors:
Message"vid: no cameras found" :nocamerasareavailable.Message"vid: camera "\<name\>" not found":ifthenamedcameraisnotavailable.
vid:camera-select
vid:camera-select
Promptstheusertoselectacameraasvideosource.Thiscommanddoesnoterroriftheusercancels.Usevid:statustoseeifauserselectedacamera.
Example:
vid:camera-select
Errors:
Message“vid:nocamerasfound”:nocamerasareavailable.
vid:movie-select
vid:movie-select
Promptstheusertoselectamovietouseasavideosource.TheformatssupportedarethosesupportedbyJavaFX2.Thiscommanddoesnoterroriftheusercancels.Usevid:statustoseeiftheuserselectedamovie.
Example:
vid:movie-select
Errors:
Message"vid: format not supported":theuserselectedamoviewithanunsupportedformat.
vid:movie-open
vid:movie-openfilename
Opensavideofromthefilesystem.Iftheprovidedpathisnotabsolutetheextensionsearchesforthegivenpathrelativetothecurrentmodeldirectory.Iftheprovidedpathisabsolutetheextensionopensthefile.
Example:
vid:movie-open "foo.mp4" ; Opens foo.mp4 in the directory containing the modelvid:movie-open user-file ; Opens a dialog for the user to select a movievid:movie-open "/tmp/foo.mp4" ; Opens a movie from the "/tmp" directory
![Page 344: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/344.jpg)
Errors:
Message"vid: no movie found" :themoviecouldnotbefound.Message"vid: format not supported":theuserselectedamoviewithanunsupportedformat.
vid:movie-open-remote
vid:movie-open-remoteurl
Opensaremotevideofromawebsiteorftpserver.
Example:
vid:movie-open-remote "http://example.org/foo.mp4"
Errors:
Message"vid: no movie found" :ThespecifiedURLcouldnotbeloadedorerroredwhileloading.Message"vid: format not supported":Thefiletypeoftheremotemovieisnotsupported.Message"vid: protocol not supported":ThemoviewasatanunsupportedURLprotocol.Supportedprotocolsareftpandhttp.
vid:close
vid:close
Closesthecurrentlyselectedvideosource.Hasnoeffectifthereisnoactivevideosource.
Example:
vid:close
vid:start
vid:start
Startstheselectedvideosource.Avideosourcemusthavebeenselectedbeforecallingvid:start.
Example:
vid:start
Errors:
Message"vid: no selected source":Thereisnocurrentlyselectedvideosource.Selectasourcewithvid:movie-open,vid:movie-select,vid:camera-open,orvid:camera-select.
vid:stop
vid:stop
Stopsthecurrentlyrunningvideosource.
Example:
![Page 345: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/345.jpg)
vid:stop
vid:status
vid:status
Reportsthecurrentstatusofanactivevideo.Notethataftercallingvid:movie-openorvid:movie-selectthestatuswillbesetto“stopped”,whileaftercallingvid:camera-openorvid:camera-selectthestatuswillbe“playing”.
Example:
vid:status ; => "inactive"
vid:movie-open "foobar.mp4"vid:status ; => "stopped"
vid:movie-startvid:status ; => "playing"
vid:capture-image
vid:capture-imagewidthheight
Capturesanimagefromthecurrentlyselectedactivesource.
Ifwidthandheightarenotspecified,theimageiscapturedatthecurrentsourceresolution.
Example:
extensions [ vid bitmap ]
to capture ; capture an image if a video source is open, ; have the user select a camera if no video source found carefully [ ; when camera open, take an image let image vid:capture-image ; returns image suitable for use with bitmap extension bitmap:copy-to-drawing image 0 0 ] [ if error-message = "Extension exception: vid: no selected source" [ vid:camera-select vid:start let image vid:capture-image bitmap:copy-to-drawing image 0 0 ] ]end
Ifyouwanttocaptureimagesatadifferentresolution,simplyreplacevid:capture-imagewith,e.g.,(vid:capture-image 640 480).
Errors:
Message"vid: no selected source":Thereisnocurrentlyselectedvideosource.Selectasourcewithvid:movie-open,vid:movie-select,vid:camera-open,orvid:camera-select.Message"vid: invalid dimensions":Theselecteddimensionsareinvalid(oneofthedimensionsiszeroornegative).
vid:set-time
vid:set-timeseconds
![Page 346: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/346.jpg)
Setsthetimeofthecurrentvideosourceto*seconds*.Thishasnoeffectwhenthecurrentvideosourceisacamera.
Example:
vid:set-time 100
Errors:
Message"vid: no selected source":Thereisnocurrentlyselectedvideosource.Selectasourcewithvid:movie-open,vid:movie-select,vid:camera-open,orvid:camera-select.Message"vid: invalid time":Thecurrentlyactivevideodoesnotcontainthespecifiedsecond.Thesecondmaybenegative,orgreaterthanthelengthofthevideo.
vid:show-player
vid:show-playerwidthheight
Showsaplayerinaseparatewindow.Ifthereisnovideosource,thewindowwillbeanemptyblackframe.Ifthereisanactivevideosource,itwillbedisplayedinthewindowwiththespecifiedwidthandheight.Ifthereisaplayingvideosource,itwillbedisplayedinthewindowatitsspecifiedwidthandheight.Ifwidthandheightareomitted,thevideowillbedisplayedinitsnativeresolution.
Examplewithnativeresolution:
vid:show-player
Examplewithcustomresolution:
(vid:show-player 640 480)
Errors:
Message"vid: invalid dimensions":Theselecteddimensionsareinvalid(oneofthedimensionsiszeroornegative).
vid:hide-player
vid:hide-player
Hidestheplayerifopen.Doesnothingifthereisnoplayerwindow.
Example:
vid:hide-player
vid:record-view
vid:record-view
RecordsthecurrentimageshownintheNetLogoviewtotheactiverecording.
Example:
vid:record-view
![Page 347: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/347.jpg)
Errors:
Message"vid: recorder not started":Therecorderhasnotbeenstarted.Starttherecorderwithvid:start-recorder.
vid:record-interface
vid:record-interface
RecordstheNetLogointerfaceviewtotheactiverecording.
Example:
vid:record-interface
Errors:
Message"vid: recorder not started":Therecorderhasnotbeenstarted.Starttherecorderwithvid:start-recorder.Message"vid: export interface not supported":ThecallingNetLogoversiondoesnotsupportinterfaceexports.ThiswilloccurwhenrunningNetLogoheadlessly.
vid:record-source
vid:record-source
Recordsaframetotheactiverecordingfromthecurrentlyactivesource.
Example:
vid:record-source
Errors:
Message"vid: recorder not started":Therecorderhasnotbeenstarted.Starttherecorderwithvid:start-recorder.Message"vid: no selected source":Thereisnocurrentlyselectedvideosource.Selectasourcewithvid:movie-open,vid:movie-select,vid:camera-open,orvid:camera-select.
vid:recorder-status
vid:recorder-status
Reportsthecurrentstatusoftherecorder.Initiallyandaftertherecorderissaved(viavid:save-recording)orreset(viavid:reset-recorder)therecorderstatusis“inactive”.Aftercallingvid:start-recorderthestatuswillbe“recording”.
Example:
vid:recorder-status ; => "inactive"
vid:start-recordervid:recorder-status ; => "recording"
vid:reset-recordervid:recorder-status ; => "inactive"
![Page 348: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/348.jpg)
vid:start-recorder
vid:start-recorder
Startstherecorder.Iftherecorderisalreadyrunningthiswillcauseanerrortoberaised.Ifdesired,arecordingwidthandheightcanbesupplied.Ifwidthandheightarenotsupplied,theywillbedeterminedfromthefirstframerecorded.
Example:
vid:start-recorder(vid:start-recorder 640 480)
Errors:
Message"vid: recorder already started":Therecorderhasalreadybeenstarted.Theexistingrecordingshouldbesavedorresetbeforestartingtherecording.Message"vid: invalid dimensions":Theselecteddimensionsareinvalid(oneofthedimensionsiszeroornegative).
vid:save-recording
vid:save-recordingfilename
Savestherecordingtothespecifiedpath.Iftherecorderisnotrunningthiswillcauseanerrortoberaised.Notethatatpresenttherecordingwillalwaysbesavedinthe“mp4”format.Ifthesuppliedfilenamedoesnotendin“.mp4”,the“.mp4”suffixwillbeadded.Notethatvid:save-recordingwilloverwriteexistingfilesofthesamename.vid:save-recordingwillerroriftherecorderhasnotbeenstartedorifthefilecannotbewrittensincethecontainingdirectorydoesnotexist.
Example:
vid:save-recording "foo.mp4" ; Saves to foo.mp4 in the directory containing the modelvid:save-recording user-new-file ; Opens a dialog for the user to select a save pathvid:save-recording "/tmp/foo.mp4" ; Saves the recording to the "/tmp" directory
Errors:
Message"vid: recorder not started":Therecorderhasnotbeenstarted.Starttherecorderwithvid:start-recorder.Message"vid: no such directory":Thedirectorycontainingthespecifiedsavefiledoesnotexist.Message"vid: no frames recorded":Youtriedtosavearecordingwithnoframesrecorded.Checkthatyouarerecordingproperlyorusevid:reset-recordingtotochangetherecordingformatwithoutsaving.
![Page 349: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/349.jpg)
NetLogoView2.5dExtension
TheView2.5DextensionoffersvisualizationforPatchandTurtlereporters,inrealtime,inasimulation’scontext.
HowtoUse
Theview2.5dextensionispre-installedinNetLogo.
Tousetheview2.5dextensioninyourmodel,addalinetothetopofyourCodetab:
extensions [view2.5d]
Ifyourmodelalreadyusesotherextensions,thenitalreadyhasanextensionslineinit,sojustaddview2.5dtothelist.
FormoreinformationonusingNetLogoextensions,seetheExtensionsGuide
IncorporatingIntoModels
openawindowusingeithertheview2.5d:patch-vieworview2.5d:turtle-viewcommands(itcanbeagoodideatoputtheseinyour‘SETUP’procedureoraseparatebutton).
updateyourwindow’sviewusingoneoftheupdatecommands(puttheseinyour‘GO’procedure).
SeetheView2.5dCodeExamplesintheNetLogomodelslibrary.
Feedback
Sendcomments,bugs,orotherfeedbacktoCCLFeedbackand/orCoreyBrady.
Primitives
view2.5d:patch-viewview2.5d:decorate-patch-viewview2.5d:undecorate-patch-viewview2.5d:turtle-viewview2.5d:update-all-patch-viewsview2.5d:update-patch-viewview2.5d:update-turtle-viewview2.5d:get-z-scaleview2.5d:set-z-scaleview2.5d:set-turtle-stem-thicknessview2.5d:get-observer-anglesview2.5d:set-observer-anglesview2.5d:get-observer-xy-focusview2.5d:set-observer-xy-focusview2.5d:get-observer-distanceview2.5d:set-observer-distanceview2.5d:remove-patch-viewview2.5d:remove-turtle-viewview2.5d:remove-all-patch-viewsview2.5d:remove-all-turtle-viewsview2.5d:count-windows
view2.5d:patch-view
view2.5d:patch-viewTitleReporter
ThiscommandmustbecalledfromtheObservercontext.(Attemptingtocallfromanothercontextcausesanerror)TheTitleisastring,whichwillbeusedtolabelthenewWindowandtocallforsubsequentupdatesandmodifications.SpecificationoftheReporterusestheNetLogoanonymousproceduresyntax,fromtheObserverperspective.
Example:
view2.5d:patch-view "Test" [ [the-turtle] -> [pxcor] of the-turtle]
view2.5d:decorate-patch-view
view2.5d:decorate-patch-viewTitle
![Page 350: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/350.jpg)
ThiscommandmustbecalledfromtheObservercontext.(Attemptingtocallfromanothercontextcausesanerror)TheTitleisastring,thelabelofanexistingPatchViewWindow.Effect:drawstheturtlesofthemodelattheircurrentlocation,ontopofthePatchviewdisplay
NOTE:onlyhasaneffectinthe“structures”patchview(intheothers,thepatchvalueisinclinedbasedonneighbors&gradient)
NOTE:fornegativepatchvalues,theturtleshapesaredrawnbelow(orbitunderneathtoseethem)
Example:
view2.5d:decorate-patch-view "Test"
view2.5d:undecorate-patch-view
view2.5d:undecorate-patch-viewTitle
ThiscommandmustbecalledfromtheObservercontext.(Attemptingtocallfromanothercontextcausesanerror)
TheTitleisastring,thelabelofanexistingPatchViewWindow.Effect:STOPSdrawingtheturtlesofthemodelattheircurrentlocation,ontopofthePatchviewdisplay
Example:
view2.5d:undecorate-patch-view "Test"
view2.5d:turtle-view
view2.5d:turtle-viewTitleAgentsReporter
ThiscommandmustbecalledfromtheObservercontext.(Attemptingtocallfromanothercontextcausesanerror)TheTitleisastring,whichwillbeusedtolabelthenewWindowandtocallforsubsequentupdates.Theturtle-setisanyselectorforturtles.SpecificationoftheReporterusestheNetLogotasksyntax,fromtheObserverperspective.
Example:
view2.5d:turtle-view "Test" turtles with [color = red] [[energy] of ?1]; This would create a new 2.5d window, plotting the ENERGY value of all turtles that are red.
view2.5d:update-all-patch-views
view2.5d:update-all-patch-views
ThiscommandmustbecalledfromtheObservercontext.Updatesallexistingpatch-viewwindowsaccordingtothelatestvalues.
view2.5d:update-patch-view
view2.5d:update-patch-viewTitle
ThiscommandmustbecalledfromtheObservercontext.Updatesonlythepatch-viewwindowwiththespecifiedtitle(ifany).
![Page 351: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/351.jpg)
view2.5d:update-turtle-view
view2.5d:update-turtle-viewTitleAgents
ThiscommandmustbecalledfromtheObservercontext.Updatesonlytheturtle-viewwindowwiththespecifiedtitle(ifany).Theturtle-setselectormustbesuppliedtorefreshthesetofturtles.
view2.5d:get-z-scale
view2.5d:get-z-scaletitle
ThisreportermustbecalledfromtheObservercontext.Returnsthecurrentz-scaleoftheturtle-vieworpatch-viewwindowwiththespecifiedtitle(ifany).
view2.5d:set-z-scale
view2.5d:set-z-scaleTitlenew-z-scale
ThiscommandmustbecalledfromtheObservercontext.Updatesonlytheturtle-vieworpatch-viewwindowwiththespecifiedtitle(ifany).Theviewisnowdisplayedwiththenewz-scale.
view2.5d:set-turtle-stem-thickness
view2.5d:set-turtle-stem-thicknessTitlethickness
ThiscommandmustbecalledfromtheObservercontext.Updatesonlytheturtle-viewwindowwiththespecifiedtitle(ifany).Turtlesarenowdrawnwith“pins”or“stems”thathavethespecifiedthickness(insteadofthehairlinedefault)
view2.5d:get-observer-angles
view2.5d:get-observer-anglesTitle
ThisreportermustbecalledfromtheObservercontext.Returnsalistreflectingtheobserver’sangularperspective{headingpitch}(theplaceonanimaginarysphereatthezoomdistanceisupdatedtoobeyheading&pitchgiven)
view2.5d:set-observer-angles
view2.5d:set-observer-anglesTitleheadingpitch
ThiscommandmustbecalledfromtheObservercontext.Updatesonlytheturtle-viewwindowwiththespecifiedtitle(ifany).Setstheobserver’sangularperspective(theplaceonanimaginarysphereatthezoomdistanceisupdatedtoobeyheading&pitchgiven)
view2.5d:get-observer-xy-focus
view2.5d:get-observer-xy-focusTitle
ThisreportermustbecalledfromtheObservercontext.Returnsalistreflectingthexandycoordinatestheobserveris“lookingat”inthepatchplane.
view2.5d:set-observer-xy-focus
view2.5d:set-observer-xy-focusTitlenumberycor
![Page 352: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/352.jpg)
ThiscommandmustbecalledfromtheObservercontext.Updatesonlytheturtle-viewwindowwiththespecifiedtitle(ifany).Setsthexandycoordinatestheobserverthatis“lookingat”inthepatchplane.
view2.5d:get-observer-distance
view2.5d:get-observer-distanceTitle
ThisreportermustbecalledfromtheObservercontext.Returnstheobserver’sdistancefromits“focuspoint”
view2.5d:set-observer-distance
view2.5d:set-observer-distanceTitlenew-distance
ThiscommandmustbecalledfromtheObservercontext.Updatesonlytheturtle-viewwindowwiththespecifiedtitle(ifany).Setstheobserver’sdistancefromits“focuspoint”
view2.5d:remove-patch-view
view2.5d:remove-patch-viewTitle
Thiscommandclosesandremovesthespecifiedpatchviewprogrammatically(equivalenttoclosingthewindowmanually).
view2.5d:remove-turtle-view
view2.5d:remove-turtle-viewTitle
Thiscommandclosesandremovesthespecifiedturtleviewprogrammatically(equivalenttoclosingthewindowmanually).
view2.5d:remove-all-patch-views
view2.5d:remove-all-patch-views
Thiscommandclosesandremovesallpatchviewsprogrammatically(equivalenttoclosingthewindowsmanually).
view2.5d:remove-all-turtle-views
view2.5d:remove-all-turtle-views
Thiscommandclosesandremovesallturtleviewsprogrammatically(equivalenttoclosingthewindowsmanually).
view2.5d:count-windows
view2.5d:count-windows
Thisreporterreturnsthenumberofturtleandpatchviewsthatarecurrentlyactive.
![Page 353: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/353.jpg)
FAQ(FrequentlyAskedQuestions)
FeedbackfromusersisveryvaluabletousindesigningandimprovingNetLogo.We'dliketohearfromyou.(SeeContactingUs.)
Questions
General
WhyisitcalledNetLogo?HowdoIciteNetLogoorHubNetinapublication?HowdoIciteamodelfromtheModelsLibraryinapublication?WhereandwhenwasNetLogocreated?WhatprogramminglanguagewasNetLogowrittenin?What'sthedifferencebetweenStarLogoandNetLogo?UnderwhatlicenseisNetLogoreleased?Isthesourcecodeavailable?DoyouofferanyworkshopsorothertrainingopportunitiesforNetLogo?ArethereanyNetLogotextbooks?IsNetLogoavailableinotherlanguagesbesidesEnglish?IsNetLogocompiledorinterpreted?Hasanyonebuiltamodelof<x>?AreNetLogomodelsrunsscientificallyreproducible?WillNetLogoandNetLogo3Dremainseparateapplications?CanIrunNetLogoonmytabletorphone?
Downloading
CanIhavemultipleversionsofNetLogoinstalledatthesametime?I'monaUNIXsystemandIcan'tuntarthedownload.Why?HowdoIinstallNetLogounattended?
Running
CanIrunNetLogofromaCD,anetworkdrive,oraUSBdrive?WhyisNetLogosomuchslowerwhenIunplugmyWindowslaptop?WhydoesNetLogobundleJava?HowcomeNetLogowon'tstartuponmyLinuxmachine?WhenItrytoinstallNetLogoonWindows,Isee"WindowsprotectedyourPC"WhenItrytostartNetLogoonWindowsIgetanerror"TheJVMcouldnotbestarted".Help!NetLogowon'tstartonMacOSSierra(orlater)NetLogowon'tstartonWindowsorcrashessuddenlyonMacOSSierraCanIrunNetLogofromthecommandline,withouttheGUI?DoesNetLogotakeadvantageofmultipleprocessors/cores?CanIdistributeNetLogomodelrunsacrossaclusterorgridofcomputers?IsthereanywaytorecoverlostworkifNetLogocrashesorfreezes?
Usage
WhenImovethespeedsliderallthewaytotheright,whydoesmymodelseemtostop?CanIusethemouseto"paint"intheview?Howbigcanmymodelbe?Howmanyturtles,patches,procedures,buttons,andsooncanmymodelcontain?CanIuseGISdatainNetLogo?Mymodelrunsslowly.HowcanIspeeditup?CanIhavemorethanonemodelopenatatime?CanIchangethechoicesinachooseronthefly?CanIdividethecodeformymodelupintoseveralfiles?
![Page 354: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/354.jpg)
Programming
HowdoestheNetLogolanguagedifferfromotherLogos?HowcomemymodelfromanearlierNetLogodoesn'tworkright?HowdoItakethenegativeofanumber?Myturtlemovedforward1,butit'sstillonthesamepatch.Why?HowdoIkeepmyturtlesonpatchcenters?patch-ahead 1isreportingthesamepatchmyturtleisalreadystandingon.Why?HowdoIgivemyturtles"vision"?Canagentssensewhat'sinthedrawinglayer?I'mgettingnumberslike0.10000000004and0.799999999999insteadof0.1and0.8.Why?Thedocumentationsaysthatrandom-float 1.0mightreturn0.0butwillneverreturn1.0.WhatifIwant1.0tobeincluded?HowcanIusedifferentpatch"neighborhoods"(circular,VonNeumann,Moore,etc.)?HowcanIkeeptwoturtlesfromoccupyingthesamepatch?HowcanIfindoutifaturtleisdead?DoesNetLogohavearrays?DoesNetLogohavehashtablesorassociativearrays?HowcanIconvertanagentsettoalist,orviceversa?HowdoIstopforeach?I'mtryingtomakealist.WhydoIkeepgettingtheerror"Expectedaconstant"?
BehaviorSpace
WhyaretherowsinmyBehaviorSpacetableresultsoutoforder?HowdoIgatherdataeverynticks?I'mvaryingaglobalvariableIdeclaredintheCodetab,butitdoesn'twork.Why?
NetLogo3D
DoesNetLogo3Dworkwithmystereoscopicdevice?
Extensions
I'mwritinganextension.Whydoesthecompilersayitcan'tfindorg.nlogo.api?
General
WhyisitcalledNetLogo?
The"Logo"partisbecauseNetLogoisadialectoftheLogolanguage.
"Net"ismeanttoevokethedecentralized,interconnectednatureofthephenomenayoucanmodelwithNetLogo,includingnetworkphenomena.ItalsoreferstoHubNet,themultiuserparticipatorysimulationenvironmentincludedinNetLogo.
HowdoIciteNetLogoorHubNetinapublication?
IfyouuseorrefertoNetLogo,HubNetoramodelfromtheNetLogomodelslibrary,weaskthatyouciteitasfollows:
NetLogoitself:Wilensky,U.1999.NetLogo.http://ccl.northwestern.edu/netlogo/.CenterforConnectedLearningandComputer-BasedModeling,NorthwesternUniversity.Evanston,IL.
![Page 355: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/355.jpg)
HubNet:Wilensky,U.&Stroup,W.,1999.HubNet.http://ccl.northwestern.edu/netlogo/hubnet.html.CenterforConnectedLearningandComputer-BasedModeling,NorthwesternUniversity.Evanston,IL.
HowdoIciteamodelfromtheModelsLibraryinapublication?
Thecorrectcitationisincludedinthe"CreditsandReferences"sectionofeachmodel'sInfotab.
WhereandwhenwasNetLogocreated?
NetLogowasfirstcreatedin1999byUriWilenskyattheCenterforConnectedLearningandComputer-BasedModeling,thenatTuftsUniversityintheBostonarea.NetLogogrewoutofStarLogoT,whichwasauthoredbyWilenskyin1997.In2000,theCCLmovedtoNorthwesternUniversity,intheChicagoarea.NetLogo1.0cameoutin2002,2.0in2003,3.0in2005,4.0in2007,4.1in2009,and5.0in2012.
WhatprogramminglanguagewasNetLogowrittenin?
NetLogoiswrittenmostlyinScala,withsomepartsinJava.(ScalacodecompilestoJavabytecodeandisfullyinteroperablewithJavaandotherJVMlanguages.)
What'stherelationshipbetweenStarLogoandNetLogo?
TheoriginalStarLogobeganattheMITMediaLabin1989andranontheConnectionMachine.LaterversionsweredevelopedforMacintoshcomputers:MacStarLogo(1994,MIT)andStarLogoT(1997,Tufts).
TodaytherearetwoStarLogodescendantsunderactivedevelopment:NetLogo(fromtheCCLatNorthwesternUniversity)andStarLogoTNG(fromMIT).NetLogoisthemostwidelyusedagent-basedmodelingenvironmentinbotheducationandresearch.StarLogoTNGisdistinguishedbyitsprogramminginterfacebasedoncoloredblocks.
UnderwhatlicenseisNetLogoreleased?Isthesourcecodeavailable?
NetLogoisfree,opensourcesoftwareundertheGPL(GNUGeneralPublicLicense),version2,or(atyouroption)anylaterversion.
Commerciallicensesarealsoavailable.Toinquireaboutcommerciallicenses,[email protected].
ThesourcecodeisonGitHub,here.Developmentdiscussionisonthenetlogo-develgroup.
TheUserManualispublishedunderaCreativeCommonsAttribution-ShareAlikelicense(CCBY-SA3.0).
SourcecodeforalloftheextensionsbundledwithNetLogoisonGitHub,here.Mostoftheextensionsareinthepublicdomain(CC0notice).Otherextensionsarereleasedunderopensourcelicenses.Seeeachextension'sREADMEfordetails.
TheCodeExamplesintheModelsLibraryareinthepublicdomain(CC0notice).
![Page 356: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/356.jpg)
TherestofthemodelsintheModelsLibraryareprovidedunderavarietyoflicenses.Somearepublicdomainandsomeareopensource,butmostareundertheCreativeCommonsAttribution-ShareAlikelicense(CCBY-NC-SA),whichisnotanopensourcelicense,thoughthemodelsarefreefornoncommercialdistributionanduse.
Seeeachmodel'sInfotabtocheckitsparticularlicense.
ThemodelsareinapublicGitrepositoryhere.
DoyouofferanyworkshopsorothertrainingopportunitiesforNetLogo?
Weofferworkshopsfromtimetotime.Ifaworkshophasbeenscheduled,wewillannounceitontheNetLogoUsersGroup.
ArethereanyNetLogotextbooks?
TheCCLhaspublishedatextbook(writtenbytheauthorofNetLogo)thatgivesanintroductiontoagent-basedmodelingmethodsusingNetLogo.Itgoesstepbystepwithcodingexampleshowtodesign,build,revise,andanalyzemodels.Anditpresentssomeadvancedtechniques.
Seewww.intro-to-abm.comformoreinformationonthattextbook.
SeetheTextbookssectionofourResourcespage.
WeattheCCLhavehopedtowriteseveralmoreNetLogotextbooks.Thesecouldbeaimedatdifferentaudiences,suchas:middleschool,highschool,undergraduatecourseinmodelingorcomplexity,practicalguideforinterestedadults.
Unfortunately,wehavenotyetbeenabletofindthetimetomakethesehappen.Ifanyonefromtheusercommunitywouldliketocollaborateonsuchaventure,pleaseletusknow.Wewouldwelcomeit.
IsNetLogoavailableinotherlanguagesbesidesEnglish?
VolunteershavetranslatedtheusermanualintoChineseandCzech.ThetranslatedversionsareavailablefromtheNetLogowebsite.
Sofar,theNetLogouserinterfacehasbeenlocalizedinEnglish,Spanish,Chinese,Russian,andJapanese.Allfivelanguagesareincludedinthestandarddownload.
WeareseekingvolunteerstocompleteandimprovetheselocalizationsandtotranslatetheNetLogosoftwareandmanualintoasmanyotherlanguagesaspossible.Ifyou'reabletohelpinthisendeavor,pleasecontactus.
IsNetLogocompiledorinterpreted?
Shortanswer:someofboth.
Longanswer:NetLogodoesincludeacompilerthatgeneratesJavabytecode.However,thiscompilerdoesnotyetsupporttheentirelanguage,sosomepartsofusercoderemaininterpreted.NotethatourcompilergeneratesJavabytecode,andJavavirtualmachineshave
![Page 357: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/357.jpg)
"just-in-time"compilersthatinturncompileJavabytecodeallthewaytonativecode,somuchusercodeisultimatelytranslatedtonativecode.
Hasanyonebuiltamodelof<x>?
TrylookingattheNetLogoModelsLibrary,theNetLogoModelingCommons,ourCommunityModelspage,andourlistofreferencestoNetLogoinoutsideworks.
YoumightalsoaskthequestionontheNetLogoUsersGroupand/orsearchpastmessagesonthegroup.
AreNetLogomodelsrunsscientificallyreproducible?
Yes.NetLogo'spseudorandomnumbergeneratorandagentschedulingalgorithmsaredeterministic,andNetLogoalwaysusesJava's"strictmath"library,whichgivesbit-for-bitidenticalresultsregardlessofplatform.Butkeepthefollowingcautionsinmind:
Ifyourmodelusesrandomnumbers,theninordertogetreproduciblebehavior,youmustusetherandom-seedcommandtosettherandomseedinadvance,sothatyourmodelwillreceivetheexactsamesequenceofrandomnumberseverytime.Rememberthatagentsetsarealwaysinrandomorder,soanythingyoudowithagentsetsusesrandomnumbers.Ifyourmodelusestheeveryorwaitcommandsinsuchawaythataffectstheoutcomeofthemodel,thenyoumaygetdifferentresultsondifferentcomputers,orevenonthesamecomputer,sincethemodelmayrunatadifferentspeed.Inordertoreproducemodelrunsexactly,youmustbeusingtheexactsameversionofNetLogo.ThedetailsoftheagentschedulingmechanismandtherandomnumbergeneratormaychangebetweenNetLogoversions,andotherchanges(bugfixesintheengine,languagechanges,andsoforth)mayalsoaffectthebehaviorofyourmodel.(Thenagain,theymaynot.)WehaveexpendedeveryefforttomakeNetLogomodelrunsfullyreproducible,butofcoursethiscannevertrulybeaniron-cladguarantee,duenotonlytothepossibilityofrandomhardwarefailure,butalsothepossibilityofhumanerrorinthedesignof:yourmodel,NetLogo,yourJavaVM,yourhardware,andsoon.
WillNetLogoandNetLogo3Dremainseparate?
Fornow,yes.NetLogo3DisincludedwithNetLogo,butitisstillaseparateapplication.
Ideallyasingleunifiedapplicationwouldsupportboth2Dand3Dmodeling.Wewoulddesignthe3Dworldsupportsoitdoesn'tgetinthewaywhenyouarebuilding2Dmodels.ModelsbuiltinNetLogo3Dmightrequirechangesinordertoruninthehypotheticalunifiedapplication.
CanIrunNetLogoonmyphoneortablet?
No.NeitheriOS,norAndroid,norWindowsRTsupportsrunningJavaapplicationssuchasNetLogo.
WeareworkingonanalternateimplementationofNetLogoonaJavaScriptandHTML5base,insteadofJava.Itwillworkonavarietyoftabletsandphones.Wedon'tknowyetwhenitwillbeready,andweexpectthatforalongtimeitwillonlysupportasubsetofthefeaturesindesktopNetLogo.Themanyperson-yearsofdevelopmenteffortthathavegoneintothe
![Page 358: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/358.jpg)
Javaversioncan'tcheaplyoreasilybereplicatedonanotherplatform.
Fortechnicaldetailsonthisnewproject,gohere.
Downloading
CanIhavemultipleversionsofNetLogoinstalledatthesametime?
Yes.WhenyouinstallNetLogo,thefolderthatiscreatedcontainshastheversionnumberinitsname,somultipleversionscancoexist.
OnWindowssystems,whicheverversionyouinstalledlastwillbetheversionthatopenswhenyoudoubleclickamodelfileinWindowsExplorer.OnMacs,youcancontrolwhatversionopensvia"GetInfo"intheFinder.
I'monaUNIXsystemandIcan'tuntarthedownload.Why?
Someofthefilesinthetarballhavelongpathnames,toolongforthestandardtarformat.YoumustusetheGNUversionoftarinstead(oranotherprogramwhichunderstandstheGNUtarextensions).Onsomesystems,theGNUversionoftarisavailableunderthename"gnutar".YoucanfindoutifyouarealreadyusingtheGNUversionbytypingtar --versionandseeingiftheoutputsays"tar(GNUtar)".
HowdoIinstallNetLogounattended
Itdependsonwhichplatformyouareusing.
Linux:UntarNetLogointotheappropriateplace.
Mac:CopytheNetLogodirectoryfromthediskimageintotheApplicationsfolder.
Windows:
Runtheinstallerfromthecommandlineusingthe-qoption:
NetLogo6.0.2Installer.exe -q
Running
CanIrunNetLogofromaCD,anetworkdrive,oraUSBdrive?
Yes.NetLogorunsfinefromanyfilesystem,includingread-onlyfilesystems.
WhyisNetLogosomuchslowerwhenIunplugmyWindowslaptop?
Yourcomputerisswitchingtopowersavingmodewhenunplugged.It'snormalforthistoreducespeedalittle,butunfortunatelythereisabuginJavathatdrasticallyslowsdownSwingapplications,includingNetLogo.
Oneworkaroundistochangethepowersettingsonyourcomputersoitdoesn'tgointopower
![Page 359: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/359.jpg)
savingmodewhenyouunplugit.(Ifyoudothis,yourbatterywon'tlastaslong.)
AnotherworkaroundistorunNetLogowithanoptionrecommendedbyOracle,byeditingtheNetLogo6.0.2.vmoptionsfile,foundintheNetLogodirectory(underProgramFilesonyourharddrive,unlessyouinstalledNetLogoinadifferentlocation).Addonanewline:
-Dsun.java2d.ddoffscreen=false
YoucanseethedetailsoftheJavabugandvoteforOracletofixithere.
WhydoesNetLogobundleJava?
SinceMacOSXLion,ApplehaveencouragedMacapplicationdeveloperstobundleJava.NetLogobundlesJavabecauseitallowsustodeliveraconsistent,convenientexperiencetoourusers.BundlingJavaallowsustotestforcompatibilityonceandavoidanybugscausedbyversionmismatchesorJavaconfigurationincompatibilities.
IfusersareinterestedinusingJavaontheirsysteminsteadoftheversionofJavabundledwithNetLogo,theycanconfigureNetLogotouseadifferentJavaruntime.Pleasenotethatthischangeisdoneatyourownrisk.WeareunabletooffersupportforproblemscausedbyrunningNetLogowithanalternateJavaRuntime.TochangetheJavaruntimeusedbyNetLogo,opentheNetLogo.cfgfileandmodifytheapp.runtimepropertytothepathofyourpreferredJavaRuntime.
HowcomeNetLogowon'tstartuponmyLinuxmachine?
WebundleOracle'sJavaruntimewhenusingNetLogoonLinux.Ifyouwouldliketochangetheversionoflinuxused,youcanmodifythe.cfgfilestopointtoadifferentversionofjava(seeHowbigcanmymodelbe?formoreinformation).
Intheory,anyJava8orlaterruntimewillrunNetLogo.Inpractice,someJavaimplementationsaren'thighenoughquality.RecentversionsofOpenJDKshouldwork;olderonesmaynot.GNUlibgcjdoesnotwork.
Ubuntuusersshouldconsulthttp://help.ubuntu.com/community/Java.
WhenItrytoinstallNetLogoonWindows,Isee"WindowsprotectedyourPC"
Windowsattemptstoprotectusersfromdownloadingmalicioussoftwarebymaintainingalistof"good"and"malicious"software.ThefirstuserstoinstallanyNetLogoreleasewillseethiswarning.Laterusersmayormaynotseethiswarning.Beforegoinganyfurther,ensureyouareprotected.TheCCLcanonlyvouchforNetLogodownloadshostedontheCCLWebsite.NetLogocanbefreelydownloadedfromtheofficialNetLogodownloadpage.IfyouobtainNetLogofromanywhereelse,youinstallitatyourownrisk!
YoucancontinuepasttheWindowspromptbytakingthefollowingsteps:
Inthe"WindowsprotectedyourPC"prompt,click"MoreInfo",thepromptwillchangeInthechangedprompt,click"RunAnyway"andcontinuewithinstallationasnormal
Noteinordertoseethe"MoreInfo"or"RunAnyway"options,youwillneedtoruntheinstallerasanadministrator.Ifyoudonotseethoseoptions,right-clickandchoose"Runas
![Page 360: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/360.jpg)
administrator"and/orchangeyouruseraccounttoanadministratoraccountbeforeinstalling.
WeattheCCLareworkingonsolvingthisproblemandhopetofreeourusersoftheaddedinstallationdifficultysoon!
WhenItrytostartNetLogoonWindowsIgetanerror"TheJVMcouldnotbestarted".Help!
AnearlycertainfixistouseatexteditortoedittheNetLogo.cfgfile,changing1024mtoasmallernumber,like512m.ThisshouldpermitNetLogotostart,althoughthelowerheapsizelimitmayaffectyourabilitytorunmodelswithmanyagents.SeeHowbigcanmymodelbe?forinformationonmodelsizeandhowtoeditthecfgfile.
Ifrunningwiththelowerheapsizelimitisunacceptable,readon.
SomeWindowssystemshavetroubleallocatinglargeamountsofcontiguousvirtualmemory.UpgradingtoanewerversionofWindowsmayhelp.
RunningWindowsin64-bitmodeinsteadof32-bitmodemayalsohelp.DoublecheckthatWindowsisactuallyrunningin64-bitmode;seeMicrosoft'sFAQpageon64-bitWindows.
NetLogowon'tstartonMacOSSierra(orlater)
SomeusershavereportedproblemsopeningNetLogo6onMacOSSierra.We'vebeenunabletodeterminearootcauseforthisproblem,butwe'recontinuingtoinvestigate.We'relookingforassistancefromyouifyourunintothisproblem.Itwouldbeextremelyhelpfulifyoucouldrunthefollowingcommandinthe"Terminal"[email protected].
xattr -pl com.apple.quarantine /Applications/NetLogo\ 6.0/NetLogo\ 6.0.app
runningitshouldgiveyouasinglelineofoutput(somethinglikecom.apple.quarantine:01e1;58ac6af2;Firefox;F2E0B1E2-D203-4B05-8DF9-ABA58B52EFEA,butyourswillhavedifferentnumbers,letters,andwords).Pleasecopyandpastethisstringintotheemailyousendus.
Thereisalsoapartialworkaround!RunningthefollowingcommandintheTerminalwillenableuserstorunNetLogowithoutturningGatekeepercompletelyoff.Thecommandis:
sudo xattr -dr com.apple.quarantine /Applications/NetLogo\ 6.0/NetLogo\ 6.0.app
NotethatifyouplantorunNetLogo3D,HubNetClient,orNetLogoLogging,youmayalsoneedtore-runthatcommandonceforeachofthoseapplications.Iftheworkaroundwasnoteffectiveforyou,pleasesendusanemailandletusknow.
NetLogowon'tstartonWindowsorcrashessuddenlyonMacOSSierra
SomeusersonMacOSwithdiscretegraphicscardsexperiencesuddencrashesofNetLogowhenswitchingbetweenintegratedanddiscretegraphics.It'spossibletopreventthesecrashesbydisablingautomaticgraphicsswitchinginSystemPreferences.
SomeWindowsusersmayalsobeunabletoopenNetLogoduetographicscardsettingsor
![Page 361: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/361.jpg)
drivers.IfyouareunabletoopenNetLogoonWindows,youmightbeabletofixthisbyupdatingorreinstallingyourgraphicsdriverand/ordisablinganygraphicscardutilities.BecauseNetLogomightbeunabletostartforanumberofreasons,weencourageyoutocontactusifthesestepsaren'teffectiveinresolvingtheproblem.
CanIrunNetLogofromthecommandline,withouttheGUI?
Yes.TheeasiestwayistosetupyourmodelrunorrunsasaBehaviorSpaceexperiment.Noadditionalprogrammingisrequired.SeetheBehaviorSpaceGuidefordetails.
AnotheroptionistouseourControllingAPI.SomelightJavaprogrammingisrequired.SeetheControllingAPIGuidefordetailsandsamplecode.
DoesNetLogotakeadvantageofmultipleprocessors?
OnlywhenusingBehaviorSpace.BehaviorSpacedoesparallelruns,oneperprocessor.
Forasinglemodelrun,onlyoneprocessorisused.
Weareseekingfundingtomakeitpossibletosplitasinglemodelrunacrossmultipleprocessorsormultiplecomputers.
CanIdistributeNetLogomodelrunsacrossaclusterorgridofcomputers?
Manyofthesamecommentsinthepreviousanswerapply.Itisnotpossibletosplitasinglemodelrunacrossmultiplecomputers,butyoucanhaveeachmachineinaclusterdoingoneormoreseparate,independentmodelruns,usingeitherBehaviorSpaceorourControllingAPI.Wedon'thaveautomatedsupportforsplittingtherunsacrossclusters,soyou'llneedtoarrangethatyourself.
VarioususersarealreadyusingNetLogoonclusters,withavarietyofhardwareandsoftware.YoucanseekthemoutontheNetLogoUsersGroup.
IsthereanywaytorecoverlostworkifNetLogocrashesorfreezes?
Yes.NetLogoauto-savesfilesasyouareworkingonthem.Thepathtotheauto-savefiledependsonwhetherornottheNetLogomodelhasbeensaved.
ForNetLogomodelswhichhavebeensaved,ahiddenfilewiththename".filename.tmp.nlogo"willbecreatedinthesamedirectoryastheNetLogomodel.
ForunsavedNetLogomodels,autosavefilescanbefoundinyourOS-specificjavatemporarydirectory.Thefilesarenamedaccordingtothefollowingformat:autosave_yyyy-MM-dd.HH_mm_ss.nlogowherethetimeanddatearethetimeanddatethemodelwasopened.Theexactpathwilldependonyouroperatingsystem:
OnMacOS,thetemporarydirectoryis/var/folders/68/<30-character-alphanumeric-sequence>/T/.The30-character-alphanumeric-sequenceisuniquetoeachmachine.OnWindowsthelogscanbefoundinC:\Users\<user>\AppData\Local\Temp,where<user>istheloggedinuser.Onmostnon-MacUnix-likesystemsthetempdirectoryis/tmp.
![Page 362: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/362.jpg)
Usage
WhenImovethespeedsliderallthewaytotheright,whydoesmymodelseemtostop?
TheonlywayNetLogocanmakeyourmodelrunfasterisbyupdatingtheviewlessfrequently.Asyoumovethespeedslidertotheright,viewupdatesbecomelessandlessfrequent.Sinceviewupdatestaketime,thatmeansmorespeed.
However,fewerupdatesalsomeansthattheupdatescomefartherapart.Whenseveralsecondspassbetweenupdates,itmayseemlikeyourmodelhasstopped.Ithasn't.It'srunningatfullspeed.Watchthetickcounter!(Ifyourmodelusesit.Ifitdoesn't,watchsomethingelse,likeaplot.)
Togetafeelforwhat'sgoingon,trymovingtheslidertotherightgraduallyratherthansuddenly.Ifyoufindtheupdatestooinfrequentattherightmostposition,justdon'tpushthesliderthatfar.
CanIusethemouseto"paint"intheview?
NetLogodoesnothaveabuilt-insetofpaintingtoolsforpaintingintheview.Butwithonlyafewlinesofcode,youcanaddpaintingcapabilitytoyourmodel.Toseehowit'sdone,lookatMouseExample,intheCodeExamplessectionoftheModelsLibrary.Thesametechniquescanbeusedtolettheuserinteractwithyourmodelusingthemouseinotherways,too.
AnotherpossibilityistocreateanimageinanotherprogramandimportitusingtheimportitemsontheFilemenuortheimport-*primitives.
Howbigcanmymodelbe?Howmanyturtles,patches,procedures,buttons,andsooncanmymodelcontain?
WehavetestedNetLogowithmodelsthatusehundredsofmegabytesofRAMandtheyworkfine.Wehaven'ttestedmodelsthatusegigabytesofRAM,though.Theoreticallyitshouldwork,butyoumighthitsomelimitsthatareinherentintheunderlyingJavaVMand/oroperatingsystem(eitherdesigned-inlimits,orbugs).
TheNetLogoenginehasnofixedlimitsonsize.Bydefault,though,NetLogoshipswithaone-gigabyteceilingonhowmuchtotalRAMitcanuse.Ifyourmodelexceedsthatlimit,you'llgetanOutOfMemoryErrordialog.
IfyouareusingBehaviorSpace,notethatdoingrunsinparallelwillmultiplyyourRAMusageaccordingly.
Eachplatformcontains".cfg"filescontainingJVMsettings.Thereisonecfgfileforeachsub-application(NetLogo,NetLogo3D,HubNetClient,etc.)Althoughthefilelocationvariesbyplatform,theprocessforchangingitisthesame.Locatethesectionofthefilethatlookslikethefollowing:
[JVMOptions]# there may be one or more lines, leave them unchanged-Xmx1024m# there may be one or more lines, leave them unchanged
![Page 363: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/363.jpg)
Modifythevalueimmediatelyfollowing
-Xmx
,changingittotheamountofspaceyouneed,savethefile,andrestartNetLogo.Platformspecificnotesfollow:
Windows:Thecfgfileswillbein
C:\Program Files (x86)\NetLogo 6.0.2\app
ifyouarerunning64-bitwindows,and
C:\Program Files\NetLogo 6.0.2\app
otherwise.MacOSX:ThefileforNetLogowillbelocatedat:
/Application/NetLogo 6.0.2/NetLogo.app/Contents/Java/NetLogo.cfg
ForNetLogo3Dandtheotherapplications,youwillfindthefileinthecorrespondinglocationforeachapplicationpackage.Youcanreachthecfgfilebycontrol-clickingtheapplicationintheFinderandchoosing"ShowPackageContents"fromthepopupmenu.
PleasenotethatdependingonyourversionofMacOSX,changingthecfgfile*may*breakapplicationsigning.Ifthishappens,followApple'sdirectionsonthispagetotemporarilyallowappsfrom"Anywhere",runNetLogoonce,thenrestorethesettingto"MacAppStoreandIdentifiedDevelopers".
Other:Thecfgfileswillbelocatedinthe
netlogo-6.0.2/app
folderafteruntarring.
Bydefault,MacbuildsofNetLogobundlea64-bitJVM,whichshouldbeabletomakeuseofasmuchmemoryasthelesserofavailablesystemmemoryandthevaluefollowing
-Xmx
.WindowsandLinuxwillbundlea32-bitor64-bitJVM,dependingonwhichversionyouhavedownloaded.Itisrecommendedthatyouinstall64-bitNetLogoonall64-bitoperatingsystemsforbestperformance.
CanIuseGISdatainNetLogo?
Yes,manyusersareusingGISdatawithNetLogo.ThemostcompletewaytodothatiswiththeGISextension.SeetheGISExtensionGuide.
Asimplerwayistouseimport-pcolors,butthatonlyworksforimportingmapsthatareimages,notmapsinotherformats.
![Page 364: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/364.jpg)
ItisalsopossibletowriteNetLogocodethatreadsGISdatausingourfileI/Oprimitivessuchasfile-open.Forexample,seetheGrandCanyonmodelintheEarthSciencesectionofSampleModels.
Mymodelrunsslowly.HowcanIspeeditup?
Here'ssomewaystomakeitrunfasterwithoutchangingthestructureofthecode:
Usetick-basedviewupdates,notcontinuousupdates.Decreasethefrequencyofviewupdatesbypushingthespeedslidertotheright,orturnupdatesoffusingthecheckbox.IfyourmodelisusingallavailableRAMonyourcomputer,theninstallingmoreRAMshouldhelp.Ifyourharddrivemakesalotofnoisewhileyourmodelisrunning,youprobablyneedmoreRAM.Useturtlesize1,1.5,or2,asthe2DrenderingsforthesesizesarecachedbyNetLogo.(Thisonlyaffectsgraphicsspeedinthe2Dview,notcomputationspeed.)
Inmanycases,though,ifyouwantyourmodeltorunfaster,youmayneedtomakesomechangestothecode.Usuallythemostobviousopportunityforspeedupisthatyou'redoingtoomanycomputationsthatinvolvealltheturtlesorallthepatches.Oftenthiscanbereducedbyreworkingthemodelsothatitdoeslesscomputationpertimestep.ThemembersoftheNetLogoUsersGroupmaybeabletohelpwiththis.
Theprofilerextensionisusefulforidentifyingwhichpartsofyourcodearetakingthemosttime.
Unlessyouarerunningtheexactsamestringsoverandover,usingrunandrunresultaremuchslowerthanrunningcodedirectly;youshouldavoidusingtheseprimitivesonfreshstringsinperformance-criticalcode.
CanIhavemorethanonemodelopenatatime?
OneinstanceofNetLogocanonlyhaveonemodelopenatatime.(Unfortunately,itisunlikelythatthiswillchangeinafutureversion,duetotheengineeringdifficultiesinvolved.)
YoucanhavemultiplemodelsopenbyopeningmultipleinstancesofNetLogo,though.OnWindowsandLinux,simplystarttheapplicationagain.OnaMac,you'llneedtoduplicatetheapplication(notthewholefolder,justtheapplicationitself)intheFinder,thenopenthecopy.(Thecopytakesuponlyaverysmallamountofadditionaldiskspace.)
CanIchangethechoicesinachooseronthefly?
No.
CanIdividethecodeformymodelupintoseveralfiles?
Onanexperimentalbasis,thisisavailableusingthe__includeskeyword.
Programming
HowdoestheNetLogolanguagedifferfromotherLogos?
![Page 365: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/365.jpg)
ThisisansweredindetailattheendoftheProgrammingGuide.
HowcomemymodelfromanearlierNetLogodoesn'tworkright?
SeetheTransitionGuideforhelp.
HowdoItakethenegativeofanumber?
Anyoftheseways:
(- x)-1 * x0 - x
Withthefirstway,theparenthesesarerequired.
Myturtlemovedforward1,butit'sstillonthesamepatch.Why?
Ifyouhavedisabledwrappingattheworldedgesinyourmodel,thentheturtlemightbeataworldedgeandunabletomoveanyfurther.Youcantestforthisusingcan-move?.
Assumingtheturtleisn'thittingaworldedge,movingforward1isonlyguaranteedtotakeaturtletoanewpatchiftheturtle'sheadingisamultipleof90(thatis,exactlynorth,south,east,orwest).
It'sbecausetheturtlemightnotbestandinginthecenterofapatch.Itmightbenearthecornerofapatch.Forexample,supposeyourturtleisclosetothesouthwestcornerofapatchandisfacingnortheast.Thelengthofthepatchdiagonalis1.414...(thesquarerootoftwo),sofd 1willleavetheturtlenearthenortheastcornerofthesamepatch.
Ifyoudon'twanttohavetothinkabouttheseissues,onepossibilityistowriteyourmodelinsuchawaythatyourturtlesalwayscometorestonpatchcenters.Seenextquestion.
HowdoIkeepmyturtlesonpatchcenters?
Aturtleisonapatchcenterwhenitsxcorandycorareintegers.
Youcanmoveaturtletothecenterofitscurrentpatchwitheitherofthesetwoequivalentcommands:
move-to patch-heresetxy pxcor pycor
Butyou'llneverneedtodothatifyouneverallowturtlesoffofpatchcentersinthefirstplace.
Thesproutcommandcreatesturtlesonpatchcenters.Forexample:
ask n-of 50 patches [ sprout 1 [ face one-of neighbors4 ] ]
Anotherwayforaturtletostartonapatchcenteriswithacommandsuchasthislineofturtlecode,whichmovesittothecenterofarandompatch:
![Page 366: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/366.jpg)
move-to one-of patches
Onceaturtleisonapatchcenter,aslongasitsheadingalwaysstaysanexactmultipleof90(thatistosay,duenorth,east,south,orwest),andasitlongasitmovesforwardorbackbyintegeramounts,itwillalwayslandonpatchcenters.
SeeRandomGridWalkExample,intheCodeExamplessectionoftheModelsLibrary,toseethesecodesnippetsinuse.
patch-ahead 1isreportingthesamepatchmyturtleisalreadystandingon.Why?
Seetheanswertwoanswersup.It'sthesameissue.
Thismightnotbethemeaningof"ahead"youwereexpecting.Withpatch-ahead,youmustspecifythedistanceaheadthatyouwanttolook.Ifyouwanttoknowthenextpatchaturtlewouldcrossintoifitmovedforwardcontinuously,itispossibletofindthatout.SeeNextPatchExample,intheCodeExamplessectionoftheModelsLibrary.
HowdoIgivemyturtles"vision"?
Youcanusein-radiustoletaturtleseeacircularareaaroundit.
Severalprimitiveslettheturtle"look"atspecificpoints.Thepatch-aheadprimitiveisusefulforlettingaturtleseewhatisdirectlyinfrontofit.Ifyouwanttheturtletolookinanotherdirectionbesidesstraightahead,trypatch-left-and-aheadandpatch-right-and-ahead.
Ifyouwanttheturtletohaveafull"cone"ofvision,usethein-coneprimitive.
Youcanalsofindoutthenextpatchaturtlewouldcrossintoifitmovedforwardcontinuously.SeeNextPatchExample,intheCodeExamplessectionoftheModelsLibrary.
Canagentssensewhat'sinthedrawinglayer?
No.Ifyouwanttomakemarksthatagentscansense,usepatchcolors.
I'mgettingnumberslike0.10000000004and0.799999999999insteadof0.1and0.8.Why?
Seethe"Math"sectionoftheProgrammingGuideforadiscussionofthisissue.
Thedocumentationsaysthatrandom-float 1mightreturn0butwillneverreturn1.WhatifIwant1tobeincluded?
Itreallydoesn'tmatter.Evenif1wereapossibleresult,itwouldonlycomeupapproximately1in2^64tries,whichmeansyou'dbewaitinghundredsofyearsbeforeitevercameupexactly1.
Nonetheless,ifyouareconvincedthatitreallymustbepossibletoget1,youcanuseprecisiontoroundyouranswertoacertainnumberofdecimalplaces.Forexample:
![Page 367: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/367.jpg)
print precision (random-float 1) 100.2745173723
(Ifyouusethismethod,notethat0and1areonlyhalfaslikelytocomeupasotheranswers.Toseewhythisisso,considerthecasewhereyouonlykeeponedigitafterthedecimalpoint.Resultsbetween0and0.5getroundedto0,butresultsbetween0.5and1.5getroundedto1;thelatterrangeistwiceaslarge.Ifyouwant0,0.1,0.2,...,0.9,and1toallbeequallylikely,analternativeistowriterandom 11 / 10 ;thisgivesall11answerswithequalprobability.)
HowcanIkeeptwoturtlesfromoccupyingthesamepatch?
SeeOneTurtlePerPatchExample,intheCodeExamplessectionoftheModelsLibrary.
HowcanIfindoutifaturtleisdead?
Whenaturtledies,itturnsintonobody.nobodyisaspecialvalueusedinNetLogousedtoindicatetheabsenceofaturtleorpatch.Soforexample:
if turtle 0 != nobody [ ... ]
Youcouldalsouseis-turtle?:
if is-turtle? turtle 0 [ ... ]
DoesNetLogohavearrays?
Nearlyallmodelsshouldjustuselistsforthis.
Theusualmotivationforusingarraysinotherprogramminglanguagesisthattheyprovidefastrandomaccess(item)andmutation(replace-item).ButNetLogo'slists,eventhoughtheyareimmutable,nowprovidenearconstanttimeperformanceontheseoperations.
ListsinearlierversionsofNetLogo(4.1and4.0)weresimplesingly-linkedlistsandthereforetheseoperationstooklineartime.ThedatastructureunderlyingNetLogo'slistsnowistheimmutableVectorclassfromtheScalacollectionslibrary.Ituses32-widehasharraymappedtries,asimplementedbyTiarkRompf,basedinpartonworkbyPhilBagwellandRichHickey.
Ifyouarecertainyouwanttouseraw,mutableJVMarraysinyourmodel,theyareprovidedbythearrayextension.SeetheArrays&TablessectionoftheUserManual.
DoesNetLogohavehashtablesorassociativearrays?
Yes,usingthetableextension.SeetheArrays&TablessectionoftheUserManual.
HowcanIusedifferentpatch"neighborhoods"(circular,VonNeumann,Moore,etc.)?
Thein-radiusprimitivesletsyouaccesscircularneighborhoodsofanyradius.
![Page 368: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/368.jpg)
TheneighborsprimitivegivesyouaMooreneighborhoodofradius1,andtheneighbors4primitivegivesyouaVonNeumannneighborhoodofradius1.
ForMooreorVonNeumannneighborhoodsofalargerradius,seeMoore&VonNeumannExampleintheCodeExamplessectionoftheModelsLibrary.
HowcanIconvertanagentsettoalistofagents,orviceversa?
Ifyouwantthelistinaparticularorder,usethesortorsort-byprimitives.TheListssectionoftheProgrammingGuideexplainshowtodothis.SeealsoAskOrderingExample,intheCodeExamplessectionoftheModelsLibrary.
Ifyouwantthelistinarandomorder,here'show:
[self] of <agentset>
Becausealloperationsonagentsetsareinrandomorder,theresultinglistisinrandomorder.
Toconvertalistofagentstoanagentset,usetheturtle-set,patch-set,orlink-setprimitives.
HowdoIstopforeach?
Tostopaforeachfromexecutingyouneedtodefineaseparateprocedurethatcontainsonlytheforeach,forexample:
to test foreach [1 2 3] [ i -> if i = 2 [ stop ] print i ]end
Thiscodewillonlyprintthenumber1.Thestopreturnsfromthecurrentproceduresonothingaftertheforeachwillbeexecutedeither.(Iftheprocedureisareporterprocedure,usereportinsteadofstop.)
I'mtryingtomakealist.WhydoIkeepgettingtheerror"Expectedaconstant"?
Ifalistcontainsonlyconstants,youcanwriteitdownjustbyputtingsquarebracketsaroundit,like[1 2 3] .
Ifyouwantyourlisttocontainitemsthatmayvaryatruntime,thelistcannotbewrittendowndirectly.Instead,youbuilditusingthelistprimitive.
BehaviorSpace
WhyaretherowsinmyBehaviorSpacetableresultsoutoforder?
Thisisnormalwhendoingmultiplerunsinparallel.Foradiscussionoftheissue,seethe
![Page 369: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/369.jpg)
sectiononparallelrunsintheBehaviorSpaceGuidesectionoftheUserManual.
HowdoImeasurerunseverynticks?
Userepeatinyourexperiment'sgocommands,e.g.:
repeat 10 [ go ]
tomeasuretherunafterevery10ticks.Essentiallyyouaremakingoneexperimentstepequal10ticks.
I'mvaryingaglobalvariableIdeclaredintheCodetab,butitdoesn'twork.Why?
It'sprobablybecauseyoursetupcommandsorsetupprocedureareusingclear-all,causingthevaluessetbyBehaviorSpacetobecleared.
Onepossibleworkaroundistochangeyourexperiment'ssetupcommandstopreservethevalueofthevariable,e.g.:
let old-var1 var1setupset var1 old-var1
Thisworksbecauseevenclear-alldoesn'tclearthevaluesoflocalvariablesmadewithlet
Anotherpossibleworkaroundistochangeyourmodel'ssetupproceduretousemorespecificclearingcommandstoclearonlywhatyouwantcleared.
NetLogo3D
DoesNetLogoworkwithmystereoscopicdevice?
NetLogosupportsfullscreenexclusivemode.Ifthatisallyourdeviceneedsthen,possiblyyes.However,itcanbetrickytogetitworking.Wedon'thaveanysuchdevicessoitisdifficultforustomaketheprocesseasier.Ifyourdeviceneedssomethingelse,forexample,quadbuffersenabled,theanswerisprobablyno.
Extensions
I'mwritinganextension.Whydoesthecompilersayitcan'tfindorg.nlogo.api?
YouneedtoaddNetLogo.jartoyourclasspathwhencompiling.NetLogo.jarisincludedwithNetLogo.
![Page 370: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/370.jpg)
NetLogoDictionaryAlphabetical:ABCDEFGHIJLMNOPRSTUVWXY->
Categories:Turtle-Patch-Links-Agentset-Color-AnonymousProcedures-Control/Logic-WorldPerspective-Input/Output-File-List-String-Math-Plotting-System-HubNet
Special:Variables-Keywords-Constants
Categories
Thisisanapproximategrouping.Rememberthataturtle-relatedprimitivemightstillbeusedbypatchesortheobserver,andviceversa.Toseewhichagents(turtles,patches,links,observer)canactuallyrunaprimitive,consultitsdictionaryentry.
Turtle-related
back(bk)<breeds>-at<breeds>-here<breeds>-oncan-move?clear-turtles(ct)create-<breeds>create-ordered-<breeds>create-ordered-turtles(cro)create-turtles(crt)diedistancedistancexydownhilldownhill4dxdyfacefacexyforward(fd)hatchhatch-<breeds>hide-turtle(ht)homeinspectis-<breed>?is-turtle?jumplayout-circleleft(lt)move-tomyselfnobodyno-turtlesofotherpatch-aheadpatch-atpatch-at-heading-and-distancepatch-herepatch-left-and-aheadpatch-right-and-aheadpen-down(pd)pen-erase(pe)pen-up(pu)random-xcorrandom-ycorright(rt)selfset-default-shape__set-line-thicknesssetxyshapesshow-turtle(st)sproutsprout-<breeds>stampstamp-erasestop-inspectingsubjectsubtract-headingstietowardstowardsxyturtleturtle-setturtlesturtles-atturtles-hereturtles-onturtles-ownuntieuphilluphill4
Patch-related
clear-patches(cp)diffusediffuse4distancedistancexyimport-pcolorsimport-pcolors-rgbinspectis-patch?myselfneighborsneighbors4nobodyno-patchesofotherpatchpatch-atpatch-aheadpatch-at-heading-and-distancepatch-herepatch-left-and-aheadpatch-right-and-aheadpatch-setpatchespatches-ownrandom-pxcorrandom-pycorselfsproutsprout-<breeds>stop-inspectingsubjectturtles-here
Link-related
both-endsclear-linkscreate-<breed>-fromcreate-<breeds>-fromcreate-<breed>-tocreate-<breeds>-tocreate-<breed>-withcreate-<breeds>-withcreate-link-fromcreate-links-fromcreate-link-tocreate-links-tocreate-link-withcreate-links-withdiehide-linkin-<breed>-neighbor?in-<breed>-neighborsin-<breed>-fromin-link-neighbor?in-link-neighborsin-link-fromis-directed-link?is-link?is-link-set?is-<link-breed>?is-undirected-link?layout-radiallayout-springlayout-tutte<breed>-neighbor?<breed>-neighbors<breed>-withlink-headinglink-lengthlink-neighbor?linklinkslinks-own<link-breeds>-ownlink-neighborslink-withmy-<breeds>my-in-<breeds>my-in-linksmy-linksmy-out-<breeds>my-out-linksno-linksother-endout-<breed>-neighbor?out-<breed>-neighborsout-<breed>-toout-link-neighbor?out-link-neighborsout-link-toshow-linktieuntie
Agentset
all?any?askask-concurrentat-points<breeds>-at<breeds>-here<breeds>-oncountin-conein-radiusis-agent?is-agentset?is-patch-set?is-turtle-set?link-setmax-n-ofmax-one-ofmember?min-n-ofmin-one-ofn-ofneighborsneighbors4no-linksno-patchesno-turtlesofone-ofotherpatch-setpatchessortsort-bysort-onturtle-setturtlesturtles-atturtles-hereturtles-onwithwith-maxwith-min
Color
approximate-hsbapproximate-rgbbase-colorscolorextract-hsbextract-rgbhsbimport-pcolorsimport-pcolors-rgbpcolorrgbscale-colorshade-of?wrap-color
Controlflowandlogic
andaskask-concurrentcarefullyenderrorerror-messageeveryififelseifelse-valueletloopnotorrepeatreportrunrunresult;(semicolon)setstopstartuptoto-reportwaitwhilewith-local-randomnesswithout-interruptionxor
AnonymousProcedures
->(anonymousprocedure)filterforeachis-anonymous-command?is-anonymous-reporter?mapn-valuesreducerunrunresultsort-by
World
clear-all(ca)clear-drawing(cd)clear-globalsclear-patches(cp)clear-ticksclear-turtles(ct)displayimport-drawingimport-pcolorsimport-pcolors-rgbno-displaymax-pxcormax-pycormin-pxcormin-pycorpatch-sizereset-ticksresize-worldset-patch-sizestop-inspecting-dead-agentsticktick-advanceticksworld-widthworld-height
Perspective
followfollow-mereset-perspective(rp)rideride-mesubjectwatchwatch-me
HubNet
hubnet-broadcasthubnet-broadcast-clear-outputhubnet-broadcast-messagehubnet-clear-overridehubnet-clear-overrideshubnet-clients-listhubnet-enter-message?hubnet-exit-message?hubnet-kick-all-clientshubnet-kick-clienthubnet-fetch-messagehubnet-messagehubnet-message-sourcehubnet-message-taghubnet-message-waiting?hubnet-resethubnet-reset-perspectivehubnet-sendhubnet-send-clear-outputhubnet-send-followhubnet-send-messagehubnet-send-overridehubnet-send-watch
Input/output
beepclear-outputdate-and-timeexport-viewexport-interfaceexport-outputexport-plotexport-all-plotsexport-worldimport-drawingimport-
![Page 371: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/371.jpg)
pcolorsimport-pcolors-rgbimport-worldmouse-down?mouse-inside?mouse-xcormouse-ycoroutput-printoutput-showoutput-typeoutput-writeprintread-from-stringreset-timerset-current-directoryshowtimertypeuser-directoryuser-fileuser-new-fileuser-inputuser-messageuser-one-ofuser-yes-or-no?write
File
file-at-end?file-closefile-close-allfile-deletefile-exists?file-flushfile-openfile-printfile-readfile-read-charactersfile-read-linefile-showfile-typefile-writeuser-directoryuser-fileuser-new-file
List
but-firstbut-lastempty?filterfirstforeachfputhistograminsert-itemis-list?itemlastlengthlistlputmapmaxmember?minmodesn-ofn-valuesofpositionone-ofrangereduceremoveremove-duplicatesremove-itemreplace-itemreversesentenceshufflesortsort-bysort-onsublist
String
Operators(<,>,=,!=,<=,>=)but-firstbut-lastempty?firstinsert-itemis-string?itemlastlengthmember?positionremoveremove-itemread-from-stringreplace-itemreversesubstringword
Mathematical
ArithmeticOperators(+,*,-,/,^,<,>,=,!=,<=,>=)absacosasinatanceilingcoseexpfloorintis-number?lnlogmaxmeanmedianminmodmodesnew-seedpiprecisionrandomrandom-exponentialrandom-floatrandom-gammarandom-normalrandom-poissonrandom-seedremainderroundsinsqrtstandard-deviationsubtract-headingssumtanvariance
Plotting
autoplot?auto-plot-offauto-plot-onclear-all-plotsclear-plotcreate-temporary-plot-penexport-plotexport-all-plotshistogramplotplot-nameplot-pen-exists?plot-pen-downplot-pen-resetplot-pen-upplot-x-maxplot-x-minplot-y-maxplot-y-minplotxyset-current-plotset-current-plot-penset-histogram-num-barsset-plot-background-colorset-plot-pen-colorset-plot-pen-intervalset-plot-pen-modeset-plot-x-rangeset-plot-y-rangesetup-plotsupdate-plots
BehaviorSpace
behaviorspace-experiment-namebehaviorspace-run-number
System
netlogo-versionnetlogo-web?
Built-InVariables
Turtles
breedcolorheadinghidden?labellabel-colorpen-modepen-sizeshapesizewhoxcorycor
Patches
pcolorplabelplabel-colorpxcorpycor
Links
breedcolorend1end2hidden?labellabel-colorshapethicknesstie-mode
Other
->
Keywords
breeddirected-link-breedendextensionsglobals__includeslinks-ownpatches-owntoto-reportturtles-ownundirected-link-breed
Constants
MathematicalConstants
e=2.718281828459045pi=3.141592653589793
BooleanConstants
falsetrue
ColorConstants
![Page 372: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/372.jpg)
Since1.0
Since1.3
Since4.0
Since1.0
Since2.0
black=0gray=5white=9.9red=15orange=25brown=35yellow=45green=55lime=65turquoise=75cyan=85sky=95blue=105violet=115magenta=125pink=135
SeetheColorssectionoftheProgrammingGuideformoredetails.
A
abs
absnumber
Reportstheabsolutevalueofnumber.
show abs -7=> 7show abs 5=> 5
acos
acosnumber
Reportsthearccosine(inversecosine)ofthegivennumber.Theinputmustbeintherange-1to1.Theresultisindegrees,andliesintherange0to180.
all?
all?agentset[reporter]
Reportstrueifalloftheagentsintheagentsetreporttrueforthegivenreporter.Otherwisereportsfalseassoonasacounterexampleisfound.
Iftheagentsetisempty,reportstrue.
Thereportermustreportabooleanvalueforeveryagent(eithertrueorfalse),otherwiseanerroroccurs.
if all? turtles [color = red] [ show "every turtle is red!" ]
Seealsoany?.
and
condition1andcondition2
Reportstrueifbothcondition1andcondition2aretrue.
Notethatifcondition1isfalse,thencondition2willnotberun(sinceitcan'taffecttheresult).
if (pxcor > 0) and (pycor > 0) [ set pcolor blue ] ;; the upper-right quadrant of ;; patches turn blue
any?
any?agentset
Reportstrueifthegivenagentsetisnon-empty,falseotherwise.
Equivalentto"countagentset>0",butmoreefficient(andarguablymorereadable).
if any? turtles with [color = red] [ show "at least one turtle is red!" ]
Note:nobodyisnotanagentset.Youonlygetnobodybackinsituationswhereyouwereexpectingasingleagent,notawholeagentset.If
![Page 373: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/373.jpg)
Since4.0
Since4.0
Since1.0Since1.0Since1.0Since1.0Since1.0Since1.0Since1.0Since1.0Since1.0Since1.0Since1.0
any?getsnobodyasinput,anerrorresults.
Seealsoall?,nobody.
approximate-hsb
approximate-hsbhuesaturationbrightness
Reportsanumberintherange0to140,notincluding140itself,thatrepresentsthegivencolor,specifiedintheHSBspectrum,inNetLogo'scolorspace.
Thefirstvalue(hue)shouldbeintherangeof0to360,thesecondandthird(saturationandbrightness)intherangebetween0and100.
Thecolorreportedmaybeonlyanapproximation,sincetheNetLogocolorspacedoesnotincludeallpossiblecolors.
show approximate-hsb 0 0 0=> 0 ;; (black)show approximate-hsb 180 57.143 76.863=> 85 ;; (cyan)
Seealsoextract-hsb,approximate-rgb,extract-rgb.
approximate-rgb
approximate-rgbredgreenblue
Reportsanumberintherange0to140,notincluding140itself,thatrepresentsthegivencolor,specifiedintheRGBspectrum,inNetLogo'scolorspace.
Allthreeinputsshouldbeintherange0to255.
Thecolorreportedmaybeonlyanapproximation,sincetheNetLogocolorspacedoesnotincludeallpossiblecolors.(Seeapproximate-hsbforadescriptionofwhatpartsoftheHSBcolorspaceNetLogocolorscover;thisisdifficulttocharacterizeinRGBterms.)
show approximate-rgb 0 0 0=> 0 ;; blackshow approximate-rgb 0 255 255=> 85.2 ;; cyan
Seealsoextract-rgb,approximate-hsb,andextract-hsb.
ArithmeticOperators+*-/^<>=!=<=>=
Alloftheseoperatorstaketwoinputs,andallactas"infixoperators"(goingbetweenthetwoinputs,asinstandardmathematicaluse).NetLogocorrectlysupportsorderofoperationsforinfixoperators.
Theoperatorsworkasfollows:+isaddition,*ismultiplication,-issubtraction,/isdivision,^isexponentiation,<islessthan,>isgreaterthan,=isequalto,!=isnotequalto,<=islessthanorequal,>=isgreaterthanorequal.
Notethatthesubtractionoperator(-)alwaystakestwoinputsunlessyouputparenthesesaroundit,inwhichcaseitcantakeoneinput.Forexample,totakethenegativeofx,write(-x),withtheparentheses.
Allofthecomparisonoperatorsalsoworkonstrings.
Allofthecomparisonoperatorsworkonagents.Turtlesarecomparedbywhonumber.Patchesarecomparedtoptobottomlefttoright,sopatch010islessthanpatch09andpatch90islessthanpatch100.Linksareorderedbyendpointsandincaseofatiebybreed.Solink09isbeforelink110astheend1issmaller,andlink08islessthanlink09.IftherearemultiplebreedsoflinksunbreededlinkswillcomebeforebreededlinksofthesameendpointsandbreededlinkswillbesortedintheordertheyaredeclaredintheCodetab.
Agentsetscanbetestedforequalityorinequality.Twoagentsetsareequaliftheyarethesametype(turtleorpatch)andcontainthesameagents.
IfyouarenotsurehowNetLogowillinterpretyourcode,youshouldaddparentheses.
show 5 * 6 + 6 / 3=> 32show 5 * (6 + 6) / 3=> 20
Manyextensionobjectsmaybetestedforequalityandinequalityusing=and!=.Forinstance,thearray,matrix,andtableobjectsreturnedbytheirrespectiveextensionsmaybecomparedforequality/inequality.Extensionobjectsmaynotbetestedusing<,>,<=,or>=.
![Page 374: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/374.jpg)
Since1.3
Since1.0
Since4.0
Since1.0
Since1.0
asin
asinnumber
Reportsthearcsine(inversesine)ofthegivennumber.Theinputmustbeintherange-1to1.Theresultisindegrees,andliesintherange-90to90.
ask
askagentset[commands]askagent[commands]
Thespecifiedagentoragentsetrunsthegivencommands.
ask turtles [ fd 1 ] ;; all turtles move forward one stepask patches [ set pcolor red ] ;; all patches turn redask turtle 4 [ rt 90 ] ;; only the turtle with id 4 turns right
Note:onlytheobservercanaskallturtlesorallpatches.Thispreventsyoufrominadvertentlyhavingallturtlesaskallturtlesorallpatchesaskallpatches,whichisacommonmistaketomakeifyou'renotcarefulaboutwhichagentswillrunthecodeyouarewriting.
Note:Onlytheagentsthatareintheagentsetatthetimetheaskbeginsrunthecommands.
ask-concurrent
ask-concurrentagentset[commands]
Thisprimitiveexistsonlyforbackwardscompatibility.Wedon'trecommendusingitnewmodels.
Theagentsinthegivenagentsetrunthegivencommands,usingaturn-takingmechanismtoproducesimulatedconcurrency.SeetheAsk-ConcurrentsectionoftheProgrammingGuidefordetailsonhowthisworks.
Note:Onlytheagentsthatareintheagentsetatthetimetheaskbeginsrunthecommands.
Seealsowithout-interruption.
at-points
agentsetat-points[[x1y1][x2y2]...]
Reportsasubsetofthegivenagentsetthatincludesonlytheagentsonthepatchesatthegivencoordinates(relativetothisagent).Thecoordinatesarespecifiedasalistoftwo-itemlists,wherethetwoitemsarethexandyoffsets.
Ifthecalleristheobserver,thenthepointsaremeasuredrelativetotheorigin,inotherwords,thepointsaretakenasabsolutepatchcoordinates.
Ifthecallerisaturtle,thepointsaremeasuredrelativetotheturtle'sexactlocation,andnotfromthecenterofthepatchundertheturtle.
ask turtles at-points [[2 4] [1 2] [10 15]] [ fd 1 ] ;; only the turtles on the patches at the ;; coordinates (2,4), (1,2) and (10,15), ;; relative to the caller, move
atan
atanxy
Convertsxandyoffsetstoaturtleheadingindegrees(from0to360).
NotethatthisversionofatanisdesignedtoconformtothegeometryoftheNetLogoworld,whereaheadingof0isstraightup,90istotheright,andsoonclockwisearoundthecircle.(Normallyingeometryanangleof0isright,90isup,andsoon,counterclockwisearoundthecircle,andatanwouldbedefinedaccordingly.)
Whenyis0:ifxispositive,itreports90;ifxisnegative,itreports270;ifxiszero,yougetanerror.
show atan 1 -1=> 135show atan -1 1=> 315crt 1 [ set heading 30 fd 1 print atan xcor ycor ]=> 30
Inthefinalexample,notethattheresultofatanequalstheturtle'sheading.
Ifyoueverneedtoconvertaturtleheading(obtainedwithatanorotherwise)toanormalmathematicalangle,thefollowingshouldbehelpful:
to-report heading-to-angle [ h ] report (90 - h) mod 360end
![Page 375: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/375.jpg)
Since1.0
Since1.0Since1.0
Since1.0Since1.0
Since4.0
Since2.1
Since5.2
Since4.1.1
autoplot?
autoplot?
Reportstrueifauto-plottingisonforthecurrentplot,falseotherwise.
auto-plot-offauto-plot-on
auto-plot-offauto-plot-on
ThispairofcommandsisusedtocontroltheNetLogofeatureofauto-plottinginthecurrentplot.Auto-plottingwillautomaticallyupdatethexandyaxesoftheplotwheneverthecurrentpenexceedstheseboundaries.Itisusefulwhenwantingtoshowallplottedvaluesinthecurrentplot,regardlessofthecurrentplotranges.
B
backbk
backnumber
Theturtlemovesbackwardbynumbersteps.(Ifnumberisnegative,theturtlemovesforward.)
Turtlesusingthisprimitivecanmoveamaximumofoneunitpertimeincrement.Sobk 0.5andbk 1bothtakeoneunitoftime,butbk 3takesthree.
Iftheturtlecannotmovebackwardnumberstepsbecauseitisnotpermittedbythecurrenttopologytheturtlewillcompleteasmanystepsof1asitcanandstop.
Seealsoforward,jump,can-move?.
base-colors
base-colors
Reportsalistofthe14basicNetLogohues.
print base-colors=> [5 15 25 35 45 55 65 75 85 95 105 115 125 135]ask turtles [ set color one-of base-colors ];; each turtle turns a random base colorask turtles [ set color one-of remove gray base-colors ];; each turtle turns a random base color except for gray
beep
beep
Emitsabeep.Notethatthebeepsoundsimmediately,soseveralbeepcommandsinclosesuccessionmayproduceonlyoneaudiblesound.
Example:
beep ;; emits one beeprepeat 3 [ beep ] ;; emits 3 beeps at once, ;; so you only hear one soundrepeat 3 [ beep wait 0.1 ] ;; produces 3 beeps in succession, ;; separated by 1/10th of a second
Whenrunningheadless,thiscommandhasnoeffect.
behaviorspace-experiment-name
behaviorspace-experiment-name
Reportsthecurrentexperimentnameinthecurrentexperiment.
IfnoBehaviorSpaceexperimentisrunning,reports"".
behaviorspace-run-number
behaviorspace-run-number
ReportsthecurrentrunnumberinthecurrentBehaviorSpaceexperiment,startingat1.
IfnoBehaviorSpaceexperimentisrunning,reports0.
![Page 376: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/376.jpg)
Since4.0
Since1.0Since1.0Since1.0Since1.0Since1.0Since1.0
both-ends
both-ends
Reportstheagentsetofthe2nodesconnectedbythislink.
crt 2ask turtle 0 [ create-link-with turtle 1 ]ask link 0 1 [ ask both-ends [ set color red ] ;; turtles 0 and 1 both turn red]
breed
breed
Thisisabuilt-inturtleandlinkvariable.Itholdstheagentsetofallturtlesorlinksofthesamebreedasthisturtleorlink.(Forturtlesorlinksthatdonothaveanyparticularbreed,thisistheturtlesagentsetofallturtlesorthelinksagentsetofalllinksrespectively.)
Youcansetthisvariabletochangeaturtleorlink'sbreed.(Whenaturtlechangesbreeds,itsshapeisresettothedefaultshapeforthatbreed.Seeset-default-shape.)
Seealsobreed,directed-link-breed,undirected-link-breed
Example:
breed [cats cat]breed [dogs dog];; turtle code:if breed = cats [ show "meow!" ]set breed dogsshow "woof!"
directed-link-breed [ roads road ];; link codeif breed = roads [ set color gray ]
breed
breed[<breeds><breed>]
Thiskeyword,liketheglobals,turtles-own,andpatches-ownkeywords,canonlybeusedatthebeginningoftheCodetab,beforeanyproceduredefinitions.Itdefinesabreed.Thefirstinputdefinesthenameoftheagentsetassociatedwiththebreed.Thesecondinputdefinesthenameofasinglememberofthebreed.
Anyturtleofthegivenbreed:
ispartoftheagentsetnamedbythebreednamehasitsbreedbuilt-invariablesettothatagentset
Mostoften,theagentsetisusedinconjunctionwithasktogivecommandstoonlytheturtlesofaparticularbreed.
breed [mice mouse]breed [frogs frog]to setup clear-all create-mice 50 ask mice [ set color white ] create-frogs 50 ask frogs [ set color green ] show [breed] of one-of mice ;; prints mice show [breed] of one-of frogs ;; prints frogsend
show mouse 1;; prints (mouse 1)show frog 51;; prints (frog 51)show turtle 51;; prints (frog 51)
Seealsoglobals,patches-own,turtles-own,<breeds>-own,create-<breeds>,<breeds>-at,<breeds>-here.
but-firstbutfirstbfbut-lastbutlastbl
but-firstlistbut-firststringbut-lastlistbut-laststring
![Page 377: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/377.jpg)
Since3.1
Since2.1
Since1.0
Since1.0Since1.0
Since1.0
Since3.0Since3.0
Since5.2
Whenusedonalist,but-firstreportsallofthelistitemsoflistexceptthefirst,andbut-lastreportsallofthelistitemsoflistexceptthelast.
Onstrings,but-firstandbut-lastreportashorterstringomittingthefirstorlastcharacteroftheoriginalstring.
;; mylist is [2 4 6 5 8 12]set mylist but-first mylist;; mylist is now [4 6 5 8 12]set mylist but-last mylist;; mylist is now [4 6 5 8]show but-first "string";; prints "tring"show but-last "string";; prints "strin"
C
can-move?
can-move?distance
Reportstrueifthisturtlecanmovedistanceinthedirectionitisfacingwithoutviolatingthetopology;reportsfalseotherwise.
Itisequivalentto:
patch-ahead distance != nobody
carefully
carefully[commands1][commands2]
Runscommands1.Ifaruntimeerroroccursinsidecommands1,NetLogowon'tstopandalerttheuserthatanerroroccurred.Itwillsuppresstheerrorandruncommands2instead.
Theerror-messagereportercanbeusedincommands2tofindoutwhaterrorwassuppressedincommands1.Seeerror-message.
carefully [ print one-of [1 2 3] ] [ print error-message ]=> 3observer> carefully [ print one-of [] ] [ print error-message ]=> ONE-OF got an empty list as input.
ceiling
ceilingnumber
Reportsthesmallestintegergreaterthanorequaltonumber.
show ceiling 4.5=> 5show ceiling -4.5=> -4
Seealsofloor,round,precision.
clear-allca
clear-all
Combinestheeffectsofclear-globals,clear-ticks,clear-turtles,clear-patches,clear-drawing,clear-all-plots,andclear-output.
clear-all-plots
clear-all-plots
Clearseveryplotinthemodel.Seeclear-plotformoreinformation.
clear-drawingcd
clear-drawing
Clearsalllinesandstampsdrawnbyturtles.
clear-globals
![Page 378: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/378.jpg)
Since4.0
Since1.0
Since1.0Since1.0
Since5.0
Since1.0Since1.0
clear-globals
Setsallglobalvariablesto0.
clear-links
clear-links
Killsalllinks.
Seealsodie.
clear-output
clear-output
Clearsalltextfromthemodel'soutputarea,ifithasone.Otherwisedoesnothing.
clear-patchescp
clear-patches
Clearsthepatchesbyresettingallpatchvariablestotheirdefaultinitialvalues,includingsettingtheircolortoblack.
clear-plot
clear-plot
Inthecurrentplotonly,resetsallplotpens,deletesalltemporaryplotpens,resetstheplottoitsdefaultvalues(forxrange,yrange,etc.),andresetsallpermanentplotpenstotheirdefaultvalues.ThedefaultvaluesfortheplotandforthepermanentplotpensaresetintheplotEditdialog,whichisdisplayedwhenyouedittheplot.Iftherearenoplotpensafterdeletingalltemporarypens,thatistosayiftherearenopermanentplotpens,adefaultplotpenwillbecreatedwiththefollowinginitialsettings:
Pen:downColor:blackMode:0(linemode)Name:"default"Interval:1
Seealsoclear-all-plots.
clear-ticks
clear-ticks
Clearsthetickcounter.
Doesnotsetthecountertozero.Afterthiscommandruns,thetickcounterhasnovalue.Attemptingtoaccessorupdateitisanerroruntilreset-ticksiscalled.
Seealsoreset-ticks.
clear-turtlesct
clear-turtles
Killsallturtles.
Alsoresetsthewhonumbering,sothenextturtlecreatedwillbeturtle0.
Seealsodie.
color
color
Thisisabuilt-inturtleorlinkvariable.Itholdsthecoloroftheturtleorlink.Youcansetthisvariabletomaketheturtleorlinkchangecolor.ColorcanberepresentedeitherasaNetLogocolor(asinglenumber),oranRGBcolor(alistof3numbers).SeedetailsintheColorssectionoftheProgrammingGuide.
![Page 379: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/379.jpg)
Since1.0
Since1.0
Since4.0Since4.0
Since4.0Since4.0Since4.0Since4.0Since4.0Since4.0
Seealsopcolor.
cos
cosnumber
Reportsthecosineofthegivenangle.Assumestheangleisgivenindegrees.
show cos 180=> -1
count
countagentset
Reportsthenumberofagentsinthegivenagentset.
show count turtles;; prints the total number of turtlesshow count patches with [pcolor = red];; prints the total number of red patches
create-ordered-turtlescro
create-ordered-turtlesnumbercreate-ordered-turtlesnumber[commands]create-ordered<breeds>numbercreate-ordered<breeds>number[commands]
Createsnumbernewturtles.Newturtlesstartatposition(0,0),arecreatedwiththe14primarycolors,andhaveheadingsfrom0to360,evenlyspaced.
Ifthecreate-ordered-<breeds>formisused,thenewturtlesarecreatedasmembersofthegivenbreed.
Ifcommandsaresupplied,thenewturtlesimmediatelyrunthem.Thisisusefulforgivingthenewturtlesadifferentcolor,heading,orwhatever.(Thenewturtlesarecreatedallatoncethenrunoneatatime,inrandomorder.)
cro 100 [ fd 10 ] ;; makes an evenly spaced circle
create-<breed>-tocreate-<breeds>-tocreate-<breed>-fromcreate-<breeds>-fromcreate-<breed>-withcreate-<breeds>-withcreate-link-tocreate-links-tocreate-link-fromcreate-links-fromcreate-link-withcreate-links-with
create-<breed>-toturtlecreate-<breed>-toturtle[commands]create-<breed>-fromturtlecreate-<breed>-fromturtle[commands]create-<breed>-withturtlecreate-<breed>-withturtle[commands]create-<breeds>-toturtlesetcreate-<breeds>-toturtleset[commands]create-<breeds>-fromturtlesetcreate-<breeds>-fromturtleset[commands]create-<breeds>-withturtlesetcreate-<breeds>-withturtleset[commands]create-link-toturtlecreate-link-toturtle[commands]create-link-fromturtlecreate-link-fromturtle[commands]create-link-withturtlecreate-link-withturtle[commands]create-links-toturtlesetcreate-links-toturtleset[commands]create-links-fromturtlesetcreate-links-fromturtleset[commands]create-links-withturtlesetcreate-links-withturtleset[commands]
![Page 380: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/380.jpg)
Since1.0Since1.0
Since1.1
Usedforcreatingbreededandunbreededlinksbetweenturtles.
create-link-withcreatesanundirectedlinkbetweenthecallerandagent.create-link-tocreatesadirectedlinkfromthecallertoagent.create-link-fromcreatesadirectedlinkfromagenttothecaller.
Whenthepluralformofthebreednameisused,anagentsetisexpectedinsteadofanagentandlinksarecreatedbetweenthecallerandallagentsintheagentset.
Theoptionalcommandblockisthesetofcommandseachnewlyformedlinkruns.(Thelinksarecreatedallatoncethenrunoneatatime,inrandomorder.)
Anodecannotbelinkedtoitself.Also,youcannothavemorethanoneundirectedlinkofthesamebreedbetweenthesametwonodes,norcanyouhavemorethanonedirectedlinkofthesamebreedgoinginthesamedirectionbetweentwonodes.
Ifyoutrytocreatealinkwhereone(ofthesamebreed)alreadyexists,nothinghappens.Ifyoutrytocreatealinkfromaturtletoitselfyougetaruntimeerror.
to setup clear-all create-turtles 5 ;; turtle 1 creates links with all other turtles ;; the link between the turtle and itself is ignored ask turtle 0 [ create-links-with other turtles ] show count links ;; shows 4 ;; this does nothing since the link already exists ask turtle 0 [ create-link-with turtle 1 ] show count links ;; shows 4 since the previous link already existed ask turtle 2 [ create-link-with turtle 1 ] show count links ;; shows 5end
directed-link-breed [red-links red-link]undirected-link-breed [blue-links blue-link]
to setup clear-all create-turtles 5 ;; create links in both directions between turtle 0 ;; and all other turtles ask turtle 0 [ create-red-links-to other turtles ] ask turtle 0 [ create-red-links-from other turtles ] show count links ;; shows 8 ;; now create undirected links between turtle 0 and other turtles ask turtle 0 [ create-blue-links-with other turtles ] show count links ;; shows 12end
create-turtlescrt
create-turtlesnumbercreate-turtlesnumber[commands]create-<breeds>numbercreate-<breeds>number[commands]
Createsnumbernewturtlesattheorigin.Newturtleshaverandomintegerheadingsandthecolorisrandomlyselectedfromthe14primarycolors.
Ifthecreate-<breeds>formisused,thenewturtlesarecreatedasmembersofthegivenbreed.
Ifcommandsaresupplied,thenewturtlesimmediatelyrunthem.Thisisusefulforgivingthenewturtlesadifferentcolor,heading,orwhatever.(Thenewturtlesarecreatedallatoncethenrunoneatatime,inrandomorder.)
crt 100 [ fd 10 ] ;; makes a randomly spaced circle
breed [canaries canary]breed [snakes snake]to setup clear-all create-canaries 50 [ set color yellow ] create-snakes 50 [ set color green ]end
Seealsohatch,sprout.
create-temporary-plot-pen
create-temporary-plot-penstring
Anewtemporaryplotpenwiththegivennameiscreatedinthecurrentplotandsettobethecurrentpen.
Fewmodelswillwanttousethisprimitive,becausealltemporarypensdisappearwhenclear-plotorclear-all-plotsarecalled.Thenormalwaytomakeapenistomakeapermanentpenintheplot'sEditdialog.
Ifapenwiththatnamealreadyexistsinthecurrentplot,nonewpeniscreated,andtheexistingpenissettothecurrentpen.
Thenewtemporaryplotpenhasthefollowinginitialsettings:
![Page 381: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/381.jpg)
Since3.0
Since1.0
Since1.0
Since1.0
Pen:downColor:blackMode:0(linemode)Interval:1
See:clear-plot,clear-all-plots,andset-current-plot-pen.
D
date-and-time
date-and-time
Reportsastringcontainingthecurrentdateandtime.Theformatisshownbelow.Allfieldsarefixedwidth,sotheyarealwaysatthesamelocationsinthestring.Thepotentialresolutionoftheclockismilliseconds.(Whetheryougetresolutionthathighinpracticemayvaryfromsystemtosystem,dependingonthecapabilitiesoftheunderlyingJavaVirtualMachine.)
show date-and-time=> "01:19:36.685 PM 19-Sep-2002"
die
die
Theturtleorlinkdies.
if xcor > 20 [ die ];; all turtles with xcor greater than 20 dieask links with [color = blue] [ die ];; all the blue links will die
Adeadagentceasestoexist.Theeffectsofthisinclude:
Theagentwillnotexecuteanyfurthercode.Soifyouwriteask turtles [ die print "last words?" ] ,nolastwordswillbeprinted,becausetheturtlesarealreadydeadbeforetheyhaveachancetoprintanything.Theagentwilldisappearfromanyagentsetsitwasin,reducingthesizeofthoseagentsetsbyone.Anyvariablethatwasstoringtheagentwillnowinsteadhavenobodyinit.Soforexamplelet x one-of turtles ask x [ die ] print xprintsnobody.Ifthedeadagentwasaturtle,everylinkconnectedtoitalsodies.Iftheobserverwaswatchingorfollowingtheagent,theobserver'sperspectiveresets,asifreset-perspectivehadbeenrun.
Seealso:clear-turtlesclear-links
diffuse
diffusepatch-variablenumber
Tellseachpatchtogiveequalsharesof(number*100)percentofthevalueofpatch-variabletoitseightneighboringpatches.numbershouldbebetween0and1.Regardlessoftopologythesumofpatch-variablewillbeconservedacrosstheworld.(Ifapatchhasfewerthaneightneighbors,eachneighborstillgetsaneighthshare;thepatchkeepsanyleftovershares.)
Notethatthisisanobservercommandonly,eventhoughyoumightexpectittobeapatchcommand.(Thereasonisthatitactsonallthepatchesatonce--patchcommandsactonindividualpatches.)
diffuse chemical 0.5;; each patch diffuses 50% of its variable;; chemical to its neighboring 8 patches. Thus,;; each patch gets 1/8 of 50% of the chemical;; from each neighboring patch.)
diffuse4
diffuse4patch-variablenumber
Likediffuse,butonlydiffusestothefourneighboringpatches(tothenorth,south,east,andwest),nottothediagonalneighbors.
diffuse4 chemical 0.5;; each patch diffuses 50% of its variable;; chemical to its neighboring 4 patches. Thus,;; each patch gets 1/4 of 50% of the chemical;; from each neighboring patch.)
directed-link-breed
directed-link-breed[<link-breeds><link-breed>]
Thiskeyword,liketheglobalsandbreedskeywords,canonlybeusedatthebeginningoftheCodetab,beforeanyproceduredefinitions.It
![Page 382: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/382.jpg)
Since1.0
Since1.0
Since1.0
definesadirectedlinkbreed.LinksofaparticularbreedarealwaysalldirectedorallundirectedThefirstinputdefinesthenameoftheagentsetassociatedwiththelinkbreed.Thesecondinputdefinesthenameofasinglememberofthebreed.Directedlinkscanbecreatedusingcreate-link(s)-to,andcreate-link(s)-from,butnotcreate-link(s)-with
Anylinkofthegivenlinkbreed:
ispartoftheagentsetnamedbythelinkbreednamehasitsbuilt-invariablebreedsettothatagentsetisdirectedorundirectedasdeclaredbythekeyword
Mostoften,theagentsetisusedinconjunctionwithasktogivecommandstoonlythelinksofaparticularbreed.
directed-link-breed [streets street]directed-link-breed [highways highway]to setup clear-all crt 2 ;; create a link from turtle 0 to turtle 1 ask turtle 0 [ create-street-to turtle 1 ] ;; create a link from turtle 1 to turtle 0 ask turtle 0 [ create-highway-from turtle 1 ]end
ask turtle 0 [ show one-of my-in-links ];; prints (street 0 1)ask turtle 0 [ show one-of my-out-links ];; prints (highway 1 0)
Seealsobreed,undirected-link-breed
display
display
Causestheviewtobeupdatedimmediately.(Exception:iftheuserisusingthespeedslidertofast-forwardthemodel,thentheupdatemaybeskipped.)
Alsoundoestheeffectoftheno-displaycommand,sothatifviewupdatesweresuspendedbythatcommand,theywillresume.
no-displayask turtles [ jump 10 set color blue set size 5 ]display;; turtles move, change color, and grow, with none of;; their intermediate states visible to the user, only;; their final state
Evenifno-displaywasnotused,"display"canstillbeuseful,becauseordinarilyNetLogoisfreetoskipsomeviewupdates,sothatfewertotalupdatestakeplace,sothatmodelsrunfaster.Thiscommandletsyouforceaviewupdate,sowhateverchangeshavetakenplaceintheworldarevisibletotheuser.
ask turtles [ set color red ]displayask turtles [ set color blue];; turtles turn red, then blue; use of "display" forces;; red turtles to appear briefly
Notethatdisplayandno-displayoperateindependentlyoftheswitchintheviewcontrolstripthatfreezestheview.
Seealsono-display.
distance
distanceagent
Reportsthedistancefromthisagenttothegiventurtleorpatch.
Thedistancetoorafromapatchismeasuredfromthecenterofthepatch.Turtlesandpatchesusethewrappeddistance(aroundtheedgesoftheworld)ifwrappingisallowedbythetopologyandthewrappeddistanceisshorter.
ask turtles [ show max-one-of turtles [distance myself] ];; each turtle prints the turtle farthest from itself
distancexy
distancexyxy
Reportsthedistancefromthisagenttothepoint(x,y).
Thedistancefromapatchismeasuredfromthecenterofthepatch.Turtlesandpatchesusethewrappeddistance(aroundtheedgesoftheworld)ifwrappingisallowedbythetopologyandthewrappeddistanceisshorter.
if (distancexy 0 0) > 10 [ set color green ];; all turtles more than 10 units from;; the center of the world turn green.
![Page 383: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/383.jpg)
Since1.0Since1.0
Since1.0Since1.0
Since1.0
Since4.0
Since4.0
downhilldownhill4
downhillpatch-variabledownhill4patch-variable
Movestheturtletotheneighboringpatchwiththelowestvalueforpatch-variable.Ifnoneighboringpatchhasasmallervaluethanthecurrentpatch,theturtlestaysput.Iftherearemultiplepatcheswiththesamelowestvalue,theturtlepicksonerandomly.Non-numericvaluesareignored.
downhillconsiderstheeightneighboringpatches;downhill4onlyconsidersthefourneighbors.
Equivalenttothefollowingcode(assumesvariablevaluesarenumeric):
move-to patch-here ;; go to patch centerlet p min-one-of neighbors [patch-variable] ;; or neighbors4if [patch-variable] of p < patch-variable [ face p move-to p]
Notethattheturtlealwaysendsuponapatchcenterandhasaheadingthatisamultipleof45(downhill)or90(downhill4).
Seealsouphill,uphill4.
dxdy
dxdy
Reportsthex-incrementory-increment(theamountbywhichtheturtle'sxcororycorwouldchange)iftheturtleweretotakeonestepforwardinitscurrentheading.
Note:dxissimplythesineoftheturtle'sheading,anddyissimplythecosine.(Ifthisisthereverseofwhatyouexpected,it'sbecauseinNetLogoaheadingof0isnorthand90iseast,whichisthereverseofhowanglesareusuallydefinedingeometry.)
Note:InearlierversionsofNetLogo,theseprimitiveswereusedinmanysituationswherethenewpatch-aheadprimitiveisnowmoreappropriate.
E
empty?
empty?listempty?string
Reportstrueifthegivenlistorstringisempty,falseotherwise.
Note:theemptylistiswritten[].Theemptystringiswritten"".
end
end
Usedtoconcludeaprocedure.Seetoandto-report.
end1
end1
Thisisabuilt-inlinkvariable.Itindicatesthefirstendpoint(turtle)ofalink.Fordirectedlinksthiswillalwaysbethesourceforundirectedlinksitwillalwaysbetheturtlewiththelowerwhonumber.Youcannotsetend1.
crt 2ask turtle 0[ create-link-to turtle 1 ]ask links[ show end1 ] ;; shows turtle 0
end2
end2
Thisisabuilt-inlinkvariable.Itindicatesthesecondendpoint(turtle)ofalink.Fordirectedlinksthiswillalwaysbethedestinationforundirectedlinksitwillalwaysbetheturtlewiththehigherwhonumber.Youcannotsetend2.
![Page 384: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/384.jpg)
Since5.0
Since2.1
Since1.0
Since1.0
Since3.0Since2.0Since1.0Since1.0
Since1.2.1Since1.0
crt 2ask turtle 1[ create-link-with turtle 0 ]ask links[ show end2 ] ;; shows turtle 1
error
errorvalue
Causesaruntimeerrortooccur.
Thegivenvalueisconvertedtoastring(ifitisn'tonealready)andusedastheerrormessage.
Seealsoerror-message,carefully.
error-message
error-message
Reportsastringdescribingtheerrorthatwassuppressedbycarefully.
Thisreportercanonlybeusedinthesecondblockofacarefullycommand.
Seealsoerror,carefully.
every
everynumber[commands]
Runsthegivencommandsonlyifit'sbeenmorethannumbersecondssincethelasttimethisagentrantheminthiscontext.Otherwise,thecommandsareskipped.
Byitself,everydoesn'tmakecommandsrunoverandoveragain.Youneedtouseeveryinsidealoop,orinsideaforeverbutton,ifyouwantthecommandsrunoverandoveragain.everyonlylimitshowoftenthecommandsrun.
Above,"inthiscontext"meansduringthesameask(orbuttonpressorcommandtypedintheCommandCenter).Soitdoesn'tmakesensetowriteask turtles [ every 0.5 [ ... ] ],becausewhentheaskfinishestheturtleswillalldiscardtheirtimersforthe"every".Thecorrectusageisshownbelow.
every 0.5 [ ask turtles [ fd 1 ] ];; twice a second the turtles will move forward 1every 2 [ set index index + 1 ];; every 2 seconds index is incremented
Seealsowait.
exp
expnumber
Reportsthevalueoferaisedtothenumberpower.
Note:Thisisthesamease^number.
export-viewexport-interfaceexport-outputexport-plotexport-all-plotsexport-world
export-viewfilenameexport-interfacefilenameexport-outputfilenameexport-plotplotnamefilenameexport-all-plotsfilenameexport-worldfilename
export-viewwritesthecurrentcontentsofthecurrentviewtoanexternalfilegivenbythestringfilename.ThefileissavedinPNG(PortableNetworkGraphics)format,soitisrecommendedtosupplyafilenameendingin".png".
export-interfaceissimilar,butforthewholeinterfacetab.
Notethatexport-viewstillworkswhenrunningNetLogoinheadlessmode,butexport-interfacedoesn't.
export-outputwritesthecontentsofthemodel'soutputareatoanexternalfilegivenbythestringfilename.(Ifthemodeldoesnothaveaseparateoutputarea,theoutputportionoftheCommandCenterisused.)
export-plotwritesthexandyvaluesofallpointsplottedbyalltheplotpensintheplotgivenbythestringplotnametoanexternalfilegivenbythestringfilename.Ifapenisinbarmode(mode0)andtheyvalueofthepointplottedisgreaterthan0,theupper-leftcornerpointofthebar
![Page 385: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/385.jpg)
Since1.0
Since1.0
Since3.0
willbeexported.Iftheyvalueislessthan0,thenthelower-leftcornerpointofthebarwillbeexported.
export-all-plotswriteseveryplotinthecurrentmodeltoanexternalfilegivenbythestringfilename.Eachplotisidenticalinformattotheoutputofexport-plot.
export-worldwritesthevaluesofallvariables,bothbuilt-inanduser-defined,includingallobserver,turtle,andpatchvariables,thedrawing,thecontentsoftheoutputareaifoneexists,thecontentsofanyplotsandthestateoftherandomnumbergenerator,toanexternalfilegivenbythestringfilename.(TheresultfilecanbereadbackintoNetLogowiththeimport-worldprimitive.)export-worlddoesnotsavethestateofopenfiles.
export-plot,export-all-plotsandexport-worldsavefilesininplain-text,"comma-separatedvalues"(.csv)format.CSVfilescanbereadbymostpopularspreadsheetanddatabaseprogramsaswellasanytexteditor.
Ifyouwishtoexporttoafileinalocationotherthanthemodel'slocation,youshouldincludethefullpathtothefileyouwishtoexport.(Usetheforward-slash"/"asthefolderseparator.)
NotethatthefunctionalityoftheseprimitivesisalsoavailabledirectlyfromNetLogo'sFilemenu.
export-world "fire.csv";; exports the state of the model to the file fire.csv;; located in the NetLogo folderexport-plot "Temperature" "c:/My Documents/plot.csv";; exports the plot named;; "Temperature" to the file plot.csv located in;; the C:\My Documents folderexport-all-plots "c:/My Documents/plots.csv";; exports all plots to the file plots.csv;; located in the C:\My Documents folder
Ifthefilealreadyexists,itisoverwritten.Toavoidthisyoumaywishtousesomemethodofgeneratingfreshnames.Examples:
export-world user-new-fileexport-world (word "results " date-and-time ".csv") ;; Colon characters in the time cause errors on Windowsexport-world (word "results " random-float 1.0 ".csv")
extensions
extensions[name...]
Allowsthemodeltouseprimitivesfromtheextensionswiththegivennames.SeetheExtensionsguideformoreinformation.
extract-hsb
extract-hsbcolor
Reportsalistofthreevalues,thefirst(hue)intherangeof0to360,thesecondandthird(brightnessandsaturation)intherangeof0to100.
ThegivencolorcaneitherbeaNetLogocolorintherange0to140,notincluding140itself,oranRGBlistofthreevaluesintherange0to255representingthelevelsofred,green,andblue.
show extract-hsb cyan=> [180 57.143 76.863]show extract-hsb red=> [3.103 80.93 84.314]show extract-hsb [255 0 0]=> [0 100 100]
Seealsoapproximate-hsb,approximate-rgb,extract-rgb.
extract-rgb
extract-rgbcolor
Reportsalistofthreevaluesintherange0to255representingthelevelsofred,green,andblue,respectively,ofthegivenNetLogocolorintherange0to140,notincluding140itself.
show extract-rgb red=> [215 50 41]show extract-rgb cyan=> [84 196 196]
Seealsoapproximate-rgb,approximate-hsb,extract-hsb.
F
face
faceagent
Setthecaller'sheadingtowardsagent.
Ifwrappingisallowedbythetopologyandthewrappeddistance(aroundtheedgesoftheworld)isshorter,facewillusethewrappedpath.
![Page 386: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/386.jpg)
Since3.0
Since2.0
Since2.0
Since2.0
Since2.0
Since2.0
Since4.0
Ifthecallerandtheagentareattheexactsameposition,thecaller'sheadingwon'tchange.
facexy
facexyxy
Setthecaller'sheadingtowardsthepoint(x,y).
Ifwrappingisallowedbythetopologyandthewrappeddistance(aroundtheedgesoftheworld)isshorterandwrappingisallowed,facexywillusethewrappedpath.
Ifthecallerisonthepoint(x,y),thecaller'sheadingwon'tchange.
file-at-end?
file-at-end?
Reportstruewhentherearenomorecharacterslefttoreadinfromthecurrentfile(thatwasopenedpreviouslywithfile-open).Otherwise,reportsfalse.
file-open "my-file.txt"print file-at-end?=> false ;; Can still read in more charactersprint file-read-line=> This is the last line in fileprint file-at-end?=> true ;; We reached the end of the file
Seealsofile-open,file-close-all.
file-close
file-close
Closesafilethathasbeenopenedpreviouslywithfile-open.
Notethatthisandfile-close-allaretheonlywaystorestarttothebeginningofanopenedfileortoswitchbetweenfilemodes.
Ifnofileisopen,doesnothing.
Seealsofile-close-all,file-open.
file-close-all
file-close-all
Closesallfiles(ifany)thathavebeenopenedpreviouslywithfile-open.
Seealsofile-close,file-open.
file-delete
file-deletestring
Deletesthefilespecifiedasstring
stringmustbeanexistingfilewithwritablepermissionbytheuser.Also,thefilecannotbeopen.Usethecommandfile-closetocloseanopenedfilebeforedeletion.
Notethatthestringcaneitherbeafilenameoranabsolutefilepath.Ifitisafilename,itlooksinwhateverthecurrentdirectoryis.Thiscanbechangedusingthecommandset-current-directory.Itisdefaultedtothemodel'sdirectory.
file-exists?
file-exists?string
Reportstrueifstringisthenameofanexistingfileonthesystem.Otherwiseitreportsfalse.
Notethatthestringcaneitherbeafilenameoranabsolutefilepath.Ifitisafilename,itlooksinwhateverthecurrentdirectoryis.Thiscanbechangedusingthecommandset-current-directory.Itdefaultstotothemodel'sdirectory.
file-flush
file-flush
Forcesfileupdatestobewrittentodisk.Whenyouusefile-writeorotheroutputcommands,thevaluesmaynotbeimmediatelywrittentodisk.Thisimprovestheperformanceofthefileoutputcommands.Closingafileensuresthatalloutputiswrittentodisk.
Sometimesyouneedtoensurethatdataiswrittentodiskwithoutclosingthefile.Forexample,youcouldbeusingafiletocommunicatewithanotherprogramonyourmachineandwanttheotherprogramtobeabletoseetheoutputimmediately.
![Page 387: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/387.jpg)
Since2.0
Since2.0
Since2.0
Since2.0
file-open
file-openstring
Thiscommandwillinterpretstringasapathnametoafileandopenthefile.Youmaythenusethereportersfile-read,file-read-line,andfile-read-characterstoreadinfromthefile,orfile-write,file-print,file-type,orfile-showtowriteouttothefile.
Notethatyoucanonlyopenafileforreadingorwritingbutnotboth.Thenextfilei/oprimitiveyouuseafterthiscommanddictateswhichmodethefileisopenedin.Toswitchmodes,youneedtoclosethefileusingfile-close.
Also,thefilemustalreadyexistifopeningafileinreadingmode.
Whenopeningafileinwritingmode,allnewdatawillbeappendedtotheendoftheoriginalfile.Ifthereisnooriginalfile,anewblankfilewillbecreatedinitsplace.(Youmusthavewritepermissioninthefile'sdirectory.)(Ifyoudon'twanttoappend,butwanttoreplacethefile'sexistingcontents,usefile-deletetodeleteitfirst,perhapsinsideacarefullyifyou'renotsurewhetheritalreadyexists.)
Notethatthestringcaneitherbeafilenameoranabsolutefilepath.Ifitisafilename,itlooksinwhateverthecurrentdirectoryis.Thiscanbechangedusingthecommandset-current-directory.Itisdefaultedtothemodel'sdirectory.
file-open "my-file-in.txt"print file-read-line=> First line in file ;; File is in reading modefile-open "C:\\NetLogo\\my-file-out.txt";; assuming Windows machinefile-print "Hello World" ;; File is in writing mode
Openingafiledoesnotclosepreviouslyopenedfiles.Youcanusefile-opentoswitchbackandforthbetweenmultipleopenfiles.
Seealsofile-closeSeealsofile-close-all.
file-print
file-printvalue
Printsvaluetoanopenedfile,followedbyacarriagereturn.
Thisagentisnotprintedbeforethevalue,unlikefile-show.
Notethatthiscommandisthefilei/oequivalentofprint,andfile-openneedstobecalledbeforethiscommandcanbeused.
Seealsofile-show,file-type,andfile-write.
file-read
file-read
ThisreporterwillreadinthenextconstantfromtheopenedfileandinterpretitasifithadbeentypedintheCommandCenter.Itreportstheresultingvalue.Theresultmaybeanumber,list,string,boolean,orthespecialvaluenobody.
Whitespaceseparatestheconstants.Eachcalltofile-readwillskippastbothleadingandtrailingwhitespace.
Notethatstringsneedtohavequotesaroundthem.Usethecommandfile-writetohavequotesincluded.
Alsonotethatthefile-opencommandmustbecalledbeforethisreportercanbeused,andtheremustbedataremaininginthefile.Usethereporterfile-at-end?todetermineifyouareattheendofthefile.
file-open "my-file.data"print file-read + 5;; Next value is the number 1=> 6print length file-read;; Next value is the list [1 2 3 4]=> 4
Seealsofile-openandfile-write.
file-read-characters
file-read-charactersnumber
Reportsthegivennumberofcharactersfromanopenedfileasastring.Iftherearefewerthanthatmanycharactersleft,itwillreportalloftheremainingcharacters.
Notethatitwillreturneverycharacterincludingnewlinesandspaces.
Alsonotethatthefile-opencommandmustbecalledbeforethisreportercanbeused,andtheremustbedataremaininginthefile.Usethereporterfile-at-end?todetermineifyouareattheendofthefile.
file-open "my-file.txt"print file-read-characters 5;; Current line in file is "Hello World"=> Hello
Seealsofile-open.
![Page 388: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/388.jpg)
Since2.0
Since2.0
Since2.0
Since2.0
Since1.3
Since1.0
file-read-line
file-read-line
Readsthenextlineinthefileandreportsitasastring.Itdeterminestheendofthefilebyacarriagereturn,anendoffilecharacterorbothinarow.Itdoesnotreturnthelineterminatorcharacters.
Alsonotethatthefile-opencommandmustbecalledbeforethisreportercanbeused,andtheremustbedataremaininginthefile.Usethereporterfile-at-end?todetermineifyouareattheendofthefile.
file-open "my-file.txt"print file-read-line=> Hello World
Seealsofile-open.
file-show
file-showvalue
Printsvaluetoanopenedfile,precededbythisagentagent,andfollowedbyacarriagereturn.(Thisagentisincludedtohelpyoukeeptrackofwhatagentsareproducingwhichlinesofoutput.)Also,allstringshavetheirquotesincludedsimilartofile-write.
Notethatthiscommandisthefilei/oequivalentofshow,andfile-openneedstobecalledbeforethiscommandcanbeused.
Seealsofile-print,file-type,andfile-write.
file-type
file-typevalue
Printsvaluetoanopenedfile,notfollowedbyacarriagereturn(unlikefile-printandfile-show).Thelackofacarriagereturnallowsyoutoprintseveralvaluesonthesameline.
Thisagentisnotprintedbeforethevalue.unlikefile-show.
Notethatthiscommandisthefilei/oequivalentoftype,andfile-openneedstobecalledbeforethiscommandcanbeused.
Seealsofile-print,file-show,andfile-write.
file-write
file-writevalue
Thiscommandwilloutputvalue,whichcanbeanumber,string,list,boolean,ornobodytoanopenedfile,notfollowedbyacarriagereturn(unlikefile-printandfile-show).
Thisagentisnotprintedbeforethevalue,unlikefile-show.Itsoutputalsoincludesquotesaroundstringsandisprependedwithaspace.Itwilloutputthevalueinsuchamannerthatfile-readwillbeabletointerpretit.
Notethatthiscommandisthefilei/oequivalentofwrite,andfile-openneedstobecalledbeforethiscommandcanbeused.
file-open "locations.txt"ask turtles [ file-write xcor file-write ycor ]
Seealsofile-print,file-show,andfile-type.
filter
filterreporterlist
Reportsalistcontainingonlythoseitemsoflistforwhichthereporterreportstrue--inotherwords,theitemssatisfyingthegivencondition.reportermaybeananonymousreporterorthenameofareporter.
show filter is-number? [1 "2" 3]=> [1 3]show filter [ i -> i < 3 ] [1 3 2]=> [1 2]show filter [ s -> first s != "t" ] ["hi" "there" "everyone"]=> ["hi" "everyone"]
Seealsomap,reduce,->(anonymousprocedure).
first
firstlistfirststring
Onalist,reportsthefirst(0th)iteminthelist.
![Page 389: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/389.jpg)
Since1.0
Since3.0
Since3.0
Since1.3
Since1.0Since1.0
Onastring,reportsaone-characterstringcontainingonlythefirstcharacteroftheoriginalstring.
floor
floornumber
Reportsthelargestintegerlessthanorequaltonumber.
show floor 4.5=> 4show floor -4.5=> -5
Seealsoceiling,round,precision.
follow
followturtle
Similartoride,but,inthe3Dview,theobserver'svantagepointisbehindandaboveturtle.
Theobservermayonlywatchorfollowasinglesubject.Callingfollowwillalterthehighlightcreatedbypriorcallstowatchandwatch-me,highlightingthefollowedturtleinstead.
Seealsofollow-me,ride,reset-perspective,watch,subject.
follow-me
follow-me
Askstheobservertofollowthisturtle.
Theobservermayonlywatchorfollowasinglesubject.Callingfollow-mewillremovethehighlightcreatedbypriorcallstowatchandwatch-me,highlightingthisturtleinstead.
Seealsofollow.
foreach
foreachlistcommand(foreachlist1...command)
Withasinglelist,runsthecommandforeachitemoflist.commandmaybethenameofacommand,orananonymouscommandcreatedwith->.
foreach [1.1 2.2 2.6] show=> 1.1=> 2.2=> 2.6foreach [1.1 2.2 2.6] [ x -> show (word x " -> " round x) ]=> 1.1 -> 1=> 2.2 -> 2=> 2.6 -> 3
Withmultiplelists,runscommandforeachgroupofitemsfromeachlist.So,theyarerunonceforthefirstitems,oncefortheseconditems,andsoon.Allthelistsmustbethesamelength.
Someexamplesmakethisclearer:
(foreach [1 2 3] [2 4 6] [ [a b] -> show word "the sum is: " (a + b) ])=> "the sum is: 3"=> "the sum is: 6"=> "the sum is: 9"(foreach list (turtle 1) (turtle 2) [3 4] [ [the-turtle num-steps] -> ask the-turtle [ fd num-steps ] ]);; turtle 1 moves forward 3 patches;; turtle 2 moves forward 4 patches
Seealsomap,->(anonymousprocedure).
forwardfd
forwardnumber
Theturtlemovesforwardbynumbersteps,onestepatatime.(Ifnumberisnegative,theturtlemovesbackward.)
fd 10isequivalenttorepeat 10 [ jump 1 ] .fd 10.5isequivalenttorepeat 10 [ jump 1 ] jump 0.5.
Iftheturtlecannotmoveforwardnumberstepsbecauseitisnotpermittedbythecurrenttopologytheturtlewillcompleteasmanystepsof1
![Page 390: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/390.jpg)
Since1.0
Since1.0
asitcan,thenstop.
Seealsojump,can-move?.
fput
fputitemlist
Addsitemtothebeginningofalistandreportsthenewlist.
;; suppose mylist is [5 7 10]set mylist fput 2 mylist;; mylist is now [2 5 7 10]
G
globals
globals[var1...]
Thiskeyword,likethebreed,<breeds>-own,patches-own,andturtles-ownkeywords,canonlybeusedatthebeginningofaprogram,beforeanyfunctiondefinitions.Itdefinesnewglobalvariables.Globalvariablesare"global"becausetheyareaccessiblebyallagentsandcanbeusedanywhereinamodel.
Mostoften,globalsisusedtodefinevariablesorconstantsthatneedtobeusedinmanypartsoftheprogram.
H
hatch
hatchnumber[commands]hatch-<breeds>number[commands]
Thisturtlecreatesnumbernewturtles.Eachnewturtleinheritsofallitsvariables,includingitslocation,fromitsparent.(Exceptions:eachnewturtlewillhaveanewwhonumber,anditmaybeofadifferentbreedthanitsparentifthehatch-<breeds>formisused.)
Thenewturtlesthenruncommands.Youcanusethecommandstogivethenewturtlesdifferentcolors,headings,locations,orwhatever.(Thenewturtlesarecreatedallatonce,thenrunoneatatime,inrandomorder.)
Ifthehatch-<breeds>formisused,thenewturtlesarecreatedasmembersofthegivenbreed.Otherwise,thenewturtlesarethesamebreedastheirparent.
hatch 1 [ lt 45 fd 1 ];; this turtle creates one new turtle,;; and the child turns and moves awayhatch-sheep 1 [ set color black ];; this turtle creates a new turtle;; of the sheep breed
Seealsocreate-turtles,sprout.
heading
heading
Thisisabuilt-inturtlevariable.Itindicatesthedirectiontheturtleisfacing.Thisisanumbergreaterthanorequalto0andlessthan360.0isnorth,90iseast,andsoon.Youcansetthisvariabletomakeaturtleturn.
Seealsoright,left,dx,dy.
Example:
set heading 45 ;; turtle is now facing northeastset heading heading + 10 ;; same effect as "rt 10"
hidden?
hidden?
Thisisabuilt-inturtleorlinkvariable.Itholdsaboolean(trueorfalse)valueindicatingwhethertheturtleorlinkiscurrentlyhidden(i.e.,invisible).Youcansetthisvariabletomakeaturtleorlinkdisappearorreappear.
Seealsohide-turtle,show-turtle,hide-link,show-link
Example:
![Page 391: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/391.jpg)
Since4.0
Since1.0Since1.0
Since1.0
Since1.0
Since1.0
Since1.1
Since4.1
set hidden? not hidden?;; if turtle was showing, it hides, and if it was hiding,;; it reappears
hide-link
hide-link
Thelinkmakesitselfinvisible.
Note:Thiscommandisequivalenttosettingthelinkvariable"hidden?"totrue.
Seealsoshow-link.
hide-turtleht
hide-turtle
Theturtlemakesitselfinvisible.
Note:Thiscommandisequivalenttosettingtheturtlevariable"hidden?"totrue.
Seealsoshow-turtle.
histogram
histogramlist
Histogramsthevaluesinthegivenlist
Drawsahistogramshowingthefrequencydistributionofthevaluesinthelist.Theheightsofthebarsinthehistogramrepresentthenumbersofvaluesineachsubrange.
Beforethehistogramisdrawn,firstanypreviouspointsdrawnbythecurrentplotpenareremoved.
Anynon-numericvaluesinthelistareignored.
Thehistogramisdrawnonthecurrentplotusingthecurrentplotpenandpencolor.Autoscalingdoesnotaffectahistogram'shorizontalrange,soset-plot-x-rangeshouldbeusedtocontroltherange,andthepenintervalcanthenbeset(eitherdirectlywithset-plot-pen-interval,orindirectlyviaset-histogram-num-bars)tocontrolhowmanybarsthatrangeissplitupinto.
Besurethatifyouwantthehistogramdrawnwithbarsthatthecurrentpenisinbarmode(mode1).
Forhistogrammingpurposestheplot'sXrangeisnotconsideredtoincludethemaximumXvalue.ValuesequaltothemaximumXwillfalloutsideofthehistogram'srange.
histogram [color] of turtles;; draws a histogram showing how many turtles there are;; of each color
home
home
Thisturtlemovestotheorigin(0,0).Equivalenttosetxy 0 0.
hsb
hsbhuesaturationbrightness
ReportsaRGBlistwhengiventhreenumbersdescribinganHSBcolor.Hue,saturation,andbrightnessareintegersintherange0-360,0-100,0-100respectively.TheRGBlistcontainsthreeintegersintherangeof0-255.
Seealsorgb
hubnet-broadcast
hubnet-broadcasttag-namevalue
ThisbroadcastsvaluefromNetLogototheinterfaceelementwiththenametag-nameontheclients.
SeetheHubNetAuthoringGuidefordetailsandinstructions.
hubnet-broadcast-clear-output
![Page 392: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/392.jpg)
Since4.1
Since4.1Since4.1
Since5.0
Since1.2.1
Since1.2.1
Since1.1
Since5.0
Since5.0
Since1.1
hubnet-broadcast-clear-output
Thisclearsallmessagesprintedtothetextareaoneveryclient.
Seealso:hubnet-broadcast-message,hubnet-send-clear-output
hubnet-broadcast-message
hubnet-broadcast-messagevalue
Thisprintsthevalueinthetextareaoneachclient.Thisisthesamefunctionalityasthe"BroadcastMessage"buttonintheHubNetControlCenter.
Seealso:hubnet-send-message
hubnet-clear-overridehubnet-clear-overrides
hubnet-clear-overrideclientagent-or-setvariable-namehubnet-clear-overridesclient
Removeoverridesfromtheoverridelistonclient.hubnet-clear-overrideremovesonlytheoverrideforthespecifiedvariableforthespecifiedagentoragentset.hubnet-clear-overridesremovesalloverridesfromthespecifiedclient.
Seealso:hubnet-send-override
hubnet-clients-list
hubnet-clients-list
ReportsalistcontainingthenamesofalltheclientscurrentlyconnectedtotheHubNetserver.
hubnet-enter-message?
hubnet-enter-message?
Reportstrueifanewclientjustenteredthesimulation.Reportsfalseotherwise.hubnet-message-sourcewillcontaintheusernameoftheclientthatjustloggedon.
SeetheHubNetAuthoringGuidefordetailsandinstructions.
hubnet-exit-message?
hubnet-exit-message?
Reportstrueifaclientjustexitedthesimulation.Reportsfalseotherwise.hubnet-message-sourcewillcontaintheusernameoftheclientthatjustloggedoff.
SeetheHubNetAuthoringGuidefordetailsandinstructions.
hubnet-fetch-message
hubnet-fetch-message
Ifthereisanynewdatasentbytheclients,thisretrievesthenextpieceofdata,sothatitcanbeaccessedbyhubnet-message,hubnet-message-source,andhubnet-message-tag.Thiswillcauseanerrorifthereisnonewdatafromtheclients.
SeetheHubNetAuthoringGuidefordetails.
hubnet-kick-client
hubnet-kick-clientclient-name
Kickstheclientwiththegivenclient-name.ThisisequivalenttoclickingtheclientnameintheHubNetControlCenterandpressingtheKickbutton.
hubnet-kick-all-clients
hubnet-kick-all-clients
KicksoutallcurrentlyconnectedHubNetclients.ThisisequivalenttoselectingallclientsintheHubNetControlCenterandpressingtheKickbutton.
hubnet-message
hubnet-message
![Page 393: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/393.jpg)
Since1.1
Since1.1
Since1.1
Since1.1
Since4.1
Since1.1
Since4.1
Since4.1
Reportsthemessageretrievedbyhubnet-fetch-message.
SeetheHubNetAuthoringGuidefordetails.
hubnet-message-source
hubnet-message-source
Reportsthenameoftheclientthatsentthemessageretrievedbyhubnet-fetch-message.
SeetheHubNetAuthoringGuidefordetails.
hubnet-message-tag
hubnet-message-tag
Reportsthetagthatisassociatedwiththedatathatwasretrievedbyhubnet-fetch-message.ThetagwillbeoneoftheDisplayNamesoftheinterfaceelementsintheclientinterface.
SeetheHubNetAuthoringGuidefordetails.
hubnet-message-waiting?
hubnet-message-waiting?
Thislooksforanewmessagesentbytheclients.Itreportstrueifthereisone,andfalseifthereisnot.
SeetheHubNetAuthoringGuidefordetails.
hubnet-reset
hubnet-reset
StartsuptheHubNetsystem.HubNetmustbestartedtouseanyoftheotherhubnetprimitives.
SeetheHubNetAuthoringGuidefordetails.
hubnet-reset-perspective
hubnet-reset-perspectivetag-name
Clearswatchorfollowsentdirectlytotheclient.Theviewperspectivewillreverttotheserverperspective.
Seealso:hubnet-send-watchhubnet-send-follow
hubnet-send
hubnet-sendstringtag-namevalue
hubnet-sendlist-of-stringstag-namevalue
Forastring,thissendsvaluefromNetLogotothetagtag-nameontheclientthathasstringforitsusername.
Foralist-of-strings,thissendsvaluefromNetLogotothetagtag-nameonalltheclientsthathaveausernamethatisinthelist-of-strings.
Sendingamessagetoanon-existentclient,usinghubnet-send,generatesahubnet-exit-message.
SeetheHubNetAuthoringGuidefordetails.
hubnet-send-clear-output
hubnet-send-clear-outputstring
hubnet-send-clear-outputlist-of-strings
Thisclearsallmessagesprintedtothetextareaonthegivenclientorclients(specifiedinthestringorlist-of-strings.
Seealso:hubnet-send-message,hubnet-broadcast-clear-output
hubnet-send-follow
hubnet-send-followclient-nameagentradius
Tellstheclientassociatedwithclient-nametofollowagentshowingaradiussizedMooreneighborhoodaroundtheagent.
Aclientmayonlywatchorfollowasinglesubject.Callinghubnet-send-followwillalterthehighlightcreatedbypriorcallstohubnet-send-watch,highlightingthefollowedagentinstead.
Seealso:hubnet-send-watch,hubnet-reset-perspective
![Page 394: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/394.jpg)
Since4.1
Since4.1
Since4.1
Since1.0
Since1.0
Since2.0
hubnet-send-message
hubnet-send-messagestringvalue
Thisprintsvalueinthetextareaontheclientspecifiedbystring.
Seealso:hubnet-broadcast-message
hubnet-send-override
hubnet-send-overrideclient-nameagent-or-setvariable-name[reporter]
Evaluatesreporterfortheagentoragentsetindicatedthensendsthevaluestotheclientto"override"thevalueofvariable-nameonlyonclient-name.Thisisusedtochangetheappearanceofagentsintheclientview,hence,onlybuilt-invariablesthataffecttheappearanceoftheagentmaybeselected.Forexample,youcanoverridethecolorvariableofaturtle:
ask turtles [ hubnet-send-override client-name self "color" [ red ] ]
Inthisexampleassumethatthereisaturtles-ownvariableclient-namewhichisassociatedwithaloggedinclient,andalltheturtlesareblue.Thiscodemakestheturtleassociatedwitheachclientappearredinhisorherownviewbutnotonanyoneelse'sorontheserver.
Seealso:hubnet-clear-overrides
hubnet-send-watch
hubnet-send-watchclient-nameagent
Tellstheclientassociatedwithclient-nametowatchagent.
Aclientmayonlywatchorfollowasinglesubject.Callinghubnet-send-watchwillundoperspectivechangescausedbypriorcallstohubnet-send-follow.
Seealso:hubnet-send-follow,hubnet-reset-perspective
I
if
ifcondition[commands]
Reportermustreportaboolean(trueorfalse)value.
Ifconditionreportstrue,runscommands.
Thereportermayreportadifferentvaluefordifferentagents,sosomeagentsmayruncommandsandothersdon't.
if xcor > 0[ set color blue ];; turtles in the right half of the world;; turn blue
Seealsoifelse,ifelse-value.
ifelse
ifelsereporter[commands1][commands2]
Reportermustreportaboolean(trueorfalse)value.
Ifreporterreportstrue,runscommands1.
Ifreporterreportsfalse,runscommands2.
Thereportermayreportadifferentvaluefordifferentagents,sosomeagentsmayruncommands1whileothersruncommands2.
ask patches [ ifelse pxcor > 0 [ set pcolor blue ] [ set pcolor red ] ];; the left half of the world turns red and;; the right half turns blue
Seealsoif,ifelse-value.
ifelse-value
ifelse-valuereporter[reporter1][reporter2]
Reportermustreportaboolean(trueorfalse)value.
![Page 395: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/395.jpg)
Since3.0
Since3.0
Since4.0
Since1.0
Since3.0
Ifreporterreportstrue,theresultisthevalueofreporter1.
Ifreporterreportsfalse,theresultisthevalueofreporter2.
Thiscanbeusedwhenaconditionalisneededinthecontextofareporter,wherecommands(suchasifelse)arenotallowed.
ask patches [ set pcolor ifelse-value (pxcor > 0) [blue] [red]];; the left half of the world turns red and;; the right half turns blueshow n-values 10 [ifelse-value (? < 5) [0] [1]]=> [0 0 0 0 0 1 1 1 1 1]show reduce [ [a b] -> ifelse-value (a > b) [a] [b] ] [1 3 2 5 3 8 3 2 1]=> 8
Seealsoif,ifelse.
import-drawing
import-drawingfilename
Readsanimagefileintothedrawing,scalingittothesizeoftheworld,whileretainingtheoriginalaspectratiooftheimage.Theimageiscenteredinthedrawing.Theolddrawingisnotclearedfirst.
Agentscannotsensethedrawing,sotheycannotinteractwithorprocessimagesimportedbyimport-drawing.Ifyouneedagentstosenseanimage,useimport-pcolorsorimport-pcolors-rgb.
Thefollowingimagefileformatsaresupported:BMP,JPG,GIF,andPNG.Iftheimageformatsupportstransparency(alpha),thatinformationwillbeimportedaswell.
import-pcolors
import-pcolorsfilename
Readsanimagefile,scalesittothesamedimensionsasthepatchgridwhilemaintainingtheoriginalaspectratiooftheimage,andtransferstheresultingpixelcolorstothepatches.Theimageiscenteredinthepatchgrid.Theresultingpatchcolorsmaybedistorted,sincetheNetLogocolorspacedoesnotincludeallpossiblecolors.(SeetheColorsectionoftheProgrammingGuide.)import-pcolorsmaybeslowforsomeimages,particularlywhenyouhavemanypatchesandalargeimagewithmanydifferentcolors.
Sinceimport-pcolorssetsthepcolorofpatches,agentscansensetheimage.Thisisusefulifagentsneedtoanalyze,process,orotherwiseinteractwiththeimage.Ifyouwanttosimplydisplayastaticbackdrop,withoutcolordistortion,seeimport-drawing.
Thefollowingimagefileformatsaresupported:BMP,JPG,GIF,andPNG.Iftheimageformatsupportstransparency(alpha),thenallfullytransparentpixelswillbeignored.(Partiallytransparentpixelswillbetreatedasopaque.)
import-pcolors-rgb
import-pcolors-rgbfilename
Readsanimagefile,scalesittothesamedimensionsasthepatchgridwhilemaintainingtheoriginalaspectratiooftheimage,andtransferstheresultingpixelcolorstothepatches.Theimageiscenteredinthepatchgrid.Unlikeimport-pcolorstheexactcolorsintheoriginalimageareretained.ThepcolorvariableofallthepatcheswillbeanRGBlistratherthanan(approximated)NetLogocolor.
Thefollowingimagefileformatsaresupported:BMP,JPG,GIF,andPNG.Iftheimageformatsupportstransparency(alpha),thenallfullytransparentpixelswillbeignored.(Partiallytransparentpixelswillbetreatedasopaque.)
import-world
import-worldfilename
Readsthevaluesofallvariablesforamodel,bothbuilt-inanduser-defined,includingallobserver,turtle,andpatchvariables,fromanexternalfilenamedbythegivenstring.Thefileshouldbeintheformatusedbytheexport-worldprimitive.
NotethatthefunctionalityofthisprimitiveisalsodirectlyavailablefromNetLogo'sFilemenu.
Whenusingimport-world,toavoiderrors,performthesestepsinthefollowingorder:
1. Openthemodelfromwhichyoucreatedtheexportfile.2. PresstheSetupbutton,togetthemodelinastatefromwhichitcanberun.3. Importthefile.4. Re-openanyfilesthatthemodelhadopenedwiththefile-opencommand.5. Ifyouwant,pressGobuttontocontinuerunningthemodelfromthepointwhereitleftoff.
Ifyouwishtoimportafilefromalocationotherthanthemodel'slocation,youmayincludethefullpathtothefileyouwishtoimport.Seeexport-worldforanexample.
in-cone
![Page 396: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/396.jpg)
Since4.0
Since4.0
Since4.0
Since4.0
Since1.0
agentsetin-conedistanceangle
Thisreporterletsyougiveaturtlea"coneofvision"infrontofitself.Theconeisdefinedbythetwoinputs,thevisiondistance(radius)andtheviewingangle.Theviewinganglemayrangefrom0to360andiscenteredaroundtheturtle'scurrentheading.(Iftheangleis360,thenin-coneisequivalenttoin-radius.)
in-conereportsanagentsetthatincludesonlythoseagentsfromtheoriginalagentsetthatfallinthecone.(Thiscanincludetheagentitself.)
Thedistancetoapatchismeasuredfromthecenterofthepatch.
ask turtles [ ask patches in-cone 3 60 [ set pcolor red ] ];; each turtle makes a red "splotch" of patches in a 60 degree;; cone of radius 3 ahead of itself
in-<breed>-neighbor?in-link-neighbor?
in-<breed>-neighbor?agentin-link-neighbor?turtle
Reportstrueifthereisadirectedlinkgoingfromturtletothecalleroranundirectedlinkconnectingturtletothecaller.Youcanthinkofthisas"istherealinkIcanusetogetfromturtletothecaller?"
crt 2ask turtle 0 [ create-link-to turtle 1 show in-link-neighbor? turtle 1 ;; prints false show out-link-neighbor? turtle 1 ;; prints true]ask turtle 1 [ show in-link-neighbor? turtle 0 ;; prints true show out-link-neighbor? turtle 0 ;; prints false]
in-<breed>-neighborsin-link-neighbors
in-<breed>-neighborsin-link-neighbors
Reportstheagentsetofalltheturtlesthathavedirectedlinkscomingfromthemtothecalleraswellasallturtlesthathaveanundirectedlinkconnectingthemwiththecaller.Youcanthinkofthisas"alltheturtlesthatcangettothecallerusingalink."
crt 4ask turtle 0 [ create-links-to other turtles ]ask turtle 1 [ ask in-link-neighbors [ set color blue ] ] ;; turtle 0 turns blue
in-<breed>-fromin-link-from
in-<breed>-fromturtlein-link-fromturtle
Reportsadirectedlinkfromturtletothecalleroranundirectedlinkconnectingthetwo.Ifnolinkexiststhenitreportsnobody.Ifmorethanonesuchlinkexists,reportsarandomone.Youcanthinkofthisas"givemealinkthatIcanusetotravelfromturtletothecaller."
crt 2ask turtle 0 [ create-link-to turtle 1 ]ask turtle 1 [ show in-link-from turtle 0 ] ;; shows link 0 1ask turtle 0 [ show in-link-from turtle 1 ] ;; shows nobody
Seealso:out-link-tolink-with
__includes
__includes[filename...]
CausesexternalNetLogosourcefiles(withthe.nlssuffix)tobeincludedinthismodel.Includedfilesmaycontainbreed,variable,andproceduredefinitions.__includescanonlybeusedonceperfile.
in-radius
agentsetin-radiusnumber
![Page 397: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/397.jpg)
Since6.0.2
Since1.1
Since1.0
Since1.2.1Since1.2.1
Since6.0Since6.0
Since1.2.1Since4.0Since4.0Since4.0Since1.0
Since1.2.1Since1.2.1
Since4.0Since1.0
Since1.2.1Since4.0Since4.0
Reportsanagentsetthatincludesonlythoseagentsfromtheoriginalagentsetwhosedistancefromthecallerislessthanorequaltonumber.(Thiscanincludetheagentitself.)
Thedistancetoorafromapatchismeasuredfromthecenterofthepatch.
ask turtles [ ask patches in-radius 3 [ set pcolor red ] ];; each turtle makes a red "splotch" around itself
insert-item
insert-itemindexlistvalueinsert-itemindexstring1string2
Onalist,insertsaniteminthatlist.indexistheindexwheretheitemwillbeinserted.Thefirstitemhasanindexof0.(The6thiteminalistwouldhaveanindexof5.)
Likewiseforastring,butallcharactersinamultiple-characterstring2areinsertedatindex.
show insert-item 2 [2 7 4 5] 15=> [2 7 15 4 5]show insert-item 2 "cat" "re"=> "caret"
inspect
inspectagent
Opensanagentmonitorforthegivenagent(turtleorpatch).
inspect patch 2 4;; an agent monitor opens for that patchinspect one-of sheep;; an agent monitor opens for a random turtle from;; the "sheep" breed
Seestop-inspectingandstop-inspecting-dead-agents
int
intnumber
Reportstheintegerpartofnumber--anyfractionalpartisdiscarded.
show int 4.7=> 4show int -3.5=> -3
is-agent?is-agentset?is-anonymous-command?is-anonymous-reporter?is-boolean?is-directed-link?is-link?is-link-set?is-list?is-number?is-patch?is-patch-set?is-string?is-turtle?is-turtle-set?is-undirected-link?
is-agent?valueis-agentset?valueis-anonymous-command?valueis-anonymous-reporter?valueis-boolean?valueis-<breed>?valueis-<link-breed>?valueis-directed-link?valueis-link?valueis-link-set?valueis-list?value
![Page 398: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/398.jpg)
Since1.0
Since1.0
Since1.0
is-number?valueis-patch?valueis-patch-set?valueis-string?valueis-turtle?valueis-turtle-set?valueis-undirected-link?value
Reportstrueifvalueisofthegiventype,falseotherwise.
item
itemindexlistitemindexstring
Onlists,reportsthevalueoftheiteminthegivenlistwiththegivenindex.
Onstrings,reportsthecharacterinthegivenstringatthegivenindex.
Notethattheindicesbeginfrom0,not1.(Thefirstitemisitem0,theseconditemisitem1,andsoon.)
;; suppose mylist is [2 4 6 8 10]show item 2 mylist=> 6show item 3 "my-shoe"=> "s"
J
jump
jumpnumber
Theturtlemovesforwardbynumberunitsallatonce(ratherthanonestepatatimeaswiththeforwardcommand).
Iftheturtlecannotjumpnumberunitsbecauseitisnotpermittedbythecurrenttopologytheturtledoesnotmoveatall.
Seealsoforward,can-move?.
L
label
label
Thisisabuilt-inturtleorlinkvariable.Itmayholdavalueofanytype.Theturtleorlinkappearsintheviewwiththegivenvalue"attached"toitastext.Youcansetthisvariabletoadd,change,orremoveaturtleorlink'slabel.
Seealsolabel-color,plabel,plabel-color.
Example:
ask turtles [ set label who ];; all the turtles now are labeled with their;; who numbersask turtles [ set label "" ];; all turtles now are not labeled
label-color
label-color
Thisisabuilt-inturtleorlinkvariable.Itholdsanumbergreaterthanorequalto0andlessthan140.Thisnumberdetermineswhatcolortheturtleorlink'slabelappearsin(ifithasalabel).Youcansetthisvariabletochangethecolorofaturtleorlink'slabel.
Seealsolabel,plabel,plabel-color.
Example:
ask turtles [ set label-color red ];; all the turtles now have red labels
last
lastlistlaststring
![Page 399: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/399.jpg)
Since4.0
Since4.0
Since4.0
Since4.0
Onalist,reportsthelastiteminthelist.
Onastring,reportsaone-characterstringcontainingonlythelastcharacteroftheoriginalstring.
layout-circle
layout-circleagentsetradiuslayout-circlelist-of-turtlesradius
Arrangesthegiventurtlesinacirclecenteredonthepatchatthecenteroftheworldwiththegivenradius.(Iftheworldhasanevensizethecenterofthecircleisroundeddowntothenearestpatch.)Theturtlespointoutwards.
Ifthefirstinputisanagentset,theturtlesarearrangedinrandomorder.
Ifthefirstinputisalist,theturtlesarearrangedclockwiseinthegivenorder,startingatthetopofthecircle.(Anynon-turtlesinthelistareignored.)
;; in random orderlayout-circle turtles 10;; in order by who numberlayout-circle sort turtles 10;; in order by sizelayout-circle sort-by [ [a b] -> [size] of a < [size] of b ] turtles 10
layout-radial
layout-radialturtle-setlink-setroot-agent
Arrangestheturtlesinturtle-setconnectedbylinksinlink-set,inaradialtreelayout,centeredaroundtheroot-agentwhichismovedtothecenteroftheworldview.
Onlylinksinthelink-setwillbeusedtodeterminethelayout.Iflinksconnectturtlesthatarenotinturtle-setthoseturtleswillremainstationary.
Evenifthenetworkdoescontaincycles,andisnotatruetreestructure,thislayoutwillstillwork,althoughtheresultswillnotalwaysbepretty.
to make-a-tree set-default-shape turtles "circle" crt 6 ask turtle 0 [ create-link-with turtle 1 create-link-with turtle 2 create-link-with turtle 3 ] ask turtle 1 [ create-link-with turtle 4 create-link-with turtle 5 ] ; do a radial tree layout, centered on turtle 0 layout-radial turtles links (turtle 0)end
layout-spring
layout-springturtle-setlink-setspring-constantspring-lengthrepulsion-constant
Arrangestheturtlesinturtle-set,asifthelinksinlink-setarespringsandtheturtlesarerepellingeachother.Turtlesthatareconnectedbylinksinlink-setbutnotincludedinturtle-setaretreatedasanchorsandarenotmoved.
spring-constantisameasureofthe"tautness"ofthespring.Itisthe"resistance"tochangeintheirlength.spring-constantistheforcethespringwouldexertifit'slengthwerechangedby1unit.
spring-lengthisthe"zero-force"lengthorthenaturallengthofthesprings.Thisisthelengthwhichallspringstrytoachieveeitherbypushingouttheirnodesorpullingthemin.
repulsion-constantisameasureofrepulsionbetweenthenodes.Itistheforcethat2nodesatadistanceof1unitwillexertoneachother.
Therepulsioneffecttriestogetthenodesasfaraspossiblefromeachother,inordertoavoidcrowdingandthespringeffecttriestokeepthemat"about"acertaindistancefromthenodestheyareconnectedto.Theresultisthelayingoutofthewholenetworkinawaywhichhighlightsrelationshipsamongthenodesandatthesametimeiscrowdedlessandisvisuallypleasing.
ThelayoutalgorithmisbasedontheFruchterman-Reingoldlayoutalgorithm.Moreinformationaboutthisalgorithmcanbeobtainedhere.
to make-a-triangle set-default-shape turtles "circle" crt 3 ask turtle 0 [ create-links-with other turtles ] ask turtle 1 [ create-link-with turtle 2 ] repeat 30 [ layout-spring turtles links 0.2 5 1 ] ;; lays the nodes in a triangleend
layout-tutte
![Page 400: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/400.jpg)
Since1.0Since1.0
Since1.0
Since2.1
Since4.0
Since4.0
layout-tutteturtle-setlink-setradius
Theturtlesthatareconnectedbylinksinlink-setbutnotincludedinturtle-setareplacedinacirclelayoutwiththegivenradius.Thereshouldbeatleast3agentsinthisagentset.
Theturtlesinturtle-setarethenlaidoutinthefollowingmanner:Eachturtleisplacedatcentroid(orbarycenter)ofthepolygonformedbyitslinkedneighbors.(Thecentroidislikea2-dimensionalaverageofthecoordinatesoftheneighbors.)
(Thepurposeofthecircleof"anchoragents"istopreventalltheturtlesfromcollapsingdowntoonepoint.)
Afterafewiterationsofthis,thelayoutwillstabilize.
ThislayoutisnamedafterthemathematicianWilliamThomasTutte,whoproposeditasamethodforgraphlayout.
to make-a-tree set-default-shape turtles "circle" crt 6 ask turtle 0 [ create-link-with turtle 1 create-link-with turtle 2 create-link-with turtle 3 ] ask turtle 1 [ create-link-with turtle 4 create-link-with turtle 5 ] ; place all the turtles with just one ; neighbor on the perimeter of a circle ; and then place the remaining turtles inside ; this circle, spread between their neighbors. repeat 10 [ layout-tutte (turtles with [link-neighbors = 1]) links 12 ]end
leftlt
leftnumber
Theturtleturnsleftbynumberdegrees.(Ifnumberisnegative,itturnsright.)
length
lengthlistlengthstring
Reportsthenumberofitemsinthegivenlist,orthenumberofcharactersinthegivenstring.
let
letvariablevalue
Createsanewlocalvariableandgivesitthegivenvalue.Alocalvariableisonethatexistsonlywithintheenclosingblockofcommands.
Ifyouwanttochangethevalueafterwards,useset.
Example:
let prey one-of sheep-hereif prey != nobody [ ask prey [ die ] ]
link
linkend1end2<breed>end1end2
Giventhewhonumbersoftheendpoints,reportsthelinkconnectingtheturtles.Ifthereisnosuchlinkreportsnobody.Torefertobreededlinksyoumustusethesingularbreedformwiththeendpoints.
ask link 0 1 [ set color green ];; unbreeded link connecting turtle 0 and turtle 1 will turn greenask directed-link 0 1 [ set color red ];; directed link connecting turtle 0 and turtle 1 will turn red
Seealsopatch-at.
link-heading
link-heading
Reportstheheadingindegrees(atleast0,lessthan360)fromend1toend2ofthelink.Throwsaruntimeerroriftheendpointsareatthesamelocation.
![Page 401: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/401.jpg)
Since4.0
Since4.0
Since4.0
Since4.0
Since1.0
ask link 0 1 [ print link-heading ];; prints [[towards other-end] of end1] of link 0 1
Seealsolink-length
link-length
link-length
Reportsthedistancebetweentheendpointsofthelink.
ask link 0 1 [ print link-length ];; prints [[distance other-end] of end1] of link 0 1
Seealsolink-heading
link-set
link-setvalue(link-setvalue1value2...)
Reportsanagentsetcontainingallofthelinksanywhereinanyoftheinputs.Theinputsmaybeindividuallinks,linkagentsets,nobody,orlists(ornestedlists)containinganyoftheabove.
link-set selflink-set [my-links] of nodes with [color = red]
Seealsoturtle-set,patch-set.
link-shapes
link-shapes
Reportsalistofstringscontainingallofthelinkshapesinthemodel.
Newshapescanbecreated,orimportedfromothermodels,intheLinkShapesEditor.
show link-shapes=> ["default"]
links
links
Reportstheagentsetconsistingofalllinks.
show count links;; prints the number of links
links-own
links-own[var1...]<link-breeds>-own[var1...]
Thelinks-ownkeyword,liketheglobals,breed,<breeds>-own,turtles-own,andpatches-ownkeywords,canonlybeusedatthebeginningofaprogram,beforeanyfunctiondefinitions.Itdefinesthevariablesbelongingtoeachlink.
Ifyouspecifyabreedinsteadof"links",onlylinksofthatbreedhavethelistedvariables.(Morethanonelinkbreedmaylistthesamevariable.)
undirected-link-breed [sidewalks sidewalk]directed-link-breed [streets street]links-own [traffic] ;; applies to all breedssidewalks-own [pedestrians]streets-own [cars bikes]
list
listvalue1value2(listvalue1...)
Reportsalistcontainingthegivenitems.Theitemscanbeofanytype,producedbyanykindofreporter.
show list (random 10) (random 10)=> [4 9] ;; or similar listshow (list 5)
![Page 402: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/402.jpg)
Since1.0
Since1.0
Since1.0
Since1.0
Since1.3
Since1.0
=> [5]show (list (random 10) 1 2 3 (random 10))=> [4 1 2 3 9] ;; or similar list
ln
lnnumber
Reportsthenaturallogarithmofnumber,thatis,thelogarithmtothebasee(2.71828...).
Seealsoe,log.
log
lognumberbase
Reportsthelogarithmofnumberinbasebase.
show log 64 2=> 6
Seealsoln.
loop
loop[commands]
Repeatsthecommandsforever,oruntiltheenclosingprocedureexitsthroughuseofthestoporreportcommands.
to move-to-world-edge ;; turtle procedure loop [ if not can-move? 1 [ stop ] fd 1 ]end
Inthisexample,stopexitsnotjusttheloop,buttheentireprocedure.
Note:inmanycircumstances,itismoreappropriatetouseaforeverbuttontorepeatsomethingindefinitely.SeeButtonsintheProgrammingGuide.
lput
lputvaluelist
Addsvaluetotheendofalistandreportsthenewlist.
;; suppose mylist is [2 7 10 "Bob"]set mylist lput 42 mylist;; mylist now is [2 7 10 "Bob" 42]
M
map
mapreporterlist(mapreporterlist1...)
Withasinglelist,thegivenreporterisrunforeachiteminthelist,andalistoftheresultsiscollectedandreported.reportermaybeananonymousreporterorthenameofareporter.
show map round [1.1 2.2 2.7]=> [1 2 3]show map [ i -> i * i ] [1 2 3]=> [1 4 9]
Withmultiplelists,thegivenreporterisrunforeachgroupofitemsfromeachlist.So,itisrunonceforthefirstitems,oncefortheseconditems,andsoon.Allthelistsmustbethesamelength.
Someexamplesmakethisclearer:
show (map + [1 2 3] [2 4 6])=> [3 6 9]show (map [ [a b c] -> a + b = c ] [1 2 3] [2 4 6] [3 5 9])=> [true false true]
Seealsoforeach,->(anonymousprocedure).
max
![Page 403: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/403.jpg)
Since4.0
Since1.0
Since3.1Since3.1
Since1.0
Since1.0
maxlist
Reportsthemaximumnumbervalueinthelist.Itignoresothertypesofitems.
show max [xcor] of turtles;; prints the x coordinate of the turtle which is;; farthest right in the worldshow max list a b;; prints the larger of the two variables a and bshow max (list a b c);; prints the largest of the three variables a, b, and c
max-n-of
max-n-ofnumberagentset[reporter]
Reportsanagentsetcontainingnumberagentsfromagentsetwiththehighestvaluesofreporter.Theagentsetisbuiltbyfindingalltheagentswiththehighestvalueofreporter,iftherearenotnumberagentswiththatvaluethenagentswiththesecondhighestvaluearefound,andsoon.Attheend,ifthereisatiethatwouldmaketheresultingagentsettoolarge,thetieisbrokenrandomly.
;; assume the world is 11 x 11show max-n-of 5 patches [pxcor];; shows 5 patches with pxcor = max-pxcorshow max-n-of 5 patches with [pycor = 0] [pxcor];; shows an agentset containing:;; (patch 1 0) (patch 2 0) (patch 3 0) (patch 4 0) (patch 5 0)
Seealsomax-one-of,with-max.
max-one-of
max-one-ofagentset[reporter]
Reportstheagentintheagentsetthathasthehighestvalueforthegivenreporter.Ifthereisatiethiscommandreportsonerandomagentwiththehighestvalue.Ifyouwantallsuchagents,usewith-maxinstead.
show max-one-of patches [count turtles-here]
;; prints the first patch with the most turtles on it
Seealsomax-n-of,with-max.
max-pxcormax-pycor
max-pxcormax-pycor
Thesereportersgivethemaximumx-coordinateandmaximumy-coordinate,(respectively)forpatches,whichdeterminesthesizeoftheworld.
UnlikeinolderversionsofNetLogotheorigindoesnothavetobeatthecenteroftheworld.However,themaximumx-andy-coordinatesmustbegreaterthanorequaltozero.
Note:Youcansetthesizeoftheworldonlybyeditingtheview--thesearereporterswhichcannotbeset.
crt 100 [ setxy random-float max-pxcor random-float max-pycor ];; distributes 100 turtles randomly in the;; first quadrant
Seealsomin-pxcor,min-pycor,world-width,andworld-height
mean
meanlist
Reportsthestatisticalmeanofthenumericitemsinthegivenlist.Errorsonnon-numericitems.Themeanistheaverage,i.e.,thesumoftheitemsdividedbythetotalnumberofitems.
show mean [xcor] of turtles;; prints the average of all the turtles' x coordinates
median
medianlist
Reportsthestatisticalmedianofthenumericitemsofthegivenlist.Ignoresnon-numericitems.Themedianistheitemthatwouldbeinthemiddleifalltheitemswerearrangedinorder.(Iftwoitemswouldbeinthemiddle,themedianistheaverageofthetwo.)
![Page 404: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/404.jpg)
Since1.0
Since1.0
Since4.0
Since1.0
Since3.1Since3.1
show median [xcor] of turtles;; prints the median of all the turtles' x coordinates
member?
member?valuelistmember?string1string2member?agentagentset
Foralist,reportstrueifthegivenvalueappearsinthegivenlist,otherwisereportsfalse.
Forastring,reportstrueorfalsedependingonwhetherstring1appearsanywhereinsidestring2asasubstring.
Foranagentset,reportstrueifthegivenagentisappearsinthegivenagentset,otherwisereportsfalse.
show member? 2 [1 2 3]=> trueshow member? 4 [1 2 3]=> falseshow member? "bat" "abate"=> trueshow member? turtle 0 turtles=> trueshow member? turtle 0 patches=> false
Seealsoposition.
min
minlist
Reportstheminimumnumbervalueinthelist.Itignoresothertypesofitems.
show min [xcor] of turtles;; prints the lowest x-coordinate of all the turtlesshow min list a b;; prints the smaller of the two variables a and bshow min (list a b c);; prints the smallest of the three variables a, b, and c
min-n-of
min-n-ofnumberagentset[reporter]
Reportsanagentsetcontainingnumberagentsfromagentsetwiththelowestvaluesofreporter.Theagentsetisbuiltbyfindingalltheagentswiththelowestvalueofreporter,iftherearenotnumberagentswiththatvaluethentheagentswiththesecondlowestvaluearefound,andsoon.Attheend,ifthereisatiethatwouldmaketheresultingagentsettoolarge,thetieisbrokenrandomly.
;; assume the world is 11 x 11show min-n-of 5 patches [pxcor];; shows 5 patches with pxcor = min-pxcorshow min-n-of 5 patches with [pycor = 0] [pxcor];; shows an agentset containing:;; (patch -5 0) (patch -4 0) (patch -3 0) (patch -2 0) (patch -1 0)
Seealsomin-one-of,with-min.
min-one-of
min-one-ofagentset[reporter]
Reportsarandomagentintheagentsetthatreportsthelowestvalueforthegivenreporter.Ifthereisatie,thiscommandreportsonerandomagentthatmeetsthecondition.Ifyouwantallsuchagentsusewith-mininstead.
show min-one-of turtles [xcor + ycor];; reports the first turtle with the smallest sum of;; coordinates
Seealsowith-min,min-n-of.
min-pxcormin-pycor
min-pxcormin-pycor
Thesereportersgivetheminimumx-coordinateandminimumy-coordinate,(respectively)forpatches,whichdeterminesthesizeoftheworld.
UnlikeinolderversionsofNetLogotheorigindoesnothavetobeatthecenteroftheworld.However,theminimumx-andy-coordinatesmustbelessthanorequaltozero.
Note:Youcansetthesizeoftheworldonlybyeditingtheview--thesearereporterswhichcannotbeset.
![Page 405: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/405.jpg)
Since1.0
Since2.0
Since1.0
Since3.0
Since1.0Since1.0
Since4.0
crt 100 [ setxy random-float min-pxcor random-float min-pycor ];; distributes 100 turtles randomly in the;; third quadrant
Seealsomax-pxcor,max-pycor,world-width,andworld-height
mod
number1modnumber2
Reportsnumber1modulonumber2:thatis,theresidueofnumber1(modnumber2).modisisequivalenttothefollowingNetLogocode:
number1 - (floor (number1 / number2)) * number2
Notethatmodis"infix",thatis,itcomesbetweenitstwoinputs.
show 62 mod 5=> 2show -8 mod 3=> 1
Seealsoremainder.modandremainderbehavethesameforpositivenumbers,butdifferentlyfornegativenumbers.
modes
modeslist
Reportsalistofthemostcommonitemoritemsinlist.
TheinputlistmaycontainanyNetLogovalues.
Iftheinputisanemptylist,reportsanemptylist.
show modes [1 2 2 3 4]=> [2]show modes [1 2 2 3 3 4]=> [2 3]show modes [ [1 2 [3]] [1 2 [3]] [2 3 4] ]=> [[1 2 [3]]]show modes [pxcor] of turtles;; shows which columns of patches have the most;; turtles on them
mouse-down?
mouse-down?
Reportstrueifthemousebuttonisdown,falseotherwise.
Note:Ifthemousepointerisoutsideofthecurrentview,mouse-down?willalwaysreportfalse.
mouse-inside?
mouse-inside?
Reportstrueifthemousepointerisinsidethecurrentview,falseotherwise.
mouse-xcormouse-ycor
mouse-xcormouse-ycor
Reportsthexorycoordinateofthemouseinthe2Dview.Thevalueisintermsofturtlecoordinates,soitmightnotbeaninteger.Ifyouwantpatchcoordinates,useround mouse-xcorandround mouse-ycor.
Note:Ifthemouseisoutsideofthe2Dview,reportsthevaluefromthelasttimeitwasinside.
;; to make the mouse "draw" in red:if mouse-down? [ ask patch mouse-xcor mouse-ycor [ set pcolor red ] ]
move-to
move-toagent
Theturtlesetsitsxandycoordinatestobethesameasthegivenagent's.
![Page 406: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/406.jpg)
Since4.0
Since4.0
Since4.0
Since1.0
(Ifthatagentisapatch,theeffectistomovetheturtletothecenterofthatpatch.)
move-to turtle 5;; turtle moves to same point as turtle 5move-to one-of patches;; turtle moves to the center of a random patchmove-to max-one-of turtles [size];; turtle moves to same point as biggest turtle
Notethattheturtle'sheadingisunaltered.Youmaywanttousethefacecommandfirsttoorienttheturtleinthedirectionofmotion.
Seealsosetxy.
my-<breeds>my-links
my-<breeds>my-links
Reportsanagentsetofalllinksconnectedtothecallerofthecorrespondingbreed,regardlessofdirectedness.Generally,youmightconsiderusingmy-out-linksinsteadofthisprimitive,asitworkswellforeitherdirectedorundirectednetworks(sinceitexcludesdirected,incominglinks).
crt 5ask turtle 0[ create-links-with other turtles show my-links ;; prints the agentset containing all links ;; (since all the links we created were with turtle 0 )]ask turtle 1[ show my-links ;; shows an agentset containing the link 0 1]end
Ifyouonlywanttheundirectedlinksconnectedtoanode,youcandomy-links with [ not is-directed-link? self ].
my-in-<breeds>my-in-links
my-in-<breeds>my-in-links
Reportsanagentsetofallthedirectedlinkscominginfromothernodestothecalleraswellasallundirectedlinksconnectedtothecaller.Youcanthinkofthisas"alllinksthatyoucanusetotraveltothisnode".
crt 5ask turtle 0[ create-links-to other turtles show my-in-links ;; shows an empty agentset]ask turtle 1[ show my-in-links ;; shows an agentset containing the link 0 1]
my-out-<breeds>my-out-links
my-out-<breeds>my-out-links
Reportsanagentsetofallthedirectedlinksgoingoutfromthecallertoothernodesaswellasundirectedlinksconnectedtothecaller.Youcanthinkofthisas"alllinksyoucanusetotravelfromthisnode".
crt 5ask turtle 0[ create-links-to other turtles show my-out-links ;; shows agentset containing all the links]ask turtle 1[ show my-out-links ;; shows an empty agentset]
myself
myself
"self"and"myself"areverydifferent."self"issimple;itmeans"me"."myself"means"theturtle,patchorlinkwhoaskedmetodowhatI'm
![Page 407: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/407.jpg)
Since3.1
Since2.0
Since1.1Since1.1
Since4.0
doingrightnow."
Whenanagenthasbeenaskedtorunsomecode,usingmyselfinthatcodereportstheagent(turtle,patchorlink)thatdidtheasking.
myselfismostoftenusedinconjunctionwithoftoreadorsetvariablesintheaskingagent.
myselfcanbeusedwithinblocksofcodenotjustintheaskcommand,butalsohatch,sprout,of,with,all?,with-min,with-max,min-one-of,max-one-of,min-n-of,max-n-of.
ask turtles [ ask patches in-radius 3 [ set pcolor [color] of myself ] ];; each turtle makes a colored "splotch" around itself
Seethe"MyselfExample"codeexampleformoreexamples.
Seealsoself.
N
n-of
n-ofsizeagentsetn-ofsizelist
Fromanagentset,reportsanagentsetofsizesizerandomlychosenfromtheinputset,withnorepeats.
Fromalist,reportsalistofsizesizerandomlychosenfromtheinputset,withnorepeats.Theitemsintheresultappearinthesameorderthattheyappearedintheinputlist.(Ifyouwanttheminrandomorder,useshuffleontheresult.)
Itisanerrorforsizetobegreaterthanthesizeoftheinput.
ask n-of 50 patches [ set pcolor green ];; 50 randomly chosen patches turn green
Seealsoone-of.
n-values
n-valuessizereporter
Reportsalistoflengthsizecontainingvaluescomputedbyrepeatedlyrunningthereporter.reportermaybeananonymousreporterorthenameofareporter.
Ifthereporteracceptsinputs,theinputwillbethenumberoftheitemcurrentlybeingcomputed,startingfromzero.
show n-values 5 [1]=> [1 1 1 1 1]show n-values 5 [ i -> i ]=> [0 1 2 3 4]show n-values 3 turtle=> [(turtle 0) (turtle 1) (turtle 2)]show n-values 5 [ x -> x * x ]=> [0 1 4 9 16]
Seealsoreduce,filter,->(anonymousprocedure),range.
neighborsneighbors4
neighborsneighbors4
Reportsanagentsetcontainingthe8surroundingpatches(neighbors)or4surroundingpatches(neighbors4).
show sum [count turtles-here] of neighbors ;; prints the total number of turtles on the eight ;; patches around this turtle or patchshow count turtles-on neighbors ;; a shorter way to say the same thingask neighbors4 [ set pcolor red ] ;; turns the four neighboring patches red
<breed>-neighborslink-neighbors
<breed>-neighborslink-neighbors
Reportstheagentsetofallturtlesfoundattheotherendofanylinks(undirectedordirected,incomingoroutgoing)connectedtothisturtle.
![Page 408: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/408.jpg)
Since4.0
Since3.0
Since5.2
Since3.0
Since1.0
crt 3ask turtle 0[ create-links-with other turtles ask link-neighbors [ set color red ] ;; turtles 1 and 2 turn red]ask turtle 1[ ask link-neighbors [ set color blue ] ;; turtle 0 turns blue]end
<breed>-neighbor?link-neighbor?
<breed>-neighbor?turtlelink-neighbor?turtle
Reportstrueifthereisalink(eitherdirectedorundirected,incomingoroutgoing)betweenturtleandthecaller.
crt 2ask turtle 0[ create-link-with turtle 1 show link-neighbor? turtle 1 ;; prints true]ask turtle 1[ show link-neighbor? turtle 0 ;; prints true]
netlogo-version
netlogo-version
ReportsastringcontainingtheversionnumberoftheNetLogoyouarerunning.
show netlogo-version=> "6.0.2"
netlogo-web?
netlogo-web?
ReportstrueifthemodelisrunninginNetLogoWeb.
new-seed
new-seed
Reportsanumbersuitableforseedingtherandomnumbergenerator.
Thenumbersreportedbynew-seedarebasedonthecurrentdateandtimeinmillisecondsandlieinthegenerator'susablerangeofseeds,-2147483648to2147483647.
new-seedneverreportsthesamenumbertwiceinsuccession,evenacrossparallelBehaviorSpaceruns.(Thisisaccomplishedbywaitingamillisecondiftheseedforthecurrentmillisecondwasalreadyused.)
Seealsorandom-seed.
no-display
no-display
Turnsoffallupdatestothecurrentviewuntilthedisplaycommandisissued.Thishastwomajoruses.
One,youcancontrolwhentheuserseesviewupdates.Youmightwanttochangelotsofthingsontheviewbehindtheuser'sback,sotospeak,thenmakethemvisibletotheuserallatonce.
Two,yourmodelwillrunfasterwhenviewupdatingisoff,soifyou'reinahurry,thiscommandwillletyougetresultsfaster.(Notethatnormallyyoudon'tneedtouseno-displayforthis,sinceyoucanalsousetheon/offswitchinviewcontrolstriptofreezetheview.)
Notethatdisplayandno-displayoperateindependentlyoftheswitchintheviewcontrolstripthatfreezestheview.
Seealsodisplay.
nobody
nobody
Thisisaspecialvaluewhichsomeprimitivessuchasturtle,one-of,max-one-of,etc.reporttoindicatethatnoagentwasfound.Also,whenaturtledies,itbecomesequaltonobody.
![Page 409: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/409.jpg)
Since4.0
Since4.0
Since1.0
Since4.0
Since4.0
Since1.0
Note:Emptyagentsetsarenotequaltonobody.Ifyouwanttotestforanemptyagentset,useany?.Youonlygetnobodybackinsituationswhereyouwereexpectingasingleagent,notawholeagentset.
set target one-of other turtles-hereif target != nobody [ ask target [ set color red ] ]
no-links
no-links
Reportsanemptylinkagentset.
no-patches
no-patches
Reportsanemptypatchagentset.
not
notboolean
Reportstrueifbooleanisfalse,otherwisereportsfalse.
if not any? turtles [ crt 10 ]
no-turtles
no-turtles
Reportsanemptyturtleagentset.
O
of
[reporter]ofagent[reporter]ofagentset
Foranagent,reportsthevalueofthereporterforthatagent(turtleorpatch).
show [pxcor] of patch 3 5;; prints 3show [pxcor] of one-of patches;; prints the value of a random patch's pxcor variableshow [who * who] of turtle 5=> 25show [count turtles in-radius 3] of patch 0 0;; prints the number of turtles located within a;; three-patch radius of the origin
Foranagentset,reportsalistthatcontainsthevalueofthereporterforeachagentintheagentset(inrandomorder).
crt 4show sort [who] of turtles=> [0 1 2 3]show sort [who * who] of turtles=> [0 1 4 9]
one-of
one-ofagentsetone-oflist
Fromanagentset,reportsarandomagent.Iftheagentsetisempty,reportsnobody.
Fromalist,reportsarandomlistitem.Itisanerrorforthelisttobeempty.
ask one-of patches [ set pcolor green ];; a random patch turns greenask patches with [any? turtles-here] [ show one-of turtles-here ];; for each patch containing turtles, prints one of;; those turtles
;; suppose mylist is [1 2 3 4 5 6]show one-of mylist;; prints a value randomly chosen from the list
Seealson-of.
![Page 410: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/410.jpg)
Since1.0
Since4.0
Since4.0
Since4.0
Since4.0
or
boolean1orboolean2
Reportstrueifeitherboolean1orboolean2,orboth,istrue.
Notethatifcondition1istrue,thencondition2willnotberun(sinceitcan'taffecttheresult).
if (pxcor > 0) or (pycor > 0) [ set pcolor red ];; patches turn red except in lower-left quadrant
other
otheragentset
Reportsanagentsetwhichisthesameastheinputagentsetbutomitsthisagent.
show count turtles-here=> 10show count other turtles-here=> 9
other-end
other-end
Ifrunbyaturtle,reportstheturtleattheotherendoftheaskinglink.
Ifrunbyalink,reportstheturtleattheendofthelinkthatisn'ttheaskingturtle.
Thesedefinitionsaredifficulttounderstandintheabstract,butthefollowingexamplesshouldhelp:
ask turtle 0 [ create-link-with turtle 1 ]ask turtle 0 [ ask link 0 1 [ show other-end ] ] ;; prints turtle 1ask turtle 1 [ ask link 0 1 [ show other-end ] ] ;; prints turtle 0ask link 0 1 [ ask turtle 0 [ show other-end ] ] ;; prints turtle 1
Astheseexampleshopefullymakeplain,the"other"endistheendthatisneitheraskingnorbeingasked.
out-<breed>-neighbor?out-link-neighbor?
out-<breed>-neighbor?turtleout-link-neighbor?turtle
Reportstrueifthereisadirectedlinkgoingfromthecallertoturtleorifthereisanundirectedlinkconnectingthecallerwithturtle.Youcanthinkofthisas"canIgetfromthecallertoturtleusingalink?"
crt 2ask turtle 0 [ create-link-to turtle 1 show in-link-neighbor? turtle 1 ;; prints false show out-link-neighbor? turtle 1 ;; prints true]ask turtle 1 [ show in-link-neighbor? turtle 0 ;; prints true show out-link-neighbor? turtle 0 ;; prints false]
out-<breed>-neighborsout-link-neighbors
out-<breed>-neighborsout-link-neighbors
Reportstheagentsetofalltheturtlesthathavedirectedlinksfromthecaller,orundirectedlinkswiththecaller.Youcanthinkofthisas"whocanIgettofromthecallerusingalink?"
crt 4ask turtle 0[ create-links-to other turtles ask out-link-neighbors [ set color pink ] ;; turtles 1-3 turn pink]ask turtle 1[ ask out-link-neighbors [ set color orange ] ;; no turtles change colors ;; since turtle 1 only has in-links]end
![Page 411: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/411.jpg)
Since4.0
Since2.1Since2.1Since2.1Since2.1
Since1.0
Since2.0
Since1.0
out-<breed>-toout-link-to
out-<breed>-toturtleout-link-toturtle
Reportsadirectedlinkfromthecallertoturtleoranundirectedlinkconnectingthetwo.Ifnolinkexiststhenitreportsnobody.Ifmorethanonesuchlinkexists,reportsarandomone.Youcanthinkofthisas"givemealinkthatIcanusetotravelfromthecallertoturtle."
crt 2ask turtle 0 [ create-link-to turtle 1 show out-link-to turtle 1 ;; shows link 0 1]ask turtle 1[ show out-link-to turtle 0 ;; shows nobody]
Seealso:in-link-fromlink-with
output-printoutput-showoutput-typeoutput-write
output-printvalueoutput-showvalueoutput-typevalueoutput-writevalue
Thesecommandsarethesameastheprint,show,type,andwritecommandsexceptthatvalueisprintedinthemodel'soutputarea,insteadofintheCommandCenter.(Ifthemodeldoesnothaveaseparateoutputarea,thentheCommandCenterisused.)
P
patch
patchxcorycor
Giventhexandycoordinatesofapoint,reportsthepatchcontainingthatpoint.(Thecoordinatesareabsolutecoordinates;theyarenotcomputedrelativetothisagent,aswithpatch-at.)
Ifxandyareintegers,thepointisthecenterofapatch.Ifxoryisnotaninteger,roundingtothenearestintegerisusedtodeterminewhichpatchcontainsthepoint.
Ifwrappingisallowedbythetopology,thegivencoordinateswillbewrappedtobewithintheworld.Ifwrappingisnotallowedandthegivencoordinatesareoutsidetheworld,reportsnobody.
ask patch 3 -4 [ set pcolor green ];; patch with pxcor of 3 and pycor of -4 turns greenshow patch 1.2 3.7;; prints (patch 1 4); note roundingshow patch 18 19;; supposing min-pxcor and min-pycor are -17;; and max-pxcor and max-pycor are 17,;; in a wrapping topology, prints (patch -17 -16);;; in a non-wrapping topology, prints nobody
Seealsopatch-at.
patch-ahead
patch-aheaddistance
Reportsthesinglepatchthatisthegivendistance"ahead"ofthisturtle,thatis,alongtheturtle'scurrentheading.Reportsnobodyifthepatchdoesnotexistbecauseitisoutsidetheworld.
ask patch-ahead 1 [ set pcolor green ];; turns the patch 1 in front of this turtle;; green; note that this might be the same patch;; the turtle is standing on
Seealsopatch-at,patch-left-and-ahead,patch-right-and-ahead,patch-at-heading-and-distance.
patch-at
patch-atdxdy
![Page 412: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/412.jpg)
Since2.0
Since1.0
Since2.0Since2.0
Since4.0
Since4.1
Reportsthepatchat(dx,dy)fromthecaller,thatis,thepatchcontainingthepointdxeastanddypatchesnorthofthisagent.
Reportsnobodyifthereisnosuchpatchbecausethatpointisbeyondanon-wrappingworldboundary.
ask patch-at 1 -1 [ set pcolor green ];; if caller is a turtle or patch, turns the;; patch just southeast of the caller green
Seealsopatch,patch-ahead,patch-left-and-ahead,patch-right-and-ahead,patch-at-heading-and-distance.
patch-at-heading-and-distance
patch-at-heading-and-distanceheadingdistance
patch-at-heading-and-distancereportsthesinglepatchthatisthegivendistancefromthisturtleorpatch,alongthegivenabsoluteheading.(Incontrasttopatch-left-and-aheadandpatch-right-and-ahead,thisturtle'scurrentheadingisnottakenintoaccount.)Reportsnobodyifthepatchdoesnotexistbecauseitisoutsidetheworld.
ask patch-at-heading-and-distance -90 1 [ set pcolor green ];; turns the patch 1 to the west of this patch green
Seealsopatch,patch-at,patch-left-and-ahead,patch-right-and-ahead.
patch-here
patch-here
patch-herereportsthepatchundertheturtle.
Notethatthisreporterisn'tavailabletoapatchbecauseapatchcanjustsay"self".
patch-left-and-aheadpatch-right-and-ahead
patch-left-and-aheadangledistancepatch-right-and-aheadangledistance
Reportsthesinglepatchthatisthegivendistancefromthisturtle,inthedirectionturnedleftorrightthegivenangle(indegrees)fromtheturtle'scurrentheading.Reportsnobodyifthepatchdoesnotexistbecauseitisoutsidetheworld.
(Ifyouwanttofindapatchinagivenabsoluteheading,ratherthanonerelativetothecurrentturtle'sheading,usepatch-at-heading-and-distanceinstead.)
ask patch-right-and-ahead 30 1 [ set pcolor green ];; this turtle "looks" 30 degrees right of its;; current heading at the patch 1 unit away, and turns;; that patch green; note that this might be the same;; patch the turtle is standing on
Seealsopatch,patch-at,patch-at-heading-and-distance.
patch-set
patch-setvalue1(patch-setvalue1value2...)
Reportsanagentsetcontainingallofthepatchesanywhereinanyoftheinputs.Theinputsmaybeindividualpatches,patchagentsets,nobody,orlists(ornestedlists)containinganyoftheabove.
patch-set selfpatch-set patch-here(patch-set self neighbors)(patch-set patch-here neighbors)(patch-set patch 0 0 patch 1 3 patch 4 -2)(patch-set patch-at -1 1 patch-at 0 1 patch-at 1 1)patch-set [patch-here] of turtlespatch-set [neighbors] of turtles
Seealsoturtle-set,link-set.
patch-size
patch-size
Reportsthesizeofthepatchesintheviewinpixels.Thesizeistypicallyaninteger,butmayalsobeafloatingpointnumber.
Seealsoset-patch-size.
![Page 413: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/413.jpg)
Since1.0
Since1.0Since1.0Since3.0Since3.0Since1.0Since1.0
patches
patches
Reportstheagentsetconsistingofallpatches.
patches-own
patches-own[var1...]
Thiskeyword,liketheglobals,breed,<breed>-own,andturtles-ownkeywords,canonlybeusedatthebeginningofaprogram,beforeanyfunctiondefinitions.Itdefinesthevariablesthatallpatchescanuse.
Allpatcheswillthenhavethegivenvariablesandbeabletousethem.
Allpatchvariablescanalsobedirectlyaccessedbyanyturtlestandingonthepatch.
Seealsoglobals,turtles-own,breed,<breeds>-own.
pcolor
pcolor
Thisisabuilt-inpatchvariable.Itholdsthecolorofthepatch.Youcansetthisvariabletomakethepatchchangecolor.
Allpatchvariablescanbedirectlyaccessedbyanyturtlestandingonthepatch.ColorcanberepresentedeitherasaNetLogocolor(asinglenumber)oranRGBcolor(alistof3numbers).SeedetailsintheColorssectionoftheProgrammingGuide.
Seealsocolor.
pen-downpdpen-erasepepen-uppu
pen-downpen-erasepen-up
Theturtlechangesmodesbetweendrawinglines,removinglinesorneither.Thelineswillalwaysbedisplayedontopofthepatchesandbelowtheturtles.Tochangethecolorofthepensetthecoloroftheturtleusingset color.
Note:Whenaturtle'spenisdown,allmovementcommandscauselinestobedrawn,includingjump,setxy,andmove-to.
Note:Thesecommandsareequivalenttosettingtheturtlevariable"pen-mode"to"down","up",and"erase".
Note:OnWindowsdrawinganderasingalinemightnoteraseeverypixel.
pen-mode
Thisisabuilt-inturtlevariable.Itholdsthestateoftheturtle'spen.Yousetthevariabletodrawlines,eraselinesorstopeitheroftheseactions.Possiblevaluesare"up","down",and"erase".
pen-size
Thisisabuilt-inturtlevariable.Itholdsthewidthoftheline,inpixels,thattheturtlewilldraw(orerase)whenthepenisdown(orerasing).
plabel
plabel
Thisisabuilt-inpatchvariable.Itmayholdavalueofanytype.Thepatchappearsintheviewwiththegivenvalue"attached"toitastext.Youcansetthisvariabletoadd,change,orremoveapatch'slabel.
Allpatchvariablescanbedirectlyaccessedbyanyturtlestandingonthepatch.
Seealsoplabel-color,label,label-color.
plabel-color
![Page 414: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/414.jpg)
Since1.0
Since1.0
Since4.0
Since1.0Since1.0
Since1.0
Since1.0
Since1.0Since1.0Since1.0Since1.0
Since1.0
plabel-color
Thisisabuilt-inpatchvariable.Itholdsanumbergreaterthanorequalto0andlessthan140.Thisnumberdetermineswhatcolorthepatch'slabelappearsin(ifithasalabel).Youcansetthisvariabletochangethecolorofapatch'slabel.
Allpatchvariablescanbedirectlyaccessedbyanyturtlestandingonthepatch.
Seealsoplabel,label,label-color.
plot
plotnumber
Incrementsthex-valueoftheplotpenbyplot-pen-interval,thenplotsapointattheupdatedx-valueanday-valueofnumber.(Thefirsttimethecommandisusedonaplot,thepointplottedhasanx-valueof0.)
plot-name
plot-name
Reportsthenameofthecurrentplot(astring)
plot-pen-exists?
plot-pen-exists?string
Reportstrueifaplotpenwiththegivennameisdefinedinthecurrentplot.Otherwisereportsfalse.
plot-pen-downplot-pen-up
plot-pen-downplot-pen-up
Putsdown(orup)thecurrentplot-pen,sothatitdraws(ordoesn't).(Bydefault,allpensaredowninitially.)
plot-pen-reset
plot-pen-reset
Clearseverythingthecurrentplotpenhasdrawn,movesitto(0,0),andputsitdown.Ifthepenisapermanentpen,thecolor,mode,andintervalareresettothedefaultvaluesfromtheplotEditdialog.
plotxy
plotxynumber1number2
Movesthecurrentplotpentothepointwithcoordinates(number1,number2).Ifthepenisdown,aline,bar,orpointwillbedrawn(dependingonthepen'smode).
plot-x-minplot-x-maxplot-y-minplot-y-max
plot-x-minplot-x-maxplot-y-minplot-y-max
Reportstheminimumormaximumvalueonthexoryaxisofthecurrentplot.
Thesevaluescanbesetwiththecommandsset-plot-x-rangeandset-plot-y-range.(TheirdefaultvaluesaresetfromtheplotEditdialog.)
position
positionitemlistpositionstring1string2
Onalist,reportsthefirstpositionofiteminlist,orfalseifitdoesnotappear.
Onstrings,reportsthepositionofthefirstappearancestring1asasubstringofstring2,orfalseifitdoesnotappear.
Note:Thepositionsarenumberedbeginningwith0,notwith1.
;; suppose mylist is [2 7 4 7 "Bob"]
![Page 415: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/415.jpg)
Since1.0
Since1.0
Since1.0
Since2.0
show position 7 mylist=> 1show position 10 mylist=> falseshow position "in" "string"=> 3
Seealsomember?.
precision
precisionnumberplaces
Reportsnumberroundedtoplacesdecimalplaces.
Ifplacesisnegative,theroundingtakesplacetotheleftofthedecimalpoint.
show precision 1.23456789 3=> 1.235show precision 3834 -3=> 4000
Seealsoround,ceiling,floor.
printvalue
PrintsvalueintheCommandCenter,followedbyacarriagereturn.
Thisagentisnotprintedbeforethevalue,unlikeshow.
Seealsoshow,type,andwrite.
Seealsooutput-print.
pxcorpycor
pxcorpycor
Thesearebuilt-inpatchvariables.Theyholdthexandycoordinateofthepatch.Theyarealwaysintegers.Youcannotsetthesevariables,becausepatchesdon'tmove.
pxcorisgreaterthanorequaltomin-pxcorandlessthanorequaltomax-pxcor;similarlyforpycorandmin-pycorandmax-pycor.
Allpatchvariablescanbedirectlyaccessedbyanyturtlestandingonthepatch.
Seealsoxcor,ycor.
R
random
randomnumber
Ifnumberispositive,reportsarandomintegergreaterthanorequalto0,butstrictlylessthannumber.
Ifnumberisnegative,reportsarandomintegerlessthanorequalto0,butstrictlygreaterthannumber.
Ifnumberiszero,theresultisalways0aswell.
Note:InversionsofNetLogopriortoversion2.0,thisprimitivereportedafloatingpointnumberifgivenanon-integerinput.Thisisnolongerthecase.Ifyouwantafloatingpointanswer,youmustnowuserandom-floatinstead.
show random 3;; prints 0, 1, or 2show random -3;; prints 0, -1, or -2show random 3.5;; prints 0, 1, 2, or 3
Seealsorandom-float.
random-float
random-floatnumber
Ifnumberispositive,reportsarandomfloatingpointnumbergreaterthanorequalto0butstrictlylessthannumber.
Ifnumberisnegative,reportsarandomfloatingpointnumberlessthanorequalto0,butstrictlygreaterthannumber.
![Page 416: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/416.jpg)
Since1.2.1Since2.0
Since1.2.1Since1.2.1
Since3.1Since3.1
Since1.0
Since3.1Since3.1
Ifnumberiszero,theresultisalways0.
show random-float 3;; prints a number at least 0 but less than 3,;; for example 2.589444906014774show random-float 2.5;; prints a number at least 0 but less than 2.5,;; for example 1.0897423196760796
random-exponentialrandom-gammarandom-normalrandom-poisson
random-exponentialmeanrandom-gammaalphalambdarandom-normalmeanstandard-deviationrandom-poissonmean
Reportsanaccordinglydistributedrandomnumberwiththemeanand,inthecaseofthenormaldistribution,thestandard-deviation.(Thestandarddeviationmaynotbenegative.)
random-exponentialreportsanexponentiallydistributedrandomfloatingpointnumber.Itisequivalentto(- mean) * ln random-float 1.0.
random-gammareportsagamma-distributedrandomfloatingpointnumberascontrolledbythefloatingpointalphaandlambdaparameters.Bothinputsmustbegreaterthanzero.(Note:forresultswithagivenmeanandvariance,useinputsasfollows:alpha=mean*mean/variance;lambda=1/(variance/mean).)
random-normalreportsanormallydistributedrandomfloatingpointnumber.
random-poissonreportsaPoisson-distributedrandominteger.
show random-exponential 2;; prints an exponentially distributed random floating;; point number with a mean of 2show random-normal 10.1 5.2;; prints a normally distributed random floating point;; number with a mean of 10.1 and a standard deviation;; of 5.2show random-poisson 3.4;; prints a Poisson-distributed random integer with a;; mean of 3.4
random-pxcorrandom-pycor
random-pxcorrandom-pycor
Reportsarandomintegerrangingfrommin-pxcor(or-y)tomax-pxcor(or-y)inclusive.
ask turtles [ ;; move each turtle to the center of a random patch setxy random-pxcor random-pycor]
Seealsorandom-xcor,random-ycor.
random-seed
random-seednumber
Setstheseedofthepseudo-randomnumbergeneratortotheintegerpartofnumber.Theseedmustbeintherange-2147483648to2147483647;notethatthisissmallerthanthefullrangeofintegerssupportedbyNetLogo(-9007199254740992to9007199254740992).
SeetheRandomNumberssectionoftheProgrammingGuideformoredetails.
random-seed 47822show random 100=> 50show random 100=> 35random-seed 47822show random 100=> 50show random 100=> 35
random-xcorrandom-ycor
random-xcorrandom-ycor
Reportsarandomfloatingpointnumberfromtheallowablerangeofturtlecoordinatesalongthegivenaxis,xory.
![Page 417: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/417.jpg)
Since6.0
Since1.1
Since1.3
Turtlecoordinatesrangefrommin-pxcor-0.5(inclusive)tomax-pxcor+0.5(exclusive)horizontally;vertically,substitute-yfor-x.
ask turtles [ ;; move each turtle to a random point setxy random-xcor random-ycor]
Seealsorandom-pxcor,random-pycor.
range
rangestop(rangestartstop)(rangestartstopstep)
Generatesalistofnumbers,startingatstart,endingbeforestop,countingbystep.startdefaultsto0andstepdefaultsto1.
show range 5=> [0 1 2 3 4]show (range 2 5)=> [2 3 4]show (range 2 5 0.5)=> [2 2.5 3 3.5 4 4.5]show (range 10 0 -1)=> [10 9 8 7 6 5 4 3 2 1]
Seealson-values
read-from-string
read-from-stringstring
InterpretsthegivenstringasifithadbeentypedintheCommandCenter,andreportstheresultingvalue.Theresultmaybeanumber,list,string,orbooleanvalue,orthespecialvalue"nobody".
Usefulinconjunctionwiththeuser-inputprimitiveforconvertingtheuser'sinputintousableform.
show read-from-string "3" + read-from-string "5"=> 8show length read-from-string "[1 2 3]"=> 3crt read-from-string user-input "Make how many turtles?";; the number of turtles input by the user;; are created
reduce
reducereporterlist
Reducesalistfromlefttorightusingthegivenreporter,resultinginasinglevalue.Thismeans,forexample,thatreduce [ [a b] -> a + b][1 2 3 4]isequivalentto(((1+2)+3)+4).Iflisthasasingleitem,thatitemisreported.Itisanerrortoreduceanemptylist.reportermaybeananonymousreporterorthenameofareporter.
Thefirstinputpassedtothereporteristheresultsofar,andthesecondinputisthenextiteminthelist.
Sinceitcanbedifficulttodevelopanintuitionaboutwhatreducedoes,herearesomesimpleexampleswhich,whilenotusefulinthemselves,maygiveyouabetterunderstandingofthisprimitive:
show reduce + [1 2 3]=> 6show reduce - [1 2 3]=> -4show reduce [ [result-so-far next-item] -> next-item - result-so-far ] [1 2 3]=> 2show reduce [ [result-so-far ignored-item] -> result-so-far ] [1 2 3]=> 1show reduce [ [ignored next-item] -> next-item ] [1 2 3]=> 3show reduce sentence [[1 2] [3 [4]] 5]=> [1 2 3 [4] 5]show reduce [ [result-so-far next-item] -> fput next-item result-so-far ] (fput [] [1 2 3 4 5])=> [5 4 3 2 1]
Herearesomemoreusefulexamples:
;; find the longest string in a listto-report longest-string [strings] report reduce [ [longest-so-far next-string] -> ifelse-value (length longest-so-far >= length next-string) [longest-so-far] [next-string] ] stringsend
show longest-string ["hi" "there" "!"]=> "there"
;; count the number of occurrences of an item in a listto-report occurrences [x the-list] report reduce [ [occurrence-count next-item] -> ifelse-value (next-item = x) [occurrence-count + 1] [occurrence-count] ] (fput 0 the-list)end
show occurrences 1 [1 2 1 3 1 2 3 1 1 4 5 1]
![Page 418: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/418.jpg)
Since1.2.1
Since1.0
Since1.0
Since2.0
Since1.0
Since1.0
=> 6
;; evaluate the polynomial, with given coefficients, at xto-report evaluate-polynomial [coefficients x] report reduce [ [value coefficient] -> (x * value) + coefficient ] coefficientsend
;; evaluate 3x^2 + 2x + 1 at x = 4show evaluate-polynomial [3 2 1] 4=> 57
Seealsofilter,->(anonymousprocedure.
remainder
remaindernumber1number2
Reportstheremainderwhennumber1isdividedbynumber2.ThisisequivalenttothefollowingNetLogocode:
number1 - (int (number1 / number2)) * number2
show remainder 62 5=> 2show remainder -8 3=> -2
Seealsomod.modandremainderbehavethesameforpositivenumbers,butdifferentlyfornegativenumbers.
remove
removeitemlistremovestring1string2
Foralist,reportsacopyoflistwithallinstancesofitemremoved.
Forstrings,reportsacopyofstring2withalltheappearancesofstring1asasubstringremoved.
set mylist [2 7 4 7 "Bob"]set mylist remove 7 mylist;; mylist is now [2 4 "Bob"]show remove "to" "phototonic"=> "phonic"
remove-duplicates
remove-duplicateslist
Reportsacopyoflistwithallduplicateitemsremoved.Thefirstofeachitemremainsinplace.
set mylist [2 7 4 7 "Bob" 7]set mylist remove-duplicates mylist;; mylist is now [2 7 4 "Bob"]
remove-item
remove-itemindexlistremove-itemindexstring
Foralist,reportsacopyoflistwiththeitematthegivenindexremoved.
Forstrings,reportsacopyofstringwiththecharacteratthegivenindexremoved.
Notethattheindicesbeginfrom0,not1.(Thefirstitemisitem0,theseconditemisitem1,andsoon.)
set mylist [2 7 4 7 "Bob"]set mylist remove-item 2 mylist;; mylist is now [2 7 7 "Bob"]show remove-item 2 "string"=> "sting"
repeat
repeatnumber[commands]
Runscommandsnumbertimes.
pd repeat 36 [ fd 1 rt 10 ] ;; the turtle draws a circle
replace-item
![Page 419: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/419.jpg)
Since1.0
Since3.0Since3.0
Since4.0
Since1.0
Since4.1
Since1.0
Since1.0
replace-itemindexlistvaluereplace-itemindexstring1string2
Onalist,replacesaniteminthatlist.indexistheindexoftheitemtobereplaced,startingwith0.(The6thiteminalistwouldhaveanindexof5.)Notethat"replace-item"isusedinconjunctionwith"set"tochangealist.
Likewiseforastring,butthegivencharacterofstring1removedandthecontentsofstring2splicedininstead.
show replace-item 2 [2 7 4 5] 15=> [2 7 15 5]show replace-item 1 "cat" "are"=> "caret"
report
reportvalue
Immediatelyexitsfromthecurrentto-reportprocedureandreportsvalueastheresultofthatprocedure.reportandto-reportarealwaysusedinconjunctionwitheachother.Seeto-reportforadiscussionofhowtousethem.
reset-perspectiverp
reset-perspective
Theobserverstopswatching,following,orridinganyturtles(orpatches).(Ifitwasn'twatching,following,orridinganybody,nothinghappens.)Inthe3Dview,theobserveralsoreturnstoitsdefaultposition(abovetheorigin,lookingstraightdown).
Seealsofollow,ride,watch.
reset-ticks
reset-ticks
Resetsthetickcountertozero,setsupallplots,thenupdatesallplots(sothattheinitialstateoftheworldisplotted).
Normallyreset-ticksgoesattheendofasetupprocedure.
Seealsoclear-ticks,tick,ticks,tick-advance,setup-plots,update-plots.
reset-timer
reset-timer
Resetsthetimertozeroseconds.Seealsotimer.
Notethatthetimerisdifferentfromthetickcounter.Thetimermeasureselapsedrealtimeinseconds;thetickcountermeasureselapsedmodeltimeinticks.
resize-world
resize-worldmin-pxcormax-pxcormin-pycormax-pycor
Changesthesizeofthepatchgrid.
Asasideeffect,allturtlesandlinksdie,andtheexistingpatchgridisdiscardedandnewpatchescreated.
Retainingreferencestooldpatchesorpatchsetsisinadvisableandmaysubsequentlycauseruntimeerrorsorotherunexpectedbehavior.
Seealsoset-patch-size.
reverse
reverselistreversestring
Reportsareversedcopyofthegivenlistorstring.
show mylist;; mylist is [2 7 4 "Bob"]set mylist reverse mylist;; mylist now is ["Bob" 4 7 2]show reverse "live"=> "evil"
rgb
rgbredgreenblue
![Page 420: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/420.jpg)
Since3.0
Since3.0
Since1.0Since1.0
Since1.0
Since1.3Since1.3
ReportsaRGBlistwhengiventhreenumbersdescribinganRGBcolor.Thenumbersarerangecheckedtobebetween0and255.
Seealsohsb
ride
rideturtle
Settheperspectivetoturtle.
Everytimeturtlemovestheobserveralsomoves.Thus,inthe2DViewtheturtlewillstayatthecenteroftheview.Inthe3Dviewitisasiflookingthroughtheeyesoftheturtle.Iftheturtledies,theperspectiveresetstothedefault.
Theobservermayonlywatchorfollowasinglesubject.Callingridewillremovethehighlightcreatedbypriorcallstowatchandwatch-me,highlightingtheriddenturtleinstead.
Seealsoreset-perspective,watch,follow,subject.
ride-me
ride-me
Askstheobservertoridethisturtle.
Theobservermayonlywatchorfollowasinglesubject.Callingride-mewillremovethehighlightcreatedbypriorcallstowatchandwatch-me,highlightingthisturtleinstead.
Seealsoride.
rightrt
rightnumber
Theturtleturnsrightbynumberdegrees.(Ifnumberisnegative,itturnsleft.)
round
roundnumber
Reportstheintegernearesttonumber.
Ifthedecimalportionofnumberisexactly.5,thenumberisroundedinthepositivedirection.
Notethatroundinginthepositivedirectionisnotalwayshowroundingisdoneinothersoftwareprograms.(Inparticular,itdoesnotmatchthebehaviorofStarLogoT,whichalwaysroundednumbersendingin0.5tothenearesteveninteger.)TherationaleforthisbehavioristhatitmatcheshowturtlecoordinatesrelatetopatchcoordinatesinNetLogo.Forexample,ifaturtle'sxcoris-4.5,thenitisontheboundarybetweenapatchwhosepxcoris-4andapatchwhosepxcoris-5,buttheturtlemustbeconsideredtobeinonepatchortheother,sotheturtleisconsideredtobeinthepatchwhosepxcoris-4,becauseweroundtowardsthepositivenumbers.
show round 4.2=> 4show round 4.5=> 5show round -4.5=> -4
Seealsoprecision,ceiling,floor.
runrunresult
runcommand(runcommandinput1...)runstringrunresultreporter(runresultreporterinput1...)runresultstring
Therunformexpectsthenameofacommand,ananonymouscommand,orastringcontainingcommands.Thisagentthenrunsthem.
Therunresultformexpectsthenameofareporter,ananonymousreporter,orastringcontainingareporter.Thisagentrunsitandreportstheresult.
Notethatyoucan'tuseruntodefineorredefineprocedures.Ifyoucareaboutperformance,notethatthecodemustbecompiledfirstwhichtakestime.However,compiledbitsofcodearecachedbyNetLogoandthususingrunonthesamestringoverandoverismuchfasterthanrunningdifferentstrings.Thefirstrun,though,willbemanytimesslowerthanrunningthesamecodedirectly,orinananonymouscommand.
![Page 421: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/421.jpg)
Since1.0
Since1.3
Since1.0Since1.0
Since1.0
Anonymousproceduresarerecommendedoverstringswheneverpossible.(Anexampleofwhenyoumustusestringsisifyouacceptpiecesofcodefromtheuserofyourmodel.)
Anonymousproceduresmayfreelyreadand/orsetlocalvariablesandprocedureinputs.Tryingtodothesamewithstringsmayormaynotworkandshouldnotbereliedon.
Whenusinganonymousprocedures,youcanprovidethemwithinputs,ifyousurroundtheentirecallwithparentheses.Forexample:
(run [ [turtle-count step-count] -> crt turtle-count [ fd step-count ] ] 10 5);; creates 10 turtles and move them forward 5 stepsshow (runresult [ [a b] -> a + b ] 10 5)=> 15;; adds 10 and 5
Seealsoforeach,->(anonymousprocedure).
S
scale-color
scale-colorcolornumberrange1range2
Reportsashadeofcolorproportionaltothevalueofnumber.
Ifrange1islessthanrange2,thenthelargerthenumber,thelightertheshadeofcolor.Butifrange2islessthanrange1,thecolorscalingisinverted.
Ifnumberislessthanrange1,thenthedarkestshadeofcolorischosen.
Ifnumberisgreaterthanrange2,thenthelightestshadeofcolorischosen.
Note:forcolorshadeisirrelevant,e.g.greenandgreen+2areequivalent,andthesamespectrumofcolorswillbeused.
ask turtles [ set color scale-color red age 0 50 ];; colors each turtle a shade of red proportional;; to its value for the age variable
self
self
Reportsthisturtle,patch,orlink.
"self"and"myself"areverydifferent."self"issimple;itmeans"me"."myself"means"theagentwhoaskedmetodowhatI'mdoingrightnow."
Notethatitisalwaysredundanttowrite[foo] of self.Thisisalwaysequivalenttosimplywritingfoo.
Seealsomyself.
;(semicolon)
;comments
Afterasemicolon,therestofthelineisignored.Thisisusefulforadding"comments"toyourcode--textthatexplainsthecodetohumanreaders.Extrasemicolonscanbeaddedforvisualeffect.
NetLogo'sEditmenuhasitemsthatletyoucommentoruncommentwholesectionsofcode.
sentencese
sentencevalue1value2(sentencevalue1...)
Makesalistoutofthevalues.Ifanyvalueisalist,itsitemsareincludedintheresultdirectly,ratherthanbeingincludedasasublist.Examplesmakethisclearer:
show sentence 1 2=> [1 2]show sentence [1 2] 3=> [1 2 3]show sentence 1 [2 3]=> [1 2 3]show sentence [1 2] [3 4]=> [1 2 3 4]show sentence [[1 2]] [[3 4]]=> [[1 2] [3 4]]show (sentence [1 2] 3 [4 5] (3 + 3) 7)=> [1 2 3 4 5 6 7]
set
![Page 422: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/422.jpg)
Since2.0
Since1.0
Since1.0
Since1.0
Since1.0
setvariablevalue
Setsvariabletothegivenvalue.
Variablecanbeanyofthefollowing:
Aglobalvariabledeclaredusing"globals"Theglobalvariableassociatedwithaslider,switch,chooser,orinputbox.AvariablebelongingtothisagentIfthisagentisaturtle,avariablebelongingtothepatchundertheturtle.Alocalvariablecreatedbytheletcommand.Aninputtothecurrentprocedure.
set-current-directory
set-current-directorystring
Setsthecurrentdirectorythatisusedbytheprimitivesfile-delete,file-exists?,andfile-open.
Thecurrentdirectoryisnotusediftheabovecommandsaregivenanabsolutefilepath.Thisisdefaultedtotheuser'shomedirectoryfornewmodels,andischangedtothemodel'sdirectorywhenamodelisopened.
NotethatinWindowsfilepathsthebackslashneedstobeescapedwithinastringbyusinganotherbackslash"C:\\"
Thechangeistemporaryandisnotsavedwiththemodel.
set-current-directory "C:\\NetLogo";; Assume it is a Windows Machinefile-open "my-file.txt";; Opens file "C:\\NetLogo\\my-file.txt"
set-current-plot
set-current-plotplotname
Setsthecurrentplottotheplotwiththegivenname(astring).Subsequentplottingcommandswillaffectthecurrentplot.
set-current-plot-pen
set-current-plot-penpenname
Thecurrentplot'scurrentpenissettothepennamedpenname(astring).Ifnosuchpenexistsinthecurrentplot,aruntimeerroroccurs.
set-default-shape
set-default-shapeturtlesstringset-default-shapelinksstringset-default-shapebreedstring
Specifiesadefaultinitialshapeforallturtlesorlinks,orforaparticularbreedofturtlesorlinks.Whenaturtleorlinkiscreated,oritchangesbreeds,itshapeissettothegivenshape.
Thiscommanddoesn'taffectexistingagents,onlyagentsyoucreateafterwards.
Thegivenbreedmustbeeitherturtles,links,orthenameofabreed.Thegivenstringmustbethenameofacurrentlydefinedshape.
Innewmodels,thedefaultshapeforallturtlesis"default".
Notethatspecifyingadefaultshapedoesnotpreventyoufromchanginganagent'sshapelater.Agentsdon'thavetobestuckwiththeirbreed'sdefaultshape.
create-turtles 1 ;; new turtle's shape is "default"create-cats 1 ;; new turtle's shape is "default"
set-default-shape turtles "circle"create-turtles 1 ;; new turtle's shape is "circle"create-cats 1 ;; new turtle's shape is "circle"
set-default-shape cats "cat"set-default-shape dogs "dog"create-cats 1 ;; new turtle's shape is "cat"ask cats [ set breed dogs ] ;; all cats become dogs, and automatically ;; change their shape to "dog"
Seealsoshape.
set-histogram-num-bars
set-histogram-num-barsnumber
Setthecurrentplotpen'splotintervalsothat,giventhecurrentxrangefortheplot,therewouldbenumbernumberofbarsdrawnifthehistogramcommandiscalled.
![Page 423: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/423.jpg)
Since4.1
Since6.0.2
Since1.0
Since1.0
Since1.0
Since5.0
Since1.0Since1.0
Seealsohistogram.
__set-line-thickness
__set-line-thicknessnumber
Specifiesthethicknessoflinesandoutlinedelementsintheturtle'sshape.
Thedefaultvalueis0.Thisalwaysproduceslinesonepixelthick.
Non-zerovaluesareinterpretedasthicknessinpatches.Athicknessof1,forexample,produceslineswhichappearonepatchthick.(It'scommontouseasmallervaluesuchas0.5or0.2.)
Linesarealwaysatleastonepixelthick.
Thiscommandisexperimentalandmaychangeinlaterreleases.
set-patch-size
set-patch-sizesize
Setsthesizeofthepatchesoftheviewinpixels.Thesizeistypicallyaninteger,butmayalsobeafloatingpointnumber.
Seealsopatch-size,resize-world.
set-plot-background-color
set-plot-background-colorcolor
Setsthebackgroundcolorofthecurrentplot.Thecolormaybespecifiedasanumberoralist.SeetheColorssectionoftheprogrammingguideformoredetails.Thischangeistemporaryandisnotsavedwiththemodel.Whentheplotiscleared,thebackgroundcolorwillreverttowhite.
Note:Plotbackgroundsdonotsupporttransparency.Ifalistisusedtosetthecolor,thealphacomponentwillbeignored.
set-plot-pen-color
set-plot-pen-colorcolor
Setsthecolorofthecurrentplotpentocolor.
set-plot-pen-interval
set-plot-pen-intervalnumber
Tellsthecurrentplotpentomoveadistanceofnumberinthexdirectionduringeachuseoftheplotcommand.(Theplotpenintervalalsoaffectsthebehaviorofthehistogramcommand.)
set-plot-pen-mode
set-plot-pen-modenumber
Setsthemodethecurrentplotpendrawsintonumber.Theallowedplotpenmodesare:
0(linemode)theplotpendrawsalineconnectingtwopointstogether.1(barmode):theplotpendrawsabarofwidthplot-pen-intervalwiththepointplottedastheupper(orlower,ifyouareplottinganegativenumber)leftcornerofthebar.2(pointmode):theplotpendrawsapointatthepointplotted.Pointsarenotconnected.
Thedefaultmodefornewpensis0(linemode).
setup-plots
setup-plots
Foreachplot,runsthatplot'ssetupcommands,includingthesetupcodeforanypensintheplot.
reset-tickshasthesameeffect,soinmodelsthatusethetickcounter,thisprimitiveisnotnormallyused.
SeethePlottingsectionoftheProgrammingGuideformoredetails.
Seealsoupdate-plots.
set-plot-x-rangeset-plot-y-range
set-plot-x-rangeminmax
![Page 424: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/424.jpg)
Since1.0
Since1.0
Since2.1
Since1.0
set-plot-y-rangeminmax
Setstheminimumandmaximumvaluesofthexoryaxisofthecurrentplot.
Thechangeistemporaryandisnotsavedwiththemodel.Whentheplotiscleared,therangeswillreverttotheirdefaultvaluesassetintheplot'sEditdialog.
setxy
setxyxy
Theturtlesetsitsx-coordinatetoxanditsy-coordinatetoy.
Equivalenttoset xcor x set ycor y,exceptithappensinonetimestepinsteadoftwo.
Ifxoryisoutsidetheworld,NetLogowillthrowaruntimeerror,unlesswrappingisturnedonintherelevantdimensions.Forexample,withwrappingturnedoninbothdimensionsandthedefaultworldsizewheremin-pxcor = -16,max-pxcor = 16,min-pycor = -16andmax-pycor =16,askingaturtletosetxy 17 17willmoveittothecenterofpatch(-16,-16).
setxy 0 0;; turtle moves to the middle of the center patchsetxy random-xcor random-ycor;; turtle moves to a random pointsetxy random-pxcor random-pycor;; turtle moves to the center of a random patch
Seealsomove-to.
shade-of?
shade-of?color1color2
Reportstrueifbothcolorsareshadesofoneanother,falseotherwise.
show shade-of? blue red=> falseshow shade-of? blue (blue + 1)=> trueshow shade-of? gray white=> true
shape
shape
Thisisabuilt-inturtleandlinkvariable.Itholdsastringthatisthenameoftheturtleorlink'scurrentshape.Youcansetthisvariabletochangetheshape.Newturtlesandlinkshavetheshape"default"unlesstheadifferentshapehasbeenspecifiedusingset-default-shape.
Example:
ask turtles [ set shape "wolf" ];; assumes you have made a "wolf";; shape in NetLogo's Turtle Shapes Editorask links [ set shape "link 1" ];; assumes you have made a "link 1" shape in;; the Link Shapes Editor
Seealsoset-default-shape,shapes.
shapes
shapes
Reportsalistofstringscontainingalloftheturtleshapesinthemodel.
Newshapescanbecreated,orimportedfromtheshapeslibraryorfromothermodels,intheShapesEditor.
show shapes=> ["default" "airplane" "arrow" "box" "bug" ...ask turtles [ set shape one-of shapes ]
show
showvalue
PrintsvalueintheCommandCenter,precededbythisagent,andfollowedbyacarriagereturn.(Thisagentisincludedtohelpyoukeeptrackofwhatagentsareproducingwhichlinesofoutput.)Also,allstringshavetheirquotesincludedsimilartowrite.
Seealsoprint,type,andwrite.
![Page 425: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/425.jpg)
Since1.0Since1.0
Since4.0
Since2.0
Since1.0
Since1.0
Seealsooutput-show.
show-turtlest
show-turtle
Theturtlebecomesvisibleagain.
Note:Thiscommandisequivalenttosettingtheturtlevariable"hidden?"tofalse.
Seealsohide-turtle.
show-link
show-link
Thelinkbecomesvisibleagain.
Note:Thiscommandisequivalenttosettingthelinkvariable"hidden?"tofalse.
Seealsohide-link.
shuffle
shufflelist
Reportsanewlistcontainingthesameitemsastheinputlist,butinrandomizedorder.
show shuffle [1 2 3 4 5]=> [5 2 4 1 3]show shuffle [1 2 3 4 5]=> [1 3 5 2 4]
sin
sinnumber
Reportsthesineofthegivenangle.Assumesangleisgivenindegrees.
show sin 270=> -1
size
size
Thisisabuilt-inturtlevariable.Itholdsanumberthatistheturtle'sapparentsize.Thedefaultsizeis1,whichmeansthattheturtleisthesamesizeasapatch.Youcansetthisvariabletochangeaturtle'ssize.
sort
sortlistsortagentset
Reportsasortedlistofnumbers,strings,oragents.
Iftheinputcontainsnonumbers,strings,oragents,theresultistheemptylist.
Iftheinputcontainsatleastonenumber,thenumbersinthelistaresortedinascendingorderandanewlistreported;non-numbersareignored.
Or,iftheinputcontainsatleastonestring,thestringsinthelistaresortedinascendingorderandanewlistreported;non-stringsareignored.
Or,iftheinputisanagentsetoralistcontainingatleastoneagent,asortedlistofagents(neveranagentset)isreported;non-agentsareignored.Agentsaresortedinthesameorderthe<operatoruses.(Patchesaresortedwiththetopleft-mostpatchfirstandthebottomright-mostpatchlast,turtlesaresortedbywhonumber).
show sort [3 1 4 2]=> [1 2 3 4]show sort [2 1 "a"]=> [1 2]show sort (list "a" "c" "b" (patch 0 0))=> ["a" "b" "c"]show sort (list (patch 0 0) (patch 0 1) (patch 1 0))=> [(patch 0 1) (patch 0 0) (patch 1 0)]
;; label patches with numbers in left-to-right, top-to-bottom order
![Page 426: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/426.jpg)
Since1.3
Since5.0
Since1.0
Since1.0
let n 0foreach sort patches [ the-patch -> ask the-patch [ set plabel n set n n + 1 ]]
;; some additional examples to clarify behavior in strange casesshow sort (list patch 0 0 patch 0 1 patch 1 0 turtle 0 turtle 1) ; turtles are always sorted lower than patches=> [(turtle 0) (turtle 1) (patch 0 1) (patch 0 0) (patch 1 0)]show sort (list nobody false true) ; booleans and nobody cannot be sorted=> []show sort (list [1 2 3] turtles) ; lists and agentsets are not included if they are inside a list passed to sort=> []
Seealsosort-by,sort-on.
sort-by
sort-byreporterlistsort-byreporteragentset
Iftheinputisalist,reportsanewlistcontainingthesameitemsastheinputlist,inasortedorderdefinedbythebooleanreporter.reportermaybeananonymousreporterorthenameofareporter.
Thetwoinputstoreporterarethevaluesbeingcompared.Thereportershouldreporttrueifthefirstargumentcomesstrictlybeforethesecondinthedesiredsortorder,andfalseotherwise.
Iftheinputisanagentsetoralistofagents,reportsalist(neveranagentset)ofagents.
Iftheinputisalist,thesortisstable,thatis,theorderofitemsconsideredequalbythereporterisnotdisturbed.Iftheinputisanagentset,tiesarebrokenrandomly.
show sort-by < [3 1 4 2]=> [1 2 3 4]show sort-by > [3 1 4 2]=> [4 3 2 1]show sort-by [ [string1 string2] -> length string1 < length string2 ] ["Grumpy" "Doc" "Happy"]=> ["Doc" "Happy" "Grumpy"]
Seealsosort,sort-on,->(anonymousprocedure).
sort-on
sort-on[reporter]agentset
Reportsalistofagents,sortedaccordingtoeachagent'svalueforreporter.Tiesarebrokenrandomly.
Thevaluesmustbeallnumbers,allstrings,orallagentsofthesametype.
crt 3show sort-on [who] turtles=> [(turtle 0) (turtle 1) (turtle 2)]show sort-on [(- who)] turtles=> [(turtle 2) (turtle 1) (turtle 0)]foreach sort-on [size] turtles [ the-turtle -> ask the-turtle [ do-something ] ];; turtles run "do-something" one at a time, in;; ascending order by size
Seealsosort,sort-by.
sprout
sproutnumber[commands]sprout-<breeds>number[commands]
Createsnumbernewturtlesonthecurrentpatch.Thenewturtleshaverandomintegerheadingsandthecolorisrandomlyselectedfromthe14primarycolors.Theturtlesimmediatelyruncommands.Thisisusefulforgivingthenewturtlesdifferentcolors,headings,orwhatever.(Thenewturtlesarecreatedallatoncethenrunoneatatime,inrandomorder.)
Ifthesprout-<breeds>formisused,thenewturtlesarecreatedasmembersofthegivenbreed.
sprout 5sprout-wolves 10sprout 1 [ set color red ]sprout-sheep 1 [ set color black ]
Seealsocreate-turtles,hatch.
sqrt
sqrtnumber
Reportsthesquarerootofnumber.
![Page 427: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/427.jpg)
Since1.0
Since3.1
Since1.0
Since1.0
Since5.2
Since5.2
stamp
stamp
Thisturtleorlinkleavesanimageofitsshapeinthedrawingatitscurrentlocation.
Note:Theshapesmadebystampmaynotbepixel-for-pixelidenticalfromcomputertocomputer.
stamp-erase
stamp-erase
Thisturtleorlinkremovesanypixelsbelowitinthedrawinginsidetheboundsofitsshape.
Note:Theshapesmadebystamp-erasemaynotbepixel-for-pixelidenticalfromcomputertocomputer.
standard-deviation
standard-deviationlist
Reportsthesamplestandarddeviationofalistofnumbers.Ignoresothertypesofitems.
(Notethatthisestimatesthestandarddeviationforasample,ratherthanforawholepopulation,usingBessel'scorrection.)
show standard-deviation [1 2 3 4 5 6]=> 1.8708286933869707show standard-deviation [energy] of turtles;; prints the standard deviation of the variable "energy";; from all the turtles
startup
startup
User-definedprocedurewhich,ifitexists,willbecalledwhenamodelisfirstloadedintheNetLogoapplication.
to startup setupend
startupdoesnotrunwhenamodelisrunheadlessfromthecommandline,orbyparallelBehaviorSpace.
stop
stop
Thisagentexitsimmediatelyfromtheenclosingprocedure,ask,orask-likeconstruct(e.g.crt,hatch,sprout).Onlytheenclosingprocedureorconstructstops,notallexecutionfortheagent.
if not any? turtles [ stop ];; exits if there are no more turtles
Note:stopcanalsobeusedtostopaforeverbutton.SeeButtonsintheProgrammingGuidefordetails.
stopcanalsobeusedtostopaBehaviorSpacemodelrun.Ifthegocommandsdirectlycallaprocedure,thenwhenthatprocedurecallsstop,therunends.
stop-inspecting
stop-inspectingagent
Closestheagentmonitorforthegivenagent(turtleorpatch).Inthecasethatnoagentmonitorisopen,stop-inspectingdoesnothing.
stop-inspecting patch 2 4;; the agent monitor for that patch closesask sheep [ stop-inspecting self ];; close all agent monitors for sheep
Seeinspectandstop-inspecting-dead-agents.
stop-inspecting-dead-agents
stop-inspecting-dead-agents
Closesallagentmonitorsfordeadagents.Seeinspectandstop-inspecting.
![Page 428: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/428.jpg)
Since3.0
Since2.1Since1.0
Since2.1
Since1.0
Since1.0
Since4.0
subject
subject
Reportstheturtle(orpatch)thattheobserveriscurrentlywatching,following,orriding.Reportsnobodyifthereisnosuchturtle(orpatch).
Seealsowatch,follow,ride.
sublistsubstring
sublistlistposition1position2substringstringposition1position2
Reportsjustasectionofthegivenlistorstring,rangingbetweenthefirstposition(inclusive)andthesecondposition(exclusive).
Note:Thepositionsarenumberedbeginningwith0,notwith1.
show sublist [99 88 77 66] 1 3=> [88 77]show substring "apartment" 1 5=> "part"
subtract-headings
subtract-headingsheading1heading2
Computesthedifferencebetweenthegivenheadings,thatis,thenumberofdegreesinthesmallestanglebywhichheading2couldberotatedtoproduceheading1.Apositiveanswermeansaclockwiserotation,anegativeanswercounterclockwise.Theresultisalwaysintherange-180to180,butisneverexactly-180.
Notethatsimplysubtractingthetwoheadingsusingthe-(minus)operatorwouldn'twork.Justsubtractingcorrespondstoalwaysrotatingclockwisefromheading2toheading1;butsometimesthecounterclockwiserotationisshorter.Forexample,thedifferencebetween5degreesand355degreesis10degrees,not-350degrees.
show subtract-headings 80 60=> 20show subtract-headings 60 80=> -20show subtract-headings 5 355=> 10show subtract-headings 355 5=> -10show subtract-headings 180 0=> 180show subtract-headings 0 180=> 180
sum
sumlist
Reportsthesumoftheitemsinthelist.
show sum [energy] of turtles;; prints the total of the variable "energy";; from all the turtles
T
tan
tannumber
Reportsthetangentofthegivenangle.Assumestheangleisgivenindegrees.
thickness
thickness
Thisisabuilt-inlinkvariable.Itholdsanumberthatisthelink'sapparentsizeasafractionofthepatchsize.Thedefaultthicknessis0,whichmeansthatregardlessofpatch-sizethelinkswillalwaysappear1pixelwide.Youcansetthisvariabletochangealink'sthickness.
tick
tick
Advancesthetickcounterbyoneandupdatesallplots.
![Page 429: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/429.jpg)
Since4.0
Since4.0
Since4.0
Since1.0
Ifthetickcounterhasnotbeenstartedyetwithreset-ticks,anerrorresults.
Normallytickgoesattheendofagoprocedure.
Seealsoticks,tick-advance,reset-ticks,clear-ticks,update-plots.
tick-advance
tick-advancenumber
Advancesthetickcounterbynumber.Theinputmaybeanintegerorafloatingpointnumber.(Somemodelsdivideticksmorefinelythanbyones.)Theinputmaynotbenegative.
Whenusingtick-basedviewupdates,theviewisnormallyupdatedevery1.0ticks,sousingtick-advancewithanumberlessthen1.0maynotalwaystriggeranupdate.Ifyouwanttomakesurethattheviewisupdated,youcanusethedisplaycommand.
Ifthetickcounterhasnotbeenstartedyetwithreset-ticks,anerrorresults.
Doesnotupdateplots.
Seealsotick,ticks,reset-ticks,clear-ticks.
ticks
ticks
Reportsthecurrentvalueofthetickcounter.Theresultisalwaysanumberandnevernegative.
Ifthetickcounterhasnotbeenstartedyetwithreset-ticks,anerrorresults.
Mostmodelsusethetickcommandtoadvancethetickcounter,inwhichcasetickswillalwaysreportaninteger.Ifthetick-advancecommandisused,thenticksmayreportafloatingpointnumber.
Seealsotick,tick-advance,reset-ticks,clear-ticks.
tie
tie
Tiesend1andend2ofthelinktogether.Ifthelinkisadirectedlinkend1istherootturtleandend2istheleafturtle.Themovementoftherootturtleaffectsthelocationandheadingoftheleafturtle.Ifthelinkisundirectedthetieisreciprocalsobothturtlescanbeconsideredrootturtlesandleafturtles.Movementorchangeinheadingofeitherturtleaffectsthelocationandheadingoftheotherturtle.
Whentherootturtlemoves,theleafturtlesmovesthesamedistance,inthesamedirection.Theheadingoftheleafturtleisnotaffected.Thisworkswithforward,jump,andsettingthexcororycoroftherootturtle.
Whentherootturtleturnsrightorleft,theleafturtleisrotatedaroundtherootturtlethesameamount.Theheadingoftheleafturtleisalsochangedbythesameamount.
Ifthelinkdies,thetierelationisremoved.
crt 2 [ fd 3 ] ;; creates a link and ties turtle 1 to turtle 0 ask turtle 0 [ create-link-to turtle 1 [ tie ] ]
Seealsountie
tie-mode
tie-mode
Thisisabuilt-inlinkvariable.Itholdsastringthatisthenameofthetiemodethelinkiscurrentlyin.Usingthetieanduntiecommandschangesthemodeofthelink.Youcanalsosettie-modeto"free"tocreateanon-rigidjointbetweentwoturtles(seetheTiesectionoftheProgrammingGuidefordetails).Bydefaultlinksarenottied.
Seealso:tie,untie
timer
timer
Reportshowmanysecondshavepassedsincethecommandreset-timerwaslastrun(orsinceNetLogostarted).Thepotentialresolutionoftheclockismilliseconds.(Whetheryougetresolutionthathighinpracticemayvaryfromsystemtosystem,dependingonthecapabilitiesoftheunderlyingJavaVirtualMachine.)
Seealsoreset-timer.
Notethatthetimerisdifferentfromthetickcounter.Thetimermeasureselapsedrealtimeinseconds;thetickcountermeasureselapsed
![Page 430: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/430.jpg)
Since1.0
Since1.0
Since1.0
modeltimeinticks.
to
toprocedure-nametoprocedure-name[input1...]
Usedtobeginacommandprocedure.
to setup clear-all crt 500end
to circle [radius] crt 100 [ fd radius ]end
to-report
to-reportprocedure-nameto-reportprocedure-name[input1...]
Usedtobeginareporterprocedure.
Thebodyoftheprocedureshouldusereporttoreportavaluefortheprocedure.Seereport.
to-report average [a b] report (a + b) / 2end
to-report absolute-value [number] ifelse number >= 0 [ report number ] [ report (- number) ]end
to-report first-turtle? report who = 0 ;; reports true or falseend
towards
towardsagent
Reportstheheadingfromthisagenttothegivenagent.
Ifwrappingisallowedbythetopologyandthewrappeddistance(aroundtheedgesoftheworld)isshorter,towardswillusethewrappedpath.
Note:askingfortheheadingfromanagenttoitself,oranagentonthesamelocation,willcausearuntimeerror.
set heading towards turtle 1;; same as "face turtle 1"
Seealsoface.
towardsxy
towardsxyxy
Reportstheheadingfromtheturtleorpatchtowardsthepoint(x,y).
Ifwrappingisallowedbythetopologyandthewrappeddistance(aroundtheedgesoftheworld)isshorter,towardsxywillusethewrappedpath.
Note:askingfortheheadingtothepointtheagentisalreadystandingonwillcausearuntimeerror.
Seealsofacexy.
turtle
turtlenumber<breed>number
Reportstheturtlewiththegivenwhonumber,ornobodyifthereisnosuchturtle.Forbreededturtlesyoumayalsousethesinglebreedformtorefertothem.
ask turtle 5 [ set color red ];; turtle with who number 5 turns red
![Page 431: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/431.jpg)
Since4.0
Since1.0
Since1.0
Since1.0
Since2.0
turtle-set
turtle-setvalue1(turtle-setvalue1value2...)
Reportsanagentsetcontainingalloftheturtlesanywhereinanyoftheinputs.Theinputsmaybeindividualturtles,turtleagentsets,nobody,orlists(ornestedlists)containinganyoftheabove.
turtle-set self(turtle-set self turtles-on neighbors)(turtle-set turtle 0 turtle 2 turtle 9)(turtle-set frogs mice)
Seealsopatch-set,link-set.
turtles
turtles
Reportstheagentsetconsistingofallturtles.
show count turtles;; prints the number of turtles
turtles-at
turtles-atdxdy<breeds>-atdxdy
Reportsanagentsetcontainingtheturtlesonthepatch(dx,dy)fromthecaller.(Theresultmayincludethecalleritselfifthecallerisaturtle.)
create-turtles 5 [ setxy 2 3 ]show count [turtles-at 1 1] of patch 1 2=> 5
Ifthenameofabreedissubstitutedfor"turtles",thenonlyturtlesofthatbreedareincluded.
turtles-here
turtles-here<breeds>-here
Reportsanagentsetcontainingalltheturtlesonthecaller'spatch(includingthecalleritselfifit'saturtle).
crt 10ask turtle 0 [ show count turtles-here ]=> 10
Ifthenameofabreedissubstitutedfor"turtles",thenonlyturtlesofthatbreedareincluded.
breed [cats cat]breed [dogs dog]create-cats 5create-dogs 1ask dogs [ show count cats-here ]=> 5
turtles-on
turtles-onagentturtles-onagentset<breeds>-onagent<breeds>-onagentset
Reportsanagentsetcontainingalltheturtlesthatareonthegivenpatchorpatches,orstandingonthesamepatchasthegiventurtleorturtles.
ask turtles [ if not any? turtles-on patch-ahead 1 [ fd 1 ]]ask turtles [ if not any? turtles-on neighbors [ die-of-loneliness ]]
Ifthenameofabreedissubstitutedfor"turtles",thenonlyturtlesofthatbreedareincluded.
![Page 432: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/432.jpg)
Since1.0
Since4.0
Since5.0
turtles-own
turtles-own[var1...]<breeds>-own[var1...]
Theturtles-ownkeyword,liketheglobals,breed,<breeds>-own,andpatches-ownkeywords,canonlybeusedatthebeginningofaprogram,beforeanyfunctiondefinitions.Itdefinesthevariablesbelongingtoeachturtle.
Ifyouspecifyabreedinsteadof"turtles",onlyturtlesofthatbreedhavethelistedvariables.(Morethanoneturtlebreedmaylistthesamevariable.)
breed [cats cat ]breed [dogs dog]breed [hamsters hamster]turtles-own [eyes legs] ;; applies to all breedscats-own [fur kittens]hamsters-own [fur cage]dogs-own [hair puppies]
Seealsoglobals,patches-own,breed,<breeds>-own.
type
typevalue
PrintsvalueintheCommandCenter,notfollowedbyacarriagereturn(unlikeprintandshow).Thelackofacarriagereturnallowsyoutoprintseveralvaluesonthesameline.
Thisagentisnotprintedbeforethevalue.unlikeshow.
type 3 type " " print 4=> 3 4
Seealsoprint,show,andwrite.
Seealsooutput-type.
U
undirected-link-breed
undirected-link-breed[<link-breeds><link-breed>]
Thiskeyword,liketheglobalsandbreedskeywords,canonlybeusedatthebeginningoftheCodetab,beforeanyproceduredefinitions.Itdefinesanundirectedlinkbreed.Linksofaparticularbreedarealwayseitheralldirectedorallundirected.Thefirstinputdefinesthenameoftheagentsetassociatedwiththelinkbreed.Thesecondinputdefinesthenameofasinglememberofthebreed.
Anylinkofthegivenlinkbreed:
ispartoftheagentsetnamedbythelinkbreednamehasitsbuilt-invariablebreedsettothatagentsetisdirectedorundirectedasdeclaredbythekeyword
Mostoften,theagentsetisusedinconjunctionwithasktogivecommandstoonlythelinksofaparticularbreed.
undirected-link-breed [streets street]undirected-link-breed [highways highway]to setup clear-all crt 2 ask turtle 0 [ create-street-with turtle 1 ] ask turtle 0 [ create-highway-with turtle 1 ]end
ask turtle 0 [ show sort my-links ];; prints [(street 0 1) (highway 0 1)]
Seealsobreed,directed-link-breed
untie
untie
Untiesend2fromend1(setstie-modeto"none")iftheywerepreviouslytiedtogether.Ifthelinkisanundirectedlink,thenitwilluntieend1fromend2aswell.Itdoesnotremovethelinkbetweenthetwoturtles.
Seealsotie
SeetheTiesectionoftheProgrammingGuideformoredetails.
update-plots
![Page 433: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/433.jpg)
Since1.0Since1.0
Since3.1
Since3.1
Since3.1
Since1.1
update-plots
Foreachplot,runsthatplot'supdatecommands,includingtheupdatecodeforanypensintheplot.
tickhasthesameeffect,soinmodelsthatusethetickcounter,thisprimitiveisnotnormallyused.Modelsthatusefractionalticksmayneedupdate-plots,sincetick-advancedoesnotupdatetheplots.
SeethePlottingsectionoftheProgrammingGuideformoredetails.
Seealsosetup-plots.
uphilluphill4
uphillpatch-variableuphill4patch-variable
Movestheturtletotheneighboringpatchwiththehighestvalueforpatch-variable.Ifnoneighboringpatchhasahighervaluethanthecurrentpatch,theturtlestaysput.Iftherearemultiplepatcheswiththesamehighestvalue,theturtlepicksonerandomly.Non-numericvaluesareignored.
uphillconsiderstheeightneighboringpatches;uphill4onlyconsidersthefourneighbors.
Equivalenttothefollowingcode(assumesvariablevaluesarenumeric):
move-to patch-here ;; go to patch centerlet p max-one-of neighbors [patch-variable] ;; or neighbors4if [patch-variable] of p > patch-variable [ face p move-to p]
Notethattheturtlealwaysendsuponapatchcenterandhasaheadingthatisamultipleof45(uphill)or90(uphill4).
Seealsodownhill,downhill4.
user-directory
user-directory
Opensadialogthatallowstheusertochooseanexistingdirectoryonthesystem.
Itreportsastringwiththeabsolutepathorfalseiftheusercancels.
set-current-directory user-directory;; Assumes the user will choose a directory
user-file
user-file
Opensadialogthatallowstheusertochooseanexistingfileonthesystem.
Itreportsastringwiththeabsolutefilepathorfalseiftheusercancels.
file-open user-file;; Assumes the user will choose a file
user-new-file
user-new-file
Opensadialogthatallowstheusertochoosealocationandnameofanewfiletobecreated.Itreportsastringwiththeabsolutefilepathorfalseiftheusercancels.
file-open user-new-file;; Assumes the user will choose a file
Notethatthisreporterdoesn'tactuallycreatethefile;normallyyouwouldcreatethefileusingfile-open,asintheexample.
Iftheuserchoosesanexistingfile,theywillbeaskediftheywishtoreplaceitornot,butthereporteritselfdoesn'tcausethefiletobereplaced.Todothatyouwouldusefile-delete.
user-input
user-inputvalue
Reportsthestringthatausertypesintoanentryfieldinadialogwithtitlevalue.
![Page 434: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/434.jpg)
Since1.1
Since3.1
Since2.0
Since1.0
Since1.0
valuemaybeofanytype,butistypicallyastring.
show user-input "What is your name?"
SeetheUserInteractionPrimitivessectionoftheProgrammingGuideforadditionaldetails.
user-message
user-messagevalue
Opensadialogwithvaluedisplayedasthemessagetotheuser.
valuemaybeofanytype,butistypicallyastring.
user-message (word "There are " count turtles " turtles.")
Notethatifauserclosestheuser-messagedialogwiththe"X"inthecorner,thebehaviorwillbethesameasiftheyhadclicked"OK".
SeetheUserInteractionPrimitivessectionoftheProgrammingGuideforadditionaldetails.
user-one-of
user-one-ofvaluelist-of-choices
Opensadialogwithvaluedisplayedasthemessageandlist-of-choicesdisplayedasapopupmenufortheusertoselectfrom.
Reportstheiteminlist-of-choicesselectedbytheuser.
valuemaybeofanytype,butistypicallyastring.
if "yes" = user-one-of "Set up the model?" ["yes" "no"] [ setup ]
SeetheUserInteractionPrimitivessectionoftheProgrammingGuideforadditionaldetails.
user-yes-or-no?
user-yes-or-no?value
Reportstrueorfalsebasedontheuser'sresponsetovalue.
valuemaybeofanytype,butistypicallyastring.
if user-yes-or-no? "Set up the model?" [ setup ]
SeetheUserInteractionPrimitivessectionoftheProgrammingGuideforadditionaldetails.
V
variance
variancelist
Reportsthesamplevarianceofalistofnumbers.Ignoresothertypesofitems.
(Notethatthiscomputesanunbiasedestimateofthevarianceforasample,ratherthanforawholepopulation,usingBessel'scorrection.)
Thesamplevarianceisthesumofthesquaresofthedeviationsofthenumbersfromtheirmean,dividedbyonelessthanthenumberofnumbersinthelist.
show variance [2 7 4 3 5]=> 3.7
W
wait
waitnumber
Waitthegivennumberofseconds.(Thisneedn'tbeaninteger;youcanspecifyfractionsofseconds.)Notethatyoucan'texpectcompleteprecision;theagentwillneverwaitlessthanthegivenamount,butmightwaitslightlymore.
repeat 10 [ fd 1 wait 0.5 ]
Whiletheagentiswaiting,nootheragentscandoanything.Everythingstopsuntiltheagentisdone.
![Page 435: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/435.jpg)
Since3.0
Since3.0
Since1.0
Since1.0
Seealsoevery.
watch
watchagent
Putsaspotlightonagent.Inthe3Dviewtheobserverwillalsoturntofacethesubject.
Theobservermayonlywatchorfollowasinglesubject.Callingwatchwillundoperspectivechangescausedbypriorcallstofollow,follow-me,ride,andride-me.
Seealsofollow,subject,reset-perspective,ride,ride-me,watch-me.
watch-me
watch-me
Askstheobservertowatchthisagent.
Theobservermayonlywatchorfollowasinglesubject.Callingwatchwillundoperspectivechangescausedbypriorcallstofollow,follow-me,ride,andride-me.
Seealsofollow,subject,reset-perspective,ride,ride-me,watch.
while
while[reporter][commands]
Ifreporterreportsfalse,exittheloop.Otherwiseruncommandsandrepeat.
Thereportermayhavedifferentvaluesfordifferentagents,sosomeagentsmayruncommandsadifferentnumberoftimesthanotheragents.
while [any? other turtles-here] [ fd 1 ];; turtle moves until it finds a patch that has;; no other turtles on it
who
who
Thisisabuilt-inturtlevariable.Itholdstheturtle's"whonumber"orIDnumber,anintegergreaterthanorequaltozero.Youcannotsetthisvariable;aturtle'swhonumberneverchanges.
Whonumbersstartat0.Adeadturtle'snumberwillnotbereassignedtoanewturtleuntilyouusetheclear-turtlesorclear-allcommands,atwhichtimewhonumberingstartsoveragainat0.
Example:
show [who] of turtles with [color = red];; prints a list of the who numbers of all red turtles;; in the Command Center, in random ordercrt 100 [ ifelse who < 50 [ set color red ] [ set color blue ] ];; turtles 0 through 49 are red, turtles 50;; through 99 are blue
Youcanusetheturtlereportertoretrieveaturtlewithagivenwhonumber.Seealsoturtle.
Notethatwhonumbersaren'tbreed-specific.Notwoturtlescanhavethesamewhonumber,eveniftheyaredifferentbreeds:
clear-turtlescreate-frogs 1create-mice 1ask turtles [ print who ];; prints (in some random order):;; (frog 0): 0;; (mouse 1): 1
Eventhoughweonlyhaveonemouse,itismouse 1notmouse 0,becausethewhonumber0wasalreadytakenbythefrog.
with
agentsetwith[reporter]
Takestwoinputs:ontheleft,anagentset(usually"turtles"or"patches").Ontheright,abooleanreporter.Reportsanewagentsetcontainingonlythoseagentsthatreportedtrue--inotherwords,theagentssatisfyingthegivencondition.
![Page 436: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/436.jpg)
Since4.0
Since2.1
Since2.1
Since4.0
Since1.1
show count patches with [pcolor = red];; prints the number of red patches
<breed>-withlink-with
<breed>-withturtlelink-withturtle
Reportsalinkbetweenturtleandthecaller(directedorundirected,incomingoroutgoing).Ifnolinkexiststhenitreportsnobody.Ifmorethanonesuchlinkexists,reportsarandomone.
crt 2ask turtle 0 [ create-link-with turtle 1 show link-with turtle 1 ;; prints link 0 1]
Seealso:in-link-from,out-link-to
with-max
agentsetwith-max[reporter]
Takestwoinputs:ontheleft,anagentset(usually"turtles"or"patches").Ontheright,areporter.Reportsanewagentsetcontainingallagentsreportingthemaximumvalueofthegivenreporter.
show count patches with-max [pxcor];; prints the number of patches on the right edge
Seealsomax-one-of,max-n-of.
with-min
agentsetwith-min[reporter]
Takestwoinputs:ontheleft,anagentset(usually"turtles"or"patches").Ontheright,areporter.Reportsanewagentsetcontainingonlythoseagentsthathavetheminimumvalueofthegivenreporter.
show count patches with-min [pycor];; prints the number of patches on the bottom edge
Seealsomin-one-of,min-n-of.
with-local-randomness
with-local-randomness[commands]
Thecommandsarerunwithoutaffectingsubsequentrandomevents.Thisisusefulforperformingextraoperations(suchasoutput)withoutchangingtheoutcomeofamodel.
Example:
;; Run #1:random-seed 50 setup repeat 10 [ go ];; Run #2:random-seed 50 setupwith-local-randomness [ watch one-of turtles ]repeat 10 [ go ]
Sinceone-ofisusedinsidewith-local-randomness,bothrunswillbeidentical.
Specificallyhowitworksis,thestateoftherandomnumbergeneratorisrememberedbeforethecommandsrun,thenrestoredafterwards.(Ifyouwanttorunthecommandswithafreshrandomstateinsteadofthesamerandomstatethatwillberestoredlater,youcanbeginthecommandswithrandom-seed new-seed.)
Thefollowingexampledemonstratesthattherandomnumbergeneratorstateisthesamebothbeforethecommandsrunandafterwards.
random-seed 10with-local-randomness [ print n-values 10 [random 10] ];; prints [8 9 8 4 2 4 5 4 7 9]print n-values 10 [random 10];; prints [8 9 8 4 2 4 5 4 7 9]
without-interruption
without-interruption[commands]
Thisprimitiveexistsonlyforbackwardscompatibility.Wedon'trecommendusingitinnewmodels.
![Page 437: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/437.jpg)
Since1.0
Since3.1Since3.1
Since1.0
Since2.0
Theagentrunsallthecommandsintheblockwithoutallowingotheragentsusingask-concurrentto"interrupt".Thatis,otheragentsareput"onhold"anddonotrunanycommandsuntilthecommandsintheblockarefinished.
Note:Thiscommandisonlyusefulinconjunctionwithask-concurrent.
Seealsoask-concurrent.
word
wordvalue1value2(wordvalue1...)
Concatenatestheinputstogetherandreportstheresultasastring.
show word "tur" "tle"=> "turtle"word "a" 6=> "a6"set directory "c:\\foo\\fish\\"show word directory "bar.txt"=> "c:\foo\fish\bar.txt"show word [1 54 8] "fishy"=> "[1 54 8]fishy"show (word 3)=> "3"show (word "a" "b" "c" 1 23)=> "abc123"
world-widthworld-height
world-widthworld-height
ThesereportersgivethetotalwidthandheightoftheNetLogoworld.
Thewidthequalsmax-pxcor-min-pxcor+1andtheheightequalsmax-pycor-min-pycor+1.
Seealsomax-pxcor,max-pycor,min-pxcor,andmin-pycor
wrap-color
wrap-colornumber
wrap-colorcheckswhethernumberisintheNetLogocolorrangeof0to140(notincluding140itself).Ifitisnot,wrap-color"wraps"thenumericinputtothe0to140range.
Thewrappingisdonebyrepeatedlyaddingorsubtracting140fromthegivennumberuntilitisinthe0to140range.(Thisisthesamewrappingthatisdoneautomaticallyifyouassignanout-of-rangenumbertothecolorturtlevariableorpcolorpatchvariable.)
show wrap-color 150=> 10show wrap-color -10=> 130
write
writevalue
Thiscommandwilloutputvalue,whichcanbeanumber,string,list,boolean,ornobodytotheCommandCenter,notfollowedbyacarriagereturn(unlikeprintandshow).
Thisagentisnotprintedbeforethevalue,unlikeshow.Itsoutputalsoincludesquotesaroundstringsandisprependedwithaspace.
write "hello world"=> "hello world"
Seealsoprint,show,andtype.
Seealsooutput-write.
X
xcor
xcor
Thisisabuilt-inturtlevariable.Itholdsthecurrentxcoordinateoftheturtle.Youcansetthisvariabletochangetheturtle'slocation.
Thisvariableisalwaysgreaterthanorequalto(min-pxcor-0.5)andstrictlylessthan(max-pxcor+0.5).
Seealsosetxy,ycor,pxcor,pycor,
![Page 438: NetLogo 6.0 User Manual](https://reader030.fdocuments.us/reader030/viewer/2022012323/586fdd9a1a28ab676b8bb2f2/html5/thumbnails/438.jpg)
Since1.0
Since6.0
xor
boolean1xorboolean2
Reportstrueifeitherboolean1orboolean2istrue,butnotwhenbotharetrue.
if (pxcor > 0) xor (pycor > 0) [ set pcolor blue ];; upper-left and lower-right quadrants turn blue
Y
ycor
ycor
Thisisabuilt-inturtlevariable.Itholdsthecurrentycoordinateoftheturtle.Youcansetthisvariabletochangetheturtle'slocation.
Thisvariableisalwaysgreaterthanorequalto(min-pycor-0.5)andstrictlylessthan(max-pycor+0.5).
Seealsosetxy,xcor,pxcor,pycor,
->
->
[[args]->commands][[args]->reporter]
Createsandreportsananonymousprocedure-acommandorreporter-dependingontheinput.Withincommandsorreporterthelistedargsmaybeusedjustasyouwoulduseletorprocedurevariables.Thevariablenamesinargshavethesamerestrictionsasvariablenamesofcommandsandreporters.Inaddition,theymustnotmatchthenameofanyletorprocedurevariableintheirprocedure.
Anonymousproceduresarecommonlyusedwiththeprimitivesforeach,map,reduce,filter,sort-by,andn-values.Seethoseentriesforexampleusage.
SeetheAnonymousProceduressectionoftheProgrammingGuidefordetails.