## Modelling Population Dynamics

Chapter 4: Fitting state space models

To run the code presented, simply press ** Run** in the upper right-hand corner of the frame. You can explore the code further by pressing

**. This will take you to a website where you can edit the code and explore all of the figures produced by the code.**

*Edit**The code will take longer to run on the server than on your local machine, so have some patience.*

If the code fails to run or is subject to delays on *r-fiddle.org*, run it on your local machine, after installing R. To download the code to your machine, select all text inside the frame, copy to clipboard, and paste into an editor on your machine. Note each piece of code has file(s) containing *helper* functions listed in the top two lines of code. Download those files onto your machine as well for the code to function.

### Section 4.4.1 The Kalman filter

### Section 4.5.2.1 (WinBUGS code)

```
#(i) Model Statement
model {
#Prior distribution for parameters
beta1 ~ dnorm(0,0.01)
beta0 ~ dnorm(0,0.01)
sigma ~ dunif(0.01,10)
tau
```

### Section 4.5.3 salmon SSM in WinBUGS

Save this block of WinBUGS code locally as C:/PopDynBook/BUGSCode/Ricker-Poisson-logN.txt)

```
model {
#WinBUGS model code for Ricker model Poisson-LogN
# assuming known obs'n noise CV
# Priors
alpha ~ dunif(1,2.5)
beta ~ dunif(0.00001,0.001)
n.init ~ dunif(50,500)
sigma.sq
```

Load the following code into R

```
library(R2WinBUGS)
input.data
```

### Section 4.5.4 WinBUGS model statement for the BRS SSM

```
model {
#WinBUGS model code for BRS model (Bin-Bin-Bin)-LogN assuming known obs'n noise CV
# Priors
#Survival parameters
phi1 ~ dunif(0.05,0.95)
phi2 ~ dunif(0.05,0.95)
#Growth
Pi ~ dunif(0.05,0.95)
not.Pi
```

R code for generating initial values to fit BRS SSM with WinBUGS.

```
init.value.generator
```

### Section 4.5.5.2 Sequential importance sampling

R code for univariate coho salmon SSM

```
ricker.sis
```