chapter six - phys.ubbcluj.ro

22
Modeling-Science June 3, 2008 Chapter Six Explicit Algorithms and Visualization “Not only in research but also in the everyday world of economics and politics we would all be better off if more people realized that simple nonlinear systems do not necessarily possess simple dynamical properties.” Robert May We describe models that can be evolved with explicit (non differential equation based) algorithms using examples in one and two dimensions. We introduce new EJS objects and show how to access these objects from within EJS. We also show how to create and use arrays. 6.1 GEOMETRIC MAP Figure 6.1: A data table showing a population P growing at the fixed rate r. A growth rate of r =0.1 causes the population to double in seven generations. Imagine a population of insects that lays eggs each summer; the eggs hatch one year later. The population P during the second summer is P 1 = rP 0 , (geometric map) (6.1.1)

Upload: others

Post on 12-Apr-2022

1 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Chapter Six - phys.ubbcluj.ro

Modeling-Science June 3, 2008

Chapter Six

Explicit Algorithms and Visualization

“Not only in research but also in the everyday world of economicsand politics we would all be better off if more people realizedthat simple nonlinear systems do not necessarily possess simpledynamical properties.” Robert May

We describe models that can be evolved with explicit (non differentialequation based) algorithms using examples in one and two dimensions. Weintroduce new EJS objects and show how to access these objects from withinEJS. We also show how to create and use arrays.

6.1 GEOMETRIC MAP

Figure 6.1: A data table showing a population P growing at the fixed rater. A growth rate of r = 0.1 causes the population to double in sevengenerations.

Imagine a population of insects that lays eggs each summer; the eggshatch one year later. The population P during the second summer is

P1 = rP0, (geometric map) (6.1.1)

Page 2: Chapter Six - phys.ubbcluj.ro

Modeling-Science June 3, 2008

100 CHAPTER 6

where r represents the average number of surviving offspring of each insect.The population increases or decreases if r > 1 or r < 1, respectively. Thespecial, and highly unlikely, condition r = 1 produces a constant population.The population after n years is given by

Pn = rnP0, (6.1.2)

and is an example of geometric growth or decay. In the latter the successivechanges in a variable over a discrete time interval differ by a constant ratio.Geometric growth or decay is closely related to exponential growth or decayfor which the change is continuous. (See Chapter5.)

The simple population model in (6.1.1) is a deterministic dynamicalsystem because the population in any given spring is determined by thevalue the previous spring. The model’s dynamics is discrete in time as itonly predicts the spring population. Mathematically such a model is knownas an iterated map because the algorithm is repeatedly applied to one spring’spopulation to compute the next. How do we implement this simple modelin EJS?

A map models a discrete dynamical system by defining a relation (function)that transforms the system’s state into another ) state. The starting stateis called the seed and the sequence of states is called the trajectory or orbit.

The GeometricGrowth model shown in Figure 6.1 has dynamicalvariables for the population P and the measurement year n. The growthparameter r remains fixed. The Evolution workpanel uses these variables toimplement (6.1.1) as an explicit algorithm that is invoked with a two frameper second (FPS) rate.

P += r*P; // advances the population; equivalent to P = P + r*P

n++; // advances the time; equivalent to n = n + 1

The += operator used in the code is Java shorthand for adding a num-ber to a variable. It is equivalent to the addition operator + followed byassignment operator =. Note that assignment = is not the same as mathe-matical equality. (The Java expression for equality, such as 3+2==5 or y==x,produces a boolean if the arguments are equal.) The ++ operator incrementsthe year n by one.

The model’s View consists of input fields for the parameters and initialvalues, a table for output, and the usual buttons as described in Chapter 2.The property inspectors for the data table and the numeric input fields areworth examining by double clicking on the Element in the View’s the Tree

Page 3: Chapter Six - phys.ubbcluj.ro

Modeling-Science June 3, 2008

EXPLICIT ALGORITHMS AND VISUALIZATION 101

of Elements. The data table inspector (not shown) sets the column namesand column numeric format.

Figure 6.2: Input fields are often disabled while a program is running by set-ting the Editable property to isPaused(). The input field Action methodis invoked after the user types a new value and presses the Enter key.

The growth field inspector shown in Figure 6.2 binds the variable Pin the model to the text field in the user interface (the View) as describedin Chapter 2. The text field displays the P value as the model evolves;editing the text field changes the variable’s value in the model. The userinterface field’s Editable property is set to isPaused(). This propertyvalue is a predefined EJS method (function or subroutine) that returns aboolean value of true or false depending on whether the evolution of thesimulation is running or not. Controlling the Editable property in this wayinsures that the r parameter can be edited only when the simulation is notrunning. The Action is set to the initialize() method and is invokedwhen the user enters a new value into the field. The initialize() methodreads values from the user interface and clears all view elements, such asoutput tables. Click on the property field’s options (second) icon to see thesuggested methods and variables that can set the property value. The listof suggestions includes user defined methods and variables that match thedata type (integer, string, or double) required to set the property.

