# Modelling: Conway’s Game of Life Implemented in R Figure 1. Several iterations of the algorithm, beginning from a randomly determined initial position.

By Allan Roberts

The R script provided below implements J.H. Conway’s “Game of Life” algorithm on an 8 by 8 grid. In this model, cells persist and propagate according to how many neighbours they have (including perpendicular and diagonal neighbours). A cell persists if it has either  2 or 3 neighbours, and empty cells become occupied if they have exactly 3 neighbours. This set of rules might be thought of as mimicking a single species population with density-related effects. Note that, in the final stable distribution shown in Figure 1, each green square is adjacent to either 2 or 3 other green squares.

Reference

Game of Life. Wolfram Mathworld:  http://mathworld.wolfram.com/GameofLife.html

R Script

#An implementation of J.H. Conway’s ‘Game of Life’ algorithm.
#Implemented by A. Roberts, May 2013

Life.Example = function(){
neighbours = function(M){
if (!is.matrix(M)) return(NULL);
m = dim(M);
n = dim(M);
left = cbind( rep(0,m), M[ ,1:(n-1)]);
right = cbind(M[ ,2:n], rep(0,m));
up = rbind( rep(0,n), M[1:(m-1),]);
down = rbind( M[2:m,], rep(0,n));
upper.right = M[1:(m-1),2:n];
upper.right = rbind(rep(0,n-1),upper.right);
upper.right = cbind(upper.right,rep(0,m));
lower.right = M[2:m,2:n];
lower.right = rbind(lower.right, rep(0,n-1));
lower.right = cbind(lower.right, rep(0,m));
lower.left = M[2:m,1:(n-1)];
lower.left = cbind(rep(0,n-1),lower.left);
lower.left = rbind(lower.left, rep(0,m));
upper.left = M[1:(m-1),1:(n-1)];
upper.left = rbind(rep(0,n-1),upper.left);
upper.left = cbind(rep(0,m),upper.left);

N =up+down+right+left+upper.right+lower.right+lower.left+upper.left;return(N);
}

N2 = function(M){
m = dim(M);
n = dim(M);
N2 = (neighbours(M)==2);
N2 = as.numeric(N2);
dim(N2) = c(m,n);
return(N2);
}

N3 = function(M){
m = dim(M);
n = dim(M);
N3 = (neighbours(M)==3);
N3 = as.numeric(N3);
dim(N3) = c(m,n);
return(N3);
}

update = function(M){
return( N3(M) + N2(M)*M);
}

random.setup = function(n){
M = matrix(sample(c(0,1),n*n,replace=TRUE),n,n);
return(M);
}

M = random.setup(8);
plot.new();
par( mfrow=c(4,4),mar=c(1,1,2,2));
for (i in 1:16){
M=update(M);
image(M,col=c(rgb(1,1,1),rgb(0,0.5,0)),axes=FALSE,frame=TRUE);mtext(side=3,paste(quote(iteration),i-1));
}
}
Life.Example();

# Logistic Growth Model with R

Models like the discrete logistic growth model are famous for producing complex behaviour from simple equations. You can cut and paste the R script provided below onto the R command line, to produce a graph like the one given Figure 1. Try varying the parameter r to see what happens; for example, to set the parameter r to 1.5, enter the following:

> LogisticGrowthExample( r = 1.5 );

References

Logistic Equation. Wolfram Mathworld: mathworld.wolfram.com/LogisticEquation.html
Logistic Map. Wikipedia: en.wikipedia.org/wiki/Logistic_map

R Script

#NOTE: You will need to replace the right and left quotation marks with
#straight quotes before running this script in R.

LogisticGrowthExample <- function(r = 3.7, N0 = 0.1, steps = 100){
#Implemention by Allan Roberts, March 2013.

N <- numeric(steps);
N <- N0; #the initial population

Next <- function(N) {N <-  N + (r-1)*N*(1-N)};
for (i in 2:(steps)) N[i] <- Next(N[i-1]);

plot(N~seq(0,(steps-1)),type=”l”,xlab=quote(time), ylim=c(0,1.5), las = 1 );
title(main=”Discrete Logistic Growth Model”, font.main=1, cex.main=2);
}

LogisticGrowthExample( );

# Fractals with R, Part 2: the Sierpiński Carpet

by Allan Roberts

This post is a variation on the previous post, Fractals with R. Here it is shown how a different fractal pattern can be produced by just a slight variation in the R script; the result is an iteration of a fractal called the Sierpiński Carpet. The method used here is basically the same as that described in Weisstein (2012). Below is the R script that produces the image. Figure 1. An iteration in the construction of the Sierpiński Carpet, which I produced using R.

