Hello, dear friend, you can consult us at any time if you have any questions, add WeChat: daixieit


LF211 Lab Stochastic Modelling


This document will guide you through the code required . Suggested code in the text below, is shown in inverted commas ‘some code’. Do not enter the inverted commas as code.


1. Stochastic logistic growth

1.1. Opening and running a script

a.   Download log_growth.m from Moodle.

b.   Move the file to the Matlab folder.

c.   Open Matlab. The log_growth.m file should appear in the ‘Current Folder’ windows.

d.   In the Command Window type ‘open log_growth’ (without the speech marks), press enter.

e.   In the Editor tab in the ribbon there is a Run button. This will run the script that models stochastic logistic growth.

1.2. Make small edits

a.   Increase the number of runs (don’t delete the semicolon), save by clicking save in the ribbon, or press command and S.

b.   Run the script again. What results do you have?

c.    Fix runs to 12.

d.   K is the carrying capacity. Try it at 100, how do the dynamics change? Try it at 10, how have the dynamics changed again?

e.   When finished, you can close all figure windows by typing ‘close all’ in the Command Window.


2.  Understanding and using Matlab

This section will cover comes basics that will help you use the stochastic models provided. Sections of practice code are provided in the script called LF211_lab_code.m, the content  below will lead you through them.

2.1. General comments on using the practice code

In the practice code, there are sections. You will see these are marked by horizontal lines     and that the top of each section has a double percentage sign and name e.g., %% Plotting.  Most of the time you will run only one section and not the whole script. To run a single         section, make sure your cursor is in the section you want to run, click EDITOR in the ribbon   and Run Section. The keyboard shortcut for this (on a Mac) is to press Command and Enter.

•    Type ‘clear’ in the Command Window at any time to clear variables in the Workspace.

•    Type ‘close all’ to close all figure windows.

2.2. Defining values

We need to tell Matlab what the values are that we are using. We give them a name and      then use those values to both calculations. We also define arrays to store output, these are

matrices (or vectors, but vectors are a matrix where one of the dimensions is only of size      one). The values we use are called variable in Matlab code language.This Matlab help page is useful.

Note that values are defined with the equals sign ‘=’, see lines 2 and 3 in the practice code      defining a and b. Run the section on defining values and see that the values of a and b are      stored in the Workspace. This would allow us to use these variables time and again without   re-defining them, and if our script will need to vary the variables, we can redefine them. The  definitions are ended with a semi-colon. This suppresses output. If you omit a semi-colon,      the output will appear in the Command Window. This makes for a messy Command Window and can slow the running of code. Be sure to suppress your output. Try deleting a semi-          colon for the defining of a and/or b and run the section again. You should see it in the Command Window and see in the script that Matlab gives a warning about the missing semi- colon.

Try defining a new variable but with a useful name, e.g., ‘birthrate =’ and give it a value.        Save, and run the section again to make sure your new variable is defined. At this stage, the number you assign is unimportant.

Further to variables being a single value, a matrix can hold an array of values. When                modelling, this is particularly useful and necessary for recording output from a simulation,     for example, recording the number of cases through time. Run the section named ‘Defining  and using and array’ in the practice code. Investigate the variables created by opening them in the Workspace. In the practice code create amatrix of zeroes. Run the section and check  your new variable in the Workspace. A matrix of zeroes can be a useful way to define an        array that will be completed with values as a simulation runs.

2.3. Indexing

To retrieve an element from an array, for calculations or plotting, or to update an element     or multiple elements but not all, you will need to usearray indexing. Indexing meaning the    placement of the element in array, normally by row and column. The Indexing section of the practice code generate a matrix c. Run this section of code. Click on the new matrix c in the Workspace to see it. In the section below named Indexing part 2, is some ‘commented out’   code. This is a common way to prevent code running without deleting it, it has been made a  comment. Turn this back to code by pressing Command and T, or by deleting the percentage symbol from the beginning of the line. This specifies an element of c to change. Run just this  section and see that the value of c in the first row and column has changed.

You can enter some code into the Command Window when you don’t want to change your script. To see that you can do this, enter the following into the Command Window:

c(row, col) = num;

Changing row and col for values between 1 and 5, and picking a value to replace num. You can double click on c in the Workspace again to see how the matrix changes. You can also  index whole rows or columns. This is done by entering a colon in the row or column entry. Enter the following code in the Command Window:

c( 1, : )

This will simply output the first row and every column. The following code in the Command

Window will output every row in the 2nd column.

c( :, 2)

This indexing can be used to change values for a column or row also. Enter the following into the Command Window:

c( :, 5) = 1;

This will change all values in the 2nd column to 1.

2.4. Random numbers

Random numbers are extremely important to capturing the dynamics of biology and are   critical to modelling stochasticity. The function rand’ generates a random number from a uniform distribution between 0 and 1.

2.5. Plotting

Plotting data and simulation output(s) is the best way to interpret that outcome. The               command ‘figure’ opens a new figure window into which to plot. If you create a plot without this command, a new figure will open anyway. But requesting a figure is good practice for      when plotting code becomes more complex. You will see the Matlabplotfunction used in      the stochastic modelling scripts used in this lab to create scatterplots.

Run the section Plotting. An alternative plot command is commented out. You can turn this  to code and see what difference it makes. There are many ways of editing a plot. Within the plot command itself you can choose multiple characteristics including line style and colour,   see the linespec section of the Matlab plot help page.

Creating a second plot without opening a new figure will put the new plot in the open figure but will replace it. To put multiple plots on the same figure, use the command ‘hold on’.         After that, all plots will be made on the same figure, until you use ‘hold off’, or create a new figure with ‘figure’. Uncomment lines 23 – 26 and run the section again.

