sample abundance N in N-mixture models

Skip to first unread message

Qing Zhao

May 22, 2023, 3:39:17 PM5/22/23
to nimble-users
Dear all,

Here is a N-mixture model.

code <- nimbleCode({
  # Priors
  for (k in 1:2) {
    beta[k] ~ dnorm(0, sd=10)
  } # k
  p ~ dunif(0, 1)

  lambda[1:nsite] <- exp(x[1:nsite,1:2] %*% beta[1:2])
  for(i in 1:nsite) {
    N[i] ~ dpois(lambda[i])
    y[i] ~ dbin(p, N[i])
  } # i

}) # nimbleCode

The default sampler for the true abundance N is a slice sampler.

In the Hooten & Hefley "Bringing Bayesian Models to Life" book, they use a sampler that is written as following:

    N_star <- rpois(nsite, N + 1)
    mh1 <- apply(dbinom(y, N_star, p, log=T), 1, sum) +
           dpois(N_star, lambda, log=T) +
           dpois(N, N_star+1, log=T)
    mh2 <- apply(dbinom(y, N     , p, log=T), 1, sum) +
           dpois(N     , lambda, log=T) +
           dpois(N_star, N+1, log=T)
    mh <- exp(mh1 - mh2)
    Nkeep <- ((mh > runif(nsite)) & (N_star >= ymax))
    N[Nkeep] <- N_star[Nkeep]

I would assume this is different from a slice sampler and it is more efficient because it updates all N's simultaneously. Please let me know if I got it wrong.

Is this sampler implemented in Nimble? If yes, what is its name? 

Any help will be greatly appreciated.


Daniel Turek

May 24, 2023, 4:28:54 PM5/24/23
to Qing Zhao, nimble-users
Qing, great question.  This sampler code you provided amounts to (simultaneously, in a vectorized fashion) making nsite new (independent) proposals for each of the nsite different values in the N array, then doing nsite independent Metropolis-Hastings accept/reject decisions, one for each of these proposals.  This is effectively doing nsite independent Metropolis-Hastings proposal and accept/reject steps, sequentially, for each of the N[i] elements.

This is different from a slice sampler, which is a fundamentally different MCMC sampling algorithm. The algorithm you quoted is univariate Metropolis-Hastings, with a Poisson proposal distribution, applied nsite times (in a vectorized fashion) to all elements of N.

This sampler is not implemented in nimble, but it would be straightforward to modify the code of nimble's RW (Metropolis-Hastings) sampler, to instead use a Poisson proposal distribution, then apply that to each element of N[i].

I hope this helps, and keep up the good work.


You received this message because you are subscribed to the Google Groups "nimble-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to
To view this discussion on the web visit

Qing Zhao

May 24, 2023, 4:38:06 PM5/24/23
to nimble-users
Hi Daniel,

Thank you very much for your response. I will give it a try (to modify the sampler).

Reply all
Reply to author
0 new messages