NetLogo: Design and Implementation of a Multi-Agent...

17
NetLogo: Design and Implementation of a Multi-Agent Modeling Environment Seth Tisue [email protected] Uri Wilensky [email protected] Center for Connected Learning and Computer-Based Modeling Northwestern University, Evanston, Illinois presented at Agent 2004, Chicago, October 2004 adapted from: Tisue, S., & Wilensky, U. “NetLogo: A Simple Environment for Modeling Complexity”, International Conference on Complex Systems, Boston, May 2004. Tisue, S., & Wilensky, U. “NetLogo: Design and Implementation of a Multi-Agent Modeling Environment”, SwarmFest, Ann Arbor, May 2004. Abstract NetLogo [Wilensky, 1999] is a multi-agent program- ming language and modeling environment for simu- lating complex phenomena. It is designed for both research and education and is used across a wide range of disciplines and education levels. In this pa- per, though, we focus on NetLogo as a tool for re- search and for teaching at the undergraduate level and higher. We outline the principles behind our de- sign and describe recent and planned enhancements. 1 Overview NetLogo is a multi-agent programming language and modeling environment for simulating complex nat- ural and social phenomena. It is particularly well suited for modeling complex systems evolving over time. Modelers can give instructions to hundreds or thousands of independent “agents” all operating concurrently, in order to explore connections between micro-level behaviors of individuals and macro-level patterns that emerge from their interactions. NetLogo enables users to open simulations and “play” with them, exploring their behavior under var- ious conditions. NetLogo is also an authoring envi- ronment that is simple enough to enable students and researchers to create their own models, even if they are not professional programmers. We designed NetLogo for both education and research. There has been considerable research on the use of multi-agent modeling in K–12 settings (e.g. [Wilensky, 1995] [Resnick, 1996] [Wilensky & Resnick, 1999] [Ionnidou et al., 2003] [Wilensky, 2003] [Wilensky & Reisman, in press]). In this paper, though, we focus on NetLogo as a powerful research tool and as a tool for learners at the undergraduate level and higher. Historically, NetLogo is the next generation of the series of multi-agent modeling languages including StarLogo [Resnick & Wilensky, 1993] [Resnick, 1994]. NetLogo is a standalone application 1

Transcript of NetLogo: Design and Implementation of a Multi-Agent...

NetLogo: Design and Implementation

of a Multi-Agent Modeling Environment

Seth [email protected]

Uri [email protected]

Center for Connected Learning and Computer-Based ModelingNorthwestern University, Evanston, Illinois

presented at Agent 2004, Chicago, October 2004

adapted from:

• Tisue, S., & Wilensky, U. “NetLogo: A Simple Environment for Modeling Complexity”,International Conference on Complex Systems, Boston, May 2004.

• Tisue, S., & Wilensky, U. “NetLogo: Design and Implementation of a Multi-AgentModeling Environment”, SwarmFest, Ann Arbor, May 2004.

Abstract

NetLogo [Wilensky, 1999] is a multi-agent program-ming language and modeling environment for simu-lating complex phenomena. It is designed for bothresearch and education and is used across a widerange of disciplines and education levels. In this pa-per, though, we focus on NetLogo as a tool for re-search and for teaching at the undergraduate leveland higher. We outline the principles behind our de-sign and describe recent and planned enhancements.

1 Overview

NetLogo is a multi-agent programming language andmodeling environment for simulating complex nat-ural and social phenomena. It is particularly wellsuited for modeling complex systems evolving overtime. Modelers can give instructions to hundredsor thousands of independent “agents” all operatingconcurrently, in order to explore connections between

micro-level behaviors of individuals and macro-levelpatterns that emerge from their interactions.

NetLogo enables users to open simulations and“play” with them, exploring their behavior under var-ious conditions. NetLogo is also an authoring envi-ronment that is simple enough to enable students andresearchers to create their own models, even if theyare not professional programmers.

We designed NetLogo for both education andresearch. There has been considerable researchon the use of multi-agent modeling in K–12settings (e.g. [Wilensky, 1995] [Resnick, 1996][Wilensky & Resnick, 1999] [Ionnidou et al., 2003][Wilensky, 2003] [Wilensky & Reisman, in press]).In this paper, though, we focus on NetLogo as apowerful research tool and as a tool for learners atthe undergraduate level and higher.

Historically, NetLogo is the next generationof the series of multi-agent modeling languagesincluding StarLogo [Resnick & Wilensky, 1993][Resnick, 1994]. NetLogo is a standalone application

1

written in Java so it can run on all major computingplatforms. After five years of development, NetLogois a mature product that is stable and reliable. It isfreeware—anyone can download it for free and buildmodels without restriction. It comes with extensivedocumentation and tutorials and a large collectionof sample models.

As a language, NetLogo is a member of the Lispfamily that supports agents and concurrency. Mobileagents called “turtles” move over a grid of “patches,”which are also programmable agents. All of theagents can interact with each other and perform mul-tiple tasks concurrently.

NetLogo is being used to build an endless varietyof simulations. Members of our user community haveturned turtles into molecules, wolves, buyers, sell-ers, bees, tribespeople, birds, worms, voters, passen-gers, metals, bacteria, cars, robots, neutrons, mag-nets, planets, shepherds, lovers, ants, muscles, net-workers, and more. Patches have been made intotrees, walls, terrain, waterways, housing, plant cells,cancer cells, farmland, sky, desks, fur, sand, youname it. Turtles and patches can be used to visu-alize and study mathematical abstractions, too, orto make art and play games. Themes addressed in-clude cellular automata, genetic algorithms, positiveand negative feedback, evolution and genetic drift,population dynamics, path-finding and optimization,networks, markets, chaos, self-organization, artificialsocieties and artificial life. The models all share ourcore themes of complex systems and emergence.

