spatio-temporal models in ecology; an introduction to...

43
Spatio-Temporal Models in Ecology; an Introduction to Integro-Difference Equations James Powell Department of Mathematics and Statistics Utah State University April 9, 2001 [email protected]

Upload: others

Post on 19-Jun-2020

6 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Spatio-Temporal Models in Ecology; an Introduction to ...adler/oldcourses/minicourse/matlab/labs_pow… · Spatio-Temporal Models in Ecology; an Introduction to Integro-Difference

Spatio-TemporalModelsin Ecology;anIntroductiontoIntegro-DifferenceEquations

JamesPowell�

Departmentof MathematicsandStatisticsUtahStateUniversity

April 9, 2001

[email protected]

Page 2: Spatio-Temporal Models in Ecology; an Introduction to ...adler/oldcourses/minicourse/matlab/labs_pow… · Spatio-Temporal Models in Ecology; an Introduction to Integro-Difference

CONTENTS 2

Contents

1 Lab 1 – Intr oducing MATLAB 4

1.1 Goals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

1.2 IntroducingtheSoftware . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

EXERCISE 1 UsingHelp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

1.2.1 DefiningOne-DimensionalFunctionsandGraphing . . . . . . . . . . . . . . . . . . . . . . 4

EXERCISE 2 Plottingthediffusionequation’s fundamentalsolution . . . . . . . . . . . . . . . 5

1.2.2 ScalarFunctionsof Two Variables. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

EXERCISE 3 Surfaceplot of thewave equation . . . . . . . . . . . . . . . . . . . . . . . . . . 6

1.2.3 BasicLogicalFunctions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

EXERCISE 4 Truncatingthediffusion-lossmodel . . . . . . . . . . . . . . . . . . . . . . . . . 8

1.2.4 LearningaboutMatrix ManipulationandFourierTransformsusingtheDemos . . . . . . . . 8

EXERCISE 5 Stabilityof Nicholson-Bailey . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9

2 Lab 2 – Dispersal 10

2.1 Goals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

2.2 ProbabilityandDispersalin OneSpaceDimension . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

2.2.1 Dispersalvia RandomWalksandtheDiffusionEquation . . . . . . . . . . . . . . . . . . . . 10

2.2.2 ConvolutionsandFourierTransforms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

2.2.3 NumericalFFT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

2.2.4 MatlabImplementation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

EXERCISE 6 Diffusivedispersalof ‘tent’ function . . . . . . . . . . . . . . . . . . . . . . . . 13

2.2.5 DispersalandSettlingwith aLocalizedSource . . . . . . . . . . . . . . . . . . . . . . . . . 13

EXERCISE 7 Distribution from diffusionandsettling . . . . . . . . . . . . . . . . . . . . . . . 13

2.2.6 Ballistic Dispersal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

2.2.7 MovementatConstantSpeedfrom aSourceandSettling . . . . . . . . . . . . . . . . . . . . 15

EXERCISE 8 Advectionandsettling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

2.3 ProbabilityandDispersalin Two SpaceDimensions. . . . . . . . . . . . . . . . . . . . . . . . . . . 15

2.3.1 Dispersalvia RandomWalksin Two Dimensions. . . . . . . . . . . . . . . . . . . . . . . . 15

EXERCISE 9 Diffusionin two dimensions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16

2.3.2 ModalDispersalin Two Dimensions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16

EXERCISE 10 Advection-diffusionin two dimensions . . . . . . . . . . . . . . . . . . . . . . 17

EXERCISE 11 Randomwinds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17

2.3.3 Turchin’sModel for Prey-Taxis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17

EXERCISE 12 Prey-taxis(differentialmotility) . . . . . . . . . . . . . . . . . . . . . . . . . . 19

3 Lab 3 – Implementing an Integro-DifferenceModel 21

3.1 Goals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21

3.2 EnhancedNicholson-Bailey Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21

EXERCISE 13 Iterationsof theNicholson-Bailey (nonspatial)model . . . . . . . . . . . . . . . 22

3.3 MatlabImplementationof theSimplestIDE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22

EXERCISE 14 Iteratinglineardispersalandreproduction. . . . . . . . . . . . . . . . . . . . . 24

3.4 An Integro-DifferenceApproachto Nicholson-Bailey . . . . . . . . . . . . . . . . . . . . . . . . . . 25

Page 3: Spatio-Temporal Models in Ecology; an Introduction to ...adler/oldcourses/minicourse/matlab/labs_pow… · Spatio-Temporal Models in Ecology; an Introduction to Integro-Difference

CONTENTS 3

3.4.1 Descriptionof IDE for ENB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25

3.4.2 MatlabImplementation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26

EXERCISE 15 Nicholson-Bailey in space . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28

EXERCISE 16 Logisticequationin space . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29

3.5 SpatiallyStructuredEnvironments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29

EXERCISE 17 Spatialheterogeneity– cropstructure . . . . . . . . . . . . . . . . . . . . . . . 30

EXERCISE 18 Spatialheterogeneity– parasiteefficiency . . . . . . . . . . . . . . . . . . . . . 30

EXERCISE 19 Spatiallycorrelatedrandomenvironment– rockies . . . . . . . . . . . . . . . . 31

EXERCISE 20 Randomcarryingcapacitiesin ENB . . . . . . . . . . . . . . . . . . . . . . . . 31

4 Lab 4 – Boundaries,Chemotaxisand StudentCaseStudies 32

4.1 Goals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32

4.2 ReflectingandAbsorbingBoundaryConditions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32

4.2.1 TheWall of Doom . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32

EXERCISE 21 Implementinglethalboundaries . . . . . . . . . . . . . . . . . . . . . . . . . . 34

4.2.2 ReflectingBoundaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35

EXERCISE 22 Reflectingboundaries. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35

4.2.3 MixedBoundaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36

4.2.4 BoundaryConditionsin Two Dimensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37

EXERCISE 23 Two-dimensionalboundaryconditions. . . . . . . . . . . . . . . . . . . . . . . 38

4.3 A Model for Chemo-Taxis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38

EXERCISE 24 Chemo-taxisa la Powell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40

ClassReferences 42

Also:� GettingStartedwith MATLAB. (green)� Kot, M., 1992. “Discrete-timetravelling waves: Ecologicalexamples,” Journal of MathematicalBiology 30:413–436.(yellow)� Holmes,E.E.,M.A. Lewis, J.E.BanksandR.R.Veit, 1994. “Partial differentialequationsin ecology:spatialinteractionsandpopulationdynamics,” Ecology75: 17-29(from thespecialissueSpace,theFinalFrontierforTheoreticalEcology). (pink)� Neubert,M.G.,M. KotandM.A. Lewis,1995.“Dispersalandpatternformationin adiscretetimepredator-preymodel,” TheoreticalPopulationBiology48: 7–43.(yellow)� Allen, J.C.,C.C.BrewsterandD.H. Slone,2001.“Spatiallyexplicity ecologicalmodels:a spatialconvolutionapproach,” Chaos,SolitonsandFractals12: 333–347.(blue)� Powell, J.A. andN.E. Zimmermann,2001. “Multi-Scale Analysisof SeedDispersaland the ResolutionofReid’sParadox,” submittedto Ecology, August,2000.(white)

Page 4: Spatio-Temporal Models in Ecology; an Introduction to ...adler/oldcourses/minicourse/matlab/labs_pow… · Spatio-Temporal Models in Ecology; an Introduction to Integro-Difference

1 LAB 1 – INTRODUCING MATLAB 4

1 Lab 1 – Intr oducingMATLAB

1.1 Goals

Thegoalsof thislabareto introducestudentsto importantMATLAB commandsandphilosophies,including:� Basicgraphicaloperationsfor plottingdatain oneandtwo dimensions.� Defininggrids.� MATLAB’s Help facility.� Specialmathematicalandlogical functions.� Matrix manipulations(Demos).� ImplementingtheFastFourierTransform(FFT) in MATLAB (Demos).

MATLAB is built aroundmatrix andvectormanipulation,andviews everythingasvectorsor matricesortensors.It is not a symbolicprogram,andperformsno analyticcalculations,but is composedof computa-tionally optimizedlinearalgebraroutinesfor performingoperationsonandto matricesandvectors.

1.2 Intr oducing the Software

Note: At any time during a MATLAB sessionyou may typehelp COMMAND for MATLAB’s internalinformationon howCOMMAND maybeused,includingexamples.If you do not know what commandyouarelooking for, youmaytype lookfor SUBJECT to getMATLAB to searchfor commandswhich referto yourSUBJECT.

EXERCISE 1: Type

help linspace

andafterreadingaboutlinspacetype

lookfor space

to seewhatotherrelevantcommandstheremightbe.

1.2.1 Defining One-DimensionalFunctionsand Graphing

Let’sbegin by graphingsomefamiliarone-dimensionalfunctionsusingMATLAB . Thefirst stepis to makeavectorcorrespondingto therealaxis,saybetween-5 and5:

x = linspace(-5,5,1 01);

Theabovecommandgeneratesavectorwith 101components,named‘x’, whoseelementsareevenlyspacednumbersbeginningat -5 andendingat5. Thesemicolon(;) suppressesoutput– try thecommandwithout itandseewhathappens!Noticealsothatwegeta spacingof

���= 1/10usingtheabove command– the101

allows usto have theendpointsincludedin thevectorof coordinates.

Now definea function, �� �� ������� � ������ ����� ���� , which we will thenplot. The function � will beavector, f, whichcontainsfor everycomponentof thecoordinatevector, x , avalueaccordingto therule �� �� :

Page 5: Spatio-Temporal Models in Ecology; an Introduction to ...adler/oldcourses/minicourse/matlab/labs_pow… · Spatio-Temporal Models in Ecology; an Introduction to Integro-Difference

1 LAB 1 – INTRODUCING MATLAB 5

f = sin( x.ˆ2 )./(1 + x.ˆ2);

Thenotation‘.’ beforeanoperationmeansto applytheoperationelement-by-elementto anarray;thus

x.ˆ2

meansthe elementby elementsquareof x , or a vector of length 101 with values���

for�

between-5and5 (Look in theGettingStartedwith MATLAB materialsfor moreinformationon how basicarithmeticoperationsareimplemented).Now, to plot f issuetheMATLAB command

plot(x,f)

whichwill plot theorderedpairsgivenby x ,f. Try changingtheorderof x andf aboveto seewhathappens.

Now, to seehow to putmultipleplotsononegraphandchangesomeof thestyles,try thefollowing:

plot(x,f,’r*’)hold on, plot(x,1./(1+x .ˆ 2) ,’g ’) , hold offxlabel(’x’),yl abel( ’f (x )’ ), tit le (’ Func tio n and Envelope’)

The ‘hold’ commandsforce MATLAB to draw plots without erasingprevious plots. Onemay alsoplotseveralfunctionssimultaneously, asin

figure(2)plot(x,cos(x), ’r ’,x ,e xp (- abs(x )) ,’ b’ ,x ,si n( x. ˆ2 ), ’g’ )

Now, just to seewhatsomeof theoptionswouldbe,type

help plot

which will give you a numberof examples,setsof options,andsomesuggestionsfor othercommandsyoumightfind useful.Try someof thesejust to getthehangof it.

EXERCISE 2: Plot thefundamentalsolutionof theheatequation,�� �"! ��#$#&% � � � %�' (�*) � ��whichhastheform + � � %�, -� �. /10 ! ,325476 8:9 ���/ ! ,�; %for thefollowing , values:1, 2, 4. Plot all on thesamesetof axes,over aninterval from -10 to 10, for a

!valueof .37,andorganizethetime slicesin thecolorsof theMATLAB spectrum(’r’,’y’, ’g’,’b’,’m’). Labelthe axesandgive the plot a title. The legend commandallows you to label the differentgraphs– usehelp andcheckit out!

1.2.2 ScalarFunctionsof Two Variables

Definingfunctionsof two variablesworkswith thesamephilosophyin MATLAB , exceptthattheunderlyingsubstrateof independentvariablesbecomesa matrix asopposedto a vector. Let’s begin by definingtwocoordinates,x andy andthena two-dimensionallyextendedversionof thesecoordinates:

Page 6: Spatio-Temporal Models in Ecology; an Introduction to ...adler/oldcourses/minicourse/matlab/labs_pow… · Spatio-Temporal Models in Ecology; an Introduction to Integro-Difference

1 LAB 1 – INTRODUCING MATLAB 6

x=.1*[0:100];y=.05*[-50:50] ;[X,Y]=meshgrid (x ,y) ;

(Noticethescalarmultiplicationof a spacing,either.1 or .05 above, andanarrayof numbers,[N1:N2] ,whichisall of theintegersbetweenN1andN2, inclusive. Thus,x=.1*[0:100] isequivalenttox=linspace(0,1 0, 101). ).Now we maydefinea functionof thesetwo variablesanalogouslyto theone-dimensionalprocedure.Forexample,to plot thefunction < � � %�= >� �?��� � � � � 0 = �@� � � � = � %asa surface,wecouldusethesequenceof commands

g = sin(X.ˆ2+pi*Y). /( 1+X. ˆ2 +Y. ˆ2 );surf(X,Y,g)

Canyou tell which is the�

andwhich the = direction?Now let’s changethelocationof thegrid. Usetheup arrow, A , to accessprevious commands;to accessthe previous commandstartingwith ‘x=’ type ‘x=’on thecommandline andthenhit A . Now you canusethe back �CB andright �CD to move throughthepreviouscommand.Typing a characterwill insertit; backspaceremovesit. Call up thepreviouscommanddefiningthegrid for x andmodify it sothatx is now anarraycorrespondingto coordinatesbeginningat -5,extendingto +5, andwith a grid spacing� ���� of .1. Recreatethemeshgridfor X, Y, redefinethematrix gwhosevaluesaregivenby theruleabove,andplot theresultusing

