Lesson 5 - The dark art of debugging code
14 December 2023
styler
browser()
Grace Hopper and the origins of bugs and debugging
Link to the Tidyverse style guide
Why coding style matters
f = function(pars) { getAll(data, pars); Linfmn = exp(logLinfmn); logLinfsd = exp(loglogLinfsd); Linfs = exp(logLinfs); K = exp(logK ); Sig = exp(logSig); nponds = length(Linfs); nages = length(A); predL = matrix(0, nrow = nages, ncol = nponds); # fill one column (pond) at a time: for (i in 1:nponds) { predL[, i] = Linfs[i] * (1 - exp(-K * (A - t0)));} nll = -sum(dnorm(x = L, mean = predL, sd = Sig, log = TRUE)); nprand = -sum(dnorm(x = logLinfs, mean = logLinfmn, sd = logLinfsd, log = TRUE)); jnll = nll + nprand; jnll; }
styler()
f <- function(pars) { getAll(data, pars) Linfmn <- exp(logLinfmn) logLinfsd <- exp(loglogLinfsd) Linfs <- exp(logLinfs) K <- exp(logK) Sig <- exp(logSig) nponds <- length(Linfs) nages <- length(A) predL <- matrix(0, nrow = nages, ncol = nponds) # fill one column (pond) at a time: for (i in 1:nponds) { predL[, i] <- Linfs[i] * (1 - exp(-K * (A - t0))) } nll <- -sum(dnorm(x = L, mean = predL, sd = Sig, log = TRUE)) nprand <- -sum(dnorm(x = logLinfs, mean = logLinfmn, sd = logLinfsd, log = TRUE)) jnll <- nll + nprand jnll }
βDebugging is like being the detective in a crime movie where you are also the murderer.β - Filipe Fortes
packageVersion("RTMB")
[1] '1.7'
sessionInfo()
R version 4.5.0 (2025-04-11 ucrt) Platform: x86_64-w64-mingw32/x64 Running under: Windows 11 x64 (build 26100) Matrix products: default LAPACK version 3.12.0 locale: [1] LC_COLLATE=English_United States.utf8 [2] LC_CTYPE=English_United States.utf8 [3] LC_MONETARY=English_United States.utf8 [4] LC_NUMERIC=C [5] LC_TIME=English_United States.utf8 time zone: America/New_York tzcode source: internal attached base packages: [1] stats graphics grDevices utils datasets methods base loaded via a namespace (and not attached): [1] compiler_4.5.0 fastmap_1.2.0 cli_3.6.4 tools_4.5.0 [5] htmltools_0.5.8.1 rstudioapi_0.17.1 yaml_2.3.10 rmarkdown_2.29 [9] knitr_1.50 jsonlite_2.0.0 xfun_0.52 digest_0.6.37 [13] rlang_1.1.6 evaluate_1.0.3
Wikipedia link to Shotgun Debugging
Useful article on debugging tools in RStudio
Image reference
Wikipedia link on the consistency property of the Maximum Likelihood Estimator
Kasper Kristensen, Anders Nielsen, Casper W. Berg, Hans Skaug, Bradley M. Bell. 2016. TMB: Automatic Differentiation and Laplace Approximation. Journal of Statistical Software, 70(5), 1-21. doi:10.18637/jss.v070.i05
Kristensen K. 2023. RTMB: R Bindings for TMB. R package version 1.0, https://github.com/kaskr/RTMB