Exercise 6.1.A useful rule-of-thumb for the doubling time is to divide 70 by the growthrate in percent. For example, a 10% annual growth rate doubles the pop-ulation every seven years. Verify this rule of seventy using the geometricgrowth model. 2

There is a parable about a Persian king who was presented with abeautiful chessboard. When the king asked the chessboard maker what hewould like in return for his gift, the craftsman surprised the king by askingfor one grain of rice on the first square, two grains on the second, four grainson the third etc. Because there are only 64 squares, the king readily agreedand asked for the rice to be brought. Legend has it that the chessboardmaker was later put to death for tricking the king.

Page 4: Chapter Six - phys.ubbcluj.ro

Modeling-Science June 3, 2008

102 CHAPTER 6

Exercise 6.2.Set the growth rate in the geometric model to r = 1 to model the grains

of rice on each chessboard square. Assume that 4000 grains of rice have amass of one kilogram. Which square has one kilogram? One metric ton?The world rice harvest in 2005 was 700 million metric tons. Will this harvestbe sufficient to fulfill the Persian king’s promise? 2

Exercise 6.3.Add a plot of the population P (n) as a function of n to the geometric growthmodel. 2

The geometric map is an example of an explicit model in which thestate at time tn+1 can be computed by a known expression of the form

xn+1 = f(tn,xn) (6.1.3)

where x is a state vector (one-dimensional array) with k components (x0, x1, x2 · · ·xk−1).

Explicit models are not restricted to discrete systems. Continuousmodels for which analytic solutions are know in closed form, such as thewave function model presented in Section 3.5, are also explicit models. Tospecify an explicit model we need to create only the table of variables forthe state and write an evolution page that converts the relation (6.1.3) intoJava code.

6.2 LOGISTIC MAP

Figure 6.3: A graphical representation of logistic map iterations with r =3.6.

As shown in the chessboard example (Exercise 6.2), geometric growthcannot continue forever. A more realistic model reduces the growth rate asthe population increases. The simplest way of doing so is to add a quadraticterm to the geometric map. This new model was first studied by the biologist

Page 5: Chapter Six - phys.ubbcluj.ro

Modeling-Science June 3, 2008

EXPLICIT ALGORITHMS AND VISUALIZATION 103

Robert May[?] and is know as the logistic map because it is closely relatedto the logistic differential equation discussed in Chapter 5.

P1 = rP0 − kP 20 . (6.2.1)

If the population is small, the quadratic term in the logistic map will notbe important and geometric growth results (if r > 1). As the populationincreases the competition for resources increases and the quadratic term kP 2

0

eventually competes with the linear term rP0. According to (6.2.1) thereis a maximum population (carrying capacity) Pmax = r/k that producesextinction in the next generation. We use this maximum population torescale the independent variable by letting p = (k/r)P . We then rewrite(6.2.1) as

pn+1 = rpn(1− pn). (logistic map) (6.2.2)

The LogisticGrowth model is a modification of the geometric growthmodel that implements (6.2.2) and adds additional views. Run the modelwith the default parameters and observe how the data table and the iterateplot display the yearly population. The yearly population quickly settlesto a constant long term value that depends on the value of the controlparameter r. An iterated value that never changes is called a fixed point.Does the fixed point that you observe depend on the initial population? Doesthe simulation behave as you expected? Does the relatively uninterestingbehavior of a long term steady-state population ever change?

Exercise 6.4.Run the logistic model with control parameters in the range [0 < r < 4].

Describe the behavior for r = 0.5, 1.5, 3.1 and 3.7.. What happens to thepopulation if r > 4? 2