surf(X,Y,g),sh ading flat

Theshadingflat optionremovesthegrid linesandshadeseachportionof thegraphasa flat polygon.Youcanchangethe color mappingsby trying thingslike colormap hot, andon a computerscreenthingsaremorestriking if you issuethecommandwhitebg(’k’) (which makesthebackgroundcolor black,or ’k’ ).To seeaparticularsliceof thegraph,thatis asectionin eitherthex or y direction,youcanplot aparticularrow or columnof g. For example,to plot acrosssectionin the

�direction,with = � 9�EGFIH , type

figure(2),plot (x ,g( 1, :) )

The colon (:) in the secondargmentof g says‘all available indices,’ and in this case‘g(1,:) ’ means‘From thematrix g take the first row andall columns,’ which is, of coursethe vectorcontainingsamplestaken from g in thex directionat thesmallesty value(which hasindex 1). Usehold on, hold off to plotsomeothercrosssectionsof thefunctionuntil youfeelcomfortablewith whichindicescorrespondto whichvariables.

Now let’s plot contoursanddensitiesin anotherwindow. Try

figure(3), pcolor(X,Y,g), shading flat, colormap hot

This will createa new figure,put a densityplot of g in it, andcolor-codethedensitiesin sucha way thatlower valuesaredark (cool) andhigherdensitiesarewhite (hot). It is possibleto super-posecontoursonthisgraph:

hold on, contour(X,Y,g, ’b ’) , hold off

Thiswill place20aestheticallychosencontoursin blueon thecolordensityplot.

Page 7: Spatio-Temporal Models in Ecology; an Introduction to ...adler/oldcourses/minicourse/matlab/labs_pow… · Spatio-Temporal Models in Ecology; an Introduction to Integro-Difference

1 LAB 1 – INTRODUCING MATLAB 7

EXERCISE 3: Thefunction� � � %�, -� �EKJ 254G6ML 9 � � 9NE , ��O � 254G6PL 9 � � � E , �$OGQis a solutionto thewave equation,�R S � / ��#$# , which models,amongotherthings,waveson thesurfaceofa canal,in this casemoving at speed2 in eitherdirection. Definea meshgridin , and

�which will allow

you to visualizethis solutionfor timesbetween0 and4. Usesurfaceplots,densityplots,andcontourstovisualizethebehavior of thissolution.Also, in a third figureplot a ‘waterfall’ diagram,thatis severalslicesin constanttime, varying x , which will illustrate the evolution of the function. Use times0,1,2,3,4andcolor-codetheslicesin somewaysothatyouknow whichsliceis which.

1.2.3 BasicLogical Functions

Oneof thenicefeaturesof MATLAB is theexistenceof logicalmatrices,whicharejustarrayswith elementsthatareeitherzeroor onedependingonwhetherastatementis trueor false.Let’s returnto x andf giveninthefirst sectionabove. Re-inputtheseinto MATLAB (rememberA !) andnow let’s manipulateusinglogicalmatrices.For example,supposethatwewould like to plot only thepositive portionsof f. Define

fplus=( f>=0 );

Thearrayfplus is exactlyaslongasf (thatis 101elements)but containszeroswheref T 0 andoneswheref U 0. To plot f in yellow andonly its postive partin little redcircles,

plot(x, f, ’y’, x, fplus.*f, ’ro’)

By multiplying f andfpluselementby elementwehave createdanew entitywhich is thepositive partof fwheref is positive andzerowheref is negative. If we wantedto show thenegative partof f in little bluetriangleson thesamegraph,wecould

hold on, plot(x, (1-fplus).*f,’b ˆ’ ), hold off

Theselogicalmatricescanalsobeusedto createpiece-wisefunctions,whichwewill seenext.

Supposeyou wantedto make a function V which wasGaussianfor two standarddeviations(

EXW), and

thenuniform (with value V3� EXW ) for two standarddeviations,andthenzero,andthenthat you wantedtore-normalizeit so that the resultingfunction still representeda probability densityfunction (pdf). Pick astandarddeviationof .5; anormalpdf with standarddeviation .5 is givenbyY �[Z E0]\_^ � #�` FFirst let’s definethespaceandnormalvectors:

x = 6/100*[-50:50];N = sqrt(2/pi)*exp( -2 *x .ˆ 2) ;

Now we needlogical matricesfor the differentportionsof the pdf we arebuilding. Thesewe will call‘norm ’ and‘uni ,’

norm=(abs(x)<= 1) ;uni=(abs(x)>1 & abs(x)<=2);

Page 8: Spatio-Temporal Models in Ecology; an Introduction to ...adler/oldcourses/minicourse/matlab/labs_pow… · Spatio-Temporal Models in Ecology; an Introduction to Integro-Difference

1 LAB 1 – INTRODUCING MATLAB 8

The MATLAB commandabs(x) returnsthe absolutevalue of x ; the statement‘ (abs(x)<=1) ’ testswhetheror not the absolutevalueof x is smalleror equalto 1, returningthe value‘1’ if it is, and‘0’ ifit is not. The arraysnorm anduni will thuscontainonly oneswherethe pdf will be normalandthenuniform,respectively. Now wecancreateavector, pdf , whichwill have thepropershapebut will nothaveunit integral:

pdf=N.*norm + sqrt(2/pi)*exp(- 2) *u ni ;

Youshouldplot this to seethatit is correct.Finally wemustnormalize.Wehavedefinedagrid with spacing6/100=.06,soaquickapproximationof theactualintegral wouldbe

mass=.06*sum(p df )

The commandsum addsup all theelementsof a vectorinput, so that the above is equivalentto a simpleReimann-sumapproximationto theintegral. A betterapproximationwouldcomefrom thetrapeziodrule

mass=.06*trapz (p df)

whichsumstheaverage valuein eachcell. Now wecannormalize,

pdf=pdf/mass;

Now plot this. Youcanuseup-arrows to justfind thecommandyouusedlasttime,or youcancompareit totheprevious(unnormalized)functionby usinghold on andhold off.

EXERCISE 4: A functionwhich we will seeagainin dispersalis thesteady-statesolutionto thediffusion-lossmodelwith a localizedsourceat theorigin,�� �"! �R#$# 9ba � �bc ) � �d %thesteady-state( , Dfe ) solutionof which is+ � ��-� cE . ! a 25476hgi 9kj a!"l � l mn FUnfortunatelythis predictsa small,but perceptiblepresenceof a diffusingparticleinfinitely far away fromthe origin. Oneway to addressthis would be to chopoff the function

+at somerealisticpoint andthen

normalizetheresultingfunction. Let c � � % a � / and!o� � andtruncatethefunction

+at 50, 25, and

10 percentof its peakvalue,thenre-normalizeso that the resultingfunction is a pdf. On a singlegraph,comparethesethreepdfsto a (normalized)versionof theoriginal function.

1.2.4 Learning about Matrix Manipulation and Fourier Transforms using the Demos

Now thatyouhaveaMATLAB basis,youmightfind it usefulto tourthroughsomeof MATLAB ’scababilitiesusingdemos. Thedemosarea setof GUI slideshows which illustratevariousMATLAB functions.So,onthecommandline type

demos

Page 9: Spatio-Temporal Models in Ecology; an Introduction to ...adler/oldcourses/minicourse/matlab/labs_pow… · Spatio-Temporal Models in Ecology; an Introduction to Integro-Difference

1 LAB 1 – INTRODUCING MATLAB 9

anda window shouldpop up on screenwith a variety of MATLAB subjects.To get comfortablewith thedemosandseesomeof how MATLAB handleslinear algebraclick on Matrices in the left handwindow,followed by Basic matrix operations in the right handwindow, and then Run Basic matrix... on thelower-right handcornerbutton.A new window will appear(theSlideshow Player) whichyoucanusethento pagethroughslideswhich illustratevariousMATLAB matrix operations,which areusefulto know. Youcanactually type the commandsappearingin the slide show in your commandwindow to seehow theywork, which is probablythebestway to learn. Pay particularattentionto how to setup matricesandfindeigenvalues.

EXERCISE 5: TheNicholson-Bailey modelfor host-parasiteinteractionsisY qpsr � a Y \ ^Rt?u_v def� + � Y �%�wx %w qpsr �"y Y L � 9 \ ^Rtzu_v O def�|{ � Y %�w FThesteadystatecorrespondingto coexistenceof hostandparasitein thismodelis givenbyw � �~} � � a � Y � � a } � � a � y � a�9 � FTheJacobianmatrix (foundby hand,not MATLAB !) is� +�� � w � % Y � + u � w � % Y � { � � w � % Y � �{ u � w � % Y � �� � � a \ ^Rt?u � 9 � Y � a \ ^Rtzu �y L � 9 \ ^Rtzu � O � y Y � \ ^Rtzu � � FShow thatwhen � � ' F '1�_�G% y�� � % a � E (correspondingto the interactionbetweena greenhousewhiteflyand its chalcid parasitoid)that the steadystateis unstable. At the very leastyou will needto take theeigenvaluesof a 2x2 matrix andto seeif any of theseeigenvalueshave magnitudegreaterthanone. Canyou think of a way to plot a stability diagramin

awhich will illustratethat theseequilibriumpopulations

areneverstable?

In therestof thecoursewewill beusingtheFastFourierTransform(FFT) to evaluatetheconsequencesof dispersal. You can usethe demos facility to start learningaboutFFTs and their implementationinMATLAB . To begin with, click Numerics in the left-handwindow andthenFast Fourier Transform intheright handwindow, followedby clicking on Run Fast Fourier... on thebutton in the lower right handcorner. Youcannow pagethroughslideswhich illustratehow onecanusetheFFT to analyzesunspotdata.I suggesttyping

help fft

first to get a ideaof whattheFFT is all about,if youhavenever usedFourier transformsfor dataanalysis.Wewill beusingFFTsa lot, sodon’t despairif theseseema little cryptic just now. Remember, if you wantto seewhatany of thecomponentcommandsin thedemodo, you canalwaystypehelp SUBJECT in thecommandwindow andit will almostcertainlygive youeitherno informationor moreinformationthanyoureallyneed.

Congratulations!Youhave ‘jumpedin thedeepend’with MATLAB , but youdidn’t sink!

Page 10: Spatio-Temporal Models in Ecology; an Introduction to ...adler/oldcourses/minicourse/matlab/labs_pow… · Spatio-Temporal Models in Ecology; an Introduction to Integro-Difference

2 LAB 2 – DISPERSAL 10

2 Lab 2 – Dispersal

2.1 Goals

During this lab studentswill useMATLAB to becomefamiliar with methodologyfor simulatingtheproba-bilistic dispersalof organismsusingFFTs(FastFourierTransforms).In particular, studentswill:� Visualizeandunderstandavarietyof dispersalkernelsin oneandtwo dimensions.� Be awareof the relationshipbetweenprobabilitykernelsandspecialsolutionsto partialdifferential

equations(PDE).� UseMATLAB ‘M’ files to simplify simulations.

2.2 Probability and Dispersalin OneSpaceDimension

2.2.1 Dispersalvia RandomWalks and the Diffusion Equation

Many of thebasicprobabilitykernelsassociatedwith populationdispersalfind their basisin partialdiffer-entialequations.For example,thenormaldistribution is associatedwiththediffusionequation�R �"! �R#$# FThe diffusion equation,amongotherthings,modelsthe probability ( � ) of finding an individual nearanyspatiallocus(

�) atsometime , , giventhattheindividual is moving by takingrandomlychosenstepsof sizea

to the left or right at a rateof onestepper time interval � . The stepsizeandtime interval occurin thediffusionequationas !~� a �E � FFor thedispersalof a population,the importantsolutionto thediffusionequationis theonewhich beginswith a perfectly localizedindividual at the point

��� ' (in mathwe know this as the Dirac delta func-tion,

) � �d ), so that the initial conditionis � � � %�' ���) � �� . Thecorrespondingsolution, ��� , is calledthefundamentalsolutionandhastheform�M��� � %�, -� �. /10 ! ,s25476 8 9 ���/ ! ,X; FThis functioncanbe interpretedasthepdf associatedwith the locationof an individual at time , , movingunderrandomwalks,whichwasinitially locatedat

�P� ' .Now, supposea populationof organismsis dispersedover spacewith aninitial densityof w � � %�' . One

canthink of thenumberof individualslocatedin a small interval of size � = at a location = as w � =�%�' � = .Theseindidvidualsdisperserandomlyaccordingto thedistribution ��� ; thus,their probabilisticlocationata latertimewill be w � =�%�' ��� � � 9 =�%�, � =�%wherethe dispersalkernelhashadits argumentshiftedso that it is now centeredat the original locusofindividuals(

�b� = ). The total populationaftera time , would thenbe thesumover all suchinfinitesimalintervalscontainingpopulations:w � � %�, -�|���^ � w � =�%�' ����� � 9 =�%�, � = def� w � � %�' 3� �h� � %�, FThis latteroperationis calledtheconvolutionandis definedby theprecedingintegral.

Page 11: Spatio-Temporal Models in Ecology; an Introduction to ...adler/oldcourses/minicourse/matlab/labs_pow… · Spatio-Temporal Models in Ecology; an Introduction to Integro-Difference

2 LAB 2 – DISPERSAL 11

2.2.2 Convolutions and Fourier Transforms

