pbs-assess / sdmTMB

:earth_americas: An R package for spatial and spatiotemporal GLMMs with TMB
https://pbs-assess.github.io/sdmTMB/
182 stars 26 forks source link

MCMC samples don't work with `extra_time` #297

Closed ericward-noaa closed 5 months ago

ericward-noaa commented 5 months ago

The reason for this is that when extra_time is used, the dataframe is modified internally to include extra rows -- one for each of the years / timesteps in extra_time. The fit$tmb_data$offset_i object is also modified similarly.

library(sdmTMBextra)
#> 
#> Attaching package: 'sdmTMBextra'
#> The following objects are masked from 'package:sdmTMB':
#> 
#>     add_barrier_mesh, dharma_residuals, extract_mcmc
mesh <- make_mesh(pcod_2011, c("X", "Y"), cutoff = 20)

fit <- sdmTMB(
  density ~ 0 + as.factor(year),
  time = "year", #<
  data = pcod_2011, mesh = mesh,
  family = tweedie(link = "log"),
  extra_time = c(2012, 2014, 2016)
)

set.seed(123)
samps <- sdmTMBextra::predict_mle_mcmc(fit, mcmc_iter = 201, mcmc_warmup = 200)
#> 
#> SAMPLING FOR MODEL 'tmb_generic' NOW (CHAIN 1).
#> Chain 1: 
#> Chain 1: Gradient evaluation took 0.002488 seconds
#> Chain 1: 1000 transitions using 10 leapfrog steps per transition would take 24.88 seconds.
#> Chain 1: Adjust your expectations accordingly!
#> Chain 1: 
#> Chain 1: 
#> Chain 1: Iteration:   1 / 201 [  0%]  (Warmup)
#> Chain 1: Iteration:  20 / 201 [  9%]  (Warmup)
#> Chain 1: Iteration:  40 / 201 [ 19%]  (Warmup)
#> Chain 1: Iteration:  60 / 201 [ 29%]  (Warmup)
#> Chain 1: Iteration:  80 / 201 [ 39%]  (Warmup)
#> Chain 1: Iteration: 100 / 201 [ 49%]  (Warmup)
#> Chain 1: Iteration: 120 / 201 [ 59%]  (Warmup)
#> Chain 1: Iteration: 140 / 201 [ 69%]  (Warmup)
#> Chain 1: Iteration: 160 / 201 [ 79%]  (Warmup)
#> Chain 1: Iteration: 180 / 201 [ 89%]  (Warmup)
#> Chain 1: Iteration: 200 / 201 [ 99%]  (Warmup)
#> Chain 1: Iteration: 201 / 201 [100%]  (Sampling)
#> Chain 1: 
#> Chain 1:  Elapsed Time: 7.458 seconds (Warm-up)
#> Chain 1:                0.022 seconds (Sampling)
#> Chain 1:                7.48 seconds (Total)
#> Chain 1:
#> Error in `predict()`:
#> ! Prediction offset vector does not equal number of rows in prediction
#>   dataset.

Created on 2024-02-08 with reprex v2.1.0

seananderson commented 5 months ago

Should be fixed now over in sdmTMBextra along with new unit tests here.