Estimating the size of a population is a fundamental problem in ecology. In most natural populations, it is impractical or impossible to observe every individual, and the number of individuals observed during a survey is therefore an imperfect representation of the true population size. The difference between observed and true abundance depends on the probability of detecting an individual, which may vary with sampling effort, environmental conditions, individual behavior, and other factors. If detection probability is unknown, it is difficult to distinguish between a small population with a high probability of detection and a large population with a low probability of detection. Estimating population size therefore requires not only observations of individuals but also information that allows us to estimate detection probability.
Figure 10.1: text.
Figure 10.1 illustrates this problem with a population of 24 deer in a park. A biologist surveys the population and observes 8 deer. She knows that there are almost certainly more than 8 deer in the park, but does not know how many. One way to estimate that number would be to model the number of deer observed \(y\) as the true number of deer \(N\) and the detection probability \(p\):
\[y=Np\]
which would imply that the true number of deer is
\[N=\frac{y}{p}\]
But the problem remains: what is \(p\)?
In this chapter, we will explore two widely used approaches to population estimation: mark-recapture and distance sampling. Both methods account for imperfect detection, but they differ in the information they use to estimate detection probability. Mark-recapture uses repeated sampling of individually identifiable organisms. The frequency with which previously encountered individuals are detected again provides information about detection probability and, consequently, the number of individuals that have never been detected.
Distance sampling instead uses the distances of observed individuals from a sampling point or transect. By modeling how detection probability declines with distance, we can estimate the proportion of individuals within a surveyed area that were detected.
Both approaches lend themselves to hierarchical Bayesian modeling because they involve two distinct but related processes: an ecological process that describes the true, underlying state of the population and an observation process that describes how we obtain data about that population. By modeling these processes separately, we can make inferences about unobserved individuals and propagate uncertainty in detection probability into our estimates of population abundance, density, and demographic parameters. We will use JAGS to implement these models and introduce two important tools for Bayesian population analysis: latent state variables and data augmentation.
10.2 Mark-recapture analysis in JAGS
10.2.1 Basics of mark-recapture analysis
Mark-recapture (also called capture-recapture) is a method of estimating population parameters from repeated observations of individually identifiable organisms. In a traditional mark-recapture study, individuals are captured, given a unique identifying mark, and released back into the population. On subsequent sampling occasions, individuals are captured again and examined to determine whether they have been captured previously. Newly encountered individuals are marked and released, while previously marked individuals are recorded and released. Although the term mark-recapture implies physically capturing and marking individuals, the same approach can be used with organisms that are individually identifiable by natural markings, genetic samples, photographs, or other means.
Figure 10.2: text.
The basic principle of mark-recapture is that the frequency with which previously encountered individuals are encountered again provides information about detection probability. If most of the individuals captured during a sampling occasion have been captured previously, we might infer that detection probability is relatively high and that we have already encountered a large proportion of the population. Conversely, if few previously captured individuals are encountered again, we might infer that detection probability is relatively low and that a substantial proportion of the population remains undetected. By estimating detection probability from repeated sampling, we can estimate the number of individuals that have never been encountered and, consequently, the total population size.
Data from a mark-recapture study are typically organized into a matrix of capture histories, in which each row represents an individual and each column represents a sampling occasion. The capture history of an individual is a sequence of ones and zeros, indicating whether the individual was detected (1) or not detected (0) during each sampling occasion. For example, an individual with a capture history of 1011 was detected during the first, third, and fourth sampling occasions but was not detected during the second. Importantly, a zero does not necessarily indicate that an individual was absent from the population during a sampling occasion, only that it was not detected.
Table 10.1: Example capture history matrix for a mark-recapture study consisting of five sampling occasions. A 1 indicates that an individual was detected, and a 0 indicates that it was not detected. The italicized row represents an unknown number of individuals that were never detected and therefore do not appear in the observed dataset.
Individual
Occasion 1
Occasion 2
Occasion 3
Occasion 4
Occasion 5
1
1
0
1
1
0
2
0
1
0
1
1
3
1
1
0
0
1
4
0
0
1
0
0
5
1
0
0
0
0
6
0
1
1
0
1
7
0
0
0
1
0
Unknown
0
0
0
0
0
…
…
…
…
…
…
The capture history matrix contains a row for every individual that was detected at least once during the study. However, there may be an unknown number of additional individuals in the population whose capture histories consist entirely of zeros. Because these individuals were never detected, they do not appear in our dataset. A central objective of population estimation using mark-recapture is to infer how many of these unobserved individuals exist. As we will see, Bayesian methods provide a particularly useful approach to this problem by allowing us to explicitly incorporate these unobserved individuals into our model.
Mark-recapture models can be broadly divided into two categories:
Closed-population models: Assume that population membership does not change over the duration of the study. These models are primarily used to estimate population abundance and detection probability.
Open-population models: Allow individuals to enter and leave the population between sampling occasions through births, deaths, immigration, and emigration. These models can be used to estimate demographic parameters such as survival and recruitment, and some can also estimate changes in population abundance through time. Open population models include the famous Jolly-Seber (JS) and Cormack-Jolly-Seber (CJS) models.
The appropriate model depends on the objectives of the study, the biology of the organisms being studied, and the temporal and spatial scales over which sampling occurs.
10.2.2 Assumptions
Like all statistical methods, mark-recapture relies on a set of assumptions about both the biological system and the process by which data are collected. Violations of these assumptions can result in biased estimates of detection probability, population abundance, and other population parameters. Although the specific assumptions vary among mark-recapture models, the simplest models generally make the following assumptions:
Individuals are uniquely, permanently, and correctly identified. Marks are not lost, overlooked, or misread during the study. Each encounter with an individual can be correctly associated with its previous encounters.
Marking does not affect individuals. The process of capturing, handling, and marking an individual does not affect its survival, movement, behavior, or probability of subsequent detection.
Individuals have equal probabilities of detection. During a given sampling occasion, all individuals present in the population have the same probability of being detected, regardless of whether they have been captured previously.
Detections are independent. The detection of one individual does not influence the probability of detecting another individual. In the simplest models, detections of an individual on successive sampling occasions are also independent, conditional on its presence in the population.
Sampling occasions are effectively instantaneous. Each sampling occasion is sufficiently short relative to the interval between occasions that changes in population membership during a sampling occasion can be ignored.
Closed-population models make the additional assumption of population closure: no individuals enter or leave the population over the duration of the study. This includes both demographic closure (no births or deaths) and geographic closure (no immigration or emigration). The population therefore consists of the same individuals throughout the study, even though different subsets of those individuals may be detected during different sampling occasions. This assumption is often reasonable for studies conducted over relatively short periods but becomes increasingly difficult to justify as the duration of the study increases.
Open-population models relax the assumption of population closure by explicitly modeling the processes by which individuals enter or leave the population. However, these models introduce additional assumptions about those processes. For example, simple open-population models assume that all individuals present in the population have the same probability of surviving from one sampling occasion to the next. Furthermore, because an individual that dies and an individual that permanently emigrates from the study area both become unavailable for subsequent detection, many open-population models estimate apparent survival rather than true survival.
The robust design for mark-recapture models combines closed- and open-population models. It divides sampling effort into a hierarchy of sampling occasions and sampling bouts, with each bout consisting of several occasions. The population is assumed to be closed within a bout, and open between bouts.
Figure 10.3: text.
Many of these assumptions can be relaxed by increasing the complexity of the model. For example, detection probability can be modeled as a function of sampling effort, environmental conditions, individual characteristics, or previous capture history. Similarly, survival probability can be modeled as a function of age, sex, or other biological characteristics. One advantage of the Bayesian modeling framework is that these extensions can often be incorporated using the same regression and hierarchical modeling approaches that we have explored in previous chapters. For now, however, we will focus on relatively simple models in which detection and survival probabilities are constant.
10.2.3 The Lincoln-Petersen estimator
The Lincoln-Petersen population estimator, also called the Lincoln Index or Lincoln-Petersen index is one of the simplest mark-recapture methods. It is a closed population model that assumes no immigration, emigration, recruitment, or death. It also assumes that marks are not lost and are always correctly identified. This is the estimator derived in the introduction to this chapter.
The Lincoln-Petersen method estimates the detection probability \(p\) from at least two samples by assuming that the proportion of marked individuals that are caught equals the proportion of the population that is marked.
\[\frac{m_2}{n_2}=\frac{n_1}{N}\]
where \(n_1\) is the number of individuals captured and marked during the first sampling occasion; \(n_2\) is the number of individuals captured during the second sampling occasion; and \(m_2\) is the number of previously marked individuals captured during the second sampling occasion. This can be rearranged to solve for the estimated population size \(\hat{N}\) as
\[\hat{N}=\frac{n_1n_2}{m_2}\]
For example, if a survey of fish in a pond captures 5 fish on the first day, then 7 fish on the second day, 3 of which are marked, the Lincoln-Petersen estimator of population size is
The Lincoln-Petersen estimator is unbiased as the sample size approaches infinity, but is biased at small sample sizes. An alternative is the the Chapman estimator, which is given by
which is similar to the Lincoln-Petersen estimate.
10.2.4 Closed-population model in JAGS
10.2.4.1 Definition
The simplest closed-population mark-recapture model assumes that a population consists of \(N\) individuals, each of which has a constant probability \(p\) of being detected during each of \(T\) sampling occasions. Because the population is closed, all \(N\) individuals are present and available for detection throughout the study. The capture history of each individual consists of a series of independent Bernoulli trials, with the outcome of each trial indicating whether individual \(i\) was detected during sampling occasion \(t\). We can therefore model the observation process for individual \(i\) at time \(t\) as
\[
y_{it}\sim p
\]
where \(y_{it}=1\) if individual \(i\) was detected during sampling occasion \(t\) and \(y_{it}=0\) otherwise. The total number of times an individual is detected over the course of the study follows a binomial distribution,
Our objective is to estimate both \(N\) and \(p\) from the observed capture histories. However, because our dataset contains only individuals that were detected at least once, the number of rows in the capture history matrix is itself a consequence of the observation process. We will address this problem using data augmentation, a technique that allows us to explicitly incorporate potentially unobserved individuals into our model.
NoteAlternative models
This model is usually referred to as \(M_0\) in the mark-recapture literature, where detection probability is constant across individuals and sampling occasions. Other versions exist that allow variation in detection probability related to time (subscript \(t\)), behavioral responses to previous capture (subscript \(b\)), or heterogeneity among individuals (subscript \(h\)). These sources of variation can also be incorporated into a single model. For example, model \(M_bht\) assumes that detection probability can vary among individuals, among sampling occasions, and in response to whether an individual has been captured previously. These models allow us to relax the assumption of constant detection probability and account for biological and sampling processes that influence the probability of detecting an individual.
10.2.4.2 Data simulation
Let’s simulate a closed population of \(N=100\) individuals sampled on \(T=5\) occasions, with a constant detection probability of $p=0.3.
set.seed(123)# population and sampling parametersN <-100T <-5p <-0.3# simulate capture historiesy <-matrix(rbinom(N * T, size=1, prob=p),nrow=N, ncol=T)colnames(y) <-paste0("t", 1:T)head(y)
Each row of y represents an individual in the population, and each column represents a sampling occasion. Because we are simulating the data, we know the true population size and the capture histories of all individuals, including those that were never detected.
We can summarize the number of individuals detected during each sampling occasion:
colSums(y)
t1 t2 t3 t4 t5
29 26 29 31 28
And the frequency distribution of the number of times each individual was detected:
table(rowSums(y))
0 1 2 3 4
15 38 37 9 1
However, in a real mark-recapture study, we would not know about the individuals that were never detected. To create a realistic dataset, we need to remove the rows of the capture history matrix that consist entirely of zeros.
# retain only individuals detected at least onceyobs <- y[rowSums(y) >0, ]# number of unique individuals detectedn <-nrow(yobs)n
[1] 85
The matrix yobs now represents the dataset that we would have obtained from an actual mark-recapture study.
Given our simulation parameters, the probability that an individual is never detected during the study is
We therefore expect to detect approximately 83 of the 100 individuals at least once.
We can visualize the distribution of the number of detections per individual using a bar plot:
# frequency of capture history totalsfreq <-table(factor(rowSums(y), levels=0:T))barplot(freq,xlab="Number of detections",ylab="Number of individuals",col=c("grey70", rep("steelblue", T)))
Figure 10.4: text
This figure sets up the motivation for data augmentation nicely. The blue bars represent information that is available to us in a real study, whereas the gray bar represents the quantity that we need to infer.
10.2.4.3 Data augmentation
The challenge in fitting a closed-population mark-recapture model is that the number of individuals in the population, \(N\), is unknown, and our capture history matrix contains only the \(n\) individuals that were detected at least once. Data augmentation is a technique that addresses this problem by adding a large number of all-zero capture histories to the observed capture history matrix. The resulting augmented dataset contains \(M\) rows, where \(M\) is chosen to be substantially larger than any plausible population size. Each augmented capture history represents a potential individual that may or may not belong to the true population.
We introduce a latent indicator variable, \(z_i\), for each of the \(M\) potential individuals, where \(z_i=1\) if individual \(i\) belongs to the true population and \(z_i=0\) otherwise. We model population membership as a Bernoulli process,
\[
z_i\sim \text{Bernoulli}\left(\psi\right)
\]
where \(\psi\) is the probability that a potential individual belongs to the true population. We then modify our observation model to account for population membership,
\[
y_i\sim \text{Bernoulli}\left(z_i p\right)
\]
such that individuals belonging to the population have a probability \(p\) of being detected, whereas individuals that do not belong to the population have a detection probability of zero. For individuals that were detected at least once, \(z_i\) must equal 1. For individuals with all-zero capture histories, however, \(z_i\) is unknown: these could represent real individuals that were never detected or hypothetical individuals that do not exist in the population.
The true population size is then a derived parameter calculated as the sum of the population membership indicators,
\[
\hat{N}=\sum_{i=1}^mz_i
\]
Data augmentation therefore allows us to reformulate a problem with an unknown number of individuals as a problem with a fixed number of potential individuals whose population membership is uncertain. During MCMC sampling, we estimate \(p\), \(\psi\), and the latent membership indicators, obtaining a posterior distribution of \(N\). Note that \(M\) is a constant chosen by the researcher, not a parameter estimated by the model, and should be sufficiently large that it does not constrain the posterior distribution of \(N\).
10.2.4.4 Analysis in JAGS
The first step in fitting our closed-population model is to augment the observed capture history matrix (yobs) with additional rows of zeros. We will set \(M=300\), which is substantially larger than our true population size of 100 individuals. Note that we would not know the true population size in an actual study, so we would need to choose a value of \(M\) based on a plausible upper limit to population size or through trial and error.
# augment the capture history matrixM <-300n <-nrow(yobs)T <-ncol(yobs)yaug <-rbind(yobs,matrix(0, nrow=M-n, ncol=T))dim(yaug)
[1] 300 5
The augmented capture history matrix now contains \(M\) rows, the first \(n\) of which represent individuals known to belong to the population. The remaining \(M-n\) rows represent potential individuals whose population membership is unknown. Specifying the model
We need to specify priors for two parameters: the detection probability \(p\) and the population membership probability (\(\psi\)). Because both parameters are probabilities, we will use beta distributions as priors.
\[
p\sim\text{Beta}\left(1,1\right)
\]
\[
\psi\sim\text{Beta}\left(1,1\right)
\]
The remainder of the model follows directly from the equations that we developed in the previous section. This time we are going to supply the model as a function, not as a text file.
Note that we do not explicitly specify a prior for population size \(N\). Instead, the prior distribution of \(N\) is determined by the prior distribution of \(\psi\) and our choice of \(M\). In this case, specifying a uniform prior for \(\psi\) results in a discrete uniform prior for \(N\) over the integers from 0 to \(M\).
As with our previous models, we need to assemble the data into a list to pass to JAGS.
jags.data <-list(y=yaug,M=M,T=T)
We also need to provide initial values for our parameters, including the latent population membership indicators (z). It is particularly important that the initial values of z are consistent with the observed capture histories. If an individual was detected at least once, its population membership indicator must equal 1; otherwise, the probability of observing its capture history would be zero.
A simple solution is to initialize all membership indicators to 1. This is equivalent to starting each MCMC chain with the assumption that all \(M\) potential individuals belong to the population. JAGS will subsequently update these values during MCMC sampling.
Finally, we specify the parameters that we want to monitor. Although we could save the posterior samples of every population membership indicator, we are primarily interested in their sum, \(N\).
params <-c("p", "psi", "N")
We can now fit the model using the jags() function in the R2jags package.
Compiling model graph
Resolving undeclared variables
Allocating nodes
Graph information:
Observed stochastic nodes: 1500
Unobserved stochastic nodes: 302
Total graph size: 2107
Initializing model
print(mod01)
Inference for Bugs model at "C:/Users/ngreen62/AppData/Local/Temp/Rtmpyu0O7z/model47d03eb148a3", fit using jags,
3 chains, each with 10000 iterations (first 2000 discarded)
n.sims = 24000 iterations saved. Running time = 24.95 secs
mu.vect sd.vect 2.5% 25% 50% 75% 97.5% Rhat n.eff
N 109.602 8.103 96.000 104.000 109.000 114.000 128.000 1.001 5500
p 0.263 0.027 0.212 0.245 0.263 0.281 0.317 1.001 15000
psi 0.366 0.039 0.296 0.339 0.365 0.391 0.447 1.001 8300
For each parameter, n.eff is a crude measure of effective sample size,
and Rhat is the potential scale reduction factor (at convergence, Rhat=1).
10.2.4.5 Examine posterior distributions
We can extract the posterior samples from the model output and plot the posterior distributions of detection probability and population size.
The dashed red lines indicate the true values of the parameters that we used to simulate the data. Recall that these values were not provided to JAGS when fitting the model.
We can calculate posterior means and 95% credible intervals for each parameter:
p psi N
2.5% 0.212 0.296 96
50% 0.263 0.365 109
97.5% 0.317 0.447 128
We can also obtain the posterior distribution of the number of individuals that were never detected during the study by subtracting the number of observed individuals from each posterior sample of population size.
N.unobs <- mx[,"N"] - nmean(N.unobs)
[1] 24.60179
quantile(N.unobs, probs=c(0.025, 0.5, 0.975))
2.5% 50% 97.5%
11 24 43
It is also informative to examine the joint posterior distribution of population size and detection probability.
We should expect a negative relationship between \(N\) and \(p\) in the joint posterior distribution. Given the observed capture histories, a smaller population with a higher detection probability could produce data similar to those generated by a larger population with a lower detection probability. However, because we have information about repeated detections of individuals, we can estimate both parameters simultaneously.
Just for fun, we can visualize the most likely combinations of \(p\) and \(N\) using the ellipse package. This will use the covariance matrix of the posteriors and reflect the orientation of the joint posterior distribution.
The joint posterior distribution illustrates the negative relationship between detection probability and population size. Smaller values of detection probability imply that a larger proportion of the population remains undetected and, consequently, that population size is larger. Although our model slightly underestimates detection probability and overestimates population size, the true parameter values fall within the approximate 95% joint credible region. This example illustrates that uncertainty in detection probability translates directly into uncertainty in population size, and that the joint posterior distribution provides information about the relationship between parameters that is not apparent from their marginal posterior distributions alone.
Finally, we should verify that our choice of \(M\) was sufficiently large. Recall that the augmented dataset imposes an upper limit on population size because \(N\) cannot exceed \(M\).
range(mx[,"N"])
[1] 87 158
max(mx[,"N"])/M
[1] 0.5266667
If the posterior distribution of \(N\) approaches \(M\), we should increase the number of augmented capture histories and refit the model. Ideally, we should also verify that increasing \(M\) does not appreciably change our posterior estimates.
10.3 Distance sampling in JAGS
10.3.1 Basics of distance sampling
Distance sampling is a method of estimating population abundance and density that accounts for imperfect detection by modeling the relationship between detection probability and the distance of an individual from an observer. Unlike mark-recapture, distance sampling does not require individuals to be uniquely identifiable or detected on multiple sampling occasions. Instead, information about detection probability is obtained from the spatial distribution of detected individuals relative to a sampling point or transect. The fundamental principle of distance sampling is that individuals closer to an observer are generally more likely to be detected than individuals farther away.
There are two common approaches to distance sampling:
Line-transect sampling: An observer travels along a predetermined transect, recording the perpendicular distance of each detected individual from the transect line.
Point-transect sampling: An observer surveys the surrounding area from a fixed location, recording the radial distance of each detected individual from the sampling point.
Figure 10.8: text.
If transects are placed independently of the distribution of individuals, we expect individuals to be distributed uniformly with respect to perpendicular distance from a line transect, on average. However, because detection probability declines with distance, the distribution of distances of detected individuals will not be uniform. Instead, we expect to observe more individuals close to the transect than farther away. The difference between the expected distribution of individuals and the observed distribution of detections provides information about detection probability.
10.3.2 The detection function
10.3.2.1 Key functions
The relationship between detection probability and distance is described by a detection function, conventionally denoted \(g(x)\), where \(x\) is the distance of an individual from the transect or sampling point. Several functions can be used to model this relationship, but one of the most commonly used is the half-normal detection function,
where \(\sigma\) is the standard deviation of the function. Fitting the detection function essentially means fitting the \(\sigma\) term because the mean of the distribution is taken to be 0.
Several functions have been developed to describe the relationship between distance and detection probability. These functions are commonly referred to as key functions in the distance-sampling literature. They differ primarily in their shape near the transect and the rate at which detection probability declines with distance.
Table 10.2: Common key functions used to model detection probability in distance sampling, where \(x\) is the distance from the transect or sampling point.
Key function
Equation
Parameters
Description
Uniform
\(g(x)=1\)
None
Assumes perfect detection throughout the surveyed area. Generally used with adjustment terms.
Half-normal
\(g(x)=\exp\left(-\frac{x^2}{2\sigma^2}\right)\)
\(\sigma\): scale
Detection probability declines gradually near the transect and more rapidly at intermediate distances.
Allows for a relatively broad shoulder near the transect followed by a decline in detection probability.
Negative exponential
\(g(x)=\exp\left(-\frac{x}{\sigma}\right)\)
\(\sigma\): scale
Detection probability declines immediately and most rapidly near the transect, without a shoulder.
An important property of a detection function is its shoulder, or the region near the transect within which detection probability remains high. The half-normal and hazard rate functions have shoulders, whereas the negative exponential function does not. Detection functions with shoulders are generally preferred because small differences in distance close to the observer are unlikely to substantially affect detection probability.
10.3.2.2 Adjustment functions
Key functions can be combined with adjustment functions to provide additional flexibility in the shape of the detection function. The general form of a key-plus-adjustment model is
\[
g(x)=\frac{k(x)[1+A(x)]}{k(0)[1+A(0)]}
\] where \(g\left(x\right)\) is the adjusted detection function, \(k(x)\) is the key function, \(A(x)\) is the adjustment function, and \(x\) is the distance from the transect or sampling point. The denominator normalizes the detection function so that \(g(0)=1\).
Table 10.3 shows some common adjustment functions used in distance sampling.
Table 10.3: Common adjustment functions used to increase the flexibility of detection functions. The coefficients \(a_j\) are estimated parameters, \(w\) is the truncation distance, \(\sigma\) is the scale parameter of the key function, \(H_{2j}\) is an even-order Hermite polynomial, and \(J\) is the set of included adjustment orders.
Uses even-order Hermite polynomials to modify the shape of the key function.
Here, \(a_j\) represents an estimated adjustment coefficient, \(w\) is the truncation distance, \(H_{2j}\) is an even-order Hermite polynomial, and \(J\) is the set of included adjustment orders. The specific orders included depend on the choice of key function and adjustment series.
Common combinations include:
Table 10.4: Common combinations of key functions and adjustment functions used in conventional distance sampling.
Key function
Common adjustments
Uniform
Cosine, simple polynomial
Half-normal
Cosine, Hermite polynomial
Hazard rate
Cosine, simple polynomial
Negative exponential
Simple polynomial
Table 10.4 shows several common combinations of key functions and adjustment functions. The available combinations and the standardization of distance in adjustment functions can vary among software implementations. So, Table 10.4 is illustrative rather than an exhaustive list of permissible combinations.
Adjustment terms allow the detection function to accommodate departures from the shape of the key function alone. However, adding adjustment terms increases the number of parameters that must be estimated and can lead to overfitting or biologically unrealistic detection functions. Constraints may therefore be imposed to ensure that detection probability remains between 0 and 1 and declines monotonically with distance.
For our example, we will use the half-normal detection function without adjustment terms. This function has only one parameter, \(\sigma\), and provides a reasonable starting point for many biological applications. It also has the advantage that its integral can be expressed in terms of the cumulative distribution function of the normal distribution, which simplifies its implementation in JAGS.
10.3.3 Example analysis
Suppose we are interested in estimating the population size and density of white-tailed deer (Odocoileus virginianus) in a park using line-transect distance sampling. An observer walks along a transect and records the perpendicular distance from the transect to each deer detected. We will assume a maximum sampling distance (truncation distance) of 120 m on either side of the transect and that detection probability follows a half-normal detection function.
10.3.3.1 Data simulation
Simulating the system state
Let’s use a transect length of 2 km, which gives us a surveyed area of 48 ha and a true population density of approximately 1.67 deer per hectare.
Because the observer surveys both sides of the transect, the total area surveyed is
\[
A=2wL
\]
We can simulate the locations of the deer within this area by drawing their coordinates from uniform distributions.
set.seed(123)# population parametersN <-80L <-2000w <-120sigma <-50# calculate area (ha) and density (deer/ha)A <-2* w * L /10000D <- N / A# simulate locations of deerx <-runif(N, 0, L)y <-runif(N, -w, w)# perpendicular distance from transectd <-abs(y)
The variable x represents the position of each deer along the length of the transect, whereas y represents its position relative to the transect. Positive and negative values of y indicate opposite sides of the transect. The absolute value of y is therefore the perpendicular distance from the transect.
Simulating the observation process
Next, we use the half-normal detection function to calculate the probability of detecting each deer based on its perpendicular distance from the transect.
# half-normal detection functiong <-function(x, sigma){exp(-x^2/ (2* sigma^2))}# individual detection probabilitiesp <-g(d, sigma)# simulate detection of each deerdet <-rbinom(N, size=1, prob=p)# number of deer detectedn <-sum(det)n
[1] 38
Our “true” detection function produces a steep decline in detection probability across the surveyed area without making detections at greater distances exceptionally rare.
Figure 10.9: text
Under these simulation parameters, the average detection probability is approximately 0.514, so we expect to detect about 41 of the 80 deer.
10.3.3.2 Visualize the simulated survey
We can visualize the simulated population and the results of our survey by plotting the locations of all 80 deer, distinguishing between those that were detected and those that were not.
par(mar=c(5,5,1,1))plot(x, y, type="n",xlim=c(0,L), ylim=c(-w*1.2,w*1.2),xlab="Distance along transect (m)",ylab="Position relative to transect (m)")# transect and survey boundariesabline(h=0, lwd=2)abline(h=c(-w,w), lty=2, col="grey50")# undetected deerpoints(x[det==0], y[det==0],pch=1, col="grey50", cex=1.3)# detected deerpoints(x[det==1], y[det==1],pch=19, col="steelblue", cex=1.3)legend("topright",legend=c("Detected", "Undetected"),pch=c(19,1),col=c("steelblue","grey50"),bty="n", cex=1.3)
Figure 10.10: Simulated line-transect survey of a population of 80 deer. Filled circles represent detected deer, open circles represent undetected deer, and dashed lines indicate the truncation distance of 120 m on either side of the transect.
In a real distance-sampling study, we would not know the locations of the deer that were not detected. Our observed dataset would consist only of the perpendicular distances of the deer that were detected.
Figure 10.11: Distribution of perpendicular distances from the transect for all deer (gray) and detected deer (blue). Although deer are distributed approximately uniformly with respect to distance from the transect, detection frequency declines with increasing distance.
Notice in Figure 10.11 that the distribution of distances between observed deer and the transect drops off quickly, while the distribution of distances to all deer (observed and unobserved) does not.
If we simply divided the number of deer by the area surveyed, we would obtain a naive estimate of the population density. That estimate is less than half of the true density! The naive estimate of 0.79 deer/ha assumes that all deer are counted, which we know that they weren’t. So, we need to account for imperfect detection. That’s where distance sampling comes in.
In conventional distance-sampling analyses, it is common to fit several combinations of key functions and adjustment functions and use model selection criteria to identify the model that best describes the observed distribution of distances. We can take a similar approach in a Bayesian analysis.
For our simulated deer population, we will fit three candidate models:
table here
We will use the deviance information criterion (DIC) to compare the relative support for each model. Because we simulated our data using a half-normal detection function without adjustment terms, we know that Model 1 is the true model. However, sampling variation may result in greater support for one of the more complex models.
First, we need to prepare the data. Typically, distance sampling models are fit to data grouped into bins, or distance bands. We will use grouped distance data for this analysis. Recall that we divided the surveyed area into six distance intervals, each 20 m wide. We can count the number of deer detected within each interval.
# define distance intervalsbrks <-seq(0, w, by=20)K <-length(brks) -1# assign observations to intervalsdcat <-cut(dobs, breaks=brks,include.lowest=TRUE)# observed frequenciescounts <-as.numeric(table(dcat))n <-sum(counts)# lower and upper interval boundarieslower <- brks[1:K]upper <- brks[2:(K+1)]# interval widthswidth <- upper - lower# prepare for numerical integration# subdivide each distance interval into# J smaller intervals and calculate their# midpoints. We will evaluate the detection# function at each of these midpoints to # approximate its integral across each # distance interval.# number of subdivisions per distance intervalJ <-20# midpoints of subdivisionsdx <-matrix(NA, nrow=K, ncol=J)for(k in1:K){ dx[k,] <- lower[k] + ((1:J)-0.5)*width[k]/J}
Picking appropriate bin widths is a bit of an art. There is no requirement that bins be of equal width, only that each bin contains fewer observations than closer bins.
Let’s write the three models using identical ecological and observation processes, changing only the detection function and the prior for the adjustment coefficient. We’ll use the numerical integration approach with J subdivisions per distance interval.
Model 1: Half-normal with no adjustment
model01 <-function(){# priors sigma ~dunif(5, 120) psi ~dbeta(1, 1)# ecological process N ~dbin(psi, M)# detection functionfor(k in1:K){for(j in1:J){ g[k,j] <-exp(-dx[k,j]^2/(2*sigma^2)) }# integrate across distance interval q[k] <-sum(g[k,1:J])*width[k]/(J*w) }# average detection probability pbar <-sum(q[])# conditional detection probabilitiesfor(k in1:K){ pi[k] <- q[k]/pbar }# observation process n ~dbin(pbar, N) counts[1:K] ~dmulti(pi[], n)# derived parameters D <- N/A N.unobs <- N-n}
Model 2: Half-normal with cosine adjustment
The cosine adjustment requires normalization to ensure that \(g(0)=1\). We also constrain the prior on a to ensure that the detection function is monotonically nonincreasing.
model02 <-function(){# priors sigma ~dunif(5, 120) psi ~dbeta(1, 1)# constrained prior on adjustment coefficient amax <-0.999/(1+4*pi.const^2*sigma^2/w^2) a ~dunif(-amax, amax)# ecological process N ~dbin(psi, M)# detection functionfor(k in1:K){for(j in1:J){ key[k,j] <-exp(-dx[k,j]^2/(2*sigma^2)) adj[k,j] <- a*cos(2*pi.const*dx[k,j]/w) g[k,j] <- key[k,j]*(1+adj[k,j])/(1+a) }# integrate across distance interval q[k] <-sum(g[k,1:J])*width[k]/(J*w) }# average detection probability pbar <-sum(q[])# conditional detection probabilitiesfor(k in1:K){ pi[k] <- q[k]/pbar }# observation process n ~dbin(pbar, N) counts[1:K] ~dmulti(pi[], n)# derived parameters D <- N/A N.unobs <- N-n}
Model 3: Half-normal with simple polynomial adjustment
Unlike the cosine adjustment, the polynomial adjustment is zero at zero distance, so no additional normalization is necessary.
model03 <-function(){# priors sigma ~dunif(5, 120) psi ~dbeta(1, 1)# constrained prior on adjustment coefficient amax <- w^2/(2*sigma^2) a ~dunif(-0.999, amax)# ecological process N ~dbin(psi, M)# detection functionfor(k in1:K){for(j in1:J){ key[k,j] <-exp(-dx[k,j]^2/(2*sigma^2)) adj[k,j] <- a*(dx[k,j]/w)^2 g[k,j] <- key[k,j]*(1+adj[k,j]) }# integrate across distance interval q[k] <-sum(g[k,1:J])*width[k]/(J*w) }# average detection probability pbar <-sum(q[])# conditional detection probabilitiesfor(k in1:K){ pi[k] <- q[k]/pbar }# observation process n ~dbin(pbar, N) counts[1:K] ~dmulti(pi[], n)# derived parameters D <- N/A N.unobs <- N-n}
All three models use the same data list.
# upper bound on population sizeM <-500# assemble datajags.data <-list(n=n,counts=counts,K=K,J=J,dx=dx,width=width,w=w,M=M,A=A,pi.const=pi)
JAGS may issue a harmless warning about pi.const being unused in Models 2 and 4.
We need two initialization functions because the adjusted models contain an additional parameter, a. Initializing a at zero means that both adjusted models initially have the shape of an unadjusted half-normal detection function.
An important distinction is that q[k] represents the unconditional probability of occurring within a distance interval and being detected, whereas pi[k] represents the probability of occurring within that interval given that the individual was detected.
Using R2jags, we can run all three models with identical MCMC settings. We’ll use init.fun1 and params1 for the unadjusted half-normal model and init.fun2 and params2 for the two adjusted models.
Because we want to compare models using DIC, we will explicitly set DIC=TRUE.
library(R2jags)# Model 1: half-normalmod01 <-jags(data=jags.data,inits=init.fun1,parameters.to.save=params1,model.file=model01,n.chains=3,n.iter=20000,n.burnin=5000,n.thin=1,DIC=TRUE)
Compiling model graph
Resolving undeclared variables
Allocating nodes
Graph information:
Observed stochastic nodes: 2
Unobserved stochastic nodes: 3
Total graph size: 658
Initializing model
# Model 2: half-normal + cosinemod02 <-jags(data=jags.data,inits=init.fun2,parameters.to.save=params2,model.file=model02,n.chains=3,n.iter=20000,n.burnin=5000,n.thin=1,DIC=TRUE)
Compiling model graph
Resolving undeclared variables
Allocating nodes
Graph information:
Observed stochastic nodes: 2
Unobserved stochastic nodes: 4
Total graph size: 1390
Initializing model
# Model 3: half-normal + simple polynomialmod03 <-jags(data=jags.data,inits=init.fun2,parameters.to.save=params2,model.file=model03,n.chains=3,n.iter=20000,n.burnin=5000,n.thin=1,DIC=TRUE)
Compiling model graph
Resolving undeclared variables
Allocating nodes
Graph information:
Observed stochastic nodes: 2
Unobserved stochastic nodes: 4
Total graph size: 1263
Initializing model
10.3.3.4 Examine posteriors
Next, examine the model summaries and convergence diagnostics.
print(mod01)
Inference for Bugs model at "C:/Users/ngreen62/AppData/Local/Temp/Rtmpyu0O7z/model47d071f57670", fit using jags,
3 chains, each with 20000 iterations (first 5000 discarded)
n.sims = 45000 iterations saved. Running time = 4.07 secs
mu.vect sd.vect 2.5% 25% 50% 75% 97.5% Rhat n.eff
D 1.697 0.303 1.167 1.479 1.667 1.875 2.354 1.001 6200
N 81.458 14.565 56.000 71.000 80.000 90.000 113.000 1.001 6200
N.unobs 43.458 14.565 18.000 33.000 42.000 52.000 75.000 1.001 5100
pbar 0.480 0.067 0.372 0.433 0.472 0.519 0.633 1.001 5600
psi 0.164 0.033 0.106 0.141 0.162 0.185 0.236 1.001 7300
sigma 46.800 7.514 35.668 41.638 45.604 50.637 64.775 1.001 5100
deviance 22.205 2.047 20.190 20.732 21.568 23.040 27.665 1.002 2900
For each parameter, n.eff is a crude measure of effective sample size,
and Rhat is the potential scale reduction factor (at convergence, Rhat=1).
DIC info (using the rule: pV = var(deviance)/2)
pV = 2.1 and DIC = 24.3
DIC is an estimate of expected predictive error (lower deviance is better).
print(mod02)
Inference for Bugs model at "C:/Users/ngreen62/AppData/Local/Temp/Rtmpyu0O7z/model47d04ed969dd", fit using jags,
3 chains, each with 20000 iterations (first 5000 discarded)
n.sims = 45000 iterations saved. Running time = 7.06 secs
mu.vect sd.vect 2.5% 25% 50% 75% 97.5% Rhat n.eff
D 1.686 0.318 1.167 1.458 1.646 1.875 2.396 1.001 7400
N 80.935 15.283 56.000 70.000 79.000 90.000 115.000 1.001 7400
N.unobs 42.935 15.283 18.000 32.000 41.000 52.000 77.000 1.001 9700
a -0.009 0.088 -0.173 -0.076 -0.008 0.060 0.144 1.001 33000
pbar 0.486 0.071 0.365 0.435 0.480 0.529 0.642 1.001 16000
psi 0.163 0.035 0.104 0.139 0.160 0.184 0.239 1.001 15000
sigma 46.713 7.619 35.392 41.546 45.550 50.528 64.911 1.001 9600
deviance 22.266 2.084 20.085 20.807 21.646 23.078 27.823 1.001 7300
For each parameter, n.eff is a crude measure of effective sample size,
and Rhat is the potential scale reduction factor (at convergence, Rhat=1).
DIC info (using the rule: pV = var(deviance)/2)
pV = 2.2 and DIC = 24.4
DIC is an estimate of expected predictive error (lower deviance is better).
print(mod03)
Inference for Bugs model at "C:/Users/ngreen62/AppData/Local/Temp/Rtmpyu0O7z/model47d070676c0c", fit using jags,
3 chains, each with 20000 iterations (first 5000 discarded)
n.sims = 45000 iterations saved. Running time = 7.05 secs
mu.vect sd.vect 2.5% 25% 50% 75% 97.5% Rhat n.eff
D 1.615 0.287 1.146 1.417 1.583 1.792 2.250 1.001 19000
N 77.540 13.774 55.000 68.000 76.000 86.000 108.000 1.001 19000
N.unobs 39.540 13.774 17.000 30.000 38.000 48.000 70.000 1.001 18000
a 1.166 2.095 -0.966 -0.580 0.424 2.447 6.184 1.002 1800
pbar 0.504 0.068 0.388 0.455 0.498 0.548 0.649 1.001 15000
psi 0.156 0.032 0.102 0.134 0.154 0.176 0.225 1.001 12000
sigma 49.159 17.119 30.756 37.439 43.909 54.949 99.704 1.003 1300
deviance 22.259 2.032 20.177 20.775 21.661 23.127 27.635 1.002 2200
For each parameter, n.eff is a crude measure of effective sample size,
and Rhat is the potential scale reduction factor (at convergence, Rhat=1).
DIC info (using the rule: pV = var(deviance)/2)
pV = 2.1 and DIC = 24.3
DIC is an estimate of expected predictive error (lower deviance is better).
Now that we are satisfied with convergence, we can assemble a model selection table.
Let’s use identical histogram breaks and axis limits for all three models so that we can directly compare the location, spread, and shape of their posterior distributions. We’ll also add a dashed red line indicating the true population density (80/48 = 1.67 deer/ha).
# assemble density posteriorsds <-list(mx1[,"D"], mx2[,"D"], mx3[,"D"])labs <-c("Half-normal","Half-normal + cosine","Half-normal + polynomial")# common histogram breaksxr <-range(unlist(ds), D)brks.d <-pretty(xr, n=40)# calculate histogramshs <-lapply(ds, hist, breaks=brks.d, plot=FALSE)# common y-axis limitsyr <-c(0, max(sapply(hs, function(h) max(h$counts))))# plot histogramspar(mfrow=c(3,1), mar=c(4,5,2,1))for(i in1:3){plot(hs[[i]],xlim=range(brks.d),ylim=yr,col="grey80",border="white",main=labs[i],xlab="Population density (deer/ha)",ylab="Frequency")# true population densityabline(v=D, col="red", lwd=2, lty=2)}par(mfrow=c(1,1))
Figure 10.12: Posterior distributions of deer population density estimated using three candidate detection functions. Dashed red lines indicate the true population density.
All three models produced essentially identical posterior distributions of population density, and all three had posterior medians of \(D\) close to the true value of 1.67 deer/ha. The similarity in output isn’t surprising given how similar the fits were (all \(\Delta DIC <0.2\))
The additional flexibility afforded by the adjustment functions in models 2 and 3 did not produce additional uncertainty in the estimate of population density:
In the absence of clear evidence to prefer model 2 or 3 to model 1, I would retain and interpret model 1 because it achieves the same fit with fewer parameters. I.e., it is more parsimonious.