{"id":13724831,"url":"https://github.com/pbs-assess/sdmTMB","last_synced_at":"2025-05-07T19:30:44.694Z","repository":{"id":37269744,"uuid":"149399567","full_name":"pbs-assess/sdmTMB","owner":"pbs-assess","description":":earth_americas: An R package for spatial and spatiotemporal GLMMs with TMB","archived":false,"fork":false,"pushed_at":"2025-04-13T17:49:19.000Z","size":385618,"stargazers_count":206,"open_issues_count":32,"forks_count":27,"subscribers_count":14,"default_branch":"main","last_synced_at":"2025-05-04T16:50:20.470Z","etag":null,"topics":["ecology","glmm","r","spatial-analysis","species-distribution-modelling","tmb"],"latest_commit_sha":null,"homepage":"https://pbs-assess.github.io/sdmTMB/","language":"R","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/pbs-assess.png","metadata":{"files":{"readme":"README.Rmd","changelog":"NEWS.md","contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2018-09-19T05:59:53.000Z","updated_at":"2025-04-16T14:09:29.000Z","dependencies_parsed_at":"2023-12-18T23:28:02.690Z","dependency_job_id":"cf770752-ef43-4e22-98f3-1ffda2664cc8","html_url":"https://github.com/pbs-assess/sdmTMB","commit_stats":{"total_commits":2312,"total_committers":18,"mean_commits":"128.44444444444446","dds":"0.15138408304498274","last_synced_commit":"af6267e873c0069b3b6d05530cc4482050946a66"},"previous_names":[],"tags_count":8,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pbs-assess%2FsdmTMB","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pbs-assess%2FsdmTMB/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pbs-assess%2FsdmTMB/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pbs-assess%2FsdmTMB/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/pbs-assess","download_url":"https://codeload.github.com/pbs-assess/sdmTMB/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":252931535,"owners_count":21827111,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["ecology","glmm","r","spatial-analysis","species-distribution-modelling","tmb"],"created_at":"2024-08-03T01:02:04.131Z","updated_at":"2025-05-07T19:30:44.687Z","avatar_url":"https://github.com/pbs-assess.png","language":"R","funding_links":[],"categories":["Biosphere","R"],"sub_categories":["Species Distribution Modeling"],"readme":"---\noutput: \n  github_document:\n    toc: true\n    toc_depth: 3\n    df_print: \"tibble\"\n    includes:\n      in_header: header.md\n---\n\n```{r setup, include = FALSE}\nknitr::opts_chunk$set(\n  collapse = TRUE,\n  comment = \"#\u003e\",\n  fig.path = \"man/figures/README-\",\n  out.width = \"50%\",\n  cache = FALSE,\n  autodep = TRUE,\n  dpi = 72\n)\n```\n    \n## Installation\n\nsdmTMB can be installed from CRAN:\n\n```{r, eval=FALSE}\ninstall.packages(\"sdmTMB\", dependencies = TRUE)\n```\n\nAssuming you have a [C++ compiler](https://support.posit.co/hc/en-us/articles/200486498-Package-Development-Prerequisites) installed, the development version is recommended and can be installed:\n\n```{r, eval=FALSE}\n# install.packages(\"pak\")\npak::pkg_install(\"pbs-assess/sdmTMB\", dependencies = TRUE)\n```\n\nThere are some extra utilities in the [sdmTMBextra](https://github.com/pbs-assess/sdmTMBextra) package.\n\n**Importantly**, it is recommended to use an optimized BLAS library, which will result in major speed improvements for TMB (and other) models in R (e.g., often 8-fold speed increases for sdmTMB models).\nSuggested installation instructions for [Mac users](https://www.mail-archive.com/r-sig-mac@r-project.org/msg06199.html), [Linux users](https://prdm0.github.io/ropenblas/), [Windows users](https://github.com/david-cortes/R-openblas-in-windows), and [Windows users without admin privileges](https://gist.github.com/seananderson/08a51e296a854f227a908ddd365fb9c1).\nTo check that you've successfully linked the optimized BLAS, start a new session and run:\n\n```r\nm \u003c- 1e4; n \u003c- 1e3; k \u003c- 3e2\nX \u003c- matrix(rnorm(m*k), nrow=m); Y \u003c- matrix(rnorm(n*k), ncol=n)\nsystem.time(X %*% Y)\n```\n\nThe result ('elapsed') should take a fraction of a second (e.g., 0.03 s), not multiple seconds.\n\n## Overview\n\nAnalyzing geostatistical data (coordinate-referenced observations from some underlying spatial process) is becoming increasingly common in ecology.\nsdmTMB implements geostatistical spatial and spatiotemporal GLMMs using TMB for model fitting and R-INLA to set up SPDE (stochastic partial differential equation) matrices.\nOne common application is for species distribution models (SDMs), hence the package name.\nThe goal of sdmTMB is to provide a fast, flexible, and user-friendly interface---similar to the popular R package glmmTMB---but with a focus on spatial and spatiotemporal models with an SPDE approach.\nWe extend the generalized linear mixed models (GLMMs) familiar to ecologists to include the following optional features:\n\n* spatial random fields\n* spatiotemporal random fields that may be independent by year or modelled with random walks or autoregressive processes\n* smooth terms for covariates, using the familiar `s()` notation from mgcv\n* breakpoint (hockey-stick) or logistic covariates\n* time-varying covariates (coefficients modelled as random walks)\n* spatially varying coefficient models (SVCs)\n* interpolation or forecasting over missing or future time slices\n* a wide range of families: all standard R families plus `tweedie()`, `nbinom1()`, `nbinom2()`, `lognormal()`, and `student()`, plus some truncated and censored families\n* delta/hurdle models including `delta_gamma()`, `delta_lognormal()`, and `delta_truncated_nbinom2()`\n\nEstimation is performed in sdmTMB via maximum marginal likelihood with the objective function calculated in TMB and minimized in R via `stats::nlminb()` with the random effects integrated over via the Laplace approximation.\nThe sdmTMB package also allows for models to be passed to Stan via tmbstan, allowing for Bayesian model estimation.\n\nSee [`?sdmTMB`](https://pbs-assess.github.io/sdmTMB/reference/sdmTMB.html) and [`?predict.sdmTMB`](https://pbs-assess.github.io/sdmTMB/reference/predict.sdmTMB.html) for the most complete examples. Also see the vignettes ('Articles') on the [documentation site](https://pbs-assess.github.io/sdmTMB/index.html) and the preprint and appendices linked to below.\n\n## Getting help\n\nFor questions about how to use sdmTMB or interpret the models, please post on the [ discussion board](https://github.com/pbs-assess/sdmTMB/discussions). If you [email](https://github.com/pbs-assess/sdmTMB/blob/main/DESCRIPTION) a question, we are likely to respond on the [discussion board](https://github.com/pbs-assess/sdmTMB/discussions) with an anonymized version of your question (and without data) if we think it could be helpful to others. Please let us know if you don't want us to do that.\n\nFor bugs or feature requests, please post in the [issue tracker](https://github.com/pbs-assess/sdmTMB/issues).\n\n[Slides](https://pbs-assess.github.io/sdmTMB-teaching/noaa-psaw-2022/) and [recordings](https://www.youtube.com/channel/UCYoFG51RjJVx7m9mZGaj-Ng/videos) from a workshop on sdmTMB.\n\n## Citation\n\nTo cite sdmTMB in publications use:\n\n```r\ncitation(\"sdmTMB\")\n```\n\nAnderson, S.C., E.J. Ward, P.A. English, L.A.K. Barnett., J.T. Thorson. 2025.\nsdmTMB: an R package for fast, flexible, and user-friendly generalized linear\nmixed effects models with spatial and spatiotemporal random fields.\nIn press at Journal of Statistical Software. \nbioRxiv preprint: \u003chttps://doi.org/10.1101/2022.03.24.485545\u003e.\n\nA list of (known) publications that use sdmTMB can be found [here](https://github.com/pbs-assess/sdmTMB/wiki/Publications-using-sdmTMB). Please use the above citation so we can track publications.\n\n## Related software\n\nsdmTMB is heavily inspired by the [VAST](https://github.com/James-Thorson-NOAA/VAST) R package:\n\nThorson, J.T. 2019. Guidance for decisions using the Vector Autoregressive Spatio-Temporal (VAST) package in stock, ecosystem, habitat and climate assessments. Fisheries Research 210: 143–161. \u003chttps://doi.org/10.1016/j.fishres.2018.10.013\u003e.\n\nand the [glmmTMB](https://github.com/glmmTMB/glmmTMB) R package:\n\nBrooks, M.E., Kristensen, K., van Benthem, K.J., Magnusson, A., Berg, C.W., Nielsen, A., Skaug, H.J., Maechler, M., and Bolker, B.M. 2017. glmmTMB balances speed and flexibility among packages for zero-inflated generalized linear mixed modeling. The R Journal 9(2): 378–400. \u003chttps://doi.org/10.32614/rj-2017-066\u003e.\n\n[INLA](https://www.r-inla.org/) and [inlabru](https://sites.google.com/inlabru.org/inlabru) can fit many of the same models as sdmTMB (and many more) in an approximate Bayesian inference framework.\n\n[mgcv](https://cran.r-project.org/package=mgcv) can fit similar SPDE-based Gaussian random field models with code included in [Miller et al. (2019)](https://doi.org/10.1007/s13253-019-00377-z).\n\nA table in the [sdmTMB preprint](https://doi.org/10.1101/2022.03.24.485545) describes functionality and timing comparisons between sdmTMB, VAST, INLA/inlabru, and mgcv and the discussion makes suggestions about when you might choose one package over another.\n\n## Basic use\n\nAn sdmTMB model requires a data frame that contains a response column, columns for any predictors, and columns for spatial coordinates.\nIt usually makes sense to convert the spatial coordinates to an equidistant projection such as UTMs such that distance remains constant throughout the study region [e.g., using `sf::st_transform()`].\nHere, we illustrate a spatial model fit to Pacific cod (*Gadus macrocephalus*) trawl survey data from Queen Charlotte Sound, BC, Canada.\nOur model contains a main effect of depth as a penalized smoother, a spatial random field, and Tweedie observation error.\nOur data frame `pcod` (built into the package) has a column `year` for the year of the survey, `density` for density of Pacific cod in a given survey tow, `present` for whether `density \u003e 0`, `depth` for depth in meters of that tow, and spatial coordinates `X` and `Y`, which are UTM coordinates in kilometres.\n\n```{r, echo=TRUE, eval=FALSE, cache=FALSE}\nlibrary(dplyr)\nlibrary(ggplot2)\nlibrary(sdmTMB)\nhead(pcod)\n```\n\n```{r, echo=FALSE, eval=TRUE, message=FALSE, warning=FALSE, cache=FALSE}\nlibrary(dplyr)\nlibrary(ggplot2)\nlibrary(sdmTMB)\ntheme_set(theme_light())\ndplyr::select(pcod, year, density, present, depth, X, Y) %\u003e% \n  head(n = 3)\n```\n\nWe start by creating a mesh object that contains matrices to apply the SPDE approach.\n\n```{r}\nmesh \u003c- make_mesh(pcod, xy_cols = c(\"X\", \"Y\"), cutoff = 10)\n```\n\nHere, `cutoff` defines the minimum allowed distance between points in the units of `X` and `Y` (km). Alternatively, we could have created any mesh via the fmesher or INLA packages and supplied it to `make_mesh()`. \nWe can inspect our mesh object with the associated plotting method `plot(mesh)`.\n\nFit a spatial model with a smoother for depth:\n\n```{r, warning=FALSE, message=FALSE}\nfit \u003c- sdmTMB(\n  density ~ s(depth),\n  data = pcod,\n  mesh = mesh,\n  family = tweedie(link = \"log\"),\n  spatial = \"on\"\n)\n```\n\nPrint the model fit:\n\n```{r}\nfit\n```\n\nThe output indicates our model was fit by maximum (marginal) likelihood (`ML`). We also see the formula, mesh, fitted data, and family. Next we see any estimated main effects including the linear component of the smoother (`sdepth`), the standard deviation on the smoother weights (`sds(depth)`), the Tweedie dispersion and power parameters, the Matérn range distance (distance at which points are effectively independent), the marginal spatial field standard deviation, and the negative log likelihood at convergence.\n\nWe can extract parameters as a data frame:\n\n```{r}\ntidy(fit, conf.int = TRUE)\ntidy(fit, effects = \"ran_pars\", conf.int = TRUE)\n```\n\nRun some basic sanity checks on our model:\n\n```{r}\nsanity(fit)\n```\n\nUse the [ggeffects](https://github.com/strengejacke/ggeffects) package to plot the smoother effect:\n\n```{r plot-ggpredict-link, warning=FALSE, message=FALSE}\nggeffects::ggpredict(fit, \"depth [50:400, by=2]\") |\u003e plot()\n```\n\nIf the depth effect was parametric and not a penalized smoother, we could have alternatively used `ggeffects::ggeffect()` for a fast marginal effect plot.\n\nNext, we can predict on new data.\nWe will use a data frame `qcs_grid` from the package, which contains all the locations (and covariates) at which we wish to predict.\nHere, these `newdata` are a grid, or raster, covering our survey.\n\n```{r}\np \u003c- predict(fit, newdata = qcs_grid)\n```\n\n```{r, eval=FALSE, echo=TRUE}\nhead(p)\n```\n\n```{r, eval=TRUE, echo=FALSE}\nselect(p, X, Y, depth, est, est_non_rf, est_rf, omega_s) %\u003e% \n  head(n = 3)\n```\n\n```{r plot-predictions}\nggplot(p, aes(X, Y, fill = exp(est))) + geom_raster() +\n  scale_fill_viridis_c(trans = \"sqrt\")\n```\n\nWe could switch to a presence-absence model by changing the response column and family:\n\n```{r, eval=TRUE}\nfit \u003c- sdmTMB(\n  present ~ s(depth),\n  data = pcod, \n  mesh = mesh,\n  family = binomial(link = \"logit\")\n)\n```\n\nOr a hurdle/delta model by changing the family:\n\n```{r, eval=TRUE}\nfit \u003c- sdmTMB(\n  density ~ s(depth),\n  data = pcod,\n  mesh = mesh,\n  family = delta_gamma(link1 = \"logit\", link2 = \"log\"),\n)\n```\n\nWe could instead fit a spatiotemporal model by specifying the `time` column and a spatiotemporal structure:\n\n```{r, eval=TRUE, echo=TRUE, warning=FALSE, message=FALSE}\nfit_spatiotemporal \u003c- sdmTMB(\n  density ~ s(depth, k = 5), \n  data = pcod, \n  mesh = mesh,\n  time = \"year\",\n  family = tweedie(link = \"log\"), \n  spatial = \"off\", \n  spatiotemporal = \"ar1\"\n)\n```\n\nIf we wanted to create an area-weighted standardized population index, we could predict on a grid covering the entire survey (`qcs_grid`) with grid cell area 4 (2 x 2 km) and pass the predictions to `get_index()`:\n\n```{r plot-index, warning=FALSE, message=FALSE}\ngrid_yrs \u003c- replicate_df(qcs_grid, \"year\", unique(pcod$year))\np_st \u003c- predict(fit_spatiotemporal, newdata = grid_yrs, \n  return_tmb_object = TRUE)\nindex \u003c- get_index(p_st, area = rep(4, nrow(grid_yrs)))\nggplot(index, aes(year, est)) +\n  geom_ribbon(aes(ymin = lwr, ymax = upr), fill = \"grey90\") +\n  geom_line(lwd = 1, colour = \"grey30\") +\n  labs(x = \"Year\", y = \"Biomass (kg)\")\n```\n\nOr the center of gravity:\n\n```{r plot-cog, message=FALSE, warning=FALSE}\ncog \u003c- get_cog(p_st, format = \"wide\")\nggplot(cog, aes(est_x, est_y, colour = year)) +\n  geom_pointrange(aes(xmin = lwr_x, xmax = upr_x)) +\n  geom_pointrange(aes(ymin = lwr_y, ymax = upr_y)) +\n  scale_colour_viridis_c()\n```\n\nFor more on these basic features, see the vignettes [Intro to modelling with sdmTMB](https://pbs-assess.github.io/sdmTMB/articles/basic-intro.html) and [Index standardization with sdmTMB](https://pbs-assess.github.io/sdmTMB/articles/index-standardization.html). \n\n## Advanced functionality\n\n### Time-varying coefficients\n\nTime-varying intercept:\n\n```{r, eval=FALSE}\nfit \u003c- sdmTMB(\n  density ~ 0 + s(depth, k = 5), \n  time_varying = ~ 1, \n  data = pcod, mesh = mesh,\n  time = \"year\",  \n  family = tweedie(link = \"log\"),\n  silent = FALSE # see progress\n)\n```\n\nTime-varying (random walk) effect of depth:\n\n```{r, eval=FALSE}\nfit \u003c- sdmTMB(\n  density ~ 1, \n  time_varying = ~ 0 + depth_scaled + depth_scaled2,\n  data = pcod, mesh = mesh,\n  time = \"year\",\n  family = tweedie(link = \"log\"),\n  spatial = \"off\",\n  spatiotemporal = \"ar1\",\n  silent = FALSE\n)\n```\n\nSee the vignette [Intro to modelling with sdmTMB](https://pbs-assess.github.io/sdmTMB/articles/basic-intro.html) for more details.\n\n### Spatially varying coefficients (SVC)\n\nSpatially varying effect of time:\n\n```{r, eval=TRUE, warning=FALSE}\npcod$year_scaled \u003c- as.numeric(scale(pcod$year))\nfit \u003c- sdmTMB(\n  density ~ s(depth, k = 5) + year_scaled,\n  spatial_varying = ~ year_scaled, \n  data = pcod, mesh = mesh, \n  time = \"year\",\n  family = tweedie(link = \"log\"),\n  spatiotemporal = \"off\"\n)\n```\n\nSee `zeta_s` in the output, which represents the coefficient varying in space. You'll want to ensure you set up your model such that it ballpark has a mean of 0 (e.g., by including it in `formula` too).\n\n```{r plot-zeta}\ngrid_yrs \u003c- replicate_df(qcs_grid, \"year\", unique(pcod$year))\ngrid_yrs$year_scaled \u003c- (grid_yrs$year - mean(pcod$year)) / sd(pcod$year)\np \u003c- predict(fit, newdata = grid_yrs) %\u003e% \n  subset(year == 2011) # any year\nggplot(p, aes(X, Y, fill = zeta_s_year_scaled)) + geom_raster() +\n  scale_fill_gradient2()\n```\n\nSee the vignette on [Fitting spatial trend models with sdmTMB](https://pbs-assess.github.io/sdmTMB/articles/spatial-trend-models.html) for more details.\n\n### Random intercepts\n\nWe can use the same syntax (`1 | group`) as lme4 or glmmTMB to fit random intercepts:\n\n```{r, eval=FALSE, echo=TRUE, warning=FALSE, message=FALSE}\npcod$year_factor \u003c- as.factor(pcod$year)\nfit \u003c- sdmTMB(\n  density ~ s(depth, k = 5) + (1 | year_factor),\n  data = pcod, mesh = mesh,\n  time = \"year\",\n  family = tweedie(link = \"log\")\n)\n```\n\n### Breakpoint and threshold effects\n\n```{r, eval=FALSE}\nfit \u003c- sdmTMB(\n  present ~ 1 + breakpt(depth_scaled), \n  data = pcod, mesh = mesh,\n  family = binomial(link = \"logit\")\n)\n```\n\n```{r, eval=FALSE}\nfit \u003c- sdmTMB(\n  present ~ 1 + logistic(depth_scaled), \n  data = pcod, mesh = mesh,\n  family = binomial(link = \"logit\")\n)\n```\n\nSee the vignette on [Threshold modeling with sdmTMB](https://pbs-assess.github.io/sdmTMB/articles/threshold-models.html) for more details.\n\n### Simulating data\n\n#### Simulating data from scratch\n\n```{r}\npredictor_dat \u003c- expand.grid(\n  X = seq(0, 1, length.out = 100), Y = seq(0, 1, length.out = 100)\n)\nmesh \u003c- make_mesh(predictor_dat, xy_cols = c(\"X\", \"Y\"), cutoff = 0.05)\nsim_dat \u003c- sdmTMB_simulate(\n  formula = ~ 1,\n  data = predictor_dat,\n  mesh = mesh,\n  family = poisson(link = \"log\"),\n  range = 0.3,\n  sigma_O = 0.4,\n  seed = 1,\n  B = 1 # B0 = intercept\n)\nhead(sim_dat)\n\n# sample 200 points for fitting:\nset.seed(1)\nsim_dat_obs \u003c- sim_dat[sample(seq_len(nrow(sim_dat)), 200), ]\n```\n\n```{r plot-sim-dat}\nggplot(sim_dat, aes(X, Y)) +\n  geom_raster(aes(fill = exp(eta))) + # mean without observation error\n  geom_point(aes(size = observed), data = sim_dat_obs, pch = 21) +\n  scale_fill_viridis_c() +\n  scale_size_area() +\n  coord_cartesian(expand = FALSE)\n```\n\nFit to the simulated data:\n\n```{r}\nmesh \u003c- make_mesh(sim_dat_obs, xy_cols = c(\"X\", \"Y\"), cutoff = 0.05)\nfit \u003c- sdmTMB(\n  observed ~ 1,\n  data = sim_dat_obs,\n  mesh = mesh,\n  family = poisson()\n)\n```\n\nSee [`?sdmTMB_simulate`](https://pbs-assess.github.io/sdmTMB/reference/sdmTMB_simulate.html) for more details.\n\n#### Simulating from an existing fit\n\n```{r sim, include=FALSE, eval=FALSE}\ns \u003c- simulate(fit, nsim = 500)\ndim(s)\ns[1:3,1:4]\n```\n\n``` r\ns \u003c- simulate(fit, nsim = 500)\ndim(s)\n#\u003e [1] 969 500\ns[1:3,1:4]\n#\u003e      [,1]     [,2]     [,3]     [,4]\n#\u003e [1,]    0 59.40310 83.20888  0.00000\n#\u003e [2,]    0 34.56408  0.00000 19.99839\n#\u003e [3,]    0  0.00000  0.00000  0.00000\n```\n\nSee the vignette on [Residual checking with sdmTMB](https://pbs-assess.github.io/sdmTMB/articles/residual-checking.html),  [`?simulate.sdmTMB`](https://pbs-assess.github.io/sdmTMB/reference/simulate.sdmTMB.html), and [`?dharma_residuals`](https://pbs-assess.github.io/sdmTMB/reference/dharma_residuals.html) for more details.\n\n### Sampling from the joint precision matrix\n\nWe can take samples from the implied parameter distribution assuming an MVN covariance matrix on the internal parameterization:\n\n```{r plot-mvn}\nsamps \u003c- gather_sims(fit, nsim = 1000)\nggplot(samps, aes(.value)) + geom_histogram() +\n  facet_wrap(~.variable, scales = \"free_x\")\n```\n\nSee [`?gather_sims`](https://pbs-assess.github.io/sdmTMB/reference/gather_sims.html) and [`?get_index_sims`](https://pbs-assess.github.io/sdmTMB/reference/get_index_sims.html) for more details.\n\n### Calculating uncertainty on spatial predictions\n\nThe fastest way to get point-wise prediction uncertainty is to use the MVN samples:\n\n```{r plot-pred-mvn}\np \u003c- predict(fit, newdata = predictor_dat, nsim = 500)\npredictor_dat$se \u003c- apply(p, 1, sd)\nggplot(predictor_dat, aes(X, Y, fill = se)) +\n  geom_raster() +\n  scale_fill_viridis_c(option = \"A\") +\n  coord_cartesian(expand = FALSE)\n```\n\n### Cross validation\n\nsdmTMB has built-in functionality for cross-validation. If we were to set a `future::plan()`, the folds would be fit in parallel:\n\n```{r cv, warning=FALSE}\nmesh \u003c- make_mesh(pcod, c(\"X\", \"Y\"), cutoff = 10)\n## Set parallel processing if desired:\n# library(future)\n# plan(multisession)\nm_cv \u003c- sdmTMB_cv(\n  density ~ s(depth, k = 5),\n  data = pcod, mesh = mesh,\n  family = tweedie(link = \"log\"), k_folds = 2\n)\n# Sum of log likelihoods of left-out data:\nm_cv$sum_loglik\n```\n\nSee [`?sdmTMB_cv`](https://pbs-assess.github.io/sdmTMB/reference/sdmTMB_cv.html) for more details.\n\n### Priors\n\nPriors/penalties can be placed on most parameters. For example, here we place a PC (penalized complexity) prior on the Matérn random field parameters, a standard normal prior on the effect of depth, a Normal(0, 10^2) prior on the intercept, and a half-normal prior on the Tweedie dispersion parameter (`phi`):\n\n```{r priors}\nmesh \u003c- make_mesh(pcod, c(\"X\", \"Y\"), cutoff = 10)\nfit \u003c- sdmTMB(\n  density ~ depth_scaled,\n  data = pcod, mesh = mesh,\n  family = tweedie(),\n  priors = sdmTMBpriors(\n    matern_s = pc_matern(range_gt = 10, sigma_lt = 5),\n    b = normal(c(0, 0), c(1, 10)),\n    phi = halfnormal(0, 15)\n  )\n)\n```\n\nWe can visualize the PC Matérn prior:\n\n```{r plot-pc-matern}\nplot_pc_matern(range_gt = 10, sigma_lt = 5)\n```\n\nSee [`?sdmTMBpriors`](https://pbs-assess.github.io/sdmTMB/reference/priors.html) for more details.\n\n### Bayesian MCMC sampling with Stan\n\nThe fitted model can be passed to the tmbstan package to sample from the posterior with Stan. See the [Bayesian vignette](https://pbs-assess.github.io/sdmTMB/articles/bayesian.html).\n\n### Turning off random fields\n\nWe can turn off the random fields for model comparison:\n\n```{r no-rf, warning=FALSE, message=FALSE}\nfit_sdmTMB \u003c- sdmTMB(\n  present ~ poly(depth_scaled, 2),\n  data = pcod, mesh = mesh,\n  spatial = \"off\",\n  family = binomial()\n)\nfit_glm \u003c- glm(\n  present ~ poly(depth_scaled, 2),\n  data = pcod,\n  family = binomial()\n)\n\ntidy(fit_sdmTMB)\nbroom::tidy(fit_glm)\n```\n\n### Using a custom fmesher mesh\n\nDefining a mesh directly with INLA:\n\n```{r inla-mesh, warning=FALSE, fig.asp = 1, dpi = 40, out.width = \"30%\"}\nbnd \u003c- INLA::inla.nonconvex.hull(cbind(pcod$X, pcod$Y), convex = -0.1)\nmesh_inla \u003c- INLA::inla.mesh.2d(\n  boundary = bnd,\n  max.edge = c(25, 50)\n)\nmesh \u003c- make_mesh(pcod, c(\"X\", \"Y\"), mesh = mesh_inla)\nplot(mesh)\n```\n\n```{r inla-mesh2, eval=FALSE}\nfit \u003c- sdmTMB(\n  density ~ s(depth, k = 5),\n  data = pcod, mesh = mesh,\n  family = tweedie(link = \"log\")\n)\n```\n\n### Barrier meshes\n\nA barrier mesh limits correlation across barriers (e.g., land or water). See `add_barrier_mesh()` in [sdmTMBextra](https://github.com/pbs-assess/sdmTMBextra).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpbs-assess%2FsdmTMB","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fpbs-assess%2FsdmTMB","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpbs-assess%2FsdmTMB/lists"}