TheFourierTransformof a functiondefinedonaninterval from

9 e to e is������ -� �. E 0 ���^ � �� �� \ ^���� # � � FThe transformedfunction

������ canbe thoughtof astheamountof ‘energy’ the functionhasstoredin the‘wave’ \ �S� # ���5 1� ��� �� �¢¡ ����� ��� �d . A convenientpropertyof theFourierTranform(FT) is that theFT oftheconvolution is theproductof theFTs, £� � < ��� >� �E 0 ������ �< ��� FConsequently, aslick analyticway to evaluatea convolution withoutactuallydoingthenastyintegral is:

1. CalculatetheFT of � and

<.

2. In wavespace,evaluatetheproductof����� and

�< ��� .3.

£� � < ��� -� r��¤ ����� �< ��� F4. Invert thetransformof

£� � < to obtain � � < .Theonly turd in thisparticularpunchbowl is thatFTsarenotall thateasyto calculateor invert. Fortunately,thereis a very simplecomputationalroutine,calledtheFastFourierTransform(FFT) which will performtheseoperationsnumerically.

2.2.3 Numerical FFT

Thenumerical(or Discrete)FourierTransform(DFT) is definedwith summationsinsteadof integrals,�� � ��s¥ �¦§©¨ ^ �x¥ � ��Sª ���� \ ��¤ �S� §?« # %

wherethefunction � is thoughtof asbeingdefinedon the interval from�¬� ' to

�N� � , choppedup intoYchunksof length

���. If

Yis a power of two, (that is

Y � E®­ � E % / %?�G% � �G%?¯ E %?� / % � E �7%$°$°�° ) thereisanefficient numericalalgorithmfor calculatingthe DFT, calledtheFFT. Onecuriosityof the FFT is that(dependingontheimplementation)it generatesa factorof

Yin theoutput,thatis, for input ��Sª ���� it gives

outputY �� � insteadof simply

�� � . Consequently, theFFT of a convolution of two functionsdefinedon theinterval

��±³² '7% �©´ is£� � < � � �Y �� � �< � F

Supposenow we have a populationfunction V definedon a periodicinterval�h±*² 9¶µ % µ ´ , anda dispersal

function, � definedonthesameinterval. A blueprintfor calculatingthedispersedpopulation� � V usingtheFFTfollows:� UseFFT to calculate

�� � and�V � .� Calculate

£� � V � � ��·� �� � �V � . Theextra factorof

EXµallows for a changein the lengthof the interval

from 1 to

EXµ. As anoteof interest,thefraction

��·�is equalto thediscretestepsizein space,

���.� Invert theFFTto arrive at � � V3� �� .

An addedwrinkle is that,althoughit is theoreticallynaturalto centertheinterval at�P� ' , in discreteterms

this is unnatural.In generala shift hasto beperformedon thediscreteversionof V sothatthevalueof V at�P� ' is associatedwith thefirst elementof a vector, asin thefollowing diagram:

Page 12: Spatio-Temporal Models in Ecology; an Introduction to ...adler/oldcourses/minicourse/matlab/labs_pow… · Spatio-Temporal Models in Ecology; an Introduction to Integro-Difference

2 LAB 2 – DISPERSAL 12

2.2.4 Matlab Implementation

WecanuseFFTsin MATLAB to calculateconvolutionsrapidly. Let’sbegin by illustratingtheprocedureforapopulationinitially localizeduniformly between-1 and1, dispersingover timeinto amuchlargerdomain.TheFFTassumesperiodicity, soif wedefineaspaceinterval between-10and10with 256nodes(remembertheFFT is muchmoreefficient for computationsinvolving

E®­elements),weneedto take into accountthat

