ringlik <- function(theta){ # Number of release occasions and recovery occasions ni = 11 nj = 11 # Read in the data: data <- matrix(c( 13,4,1,2,1,0,0,1,0,0,0,1125, 0,16,4,3,0,1,1,0,0,0,0,1260, 0,0,11,1,1,1,0,2,1,1,1,1087, 0,0,0,10,4,2,1,1,1,0,0,1596, 0,0,0,0,11,1,5,0,0,0,1,1600, 0,0,0,0,0,9,5,4,0,2,2,2098, 0,0,0,0,0,0,11,9,4,3,1,1975, 0,0,0,0,0,0,0,8,4,2,0,1949, 0,0,0,0,0,0,0,0,4,1,1,2457, 0,0,0,0,0,0,0,0,0,8,2,3082, 0,0,0,0,0,0,0,0,0,0,16,3426),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) lambda <- array(0,nj) q <- array(0,dim=c(ni,nj+1)) # Define the parameters to be constant or time-dependent for (i in 1:nj) { lambda[i] <- 1/(1+exp(-theta[1])) phi[i] <- 1/(1+exp(-theta[2])) } # Calcuate the multinomial cell probabilities # Diagonal elements for (i in 1:ni){ q[i,i] <- (1-phi[i])*lambda[i] } # Off diagonal elements for (i in 1:(ni-1)){ for (j in (i+1):nj) { q[i,j] <- prod(phi[i:(j-1)])*(1-phi[j])*lambda[j] } } # 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 }