caplik <- function(theta){ # Number of release occasions and recovery occasions ni = 6 nj = 6 # Read in the data (dipper data): data <- matrix(c( 11,2,0,0,0,0,9, 0,24,1,0,0,0,35, 0,0,34,2,0,0,42, 0,0,0,45,1,2,32, 0,0,0,0,51,0,37, 0,0,0,0,0,52,46),nrow=ni,byrow=T) # Set up the size of the arrays containing the survival probabilities, recapture # probabilities and cell probabilities and set them all initially to zero phi <- array(0,nj) p <- array(0,(nj+1)) pbar <- array(0,(nj+1)) q <- array(0,dim=c(ni,nj+1)) # Define the parameters to be constant or time-dependent for (i in 1:nj) { p[i+1] <- 1/(1+exp(-theta[1])) phi[i] <- 1/(1+exp(-theta[2])) pbar[i+1]<-1-p[i+1] } # Calcuate the multinomial cell probabilities # Diagonal elements for (i in 1:ni){ q[i,i] <- phi[i]*p[i+1] } # Off diagonal elements for (i in 1:(ni-1)){ for (j in (i+1):nj) { q[i,j] <- prod(phi[i:j])*prod(pbar[(i+1):j])*p[j+1] } } # Calculate the disappearing animal probabilities for (i in 1:ni){ q[i,nj+1] <- 1 - sum(q[i,i:nj]) } # Calculate the likelihood function likhood <- 0 for (i in 1:ni){ for (j in i:(nj+1)) { likhood <- likhood + data[i,j]*log(q[i,j]) } } # Output the negative loglikelihood value: likhood<- -likhood }