This fractal is an example of a pattern with both large and small patches. There are also distributions in ecology which are patchy across scales; see, for example Levin (1992). You might find the Sierpiński Carpet somewhat reminiscent of a fragmented eelgrass bed, or a distribution of mussels and barnacles in the intertidal.

From the point of view of handling data structures, this Sierpiński Carpet plot is an exercise in using the “rbind” and “cbind” functions in R, which allow you to aggregate matrices and data frames. I’ve found these functions useful for working with oceanographic data, such as that plotted in my posts on how to plot NEPTUNE Canada data and VENUS network data. For more, see Fractals with R, Part 3.

R Script

IterateCarpet <- function(A){
B <- cbind(A,A,A);
C <- cbind(A,0*A,A);
D <- rbind(B,C,B);
return(D);
}

S <- matrix(1,1,1);
for (i in 1:5) S <- IterateCarpet(S);

image(S,col=c(0, 12), axes=FALSE);

References

Levin, Simon A., 1992. The Problem of Pattern and Scale in Ecology:  The Robert H. MacArthur Award Lecture. Ecology, 73 (6), 1992, pp. 1943-1967.

R Development Core Team, 2011. R: A language and environment for statistical computing. R Foundation for Statistical Computing, Vienna, Austria.

Weisstein, Eric W. “Sierpiński Carpet.” From MathWorld– A Wolfram Wed Resource Accessed Oct. 22, 2012: http://mathworld.wolfram.com/SierpinskiCarpet.html

# Oceanographic Data with R: Plot VENUS Network Data

By Allan Roberts

1.1 Go to the VENUS network website:                                     www.venus.uvic.ca 1.2 If you already have an account click on “LOGIN.” (Note: If you have a NEPTUNE Canada account you can use the same e-mail and password to log into the VENUS site.) If you don’t have an account, click on “Register”:  1.4 Under “Search Type” choose “Stationary Platform”: 1.5 Under “Stationary Platform Data” choose “Search by Instrument”: 1.6 There are gaps in the data record; for this example, I’ve chosen the last two weeks of August, 2012, as an example of a particular interval with available data. Under “Time Range” set the starting and ending date and time, and then click on “Search Active Locations”: 1.7 Under “Location” choose “Saanich Inlet”, “Central Node”, and “VIP-17.” I found these to be the default settings. 1.8 Under “Instrument” choose “Aanderaa Optode 4175 (S/N 1684).” (Again, I found this to be the default setting.) 1.9 Under “Sensor(s)” choose “Temperature”: 1.10 Under “Processing” choose “No Averaging”: 1.11 Under “Data Format” choose “Comma Separated Value Text File”: 1.12 Leave “Metadata” (i.e. documentation) at the default setting of “FGDC HTML”, and click on “Search now”: 1.13 Wait …. 1.14 Click on the text file…. … you should get something like this: 1.15 Here is one place where I found that downloading VENUS data differed a bit from downloading NEPTUNE data. For the VENUS data, I’ve found that the following works: Copy and paste the downloaded data into a Word file, and then save that file as a plain text file. The plain text file is readable from R. To copy the VENUS data, click on “Select All” … … then click on “Copy”: 1.16 Paste the file into a Word document. Click on “Save As”; make the document name “VENUS data example”; make the location your desktop, and make the format “Plain Text”: When you save as a text file you may get the following warning. (The idea of saving as a text file is that we are not interested in fancy formatting, pictures, etc., we are only interested in the data.) Click “OK”. The result should be a “.txt” file called “VENUS data example” on your desktop: 1.17 Create a new folder, called “VENUS network data”, and drop the text file “VENUS data example” into this folder. Now that you have the VENUS data saved as a “.txt” file in your “VENUS network data” folder, you are ready to move onto the next step: reading the data file into R.

Step 2. Read the data file into R

The steps for changing the working directory are the same as in the NEPTUNE data tutorial:

2.1 In the R console type “getwd( )”. This will tell you what your current working directory is: 2.2 If you are on a Mac click on “Misc”, and choose “Change Working Directory”: If you are on a PC, click on “File”, and choose “Change dir …”: 2.3 If you are on a Mac, browse for the “VENUS network data” folder, click on it, and click on “Open”; if you are on a PC browse for the “NEPTUNE data” folder, click on it, and click on “OK.”