In the following sections, we offer more detail onall of these topics. We begin with a tour of the appli-cation, then back up to outline its history. We thengive a more detailed account of the language itself.NetLogo has recently become extensible; we explainwhy and how. A technical discussion of how NetLogois implemented follows. Finally, we conclude with asummary of work in progress and future plans.

2 Tour

In this section we give the reader a brief tour of theNetLogo user interface and Models Library.

Figure 1: NetLogo’s user interface, with model Dif-fusion Limited Aggregation

2.1 User interface

Figure 1 shows NetLogo’s user interface after openingand running a model from the Models Library.

On the right is the graphics window, in which the“world” of the model is made visible. In the modelshown, the turtles represent diffusing particles. Theywander randomly. When the model begins, there isa single green patch in the center. When a particleencounters a green patch, it “sticks” and turns greenitself. Over time a beautiful, branching aggregateemerges.

On the left are model controls. In this model, theyinclude:

• Buttons for controlling the model. “Setup” ini-tializes the model and “Go” makes it run.

• Sliders that control model parameters. For ex-ample, the “num-particles” slider control thenumber of particles that build the aggregate.

Note that this is a simple model with only a fewcontrols. For more complicated models, other typesof controls are available including switches, choosers,monitors, plots, text boxes, and output areas.

2

In this screen shot, we see only NetLogo’s “In-terface” tab. The Interface tab is also an interfacebuilder. No firm distinction is made between using amodel and editing it—you can move, modify, or cre-ate interface elements at any time. Agents can beinspected and altered and the code for the model canbe changed without restarting the simulation. At thebottom of the Interface tab is the “Command Cen-ter,” in which NetLogo commands can be issued, evenwhile the model is running.

The other tabs are:

• Information, where documentation on the modelis found. This typically explains the rules be-hind the model and suggests experiments for thereader to try.

• Procedures, where the actual code for the modelis stored. A well written model includes com-ments in the code explaining how it works.

• Errors (normally disabled), where any incorrectcode can be viewed and fixed.

The order of the tabs is meant to follow a user’s typ-ical engagement with a model. Usually people wantto dive right in and try out the model first in theInterface tab, then move to the Information tab tomore fully understand what they’re seeing. Eventu-ally, they can inspect the code in the Procedures tabto understand the underlying rules and make modi-fications and additions.

Figure 2 shows the Procedures tab containing thecomplete code for the model. Language elements areautomatically color-coded so the code’s structure ismore clearly visible.

NetLogo can exchange data with other applica-tions. The language includes commands that let youread or write any kind of text file. There are alsofacilities for exporting and importing data in stan-dard formats. The complete state of the world canbe saved and restored in a format that can easily beopened and analyzed with other software. Grapheddata can be exported for rendering and analysis withother tools. The contents of the graphics window, orof the model’s whole interface, can be saved as animage, or you can record a series of such images as

Figure 2: Procedures tab with complete code for theaggregation model.

a QuickTime movie. Finished models can be pub-lished on the web or embedded in presentations asJava applets.

NetLogo includes a still evolving tool called Behav-iorSpace that allows “parameter sweeping,” that is,systematically testing the behavior of a model acrossa range of parameter settings. Figure 3 shows an ex-ample of using BehaviorSpace to study a forest firemodel. Based on the experiment setup entered by theuser, BehaviorSpace automatically runs the modelmany times while varying the “density” parameter.The results show the effect of that parameter on theamount of forest burned.

NetLogo supports not only the construc-tion of wholly computer-based simulations, butalso what we call “participatory simulations”[Wilensky & Stroup, 1999a], in which a group of stu-dents acts out the behavior of a system, each studentplaying the role of an individual element of the sys-tem. To enable this, NetLogo includes a technologycalled HubNet [Wilensky & Stroup, 1999b], whichenables communication between a NetLogo model

3

Figure 3: Using BehaviorSpace to study a forest firemodel. The density slider is varied from 40 to 80by steps of 2. We measure the percentage of burnedtrees at the end of each run. A run ends when no“fire” agents remain. The graph at the bottom (gen-erated from the BehaviorSpace output by means ofa graphing packgage) shows the results: an abruptphase transition at the critical density.

Figure 4: Nodes and edges, both represented usingturtles in the graphics window.

operating as a server and a set of clients, which maybe handheld devices or computers running HubNetclient software.

The most visible area of change in NetLogo 2.0 wasgraphics. Now, turtles can be any size and shape andbe positioned anywhere. Turtles and patches can alsobe labeled with text. Turtle shapes are vector-basedto ensure smooth appearance at any scale. Thesechanges have led to dramatic visual enhancement ofmodels. An example of graphics that weren’t possiblebefore is the use of turtles to represent both nodesand edges in a network as in Figure 4.

Significant improvements made for the NetLogo 2.1release include:

• Improved editor for turtle shapes, to make it eas-ier to customize how a model looks. This is im-portant for data visualization. See Figure 5.

• Parenthesis and bracket matching in the codeeditor, to make editing complex code easier.

• Detecting individual keystrokes from code. This

4

Figure 5: New, improved editor for turtle shapes.

makes highly interactive models (and games)more usable.

• Adding let to the language, so new local vari-ables can be introduced anywhere. This helpsmodelers write clearer, more concise code.

2.2 Models Library

Just as important as NetLogo itself are the materi-als it comes with. We’ve devoted almost as muchdevelopment effort to our Models Library as to theNetLogo application.