Exercise 6.4 will likely convince you that a simple system can exhibitcomplex behavior. The simulation’s cobweb plot shown in Figure 6.3 givesa geometric interpretation of how this behavior develops. The cobweb plotdisplays the logistic function y = rx(1 − x) as well as the diagonal liney = x on a graph. At each iteration we compute the new population pn+1 =rpn(pn − 1) and draw a vertical line to (pn, pn+1 followed by a horizontalline to pn+1, pn+1. The horizontal coordinate of the endpoint now displaysthe population at the end of the iteration and the line segments show howthe logistic function maps one population to the next. The entire algorithmis coded using just a few lines in the Evolution workpanel:

double pNew = map(p); // computes next generation

_view.cobwebTrace.addPoint(p,pNew);

_view.cobwebTrace.addPoint(pNew,pNew);

p = pNew;

Page 6: Chapter Six - phys.ubbcluj.ro

Modeling-Science June 3, 2008

104 CHAPTER 6

n++; // increments the counter

This code is compact and powerful because EJS allows us to directly accessand manipulate objects in the View workpanel as described in Section 3.4.

Navigate to the cobweb frame in the View workpanel and examine thecobwebTrace element in the model’s Tree of Elements. Elements are blocksof memory called objects that store property values such as color, and cando things, such as draw data on the screen. The Element we are examin-ing is a trace that was given the name cobwebTrace when it was createdwithin the View workpanel using the “magic wand.” Although we usuallyset an element’s properties using its inspector, we can also set propertiesprogrammatically using standard Java syntax.

There are many objects within an EJS model and EJS internally orga-nizes them based on where they are used. Because the cobwebTrace objectis created and used in the View, the complete name is view.cobwebTracerather than just cobwebTrace. Appending a method name to an objectname allows us to perform (execute) that method. The second and thirdlines of the code add data points that produce the vertical and horizontallines in the plot.

The first line of code in the Evolution workpanel invokes a custommethod that is defined in the Custom workpanel. We use a custom methodto improve the organization and clarity of our model. Defining a map methodmakes it straightforward to investigate other maps because the method isdefined in a single easy-to-find location within the model. An importantfeature of custom methods is that they allow us to use local variables. Forexample, the p variable in the map method is unrelated to the model’s vari-able with the same name in the Variables workpanel. We can send a valueto the method just as we can send a value to a sine function on a calculatorwithout worrying what variables are internal to the algorithm. The valuethat is returned from the map method is assigned to the model’s p variable.

The cobweb diagram makes it easy to see how the model’s behaviorchanges as the control parameter r is increased. Intersections of the logisticfunction with the diagonal line represent fixed points where the populationremains constant. If r < 1, there is only one fixed point at p = 0 andall trajectories are attracted to this value. Populations within the interval0 ≤ p ≤ 1 approach p = 0 and are said to be within that fixed point’sbasin of attraction. If 1 < r < 3, the character of the trajectories changes.The fixed point at p = 0 becomes a repellor as trajectories move away fromit. The intersection at p = 1 − 1/r is an attractor because populationswithin the interval 0 ≤ p ≤ 1 converge toward it. If r = 3, the second

Page 7: Chapter Six - phys.ubbcluj.ro

Modeling-Science June 3, 2008

EXPLICIT ALGORITHMS AND VISUALIZATION 105

fixed point becomes a repellor that causes the population to move awayfrom it. The trajectory bifurcates and the population eventually alternatesbetween two values. Hence, there is now an attractor that consists of twopoints. The trajectory’s continual cyclic behavior persists until r ≈ 3.4495at which point another period doubling occurs and the attractor consists offour points. Although we can continue to use our logistic growth simulationto explore the map, a more productive approach is to create a model thatgives us a global perspective.

6.3 BIFURCATION DIAGRAM

Figure 6.4: A bifurcation map showing the result of iterations after the first400 iterations are discard. This computation is performed at different valuesof r to give a global perspective of the trajectories of the logistic map.

One way to visualize the properties of the logistic map is to plot theiterates for values of r. If the trajectory is close to an attractor, only thosepoints that lie on the attractor will appear on the plot. A long-term plotof state values of p as a function of the control parameter is know as abifurcation map or return map and is shown in Figure 6.4.

The Evolution workpanel in the LogisticMap model selects a ran-dom initial population, iterates the logistic map without plotting to removetransients, and iterates and plots the long-term populations. The controlparameter is then increased and the process is repeated. The following codeimplements this algorithm:

double p = Math.random(); // picks a random initial population

for(int i=0;i<nTransients; i++){

p = map(p); // iterates to remove transients

}

for(int i=0;i<nPlot; i++){

Page 8: Chapter Six - phys.ubbcluj.ro

Modeling-Science June 3, 2008

106 CHAPTER 6

p = map(p); // iterates to collect data

_view.bifurcationDataRaster.append(0,r,p);

}

r += dr; // increases control parameter

if(r>=rmax) _pause(); // stops the simulation

The first statement invokes the random number generator in the Mathclass. This class is part of Java and contains common mathematical func-tions such as Math.sin and Math.log. The second statement starts a forloop that executes the p = map(p) statement. The for statement is a com-mon looping pattern that initializes a counter (int i=0), tests a conditionto determine if the body of the loop should execute (i<nTransients), andincrements the counter (i++) before again testing the condition to deter-mine if execution should continue. Java syntax is described more fully inAppendix ??. EJS also provides a Code Wizard with syntax help by rightclicking within a code panel.

Because a bifurcation map shows hundreds of thousands of iterations,we cannot create a satisfactory visualization by adding data to a trace. Atrace is designed to plot a curve with markers and other decorations. It isredrawn after every evolution step, and the drawing time increases linearlywith the number of points. The data raster element used in the logistic mapmodel takes a different approach. A data raster creates a background imageand data points are plotted by changing the color of a single pixel on thisimage. Single data points (pixels) are often difficult to see but thousands ofdata points often form recognizable patterns. Drawing a data raster is fastand independent of the amount of data because the drawing routine merelycopies an image onto the computer screen.

The logistic bifurcation map shows a succession of period doublingsending at r ≈ 3.568. At this value the population never repeats and the sys-tem is said to be chaotic. Note that there are many small periodic windowswithin the chaotic regime that can be explored by adjusting the model’sscan range.

Exercise 6.5.One hallmark of chaos is the divergence of nearby trajectories. Return

to the LogisticGrowth model and run two copies of this model by rightclicking on the run button in EJS. Choose r = 3.99 in the chaotic regimeand choose different initial populations that differ by one part in a thousand.How many iterations are needed before the populations differ by one part inten? Repeat with an initial difference that is smaller by a factor two. Doesit take twice as many iterations to produce the same difference? 2

Exercise 6.6.

Page 9: Chapter Six - phys.ubbcluj.ro

Modeling-Science June 3, 2008

EXPLICIT ALGORITHMS AND VISUALIZATION 107

Modify the LogisticGrowth model so that it simultaneously displays twotrajectories with slightly different initial conditions in the data table andthe iterate plot. (Ignore or remove the cobweb plot.) Use your new modelto demonstrate its sensitivity to initial conditions. 2

The logistic map is a prototypical chaotic system because it exhibitsmany of the characteristics of other chaotic systems. It is a simple determin-istic model whose output is impossible to predict because trajectories withslightly different initial conditions produce very different results. The modelexhibits features, such as the sequence of bifurcations, that precede the on-set of chaos and these features are nearly universal. You are encouraged toconsult the many excellent books on chaos and nonlinear dynamics such asthose by Hilborn, [?] Sprott,[?] and Strogatz [?] for an in depth analysis ofiterated maps and chaotic systems.

6.4 CELLULAR AUTOMATA

Figure 6.5: A spacetime diagram of a one-dimensional cellular automata.The seed (top row) generates successive generations using a simple rule.

Although many laws of nature are local, we observe order on a largescale. How does this order develop? Some of the simplest models thatincorporate both space and time (spatiotemporal models) involve an arrayof cells interacting with a small number of their neighbors by simple rules.We divide space into discrete cells and associate an integer with each cell.Time is also discrete and all cells change their values simultaneously using asimple rule that depends on the cell’s own and its neighbor’s values. Modelsof this type are referred to as cellular automata and make extensive use ofarrays.

Imagine a circular coral reef divided into cells that support some typeof life form. Each cell is alive or dead and the entire reef evolves from oneyear to the next as follows:

Page 10: Chapter Six - phys.ubbcluj.ro

Modeling-Science June 3, 2008

108 CHAPTER 6

• If both neighboring cells are alive, the cell becomes (or remains) deadas if by overcrowding.

• If both neighboring cells are dead, the cell becomes (or remains) deadas if by solitude.

• If one neighboring cell is dead and the other alive, the cell becomes(or remains) alive.

How does life evolve on the reef?

A good way to visualize the evolution of the reef is to create a space-time diagram. The Automata1D model uses a Lattice Element to dis-play such a diagram as a color-coded grid. Dead cells are black and livingcells are white. The spatial state of the reef is plotted along a horizontalrow, and every row represents a different time (generation). By conven-tion, time increases downward. Data for the spacetime lattice is stored in atwo-dimensional array of integers named spacetimeCells. Open the modeland examine how this array is defined and used. The dimension columnin the Variables workpanel specifies the array size using integers in squarebrackets [nx][nt], where nx and nt are the number of spatial columns andtemporal rows. Inspect the spacetimeLattice in the View to see how thedata array is bound to the object’s Data property. Notice that we use thearray size, nx and nt, to set the lattice scale. The lattice is inside a plottingpanel. Because the default drawing convention is to plot increasing y-valuesupward, we set the y-axis autoscale property in the model’s plotting panelto false and flip the minimum and maximum values in order to show the[0][0] cell in the panel’s upper left hand corner.

The Evolution workpanel computes the number of neighbors for theith cell at time t− 1 and sets the value in the next generation to either 1 or0 depending on the sum. The following code implements this algorithm.

t++; // increments time to the next generation

for(int i=0; i<nx; i++){

int left = (nx+i-1)% nx; // adding nx to i-1 avoids a negative index for first cell

int right = (i+1)% nx;

int neighbors = spacetimeCells[left][t-1]+spacetimeCells[right][t-1];

if(neighbors==1){ // only one neighbor is alive

spacetimeCells[i][t]=1;

}else{

spacetimeCells[i][t]=0;

}

}

Array elements are accessed by appending one or more array indices

Page 11: Chapter Six - phys.ubbcluj.ro

Modeling-Science June 3, 2008

EXPLICIT ALGORITHMS AND VISUALIZATION 109

in square brackets to the array name. For example, the third element ofthe one-dimensional array x is x[2] because array indices in Java (and mostcomputer languages) start at zero. The third spatial cell in the secondgeneration of our spacetime lattice is spacetimeCells[2][1].

Because our toy reef is circular, the neighbor to the left of the firstcell is the last cell in the row and the neighbor to the right of the last cellis the first cell in the row. Connecting the last item to the first is known asa wrap around (toroidal) boundary condition. Although we can implementthis condition with a series of Java if statements

int right = i;

if(i+1 >= nx) right = 0;

a more elegant approach is to use the modulus (remainder) operator. Forexample, 9%10 gives 9, and 10%10 gives 0 and 11%10 gives 1. A negativeleft index is avoided when computing the first cell’s neighbor by addingthe row length to i − 1 before applying the % operator. We often use themodulus operator to fold (map) numbers into a fixed interval defined by thedividend.

Exercise 6.7.Run the Automata1D model and observe the resultant pattern. The ob-served pattern is that of a Sierpinski triangle at the resolution of the space-time grid as shown Figure 6.5. Modify the Initialization workpanel so thata random integer (zero or one) is assigned to each cell. Use the randomnumber generator in the Math class as follows:

// selects a number in [0,2) and converts it to an integer with a type cast

spacetimeCells[i][0] = (int)(2*Math.random());

Does the triangle within a triangle (Sierpinski-like) pattern evolve or persist?2

There is a second panel in the Evolution workpanel but this panelis disabled. You are asked to enable this alternative evolution panel inExercise 6.8.

Exercise 6.8.Return to the EJS Evolution workpanel, right click on the “Finite Time

Evolution” tab, and select the enable/disable option to disable the panel.Right click on the “Continuous Time Evolution” tab and enable this panel.Describe the evolution for time t > nx. Change the number of spatial cellsto an even number nx = 64 and repeat. Why does the behavior change? 2

Page 12: Chapter Six - phys.ubbcluj.ro

Modeling-Science June 3, 2008

110 CHAPTER 6

The continuous time evolution code uses some useful Java syntax.Multidimensional arrays in Java can be broken into lower dimension con-stituent arrays. For example, we can address the spatial state at time t bydropping the temporal (second) index from the spacetimeCells array.

int[] col = spacetimeCells[i];

The col variable addresses a one-dimensional array that contains the stateof the system at the ith time.

When the spacetimeCells array is full, we shift rows down and addnew data to the last row. This shift can be done using a loop but a sim-pler and much faster way to perform this operation is to treat the one-dimensional array as a single memory block and copy a portion of this blockwith a single command. The System.arraycopy method performs this op-eration.

System.arraycopy(col,1,col,0,nt-1);

The first and third arguments are the source and destination arrays ofthe command, respectively, and the last argument is the number of elementsto be copied. The second argument is the index of the first source element tobe copied, and the fourth argument is that element’s index in the destination.

6.5 GAME OF LIFE

Figure 6.6: Random configurations in the Game of Life quickly evolve intoclusters of cells known as colonies. Some colonies move, some grow, andothers emit new life that moves through the grid.

Page 13: Chapter Six - phys.ubbcluj.ro

Modeling-Science June 3, 2008

EXPLICIT ALGORITHMS AND VISUALIZATION 111

The Game of Life shown in Figure 6.6 is a cellular automata developedby John Conway and popularized by Martin Gardner in his MathematicalRecreations column in Scientific American.[?] Life is a cellular automataon a two-dimensional spatial grid. At each iteration the following rules areapplied:

• Any live cell with fewer than two live neighbors dies, as if by loneliness.

• Any live cell with more than three live neighbors dies, as if by over-crowding.

• Any live cell with two or three live neighbors lives, unchanged, to thenext generation.

• Any dead cell with exactly three live neighbors comes to life.

The GameOfLife model implements the Game of Life rules as follows:

// Copy current state

for (int i=0; i<n; i++)

System.arraycopy(cells[i],0,tmpCells[i],0,n);

for(int i = 0; i<n; i++) {

for(int j = 0; j<n; j++) {

switch(computeNeighbors(i, j)) { // apply the rules of Life

case 0 :

case 1 :

cells[i][j] = 0; //dies

break;

case 2 :

cells[i][j] = tmpCells[i][j]; //life goes on

break;

case 3 :

cells[i][j] = 1; //condition for birth

break;

default :

cells[i][j] = 0; // dies of overcrowding if >3

} // end of switch

} // end of j loop

} //end of i loop

t++; // increment generation

The Variables workpanel defines two arrays, cells and tmpCells. Thecells array determines the onscreen appearance because it is bound to thebinary lattice Data property. Because Game of Life rules are applied simul-taneously to the entire grid, the evolution algorithm copies the current statein cells into tmpCells and uses these temporary values to compute thenext generation. The computeNeighbors(int i, int j) custom method

Page 14: Chapter Six - phys.ubbcluj.ro

Modeling-Science June 3, 2008

112 CHAPTER 6

counts the values in the eight nearest neighbor cells. The value returned bythe computeNeighbors method is used in the switch statement to selectthe appropriate case. The switch statement is a useful alternative to along list of if statements as explained in Appendix ??.

The computeNeighbors method in the Custom workpanel takes rowand column input parameters and returns the nearest neighbor count usingthe tmpCells array.

// custom method that computes neighbors

public int computeNeighbors(int row, int col) {

int neighbors = -tmpCells[row][col]; // do not count self

row += n; // add the size so that the mod operator works for row 0

col += n;

for(int i = -1; i<=1; i++) {

for(int j = -1; j<=1; j++) {

neighbors += tmpCells[(row+i)%n][(col+j)%n];

}

}

return neighbors;

}

Note the use of the modulus operator to insure wrap around boundary con-ditions.

The onPress action of the drawing panel invokes the toggleLife cus-tom method to change the value of a cell when the mouse is pressed. Thismethod is defined as:

// custom method that toggles values in the cells array

public void toggleLife() {

// gets the mouse pressed coordinates

int ix = (int) _view.drawingPanel.getMouseX();

int iy = (int) _view.drawingPanel.getMouseY();

// switches the state of the cell

cells[ix][iy] = 1 - cells[ix][iy];

}

Because the lattice scale is set to [0, n], mouse coordinates can be usedas array indices after being converted (cast) from floating point to integervalues.

When a dimension is entered into the Variables workpanel, EJS auto-matically allocates computer memory for an array. It is sometimes conve-nient to modify the array size or to create our own arrays. For example, the

Page 15: Chapter Six - phys.ubbcluj.ro

Modeling-Science June 3, 2008

EXPLICIT ALGORITHMS AND VISUALIZATION 113

Game of Life has an input field that lets a user change the grid size. The in-put field’s action method invokes the initialize() method. This methodreads the user interface and executes the following code in the Initializationworkpanel:

n = Math.max(3,n); // insures a 3x3 grid

cells = new int[n][n];

tmpCells = new int[n][n];

for(int i=0; i<n; i++){

for(int j=0; j<n; j++){

cells[i][j]=(Math.random()<0.5)?0:1;

}

}

t = 0; // resets the time

Arrays (objects) are created using the new operator. The initializationcode allocates two n× n integer arrays after insuring that n > 2 and thesearrays are assigned to the cells and tmpCells variables. The elements inthe cells array then set randomly using nested loops. The model is nowready to be executed by the animation thread.

Exercise 6.9.Run the GameOfLife model with random initial configurations and observethe emergence of colonies. Some colonies move, some grow, and others emitnew live cells that move through the grid. Record the colonies that havethese special properties. Reduce the size of the grid and click the clearbutton to set the array to zero. Click within the grid to toggle the life offand on to recreate the more interesting colonies. 2

6.6 FOURIER ANALYSIS*

Figure 6.7: A square wave with period T = 2π constructed from a Fourierseries with 24 terms.

Page 16: Chapter Six - phys.ubbcluj.ro

Modeling-Science June 3, 2008

114 CHAPTER 6

Much like a glass prism which displays the frequency components oflight, Fourier analysis can be thought of as a mathematical prism that dis-plays the frequency components of a function. Fourier’s theorem states thatany periodic function f(t) with period T such that f(t) = f(t + T ) can bebe written as a sum (Fourier series) of sine and cosine functions

f(t) =a0

2+

∞∑

m=1

am cos(mω0t) +∞∑

m=1

bm sin(mω0t), (6.6.1)

where ω0 = 2π/T is the fundamental (angular) frequency and all otherfrequencies are integer multiples (harmonics) of ω0. The process of findingthe sine and cosine coefficients is called Fourier analysis and the process ofreconstructing the function from these coefficients is called Fourier synthesis.The summation of Fourier components must be truncated when performingFourier analysis and synthesis because a computer can only perform a finitenumber of arithmetic operations.

Although the independent variable in Fourier analysis is often time,such as when the function represents a disturbance (sound) at a fixed loca-tion, there are also many applications where we analyze a function of spacef(x). In this case, we refer to a spatial period or a wavelength λ rather thanto a temporal period T and we use the symbol for wavenumber k = 2π/λrather than frequency ω = 2π/T . In order to keep our notation and ourlanguage consistent, we assume that time is the independent variable unlessotherwise stated. We refer to a finite dataset that approximates a functionf(t) at n equal time intervals ∆t as a time series and we refer to frequencies,cycles, and periods when discussing its properties.

There are many applications of Fourier analysis is science and engi-neering. For example, analysis of natural seismic events (earthquakes) andunderground nuclear explosions reveals different frequency components foreach of these events. In optics, Fourier analysis is used to compute thediffraction pattern of light passing through an aperture.

We start by running the FourierAnalysis model to study the mean-ing of Fourier’s theorem (6.6.1) before studying the model’s EJS implemen-tation. The default function is a square wave as shown in Figure 6.7. Tosimplify the mathematics the period of the function has been set to T = 2π.The fundamental frequency is therefore ω0 = 1 and the harmonic frequenciesωm = mω0 are integers.

Examine the f(t) input field and note that the square wave is con-structed using the Heaviside step function step(x) which is zero if the ar-gument is negative and one if the argument is positive or zero. The modelplots this function over two periods in order to emphasize its periodic nature.

Page 17: Chapter Six - phys.ubbcluj.ro

Modeling-Science June 3, 2008

EXPLICIT ALGORITHMS AND VISUALIZATION 115

The red circles show the time series that approximates the given functionand the blue trace (curve) shows how well the time series is approximatedby (6.6.1) with a finite number of terms.

Figure 6.8: The Fourier cosine coefficients for a symmetric square wave.

Figure 6.8 shows the Fourier cosine components of the step functionsampled at 24 points. Clicking on a coefficient shows that coefficient’s value.If the synthesize option is checked in the function plot, the user can thenset a coefficient’s value by click-dragging within the coefficient display.

Because the cosine function is symmetric about the origin and becausethe square wave used in Figure 6.7 is also symmetric about the origin, onlythe cosine coefficients are nonzero. An asymmetric function, such as f(t) =1−2∗step(x−π), produces only sine coefficients. Note that the reconstructedfunction exactly reproduces the time series data. No information is lostbecause a time series with N data points determines exactly N constants inthe Fourier series.

Exercise 6.10.Input the following functions into the Fourier analysis program:

• Gaussian pulse: f(t) = e−4(t−π)2 .

• Sawtooth wave: f(t) = t.

• Sine wave: f(t) = sin(4t).

• Sine wave: f(t) = sin(t/2).

• A square pulse for 1/4 of the period or for 1/8 the period. Hint: Usetwo Heaviside step functions.

How many Fourier coefficients are required for a good approximation to eachfunction? Why does it take fewer coefficients to approximate some functions

Page 18: Chapter Six - phys.ubbcluj.ro

Modeling-Science June 3, 2008

116 CHAPTER 6

than others? Can you characterize the types of functions that take fewercoefficients? 2

As seen in Exercise 6.10 increasing the number of Fourier componentsproduces a better approximation to the original function. A Fourier seriesconverges to the original function except at isolated points if the originalfunction has a finite number of discontinuities, is square-integrable, and hasa finite number of maxima and minima. The overshoot at a discontinuity isknown as the Gibbs phenomena in honor of the American chemist J. WillardGibbs who first studied it. Because a sum of continuous functions, such assines and cosines, will always be continuous, the Gibbs phenomena persistseven as the number of components approaches infinity.

To implement the Fourier analysis model we must compute the sineand cosine coefficients in (6.6.1). These coefficients are obtained by per-forming the following integrals:

am =2T

∫ T

0f(t) cos(mω0t) dt (6.6.2)

bm =2T

∫ T

0f(t) sin(mω0t) dt. (6.6.3)

Starting with a time series with N terms, we approximate these integralsusing sums

am =2T

N∑

n=1

f(tn) cos(mω0tn)∆t =2N

N∑

n=1

fn cos2πnm

N(6.6.4)

bm =2T

N∑

n=1

f(tn) sin(mω0tn)∆t =2N

N∑

n=1

fn cos2πnm

N. (6.6.5)

where we have used T = N∆t and fn = f(tn) = f(n∆t) to simplify theexpressions. These sums are the discrete Fourier transform of the timeseries.

The Fourier analysis model makes extensive use of arrays and custommethods to implement (6.6.1) through (6.6.4). For example, the modeldefines the y[] array in the Variables workpanel to store the time seriesdata. The computeCosCoef method uses this array to compute each cosinecoefficient.

// Computes the cosine coefficient in the m-th harmonic.

public double computeCosCoef(int m) {

double a=0;

double omega=m*2*Math.PI/period;

for(int i=0, n=t.length; i<n; i++){

Page 19: Chapter Six - phys.ubbcluj.ro

Modeling-Science June 3, 2008

EXPLICIT ALGORITHMS AND VISUALIZATION 117

a += y[i]*Math.cos(omega*t[i]);

}

return 2*a/n;

}

There are many other custom methods. The changeN() method al-locates new arrays and is the Action property for the number of samples(n) input field. The sampleFunction() method computes the time seriesdata when the user edits the function input field. The techniques used toimplement these methods are similar to those used in previous models andreaders are encouraged to study the details by examining the EJS model.

The most important new EJS feature in the Fourier analysis modelis our use of Element sets. An element set is a collection of other elements(such as particles, arrows, texts, etc.) whose properties are bound to arraysso that changing an array element automatically changes the correspondingshape. For example, the samples, leftSamples, and rightSamples objectsin the time series display are sets of circles. Open the samples propertiesinspector and note the X-property is bound to the t[] array and Y-propertyis bound to the y[] array. The leftSamples X-property is bound to theleftT[], but reuses the y[] array for its Y-property because the time seriesis assumed to be periodic.

The Fourier coefficient display uses sets to display the sinCoef[] andcosCoef[] arrays. The sinCoefSet and cosCoefSet elements are sets ofvertical arrows with square heads. The length of each arrow shows theamplitude of the Fourier component. The visible properties of these sets isdetermined by the sin and cos radio buttons so that only one is visible.The action properties invoke custom methods when a user click-drags anobject within the set.

PROBLEMS AND PROJECTS

Project 6.1 (Other Maps). There are many interesting one-dimensionalmaps on the interval [0, 1]. A very simple map is the tent map

xn+1 = r min(xn, 1− xx). (6.6.6)

Draw this map function. For what values of r is x = 0 a fixed point?Why? Study and describe the bifurcation sequence for this map. Over whatrange of r values do you observe chaos? Are there periodic windows in thebifurcation diagram’s chaotic region?

Investigate the following maps using cobweb diagrams and describetheir bifurcation diagrams.

Page 20: Chapter Six - phys.ubbcluj.ro

Modeling-Science June 3, 2008

118 CHAPTER 6

• xn+1 = r cosxn

• xn+1 = rexn

• xn+1 = rxn − x3n

Project 6.2 (Feigenbaum constant). The mathematical physicist MitchellFeigenbaum observed that the period-doubling route to chaos in the logisticmap was common in many chaotic systems. Feigenbaum showed that if rn

is the parameter value where the logistic map changes from period rn toperiod rn+1, then the ratio

δn =rn − rn−1

rn+1 − rn(6.6.7)

is approximately constant for all values of n and approaches a fixed valueas n → ∞. This constant is now known as the Feigenbaum δ because itis a universal feature for functions approaching chaos via period doubling.Compute Feigenbaum’s δ using bifurcations in the logistic map.

Project 6.3 (Wolfram cellular automata rules). Steven Wolfram [?] has pro-posed a classification scheme for cellular automata based on dynamical char-acteristics that are reminiscent of behavior that we observed in the logisticmap. Class 1 automata reach a homogenous state for almost all initial con-ditions as was observed in attractors. Class 2 automata reach a nonuniformstate that is either constant or periodic as was observed in cycles. Class3 automata have random patterns with sensitivity to initial conditions andcorrespond to chaos. Class 4 automata have localized structures that prop-agate and interact. These behaviors are explored more fully in the end ofchapter projects and in Chapter 14.

[CA example goes here.]

Project 6.4 (Fractals). Diffusion limited aggregation (DLA) is a processwhereby particles undergoing a random walk stick together (cluster) to formaggregates of particles. A simple DLA model can be created using a two-dimensional lattice with a value of one in the center and zero elsewhere.The nonzero cell is the seed for the cluster. A particle is released intothe lattice on a circle surrounding the cluster and this particle moves ina random direction until it reaches a nearest neighbor of the cluster andsticks. Another particle is then created and the process is repeated until alarge cluster is formed. An easy way to implement this algorithm in codeis to choose a random number and increment or decrement the wanderingparticle’s lattice indices until a neighboring element is nonzero.

// ix and iy are the particles lattice indices

Page 21: Chapter Six - phys.ubbcluj.ro

Modeling-Science June 3, 2008

EXPLICIT ALGORITHMS AND VISUALIZATION 119

int r = (int)(4*Math.random()); // choose a random integer { r: 0,1,2,3}

switch(r){

case 0: ix++; break; // increment x

case 1: ix--; break; // decrement x

case 2: iy++; break; // increment y

case 3: iy--; break; // decrement y

}

// add code to check lattice for cluster here

Model a DLA cluster using a Lattice Element. In order to speed upthe computation, it is a good idea to reinitialize the particle’s position if itwanders too far from the cluster. The initialization radius should be at leasttwice the size of the cluster and this radius must be increased as the clustergrows.

An interesting property of DLA clusters is that the number of particleswithin a given area does not increase in direct proportion to the area becausethe cluster does not completely fill two-dimensional space. The cluster issaid to be a fractal and has a fractal dimension. Compute the number ofparticles within various size circles centered on the seed and show that thenumber of particles is not proportional to r2. The easiest way to check thispower law is to create a log-log plot of circle radius versus particle numberand measure the slope of the trendline. This slope is a common definitionof the fractal dimension of the cluster.

Project 6.5 (Attractors). An attractor is a state to which a sequence ofiterations converges, and its basin of attraction is the set of initial statesthat converge to that attractor. Sometimes the iteration converges to thesame value regardless of the initial state, but often it does not and thebasins of attraction can be surprisingly complex. Consider Newton’s methodfor finding the root of a function. Newton’s method evaluates a complexfunction f(z) and its derivative f ′(z) at a point zn to produce a new pointzn+1:

zn+1 = zn + f(z)/f ′(z). (6.6.8)

This iteration usually converges to the roots of the function f(z) = 0.

Consider the problem of finding the cube root of one. This problem isequivalent to finding the zeros of the function f(x) = z3 − 1 and has threesolutions in the complex plane: {z: 1, 1/2 ± i

√3/2}. If z is expressed in

terms of its real and imaginary components z = x + iy, Newton’s method

Page 22: Chapter Six - phys.ubbcluj.ro

Modeling-Science June 3, 2008

120 CHAPTER 6

can be written as an iteration:

xn+1 =23xn +

13

x2n − y2

n

(x2n + y2

n)2(6.6.9)

yn+1 =23xn − 1

32xnyn

(x2n + y2

n)2. (6.6.10)

Model the basins of attraction for this system using a DataRaster to rep-resent points in the x-y plane. Choose a pixel in the raster and iterate itsx, y coordinates until the result is sufficiently close to one of the three roots.Color the starting pixel red, green, or blue depending on the root to whichthe point converges.

Project 6.6 (Fourier Sine Analysis). There are other forms of Fourier’s The-orem. Research the sine series expansion and explain how it differs from thesine-cosine expansion. Modify the Fourier model presented in this chapterto display the Fourier sine expansion on the interval [0, T ] of an arbitraryfunction

f(t) =∞∑

m=1

bm sin(mω0t), (6.6.11)

where ω0 = π/T is the fundamental (angular) frequency and all other fre-quencies are integer multiples (harmonics) of ω0. Does the reconstructedfunction reproduce f(t) on the interval [T, 2T ]?