2.4 In the R console, type “getwd( )”; the “VENUS network data” folder should now be your working directory: 2.5 Open the text file, and look at it. We want to skip all the documentation lines before the first line of data. For this example, there should be 15 lines. This includes the line with the variable names. (The variable names are not yet formatted for R; variable names in R need to be without spaces.) 2.6 Check the downloaded data by entering “head(data)”; this will show the first few lines of the data frame. (To see all the data, just type ”data”, and press enter.) 2.7 To give names to the columns, type: Enter “head(data)” again, and you should see names at the tops of the columns. (For this tutorial, we are not concerning ourselves with the flag variable in the third column.) Step 3. Plot the data

3.1 For a rough plot of the data, type:  3.2 To plot the data as a line graph with a title, and with better axis labels, we can use two steps. First: The following command will plot the data without axis labels, and make the graph a line graph in blue. Second: Leave the graphics window open, and enter a command to add the title and axis labels. You should get a graph like the one below. I’ve found that the easiest way to put a graph made in R into a written document or slide show is to click on the graphics window and then use copy and paste. 3.3 Now go explore the other data available from the VENUS network!

Citations

VENUS, 2012. Website. Last accessed Oct. 17, 2012: www.venus.uvic.ca

R Core Team (2012). R: A language and environment for statistical computing. R Foundation for Statistical Computing, Vienna, Austria.

# Fractals with R

by Allan Roberts

Many biological objects have structure that, at least at a glance, may appear rather fractal-like. A brief discussion of the applicability of fractals and fractal dimension to biology can be found in Vogel’s ‘Comparative Biomechanics‘ (2003, pp. 84–86). While noting that there seem to be few truly fractal objects in biology, Vogel speculates, “I think, […], that sponges may be fractal, with large ones organized mainly as foldings and refoldings of proliferated small ones, thereby making transitions between the organizational grades we learned as ascons, sycons, and leucons” (p. 86). Figure 1. Four iterations in the construction of a Sierpinski triangle-like object. I produced these graphics using the statistical programming language R (R Development Core Team, 2011).

I’ve included an image, representing the construction of a fractal largely similar to a famous fractal, the Sierpiński triangle. A mathematical description of the Sierpiński triangle can be found in Vejnar (2012). (In contrast to the actual Sierpiński triangle, my example is based on right-angled triangles, rather than on equilateral ones.) These images were produced using the statistics application and programming language R (R Development Core Team, 2011). I’ve also included the R script that I used to produce the graphics. For more, see Fractals with R, Part 2.

```R Script
IterateTriangle <- function(A){
B <- cbind(A,0*A);
C <- cbind(A,A);
D <- rbind(B,C);
return(D);
}

par(mfrow=c(2,2))
for (i in 1:4){
T <- matrix(1,1,1)
for (i in 1:i) T <- IterateTriangle(T);
image(T,col=c("white","black"),axes=FALSE);
text(0,1,i,col="black")
}```

References

R Development Core Team, 2011. R: A language and environment for statistical computing. R Foundation for Statistical Computing, Vienna, Austria.

Vejnar, Benjamin. 2012. A topological characterization of the Sierpiński triangle.       Topology and its Applications, 159 (5), 1404-1408.

Vogel, Steven. 2003. Comparative Biomechanics: Life’s Physical World. Princeton University Press: Princeton, New Jersey.

# Book review – ‘More’ (a mathematical biology perspective)

by Allan Roberts

Book Discussed: Springman, I.C. (writer), Lies, Brain (illustrator). More. Houghton Mifflin Harcourt Publishing Company: New York, New York.

If you’re a student of biology you might have noticed a general lack biological accuracy in how animals are represented in children’s cartoons and literature. One thing that impressed me about the children’s book ‘More’ was the general phenotypic correctness of the main character, a bird. Or to be specific, a black-billed magpie (Pica hudsonia).

The storyline is structured around the magpie amassing an ever-greater collection of haphazard objects. The things that the bird collects include an intriguing assortment of cultural artifacts: tokens from board games (Scrabble, Monopoly, chess), a shopping list, pencils (HB and 2H), a pocket knife, a comb, a cassette tape labeled “THE WALL.” Objects perhaps reminiscent of a typical cluttered kitchen drawer of odds and ends.

Also interesting, from the ornithological perspective is that the bird has an identification number printed on a leg band.

What’s the identification number of the bird in the book ‘More’ ?

Because individual pictures offer only partial glimpses of the identification number, it is difficult to reconstruct the number with absolute certainty. However, the number begins with 31415 : the first few digits of pi.

Yup. It’s a mag-π. Credit: David Herr. Photo Source: USDA Forest Service “Find-a-Photo” site: https://fsplaces.fs.fed.us/fsfiles/unit/wo/wfrp/find_a_photo.nsf/