• Keine Ergebnisse gefunden

Linking NetLogo and R

III.2.3. New Primitives

III.2.3. New Primitives

NetLogo’s programming language consists of a large number of commands, or "primitives".

Our R extension adds only nine primitives (see documentation in Appendix C and Table III.1) and six additional primitives for debugging (see Table III.2). The new primitives provide means for sending data from NetLogo to R and vice versa, for evaluating any R command (with the exception mentioned above) and for observing the processes.

TableIII.1.:Primitives(=NetLogocommands)oftheR-ExtensionofNetLogo. PrimitiveDescriptionExample clearClearstheRworkspace,deletesallvari- ables.

r:clear evalEvaluatesthesubmittedstringinR,used forRfunctionwithoutareturnvalue.

;;createnewvectorxinRwithasequence from1to10: r:eval"x<-seq(1,10)" ;;loadanRpackage: r:eval"library(spatstat)" getGetsavaluefromR;eithersubmitsa stringincludinganRfunctionwithre- turnvalue,orgetsthevalueofavari- able;returnvaluescanbestrings,num- bers,booleans,lists,oralistoflists.

;;getvalueofvariablex: r:eval"x<-seq(1,10)" printr:get"x" ;;savetenrandomvaluesfrombinomial distributioninnewlocalvariableb: letbr:get"rbinom(10,1,0.5)" printb putCreatesanewvariableinRwithvalue(s) fromNetLogo;submittedvalues/variables canbestrings,numbers,booleans,orlists (NetLogolistsbecomeRvectors,tocreate Rlistsseeputlist).

;;createanRvariabler_varcontaining thevalueofNetLogovariableb: letb12.95 r:put"r_var"b ;;createanRlistr_turtcontainingthe sizeofallturtles: r:put"r_turt"[size]ofturtles

putagentCreatesalistinRfromvariablesofaset ofNetLogoagents;collectionsofagent- variablescanbestoredinasinglenamed list.

;;createanRlistr_patchcontainingthe pxcorofpatches: r:putagent"r_patch"patches"pxcor" ;;createanRlistr_turtlescontaining thevaluesofthevariableswho,sizeand colouroftheturtles(agentset)witha valueofwholessthanfive: (r:putagent"r_turtles"turtleswith[who< 5]"who""size""color") printr:get"r_turtles" printr:get"r_turtles$who" putagentdfSameasputagent,butcreatesanRdata- frameinsteadofalistbecausemanyR functionsrequiresdataframesasinput.

;;createanRdata-framer_patch containingthepxcorandpycorofpatches andshowthatr_patchisadata-frame: (r:putagentdf"r_patch"patches"pxcor" "pycor") printr:get"class(r_patch)" putlistCreatesanewRlistbasedonthesubmit- tedNetLogovariablesandvalues.

;;createanRlistr_listcontainingthe valuesofNetLogolistb: letb[12.951011.3] r:putlist"r_list"b ;;createanRlistr_listwiththree columns: (r:putlist"r_list"b[35]4.5) printr:get"r_list[1]" putnamedlistSameasputlist,butcreatesanamedR list,i.e.,thecolumnsofthelistcanbe calledviatheirnames.

;;createanamedRlistr_listwiththree columns: (r:putnamedlist"r_list""col1"b"col2"[3 52]"col3"4.5) printr:get"r_list$col1"

putdataframeSameasputnamedlist,butcreatesanR data-frameinsteadofalistbecausemany Rfunctionsrequiredataframesasinput.

;;createanRdata-framer_dfwith3 columns: (r:putdataframe"r_df""col1"[425] "col2"[352]"col3"4.5) printr:get"class(r_df)"

TableIII.2.:Additionalprimitives(=NetLogocommands)oftheR-ExtensionofNetLogofordebugging. PrimitiveDescriptionExample interactiveShellOpenstheunderlyingRshell,ifNetLogo wasstartedfromaconsole/shell.

;;starttheRshell: r:interactiveShell messageWindowOpensamessagewindowtodisplayde- buggingmessages(seestartDebugand startJRIDebug).

;;openamessagewindow: r:messageWindow startDebugStartsthedebuggingmodeoftheRex- tension.Theresultsofevalandgetcom- mandswillbedisplayedintheConsole, interactiveShellorMessageWindow.

;;startthedebuggingmode: r:startDebug startJRIDebugStartsthedebuggingmodeoftheunder- lyingJRIlibrary(oftherJavapackage). DisplaysthemessagesintheConsole,in- teractiveShellorMessageWindow.