You should find that you have x against y and h against v plotted on the same figure.

You will see examples of axes labelling in the stochastic SIR modelling code, but labelling can be found at the help link above too.

2.6. Histograms

When stochastic modelling, you will always need multiple simulations. Histograms can be a useful way to present a result from all simulations. The Matlab function is histogram’ . The  histogram section of the practice code will generate some random values from a normal

distribution and plot them on a histogram. The commented-out line 33 is more specific         about the plot. Uncomment this (and comment the first histogram line) and run the section again. This creates a histogram with 30 bins. Try and work out how to fix the edges of the     bins instead.

2.7. For loops

Large gains start to be made in code writing when something can be coded to happen in a     loop. In a for loop, you can enter one set of code, and that code will then be applied to         everything specified after the ‘for’ . In the stochastic logistic growth model, there is a for         loop that specifies, for every number between 1 and the set number ofruns, run the logistic growth model. The actual model is within this for loop, everything before that is ‘setting up’. Without this for loop, the model code would need to be written out for every run.                   Stochastic models are typically run thousands of times.

The practice code has a section called For Loops. Run the section, and open the array called output to see what it has done. Bear in mind that each time you run it the numbers will be   different as it calls a random number for each calculation.

2.8. Code debugging

When code doesn’t work, a good way to look for the bug is to run through code one line at a time (unlike letting it all run). The Matlabsupport is here. The debugging mode will run the    code up to a point you choose. From there, you can step through the code one line at a          time. When there is a bug, this will help you identify it as you will see calculations update.

You can also use it to help you work out what code is doing. To place a ‘breakpoint’, you        need to click a line number. It should go red. You can then run the section, and the code will pause there. If you click just to the right of the line number, it will automatically run the         code to that point, then pause. You should use this to explore the for loop practice code.

1.   Click on the line number 36.

2.   Make sure the Workspace is clear by typing ‘clear’ in the Command Window.

3.   Run the section.

4.   You will see the green arrow at line 36.

5.   In the top ribbon, at the right end of the Editor tab, you will see options in a RUN      group. Clicking continue would set the code off again. Click step to run the next line of code. The number of runs is defined, and you will see that in the Workspace.

6.   Click step again and the output array (filled with zeros) will be defined.

7.   Click step again and you will see the i appear in the Command Window. The i will count the number of loops.

8.   Click step again and the first calculation is made, and the output array in position i (one) is updated.

9.   Click step again, and ‘end’ is reached. Nothing will appear to change here, until you click next again where next loop will begin. You will see that the i has updated to 2.

10. Step through the code until you are on the last loop, i=5. When you step away ‘end’, you will find that it does not loop back around, but the green arrow points                   downwards (out of the loop). Click step again and the for loop is finished, and in this case, the script finishes running.

11. To remove the breakpoint, right click on it and ‘clear breakpoint’.


3.  Matlab Tutorial

In this lab manual, some Matlab basics are spelled out to make the epidemiological models useable. It is recommended that you also go through the official Matlab course called MATLAB Onramp. This is a 2-hour tutorial. You will need to sign-in (green button). Then       create an account, be sure to use your Warwick email address to get access.


4.  Publishing your code

There are multiple ways to publish your code. To publish creates a document with your code and output. You can practice with the log_growth.m file.

a.   Click the Publish tab in the ribbon.

b.   At the end is the Publish button, click the down arrow and Edit Publishing Options.

c.    Under Output Settings, change the Output file format to PDF.

d.   Shown in Output folder is the location the code will be published to. This can be changed if you wish.

e.   Click Publish. This will save a PDF of your code and output to the specified folder.

f. If code has errors, it will not run and therefore will not publish.


5. Assessment

5.1. Task

You will update the stochastic SIR model provided, so that it captures different dynamics.      You could change the structure from SIR to something with different infectious states, or       different movement between infectious states . You can change anything you like. All coding will be assessed, you can edit as you wish and add functionality as you see fit. It should be     fully commented to explain your code/revisions.

5.2. Assessment criteria

a.   Code will be assessed for accuracy, originality, and suitability.

b.   Comments will be assessed for understanding. It will be important to explain what your code does (or aims to do), this will doubly assess your understanding of the    science and your understanding of the technique.

5.3. Plagiarism in code writing

See this blog from Turnitin about how to avoid plagiarising code

https://www.turnitin.com/blog/plagiarism-and-programming-how-to-code-without- plagiarizing-2.

It is extremely important that you fully comment your code as explained below in section     5.4. It is likely that the Turnitin software will identify high levels of matching between             submissions, and if there is doubt about the originality of the work, it will be investigated as part of the University’s Academic Integrity process, a stage of which can include asking the   student in question to explain their work. There shouldn’t be any problems if you do your     own work!

5.4. Assessment notes

a.   You will edit the SIR of stochastic growth so that it models a new scenario. You could capture a different model structure (instead of SIR) or edit/add

b.   Use the file SIR_stoch_uncommented.m script, this is the same as SIR_stoch.m script,      but SIR_stoch_uncommented.m shas no comments in the code. Edit this file and               comment where you have edited or added code and explain what it does. The script you submit will therefore only have comments that document your work. You can still make  use of the comments in SIR_stoch.m script to guide your work.

c.   Submit your code and output as a PDF, do this via the publishing method shown in section 4.

d.   If your code has errors and will not publish, simply copy and paste it into a word file, then save as a PDF.

e.   Errors that prevent code from running can be very small. Code with an error that is        otherwise good may earn higher marks than overly simple or poor code with no errors. In terms of assessment, code with an error can achieve good marks.