netlogo design and implementation

Upload: sunayana-jayaram

Post on 06-Mar-2016

29 views

Category:

Documents


1 download

DESCRIPTION

NetLogo Design and Implementation

TRANSCRIPT

  • 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 andplay 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 K12settings (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 ve years of development, NetLogois a mature product that is stable and reliable. It isfreewareanyone 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-nding and optimization,networks, markets, chaos, self-organization, articialsocieties and articial life. The models all share ourcore themes of complex systems and emergence.

    In the following sections, we oer 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: NetLogos user interface, with model Dif-fusion Limited Aggregation

    2.1 User interface

    Figure 1 shows NetLogos user interface after openingand running a model from the Models Library.

    On the right is the graphics window, in which theworld of the model is made visible. In the modelshown, the turtles represent diusing 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 NetLogos In-terface tab. The Interface tab is also an interfacebuilder. No rm distinction is made between using amodel and editing ityou 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 xed.

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

    Figure 2 shows the Procedures tab containing thecomplete code for the model. Language elements areautomatically color-coded so the codes 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 le. 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 models 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 remodel. Based on the experiment setup entered by theuser, BehaviorSpace automatically runs the modelmany times while varying the density parameter.The results show the eect 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 remodel. 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 nore 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 werent possiblebefore is the use of turtles to represent both nodesand edges in a network as in Figure 4.

    Signicant 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. Weve devoted almost as muchdevelopment eort to our Models Library as to theNetLogo application.

    The Models Library contains more than 150 pre-built simulations that can be explored and modied.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 nd 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 NetLogos history andhow it came to be a tool for both education and re-search, and we explain the benets 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 Logos philosophy of ease ofuse, providing a low threshold of entry for newusers. From StarLisp, a parallel Lisp of the 1980s,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-LogoTs 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 nd it easy to get started. No ceil-ing means the language shouldnt be limiting for ad-vanced users. We wanted NetLogo to be just as pop-

    1There were several dierent early implementations of Star-Logo in the rst part of the 1990s. 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 signicant attention to the no ceil-ing side of the principle. Logos reputation as alanguage for schools doesnt do justice to its amplepower, as demonstrated in [Harvey, 1997].

    We believe researchers should care about lowthreshold too. Even for such users, NetLogos in-heritance from educational languages brings severalbenets. 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 benets. 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 eectively communicate their re-sults to others, verify each others results, and buildupon each others work. The goals of scientic mod-eling are compromised if programs are long, cryptic,and platform-specic. A NetLogo model is less likelyto suer 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, wasrened 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 dierentapproach; 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 dicultyof programming in Java or C++ isnt due only tothe language itself. Its 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 highevenbefore they start dealing with the diculties of thelanguages themselves.

    In contrast, the NetLogo environment allows asmooth, almost unnoticeable transition from explor-ing existing models into programming. NetLogosuser interface makes no rm 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 modelsrules is only as far away as a click on the Procedurestab.

    3.4 Development history

    NetLogo has been under development since 1999.Since then weve 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 anal 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 versionsour users now nd 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. Trac on the discussion group hasincreased vefold since 2002. Several organizationshave independently conducted workshops on NetL-ogo for both researchers and teachers. In the summer

    of 2004, we held our own rst 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 isnt limited to graphical applica-tions, it is best known for its turtle graphics, inwhich a virtual being or turtle moves around thescreen drawing gures 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. Dierent breeds of turtle may be dened,and dierent 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 sitesthey are square sections of a continuoustwo-dimensional space. Turtle coordinates are oat-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 y, 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 NetLogos 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 oatingpoint math are supported. The run and runresultcommands can be used to execute code constructedon the y.

    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 dierences 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 doesnt 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 cant de-ne 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.NetLogos 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 NetLogos descent from StarLogoT,which as discussed above needed to be very lean.Many of StarLogoTs limitations have already beenaddressed in NetLogo (for example, NetLogo hasagentsets and double-precision oating point math),but some of the leanness remains. This leannessis not only historical, though. Eciency 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 denition of newspecial forms may actually be desirable for a lan-guage in which readability and sharing of code isparamount. We weigh these tradeos carefully as wecontinue to expand the language.

    4.3 Reproducibility

    One of our core design goals for NetLogo is that re-sults be scientically 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. Javas 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 orall-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 doesnt suit a users needs, then that userwont be able to use any of the components, becausetheyre all tied together.

    We want to avoid this all-or-nothing trap by let-ting users extend or replace parts of NetLogo thatdont suit their purposes. That way even users whohave unique needs, or just needs we didnt think ofor havent gotten around to addressing yet, can buildwhat they need themselves in Java, and they will stillget the benet of the rest of our work. These newAPIs are steps towards that goal. They lift the ceil-ing on NetLogos 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 exible, but much harder to use).

    5.1 Extensions API

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

    programmers 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 dierent 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 benet from their eorts.

    5.2 Controlling API

    We also oer 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-iorSpaces present capabilities arent sucient.

    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 runheadless from the command line. (On X11-basedsystems, it is possible right now to work around thislimitation using X11s virtual framebuer 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 StarLogoTs 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 todays standards was absurdlyunderpowered. Putting thousands of agents on suchmachines was only possible if the underlying enginewas written in assembly language, which is of courseplatform-specic.

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

    StarLogoTs language design was constrained aswell by what could reasonably be implemented. Theneed for eciency led StarLogoTs architecture to be-come quite complicated. It included three dierentvirtual machines for our three agent types (observer,turtles, and patches). Dierent agent types had dif-ferent capabilities and dierent 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 doesnt 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 itwouldnt matter too much. The issue of speed is dis-cussed further below.

    Using Java oered the additional benet 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 eort.)

    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 tradeos 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 wouldnt nd 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 dicult to nd de-velopers used to working within the limitationsof the antiquated version.

    More recent VMs are higher quality. Before weabandoned Java 1.1, constantly working aroundbugs in the various 1.1 VMs was a serious dragon our development eorts.

    10

  • Unlike Java 1.1, Java 1.4 oers 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 nally released a highquality Java 1.4 implementation for Mac OS X.

    Even with the new VM, Apples 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 tooer support and bugxes for NetLogo 1.3, so thoseusers arent 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 nd NetLogo fast enough for most pur-poses. Nonetheless, we plan to continue to improveNetLogos speed, since agent-based modeling is a eldin which users always benet 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 exible and feature rich than StarLogoT. There-fore, you would expect NetLogo to be slower. Surpris-ingly, that isnt 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-ogoTs 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 dierent machines was slow. With simpler codeand more turtles and patches, overall speed benetedmore from the speed of the turtle and patch virtualmachines. In contrast, NetLogos 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 benet associated with large numbers ofagents.

    NetLogo is a hybrid compiler/interpreter. To im-prove performance, we dont interpret the users codedirectly. Instead, our compiler analyzes, annotates,and restructures it into a form that can be interpretedmore eciently.

    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 proling 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 VMsown 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 proling the engine code andaddressing ineciencies in object creation, memoryusage, and other areas.

    If we want to further increase NetLogos speed inthe future, the most promising approach, relative tothe likely development eort 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 isnt alwaysslower than C code anymore, so were not certain ifthis approach would be fruitful.

    So far we have been discussing the speed of Net-Logos core computational engine. But NetLogosoverall performance doesnt depend only on enginespeed. Theres also graphics speed to consider.Whether engine speed or graphics speed dominatesvaries widely from model to modelsome are 90%engine, others are 90% graphics. The latter kindof model can always be sped up by using NetL-ogos graphics control strip to temporarily shut ographics altogether, but that doesnt 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 oscreen buer, is not sup-ported under Swing, and on Mac OS X, the perfor-mance of painting oscreen 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 NetLogosgraphics capabilities enormously. Previously, in or-der to make incremental updates possible, the graph-ics window was limited in several important respects.Even though NetLogos 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 rst 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 dont 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; theycant really move simultaneously. So the engine con-text switches from agent to agent after each agenthas performed some minimal unit of work, called aturn. 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 dierent 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 rst job hashad a turn. Here, the NetLogo engine is taking on atask more typically associated in computer scientistsminds 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. Were not sure weve arrived at nal decisionson how best to support it. Were 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 dierent 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 dontwant wrapping use the outer layer of patchesas a barrier. In a future version, we plan tomake wrapping a global option which can beturned o. 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 cantcurrently be made as concise as we would like.

    Easier, more exible 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 proling 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 nite dierence enginetechnology into NetLogo so that researchers and stu-dents can investigate systems using agent-based andaggregate techniques in tandem.

    There are ongoing eorts within our research groupto further explore NetLogos potential for researchand education. Of particular relevance to NetLogosfuture 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 eects 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 ofNetLogos ability to support large, ambitious model-ing eorts. 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. 13, 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 articial life, Proceedings of Arti-cial Life VIII, the 8th International Conferenceon the Simulation and Synthesis of Living Sys-tems, MIT Press.

    [Lasser & Omohundro, 1986] Lasser, Cliord;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 Articial Societies andSocial Simulation vol. 3, no. 3.

    [Resnick, 1994] Resnick, Mitchel, Turtles, Termitesand Trac 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-tures 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 Firey: 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