;;startthedebuggingmodeoftheJRI library: r:startJRIDebug stopDebugStopsshowingdebuggingmessagesof theRextensionintheConsole,interac- tiveShellorMessageWindow.

;;stopshowingdebuggingmessages: r:endDebug stopJRIDebugStopsshowingdebuggingmessagesofthe underlyingJRIlibraryintheConsole,in- teractiveShellorMessageWindow.

;;stopshowingdebuggingmessagesofthe JRIlibrary: r:endJRIDebug

III.2.4. Examples

Three examples illustrate how our R-Extension of NetLogo can be used. The NetLogo pro-gram code in the listings contains only the parts where the R-Extension is used. The com-plete programs are provided in the examples folder of our R-Extension of NetLogo.

In the first example, (Listing III.2) the R-Extension is used in thesetupprocedure to get random values from a Beta and a Weibull distribution, which are not available in NetLogo.

In thegoprocedure the correlation coefficient (Spearman’s rho) between the turtle’s weight and height variables is calculated and plotted.

Listing III.2: Example 1: Random values and Spearman’s rho (correlation).

extensions [r]

turtles-own [weight height]

to setup ...

;; create turtles with weight and height randomly chosen from Weibull and Beta distribution

;; create R list from turtles

(r:putagent "turtles" turtles "weight" "height")

;; calculate correlation between weight and height

r:eval "c <- cor.test(turtles$weight,turtles$height, method = 'spearm', alternative = 'g'"

let rho r:get "c$p.value"

let p r:get "c$estimate"

...

end

The second example makes use of the R package adehabitat [Calenge, 2006] (List-ing III.3). Three animals move for 100 time steps and the points visited are stored in a list. These lists are transformed into an R data-frame, which is used for the home range analysis. The points of vertices of the home range polygons are sent back to NetLogo and plotted for visualization. In a second step, the adehabitat package is used to calculate the size of the home range area depending on different home range levels, i.e., the percentage of removed locations for the estimation of the home range polygon. The higher the level, the lower the removal percentage (see documentation of adehabitat package for details).

The results are visualized in a NetLogo plot (Figure III.6).

(a) (b)

(c)

Figure III.6.: Using R functionmcpfrom package adehabitat to calculate home ranges from animal movement data generated by a NetLogo model. (a): movement path of three animals; (b): home ranges as determined by the R package adehabitat for home range level=95, i.e., 5% of the visited locations have been removed for the home range estimation; (c): area of the estimated home range polygons at different home range levels (the higher the level, the lower the percentage of removed locations farthest away from the barycenter of the home range; see documentation of adehabitat package for details).

Listing III.3: Example 2: Home Range Analysis with NetLogo and R.

;; merge the Name-, X- and Y-lists of all animals to one data-frame

ask animals [

(r:putdataframe "turtle" "X" X "Y" Y)

r:eval (word "turtle <- data.frame(turtle, Name = '" Name

"')")

r:eval "turtles <- rbind(turtles, turtle)"

]

;; split the data-frame into coordinates and factor variable r:eval "xy <- turtles[,c('X','Y')]"

;; get the points of the home range polygon for the current animal

r:eval (word "temp <- subset(homerange, ID=='"Name"')") let tempX r:get "temp$X"

let tempY r:get "temp$Y"

let tempXY (map [list ?1 ?2] tempX tempY) ...

let precincre 5

;; calculate the size of the home range depending on home range level

r:eval (word "area <- mcp.area(xy, id, unout='m2', percent = seq(" precstart ",100, by = " precincre "), plotit=FALSE)") ...

end

In the third example we used the R package spatstat [Baddeley and Turner, 2013] to analyse spatial point patterns. It is possible to calculate the L-function (based on Ripley’s K) for the spatial distribution of the turtles for every time step of the simulation together with the theoretical Poisson function and confidence bands of Complete Spatial Randomness (CSR) from Monte-Carlo-Simulations (Listing III.4). In the setup procedure, turtles are created with random positions. In each simulation step (goprocedure) turtles move around randomly. The new positions are sent to R into a data-frame and are transformed into a point pattern. The L-function is then calculated for this point pattern and the results are sent back to NetLogo, where they are transformed and plotted. For illustration purposes we created three extreme scenarios directly in thesetupprocedure (Figure III.7).

Listing III.4: Example 3: Point pattern analysis with NetLogo agents.

extensions [r]

to setup ...

;; load R package spatstat for spatial statistics r:eval "library(spatstat)"