The Models Library contains more than 150 pre-built simulations that can be explored and modified.Figure 6 shows the structure of the Models Library.The simulations address many content areas in thenatural and social sciences, including biology andmedicine, physics and chemistry, mathematics andcomputer science, and economics and social psychol-ogy. All of the models include an explanation of thesubject matter and the rules of the simulation andsuggestions for activities, experiments, and possibleextensions. To aid learning and encourage good pro-gramming practice, the code for the simulations isclear, elegant, and well commented.

Figure 6: Structure of the Models Library.

Our goal for the library is to include as many aspossible of the standard, well-known “chestnuts” ofcomplex systems science. This serves several pur-poses:

• Researchers, already knowing the ideas behindthe models, can easily learn the language bystudying them.

• Modelers can usually find something in the li-brary to base a new model on, rather than start-ing from scratch.

• These well-known examples are introduced to anew generation of students of complex systemsscience.

The Models Library also includes a “curricularmodels” section. It contains groups of models thatare intended to be used together in an educationalsetting as part of a curricular unit. Most of theminclude extra associated curricular materials (aboveand beyond that which we provide with all of ourmodels).

In addition to the 140 simulations, the library alsoincludes several dozen “code examples.” These arenot full simulations, but brief demonstrations of Net-Logo features or coding techniques.

5

3 History and audience

In this section we summarize NetLogo’s history andhow it came to be a tool for both education and re-search, and we explain the benefits of addressing bothaudiences.

3.1 Origins

NetLogo originates in a blend of StarLisp[Lasser & Omohundro, 1986] and Logo[Papert, 1980]; Logo is itself a member of theLisp family. From Logo, it inherits the “turtle.” Intraditional Logo, the programmer controls a singleturtle; a NetLogo model can have thousands of them.NetLogo also follows Logo’s philosophy of ease ofuse, providing a “low threshold” of entry for newusers. From StarLisp, a parallel Lisp of the 1980’s,NetLogo inherits multiple agents and concurrency.

NetLogo derives from our experience with ourearlier environment, StarLogoT [Wilensky, 1997].Even though the original incarnation of StarLogo[Resnick & Wilensky, 1993, Resnick, 1994] was on asupercomputer, it had always been primarily in-tended for use in schools.1 But StarLogoT becamevery popular among researchers. So with NetLogo,we now aim more explicitly to satisfy the needs ofboth audiences. In the transition from StarLogoT toNetLogo, we redesigned both the language and theuser interface. NetLogo includes almost all of Star-LogoT’s features and many new ones. Many of thenew features of NetLogo are aimed at research users.

3.2 “Low threshold”

All the multi-agent Logos have adopted design prin-ciples from the Logo language. A central principleis “low threshold, no ceiling.” Low threshold meansnew users, including those who never programmedbefore, should find it easy to get started. No ceil-ing means the language shouldn’t be limiting for ad-vanced users. We wanted NetLogo to be just as pop-

1There were several different early implementations of Star-Logo in the first part of the 1990’s. The supercomputer versionwas Connection Machine StarLogo. Later came MacStarLogo[Begel, 1999], of which StarLogoT is a superset.

ular with researchers as StarLogoT had been, so thatmeant devoting significant attention to the “no ceil-ing” side of the principle. Logo’s reputation as alanguage for schools doesn’t do justice to its amplepower, as demonstrated in [Harvey, 1997].

We believe researchers should care about “lowthreshold” too. Even for such users, NetLogo’s in-heritance from educational languages brings severalbenefits. First, in universities there is substantialoverlap between teaching and research, and if a singletool can serve both needs there are opportunities forsynergy. Second, when code is easier to write andeasier to read, everyone benefits. Models becomeeasier to build; often researchers can build modelsthemselves when otherwise they would have to hireprogrammers. And models become more easily un-derstood by others; this is vitally important in orderfor researchers to effectively communicate their re-sults to others, verify each other’s results, and buildupon each other’s work. The goals of scientific mod-eling are compromised if programs are long, cryptic,and platform-specific. A NetLogo model is less likelyto suffer these problems than one written in commongeneral-purpose languages like Java and C++.

3.3 The integrated approach

NetLogo is its own programming language, em-bedded in an integrated, interactive modelingenvironment. The integrated approach to multi-agent modeling originates with StarLogo, wasrefined in StarLogoT and NetLogo, and hasalso been followed by other all-in-one agent-based modeling solutions such as AgentSheets[Repenning, Ioannidou & Zola, 2000] and Breve[Klein, 2002]. “Toolkits” or libraries such as Swarm[Minar, Burkhart, Langton & Askenazi, 1996] andRepast [Collier & Sallach, 2001] take a differentapproach; they make simulation facilities availableto programs written in a general-purpose languagesuch as Java.

We see the integrated approach as essential toachieving our “low threshold” goal. The difficultyof programming in Java or C++ isn’t due only tothe language itself. It’s also due to the complicationof the environments (whether command line based

6

or GUI based) in which programming in those lan-guages is normally done. When you add in the addedcomplexity of getting the environment to talk to amodeling library or toolkit, the initial barrier for en-try for new programmers becomes quite high—evenbefore they start dealing with the difficulties of thelanguages themselves.

In contrast, the NetLogo environment allows asmooth, almost unnoticeable transition from explor-ing existing models into programming. NetLogo’suser interface makes no firm distinction between us-ing a model and editing it. Even the smallest amountof knowledge of the language is immediately useful increating buttons and monitors or typing commandsinto the command center, in order to better inspectand control an existing model. Altering the model’srules is only as far away as a click on the Procedurestab.

3.4 Development history

NetLogo has been under development since 1999.Since then we’ve averaged two to three substantialnew releases per year. Version 2.0.2 (August 2004)is mature, stable, and reliable. As of October 2004version 2.1 is available in beta form and we expect afinal release soon. Even though our user base has ex-panded, the rate of incoming bug reports has slowedto a trickle. Models now run much faster than in ear-lier versions—our users now find it fast enough formost purposes.