thenodecorrespondingto 10mustbeleft off (theFFT assumesthatwhatever datamightbespecifiedthereis identicalwith thedataat

�P� 9 � ' ). So,to definethisspace:

xlr=10; np=256; dx=2*xlr/np;x=dx*[0:np-1]- xl r; % OR, equivalentlyx=linspace(-xl r, xlr -d x, np);

Theindependentvariableis now defined.Let’s alsodefinethenormaldispersalkernelandtheinitial popu-lation:

p0 = (abs(x) <= 1);t=1; D=1;K=1/sqrt(4*pi* D*t)* exp( -x .ˆ 2/( 4* D*t) );

Having therelevantfunctionsdefinedwecannow take theFouriertransform

fp0=fft(p0);fK=fft(K);

Usingthe fact that the transformof theconvolution is theproductof the transforms,we cannow evaluatetheconvolution:

fp1=fK.*fp0;p1=dx*fftshift ( ifft( fp1 ) );

Thevectorp1 now containsthedispersedpopulationafter1 time unit, but therearesomeweird thingsin thecommandthatneedexplaining. First off, thecommandfftshift basicallychopsa vectorin half andinterchangesthefirst andsecondhalvesasblocks.In thiscontext it is necessarybecausetheMATLAB FFTis built on the assumptionthat functionsaredefinedon the interval from 0 to 1, asopposedto centeredaround0. Secondly, the factorof dx . Firstly, for numericalefficiency theFFT multipliesa vectorby np ,andtheinverseFFTdividesby thatfactor. Sincewehave implementedaproductof FFTs,weneedto divideout a factorof np . Secondly, numericalFFTsassumethat functionsaredefinedon aninterval of length1,but our functionis definedon an interval of length2*xlr , andsotheFFT mustbescaledby the intervallength.Together, thesetwo conditionsareequivalentto multiplyingby thestepsize,dx=2*xlr/np ,whichis convenientfrom ourperspective.

Now let’s seewhatwehave done:

plot(x,p0,’r’, x, p1, ’y ’)

You shouldalso get a warning about imaginarynumbersbeing ignored. This occursbecausethe FFTrequirescomplex numbers,and numericalroundingcreatesvery small imaginarycomponents,even forperfectlyrealdatafields.Thebestwayto getaroundthis is to take therealpartafterconvolution,whichwewill do in thefuture.Now it is possibleto keepiteratingtherandomdispersalof thepopulation.Wecangetthepopulationafterthenext timestepusingasinglelong,cryptic MATLAB command:

p2=dx*real( fftshift( ifft( fft( p1 ).*fK ) ) );

Page 13: Spatio-Temporal Models in Ecology; an Introduction to ...adler/oldcourses/minicourse/matlab/labs_pow… · Spatio-Temporal Models in Ecology; an Introduction to Integro-Difference

2 LAB 2 – DISPERSAL 13

Usehold on to plot thisagainstthepreviousresults.Doesit look reasonable?Usetheup-arrow ( A ) andeditthepreviouscommand,plot, andseethepopulationafterdispersalover threetimeunits.

EXERCISE 6: UseMATLAB to definethepopulationdensityfunctionw � � %�' >�¹¸ E�9³E l � l % 9 ��º � º�� %'7% l � l&» � %ontheinterval from-15to15. In asinglewindow plot randomdispersalof thispopulationaftertimesof .5,1,2,and4 with diffusionconstant

!~� E. (Using A herewill simplify yourlife!) Usetrapz to approximatethe

integralof thepopulation(totalnumberof individuals)andconvinceyourselfthatthenumberof individualsis beingconserved.

2.2.5 Dispersaland Settling with a LocalizedSource

Anotherinterestingdispersalmodelinvolvesassumingrandommotionfor propagules(seeds,spores,pollen,motile larvae)while they arein themediumandthensettlingontoa substrateat somerate

a. If propagules

areinitially releasedat thepoint�¼� ' thePDEmodellingthedensityof propagulesin themediumis�� �"! �R#$# 9 �&�x% � � � %�' (�*) � �� F

Thedepositionof theseparticleson thegroundis trackedby thevariable½ , whichsatisfies½ � � ½ % ½�� � %�' >� ' FThe long-time( , D¾e ) solutionfor ½ is a dispersalkernel,andcanbewritten (following Neubertet. al.1995) ��¿À� �d-� Z �/ ! 25476ÂÁ 9 Z �!Ãl � l Ä FThefollowing commandsplot this functionon thepreviouslydefinedx interval:

D=1; a=2;KS=sqrt(.25*a/ D) *ex p( -s qr t( a/D )* abs( x) );plot(x,KS,’r’)

Now try plottingKS on thesameaxes,varyingthesettlingrate, � , to getanideaof how it behaves.

EXERCISE 7: For auniformdistributionof sourcesbetween-1 and1 investigatethedispersalof propagulesaccordingto theprobabilitydistribution � ¿ givenabove. Onthesamesetof axesplot theeffectof changing� on thedispersalof thepopulation.

2.2.6 Ballistic Dispersal

A modelfor ballistic dispersalof sporesfrom groundlevel in randomdirectionsis givenby Neubert,KotandLewis, 1995,by ��Å �ÇÆÈÉ ÈÊ

r¤GË ÌÎÍÏ ` ^ # ` % l � l ºÑÐ `Ò %'7% l � l&» Ð `Ò F

Page 14: Spatio-Temporal Models in Ecology; an Introduction to ...adler/oldcourses/minicourse/matlab/labs_pow… · Spatio-Temporal Models in Ecology; an Introduction to Integro-Difference

2 LAB 2 – DISPERSAL 14

Herey

is thespeedatwhichsporesareejectedand

<is thegravitationalconstant.Undertheassumptionthat

everysporegerminatesandthesporulatingadultsdieeachgeneration,thespreadof apopulationof fungi ismodelledby wxÓ_psr � ��-� ��Ô � wsÓ � �d %whereÕ denotesthegenerationnumberand w3Ö � �� denotestheinitial distribution of thecolony.

Wecouldillustratethespreadof thecolony usingthecommandswehavealreadymasteredin MATLAB

, but this is agoodplaceto usean‘m’ file, which is a MATLAB scriptwhichrunsasequenceof commands.In the File menuof the MATLAB commandwindow click on New andthenM-file. An editor/debuggerwindow will popup, in which you cantypein a seriesof commands,save it asanM-file, andthenexecutethewholesequenceby referringto theM-file. Below appearsthetext for anM-file modellingthisdispersal.

%% BALLSPORE%% a Matlab M-file which models ballistic dispersal of fungi in 1-D%

pold = pnew; % define initial condition, this step --% USER MUST DEFINE THE FIRST pnew% BEFORERUNNINGTHIS PROGRAM

KB=1./(pi*sqrt( cˆ 4/ gˆ 2-x .ˆ 2) ). *( abs (x ) <= cˆ2/g);% define dispersal kernel, taking care that it is zero in% the right places

KB=KB/trapz(dx* KB);% this normalizes the probability kernel. Because of% the singularities at the ends this is an important% step -- otherwise there will be net loss

fKB=dx*fft(KB); % Take FFT of dispersal kernel, multiplying by dx to save% that step later

fpnew = fKB.*fft(pold);% FFT of new dispersed population

pnew = real(fftshift( iff t( fp new) ));% new dispersed population

hold on, plot(x,pnew,’r’ ), hold off% plot results on current figure

Whenyouhavethisall typedin to theeditor, savethefile asballspore.mandclick onthecommandwindowto activateit. Make sure that thedirectoryyouare in in thecommandwindowis thesameasthedirectoryyou savethe program ballspore.m in! Now we mustsetthe initial spaceup, the parameters,andtheinitial colony:

g=980; % cm/sˆ2 for gravity constantc=50; % cm/s speed of ejectionxlr=15; np=256; dx=2*xlr/np;x=-xlr+dx*[0:n p- 1]; % define independent variablepnew=(abs(x) <= 1);

Page 15: Spatio-Temporal Models in Ecology; an Introduction to ...adler/oldcourses/minicourse/matlab/labs_pow… · Spatio-Temporal Models in Ecology; an Introduction to Integro-Difference

2 LAB 2 – DISPERSAL 15

Now wecanplot theinitial populationandcall ballspore, whichwill plot subsequentdispersedpopulationson thesamegraph.So,in thecommandwindow type:

plot(x,pnew,’y ’)ballspore

Now, you canseethe evolution of the dispersingpopulationby using A to bring back the ballsporecommandandthencarriagereturnto executethecommand.

2.2.7 Movementat ConstantSpeedfrom a Sourceand Settling

If propagules(density� ) moveat constantspeedto theleft andright away from asourceandsettleat somerate ×x� , , theprecipitatedindividuals(density½ ) satisfythefollowing systemof PDE(from Neubertet. al.,1995): �� � 9 y sign� �� �R# 9 ×s� , �x% ½ � ×x� , � FIf theseequationsaresolved with initial conditions� � � %�' Ø�Ù) � �� % ½�� � %�' M� ' correspondingto a unitreleaseof propagulespreciselyat theorigin, thefinal distribution of settledindividuals( ��Ú ) satisfies�E y ×�Û l � lyPÜ 25476 8 9 �*Ý Þ5ÝÌÖ ×x��ß �Gß ; FThis solutiondiffers from �M¿ primarily in that thereis no diffusion processoperating.Choosing×x� , k�¯X�Gà5, � givesaninterestingbi-modalsolution��Ú � ¯X� à l � l �E y à 25476 8á9 Û � l � ly Ü à ; F(seeNeubertet. al. for otherchoicesfor × andtheir consequences).Try plotting this kernel for variouschoicesof

yandseehow it behaves.

EXERCISE 8: Underthe assumptionthat every settledpropagulebecomesa propagule-producing adult,write anM-file in MATLAB thatwill allow youto investigatethemulti-generationaldispersalof aninitially-localizedpopulationwith dispersalprobabilitygiven by ��Ú . How would you modify this codeto reflectmortalityor non-germination– sayonly 50%of dispersedindividualssurvive to becomeadults?Couldyoumodify it to have morethanonegenerationproducingpropagules?

2.3 Probability and Dispersalin Two SpaceDimensions

Now we have morethanenoughunderstandingto move on to two-dimensionaldispersal.Mainly thereisnothingmorecomplicatedthanin onedimension,exceptthat it canbe computationallymuchmoretimeconsumingandmoredifficult to visualize. But the computationaltechniquesare identical in MATLAB ,exceptthata few commands(mainly theFFTcommands)needto bechangedto 2-D versions.

2.3.1 Dispersalvia RandomWalks in Two Dimensions

As in thecaseof onedimensionalrandomdispersal,dispersalgeneratedby randomwalksin two dimensionsis modelledby thediffusionequation,� �"!Pâ � � �*! � � #$# � �Rã?ã F

Page 16: Spatio-Temporal Models in Ecology; an Introduction to ...adler/oldcourses/minicourse/matlab/labs_pow… · Spatio-Temporal Models in Ecology; an Introduction to Integro-Difference

2 LAB 2 – DISPERSAL 16

Thefundamentalsolutioncorrespondingto initially localizeddata� � � %�=�%�' (�*) � �d�) � = is givenby� � � � � %�=�%�, >� �/10 ! , 25476 8á9 � � � = �/ ! , ; FThefollowing MATLAB commandsdefinespaceandthedispersalkernelK2D:

xlr=10; ylr=10; np=128; dx=2*xlr/np; dy=2*ylr/np;x=linspace(-xl r, xlr -d x, np);y=linspace(-yl r, ylr -d y, np);[X,Y]=meshgrid (x ,y) ;t=1; D=1;K2D=1/(4*pi*D* t) *ex p( -( X. ˆ2 +Y. ˆ2 ). /( 4* D*t )) ;

Youmaywish to take a secondandvisualizethis usingsurf or pcolor andshadingflat or shadinginterp.Now, to seehow a populationinitially localizedin therectangle� 9 �kº = ºä� æå � 9 ¯ º � º ¯ disperses,use:

p0=(abs(X)<=3 & abs(Y)<= 1);fp0=fft2(p0);fK2D=dx*dy*fft 2( K2D);fp1=fp0.*fK2D;p1=real( fftshift( ifft2( fp1 ) ) );

Somethingsto observe: theoverall formatfor implementingdispersalis thesameasin onedimension,withtheexceptionsthatfft andifft arereplacedby fft2 andifft2 ; thereis now amultiplicationby bothdx anddy to implementtheconvolution. To visualizehow theinitial field relatesto thedispersedfield wewill usea combinationof graphics– onechoicewouldbecontoursfor theinitial field anddensityplotsforthedispersedfield, asin:

pcolor(X,Y,p1) ,s had in g flat, hold on, contour(X,Y,p0,’ m’ ), hold off

You maywantto furtherusetheoptionsaxis square andcolormap hot. Thehot colormap,in particular,is usefulin interpretingdensityplots,sinceit givesa clearindicationof high andlow values.To seewhichcolorscorrespondto which values,you mayalsousethecommandcolorbar, which will adda color scalewith associatedscalarvalues.Youmightalsowantto try a combinationsurface/contourplot, asin

surf(X,Y,p1+1) ,s had in g flat, hold on, contour(X,Y,p0,’ m’ ), hold off

For mostapplicationsI find it easiestto usecombinationsof densityandcontourplots.

EXERCISE 9: Dispersethis populationfor one more time step,saving p1 and creatinga new, twice-dispersedpopulation,p2 . Plotall threepopulationsonasinglegraphusingcontoursin two differentcolorsfor p0 andp1 andahot-coloreddensityplot for p2. Usethecombinationof commandsdx*dy*trapz(tra pz (p 2) )to estimatethe doubleintegral of p2 , andthencomparethat to the previous two dispersalslicesto makesurethatthepopulationis beingconserved.

2.3.2 Modal Dispersalin Two Dimensions

Well, thereweremany, many different thingsto do in onedimension,andasyou might guessthereareinfinitely many morein two dimensions.We will discover moreof theseaswe go along,but asa parting

Page 17: Spatio-Temporal Models in Ecology; an Introduction to ...adler/oldcourses/minicourse/matlab/labs_pow… · Spatio-Temporal Models in Ecology; an Introduction to Integro-Difference

2 LAB 2 – DISPERSAL 17

shot let’s model a combinationof advection and diffusion in two dimensions. Supposea populationisperformingrandomwalksin a mediumwhich movesin a particulardirectionwith velocities� and ½ in the�

and = directions,respectively. Without belaboringthedetails,it canbeshown thatanindividual initiallylocalizedat theorigin disperseswith probability� � Ú � � � %�=�%�, (� �/10 ! , 25476 8:9 � � 9 ��, � �*� = 9 ½ , �/ ! , ; FEXERCISE 10: Investigatethe advective/diffusive dispersalof a populationwhich is initially localized,accordingto theprobabilitykernel � � Ú . Pick

!~� FIE_H, � � E % ½ � E , andusethecommand

p0=(abs(X+8)<= .5 & abs(Y+8)<=.5);

to specifythe initial population.Definethedispersalkernel � � Ú in MATLAB usingthepreviousgrid, andusinga sequenceof commandson a single line dispersethis populationover oneunit of time. Using acombinationof contoursanddensityplotsshow thepopulation’s progressover threetimeunitsof dispersal.(Alternatively, youmaywantto write asingleM-file to do this.)

EXERCISE 11: Build an M-file which will allow you to investigatethe behavior of a populationin anadvection/diffusion settingwith randomwinds. That is, over eachperiod of dispersal(‘day’) the windspeedis constant,but from day to day thedirectionwill vary randomly. Hint: In MATLAB thecommandfor generatinguniformly distributedrandomnumbersis rand. Visualizea coupleof dispersalstepsfor apopulationlocalizedinitially uniformly in a disk of radius1 centeredat (0,0). Would it behardto modifyyourprogramto accountfor randomchangesin wind speedaswell?

2.3.3 Turchin’sModel for Prey-Taxis

Anothercharacteristicof moving, living thingsis thatthey movefor areason,generallyto getsomewhereoravoid something.An examplewould bepredatorsor parasitessearchingfor prey/hosts.Eventhesimplestof beingsis likely to slow down, thatis, to take shorterstepsin its randomsearchingmotions,whenit is inthepresenceof prey items.Let ç�� � %�= bethedensityof ‘victims’ in space,andlet w � � %�=�%�, bethedensityof searchers(predators/parasites). Let

! � bethediffusivity of w in theabsenceof victimsand! r T ! � the

diffusivity in thepresenceof victims. Varyingmotility of thesearchercanbemodelled(following Turchin,Reeve,CroninandWilkens,1997)byè �Cç � ! � �Cç"�é� ���¢ç � `�ê �"! � 9 � ! � 9 ! r çç"�é� ! � �®! rë ì�í îïð %where � is a saturationparameterdescribinghow rapidly motility changeswith densityof victims. Thefunction

�è canbeintepretedastheprey-basedperturbationto the ‘normal’ motility of predatorsin searchmode.A PDEmodelfor theredistribution of searchersin responseto thedensityof victims iswx �|â � ² è �Cç w ´ FThe ideais that in regionswith prey predatorsslow down (to eattheprey, or at leastto hug themandpetthemandstroke their fur thewrongway), while in regionswithout prey they speedup (searching).Thus,whenadistributionof predatorsencountersadistributionof prey thepredatorstendto ‘pile up’. In principle

Page 18: Spatio-Temporal Models in Ecology; an Introduction to ...adler/oldcourses/minicourse/matlab/labs_pow… · Spatio-Temporal Models in Ecology; an Introduction to Integro-Difference

2 LAB 2 – DISPERSAL 18

thisequationis alwayssoluble,but in practicesolutionrequiresadifferentcalculationfor eachchoiceof ç .A veryapproximatesolutionwith initial condition w3Ö � � %�= is givenby:w � � %�=�%�, >� \ ^Rñ ` ïðóòSô�ò #Xõ ã5öqö /10 ! � , � w Ö � � %�= 3� 254G6 8:9 � � � = �/ ! � , ; � FRememberthat

â � � � Lø÷ `÷ # ` � ÷ `÷ ã ` O � andthat* denotesthetwo-dimensionalspatialconvolution.

Thissolutionbecomesincreasinglyvalid as ç tendsto zero(or asthediffusivities becomemorealike),anddependscritically on � being‘large’. Thesolutionis not valid at all for very large or highly variabledensitiesof prey, or when � is small,or when , is takento belarge.Fortunately, solvingPDEis notourbestandhighestgoal. As a modelfor victim-taxis,theapproximationabove canserve perfectlywell! We mustseparatetheelementswhich give therandomcharacterof diffusivity from theelementsdefiningthespatialstructureof changingmotility in thepresenceof prey. Theapproachwill beto:

1. convolve with a randommotionkernel,

2. multiply by anexponentialfunction( \ ^Rñ ` ïð ) to give theproperspatialstructure,and

3. normalizeto ensurethatpredatorshave neitherbeencreatednordestroyed.

In step2, anadditionalcrucialoperationwill be thenumericalcalculationofâ�� �è usingMATLAB’s built-

in Laplaciancalculator(del2). Below appearsMATLAB pseudo-codewhich implementsthis model forprey-taxis,assuminganinitial distribution of prey distributedin aGaussianoval centeredat

�¼� H � = ,ç�� � %�= >� � '_' 254G6 8á9 � � 9³H á�/ 9 � = 9³H � ; %anda populationof predatorsinitially distributeduniformly in a circle of radius3. In particular, noticethe‘normalization’ stepwhich keepsthe predatorpopulationfrom growing or shrinking,andthe separationbetweenthepurely randommotion(evaluatedwith convolution) andthemultiplicationby theexponentialfactor, whichgivesspatialstructureto thetaxis.

Page 19: Spatio-Temporal Models in Ecology; an Introduction to ...adler/oldcourses/minicourse/matlab/labs_pow… · Spatio-Temporal Models in Ecology; an Introduction to Integro-Difference

2 LAB 2 – DISPERSAL 19

%% Testing out Turchin-taxis%% Set up space:%np=128;xl=10; dx=2*xl/np;x=linspace(-xl ,x l-d x, np);[X,Y]=meshgrid (x ,x) ;

% Define parameters

D2=2; D1=1.5; % the motilitiesd=1; t=4; % saturation parameter, timeV=exp(-(X-5).ˆ 2. /4- (Y -5 ). ˆ2 ); % these are the victims:

% perturbation to the basic motility (D2):muhat=4*del2(( D2-D1 )* (D 2* V) ./( d* D1+ D2*V) ,dx,dx);

% Set initial population of predators

P=((X.ˆ2+Y.ˆ2) <=4);numP=dxˆ2*trap z( tra pz (P )) ; % total number predators

% Define dispersal kernel

K=.25/(pi*D2*t )* exp (- (X .ˆ 2+Y.ˆ 2) /( 4* D2*t) );fK=dx.ˆ2*fft2( K) ;

% Disperse population according to turchin-taxis

fP=fft2(P);Pt=exp(-muhat* t) .*r eal( ff ts hif t( if ft 2( fP. *f K) )) ;

% Normalize the dispersed population

numPt=dxˆ2*tra pz (tr apz( Pt )) ;Pt=numP/numPt* Pt ;

% Plot the results in comparison with the victims

pcolor(X,Y,Pt) , shading interp, colormap hot, axis squarehold on, contour(X,Y,V, ’b ’) , hold off

Onedifficulty with this sortof approachis thatit is not ‘linear’ in , , thetime step.Thatis, takingtenstepswith , � � will be different thantaking five stepswith , � E

or two stepswith , � H. In general,the

approachgetsmorelinear-actingfor shortersteps(which is just whereonedoesnot wish to useit for anIDE approach).However, it is only amodelfor chemotaxis,nomoreor lessvalid in anabsolutesensethanthePDEmodelappearingin thepaperof Turchinet. al. (1997). It is important,though,to rememberthatthereis now anextra ‘parameter’,, , whichmustbespecified.

Page 20: Spatio-Temporal Models in Ecology; an Introduction to ...adler/oldcourses/minicourse/matlab/labs_pow… · Spatio-Temporal Models in Ecology; an Introduction to Integro-Difference

2 LAB 2 – DISPERSAL 20

EXERCISE 12: With theabove MATLAB codefor defininga prey-tacticdispersalkernel,determinehowa populationof predators,initially localizednear

�K� ' � = , redistributesin responseto thepopulationofvictimsgivenabove. In two differentfiguresplot thedensityresponseof thepredatorsasadensityfield after4 and8 time unitsof dispersal.Indicatethestartingpoint, andplot contoursof thevictim field to seehowthe taxisorientsthepopulation.Checkto seethat thenumberof searchingindividualsis beingpreserved.Canyouexplain theseresultsin termsof decreasedmotility in thepresenceof they prey?

Congratulations!You have learnedmoreaboutprobabilisticdispersalandconvolutionsin MATLAB thanmostpeoplearelearnin a life time!

Page 21: Spatio-Temporal Models in Ecology; an Introduction to ...adler/oldcourses/minicourse/matlab/labs_pow… · Spatio-Temporal Models in Ecology; an Introduction to Integro-Difference

3 LAB 3 – IMPLEMENTING AN INTEGRO-DIFFERENCEMODEL 21

3 Lab 3 – Implementing an Integro-DifferenceModel

3.1 Goals

In this lab we will learnthephilosophyandsomeof thepracticalMATLAB pitfalls associatedwith imple-mentinganIntegro-DifferenceEquation(IDE) model. An IDE is onenaturalway to addspatialdynamicsto a temporallydiscretemodel.In this labyouwill:ù Learnhow MATLAB implementsmoviesandloops.ù Coupledispersalmodelswith discrete-timepopulationdynamics.ù Learnsomewaysto implementenvironmentalheterogeneity.ù Begin to seesomeof theuniquebehaviors associatedwith spatio-temporaldynamics.

3.2 EnhancedNicholson-BaileyModel

For purposesof demonstrationwewill look at versionof theNicholson-Bailey discretemodelfor theinter-actionbetweenhostandparasitespecies.A nice,detailedaccountis presentedin MathematicalModelsinBiology, pp. 79–89,by LeahEdelstein-Keshet.Thepurelytemporalmodeltracksthepopulationof thehostspecies,úØû , andtheparasitespecies,üsû asa functionof discretetime, ý . TheEnhancedNicholson-Baileymodel(ENB) mapscurrentpopulationlevelsto futurepopulationlevelsaccordingtoú�ûqþsÿ�� ��� ú�û���üxû����"ú�û��� ��������� ú�û��� ��� üsû���� (1)üsûqþsÿ�� � ú�û!��üsû"�#�%$Àú�û � ��� ��& (' �)� üsû�*+�-, (2)

Theright-hand-sideof theseequationscanbeviewedasaproductof probabilitiesof encounterrelatedto the‘Law’ of MassAction, that is, theprobabilityof anencounterbetweenhostandparasiteis proportionaltoú�û/.�üxû . Theprobabilityof ahostencounteringparasitestwiceis ú�û0.�ü21û � andtheprobabilityof encountering$ parasitesis ú�û3.®ü54û . If

�is theperparasiteprobabilityof parasitization,theprobabilityof a hostbeing

parasitizingat leastonceis� ú�û�üxû6 798 :1 encounter;

�< � 1 ú�û�ü 1û6 798 :2 encounters

;�= �?> ú�û�ü >û6 798 :

3 encounters; .@[email protected]� ú�ûCB ����DFEHGJIFKML ,

Thevariousfractions ÿ4ON occurbecausetheorder of theencountersdoesnot matter. For example,thereare= �QP&R waysfor threedifferentparasitesto encountera particularhost,but if theorderof theseencountersdoesnot matterwe needto factorout that P&R to get theprobabilityof threeorder-independentencounters.Consequently, theright-hand-sideof

<canbethoughtof astheexpectednumberof hostswhich have been

parasitizedatleastoncetimesthenumberof fuzzybabyparasites( $ ) producedbyeachsuccessfullyinfectedhost.Theproductú�û��� (' �S� üxû�* ontheRHSof equation(1) is theexpectednumberof non-parasitizedhosts,

which thenreproducewith fecunditybasedon theRicker map, ��& TB �VU/���XW KY[Z L .Therearethreefixedpointsfor ENB:

� ú\��ü]��� ��^ � ^ �_� � � � ^ � anda mixedpopulation� ú[`/��üV`a� which

mustbecalculatedusinganonlinearrootfinderon theequationsú ` � ��� ú ` ��ü ` � and ü ` �b � ú ` ��ü ` �_,This mixed populationis stablefor an intermediaterangeof fecundity(

�) andparasiteeffectiveness(

�).

When�

is sufficiently small the mixed populationis unstableand the parasitesgo extinct ( ú�ûdc �).

When�

is sufficiently largethemixedpopulationis alsounstable,but in this casetherecanbestablelimit

Page 22: Spatio-Temporal Models in Ecology; an Introduction to ...adler/oldcourses/minicourse/matlab/labs_pow… · Spatio-Temporal Models in Ecology; an Introduction to Integro-Difference

3 LAB 3 – IMPLEMENTING AN INTEGRO-DIFFERENCEMODEL 22

cycles,oscillationsleadingto extinction, or period-doublingbifurcationsleadingto chaos.To seediscretepopulationdynamicsin MATLAB you will needto implementa for loop. For example,to seebehavior intheENB youcanimplementthefollowing M-file:

%% ENB -- a small script for implementing the Enhanced Nicholson Bailey Model%

n=1; a=4; r=1.75; k=1; % set parameters for ENBngens=50; % set number of generationsh=zeros(1,ngen s) ; p=h; % initialize population vectors

p(1)=.1; h(1)=.9; % set initial conditions

for t=1:ngens-1 % iterate ENB for next ngens-1 generations

h(t+1)=h(t)*exp( r*(1 - h(t)/k) - a*p(t) );p(t+1)=n*h(t)*( 1 - exp(- a*p(t) ));

end % of iteration over generations

plot(h,’b’),ho ld on, plot(p,’r’),hol d offlegend(’host’, ’p ara si te ’)

Noticethefor andend statementsabove,whichdefinea loop in theMATLAB script.Try runningthisprogramfor increasinglylarge

�valuesandseehow thedynamicschanges.

EXERCISE 13: The(un-enhanced)Nicholson-Bailey modelfor host-parasiteinteractionsisú�ûqþsÿe� fRú�û DEHG_I K �üsûqþsÿg� h5ú�û U0����D EHGJIFK Z ,Earlier(lab 1) we examinedthestability of thesinglenon-zerofixedpoint for this modelandshowedthatit is always unstable.Write a MATLAB M-file which will allow you to set initial conditionsexterior tothe programandtheniteratefor somenumberof generations.(Hint: you may wish to modify the RHSof theseequationsto remove thepossibilityof negative values!)Additionally, plot thepopulationsagainstoneanother(phasespace)aswell asagainsttime (statespace).Theparameters

� � ^ , ^ =Fi �!hj� � �_f�� <correspondto the interactionbetweena greenhousewhitefly and its chalcid parasitoid. Now you havevisualizedthe well-known instability of what seemslike a pretty reasonablemodel. Nicholson(1957)proposedthattheinstabilityandsubsequentdeathof bothspecieswouldbemoderatedin naturebycontinualre-invasionof patches.

3.3 Matlab Implementation of the SimplestIDE

Probablythesimplestpossibleintegro-differenceequationis onewhich incorporatesasinglestepof disper-salfollowedby asinglestepof linear, Malthusiangrowth at aper-capitarateof

�:ü 4 þ)kl � �nm ü 4ü 4 þsÿ � � ü 4 þ kl ,

Page 23: Spatio-Temporal Models in Ecology; an Introduction to ...adler/oldcourses/minicourse/matlab/labs_pow… · Spatio-Temporal Models in Ecology; an Introduction to Integro-Difference

3 LAB 3 – IMPLEMENTING AN INTEGRO-DIFFERENCEMODEL 23

Theorderof thesetwo steps(reproduction/dispersal or dispersal/reproduction) is not important,mathemat-ically, althoughit canhavesignificantbiologicalrepercussions(seeAnderson(1991)for adiscussionin thecontext of plants). Onemay think of this asa model for an insectwhoseadult femalesdisperse( ü 4 þ)kl )andthenlay eggswith anoverall fecundityor

�(includingnumberof eggslaid perfemale,fractionof eggs

which hatch,fraction of larvaewhich survive to adulthood).The following MATLAB script executesthisscenariofor simpledrift anddiffusedispersaloverseveraltimesteps.

%% MALTHUS%% matlab code to evaluate dispersal due to convolution% of a spatial dispersal probability with a population density% function.%% p(x) - population density in x% K(x) - probability of individual dispersal to location% x starting at location 0.% xl - maximum x coordinate (also - minimum)% dx - spatial step delta x = 2*xl/np% np - number of points in discretization for x% (should be a power of 2 for efficiency of FFT)% c - center of spatial dispersal% D - diffusion constant (per step)% r - per-capita growth constant%

np=128; xl=5; dx=2*xl/np; c=.4; D=.25;r=1.15;nsteps=10;

%% discretize space, define an initial population distribution%

x=-xl+[0:np-1] *d x;p=(abs(x+3)<=. 5) ;p0=p; % keep track of initial population for comparison

%% define a dispersal kernel%

K=exp(-(x-c).ˆ 2/ (4* D) )/ sq rt (4* pi *D);

%% normalize K to make it have integral one%

K=K/(dx*sum(K) );

%

Page 24: Spatio-Temporal Models in Ecology; an Introduction to ...adler/oldcourses/minicourse/matlab/labs_pow… · Spatio-Temporal Models in Ecology; an Introduction to Integro-Difference

3 LAB 3 – IMPLEMENTING AN INTEGRO-DIFFERENCEMODEL 24

% calculate the fft of K, multiplying by dx to account% for the additional factor of np and converting from a% interval length of 1 to 2*xl. The fftshift accounts for% using an interval of (-xl,xl) as opposed to (0,2*xl).%

fK=fft(fftshif t( K)) *d x;

%% begin iterating the model%

for j=1:nsteps,

%% calculate the fft of p; perform the convolution%

fp=fft(p);fg=fK.*fp;

%% fg now contains the fourier transform of the convolution;% invert it, multiply by post-dispersal reproduction,% and take a look.%

g=r.*abs(ifft(fg )) ;plot(x,p0,’r’,x, g, ’b ’) , axis([-xl xl 0 1.6])pause(.5) % pause for .5 sec to see the plot

%% update p and move to the next time step%

p=g;

end % of the iterations

Therearesomefeaturesto noteaboutthis script. Thepause(.5) commandcausestheprogramto stopfor half a secondandplot. Try commentingout this line andrunningthe programagain– you will seeonly theendresultasopposedto the interveningsteps.Now try removing theparentheses,that is, replacepause(.5) with pause . This will causethe programto wait for userinput beforeproceeding– forexample,just hit thespacebarin thecommandwindow andtheprogramwill advanceonestep.Finally, toseeall thestepstogether, replacetheplot line with

hold on, plot(x,p0,’r’, x, g, ’b ’), axis([-xl xl 0 1.6]), hold off

This shouldallow you to seeall theiterationson thesameplot, with oneadditionalpereach‘click’ of thespacebar.

Page 25: Spatio-Temporal Models in Ecology; an Introduction to ...adler/oldcourses/minicourse/matlab/labs_pow… · Spatio-Temporal Models in Ecology; an Introduction to Integro-Difference

3 LAB 3 – IMPLEMENTING AN INTEGRO-DIFFERENCEMODEL 25

EXERCISE 14: Imaginenow that thenet fecundity,�, dependson space– that is, eggshatchandsurvive

betterin someregionsor others. Modify the programabove so that�

is 1.3 for o p�oSq � ,sr and� �t, i

elsewhere.(Hint: theMATLAB commandones(1,np) generatesa row-vectorof onesof lengthnp andthe logical statement(abs(x) <= 1.5) generatesa vectorwhich haselements0 where o p�ovu � ,sr and1 where o pwo�x � ,sr ). Will the populationpersistin this case?Now try the samescenariowith with meandispersaldistancezero( hS� ^ ).3.4 An Integro-DifferenceApproachto Nicholson-Bailey

3.4.1 Description of IDE for ENB

Theideafor implementinganIDE approachto known discretedynamicsis to imaginethatthebehavior oftheorganismscanberepresentedin two stages:ù Reproduction and lifecycledynamics. Thisis theportionof thepopulations’behavior thatis already

capturesin the ENB, equations(1,2). For this particularmodel, we think of parasitizedhostsasimmobilized,andfuturehostsaseggs(alsoimmobilized). Themajorchangeis thatnow ú�û and üsûasbeingpopulationdensitiesdependingonspace,ú û � p(�9yA� and ü û � p(�9yA� .ù Dispersal. Cuddly fuzzy babyhostsandparasitesdisperseafter birth, eachaccordingto species-specificdispersalprobabilities,

� W � pz�9y�� and� I � p(�9yA� respectively. Thebasicform of thedispersals

for eachspecieswill beaformof dispersalkernelderivedfromtheheatequation(for randomdiffusionin aplane): � � p(�9y{�}|5�C� �~���� | ��� �� � p 1 ; y 1~F� | � ,Here | is thedispersaltime of eachspeciesand

�is a speciesparameterdescribingthe‘dif fusivity,’

or rateof dispersal,of eachpopulation.

Themathematicalblueprintfor theIDE approachto ENB is then

1. Calculatethenumberof wrinkly babyhostsandparasitesbasedon thelastpopulationvalues:ú ûqþsÿ"� 1 � p(�9yA��� ��� úØû"��üsû����"ú�û � pz�9y��?��& � � � ��� ú û � pz�9y��� � ��� üsû � pz�9y�� � �ü ûqþsÿ"� 1 � p(�9yA��� � ú�ûJ��üxû"���%$Àú�û � pz�9y�� � ��� ��� (' �S� üsû � pz�9y���*+�-,2. Dispersethetoddlingbabyorganismsusingconvolutionsasdescribedabove:ú ûqþsÿ � pz�9y���� � W m ú ûqþsÿ"� 1 � p(�9yA�_�üxûqþsÿ � pz�9y���� � I m ü ûqþsÿ"� 1 � p(�9yA�_,

Noticethatthedispersalkernelsmaybedifferentfor hostandparasite!By iteratingtheserulesfor many ýwecansimulatemany generationsof reproduction,interaction,anddispersal.

Page 26: Spatio-Temporal Models in Ecology; an Introduction to ...adler/oldcourses/minicourse/matlab/labs_pow… · Spatio-Temporal Models in Ecology; an Introduction to Integro-Difference

3 LAB 3 – IMPLEMENTING AN INTEGRO-DIFFERENCEMODEL 26

3.4.2 Matlab Implementation

Below appearspsuedo-codewhich implementstheabovemodelin MATLAB. For interestingresultsparam-etervaluesarechosenwhereoscillatoryinstabilitiesandchaosoccur.

%% NBSPACE%% matlab code to iterate an enhanced Nicholson-Baile y model% for host and parasite, with each capable of diffusive movement.%% Intermediate variables (*) are created using a discrete% enhanced N-B step:%% h* = h(t) exp[ r (1 - h(t)/k) - a p(t) ]% p* = n h(t) ( 1 - exp[- a p(t) ] )%% This population is then allowed to disperse using a spatial% convolution, * below, (like a long step of a heat equation):%% h(t+1) = p_h(x,y) * h*% p(t+1) = p_p(x,y) * p*%% p_h and p_p can be any probability functions representing the% dispersal of the two species; I have used Gaussians below.%% Parameters appearing (and their interpretation ):%% r reproduction rate of host species% k carrying capacity of host species% a encounter rate or effectiveness of parasite on host% n parasites produced by a successful infestation%% Parameters used for the code:%% np number of points in x, y directions (a power of 2)% xl length of domain in x and y directions% dx grid spacing% dt a time-step length% mu followed by h and p -- diffusion parameter for each% species% ngens number of steps to run the code (number of% generations

%% set parameters and spatial grids%np=64; mup=.02; muh=.02; dt=.5; xl=10; dx=2*xl/np; ngens=20;x=linspace(-xl ,x l-d x, np);y=x; [X,Y]=meshgrid(x ,y );

Page 27: Spatio-Temporal Models in Ecology; an Introduction to ...adler/oldcourses/minicourse/matlab/labs_pow… · Spatio-Temporal Models in Ecology; an Introduction to Integro-Difference

3 LAB 3 – IMPLEMENTING AN INTEGRO-DIFFERENCEMODEL 27

%% set up spatial parameters%

n=ones(np);a=4*ones(np);r=1.75*ones(np );k=ones(np);

%% Set up stuff for movie%% M=moviein(ngen s); % If you want movies

%% Set up initial conditions%

p0=.5*(1+cos(. 5* pi* X/ xl +pi/ 4*r and( np)) .*s in (p i* Y/ xl- pi /2 *r and(n p) )) ;h0=.5*rand(np) .* (1+ cos( 4* pi *sq rt (X .ˆ 2+Y.ˆ 2) /x l) );

%% Define movement kernels for host and parasite%

hker=exp(-(X.ˆ 2+Y.ˆ 2) /( 4* muh*d t) )/ (4 *p i*d t* muh) *d xˆ2 ;Fhker=fft2(hke r) ; % FFT is taken because we will use it often,

% two factors of dx; one for each dimension

pker=exp(-(X.ˆ 2+Y.ˆ 2) /( 4* mup*d t) )/ (4 *p i*d t* mup) *d xˆ2 ;Fpker=fft2(pke r) ;

%% Now we are in a position to iterate for% a number of generations equal to ngens%

for j=1:ngens

%% Advance the life cycles using adjusted N-B model%

hn=h0.*exp(r.*(1 -h 0. /k )- a.* p0);pn=n.*h0.*(1-exp (- a. *p 0) );

%% Do the dispersal step%

fhn=fft2(hn); % First take fft of each species

Page 28: Spatio-Temporal Models in Ecology; an Introduction to ...adler/oldcourses/minicourse/matlab/labs_pow… · Spatio-Temporal Models in Ecology; an Introduction to Integro-Difference

3 LAB 3 – IMPLEMENTING AN INTEGRO-DIFFERENCEMODEL 28

fpn=fft2(pn); % First take fft of each species

%% Now do the convolutions.% The fftshift serves to center the probability functions.%

h0=real(fftshift (i ff t2 (F hke r. *f hn)) );p0=real(fftshift (i ff t2 (F pke r. *f pn)) );

%% Now plot the solution%

pcolor(X,Y,h0-p0 ), shading interp, colormap(jet), axis square, colorbar% M(:,j) = getframe; % If you want movies

end%% Here ends the iteration%

%% To play the movie, use this command:% movie(M,2,8)

Now, if you want to run this M-file asit standsyou shouldseebasicallya complicatedspatialfield attheend. This field is codedsothat thedifferencebetweenrelative abundancesof hostandparasitecanbeseen;placeswith moreabundanthostswill appearasred,moreabundantparastiesasblue. To seea movieyoumustun-commentthe

% If you want movies

lines in the script. Thesemovies can be memory-intensive, so don’t get freaked out if your computersuddenlystartswhirring, clicking andsmoking! Also, moviesarecreatedin MATLAB basicallyby savingscreen-grabsof the(normallycomputationallyintensive) graphics.This allows theframesof themovie tobe‘stacked’ togetherandviewedrapidly, but it alsomeansthatyou cannot changethesizeof movie whenit is beingviewed,andif youpopupany windowswhichoverlapwith theMATLAB graphicswindow whileyou areproducinga movie, MATLAB will grabwhatever you poppedup andkeepit in themovie! (I hadaparticularlybadmomentdiscovering this makinga movie for a conference.While producingthemovie Ihappenedto go lingerieshoppingfor my wife at theVictoria’s Secretwebsite.....)Thecommand

movie(M,2,8)

will play themovie, M, 2 timesat a speedof 8 framespersecond.Theadvantageof having a movie is thatyoucanplayit againandagainwithoutre-doingthecalculation.Youcanalsosaveamovie to atransportableAVI file.

EXERCISE 15: Copy theabove MATLAB M-file andmodify it to implementanIDE for thenormal,vanillaNicholsonBailey model.Runthemodelwith initial conditionswhichare:

1. Spatiallyhomogenous(constant).

Page 29: Spatio-Temporal Models in Ecology; an Introduction to ...adler/oldcourses/minicourse/matlab/labs_pow… · Spatio-Temporal Models in Ecology; an Introduction to Integro-Difference

3 LAB 3 – IMPLEMENTING AN INTEGRO-DIFFERENCEMODEL 29

2. Spatiallyrandom(rememberrand !).

3. Onaspectrumof structures(try takingaconstant+ sinusoidallyvaryingperturbationsandthenchangetherelative magnitudes– asin k=1+.9*cos(4*p i*X /x l) .* cos(4 *p i* Y/ xl ) ).

Canyouverify Nicholson’s hypothesisthatspaceallows persistenceof bothspecies?

EXERCISE 16: Createa MATLAB M-file which will simulatethe spatialspreadof a singlepopulationsatisfying(whenspaceis not included)a logisticmodel:ü 4 þsÿ �*ü 4 ; � ü 4 � ��� ü 4 �with randomdispersal.For a particular(small)diffusionparameter, investigatetheeffect of increasingtheintrinsicgrowth rate(

�) of thepopulation.Whatdoyouobserve?Is this reasonable?Whathappenswhen

�entersthechaoticregime?

3.5 Spatially Structured Envir onments

Oneof the nice thingsaboutIDE modelsimplementedin MATLAB is that they can accomodatespatialstructureeasily. Returningto the ENB modelfor a moment,considerthe waysin which the spatialenvi-ronmentmight influenceparametersin the model. It is possiblethat motility of organismscanvary withthe environment– an exampleof this is provided above in the sectionon victim-taxis. Neglecting this,theenvironmentcanhave a plethoraof life-history effects,perhapsthe largestof which is alterationin the‘carrying capacity,’

�, of theenvironmentfor thehost.Returningto theMATLAB codefor theENB given

above, noticethatwhenparametersaredefinedthey aredefinedasmatricesof thesamesizeasall spatialvariables.Whentheparametersareusedin the life-history stepof the IDE, the MATLAB implementationaccountsfor element-by-elementmatrix multiplication.Consequently, if we wantedto simpulatetheeffectof a cropon thehost,wecouldinsert

k=.1*ones(np)+ (a bs( X) <=.2 5) +(a bs (X )> =1.75 & abs(X)<=2.25). ..+(abs(X)>=3.75 & abs(X)<=4.25). ..+(abs(X)>=5.75 & abs(X)<=6.25). ..+(abs(X)>=7.75 & abs(X)<=8.25). ..+(abs(X)>=9.75 & abs(X)<=10.25) ;

in placeof theexisting line

k=ones(np)

(Notice the MATLAB form of ‘continuation’ for a long line: the ellipsis ‘...’) This will have the effect ofputting‘stripes’of highcarrying-capacitycropsin theenvironment.

Page 30: Spatio-Temporal Models in Ecology; an Introduction to ...adler/oldcourses/minicourse/matlab/labs_pow… · Spatio-Temporal Models in Ecology; an Introduction to Integro-Difference

3 LAB 3 – IMPLEMENTING AN INTEGRO-DIFFERENCEMODEL 30

EXERCISE 17: Implementthe crop-structuredspatialheterogeneityindicatedabove. Think of a way tointroduceparametersso that thewidth of thecropstripesandtheir relative ‘value’ to thehostareeasytoadjust.Try somesimulations– arethere‘crops’ andspatialstructureswhich aremoreor lessvulnerabletoinfestationby thehostevenin thepresenceof theparasite?

EXERCISE 18: Supposethatthecroppingstructurealsoinfluencesthe‘efficiency,’�, of theparasite.How

shouldthisbeincluded,andwhatareits effectson thedynamics?

Although they may be tedious,artificial spatialstructuresaremucheasierto introducethan‘natural’ones,just becausea semi-structured‘random’ environmentis very hardto put togetheroff thetop of yourhead.Of course,in principleonecouldtake field measurementsof a spatialarenaandthenscantheseintodensityplots,but probablythatis beyondthescopeof our currentlab experience.Onealternative wassug-gestedto meby ProfessorJonAllen (Departmentof EntomologyandNematology, Universityof Florida,Gainesville).Thefollowing MATLAB script,named‘rockies.m’generatesarandomizedbut spatiallycorre-latedstructureby choosingrandomphasesandanglesin Fourierspectrum,but usingauser-specifiedpowerlaw for decreasingenergy in the power spectrum.(If this doesn’t make senseto you, don’t sweatit; theprogramwill work anyway). The MATLAB script requiresa ‘fractal dimension’,H, which increasesthespatialcorrelation(think regularity) asthe‘dimension’increases.Thecodeappearsbelow, but is availablefor downloadin theclassdirectory. Thescriptwill produceasurfaceplot of thefield B, whichis normalizedso that its peakvalue is one,andis also thenavailable to be usedfor simulatingresourceheterogeneity.The‘power-law’ decreasein thespectralenergy of waves,p, is definedasp=(H+1)/2 becausewhentheexponentis 1/2 thedistribution is theoreticallyindistinguishablefrom ‘white’ noise.Themostinterestingstructuresappearfor Hbetween.5 and1.5.

Page 31: Spatio-Temporal Models in Ecology; an Introduction to ...adler/oldcourses/minicourse/matlab/labs_pow… · Spatio-Temporal Models in Ecology; an Introduction to Integro-Difference

3 LAB 3 – IMPLEMENTING AN INTEGRO-DIFFERENCEMODEL 31

%% ROCKIES%% This cryptic matlab script generates a structured but random spatial% environment of size NxN. The user inputs the following:% N - number of grid points in both x,y directions% H - fractal dimension (the bigger this is the smoother the landscape)%

N=64; H=1;p=(H+1)/2;

[I,J]=meshgrid ([ -N/ 2+1: N/ 2] , [-N/2+1:N/2]); % wave modesrandn(’seed’,0 );phases=2*pi*ra nd(N) ; % random phasesamp=randn(N).* (I .ˆ2 +J.ˆ 2) .ˆ (-p ); % normal amplitudes about power lawamp(N/2,N/2)=0 ; % mean amp of zerofA=amp.*exp(i* phase s) ; % field in tranform space

A=ifft2(fA); % invert transformB=abs(A); % make field realB=B/max(max(B) ); % normalize

surf(B), colormap(jet), shading interptitle([’Log(PS ) = - ’,num2str(p),’ k’])view(-37.5,60)

EXERCISE 19: Downloadtheprogramrockies.m andrunit for a few choicesof the‘fractal dimension.’Describetherelationshipbetweenincreasingthisparameterandtheoutputfield.

EXERCISE 20: UsetheB field outputby therockies programto generaterandomlandscapesof carryingcapacityfor theENB model.Onewayto dothiswouldbesimplyto executetherockiesscriptandthenstate

k=2*B;

in theENB program.Modify thegraphicoutputto includecontoursof theresourcewith thedensityplotsoftherelativeabundanceof victims/parasites.Whatdynamicsbehaviorsseemto correlatewith whatlandscapefeatures?Whatconsequencesdoyouthink thismighthave for Nicholson’s hypothesisfor thepersistenceofparasitizedpopulationsin space?

Wow, GoodJob! You now know secretandofficial thingsaboutthecomputationalimplementationof IDEusingMATLAB !

Page 32: Spatio-Temporal Models in Ecology; an Introduction to ...adler/oldcourses/minicourse/matlab/labs_pow… · Spatio-Temporal Models in Ecology; an Introduction to Integro-Difference

4 LAB 4 – BOUNDARIES,CHEMOTAXIS AND STUDENTCASESTUDIES 32

4 Lab 4 – Boundaries,Chemotaxisand StudentCaseStudies

4.1 Goals

In this lab we will finish off someof the complicateddetailswhich may benecessaryfor practicalappli-cationof IDE. Thefirst of theseis the implementationof boundaries,in particular‘lethal’ (or ‘absorbing’)boundariesand‘solid’ (or ‘reflecting’) boundaries.Thesecondis accountingfor semi-randommovementinresponseto externalstimuli, in particularchemo-taxis.Thus,wewillù Learnhow to useevenandoddreflectionsto implementlethal( ü�� ^ ) andsolid ( � I�@� � ^ ) boundary

conditionsfor IDE.ù ImplementPowell et. al.’s 1998approachfor modellingchemotacticmovementof apopulation.ù Spendtimeworkingoutsomeof thecomputationaldetailsof thestudentcasestudies.

An overallgoalfor thisclassis to getstudentsto ‘work withoutanet,’ thatis, to createIDE simulationsof ecologicalcircumstanceswhich mayshedlight on researchquestions.To encouragethis, we will havelab time for teamsto begin implementinganIDE approach,with our fearlessinstructoraroundto helpwithdifficulties.Participantsshouldwork in teamsof 2ormoreto discussthemodelswhichwill beimplemented,parameterregimesto bestudied,andexperimentalprotocolsto beused.Theneachstudentshouldbuild theirown simulatorandimplementtheirportionof theexperimentalprotocol,andgetbacktogetherwith therestof thegroupto discussresults. I have suggestedsomegroupprojects,but feel free to work on somethingcloserto yourown researchor interests.Eachgroupshouldhavesomethingto presentto therestof theclasson thefinal day. You mayhave to work mainly with onespatialdimensionin orderto have enoughtime toexperimentfreely. As wehave seenin therestof theclass,if youcando it in onedimensionwith MATLAB

thenyoucando it in two with only slightmodification.

4.2 Reflectingand Absorbing Boundary Conditions

4.2.1 The Wall of Doom

Thegeneralformatof anIDE for apopulationü isü ûqþsÿ"� 1 � ��� ü û �_�üsûqþsÿ#� � m ü ûqþsÿ"� 1 ,Here

�is the functional responseconnectingthe dispersalstageorganism(with density ü ûqþsÿ"� 1 ) to the

previous generationand�

is the spatialdispersalprobability for an initially localizedindividual. Spatialboundariesonly have animpactin thesecondstepduringwhichdispersaloccurs.

A lethalboundaryconditionis written mathematicallyas ü�� ^ at somep���� . This would seemtobe quite a problemfor our FFT-basedapproach,which assumesat a basiclevel that functionsgoing intothe FFT areperiodic. However, we canget aroundthis by reflectingthe data. If the dispersalkernel,

�,

is symmetricaroundtheorigin (so that theprobabilityof moving to the left is exactly thesameasthatofmoving to theright, or

� � � p��C� � � pv� ), theeffectof ü � p�������� ^ canbesimulatedby creatingananti-populationof disperserson theoppositesideof p���� , which whenit dispersesbacktoward thepositive(real)populationwill exactlycanceloutat pd��� . Sincethefunctionswearelookingatmustbeperiodicontheentire(reflected)interval, wewill alsohavea lethalboundaryat p�� ^ becauseof this reflection.Belowis ascriptwhichexecutesthis implementationof boundaryconditions.

Page 33: Spatio-Temporal Models in Ecology; an Introduction to ...adler/oldcourses/minicourse/matlab/labs_pow… · Spatio-Temporal Models in Ecology; an Introduction to Integro-Difference

4 LAB 4 – BOUNDARIES,CHEMOTAXIS AND STUDENTCASESTUDIES 33

%% BCs%% matlab code to illustrate the effect of boundary conditions% and their implementation%% boundary conditions will be implemented at x=0, x=xl% by reflecting the domain%% p(x) - population density in x% K(x) - probability of individual dispersal to location% x starting at location 0.% xl - maximum x coordinate (also - minimum)% dx - spatial step delta x = 2*xl/np% np - number of points in discretization for x% (should be a power of 2 for efficiency of FFT)% D - diffusion constant (per step)%

np=128; xl=5; dx=2*xl/np; c=0; D=.25;

%% discretize space, define an initial population distribution%

x=-xl+[0:np-1] *d x;p=(abs(x-1.5)< =1.); p0=p; % keep track of initial populationplot(x,p0,’r’)

%% define and normalize a dispersal kernel%

K=exp(-(x).ˆ2/ (4 *D) )/ sq rt (4 *pi *D);K=K/(dx*sum(K) );

%% calculate the fft of K, multiplying by dx to account% for the additional factor of np and converting from a% interval length of 1 to 2*xl.%

fK=fft(K)*dx;

%% skew-reflect the data to implement wall of doom% pa contains the actual population before dispersal% pr contains the reflected populuation before dispersal%

pa=p;

Page 34: Spatio-Temporal Models in Ecology; an Introduction to ...adler/oldcourses/minicourse/matlab/labs_pow… · Spatio-Temporal Models in Ecology; an Introduction to Integro-Difference

4 LAB 4 – BOUNDARIES,CHEMOTAXIS AND STUDENTCASESTUDIES 34

pr=-p(np:-1:1) ; % start at last index, go backwards for reflection

%% calculate the fft of the pa, pr; perform the convolutions%

fpa=fft(pa); fpr=fft(pr);fga=fK.*fpa; fgr=fK.*fpr;

%% fgr and fga now contain FFT of the convolution of reflected% and actual fields, respectively; now invert%

gr=real(fftshi ft (if ft (f gr )) );ga=real(fftshi ft (if ft (f ga)) );g=ga+gr;

%% update p, undoing the reflection (that is, take only the data% from x=0 to xl, with zeros elsewhere%p=g.*(x>=0);

hold on, plot(x,p,’m’,x ,g r, ’y’ ,x ,g a, ’b ’,x ,g ,’ g- -’ ), hold offaxis([-xl xl -1 1])

Make particularnoticeof thestatement

pr=-p(np:-1:1) ;

which implementsthe reflectionof thedata. In MATLAB thestatementnp:-1:1 will generatenumbersstartingat np andsteppingbackwards(by stepsof -1) to 1. Placingtheseindicesinto p, asabove, reflectsthefield (negatively) aroundp�� ^ . Theprogramthendispersesboththeoriginal andreflectedfields,re-sumsto getthefield whichimplementstheboundaryconditions(g above),andthenrecoverstheactualfield(by settingthefield backto zerofor negative p ). Theresultsareplottedwith thereflectedfield in yellow,the unreflectedfield in blue, the summedfield in greendashes,and the final result (the populationafterdispersal,takinginto accountthelethalboundaries)in magenta.

EXERCISE 21: Use for ... end statementsandpause to continuethe dispersalthroughseveraltimesteps.Whenyou areconfidentthatyou have donethis properly, extendtheprogramto accountfor re-productionafterdispersal(thatis, replacep=g.*(x>=0) with p=r*g.*(x>=0) ,wherer is aparameteryou will setto be larger than1). What do you observe after iteratingthecombinationof dispersal,lethalboundaries,andreproductionfor severalgenerations?

Page 35: Spatio-Temporal Models in Ecology; an Introduction to ...adler/oldcourses/minicourse/matlab/labs_pow… · Spatio-Temporal Models in Ecology; an Introduction to Integro-Difference

4 LAB 4 – BOUNDARIES,CHEMOTAXIS AND STUDENTCASESTUDIES 35

4.2.2 ReflectingBoundaries

A reflectingboundary(that is, a boundarycondition � I�a� � ^) is implementedthe sameway asa lethal

boundary, exceptthatthereflectionis donepositivelyinsteadof negatively.

EXERCISE 22: To implementsolidboundaries,in thescriptyouhave writtenabove replacetheline

pr=-p(np:-1:1) ;

with theline

pr=p(np:-1:1);

Runthescriptandseewhathappens.If you iteratedispersalseveral timesthefinal resultshouldapproacha constant,non-zeroaveragevalue. Why is this? Rememberthatyou have a solid wall on eachendof thedomain.Theeffect of a long periodof randommotion,sinceno individualsarelost, is to eventuallycreateauniformdistribution.

Page 36: Spatio-Temporal Models in Ecology; an Introduction to ...adler/oldcourses/minicourse/matlab/labs_pow… · Spatio-Temporal Models in Ecology; an Introduction to Integro-Difference

4 LAB 4 – BOUNDARIES,CHEMOTAXIS AND STUDENTCASESTUDIES 36

4.2.3 Mixed Boundaries

It might happenthatoneboundaryis lethalwhile theotheris solid, in which caseoneneedsto doa doublereflection.Let’s supposewe wantto investigatea situationwith a solid (reflecting)boundaryat p�� ^ anda lethal(absorbing)boundaryat p���� . A MATLAB script implementingmixedboundaryconditions(withdrift anddropdispersal)appearsbelow.

np=64;xl=5;dx=xl/np;x=dx*[0:np-1]; % the physical space of interestx2=dx*[-2*np:2 *n p-1 ]; % the virtual space on which reflections occur

D=.4; % per-step dispersal distance

K=.5/D*exp(-ab s( x2) /D ); % double-exponent ia l dispersal kernelfK=dx*fft(K);

p0=(abs(x-2.5) <=1); % initial population

for istp=1:10, % begin several dispersal steps

pr=[p0, -p0(np:-1:1)]; % negative reflection to right for% lethal boundary at x=xl

pl=[pr(2*np:-1: 1) , pr]; % positive reflection to left for% reflecting boundary at x=0

fpl=fft(pl);p2=real(fftshif t( if ft (f K.* fp l) )) ;

pn=p2(2*np+1:3* np); % use only that data corresponding to the% region of interest

hold on, plot(x,p0,’r’,x, pn,’ g’ ), axis([0 xl 0 1]), hold offpause(.1)p0=pn; % update the population field

end % of dispersal

Notice that implementingthis kind of mixed boundariesrequiresvectorstwice as long as implementingboundariesof the sametype. This is not sucha big problemin onedimensionalsimulations,but it canbecomeprohibitive in multipledimensions.

Page 37: Spatio-Temporal Models in Ecology; an Introduction to ...adler/oldcourses/minicourse/matlab/labs_pow… · Spatio-Temporal Models in Ecology; an Introduction to Integro-Difference

4 LAB 4 – BOUNDARIES,CHEMOTAXIS AND STUDENTCASESTUDIES 37

4.2.4 Boundary Conditions in Two Dimensions

In principle, lethalandreflectingboundariesareimplementedthesameway in two dimensionsasin one,and to implementboundariesthe dispesalkernelmuststill be symmetric. Now, however, thereare twosetsof reflectionsto implement(boundariesin both p and y ). Let’s implementreflectingboundariesfor a‘ring-random’or ‘ripple’ dispersalkernel,� � � ��� p 1 ; y 1 ����� D E����} F¡

K£¢ l¤¦¥ K �which modelspropagulesleaving the placeof their origin at speed§ andtravelling anddispersing(withdiffusivity ¨ ) for a time ý beforesettling.Thiskernel(alsocalledthe‘ripple’) wasusedby Brewsteret. al.(1997)to investigatethedispersalof whitefliesin the ImperialValley of California. Theconstant� mustbeevaluatednumericallyfor normalization.TheMATLAB scriptbelow implements‘ripple’ dispersalwithreflectingboundariesat y�� ^ and yd��� andlethalboundariesat p�� ^ and p���� . First,we setup boththegrid of interest,[X,Y] , andthegrid requiredfor thereflections,[X2,Y2] .

t=2; D=.1; v=2; % set parameters

xl=10; yl=10; np=64; dx=2*xl/np; dy=2*yl/np; % parameters for the% x,y coordinates

x=linspace(0,x l- dx, np); x2=linspace(-x l,x l- dx ,2 *n p);y=linspace(0,y l- dy, np); y2=linspace(-y l,y l- dy ,2 *n p);

[X,Y]=meshgrid (x ,y) ; % grid of interest[X2,Y2]=meshgr id (x2 ,y 2) ; % reflection grid

K2D=exp(-(sqrt (X .ˆ2 +Y.ˆ 2) -v *t) ˆ2 ./ (4 *D*t) ); % ripple dispersalK2D=K2D/(dx*dy *t rap z( tr apz( K2D)) ); % normalize

fK=fft2(K2D)*d x* dy; % FFT for convolution

This scriptsetsup thegridsandtheripple dispersalkernel. Now we candefinean initial population(in acirclecenteredin thedomain)

p0=(((X-xl/2). ˆ2 +(Y -y l/ 2) .ˆ 2)< =4);

andperformreflectionspreparatoryto doing the dipsersal.First we mustdo an even reflectionin the ydirectionfor thereflectingboundaries:

py=[p0; p0(np:-1:1,:) ];

Thesemi-colonabove placesonematrix above theother, andthe (np:-1:1,:) takesrows (first index)in reverseorder, for all columns(thecolon in thesecondargument).This matrix mustnow benegativelyreflectedin the p directionto implementthelethalboundary

px=[-py(:, np:-1:1) py];

Now wecanjustdo theregulardispersalon thereflectedgrid:

fp2=fft2(px);p2=real(fftshi ft (if ft 2( fp 2. *fK )) );pt=p2(np+1:2*n p, np+1: 2* np);pcolor(X,Y,pt) , shading interp, colormap hot, axis square

Page 38: Spatio-Temporal Models in Ecology; an Introduction to ...adler/oldcourses/minicourse/matlab/labs_pow… · Spatio-Temporal Models in Ecology; an Introduction to Integro-Difference

4 LAB 4 – BOUNDARIES,CHEMOTAXIS AND STUDENTCASESTUDIES 38

Theonly particularlydifficult thinghereis knowing whichpartof thereflectedanddisperseddatato take toget thepopulationof interest.Giventheway thatwe did thereflectionit is the ‘upper-right-corner’ of thedata,or p and y indicesfrom np+1 to 2*np .

EXERCISE 23: To make surethat you understandthe reflectionprocess,edit the script above so that itimplementsa lethal boundaryat yb� ^ �!� anda reflectingboundaryat p�� ^

and p��©� . How manyreflectionswouldyou needto implementa reflectingboundaryat only p�� ^ , with lethalboundarieson theotherthree?

4.3 A Model for Chemo-Taxis

Thelastthing thatmightbeof interestis implementingchemo-taxis.Many (if not most)insectspeciesfindmates,hosts,or prey usingchemicalclues. Bark beetlesfind hostsandinitialize a ‘mass-attack’usingapheromonefeedbacksystem(Powell et. al. 1998),naturalpopulationsof Drosophilafind rottingfruit to layeggson by following theodorof ethanol,anda varietyof insects,including ladybirdbeetles(Coccinella)respondto theodorof sugar-water. Powell andco-workers(1998)developedan IDE approachto emulatethechemotacticdispersalprocess,which is discussedherein onedimensionin the context of Drosophilaresponseto ethanol.

Considera resource(apples)distributedwith density ª , fermentingandreleasingethanol( « ) at a rate¬. Thesteady-stateethanoldistribution thensatisfies«�� �®­°¯ � ¬ ªV��� �j­ � �< � ��� � � o pwo� � �

where � is the meandispersaldistanceof the ethanol. A model for the ‘sensoryindex’, or degreeofsaturationof thesensoryapparatusof theflies, is± � «²��� ««)³ ; «Here « ³ is a saturationparameter– basicallythelevel at which thesensoryapparatusof theDrosohpilaishalfway to beingcompletelysaturatedwith ethanol.A modelfor thepopulationrepsonseis´´ ý ü�� � ´´ p¶µ···¸

towardincreasingF8 :!6 7¹ ü ´ ± � «²�´ p � randommotion8 :!6 7� ´ ü´ p�ºs»»»¼ ,Theparameters¹ and

�paramerizethe relative strengthsof the tactic responseandrandomdispersal,re-

spectively. Let �®½ � �¾ ~���� ý ��& ¿� � p{1~F� ý �be therandomdispersalkernelfor flies (when ¹ � ^

or «n� ^), implementedover sometime interval, ý .

An approximatesolution(detailsof how approximatearediscussedin Powell et. al.,1998)is givenbyÀ � p(��ý9�e� � ½ ¯ÂÁ ��& �M� ¹� ± � «Ã���>ü � p(��ý�� ^ �ÅÄ��ü � pz��ý!��� �[��� � ¹� ± � «Ã��� À � p(��ý9�_,Theconstant� mustbechosento normalizeü � pz��ý!� becausethis methodis not guaranteedto preserve thenumberof individualsin the dispersingpopulation. Following is a MATLAB codewhich implementsthechemotacticprocedureover severaliterations.

Page 39: Spatio-Temporal Models in Ecology; an Introduction to ...adler/oldcourses/minicourse/matlab/labs_pow… · Spatio-Temporal Models in Ecology; an Introduction to Integro-Difference

4 LAB 4 – BOUNDARIES,CHEMOTAXIS AND STUDENTCASESTUDIES 39

%% CHEMOTAX%% matlab code to emulate a chemotactic process%% p(x) - population density in x (drosophila)% e(x) - ethanol concentration% r(x) - resource distribution% KR(x) - probability of individual dispersal% KE(x) - dispersal kernel of ethanol% xl - maximum x coordinate (also - minimum)% dx - spatial step delta x = 2*xl/np% np - number of points in discretization for x% mu - diffusion constant (per step)% nu - chemotactic constant% a - dispersal distance of ethanol% d - release rate of ethanol from resource% E0 - saturation constant for sensory index%

np=128; xl=8; dx=2*xl/np;t=1; mu=1; nu=10;a=.5; d=2; E0=.5;nsteps=15;

%% discretize space, define an initial population distribution%

x=-xl+[0:np-1] *d x;p=(abs(x+3)<=. 5) ; p0=p; % keep track of initial p for comparisonr=(abs(x-2)<=. 5) ; % resource density

%% define dispersal kernels and normalize%

KR=exp(-(x).ˆ2 /( 4*D*t )) /s qr t(4 *p i* D*t) ;KE=exp(-abs(x) /a );KR=KR/(dx*sum( KR));KE=KE/(dx*sum( KE));

%% calculate the fft of KR, KE, dx accounts for convolution%

fKR=fft(KR)*dx ;fKE=fft(KE)*dx ;

% calculate ethanol field

Page 40: Spatio-Temporal Models in Ecology; an Introduction to ...adler/oldcourses/minicourse/matlab/labs_pow… · Spatio-Temporal Models in Ecology; an Introduction to Integro-Difference

4 LAB 4 – BOUNDARIES,CHEMOTAXIS AND STUDENTCASESTUDIES 40

E=real(fftshif t( iff t( ff t( d* r). *f KE)) );plot(x,p,’b’,x ,p ,’m -- ’, x, E/ max(E ), ’y ’, x,r ,’ r’ ), axis([-xl xl 0 1.1*max(p)])

% calculate sensory index

FE=E./(E0+E);

% begin iterating the model

for j=1:nsteps,

%% calculate the fft of pi = p.*exp(-nu/mu f(E));% perform the convolution on the pi%

peye=p.*exp(-nu/ mu*F E) ;fpi=fft(peye);fg=fKR.*fpi;

%% fg now contains the fourier transform of the convolution;% invert it, multiply by the inverse exp(nu/mu*FE)%

g=exp(nu/mu*FE). *r eal( ff tsh if t( if ft (fg )) );

%% Now we must be careful to normalize!%

C=trapz(p)/trapz (g ); g=C*g;

hold on, plot(x,g,’b’), hold offpause(.1)

% update p and move to the next time step

p=g;end % of the iterations

Onecanthink of this implementationasa pre-multiplicationof thedispersingpopulation,ü , with adisper-sal ‘bias’: individualsfurtheraway from thesourceof theethanol(thereforesensinglow

��� «²� ) aremorestronglybiasedto randomdispersal.Thebiasedpopulation(

À) is dispersedat random,andthende-biased

(by multiplicationof ��� (' ¹HÆ � � * ). Providedthetime stepsaresmallenough,this approximatesthechemo-tacticdispersalprocess.As it turnsout,themodelworksjustfinefor largetimesteps.As with theprey-taxisdiscussedin the previous lab (Turchin-taxis)the main difficulty is that the processis not linear in ý – fivestepswith ý�� < is notnecessarilyequivalentto two stepswith ý���r .EXERCISE 24: Form hypothesesaboutthe impactof the parameterson chemotacticdispersal,andtestyourhypothesesagainstmodeliterations.For example,for agiventimestep,if theethanoldispersesfurther(largera) thefliesshouldfind theresourcesmorerapidly. Or, if chemotaxisis strongerthanrandommotion( ¹ u �

) thenthe resultingpatternof aggregationshouldbe muchmoretightly centeredon the resource.

Page 41: Spatio-Temporal Models in Ecology; an Introduction to ...adler/oldcourses/minicourse/matlab/labs_pow… · Spatio-Temporal Models in Ecology; an Introduction to Integro-Difference

4 LAB 4 – BOUNDARIES,CHEMOTAXIS AND STUDENTCASESTUDIES 41

Changeparametersto reflectyourhypothesesandtestif they arecorrect.

Well, look at you! You have gottento theendof the formal lab materialon integro-differenceequations!GoodWork!

Page 42: Spatio-Temporal Models in Ecology; an Introduction to ...adler/oldcourses/minicourse/matlab/labs_pow… · Spatio-Temporal Models in Ecology; an Introduction to Integro-Difference

REFERENCES 42

References

[1] Allen, J.C.,C.C.BrewsterandD.H. Slone,2001.Spatiallyexplicit ecologicalmodels:a spatialcon-volutionapproach.Chaos,SolitonsandFractals12: 333–347.

[2] Allen, J.C.,C.C.Brewster, J.F. Paris,D.G. Riley andC.G.Summers,1996.Spatiotemporalmodelingof whitefly dynamicsin a regional croppingsystemusingsatellitedata.Pages111–124in: Gerling,D. andR.T. Mayer, eds.Bemisia1995: Taxonomy, Biology, Damage, Control andManagement. UK:Intercept,Andover.

[3] Allen, L.J.S,E.J.Allen andD.N. Atkinson,1999.Integro differenceequationsappliedto plantdisper-sal,competitionandcontrol,FieldsInstituteCommunications21: 15–30.

[4] Andersen,M., 1991.Propertiesof somedensity-dependent inegrodifferenceequationpopulationmod-els.MathematicalBiosciences104:135–157.

[5] Andow, D.A., P.M. Karieva,S.A.Levin andA. Okubo,1990.Spreadof invadingorganisms.LandscapeEcology 4: 177-188.

[6] Brewster, C.C.andJ.C.Allen, 1997.Spatiotemporalmodelfor studyinginsectdynamicsin large-scalecroppingsystems.EnvironmentalEntomology 26: 473–482.

[7] Cain,M.L., H. DammanandA. Muir, 1998.SeeddispersalandtheHolocenemigrationof woodlandherbs.Ecological Monographs 68: 325–347.

[8] Clark, J.S.,M. Silman,R. Kern,E. Macklin andJ. HilleRisLambers,1999.Seeddispersalnearandfar: patternsacrosstemperateandtropicalandtropicalforests.Ecology80: 1475–1494.

[9] Clark, J.S.,C. Fastie,G. Hurtt, S.T. Jackson,C. Johnson,G.A. King, M. Lewis, J. Lynch,S. Pacala,C. Prentice,E.W. Schupp,T. WebbIII andP. Wyckoff, 1998.Reid’s paradoxof rapidplantmigration.Bioscience48: 13–24.

[10] Edelstein-Keshet,L. 1988.MathematicalModelsin Biology. McGraw-Hill, New York, 586pages.

[11] Etienne,R., B. Wertheim,L. Hemerik,P. SchneiderandJ. Powell, 2000.“Dispersalmayenableper-sistenceof fruit flies suffering from the Allee effect andscramblecompetition,” Proceedingsof theDutch Entomological Society(11): 121–128.

[12] Hart, D.R. andR.H. Gardner, 1997.A spatialmodelfor thespreadof invadingorganismssubjecttocompetition.J. Math.Biology35: 935–948.

[13] Holmes,E.E.,M.A. Lewis, J.E.BanksandR.R.Veit, “Partialdifferentialequationsin ecology:spatialinteractionsandpopulationdynamics,” Ecology 75: 17-29.

[14] Kot, M., 1992.“Discrete-timetravelling waves:Ecologicalexamples,” Journalof MathematicalBiol-ogy30: 413–436.

[15] Kot, M.A. Lewis andP. v.d. Driessche,1996.Dispersaldataandthe spreadof invadingorganisms.Ecology 77: 2027–2042.

[16] Lewis, M.A. andJ.D.Murray, 1993.Modelling territoriality andwolf-deerinteractions.Nature 366:738–740.

[17] Luckinbill, L.S.,1973.Coexistencein laboratorypopulationsof Parameciumaurelia andits predatorDidiniumnasutum. Ecology54: 1320–1327.

[18] Murray, J.D.,1989.MathematicalBiology. Springer-Verlag,Berlin, 767pages.

[19] Neubert,M.G., M. Kot and M.A. Lewis, 1995.Dispersaland patternformation in a discrete-timepredator-prey model.TheoreticalPopulationBiology 48: 7–43.

[20] Nicholson,A.J., 1957.The self-adustmentof of populationsto change.Cold SpringHarbor Symp.QuantumBiol. 22: 153–172.

Page 43: Spatio-Temporal Models in Ecology; an Introduction to ...adler/oldcourses/minicourse/matlab/labs_pow… · Spatio-Temporal Models in Ecology; an Introduction to Integro-Difference

REFERENCES 43

[21] Pielaat98Pielaat,A. andF. vandenBosch,1998.A modelfor dispersalof plantpathogensby rain-splash.IMA J. MathematicsAppliedin MedicineandBiology 15): 117–134.

[22] Powell, J.A. andN.E. Zimmermann.Multi-ScaleAnalysisof SeedDispersalandthe ResolutionofReid’s Paradox.submittedto Ecology, August,2000.

[23] Powell, J., T. McMillen andP. White, 1998.Connectinga ChemotacticModel for MassAttack to aRapidIntegro-DifferenceEmulationStrategy, SIAMJ. Appl.Mathvol. 59,no.2, pp547-572.

[24] Tilman,D., 1994.Competitionandbiodiversity in spatiallystructuredhabitats.Ecology75: 2-16.

[25] Turchin,P., J.D. Reeve, J.T. Cronin andR.T. Wilkens,1997.Spatialpatternformationin ecologicalsystems:bridgingtehoreticalandempiricalapproaches.Pp.195-210in: BacompteJ.,SoleR.V. (eds),ModellingSpatiotemporal Dynamicsin Ecology. LandesBioscience,Austin,TX.

[26] Turchin,P., 1989.Populationconsequencesof aggregative movement.J. AnimalEcology58: 75–100.

[27] vandenBosch,F., J.A.J.Metz andJ.C.Zadoks,1997.“Pandemicsof focal plant disease,a model,”TechnicalNote97-06,WageningenAgricultural University, 22pages.

[28] vanderWerf, W., E.W. EvansandJ. Powell, 2001.Measuringandmodellingdispersalof Coccinellaseptempunctatain alfalfa fields.EuropeanJournalof Entomology 97: 487–493.