...

end to go

...

;; send agent variables into an R data-frame

(r:putagentdf "agentset" turtles "who" "xcor" "ycor")

;; create point pattern with vectors of x- and y-coordinates of turtles and the dimensions of the window/world

let revalstring (word "agppp <- ppp(agentset$xcor, agentset$ycor, c(" min-pxcor "," max-pxcor "), c("

min-pycor "," max-pycor "))") r:eval revalstring

;; calculate L-function with simulation of goodness-of-fit envelope

r:eval "Lsim <- envelope(agppp, Lest)"

;; get results from R let r r:get "Lsim$r"

let obs r:get "Lsim$obs"

(a) (b)

(c) (d)

(e) (f)

Figure III.7.: Using R functionsLestandenvelopefrom the package spatstat to calculate the L-function (based on Ripley’s K) with confidence envelopes of three differ-ent point patterns (spatial distributions of turtles in a NetLogo model). On the left the analysed point patterns are shown, on the right side the plots of the corresponding L-functions (values of L(r) vs. different radii r). The L-function was calculated using R and plotted with NetLogo. The area between the dark grey lines marks the 98% confidence envelope of the L-function under com-plete spatial randomness (CSR) calculated from 99 Monte-Carlo-Simulations;

the light gray line shows the theoretical L-function under CSR; the black line shows the L-function for the observed pattern. (a): turtles are distributed ran-domly in space using uniformly distributed random values; (b): the values of the L-function for the spatial distribution of the turtles do not deviate from the envelope of the CSR at almost all distances (r), i.e., there is no significant deviation from CSR ; (c): nearly regular distribution of turtles; (d): there are significant differences to CSR with a tendency to regularity (obs < theo) espe-cially at short distances, whereby the steps of the function values correspond to the horizontal, vertical and diagonal distances between the turtles; (e): turtles are clustered; (f): the black line (obs) shows a significant deviation from the CSR envelope with a tendency to aggregation (obs > theo) over all radii.

let theo r:get "Lsim$theo"

Both NetLogo and R are powerful tools with growing user communities. In the fields of agent-based modelling and statistics, respectively, they are increasingly considered as stan-dard software platforms. Combining these tools to tackle environmental and ecological problems provides many benefits. NetLogo users can utilize the power of R without need-ing to communicate via data files. This offers new and fascinatneed-ing opportunities to analyse agent-based models interactively and to implement submodels of, for example, delineating home ranges that are then sensed by the model animals. R users, on the other hand, may be motivated to use NetLogo in cases where R is too limited to implement full-fledged ABMs [Petzoldt and Rinke, 2007].

Our R extension requires users to be familiar with both NetLogo and R, but does not add further complexity. The interface created by our extension consists of only additional nine NetLogo primitives (six additional for debugging), dealing with the communication between NetLogo and R via data and with calling R functions. Our extension will require future updates since the implementation and overall rationale of R and, in particular, NetLogo are continually changing. We will of course attempt to perform these updates ourselves, but since our extension is based on open-source Java code, this process does not depend on us.

III.2.6. References

A. Baddeley and R. Turner. Package ’spatstat’ Manual. R package version 1.35-0, 2013. URL http://cran.r-project.org/web/packages/spatstat/. (last accessed 2014/01/06).

F. Bousquet and C. Le Page. Multi-Agent Simulations and Ecosystem Management: A Re-view. Ecological Modelling, 176:313–332, 2004.

C. Calenge. The Package ’adehabitat’ for the R Software: A Tool for the Analysis of Space and Habitat Use by Animals. Ecological Modelling, 197:516–519, 2006.

V. Grimm. Visual Debugging: A Way of Analyzing, Understanding, and Communicating Bottom-Up Simulation Models in Ecology. Natural Resource Modeling, 15:23–38, 2002.

V. Grimm. Individual-Based Models. In S.E. Jørgensen, editor, Ecological Models, pages 1959–1968. Elsevier, Oxford, 2008.

V. Grimm and S.F. Railsback. Individual-Based Modeling and Ecology. Princeton University Press, Princeton, N.J., 2005.

G. Huse, J. Giske, and A.G.V. Salvanes. Individual-Based Modelling. In P.J.B. Hart and J. Reynolds, editors, Handbook of Fish and Fisheries, pages 228–248. Blackwell, Oxford, 2002.

D.C. Parker, S.M. Manson, M.A. Janssen, M.J. Hoffmann, and P. Deadman. Multiagent