3.5 Acceptance

We have much evidence that acceptance of NetLogoin the research and education communities is wideand growing. The software has been downloaded tensof thousands of times. Currently, there are about50 downloads per day. Our announcements list hasover 5,000 members. The NetLogo discussion group(http://groups.yahoo.com/group/netlogo-users/)has over 1,600 members and averages about 100posts per month. Traffic on the discussion group hasincreased fivefold since 2002. Several organizationshave independently conducted workshops on NetL-ogo for both researchers and teachers. In the summer

of 2004, we held our own first annual workshop atNorthwestern. A number of university classes arenow taught, in whole or in part, using NetLogo.Some of these classes and workshops have richcollections of associated materials available online.The NetLogo web site has an area where users canupload models to share with the user community.More than 100 models have been uploaded so far.

4 Language

In this section, we describe the NetLogo program-ming language itself. For further information on theNetLogo language, consult the NetLogo User Man-ual [Wilensky, 1999], particularly the ProgrammingGuide and Primitives Dictionary sections.

4.1 Language fundamentals

As a language, NetLogo adds agents and concurrencyto Logo. Logo, as originally developed by SeymourPapert and Wally Feurzeig in 1968, is derived fromLisp, but has a friendlier syntax. Logo was designedas a programming language usable by children as wellas adults and is still popular today for that purpose.It is a powerful general-purpose computer language.

Although Logo isn’t limited to graphical applica-tions, it is best known for its “turtle graphics,” inwhich a virtual being or “turtle” moves around thescreen drawing figures by leaving a trail behind it.NetLogo generalizes this concept to support hundredsor thousands of turtles all moving around and inter-acting. The world in which the turtles move is a gridof “patches,” which are also programmable. Collec-tively, the turtles and patches are called “agents”.All agents can interact with each other and performmultiple tasks concurrently. NetLogo also includesa third agent type, the “observer”. There is onlyone observer. In most models, the observer gets theball rolling by issuing instructions to the turtles andpatches. Different “breeds” of turtle may be defined,and different variables and behaviors can be associ-ated with each breed.

Some models use the patch world just as a lat-tice. For example, in a cellular automaton, there are

7

no turtles, only patches. And in some other mod-els, turtles move on the lattice (from patch centerto patch center). But the patches are not just lat-tice sites—they are square sections of a continuoustwo-dimensional space. Turtle coordinates are float-ing point values, so a turtle may be positioned any-where within a patch. For example, in the aggrega-tion model shown above, the aggregate is made up oflattice sites, but particles move freely on the plane.

There are many language elements for talk-ing about space and spatial relations: towards,distance, neighbors, forward and back, left andright, size, heading, patch-ahead, diffuse, andso on. Some of these come from Logo, while othersare new.

An important NetLogo language feature, not foundin its predecessors, is “agentsets,” or collections ofagents. For example, the set of all turtles and theset of all patches are agentsets. You can also makecustom agentsets on the fly, for example the set of allred turtles, or a column of patches (the set of patcheswith a given X coordinate). Agentsets are responsiblefor much of NetLogo’s expressive power.

In addition to special constructs to support multi-agent modeling, NetLogo also includes standard pro-gramming constructs such as procedures, loops, con-ditionals, recursion, strings, lists, and so forth. Bothinteger math and double-precision IEEE floatingpoint math are supported. The run and runresultcommands can be used to execute code constructedon the fly.

4.2 NetLogo as Logo

Although there is no single agreed upon standard forthe Logo language, NetLogo shares enough syntax,vocabulary, and features with other Logos to earn theLogo name. Still, some important differences frommost Logos include:

• We have no symbol data type. Eventually, wemay add one, but since it is seldom requested,it may be that the need doesn’t arise much inagent-based modeling. In most situations wheretraditional Logo would use symbols, we simplyuse strings instead.

• Control structures such as if and while are spe-cial forms, not ordinary functions. You can’t de-fine your own special forms.

• As in most Logos, functions as values are notsupported. Most Logos provide similar function-ality, though, by allowing passing and manipu-lation of fragments of source code in list form.NetLogo’s capabilities in this area are presentlylimited. A few of our built-in special formsuse UCBLogo-style “templates” to accomplish asimilar purpose, for example, sort-by [length?1 < length ?2] string-list. In some cir-cumstances, using run and runresult instead isworkable, but they operate on strings, not lists.

There are several reasons for those omissions. Theyare partly due to NetLogo’s descent from StarLogoT,which as discussed above needed to be very lean.Many of StarLogoT’s limitations have already beenaddressed in NetLogo (for example, NetLogo hasagentsets and double-precision floating point math),but some of the “leanness” remains. This leannessis not only historical, though. Efficiency is always avital goal for multi-agent systems, since many mod-elers want to do large numbers of long model runswith as many agents as they can. It is easiest to con-struct a fast engine for a simple language, and, from alanguage design perspective, omitting advanced lan-guage features and prohibiting the definition of newspecial forms may actually be desirable for a lan-guage in which readability and sharing of code isparamount. We weigh these tradeoffs carefully as wecontinue to expand the language.

4.3 Reproducibility

One of our core design goals for NetLogo is that re-sults be scientifically reproducible, so it is importantthat models operate deterministically. NetLogo isa “simulated parallel” environment. In true paral-lel computing, programs must be constructed verycarefully to avoid nondeterminism. We think thisis too great a burden for novice programmers, soconcurrency in NetLogo operates deterministically.That means that if you “seed” the random number

8

generator the same way, then a NetLogo model al-ways follows the same steps in the same order andproduces the exact same results, regardless of whatcomputer you run it on. Java’s underlying platform-independent math libraries help assure consistency.

5 Extensibility

In this section, we describe how NetLogo has recentlybecome extensible through the addition of new “ex-tensions” and “controlling” facilities.

Earlier, we described NetLogo as an integrated or“all-in-one” environment. The full NetLogo envi-ronment bundles together many components: a pro-gramming language, a compiler, an interpreter, a syn-tax highlighting editor, an interface builder, a graph-ics engine, BehaviorSpace, and so on. The down-side of the all-in-one approach is that “all-in-one” canturn into “all-or-nothing.” We run the risk that if onecomponent doesn’t suit a user’s needs, then that userwon’t be able to use any of the components, becausethey’re all tied together.

We want to avoid this all-or-nothing trap by let-ting users extend or replace parts of NetLogo thatdon’t suit their purposes. That way even users whohave unique needs, or just needs we didn’t think ofor haven’t gotten around to addressing yet, can buildwhat they need themselves in Java, and they will stillget the benefit of the rest of our work. These newAPIs are steps towards that goal. They lift the “ceil-ing” on NetLogo’s usefulness and range of applica-tions. The integrated NetLogo environment providescore functionality; our APIs will allow advanced usersto move outside that core.

In making NetLogo extensible, we are bridgingthe gap between integrated modeling environments(easy to use, but potentially restricting) and model-ing toolkits (more flexible, but much harder to use).

5.1 Extensions API

NetLogo has always been a full-fledged programminglanguage, so users may write procedures in NetLogoand then use them just like built-in commands. Butsince NetLogo 2.0.1 we have offered an application

programmer’s interface (API) for extensions so thatusers can add new elements to the language by im-plementing them directly in Java. This lets users addwhole new types of capabilities to NetLogo.

We have been using this new API internally fora while now, and have written extensions that letNetLogo:

• Talk to other NetLogos running on different com-puters, peer-to-peer

• Pull down data from a web server

• Make sounds and music using MIDI

The sound extension is now included with NetLogo.Full Java source code for it, and a number of othersample extensions, are available from our website.Our hope is that extension authors will share theirextensions with the wider user community, so thateveryone can benefit from their efforts.

5.2 Controlling API

We also offer a “controlling” API which allows ex-ternal code to operate the NetLogo application byremote control, so to speak. This API includes callsfor opening a model and running any NetLogo com-mands. This permits users willing to do a littlelight Java programming to automate large numbersof model runs from the command line. This is usefulboth on a single machine and when distributing runsacross a cluster. We already provide an automatedparameter-sweeping tool called BehaviorSpace, butthe API is still be useful in situations where Behav-iorSpace’s present capabilities aren’t sufficient.

The API currently requires the full NetLogo userinterface to be present, but we are working on re-moving this limitation so that models can be run“headless” from the command line. (On X11-basedsystems, it is possible right now to work around thislimitation using X11’s ‘virtual framebuffer” support.)

6 Implementation

In this section, we explain how how we have con-structed the NetLogo software. This section is moretechnical than the others.

9

6.1 Background: StarLogoT

StarLogoT succeeded in attracting a large user basefrom a range of disciplines, but it had important tech-nical limitations that we wanted to address.

The biggest limitation of StarLogoT was that itonly ran on Macintosh computers. At the time de-velopment on StarLogoT’s precursors began, the in-troduction of Java had not yet brought cross-platformdevelopment of GUI applications within easy reach.Also, the target audience was schools, so the softwareneeded to be compact and fast enough to run evenon hardware that by today’s standards was absurdlyunderpowered. Putting thousands of agents on suchmachines was only possible if the underlying enginewas written in assembly language, which is of courseplatform-specific.

The need to be fast and small resulted in other lim-itations as well. Math in StarLogoT was fixed point,not floating point, with only a few digits of preci-sion. Many arbitrary limits were imposed in orderfor crucial data structures to fit within a small, fixednumber of bits. For example, a model couldn’t havemore than 16,384 turtles, or a patch grid bigger than251x251, or a stack depth of more than 64.

StarLogoT’s language design was constrained aswell by what could reasonably be implemented. Theneed for efficiency led StarLogoT’s architecture to be-come quite complicated. It included three differentvirtual machines for our three agent types (observer,turtles, and patches). Different agent types had dif-ferent capabilities and different rules for acting inparallel; this was confusing to users and some of therestrictions placed on user programs were severe.

6.2 Starting over

Because of these limitations, we chose to start overand write our new environment, NetLogo, fromscratch. We bet that Java would permit us to build across-platform application that was reasonably fast.Java doesn’t always completely live up to its “writeonce, run anywhere” promise, but comes close enoughof the time that it brought cross-platform develop-ment within reach for our small development team.We knew that Java was slower than assembly lan-

guage, but hoped that on newer, faster machines itwouldn’t matter too much. The issue of speed is dis-cussed further below.

Using Java offered the additional benefit that in-dividual NetLogo models could be embedded in webpages and run in a browser, without the end userneeding to download and install an application. (Ini-tially, we even allowed the full NetLogo authoringenvironment to run as an applet in a web browser,but later we abandoned this option as not worth theextra development effort.)

Since we were starting from scratch anyway, wetook the opportunity to redesign the language to fur-ther both our “low threshold” and “no ceiling” goals.Sometimes we had to weigh tradeoffs between thosetwo goals; in other cases, such as agentsets, we wereable to reduce barriers to novice entry while also mak-ing the language more expressive and powerful. Indoing so, we also tried to be compatible with stan-dard, popular Logo implementations whenever pos-sible and reasonable. In particular, we tried not tostray too far from StarLogoT, so our existing userbase wouldn’t find the transition too painful.

6.3 Java

NetLogo is written entirely in Java. Java was chosenbecause both the core language and the GUI librariesare cross-platform, and because modern Java virtualmachines have use JIT (just in time) compiler tech-nology to achieve relatively high performance.

NetLogo 1.3 supported earlier Java versions goingback to Java 1.1, but for NetLogo 2.0 we decided torequire Java 1.4. The major reasons for choosing Java1.4 for the new version were as follows:

• The new language version includes much richerlibraries. It was increasingly difficult to find de-velopers used to working within the limitationsof the antiquated version.

• More recent VM’s are higher quality. Before weabandoned Java 1.1, constantly working aroundbugs in the various 1.1 VM’s was a serious dragon our development efforts.

10

• Unlike Java 1.1, Java 1.4 offers “strict” mathlibraries which guarantee identical, reproducibleresults cross-platform.

• Leaving Java 1.1 behind allowed us to switchGUI toolkits, from the old AWT toolkit to thenewer Swing toolkit, which has numerous advan-tages, including better look & feel (Figure 7).

• After a long wait, Apple finally released a highquality Java 1.4 implementation for Mac OS X.

• Even with the new VM, Apple’s support forAWT-based applications on Mac OS X was poor.Mac support is important to us, but a high qual-ity implementation on the Mac was simply im-possible without switching to Swing.

• Since Java 1.4 is available for all the major plat-forms for which 1.3 is also available (not countingMac OS X 10.0 and 10.1), it seemed unnecessaryto be backwards compatible with Java 1.3.

Regrettably, switching to Java 1.4 meant droppingsupport for users of Windows 95 and MacOS 8 and9, since no Java 1.4 implementation is available forthose operating systems. However, we continue tooffer support and bugfixes for NetLogo 1.3, so thoseusers aren’t left out in the cold.

6.4 Speed

Early versions of NetLogo were slow, but especiallysince version 1.3, models run much faster. Most ofour users now find NetLogo fast enough for most pur-poses. Nonetheless, we plan to continue to improveNetLogo’s speed, since agent-based modeling is a fieldin which users always benefit from more speed.

StarLogoT was written partially in assembly lan-guage and was highly performance tuned. NetLogois written in Java and the NetLogo language is muchmore flexible and feature rich than StarLogoT. There-fore, you would expect NetLogo to be slower. Surpris-ingly, that isn’t always or even usually true. Whichenvironment is faster depends on the nature of themodel. In general, StarLogoT is still faster for mod-els with very simple code and large numbers of agents.

Figure 7: Our new, Swing-based user interface. Alsoillustrates new graphics features.

But NetLogo is usually faster for models with com-plex code and smaller numbers of agents.

The surprising fact that StarLogoT is not alwaysfaster can be accounted for by reference to StarL-ogoT’s unique architecture. As mentioned above, theStarLogoT engine was divided into three virtual ma-chines: one for the observer, written in Lisp, andtwo for the turtles and patches, written in assem-bly language. The turtle and patch machines wereextremely fast, but crossing the boundaries betweenthe different machines was slow. With simpler codeand more turtles and patches, overall speed benefitedmore from the speed of the turtle and patch virtualmachines. In contrast, NetLogo’s internal architec-ture is much more uniform. A single virtual machinehandles all three agent types. Therefore, there isno special penalty associated with complex code andno special benefit associated with large numbers ofagents.

NetLogo is a hybrid compiler/interpreter. To im-prove performance, we don’t interpret the user’s codedirectly. Instead, our compiler analyzes, annotates,and restructures it into a form that can be interpretedmore efficiently.

Earlier versions of NetLogo (1.0 and 1.1) compiled

11

user code into a form suitable for execution by avirtual machine which was stack-based. However,we discovered through profiling that making the vir-tual machine stack-based actually hurt performancerather than helping it. So, in our current compiledrepresentation, each command is tree-structured sothat intermediate results are stored on the Java VM’sown stack instead of our stack. This change re-sulted in an approximately twofold performance gain.Other, smaller engine performance gains since Net-Logo 1.0 came from profiling the engine code andaddressing inefficiencies in object creation, memoryusage, and other areas.

If we want to further increase NetLogo’s speed inthe future, the most promising approach, relative tothe likely development effort required, seems to beto compile NetLogo code to Java byte code insteadof our own custom intermediate representation. In-formal tests indicate that this would likely result inat least a twofold improvement in speed. We alsohave considered replacing the Java-based engine witha native one, perhaps written in C. However, generalopinion recently is that JITted Java code isn’t alwaysslower than C code anymore, so we’re not certain ifthis approach would be fruitful.

So far we have been discussing the speed of Net-Logo’s core computational engine. But NetLogo’soverall performance doesn’t depend only on enginespeed. There’s also graphics speed to consider.Whether engine speed or graphics speed dominatesvaries widely from model to model—some are 90%engine, others are 90% graphics. The latter kindof model can always be sped up by using NetL-ogo’s graphics “control strip” to temporarily shut offgraphics altogether, but that doesn’t mean graphicsperformance is unimportant.

Switching our GUI framework from AWT to Swingraised problems for graphics performance. Prior toNetLogo 2.0, graphics window updates were “incre-mental,” that is to say, only agents that moved orchanged were redrawn. Incremental painting on-screen, instead of to an offscreen buffer, is not sup-ported under Swing, and on Mac OS X, the perfor-mance of painting offscreen was unacceptable. Asan experiment, we switched from incremental paint-ing to always redrawing the complete contents of the

graphics window every time, fearful that the changewould hurt performance. We were pleasantly sur-prised; on Macs graphics performance actually in-creased, and on Windows, the speed penalty was neg-ligible.

Abandoning incremental updates freed NetLogo’sgraphics capabilities enormously. Previously, in or-der to make incremental updates possible, the graph-ics window was limited in several important respects.Even though NetLogo’s world is continuous, turtlesin the graphics window were always the same size andappeared centered on their patches, like chess pieces.Since patches did not overlap, it was possible to re-draw each patch incrementally and separately. Butif incremental updates are no longer performed, thenthere is no longer any reason to align turtles with thegrid. So now, in NetLogo 2.0, turtles can be any sizeand shape and be positioned anywhere. Turtles andpatches can also be labeled with text. Turtle shapesare vector-based to ensure smooth appearance at anyscale. These features had actually been available inearlier NetLogo versions, but were slow and buggy.Now they are fast and reliable. These changes haveled to dramatic visual enhancement of models (Fig-ure 7, Figure 8).

6.5 Concurrency

In many respects the NetLogo engine is an ordinaryinterpreter. But it also has some unusual featuresbecause of the need to support concurrent processes.Concurrency in NetLogo has two sources.

The first kind of concurrency we support is con-currency among agents. If you use the commandforward 20 to ask a set of turtles to move forward20 steps, we don’t want one turtle to win the racebefore the others have even left the starting line.So, we have all the turtles take one step together,then they all take another step, and so forth. Ulti-mately, the NetLogo engine is single-threaded, so theturtles must move one at a time in some order; theycan’t really move simultaneously. So the engine “con-text switches” from agent to agent after each agenthas performed some minimal unit of work, called a“turn.” Because the timing of context switches is de-terministic, the overall behavior of the model remains

12

Figure 8: The Ants model, with and without newgraphics features.

deterministic. We only update the screen after all theagents have had a turn; this visually preserves the il-lusion of simultaneity. The NetLogo User Manualcontains a more detailed discussion of the timing ofcontext switches between agents. We provide a com-mand, without-interruption, which the program-mer can use to prevent unwanted switching.

The second kind of concurrency we support is con-currency among the different elements of the NetL-ogo user interface which can initiate the execution ofcode. Currently these are: buttons, monitors, andthe Command Center. Buttons and monitors con-tain code entered by the model author, and the usermay enter commands into the Command Center atany time. In all three cases, a “job” is created andsubmitted to the engine to request that some codebe executed by some agents. Jobs are akin to whatoperating systems call “threads” or “processes.” Weuse the word “job” to avoid confusion. At the op-erating system level, the NetLogo application is oneprocess, and the NetLogo engine is one thread withinthat process.

When multiple jobs are active, the engine mustswitch between them, just as it switches between theagents within a job. The rule followed is to switchfrom job to job once every agent in the first job hashad a turn. Here, the NetLogo engine is taking on atask more typically associated in computer scientists’minds with the process scheduler in a cooperativelymulti-tasked operating system rather than with a lan-guage interpreter.

Concurrency is still an active area of concern forus. We’re not sure we’ve arrived at final decisionson how best to support it. We’re presently revisitingand rethinking our current design choices with an eyetowards both helping newcomers avoid mistakes andincreasing the power available to advanced users.

7 Conclusion

We have already touched upon some goals for futureNetLogo versions, such as increased speed and head-less operation. Here are some other enhancements forwhich we already have working prototypes:

• 3-D NetLogo, including language extensions and

13

OpenGL-based 3-D graphics. Some 3-D modelsare already possible, but language support willmake them easier to build and OpenGL will en-able much higher quality 3-D visualization. Thisis a very big job, but we have a working proto-type already (see Figure 9).

• Support for different lattices and world topolo-gies, with no extra code required. Currently, theNetLogo patch world “wraps” in the X and Ydirections, forming a torus. Some language ele-ments are available in both wrapping and non-wrapping versions. Typically, models that don’twant wrapping use the outer layer of patchesas a barrier. In a future version, we plan tomake wrapping a global option which can beturned off. This is an example of an alternateworld topology. Soon, we will also support even-numbered grid sizes and arbitrary placement ofthe origin of the coordinate plane. In the longerterm, we would like to support unbounded planemodels. We already have some models that op-erate on a hexagonal lattice, but their code can’tcurrently be made as concise as we would like.

• Easier, more flexible randomized agent schedul-ing. (Random scheduling is already possible byadding extra code, but will be built in.)

• Improved plotting requiring less additional codein the procedures tab. Separating code for agentbehaviors from code for data generation and vi-sualization code will improve clarity and concise-ness of models.

• A profiling tool for identifying speed bottlenecksin model code.

Networks are currently a very active area of re-search in the agent-based modeling community. Net-work models are already possible in NetLogo, but wewant to make them easier to build, including mak-ing it easier to leverage the capabilities of existingnetwork analysis and visualization tools.

We are also adding support to NetLogo for ag-gregate modeling. Aggregate modeling, also knownas systems dynamics modeling, has historically been Figure 9: Some screen captures of our prototype 3-D

version of NetLogo.

14

supported by separate, non-agent-based modelingtools such as STELLA [Richmond & Peterson, 1990].We are incorporating similar finite difference enginetechnology into NetLogo so that researchers and stu-dents can investigate systems using agent-based andaggregate techniques in tandem.

There are ongoing efforts within our research groupto further explore NetLogo’s potential for researchand education. Of particular relevance to NetLogo’sfuture as a research tool are these major ongoinglong-term projects:

• Integrated Simulation and Modeling Environ-ments (ISME), a project in collaborationwith the University of Texas which usesNetLogo to enact “participatory simulations”[Wilensky & Stroup, 1999a] in both classroomand research contexts.

• Procedural Modeling of Cities, a project inwhich agents “grow” virtual cityscapes foruse in architecture, urban planning, train-ing, and entertainment. Preliminary resultsfrom the model are shown in Figure 10[Lechner, Watson, Wilensky & Felsen, 2003].

• Modeling School Reform, a project to build mod-els of the potential effects of educational pol-icy decisions, to assist school leaders and policymakers. This work will include social networkmodeling and analysis.

These projects will drive substantial expansion ofNetLogo’s ability to support large, ambitious model-ing efforts. We also have a number of other projects,focused on the use of NetLogo in educational con-texts.

8 Acknowledgments

Thanks to the members of our user community, andto all past and present members of the Center forConnected Learning and Computer-Based Modeling,for all of their contributions to NetLogo.

Portions of this paper were loosely adapted fromthe NetLogo User Manual [Wilensky, 1999]. We

Figure 10: Growth of a simulated city. Left columnrepresents land use, right column represents popula-tion density.

15

thank Owen Densmore for contributing the networklayout model used to produce Figure 4.

We gratefully acknowledge the support of the Na-tional Science Foundation.

References

[Begel, 1999] Begel, Andrew, “StarLogo: Buildinga Modeling Construction Kit for Kids”, Proceed-ings of the Workshop on Agent Simulation: Ap-plications, Models, and Tools.

[Collier & Sallach, 2001] Collier, N. & Sallach,D.; Repast. University of Chicago.http://repast.sourceforge.net/

[Harvey, 1997] Harvey, Brian, Computer ScienceLogo Style, 2nd ed., vols. 1–3, MIT Press.

[Ionnidou et al., 2003] Ioannidou, Andri; Repen-ning, Alexander; Lewis, Clayton; Cherry,Gina; and Rader, Cyndi; “Making Construc-tionism Work in the Classroom”, InternationalJournal of Computers for Mathematical Learn-ing, Volume 8, Issue 1, pp. 63-108.

[Klein, 2002] Klein, Jon, “Breve: a 3D simulationenvironment for the simulation of decentralizedsystems and artificial life”, Proceedings of Arti-ficial Life VIII, the 8th International Conferenceon the Simulation and Synthesis of Living Sys-tems, MIT Press.

[Lasser & Omohundro, 1986] Lasser, Clifford;Omohundro, Stephen M.; The Essential Star-lisp Manual, Thinking Machines Corporation.

[Lechner, Watson, Wilensky & Felsen, 2003]Lechner, Thomas; Watson, Ben; Wilensky,Uri; and Felsen, Martin. “Procedural Mod-eling of Land Use in Cities”. Proceedings ofMidgraph.

[Minar, Burkhart, Langton & Askenazi, 1996]Minar, Nelson; Burkhart, Roger; Langton,Chris; and Askenazi, Manor; “The SwarmSimulation System: A Toolkit for Building

Multi-agent Simulations.” Santa Fe Instituteworking paper 96-06-042.

[Papert, 1980] Papert, Seymour, Mindstorms:Children, Computers, and Powerful Ideas, BasicBooks.

[Repenning, Ioannidou & Zola, 2000] Repenning,Alexander; Ioannidou, Andri; and Zola,John; “AgentSheets: End-User ProgrammableSimulations”, Journal of Artificial Societies andSocial Simulation vol. 3, no. 3.

[Resnick, 1994] Resnick, Mitchel, Turtles, Termitesand Traffic Jams: Explorations in MassivelyParallel Microworlds, MIT Press.

[Resnick, 1996] Resnick, Mitchel, “Beyond theCentralized Mindset”, Journal of the LearningSciences 5(1): 1-22.

[Resnick & Wilensky, 1993] Resnick, Mitchel; andWilensky, Uri, “Beyond the Deterministic,Centralized Mindsets: New Thinking for NewSciences”, American Educational Research As-sociation.

[Richmond & Peterson, 1990] Richmond, Barry;and Peterson, Steve. STELLA II. HighPerformance Systems, Inc.

[Wilensky, 1995] Wilensky, Uri, “Paradox, Pro-gramming and Learning Probability”, Journalof Mathematical Behavior Vol. 14, No. 2, p 231-280.

[Wilensky, 1997] Wilensky, Uri, StarLogoT, Cen-ter for Connected Learning and Computer-Based Modeling, Northwestern University.http://ccl.northwestern.edu/cm/starlogot/

[Wilensky, 1999] Wilensky, Uri, NetLogo(and NetLogo User Manual), Centerfor Connected Learning and Computer-Based Modeling, Northwestern University.http://ccl.northwestern.edu/netlogo/

[Wilensky, 2002] Wilensky, Uri, “Modeling Na-ture’s Emergent Patterns with Multi-agent Lan-guages”, Proceedings of EuroLogo 2002.

16

[Wilensky, 2003] Wilensky, Uri, “Statistical Me-chanics for Secondary School: The GasLabMulti-Agent Modeling Toolkit”, InternationalJournal of Computers for Mathematical Learn-ing, Volume 8, Issue 1, special issue on agent-based modeling.

[Wilensky & Reisman, in press] Wilensky, Uri;and Reisman, Kenneth; “Thinking Like a Wolf,a Sheep or a Firefly: Learning Biology throughConstructing and Testing ComputationalTheories”, Cognition & Instruction.

[Wilensky & Resnick, 1999] Wilensky, Uri; andResnick, Mitchel; “Thinking in Levels: A Dy-namic Systems Approach to Making Sense of theWorld”, Journal of Science Education and Tech-nology, vol. 8, no. 1.

[Wilensky & Stroup, 1999a] Wilensky, Uri; andStroup, Walter; “Learning through Participa-tory Simulations: Network-based Design for Sys-tems Learning in Classrooms”, Proceedings ofthe Computer Supported Collaborative Learn-ing Conference, Stanford University.

[Wilensky & Stroup, 1999b] Wilensky, Uri; andStroup, Walter; HubNet. Center for ConnectedLearning and Computer-Based Modeling,Northwestern University.http://ccl.northwestern.edu/netlogo/hubnet.html

17