Impaired spatial coding and neuronal hyperactivity in the medial entorhinal cortex of aged APP knock-in mice.
The 2 matches
- [1] § STAR★METHODS › QUANTIFICATION AND STATISTICAL ANALYSIS ↔ DHARMa/R/tests.R, lines 402–520 · score 0.53 · zero inflation, glmmTMB, outliers, Pearson, nonparametric, ratios
- [2] § STAR★METHODS › QUANTIFICATION AND STATISTICAL ANALYSIS ↔ glmmTMB/R/diagnose.R, lines 1–35 · score 0.51 · zero inflation, Diagnostic, glmmTMB, logit, coefficients, ratios
Paper
Loaded from Europe PMC by your browser, not stored by OSCR: doi.org · Europe PMC
The paper is loaded when this pane is shown.
The authors' code
R · 903 lines · 56 KB · gnu · 1 match
- #' DHARMa general residual test
- #'
- #' Calls uniformity, dispersion and outliers tests.
- #'
- #' This function is a wrapper for the various test functions implemented in DHARMa. Currently, this function calls the functions [testUniformity], [testDispersion], and [testOutliers]. All other tests (see list below) have to be called by hand.
- #'
- #' @param simulationOutput an object of class DHARMa, either created via [simulateResiduals] for supported models or by [createDHARMa] for simulations created outside DHARMa, or a supported model. Providing a supported model directly is discouraged, because simulation settings cannot be changed in this case.
- #' @param plot if TRUE, plot functions of the tests are called.
- #' @author Florian Hartig
- #' @seealso [testResiduals], [testUniformity], [testOutliers], [testDispersion], [testZeroInflation], [testGeneric], [testTemporalAutocorrelation], [testSpatialAutocorrelation], [testQuantiles], [testCategorical]
- #' @example inst/examples/testsHelp.R
- #' @export
- testResiduals <- function(simulationOutput, plot = TRUE){
- opar = par(mfrow = c(1,3))
- on.exit(par(opar))
- out = list()
- out$uniformity = testUniformity(simulationOutput, plot = plot)
- out$dispersion = testDispersion(simulationOutput, plot = plot)
- out$outliers = testOutliers(simulationOutput, plot = plot)
- #print(out) # do we need it?
- return(out)
- }
- #' Residual tests
- #'
- #' @details Deprecated, switch your code to using the [testResiduals] function
- #'
- #' @param simulationOutput an object of class DHARMa, either created via [simulateResiduals] for supported models or by [createDHARMa] for simulations created outside DHARMa, or a supported model. Providing a supported model directly is discouraged, because simulation settings cannot be changed in this case.
- #' @author Florian Hartig
- #' @export
- testSimulatedResiduals <- function(simulationOutput){
- message("testSimulatedResiduals is deprecated, switch your code to using the testResiduals function")
- testResiduals(simulationOutput)
- }
- #' Test for overall uniformity
- #'
- #' This function tests the overall uniformity of the simulated residuals in a DHARMa object.
- #'
- #' @param simulationOutput an object of class DHARMa, either created via [simulateResiduals] for supported models or by [createDHARMa] for simulations created outside DHARMa, or a supported model. Providing a supported model directly is discouraged, because simulation settings cannot be changed in this case.
- #' @param alternative a character string specifying whether the test should test if observations are "greater", "less" or "two.sided" compared to the simulated null hypothesis. See [stats::ks.test] for details.
- #' @param plot if TRUE, plots calls [plotQQunif] as well.
- #' @details The function applies a [stats::ks.test] for uniformity on the simulated residuals.
- #' @author Florian Hartig
- #' @seealso [testResiduals], [testUniformity], [testOutliers], [testDispersion], [testZeroInflation], [testGeneric], [testTemporalAutocorrelation], [testSpatialAutocorrelation], [testQuantiles], [testCategorical]
- #' @example inst/examples/testsHelp.R
- #' @export
- testUniformity <- function(simulationOutput, alternative = c("two.sided", "less", "greater"), plot = TRUE){
- simulationOutput = ensureDHARMa(simulationOutput, convert = T)
- out <- suppressWarnings(ks.test(simulationOutput$scaledResiduals, 'punif', alternative = alternative))
- if(plot == T) plotQQunif(simulationOutput = simulationOutput)
- return(out)
- }
- # Experimental
- testBivariateUniformity <- function(simulationOutput, alternative = c("two.sided", "less", "greater"), plot = TRUE){
- simulationOutput = ensureDHARMa(simulationOutput, convert = T)
- #out <- suppressWarnings(ks.test(simulationOutput$scaledResiduals, 'punif', alternative = alternative))
- #if(plot == T) plotQQunif(simulationOutput = simulationOutput)
- out = NULL
- return(out)
- }
- #' Test for quantiles
- #'
- #' This function fits quantile regressions on the residuals, and compares their location to the expected location.
- #'
- #' @param simulationOutput an object of class DHARMa, either created via [simulateResiduals] for supported models or by [createDHARMa] for simulations created outside DHARMa, or a supported model. Providing a supported model directly is discouraged, because simulation settings cannot be changed in this case.
- #' @param predictor an optional predictor variable to be used, instead of the predicted response (default). See details.
- #' @param rank if TRUE, the values provided in predictor will be rank transformed. This will usually make patterns easier to spot visually, especially if the distribution of the predictor is skewed. If form is a factor, this has no effect.
- #' @param quantiles the quantiles to be tested.
- #' @param plot if TRUE, the function will create an additional plot.
- #' @details The function fits quantile regressions (via package qgam) on the residuals, and compares their location to the expected location (because of the uniform distribution, the expected location is 0.5 for the 0.5 quantile).
- #'
- #' A significant p-value for the splines means the fitted spline deviates from a flat line at the expected location.
- #'
- #' The p-values of the intercept and splines are combined into a total p-value via Benjamini & Hochberg adjustment to control the FDR.
- #'
- #' Predictor can be a formula (e.g. predictor = ~predictor), in which case NAs are handled automatically (recommended). Predictor can also be a variable in your environment (e.g. predictor = data$predictor), but then you need to remove rows that were excluded by the model due to NAs by hand. For more details and a more flexible syntax for predictors, see the help of the argument `form` in [plotResiduals].
- #'
- #' When plotting (plot = TRUE), the shaded gray areas indicate 95% confidence intervals of the quantile estimates (1.96 * standard error).
- #'
- #' @author Florian Hartig
- #' @example inst/examples/testQuantilesHelp.R
- #' @seealso [testResiduals], [testUniformity], [testOutliers], [testDispersion], [testZeroInflation], [testGeneric], [testTemporalAutocorrelation], [testSpatialAutocorrelation], [testQuantiles], [testCategorical]
- #' @export
- testQuantiles <- function(simulationOutput, predictor = NULL, rank = TRUE,
- quantiles = c(0.25,0.5,0.75), plot = TRUE){
- if(plot == F){
- out = list()
- out$data.name = deparse(substitute(simulationOutput))
- simulationOutput = ensureDHARMa(simulationOutput, convert = T)
- res = simulationOutput$scaledResiduals
- if(inherits(predictor, "formula")) predictor = getFormulaPredictors(simulationOutput, predictor)[[1]]
- pred = ensurePredictor(simulationOutput, predictor)
- if (rank == TRUE) pred = rankTransform(pred)
- dat = data.frame(res = simulationOutput$scaledResiduals, pred = pred)
- quantileFits <- list()
- pval = rep(NA, length(quantiles))
- predictions = data.frame(pred = sort(dat$pred))
- predictions = cbind(predictions, matrix(ncol = 2 * length(quantiles),
- nrow = nrow(dat)))
- for(i in 1:length(quantiles)){
- datTemp = dat
- datTemp$res = datTemp$res - quantiles[i]
- # settings for k = the dimension of the basis used to represent the smooth term.
- # see https://github.com/mfasiolo/qgam/issues/37
- dimSmooth = min(length(unique(datTemp$pred)), 10)
- quantResult = try(capture.output(quantileFits[[i]] <-
- qgam::qgam(res ~ s(pred, k = dimSmooth),
- data = datTemp,
- qu = quantiles[i])), silent = T)
- if(inherits(quantResult, "try-error")){
- message("\n DHARMa: qgam was unable to calculate quantile regression for quantile ",
- quantiles[i], ". Possibly too few (unique) data points / predictions. The quantile will be ommited in plots and significance calculations. \n")
- } else {
- x = summary(quantileFits[[i]])
- pval[i] = min(p.adjust(c(x$p.table[1,4], x$s.table[1,4]), method = "BH")) # correction for test on slope and intercept
- quantPre = predict(quantileFits[[i]], newdata = predictions, se = T)
- predictions[, 2*i] = quantPre$fit + quantiles[i]
- predictions[, 2*i + 1] = 1.96*quantPre$se.fit
- }
- }
- out$method = "Test for location of quantiles via qgam"
- out$alternative = "both"
- out$pvals = pval
- out$p.value = min(p.adjust(pval, method = "BH")) # correction for multiple quantile tests
- out$predictions = predictions
- out$qgamFits = quantileFits
- class(out) = "htest"
- } else if(plot == T) {
- if(is.null(predictor)) {
- out <- plotResiduals(simulationOutput = simulationOutput, form = NULL,
- rank = rank, quantiles = quantiles, quantreg = TRUE)
- } else {
- out <- plotResiduals(simulationOutput = simulationOutput, form = predictor,
- rank = rank, quantiles = quantiles, quantreg = TRUE)
- }
- }
- return(out)
- }
- #unif.2017YMi(X, type = c("Q1", "Q2", "Q3"), lower = rep(0, ncol(X)),upper = rep(1, ncol(X)))
- #' Test for outliers
- #'
- #' This function tests if the number of observations outside the simulation envelope are larger or smaller than expected
- #'
- #' @param simulationOutput an object of class DHARMa, either created via [simulateResiduals] for supported models or by [createDHARMa] for simulations created outside DHARMa, or a supported model. Providing a supported model directly is discouraged, because simulation settings cannot be changed in this case.
- #' @param alternative a character string specifying whether the test should test if observations are "greater", "less" or "two.sided" (default) compared to the simulated null hypothesis.
- #' @param margin whether to test for outliers only at the lower, only at the upper, or both sides (default) of the simulated data distribution.
- #' @param type either default, bootstrap or binomial. See details.
- #' @param nBoot number of bootstrap replicates. Only used at type = "bootstrap".
- #' @param plot if TRUE, the function will create an additional plot.
- #' @param plotBoostrap if plot should be produced of outlier frequencies calculated under the bootstrap.
- #' @details DHARMa residuals are created by simulating from the fitted model, and comparing the simulated values to the observed data. It can occur that all simulated values are higher or smaller than the observed data, in which case they get the residual value of 0 and 1, respectively. I refer to these values as simulation outliers, or simply outliers.
- #'
- #' Because no data was simulated in the range of the observed values, we don't know "how strongly" these values deviate from the model expectation, so the term "outlier" should be used with a grain of salt. It is not a judgment about the magnitude of the residual deviation, but simply a dichotomous sign that we are outside the simulated range. Moreover, the number of outliers will decrease as we increase the number of simulations.
- #'
- #' To test if the outliers are a concern, testOutliers implements 2 options (bootstrap, binomial), which can be chosen via the parameter "type". The third option (default) chooses bootstrap for integer-valued distributions with nObs < 500, and else binomial.
- #'
- #' The binomial test considers that under the null hypothesis that the model is correct, and for continuous distributions (i.e. data and the model distribution are identical and continuous), the probability that a given observation is higher than all simulations is 1/(nSim +1), and binomial distributed. The testOutlier function can test this null hypothesis via type = "binomial". In principle, it would be nice if we could extend this idea to integer-valued distributions, which are randomized via the PIT procedure (see [simulateResiduals]); the rate of "true" outliers is more difficult to calculate, and in general not 1/(nSim +1). The testOutlier function implements a small tweak that calculates the rate of residuals that are closer than 1/(nSim+1) to the 0/1 border, which roughly occur at a rate of nData /(nSim +1). This approximate value, however, is generally not exact, and may be particularly off non-bounded integer-valued distributions (such as Poisson or Negative Binomial).
- #'
- #' For this reason, the testOutlier function implements an alternative procedure that uses the bootstrap to generate a simulation-based expectation for the outliers. It is recommended to use the bootstrap for integer-valued distributions (and integer-valued only, because it has no advantage for continuous distributions, ideally with reasonably high values of nSim and nBoot (I recommend at least 1000 for both)). Because of the high runtime, however, this option is switched off for type = default when nObs > 500.
- #'
- #' Both binomial and bootstrap generate a null expectation, and then test for an excess or lack of outliers. Per default, testOutliers() looks for both, so if you get a significant p-value, you have to check if you have too many or too few outliers. An excess of outliers is to be interpreted as too many values outside the simulation envelope. This could be caused by overdispersion, or by what we classically call outliers. A lack of outliers would be caused, for example, by underdispersion.
- #'
- #'
- #' @author Florian Hartig
- #' @seealso [testResiduals], [testUniformity], [testOutliers], [testDispersion], [testZeroInflation], [testGeneric], [testTemporalAutocorrelation], [testSpatialAutocorrelation], [testQuantiles], [testCategorical]
- #' @export
- testOutliers <- function(simulationOutput, alternative = c("two.sided", "greater", "less"), margin = c("both", "upper", "lower"), type = c("default","bootstrap", "binomial"), nBoot = 100, plot = TRUE, plotBoostrap = FALSE){
- # check inputs
- alternative = match.arg(alternative)
- margin = match.arg(margin)
- type = match.arg(type)
- data.name = deparse(substitute(simulationOutput)) # remember: needs to be called before ensureDHARMa
- simulationOutput = ensureDHARMa(simulationOutput, convert = "Model")
- if(type == "default"){
- if(simulationOutput$integerResponse == FALSE) type = "binomial"
- else{
- if(simulationOutput$nObs > 500) type = "binomial"
- else type = "bootstrap"
- }
- }
- # using the binomial test, not exact
- if(type == "binomial"){
- # calculation of outliers
- if(margin == "both") outliers = sum(simulationOutput$scaledResiduals < (1/(simulationOutput$nSim+1))) + sum(simulationOutput$scaledResiduals > (1-1/(simulationOutput$nSim+1)))
- if(margin == "upper") outliers = sum(simulationOutput$scaledResiduals > (1-1/(simulationOutput$nSim+1)))
- if(margin == "lower") outliers = sum(simulationOutput$scaledResiduals < (1/(simulationOutput$nSim+1)))
- # calculations of trials and H0
- outFreqH0 = 1/(simulationOutput$nSim +1) * ifelse(margin == "both", 2, 1)
- trials = simulationOutput$nObs
- out = binom.test(outliers, trials, p = outFreqH0, alternative = alternative)
- # overwrite information in binom.test
- out$method = "DHARMa outlier test based on exact binomial test with approximate expectations"
- out$data.name = data.name
- out$margin = margin
- names(out$statistic) = paste("outliers at", margin, "margin(s)")
- names(out$parameter) = "observations"
- names(out$estimate) = paste("frequency of outliers (expected:", out$null.value,")")
- if (simulationOutput$integerResponse == T & out$p.value < 0.05) message("DHARMa:testOutliers with type = binomial may have inflated Type I error rates for integer-valued distributions. To get a more exact result, it is recommended to re-run testOutliers with type = 'bootstrap'. See ?testOutliers for details")
- if(plot == T) {
- hist(simulationOutput, main = "")
- main = ifelse(out$p.value <= 0.05,
- "Outlier test significant",
- "Outlier test n.s.")
- title(main = main, cex.main = 1,
- col.main = ifelse(out$p.value <= 0.05, "red", "black"))
- }
- } else {
- if(margin == "both") outliers = mean(simulationOutput$scaledResiduals == 0) +
- mean(simulationOutput$scaledResiduals == 1)
- if(margin == "upper") outliers = mean(simulationOutput$scaledResiduals == 1)
- if(margin == "lower") outliers = mean(simulationOutput$scaledResiduals == 0)
- # Bootstrapping to compare to expected
- simIndices = 1:simulationOutput$nSim
- nSim = simulationOutput$nSim
- if(simulationOutput$refit == T){
- simResp = simulationOutput$refittedResiduals
- } else {
- simResp = simulationOutput$simulatedResponse
- }
- resMethod = simulationOutput$method
- resInteger = simulationOutput$integerResponse
- if (nBoot > nSim){
- message("DHARMa::testOutliers: nBoot > nSim does not make much sense, thus changed to nBoot = nSim. If you want to increase nBoot, increase nSim in DHARMa::simulateResiduals as well.")
- nBoot = nSim
- }
- frequBoot <- rep(NA, nBoot)
- for (i in 1:nBoot){
- #sel = -i
- sel = sample(simIndices[-i], size = nSim, replace = T)
- residuals <- getQuantile(simulations = simResp[,sel],
- observed = simResp[,i],
- integerResponse = resInteger,
- method = resMethod)
- if(margin == "both") frequBoot[i] = mean(residuals == 1) + mean(residuals == 0)
- else if(margin == "upper") frequBoot[i] = mean(residuals == 1)
- else if(margin == "lower") frequBoot[i] = mean(residuals == 0)
- }
- out = list()
- class(out) = "htest"
- out$alternative = alternative
- out$p.value = getP(frequBoot, outliers, alternative = alternative)
- out$conf.int = quantile(frequBoot, c(0.025, 0.975))
- out$data.name = data.name
- out$margin = margin
- out$method = "DHARMa bootstrapped outlier test"
- out$statistic = outliers * simulationOutput$nObs
- names(out$statistic) = paste("outliers at", margin, "margin(s)")
- out$parameter = simulationOutput$nObs
- names(out$parameter) = "observations"
- out$estimate = outliers
- names(out$estimate) = paste("outlier frequency (expected:", mean(frequBoot),")")
- if(plotBoostrap == T){
- hist(frequBoot, xlim = range(frequBoot, outliers), col = "lightgrey", main = "Bootstrapped outlier frequency")
- abline(v = mean(frequBoot), col = 1, lwd = 2)
- abline(v = outliers, col = "red", lwd = 2)
- # legend("center", c(paste("p=", round(out$p.value, digits = 5)), paste("Deviation ", ifelse(out$p.value < 0.05, "significant", "n.s."))), text.col = ifelse(out$p.value < 0.05, "red", "black" ))
- }
- if(plot == T) {
- hist(simulationOutput, main = "")
- main = ifelse(out$p.value <= 0.05,
- "Outlier test significant",
- "Outlier test n.s.")
- title(main = main, cex.main = 1,
- col.main = ifelse(out$p.value <= 0.05, "red", "black"))
- }
- }
- return(out)
- }
- #' Test for categorical dependencies
- #'
- #' This function tests if there are problems in a res ~ group structure. It performs two tests: test for within-group uniformity, and test for between-group homogeneity of variances.
- #'
- #' @param simulationOutput an object of class DHARMa, either created via [simulateResiduals] for supported models or by [createDHARMa] for simulations created outside DHARMa, or a supported model. Providing a supported model directly is discouraged, because simulation settings cannot be changed in this case.
- #' @param catPred a categorical predictor with the same dimensions as the residuals in simulationOutput. If specified as formula, e.g. catPred = ~group, NAs are handled automatically (recommended).
- #' @param quantiles whether to draw the quantile lines.
- #' @param plot if TRUE, the function will create an additional plot.
- #' @param ... additional arguments to boxplot.
- #' @details The function tests for two common problems: are residuals within each group distributed according to model assumptions, and is the variance between groups heterogeneous.
- #'
- #' The test for within-group uniformity is performed via multiple KS-tests, with adjustment of p-values for multiple testing. If the plot is drawn, problematic groups are highlighted in red, and a corresponding message is displayed in the plot.
- #'
- #' The test for homogeneity of variances is done with a Levene test. A significant p-value means that group variances are not constant. In this case, you should consider modelling variances, e.g. via ~dispformula in glmmTMB.
- #'
- #' @author Florian Hartig
- #' @seealso [testResiduals], [testUniformity], [testOutliers], [testDispersion], [testZeroInflation], [testGeneric], [testTemporalAutocorrelation], [testSpatialAutocorrelation], [testQuantiles], [testCategorical]
- #' @example inst/examples/testsHelp.R
- #' @export
- testCategorical <- function(simulationOutput, catPred,
- quantiles = c(0.25, 0.5, 0.75), plot = TRUE, ...){
- simulationOutput = ensureDHARMa(simulationOutput, convert = T)
- a = list(...)
- a$xlab = paste(checkDots("xlab", deparse(substitute(catPred)), ...), "(catPred)")
- if(!inherits(catPred, "formula")) {
- catPred = catPred # old default
- } else {
- catPred = getFormulaPredictors(simulationOutput, formula = catPred)[[1]] # formula syntax
- }
- catPred = as.factor(catPred)
- out = list()
- out$uniformity$details = suppressWarnings(by(simulationOutput$scaledResiduals,
- catPred, ks.test, 'punif',
- simplify = TRUE))
- out$uniformity$p.value = rep(NA, nlevels(catPred))
- for(i in 1:nlevels(catPred)) out$uniformity$p.value[i] = out$uniformity$details[[i]]$p.value
- out$uniformity$p.value.cor = p.adjust(out$uniformity$p.value)
- if(nlevels(catPred) > 1) out$homogeneity = leveneTest_formula(simulationOutput$scaledResiduals ~ catPred)
- if(plot == T){
- boxplot(simulationOutput$scaledResiduals ~ catPred, ylim = c(0,1), xlab = a$xlab, axes = FALSE, col = ifelse(out$uniformity$p.value.cor < 0.05, "red", "lightgrey"))
- axis(1, at = 1:nlevels(catPred), levels(catPred))
- axis(2, at=c(0, quantiles, 1))
- abline(h = quantiles, lty = 2)
- }
- title(ifelse(any(out$uniformity$p.value.cor < 0.05), "Within-group deviations from uniformity significant (red)", "Within-group deviation from uniformity n.s."),
- col.main = ifelse(any(out$uniformity$p.value.cor < 0.05), "red", "black"),
- line = 1, cex.main = 0.8)
- if(length(out) > 1) {
- title(ifelse(out$homogeneity$`Pr(>F)`[1] < 0.05, "Levene Test for homogeneity of variance significant", "Levene Test for homogeneity of variance n.s."),
- col.main = ifelse(out$homogeneity$`Pr(>F)`[1] < 0.05, "red", "black"), cex.main = 0.8)
- }
- return(out)
- }
- #' DHARMa dispersion tests
- #'
- #' This function performs simulation-based tests for over / underdispersion. If type = "DHARMa" (default and recommended), simulation-based dispersion tests are performed. Their behavior differs depending on whether simulations are done with refit = F, or refit = T, and whether data is simulated conditional (see below). If type = "PearsonChisq", a chi2 test on Pearson residuals is performed.
- #'
- #' @param simulationOutput an object of class DHARMa, either created via [simulateResiduals] for supported models or by [createDHARMa] for simulations created outside DHARMa, or a supported model. Providing a supported model directly is discouraged, because simulation settings cannot be changed in this case.
- #' @param alternative a character string specifying whether the test should test if observations are "greater", "less" or "two.sided" compared to the simulated null hypothesis. Greater corresponds to testing only for overdispersion. It is recommended to keep the default setting (testing for both over and underdispersion).
- #' @param plot whether to provide a plot for the results.
- #' @param type which test to run. Default is DHARMa, other options are PearsonChisq (see details).
- #' @param ... arguments to pass on to [testGeneric].
- #'
- #' @details Over / underdispersion means that the observed data is more / less dispersed than expected under the fitted model. There is no unique way to test for dispersion problems, and there are a number of different dispersion tests implemented in various R packages. For detailed recommendations see also Leite M.S., Rettelbach, D. and Hartig, F. (2025), preprint available at https://doi.org/10.32942/X23M14.
- #'
- #' The testDispersion function implements several dispersion tests:
- #'
- #' **Simulation-based dispersion tests (type == "DHARMa")**
- #'
- #' If type = "DHARMa" (default and recommended), simulation-based dispersion tests are performed. Their behavior differs depending on whether simulations are done with refit = F, or refit = T.
- #'
- #' **Important:** for either refit = T or F, the results of type = "DHARMa" dispersion test will differ depending on whether simulations are done conditional (= conditional on fitted random effects) or unconditional (= REs are re-simulated). The default as of DHARMa 0.5.0 is conditional simulations, which substantially increase the power and sensitivity of the dispersion test (for details see [simulateResiduals] and the DHARMa vignette).
- #'
- #' If refit = F, the function uses [testGeneric] to compare the variance of the observed raw residuals (i.e. var(observed - predicted), displayed as a red line) against the variance of the simulated residuals (i.e. var(simulated - predicted), histogram). The variances are scaled to the mean simulated variance. A significant ratio > 1 indicates overdispersion, a significant ratio < 1 underdispersion.
- #'
- #' If refit = T, the function compares the approximate deviance (via squared Pearson residuals) with the same quantity from the models refitted with simulated data. Applying this is much slower than the previous alternative. Given the computational cost, I would suggest that most users will be satisfied with the standard dispersion test.
- #'
- #' **Analytical dispersion tests (type == "PearsonChisq")**
- #'
- #' This is the test described in https://bbolker.github.io/mixedmodels-misc/glmmFAQ.html#overdispersion, identical to performance::check_overdispersion. Works only if the fitted model provides df.residual and Pearson residuals.
- #'
- #' The test statistic is biased to lower values under quite general conditions, and will therefore tend to test significant for underdispersion. It is recommended to use this test only for overdispersion, i.e. use alternative == "greater". Also, obviously, it requires that Pearson residuals are available for the chosen model, which will not be the case for all models / packages.
- #'
- #' @note For particular model classes / situations, there may be more powerful and thus preferable options over the DHARMa test. The advantage of the DHARMa test is that it directly targets the spread of the data (unlike other tests such as dispersion/df, which essentially measure fit and may thus be triggered by problems other than dispersion as well), and it makes practically no assumptions about the fitted model, other than the availability of simulations.
- #'
- #' @author Florian Hartig
- #' @references Leite, MS, Rettelbach, D. & Hartig, F. 2025. Dispersion tests in generalised linear mixed-effects models - a methods comparison and practical guide. EcoEvoRxiv Preprint: https://doi.org/10.32942/X23M14.
- #' @seealso [testResiduals], [testUniformity], [testOutliers], [testDispersion], [testZeroInflation], [testGeneric], [testTemporalAutocorrelation], [testSpatialAutocorrelation], [testQuantiles], [testCategorical]
- #' @example inst/examples/testDispersionHelp.R
- #' @export
- testDispersion <- function(simulationOutput, alternative = c("two.sided", "greater", "less"), plot = T, type = c("DHARMa", "PearsonChisq"), ...){
- alternative <- match.arg(alternative)
- type <- match.arg(type)
- out = list()
- out$data.name = deparse(substitute(simulationOutput))
- if(type == "DHARMa"){
- simulationOutput = ensureDHARMa(simulationOutput, convert = "Model")
- if(simulationOutput$refit == F){
- expectedVar = sd(simulationOutput$simulatedResponse)^2
- spread <- function(x) var(x - simulationOutput$fittedPredictedResponse) / expectedVar
- out = testGeneric(simulationOutput, summary = spread, alternative = alternative, methodName = "DHARMa nonparametric dispersion test via sd of residuals fitted vs. simulated", plot = plot, ...)
- names(out$statistic) = "dispersion"
- } else {
- rp <- getPearsonResiduals(simulationOutput$fittedModel)
- observed = sum(rp^2)
- expected = apply(simulationOutput$refittedPearsonResiduals^2 , 2, sum)
- out$statistic = c(dispersion = observed / mean(expected))
- names(out$statistic) = "dispersion"
- out$method = "DHARMa nonparametric dispersion test via mean deviance residual fitted vs. simulated-refitted"
- p = getP(simulated = expected, observed = observed, alternative = alternative)
- out$alternative = alternative
- out$p.value = p
- class(out) = "htest"
- if(plot == T) {
- #plotTitle = gsub('(.{1,50})(\\s|$)', '\\1\n', out$method)
- xLabel = paste("Simulated values, red line = fitted model. p-value (",out$alternative, ") = ", out$p.value, sep ="")
- hist(expected, xlim = range(expected, observed, na.rm=T ), col = "lightgrey", main = "", xlab = xLabel, breaks = 20, cex.main = 1)
- abline(v = observed, lwd= 2, col = "red")
- main = ifelse(out$p.value <= 0.05,
- "Dispersion test significant",
- "Dispersion test n.s.")
- title(main = main, cex.main = 1,
- col.main = ifelse(out$p.value <= 0.05, "red", "black"))
- }
- }
- } else if(type == "PearsonChisq"){
- if("DHARMa" %in% class(simulationOutput)){
- model = simulationOutput$fittedModel
- }
- else model = simulationOutput
- if(!alternative == "greater" & class(model)[1] %in% c("lmerMod", "lmerModLmerTest", "glmerMod", "bam", "glmmTMB", "HLfit", "MixMod")) {
- message("Note that the Chi2 test on Pearson residuals is biased for MIXED models towards underdispersion. Tests with alternative = two.sided or less are therefore not reliable. If you have random effects in your model, we recommend to test only with alternative = 'greater', i.e. test for overdispersion, or else use the DHARMa default tests which are unbiased. See help for details.")}
- rp <- getPearsonResiduals(model)
- rdf <- df.residual(model)
- Pearson.chisq <- sum(rp^2)
- prat <- Pearson.chisq/rdf
- if(alternative == "greater") pval <- pchisq(Pearson.chisq, df=rdf, lower.tail=FALSE)
- else if (alternative == "less") pval <- pchisq(Pearson.chisq, df=rdf, lower.tail=TRUE)
- else if (alternative == "two.sided") pval <- min(min(pchisq(Pearson.chisq, df=rdf, lower.tail=TRUE), pchisq(Pearson.chisq, df=rdf, lower.tail=FALSE)) * 2,1)
- out$statistic = prat
- names(out$statistic) = "dispersion"
- out$parameter = rdf
- names(out$parameter) = "df"
- out$method = "Parametric dispersion test via mean Pearson-chisq statistic"
- out$alternative = alternative
- out$p.value = pval
- class(out) = "htest"
- # c(chisq=Pearson.chisq,ratio=prat,rdf=rdf,p=pval)
- return(out)
- }
- return(out)
- }
- #' Simulated overdisperstion tests (deprecated)
- #'
- #' @details Deprecated, switch your code to using the [testDispersion] function
- #'
- #' @param simulationOutput an object of class DHARMa with simulated quantile residuals, either created via [simulateResiduals] or by [createDHARMa] for simulations created outside DHARMa
- #' @param ... additional arguments to [testDispersion]
- #' @export
- testOverdispersion <- function(simulationOutput, ...){
- message("testOverdispersion is deprecated, switch your code to using the testDispersion function")
- testDispersion(simulationOutput, ...)
- }
- #' Parametric overdisperstion tests (deprecated)
- #'
- #' @details Deprecated, switch your code to using the [testDispersion] function.
- #'
- #' @param ... arguments will be ignored, the parametric tests is no longer recommend
- #' @export
- testOverdispersionParametric <- function(...){
- message("testOverdispersionParametric is deprecated - switch your code to using the testDispersion function")
- return(0)
- }
- #' Tests for zero-inflation
- #'
- #' This function compares the observed number of zeros with the zeros expected from simulations.
- #'
- #' @param simulationOutput an object of class DHARMa, either created via [simulateResiduals] for supported models or by [createDHARMa] for simulations created outside DHARMa, or a supported model. Providing a supported model directly is discouraged, because simulation settings cannot be changed in this case.
- #' @param ... further arguments to [testGeneric].
- #' @details Zero-inflation means that the observed data contains more zeros than would be expected under the fitted model. Zero-inflation must always be accessed with respect to a particular model, so the mere fact that there are many zeros in the observed data is not an indication of zero-inflation, see Warton, D. I. (2005). Many zeros does not mean zero inflation: comparing the goodness-of-fit of parametric models to multivariate abundance data. Environmetrics 16(3), 275-289.
- #'
- #' The testZeroInflation function simulates new datasets from the fitted model and compares this null distribution (gray histogram in the plot) with the observed values (red line in the plot). Technically, it is a wrapper for [testGeneric], with the summary argument set to function(x) sum(x == 0). The test statistic is the ratio of observed to simulated zeros. A value < 1 means that the observed data have fewer zeros than expected, a value > 1 means that they have more zeros than expected (aka zero inflation). By default, the function tests both sides, so it would also test for fewer zeros than expected.
- #'
- #' @note Zero-inflation can occur for a number of reasons other than an underlying data generating process corresponding to a ZIP model. Vice versa, it is very well possible that no zero-inflation will be observed when fitting models to data derived from a ZIP process. The latter is due to the fact that excess zeros can often be explained by other model parameters, such as the theta parameter in the negative binomial.
- #'
- #' For this reason, results of the zero-inflation test should be interpreted as a residual pattern that can have many reasons, not as a decision criterion for whether or not to fit a ZIP model. To decide whether to add a ZIP term, I would advise relying on appropriate model selection techniques such as AIC, BIC, WAIC, Bayes factor, or LRT. Note that these tests are often not reliable in GLMMs because it is difficult to determine the df spent by the different models. The [simulateLRT] function in DHARMa provides a nonparametric alternative to obtain p-values for LRTs in nested models with unknown df.
- #'
- #' @author Florian Hartig
- #' @example inst/examples/testsHelp.R
- #' @seealso [testResiduals], [testUniformity], [testOutliers], [testDispersion], [testZeroInflation], [testGeneric], [testTemporalAutocorrelation], [testSpatialAutocorrelation], [testQuantiles], [testCategorical]
- #' @export
- testZeroInflation <- function(simulationOutput, ...){
- countZeros <- function(x) sum( x == 0)
- testGeneric(simulationOutput = simulationOutput, summary = countZeros, methodName = "DHARMa zero-inflation test via comparison to expected zeros with simulation under H0 = fitted model", ... )
- }
- #' Test for a generic summary statistic based on simulated data
- #'
- #' This function tests if a user-defined summary differs when applied to simulated / observed data.
- #'
- #' @param simulationOutput an object of class DHARMa, either created via [simulateResiduals] for supported models or by [createDHARMa] for simulations created outside DHARMa, or a supported model. Providing a supported model directly is discouraged, because simulation settings cannot be changed in this case.
- #' @param summary a function that can be applied to simulated / observed data. See examples below.
- #' @param alternative a character string specifying whether the test should test if observations are "greater", "less" or "two.sided" compared to the simulated null hypothesis.
- #' @param plot whether to plot the simulated summary.
- #' @param methodName name of the test (will be used in plot).
- #'
- #' @details This function applies a user-defined summary to the simulated / observed data of a DHARMa object and then performs a hypothesis test using the ratio Obs / Sim as the test statistic.
- #'
- #' The summary is applied directly to the data and not to the residuals, but it can easily be remodeled to apply summaries to the residuals by simply defining something like f = function(x) summary (x - predictions), as done in [testDispersion].
- #'
- #' @note The summary function you specify will be applied to the data as it appears in your fitted model, which may not always be what you want.
- #'
- #' As an example, consider the case where we want to test for n-inflation in k/n data. If you provide your data via cbind (k, n-k), you have to test for n-inflation, but if you provide your data via k/n and weights = n, you should test for 1-inflation. When in doubt, check how the data is represented internally in model.frame(model) or via simulate(model).
- #'
- #' @export
- #' @author Florian Hartig
- #' @example inst/examples/testsHelp.R
- #' @seealso [testResiduals], [testUniformity], [testOutliers], [testDispersion], [testZeroInflation], [testGeneric], [testTemporalAutocorrelation], [testSpatialAutocorrelation], [testQuantiles], [testCategorical]
- testGeneric <- function(simulationOutput, summary, alternative = c("two.sided", "greater", "less"), plot = T, methodName = "DHARMa generic simulation test"){
- out = list()
- out$data.name = deparse(substitute(simulationOutput))
- simulationOutput = ensureDHARMa(simulationOutput, convert = "Model")
- alternative <- match.arg(alternative)
- observed = summary(simulationOutput$observedResponse)
- simulated = apply(simulationOutput$simulatedResponse, 2, summary)
- p = getP(simulated = simulated, observed = observed, alternative = alternative)
- out$statistic = c(ratioObsSim = observed / mean(simulated))
- out$method = methodName
- out$alternative = alternative
- out$p.value = p
- class(out) = "htest"
- if(plot == T) {
- plotTitle = gsub('(.{1,50})(\\s|$)', '\\1\n', methodName)
- xLabel = paste("Simulated values, red line = fitted model. p-value (",out$alternative, ") = ", out$p.value, sep ="")
- hist(simulated, xlim = range(simulated, observed, na.rm=T ), col = "lightgrey", main = plotTitle, xlab = xLabel, breaks = max(round(simulationOutput$nSim / 5), 20), cex.main = 0.8)
- abline(v = observed, lwd= 2, col = "red")
- }
- return(out)
- }
- #' Test for temporal autocorrelation
- #'
- #' This function performs a standard test for temporal autocorrelation on the simulated residuals.
- #'
- #' @param simulationOutput an object of class DHARMa, either created via [simulateResiduals] for supported models or by [createDHARMa] for simulations created outside DHARMa, or a supported model. Providing a supported model directly is discouraged, because simulation settings cannot be changed in this case.
- #' @param time time variable in the same order as the datapoints and with the same length as the residuals in simulationOutput. If specified as formula, e.g. time = ~time, NAs are handled automatically (recommended).
- #' @param alternative a character string specifying whether the test should test if observations are "greater", "less" or "two.sided" compared to the simulated null hypothesis.
- #' @param plot whether to plot output.
- #' @details The function performs a Durbin-Watson test on the uniformly scaled residuals, and plots the residuals against time. The DB test was originally designed for normal residuals. In simulations, I didn't see a problem with this setting though. The alternative is to transform the uniform residuals to normal residuals and perform the DB test on those.
- #'
- #' Testing for temporal autocorrelation requires unique time values - if you have several observations per time value, either use [recalculateResiduals] function to aggregate residuals per time step, or extract the residuals from the fitted object, and plot / test each of them independently for temporally repeated subgroups (typical choices would be location / subject etc.). Note that the latter must be done by hand, outside testTemporalAutocorrelation.
- #'
- #' @note Standard DHARMa simulations from models with (temporal / spatial / phylogenetic) conditional autoregressive terms will still have the respective temporal / spatial / phylogenetic correlation in the DHARMa residuals, unless the package you are using is modelling the autoregressive terms as explicit REs and is able to simulate conditional on the fitted REs. This has two consequences:
- #'
- #' 1. If you check the residuals for such a model, they will still show significant autocorrelation, even if the model fully accounts for this structure.
- #'
- #' 2. Because the DHARMa residuals for such a model are not statistically independent anymore, other tests (e.g. dispersion, uniformity) may have inflated type I error, i.e. you will have a higher likelihood of spurious residual problems.
- #'
- #' There are three (non-exclusive) routes to address these issues when working with spatial / temporal / other autoregressive models:
- #'
- #' 1. Simulate conditional on the fitted CAR structures (see conditional simulations in the help of [simulateResiduals]).
- #'
- #' 2. Rotate simulations prior to residual calculations (see parameter rotation in [simulateResiduals]).
- #'
- #' 3. Use custom tests / plots that explicitly compare the correlation structure in the simulated data to the correlation structure in the observed data.
- #'
- #' @author Florian Hartig
- #' @seealso [testResiduals], [testUniformity], [testOutliers], [testDispersion], [testZeroInflation], [testGeneric], [testTemporalAutocorrelation], [testSpatialAutocorrelation], [testQuantiles], [testCategorical]
- #' @example inst/examples/testTemporalAutocorrelationHelp.R
- #' @export
- testTemporalAutocorrelation <- function(simulationOutput, time, alternative = c("two.sided", "greater", "less"), plot = TRUE){
- simulationOutput = ensureDHARMa(simulationOutput, convert = T)
- alternative <- match.arg(alternative)
- if(is.null(time)){
- time = sample.int(simulationOutput$nObs, simulationOutput$nObs)
- message("DHARMa::testTemporalAutocorrelation - no time argument provided, using random times for each data point")
- }
- if(!inherits(time, "formula")){
- # old default
- # To avoid Issue #190
- if (length(time) != length(residuals(simulationOutput))) stop("Dimensions of time don't match the dimension of the residuals. Remove rows with NAs or use formula syntax for group to handle NAs automatically.")
- } else {
- time = getFormulaPredictors(simulationOutput, formula = time)[[1]] # formula syntax
- }
- # actually not sure if this is neccessary for dwtest, but seems better to aggregate
- if(any(duplicated(time))) stop("testing for temporal autocorrelation requires unique time values - if you have several observations per time value, either use the recalculateResiduals function to aggregate residuals per time step, or extract the residuals from the fitted object, and plot / test each of them independently for temporally repeated subgroups (typical choices would be location / subject etc.). Note that the latter must be done by hand, outside testTemporalAutocorrelation.")
- out = lmtest::dwtest(simulationOutput$scaledResiduals ~ 1, order.by = time, alternative = alternative)
- if(plot == T) {
- oldpar <- par(mfrow = c(1,2))
- on.exit(par(oldpar))
- plot(simulationOutput$scaledResiduals[order(time)] ~ time[order(time)],
- type = "l", ylab = "Scaled residuals", xlab = "Time", main = "Residuals vs. time", ylim = c(0,1))
- abline(h=c(0.5))
- abline(h=c(0,0.25,0.75,1), lty = 2 )
- acf(simulationOutput$scaledResiduals[order(time)], main = "Autocorrelation", ylim = c(-1,1))
- legend("topright",
- c(paste(out$method, " p=", round(out$p.value, digits = 5)),
- paste("Deviation ", ifelse(out$p.value < 0.05, "significant", "n.s."))),
- text.col = ifelse(out$p.value < 0.05, "red", "black" ), bty="n")
- }
- return(out)
- }
- #' Test for distance-based spatial (or similar type) autocorrelation
- #'
- #' This function performs a Moran's I test for distance-based spatial (or similar type) autocorrelation on the calculated quantile residuals.
- #'
- #' @param simulationOutput an object of class DHARMa, either created via [simulateResiduals] for supported models or via [createDHARMa] for simulations created outside DHARMa, or a supported model. Providing a supported model directly is discouraged, because simulation settings cannot be changed in this case.
- #' @param x the x coordinate, in the same order as the data points. Must be specified unless distMat is provided.
- #' @param y the y coordinate, in the same order as the data points. Must be specified unless distMat is provided.
- #' @param distMat optional distance matrix. Must be provided as class "matrix/array" (class "dist" is not supported). If distMat is not provided, euclidean distances based on x and y will be calculated. See details for explanation.
- #' @param alternative a character string specifying whether the test should test if observations are "greater", "less" or "two.sided" compared to the simulated null hypothesis.
- #' @param plot if T, and if x and y is provided, plot the output (see details).
- #'
- #' @details The function performs Moran.I test from the package ape on the DHARMa residuals. If a distance matrix (distMat) is provided, calculations will be based on this distance matrix, and x,y coordinates will only be used for the plotting (if provided). If distMat is not provided, the function will calculate the euclidean distances between x,y coordinates, and test Moran.I based on these distances.
- #'
- #' If plot = T, a plot will be produced showing each residual at its x,y position, colored according to the residual value. Residuals with 0.5 are colored white, everything below 0.5 is colored increasingly red, everything above 0.5 is colored increasingly blue.
- #'
- #' Testing for spatial autocorrelation requires unique x,y values - if you have several observations per location, either use the [recalculateResiduals] function to aggregate residuals per location, or extract the residuals from the fitted object, and plot / test each of them independently for spatially repeated subgroups (a typical scenario would be repeated spatial observation, in which case one could plot / test each time step separately for temporal autocorrelation). Note that the latter must be done by hand, outside [testSpatialAutocorrelation].
- #'
- #' @note Standard DHARMa simulations from models with (temporal / spatial / phylogenetic) conditional autoregressive terms will still have the respective temporal / spatial / phylogenetic correlation in the DHARMa residuals, unless the package you are using is modelling the autoregressive terms as explicit REs and is able to simulate conditional on the fitted REs. This has two consequences:
- #'
- #' 1. If you check the residuals for such a model, they will still show significant autocorrelation, even if the model fully accounts for this structure.
- #'
- #' 2. Because the DHARMa residuals for such a model are not statistically independent anymore, other tests (e.g. dispersion, uniformity) may have inflated type I error, i.e. you will have a higher likelihood of spurious residual problems.
- #'
- #' There are three (non-exclusive) routes to address these issues when working with spatial / temporal / phylogenetic / other autoregressive models:
- #'
- #' 1. Simulate conditional on the fitted CAR structures (see conditional simulations in the help of [simulateResiduals]).
- #'
- #' 2. Rotate simulations prior to residual calculations (see parameter rotation in [simulateResiduals]).
- #'
- #' 3. Use custom tests / plots that explicitly compare the correlation structure in the simulated data to the correlation structure in the observed data.
- #'
- #' @author Florian Hartig
- #' @seealso [testResiduals], [testUniformity], [testOutliers], [testDispersion], [testZeroInflation], [testGeneric], [testTemporalAutocorrelation], [testSpatialAutocorrelation], [testQuantiles], [testCategorical]
- #' @import grDevices
- #' @example inst/examples/testSpatialAutocorrelationHelp.R
- #' @export
- testSpatialAutocorrelation <- function(simulationOutput, x = NULL, y = NULL, distMat = NULL, alternative = c("two.sided", "greater", "less"), plot = TRUE){
- alternative <- match.arg(alternative)
- data.name = deparse(substitute(simulationOutput)) # needs to be before ensureDHARMa
- simulationOutput = ensureDHARMa(simulationOutput, convert = T)
- # Assertions
- if( (!is.null(x) | !is.null(y)) & !is.null(distMat) ){
- if(isTRUE(plot)) {message("Both coordinates and distMat provided, calculations will be done based on the distance matrix, coordinates will only be used for plotting.")}
- else { # set x,y to NULL so they don't cause errors if wrong dimensions
- x = NULL
- y = NULL
- message("Both coordinates and distMat provided, calculations will be done based on the distance matrix, coordinates will be ignored.")
- }
- }
- if( (is.null(x) | is.null(y)) & is.null(distMat) ) stop("You need to provide either x,y coordinates or a distMatrix.")
- # check if x,y are formulas
- if(!inherits(x, "formula") | !inherits(y, "formula")) {
- # old default
- # To avoid Issue #190
- if (is.null(distMat) & !is.null(x) & length(x) != length(residuals(simulationOutput)) | is.null(distMat) & !is.null(y) & length(y) != length(residuals(simulationOutput))) stop("Dimensions of x / y coordinates don't match the dimension of the residuals. Remove rows with NAs or specify x,y as formula to handle NAs automatically.")
- if(inherits(x, "formula") != inherits(y, "formula")) stop("Please specify x and y the same way, either both as formula (e.g.x = ~x) or both as vector (e.g. x = data$x).")
- } else {
- # formula syntax
- x = getFormulaPredictors(simulationOutput, formula = x)[[1]]
- y = getFormulaPredictors(simulationOutput, formula = y)[[1]]
- }
- # if not provided, create distance matrix based on x and y
- if(is.null(distMat)) distMat <- as.matrix(dist(cbind(x, y)))
- # check for duplicates in x,y and distMat (off-diagonal zero values) (#73)
- testDistMat = distMat
- diag(testDistMat) = NA # set diagonal to NA
- if(any(duplicated(cbind(x,y))) | any(testDistMat == 0, na.rm = TRUE)) stop("Testing for spatial autocorrelation requires unique x,y values - if you have several observations per location, either use the recalculateResiduals function to aggregate residuals per location, or extract the residuals from the fitted object, and plot / test each of them independently for spatially repeated subgroups (a typical scenario would be repeated spatial observation, in which case one could plot / test each time step separately for temporal autocorrelation). Note that the latter must be done by hand, outside testSpatialAutocorrelation.")
- invDistMat <- 1/distMat
- diag(invDistMat) <- 0
- MI = ape::Moran.I(simulationOutput$scaledResiduals, weight = invDistMat, alternative = alternative)
- out = list()
- out$statistic = c(observed = MI$observed, expected = MI$expected, sd = MI$sd)
- out$method = "DHARMa Moran's I test for distance-based autocorrelation"
- out$alternative = "Distance-based autocorrelation"
- out$p.value = MI$p.value
- out$data.name = data.name
- class(out) = "htest"
- if(plot == T & !is.null(x) & !is.null(y)) {
- opar = par(no.readonly = TRUE)
- on.exit(par(opar))
- col = colorRamp(c("red", "white", "blue"))(simulationOutput$scaledResiduals)
- layout(matrix(c(1, 2), ncol = 2), widths = c(6, 1))
- # scatterplot
- par(mar = c(5, 4, 4, 1))
- plot(x, y,
- col = rgb(col, maxColorValue = 255),
- main = "Standardized residuals in space",
- cex.main = 0.8)
- mtext(paste0(out$method, "\n",
- " p = ", round(out$p.value, digits = 5), ", Deviation ", ifelse(out$p.value < 0.05, "significant", "n.s.")),
- col = ifelse(out$p.value < 0.05, "red", "black"),
- cex = 0.8,
- side = 3, line = 0)
- # legend
- par(mar = c(1, 0.5, 2, 2))
- plot.new()
- plot.window(xlim = c(0, 1), ylim = c(-1, 1))
- legend_image = as.raster(matrix(colorRampPalette(c("blue", "white", "red"))(200), ncol = 1))
- rasterImage(legend_image,
- xleft = -0.5, xright = 1,
- ybottom = -0.1, ytop = 0.5)
- axis(4, at = c(-0.1, 0.5), labels = c("0", "1"), las = 1)
- mtext("Standardized \n residuals", side = 3, line = -5,cex = 0.8,)
- # TODO implement correlogram
- }
- return(out)
- }
- #' Test for phylogenetic autocorrelation
- #'
- #' This function performs a Moran's I test for phylogenetic autocorrelation on the calculated quantile residuals.
- #'
- #' @param simulationOutput an object of class DHARMa, either created via [simulateResiduals] for supported models or via [createDHARMa] for simulations created outside DHARMa, or a supported model. Providing a supported model directly is discouraged, because simulation settings cannot be changed in this case.
- #' @param tree a phylogenetic tree object.
- #' @param alternative a character string specifying whether the test should test if observations are "greater", "less" or "two.sided" compared to the simulated null hypothesis of no phylogenetic correlation.
- #'
- #' @details The function performs Moran.I test from the package ape on the DHARMa residuals, based on the phylogenetic distance matrix internally created from the provided tree. For custom distance matrices, you can use [testSpatialAutocorrelation].
- #'
- #' @note Standard DHARMa simulations from models with (temporal / spatial / phylogenetic) conditional autoregressive terms will still have the respective temporal / spatial / phylogenetic correlation in the DHARMa residuals, unless the package you are using is modelling the autoregressive terms as explicit REs and is able to simulate conditional on the fitted REs. This has two consequences:
- #'
- #' 1. If you check the residuals for such a model, they will still show significant autocorrelation, even if the model fully accounts for this structure.
- #'
- #' 2. Because the DHARMa residuals for such a model are not statistically independent anymore, other tests (e.g. dispersion, uniformity) may have inflated type I error, i.e. you will have a higher likelihood of spurious residual problems.
- #'
- #' There are three (non-exclusive) routes to address these issues when working with spatial / temporal / phylogenetic autoregressive models:
- #'
- #' 1. Simulate conditional on the fitted CAR structures (see conditional simulations in the help of [simulateResiduals]).
- #'
- #' 2. Rotate simulations prior to residual calculations (see parameter rotation in [simulateResiduals]).
- #'
- #' 3. Use custom tests / plots that explicitly compare the correlation structure in the simulated data to the correlation structure in the observed data.
- #'
- #' @author Florian Hartig
- #' @seealso [testResiduals], [testUniformity], [testOutliers], [testDispersion], [testZeroInflation], [testGeneric], [testTemporalAutocorrelation], [testSpatialAutocorrelation], [testQuantiles], [testCategorical]
- #' @example inst/examples/testPhylogeneticAutocorrelationHelp.R
- #' @export
- testPhylogeneticAutocorrelation <- function(simulationOutput,
- tree,
- alternative = c("two.sided", "greater", "less")){
- alternative <- match.arg(alternative)
- data.name = deparse(substitute(simulationOutput)) # needs to be before ensureDHARMa
- simulationOutput = ensureDHARMa(simulationOutput, convert = T)
- # calculate distance matrix
- distMat <- cophenetic(tree)
- invDistMat <- 1/distMat
- diag(invDistMat) <- 0
- MI = ape::Moran.I(simulationOutput$scaledResiduals, weight = invDistMat, alternative = alternative)
- out = list()
- out$statistic = c(observed = MI$observed, expected = MI$expected, sd = MI$sd)
- out$method = "DHARMa Moran's I test for phylogenetic autocorrelation"
- out$alternative = "Phylogenetic autocorrelation"
- out$p.value = MI$p.value
- out$data.name = data.name
- class(out) = "htest"
- return(out)
- }
- getP <- function(simulated, observed, alternative, plot = FALSE, ...){
- if(alternative == "greater") p = mean(simulated >= observed)
- if(alternative == "less") p = mean(simulated <= observed)
- if(alternative == "two.sided") p = min(min(mean(simulated <= observed), mean(simulated >= observed) ) * 2,1)
- if(plot == T){
- hist(simulated, xlim = range(simulated, observed), col = "lightgrey", main = "Distribution of test statistic \n grey = simulated, red = observed", ...)
- abline(v = mean(simulated), col = 1, lwd = 2)
- abline(v = observed, col = "red", lwd = 2)
- }
- return(p)
- }
tests.R at commit c9dbcee, under gnu · at the source
Overview
- Taub Institute for Research on Alzheimer’s Disease and the Aging Brain, Columbia University Irving Medical Center, New York, NY 10032, USA
- Burke Neurological Institute, White Plains, NY 10605, USA
- Center for Neural Science, New York University, New York, NY 10003, USA
- Department of Neuroscience, Columbia University Irving Medical Center, New York, NY 10027, USA
- Center for Theoretical Neuroscience, Columbia University, New York, NY 10027, USA
- Zuckerman Mind Brain Behavior Institute, Columbia University, New York, NY 10027, USA
- Kavli Institute for Brain Science, Columbia University, New York, NY 10027, USA
- Department of Pathology and Cell Biology, Columbia University Irving Medical Center, New York, NY 10032, USA
- Lead contact
Abstract
Advanced amyloid beta (Aβ) pathology is associated with aberrant neuronal network activity and cognitive impairment in preclinical Alzheimer’s disease (AD) models. Here, we assess Aβ pathology’s impact on spatial information processing in the medial entorhinal cortex (MEC) of 18-month AppNL-G-F/
Reproduced under the paper's license (CC BY), from the paper cited above.
Repositories
Its files are read in the Code ↔ Paper reader above, with 2 matches between paragraphs and lines of code.
Zenodo 19040105
Availability: 1 check, the latest on 27 September 2026: the link answers (HTTP 200)
- 27 September 2026: the link answers (HTTP 200)
1 file
- README.md, Text, 4 lines
klusta-team/klustakwik
d8b750107fef53996957d774dfa3ec71f2442462, 21 April 2015Availability: 1 check, the latest on 27 September 2026: the link answers
- 27 September 2026: the link answers
19 files
- devtools/
cluster_mask_stats.py , Python, 155 lines - devtools/
filter_noise_spikes.py , Python, 136 lines - globalswitches.h, C/C++, 43 lines
- io.cpp, C++, 471 lines
- klustakwik.cpp, C++, 1,887 lines
- klustakwik.h, C/C++, 217 lines
- linalg.cpp, C++, 334 lines
- linalg.h, C/C++, 40 lines
- log.cpp, C++, 56 lines
- log.h, C/C++, 21 lines
- memorytracking.cpp, C++, 90 lines
- memorytracking.h, C/C++, 37 lines
- numerics.h, C/C++, 134 lines
- parameters.cpp, C++, 194 lines
- parameters.h, C/C++, 138 lines
- precomputations.cpp, C++, 315 lines
- util.cpp, C++, 78 lines
- util.h, C/C++, 24 lines
- README.md, Text, 299 lines
glmmTMB/glmmTMB
db725d143d529c93c55cf7baa7402dc5135fe6ff, 23 September 2026Availability: 1 check, the latest on 27 September 2026: the link answers
- 27 September 2026: the link answers
201 files
- docs/
articles/ , JavaScript, 15 linescovstruct_files/ accessible-code-block-0. 0.1/ empty-anchor.js - docs/
articles/ , JavaScript, 12 linescovstruct_files/ header-attrs-2.11/ header-attrs.js - docs/
articles/ , JavaScript, 15 linesglmmTMB_files/ accessible-code-block-0. 0.1/ empty-anchor.js - docs/
articles/ , JavaScript, 12 linesglmmTMB_files/ header-attrs-2.11/ header-attrs.js - docs/
articles/ , JavaScript, 15 lineshacking_files/ accessible-code-block-0. 0.1/ empty-anchor.js - docs/
articles/ , JavaScript, 15 linesmcmc_files/ accessible-code-block-0. 0.1/ empty-anchor.js - docs/
articles/ , JavaScript, 12 linesmcmc_files/ header-attrs-2.11/ header-attrs.js - docs/
articles/ , JavaScript, 15 linesmiscEx_files/ accessible-code-block-0. 0.1/ empty-anchor.js - docs/
articles/ , JavaScript, 12 linesmiscEx_files/ header-attrs-2.11/ header-attrs.js - docs/
articles/ , JavaScript, 15 linesmodel_evaluation_files/ accessible-code-block-0. 0.1/ empty-anchor.js - docs/
articles/ , JavaScript, 12 linesmodel_evaluation_files/ header-attrs-2.11/ header-attrs.js - docs/
articles/ , JavaScript, 15 linesparallel_files/ accessible-code-block-0. 0.1/ empty-anchor.js - docs/
articles/ , JavaScript, 12 linesparallel_files/ header-attrs-2.11/ header-attrs.js - docs/
articles/ , JavaScript, 15 linessim_files/ accessible-code-block-0. 0.1/ empty-anchor.js - docs/
articles/ , JavaScript, 12 linessim_files/ header-attrs-2.11/ header-attrs.js - docs/
articles/ , JavaScript, 15 linestroubleshooting_files/ accessible-code-block-0. 0.1/ empty-anchor.js - docs/
articles/ , JavaScript, 12 linestroubleshooting_files/ header-attrs-2.11/ header-attrs.js - docs/
bootstrap-toc.js , JavaScript, 159 lines - docs/
docsearch.js , JavaScript, 85 lines - docs/
pkgdown.js , JavaScript, 108 lines - docs/
repos/ , R, 48 linesindex.Rmd - glmmTMB/
R/ , R, 409 linesAnova.R - glmmTMB/
R/ , R, 279 linesVarCorr.R - glmmTMB/
R/ , R, 28 linesdata.R - glmmTMB/
R/ , R, 696 linesdenom_df.R - glmmTMB/
R/ , R, 219 lines, 1 matchdiagnose.R - glmmTMB/
R/ , R, 356 linesdistributions.R - glmmTMB/
R/ , R, 37 lineseffects.R - glmmTMB/
R/ , R, 416 linesemmeans.R - glmmTMB/
R/ , R, 82 linesenum.R - glmmTMB/
R/ , R, 570 linesfamily.R - glmmTMB/
R/ , R, 2,489 linesglmmTMB.R - glmmTMB/
R/ , R, 28 lineslme4_utils_temp.R - glmmTMB/
R/ , R, 2,378 linesmethods.R - glmmTMB/
R/ , R, 595 linespredict.R - glmmTMB/
R/ , R, 273 linespriors.R - glmmTMB/
R/ , R, 218 linesprofile.R - glmmTMB/
R/ , R, 638 linesrtmb_covstruct.R - glmmTMB/
R/ , R, 938 linesrtmb_distributions.R - glmmTMB/
R/ , R, 593 linesrtmb_tpl.R - glmmTMB/
R/ , R, 7 linesto_be_removed.R - glmmTMB/
R/ , R, 1,135 linesutils.R - glmmTMB/
R/ , R, 73 linesutils_covstruct.R - glmmTMB/
R/ , R, 30 lineszzz.R - glmmTMB/
inst/ , R, 5 linesexample_files/ mk_examples.R - glmmTMB/
inst/ , R, 53 linesmisc/ extract_rr.R - glmmTMB/
inst/ , R, 190 linesmisc/ rsqglmm.R - glmmTMB/
inst/ , R, 63 linesmisc/ test_parallel.R - glmmTMB/
inst/ , R, 20 linesother_methods/ car_methods.R - glmmTMB/
inst/ , R, 123 linesother_methods/ effectsglmmTMB.R - glmmTMB/
inst/ , R, 62 linesother_methods/ extract.R - glmmTMB/
inst/ , R, 225 linesother_methods/ influence_mixed.R - glmmTMB/
inst/ , R, 34 linesother_methods/ lsmeans_methods.R - glmmTMB/
inst/ , R, 5 linestest_data/ glmmTMB-test-funs.R - glmmTMB/
inst/ , R, 108 linestest_data/ make_ex.R - glmmTMB/
inst/ , R, 101 linestest_data/ turner_glmmadapt.R - glmmTMB/
inst/ , R, 180 linesvignette_data/ mcmc.R - glmmTMB/
inst/ , R, 23 linesvignette_data/ model_evaluation.R - glmmTMB/
inst/ , R, 14 linesvignette_data/ troubleshooting.R - glmmTMB/
src/ , C/C++, 151 linescordistrib.h - glmmTMB/
src/ , C/C++, 614 linesdistrib.h - glmmTMB/
src/ , C++, 1,511 linesglmmTMB.cpp - glmmTMB/
src/ , C/C++, 39 linesinit.h - glmmTMB/
src/ , C++, 16 linesutils.cpp - glmmTMB/
tests/ , R, 10 linesAAAtest-all.R - glmmTMB/
tests/ , R, 6 linestestthat/ setup-rtmb.R - glmmTMB/
tests/ , R, 12 linestestthat/ setup_makeex.R - glmmTMB/
tests/ , R, 110 linestestthat/ test-Anova.R - glmmTMB/
tests/ , R, 242 linestestthat/ test-VarCorr.R - glmmTMB/
tests/ , R, 17 linestestthat/ test-altopt.R - glmmTMB/
tests/ , R, 243 linestestthat/ test-anova-ddf.R - glmmTMB/
tests/ , R, 430 linestestthat/ test-basics.R - glmmTMB/
tests/ , R, 31 linestestthat/ test-bootMer.R - glmmTMB/
tests/ , R, 197 linestestthat/ test-checkRank.R - glmmTMB/
tests/ , R, 204 linestestthat/ test-control.R - glmmTMB/
tests/ , R, 371 linestestthat/ test-ddf.R - glmmTMB/
tests/ , R, 56 linestestthat/ test-diagnose.R - glmmTMB/
tests/ , R, 53 linestestthat/ test-disp.R - glmmTMB/
tests/ , R, 99 linestestthat/ test-distributions.R - glmmTMB/
tests/ , R, 128 linestestthat/ test-downstream.R - glmmTMB/
tests/ , R, 17 linestestthat/ test-edgecases.R - glmmTMB/
tests/ , R, 52 linestestthat/ test-env.R - glmmTMB/
tests/ , R, 116 linestestthat/ test-equalto.R - glmmTMB/
tests/ , R, 593 linestestthat/ test-families.R - glmmTMB/
tests/ , R, 49 linestestthat/ test-formulas.R - glmmTMB/
tests/ , R, 24 linestestthat/ test-mapequal.R - glmmTMB/
tests/ , R, 117 linestestthat/ test-mapopt.R - glmmTMB/
tests/ , R, 91 linestestthat/ test-mappedvcov.R - glmmTMB/
tests/ , R, 1,204 linestestthat/ test-methods.R - glmmTMB/
tests/ , R, 16 linestestthat/ test-misc.R - glmmTMB/
tests/ , R, 106 linestestthat/ test-offset.R - glmmTMB/
tests/ , R, 468 linestestthat/ test-ordinal.R - glmmTMB/
tests/ , R, 694 linestestthat/ test-predict.R - glmmTMB/
tests/ , R, 183 linestestthat/ test-priors.R - glmmTMB/
tests/ , R, 145 linestestthat/ test-propto.R - glmmTMB/
tests/ , R, 70 linestestthat/ test-reml.R - glmmTMB/
tests/ , R, 129 linestestthat/ test-rr.R - glmmTMB/
tests/ , R, 207 linestestthat/ test-rtmb-bell.R - glmmTMB/
tests/ , R, 308 linestestthat/ test-rtmb-beta.R - glmmTMB/
tests/ , R, 305 linestestthat/ test-rtmb-betabinomial.R - glmmTMB/
tests/ , R, 306 linestestthat/ test-rtmb-binomial.R - glmmTMB/
tests/ , R, 241 linestestthat/ test-rtmb-combinomial.R - glmmTMB/
tests/ , R, 278 linestestthat/ test-rtmb-compois.R - glmmTMB/
tests/ , R, 52 linestestthat/ test-rtmb-control.R - glmmTMB/
tests/ , R, 314 linestestthat/ test-rtmb-gamma.R - glmmTMB/
tests/ , R, 1,676 linestestthat/ test-rtmb-gaussian.R - glmmTMB/
tests/ , R, 231 linestestthat/ test-rtmb-genpois.R - glmmTMB/
tests/ , R, 325 linestestthat/ test-rtmb-lognormal.R - glmmTMB/
tests/ , R, 281 linestestthat/ test-rtmb-nbinom1.R - glmmTMB/
tests/ , R, 221 linestestthat/ test-rtmb-nbinom12.R - glmmTMB/
tests/ , R, 278 linestestthat/ test-rtmb-nbinom2.R - glmmTMB/
tests/ , R, 277 linestestthat/ test-rtmb-ordbeta.R - glmmTMB/
tests/ , R, 70 linestestthat/ test-rtmb-osa.R - glmmTMB/
tests/ , R, 1,397 linestestthat/ test-rtmb-poisson.R - glmmTMB/
tests/ , R, 226 linestestthat/ test-rtmb-rr.R - glmmTMB/
tests/ , R, 68 linestestthat/ test-rtmb-simulation.R - glmmTMB/
tests/ , R, 299 linestestthat/ test-rtmb-skewnormal.R - glmmTMB/
tests/ , R, 355 linestestthat/ test-rtmb-spatial.R - glmmTMB/
tests/ , R, 274 linestestthat/ test-rtmb-t.R - glmmTMB/
tests/ , R, 238 linestestthat/ test-rtmb-truncated-comp ois.R - glmmTMB/
tests/ , R, 259 linestestthat/ test-rtmb-truncated-genp ois.R - glmmTMB/
tests/ , R, 239 linestestthat/ test-rtmb-truncated-nbin om1.R - glmmTMB/
tests/ , R, 308 linestestthat/ test-rtmb-truncated-nbin om2.R - glmmTMB/
tests/ , R, 443 linestestthat/ test-rtmb-truncated-pois son.R - glmmTMB/
tests/ , R, 241 linestestthat/ test-rtmb-tweedie.R - glmmTMB/
tests/ , R, 15 linestestthat/ test-saveload.R - glmmTMB/
tests/ , R, 42 linestestthat/ test-simulate.R - glmmTMB/
tests/ , R, 271 linestestthat/ test-simulate_new.R - glmmTMB/
tests/ , R, 75 linestestthat/ test-smooths.R - glmmTMB/
tests/ , R, 26 linestestthat/ test-sparseX.R - glmmTMB/
tests/ , R, 15 linestestthat/ test-start.R - glmmTMB/
tests/ , R, 86 linestestthat/ test-utils.R - glmmTMB/
tests/ , R, 211 linestestthat/ test-varstruc.R - glmmTMB/
tests/ , R, 85 linestestthat/ test-weight.R - glmmTMB/
tests/ , R, 57 linestestthat/ test-zi.R - glmmTMB/
vignettes/ , R, 912 linescovstruct.rmd - glmmTMB/
vignettes/ , R, 200 lineshacking.rmd - glmmTMB/
vignettes/ , R, 204 linesmcmc.rmd - glmmTMB/
vignettes/ , R, 47 linesmiscEx.rmd - glmmTMB/
vignettes/ , R, 100 linesparallel.rmd - glmmTMB/
vignettes/ , R, 299 linespriors.rmd - glmmTMB/
vignettes/ , R, 249 linessim.rmd - glmmTMB/
vignettes/ , R, 33 linestimingContraception.R - glmmTMB/
vignettes/ , R, 28 linestimingFuns.R - glmmTMB/
vignettes/ , R, 32 linestimingInstEval.R - glmmTMB/
vignettes/ , R, 356 linestroubleshooting.rmd - misc/
CV675759.R , R, 17 lines - misc/
GH164.R , R, 44 lines - misc/
GH662.R , R, 183 lines - misc/
allFit.R , R, 72 lines - misc/
ar1_tests.R , R, 111 lines - misc/
ar_mem.R , R, 112 lines - misc/
autoreplace.sh , Shell, 19 lines - misc/
autowinbuilder.sh , Shell, 44 lines - misc/
bell.R , R, 155 lines - misc/
cloglog.R , R, 81 lines - misc/
compare_tarball.R , R, 46 lines - misc/
dgenpois.R , R, 44 lines - misc/
fixcorr.rmd , R, 129 lines - misc/
glmmTMB_GH1089.R , R, 101 lines - misc/
glmmTMB_GH1309.R , R, 190 lines - misc/
glmmTMB_GH635.R , R, 249 lines - misc/
glmmTMB_GH928.R , R, 31 lines - misc/
glmmTMB_PR652.R , R, 86 lines - misc/
glmmTMB_corcalcs.ipynb , Jupyter, 69 lines - misc/
glmmTMB_deseq.rmd , R, 94 lines - misc/
glmmTMB_hacks.Rmd , R, 12 lines - misc/
growth.model_check.R , R, 249 lines - misc/
hetero_ddf_sim.R , R, 216 lines - misc/
hetero_ddf_sim_analysis. , R, 66 linesR - misc/
kenward_roger.R , R, 243 lines - misc/
mkrepos.R , R, 80 lines - misc/
neg_binom_ex.R , R, 31 lines - misc/
ordbeta.R , R, 153 lines - misc/
owls.rmd , R, 262 lines - misc/
predsim.qmd , Quarto, 23 lines - misc/
problematic/ , R, 30 linespsinger.R - misc/
problematic/ , R, 34 linesunconverged_dispersion.R - misc/
problematic/ , R, 22 linesunconverged_salamanders. R - misc/
rr_ex.R , R, 30 lines - misc/
run_timing_combined.R , R, 166 lines - misc/
salamanders.rmd , R, 262 lines - misc/
sandwich_tests.R , R, 23 lines - misc/
set_simcodes.R , R, 34 lines - misc/
sim.R , R, 162 lines - misc/
simcode.R , R, 72 lines - misc/
smooth_issues.R , R, 46 lines - misc/
starting_values.R , R, 168 lines - misc/
test-ar1var.R , R, 35 lines - misc/
test_confint.R , R, 63 lines - misc/
test_sim.R , R, 120 lines - misc/
trunc_predict.R , R, 84 lines - notes/
arni-demo.R , R, 190 lines - notes/
glmmTMB_GH920.R , R, 59 lines - notes/
kronecker.qmd , Quarto, 378 lines - notes/
ranef.merMod.R , R, 134 lines - notes/
smooths.rmd , R, 138 lines - notes/
what_we_want.R , R, 75 lines - reverse/
checkChanges.R , R, 84 lines - reverse/
checkReverse.R , R, 206 lines - README.md, Text, 29 lines
florianhartig/DHARMa
c9dbcee2eec12904e505dd8c7c4f1f8d61ec1f79, 25 September 2026Availability: 1 check, the latest on 27 September 2026: the link answers
- 27 September 2026: the link answers
143 files
- Code/
DHARMaData/ , R, 10 linesDataCreationMaster.R - Code/
DHARMaDevelopment/ , R, 155 linesDHARMaReport.Rmd - Code/
DHARMaDevelopment/ , R, 156 linesExperimental.Rmd - Code/
DHARMaDevelopment/ , R, 12 linesPIT.R - Code/
DHARMaDevelopment/ , R, 24 linesREML.R - Code/
DHARMaDevelopment/ , R, 254 linesResiduals.Rmd - Code/
DHARMaDevelopment/ , R, 121 linesarm.R - Code/
DHARMaDevelopment/ , R, 107 linescompatibility.R - Code/
DHARMaDevelopment/ , R, 47 linesecdf-Def.R - Code/
DHARMaDevelopment/ , R, 16 linesformula.R - Code/
DHARMaDevelopment/ , R, 53 linesgamm4-support.R - Code/
DHARMaDevelopment/ , R, 23 linesglmmtmb-correlationStruc tures.R - Code/
DHARMaDevelopment/ , R, 21 linesnaAction.R - Code/
DHARMaDevelopment/ , R, 16 linesordinal.R - Code/
DHARMaDevelopment/ , R, 33 linesoutliers.R - Code/
DHARMaDevelopment/ , R, 117 linesparametricDispersionTest Fragments.R - Code/
DHARMaDevelopment/ , R, 34 linespoissonTest.R - Code/
DHARMaDevelopment/ , R, 125 linessimulate.lm.R - Code/
DHARMaDevelopment/ , R, 97 linestesting_getFormulaPredic tors.R - Code/
DHARMaDevelopment/ , R, 44 linestweedie.R - Code/
DHARMaDevelopment/ , R, 52 linesweights.R - Code/
DHARMaDevelopment/ , R, 22 lineszeroinflation.R - Code/
DHARMaExamples/ , R, 54 linesCNDD.R - Code/
DHARMaExamples/ , R, 95 linesConditionalUnconditional .R - Code/
DHARMaExamples/ , R, 67 linesDevianceResiduals.Rmd - Code/
DHARMaExamples/ , R, 27 linesDispersionBinomial.Rmd - Code/
DHARMaExamples/ , R, 199 linesGammaProblems.Rmd - Code/
DHARMaExamples/ , R, 27 linesScript_Budworm_for_Flori an.R - Code/
DHARMaExamples/ , R, 9 linesSimplePoisson.R - Code/
DHARMaExploration/ , R, 125 linesOverdispersion/ overdispersion.R - Code/
DHARMaIssues/ , R, 28 lines144.Rmd - Code/
DHARMaIssues/ , R, 2 lines152.R - Code/
DHARMaIssues/ , R, 78 lines152/ s_america_mod.R - Code/
DHARMaIssues/ , R, 148 lines158.R - Code/
DHARMaIssues/ , R, 16 lines160.R - Code/
DHARMaIssues/ , R, 11 lines163.R - Code/
DHARMaIssues/ , R, 108 lines201.R - Code/
DHARMaIssues/ , R, 21 lines222.R - Code/
DHARMaIssues/ , R, 1,034 lines269.R - Code/
DHARMaIssues/ , R, 19 lines270.R - Code/
DHARMaIssues/ , R, 22 lines272.R - Code/
DHARMaIssues/ , R, 14 lines282.R - Code/
DHARMaIssues/ , R, 32 lines294.R - Code/
DHARMaIssues/ , R, 73 lines303.R - Code/
DHARMaIssues/ , R, 38 lines307.R - Code/
DHARMaIssues/ , R, 16 lines348.R - Code/
DHARMaIssues/ , R, 22 lines351.R - Code/
DHARMaIssues/ , R, 47 lines38.R - Code/
DHARMaIssues/ , R, 89 lines392.R - Code/
DHARMaIssues/ , R, 32 lines402.R - Code/
DHARMaIssues/ , R, 36 lines406.R - Code/
DHARMaIssues/ , R, 106 lines415.R - Code/
DHARMaIssues/ , R, 64 lines417.R - Code/
DHARMaIssues/ , R, 112 lines418.R - Code/
DHARMaIssues/ , R, 316 lines436.R - Code/
DHARMaIssues/ , R, 32 lines504.R - Code/
DHARMaIssues/ , R, 53 linesissue-496.R - Code/
DHARMaIssues/ , R, 1,742 linesq1.R - Code/
DHARMaIssues/ , R, 29 linesrotation.R - Code/
DHARMaPackageSupport/ , R, 222 linesBayesianExamples/ beetlesBayes.Rmd - Code/
DHARMaPackageSupport/ , R, 60 linesGLMMadaptive/ GLMMadaptive-PackageSupp ortChecks.R - Code/
DHARMaPackageSupport/ , R, 579 linesGLMMadaptive/ glmmAdaptive_examples.R - Code/
DHARMaPackageSupport/ , R, 51 linesbrms/ brms.R - Code/
DHARMaPackageSupport/ , R, 20 linesgamlss/ gamlss.R - Code/
DHARMaPackageSupport/ , R, 55 linesglmmTMB/ glmmTMB-AR1.R - Code/
DHARMaPackageSupport/ , R, 141 linesglmmTMB/ glmmTMB.R - Code/
DHARMaPackageSupport/ , R, 384 linesglmmTMB/ glmmTMB.Rmd - Code/
DHARMaPackageSupport/ , R, 30 linesglmmTMB/ issue107.R - Code/
DHARMaPackageSupport/ , R, 53 lineslme4/ glmer.nb.R - Code/
DHARMaPackageSupport/ , R, 108 lineslme4/ lme4problems.R - Code/
DHARMaPackageSupport/ , R, 109 linesmgcv/ GAM.R - Code/
DHARMaPackageSupport/ , R, 312 linesmgcv/ GAMProblems.Rmd - Code/
DHARMaPackageSupport/ , R, 65 linesmgcv/ GAMproblems.R - Code/
DHARMaPackageSupport/ , R, 48 linesphylolm/ phylolm.R - Code/
DHARMaPackageSupport/ , R, 60 linesphyr/ phyrTests.R - Code/
DHARMaPackageSupport/ , R, 124 linessjSDM/ sjSDM-tests.R - Code/
DHARMaPackageSupport/ , R, 106 linesspaMM/ spaMM-test.R - Code/
DHARMaPackageSupport/ , R, 55 linestestCompatibility.R - Code/
DHARMaPackageSupport/ , R, 25 linesvgam/ vgam-support.R - Code/
DHARMaPerformance/ , R, 61 linesCalibration.Rmd - Code/
DHARMaPerformance/ , R, 24 linesOverdispersion.R - Code/
DHARMaPerformance/ , R, 171 linesPowerBias.Rmd - Code/
DHARMaPerformance/ , R, 56 linesRSA.Rmd - Code/
DHARMaPerformance/ , R, 211 linesTestPower.Rmd - Code/
DHARMaPerformance/ , R, 81 linespValuesAutocorrelation.R - Code/
DHARMaPerformance/ , R, 28 linessimLRT.R - Code/
DHARMaPerformance/ , R, 26 linestestRefit.R - Code/
DHARMaPerformance/ , R, 24 lineszeroinflation.R - Code/
DHARMaTeaching/ , R, 192 lines21-BayesianThinkingWorks hopZuerich/ BayesianModelCriticism.R - Code/
DHARMaTeaching/ , R, 138 linesBayesianChecks/ Bayesian.R - Code/
DHARMaTeaching/ , R, 98 linesISEC2020/ ISEC-2020-live.R - Code/
DHARMaTeaching/ , R, 288 linesISEC2020/ ISEC2020.Rmd - Code/
DHARMaTeaching/ , R, 381 linesroteiro_DHARMa_Port/ roteiro_DHARMa.Rmd - Code/
Visualization/ , R, 24 linesECDF.R - DHARMa/
R/ , R, 168 linesDHARMa.R - DHARMa/
R/ , R, 1,124 linescompatibility.R - DHARMa/
R/ , R, 155 linescreateData.R - DHARMa/
R/ , R, 30 linesdata.R - DHARMa/
R/ , R, 253 lineshelper.R - DHARMa/
R/ , R, 48 linesimports.R - DHARMa/
R/ , R, 565 linesplots.R - DHARMa/
R/ , R, 42 linesrandom.R - DHARMa/
R/ , R, 265 linesrunBenchmarks.R - DHARMa/
R/ , R, 108 linessimulateLRT.R - DHARMa/
R/ , R, 322 linessimulateResiduals.R - DHARMa/
R/ , R, 15 linesstartup.R - DHARMa/
R/ , R, 903 lines, 1 matchtests.R - DHARMa/
R/ , R, 13 linestransformQuantiles.R - DHARMa/
inst/ , R, 24 linesexamples/ benchmarkRuntimeHelp.R - DHARMa/
inst/ , R, 10 linesexamples/ checkModelHelp.R - DHARMa/
inst/ , R, 34 linesexamples/ createDataHelp.R - DHARMa/
inst/ , R, 26 linesexamples/ createDharmaHelp.R - DHARMa/
inst/ , R, 13 linesexamples/ dharma-package.R - DHARMa/
inst/ , R, 34 linesexamples/ getRandomStateHelp.R - DHARMa/
inst/ , R, 29 linesexamples/ hurricanes.R - DHARMa/
inst/ , R, 56 linesexamples/ plotResidualsHelp.R - DHARMa/
inst/ , R, 28 linesexamples/ plotsHelp.R - DHARMa/
inst/ , R, 53 linesexamples/ runBenchmarksHelp.R - DHARMa/
inst/ , R, 22 linesexamples/ simulateLRTHelp.R - DHARMa/
inst/ , R, 61 linesexamples/ simulateResidualsHelp.R - DHARMa/
inst/ , R, 31 linesexamples/ testDispersionHelp.R - DHARMa/
inst/ , R, 36 linesexamples/ testOutliersHelp.R - DHARMa/
inst/ , R, 30 linesexamples/ testPhylogeneticAutocorr elationHelp.R - DHARMa/
inst/ , R, 31 linesexamples/ testQuantilesHelp.R - DHARMa/
inst/ , R, 85 linesexamples/ testSpatialAutocorrelati onHelp.R - DHARMa/
inst/ , R, 159 linesexamples/ testTemporalAutocorrelat ionHelp.R - DHARMa/
inst/ , R, 43 linesexamples/ testsHelp.R - DHARMa/
inst/ , R, 22 linesexamples/ wrappersHelp.R - DHARMa/
tests/ , R, 18 linesmanualTests/ DHARMa-rhub.R - DHARMa/
tests/ , R, 64 linesmanualTests/ comparingPackges_condUnc onditional_GLMM.R - DHARMa/
tests/ , R, 17 linesmanualTests/ numericReproducibility.R - DHARMa/
tests/ , R, 12 linestestthat.R - DHARMa/
tests/ , R, 76 linestestthat/ testCompatibility.R - DHARMa/
tests/ , R, 122 linestestthat/ testDharmaClass.R - DHARMa/
tests/ , R, 76 linestestthat/ testHelper.R - DHARMa/
tests/ , R, 730 linestestthat/ testModelTypes.R - DHARMa/
tests/ , R, 18 linestestthat/ testNumericReproducibili ty.R - DHARMa/
tests/ , R, 90 linestestthat/ testPlots.R - DHARMa/
tests/ , R, 92 linestestthat/ testSimulateResiduals.R - DHARMa/
tests/ , R, 269 linestestthat/ testTests.R - DHARMa/
vignettes/ , R, 1,010 linesDHARMa.Rmd - DHARMa/
vignettes/ , R, 171 linesDHARMaForBayesians.Rmd - README.md, Text, 93 lines
hussainilab/rodriguez-et-al-cell-reports-2026
7772cfa1cce93cad101419229805151e27f5beea, 14 May 2026Availability: 1 check, the latest on 27 September 2026: the link answers
- 27 September 2026: the link answers
1 file
- README.md, Text, 15 lines
The paper's code and data availability statement is in the Data section.
Tracing map
Proposed by the machine: these links were found in the paper and verified at the source, without human review. The map will receive a Zenodo DOI once one of the paper's authors has validated it with their ORCID.
What the map holds:
- 5 repositories of the authors' code, each at its verified commit, with its license and how the link was found in the paper;
- 360 scripts, each with its path and the digest of its content;
- 2 matches between paragraphs of the paper and lines of the code (method lexical-v1);
- neither the text of the paper nor the code itself.
Its JSON (tracing-map.json) is deposited on Zenodo with its DOI once the map is validated.
Data
No dataset and no data link were found in the paper.
Data and code availability
Source data for all figures will be made freely available on the Hussaini Lab GitHub page (https://
All original code used for data analysis will be made freely available on the Hussaini Lab GitHub page.
Any additional information regarding data is available from the lead contact upon request.
Reproduced under the paper's license (CC BY), from the paper cited above.
Versions
The history of this record: each version stored by the harvester or made by a correction of its authors or of the maintainers of its code, and what changed in its facts. The texts of the paper (its abstract, its availability statements) are not part of it; versions that changed only those are not listed.
Version 2, 28 September 2026
- Publisher: n/a → Cell Press
- Authors: added S Abid Hussaini (0000-0002-3921-9021); removed S Abid Hussaini
Version 1, 27 September 2026: the first record
Recorded: type, language, journal, volume, issue, pages, dates, 10 authors, 11 keywords, 13 MeSH terms, 3 funders, 140 references, 10 RRIDs.
Cite
This paper
Rodriguez, G. A., Aoun, A., Rothenberg, E. F., Shetler, C. O., Posani, L., Vajram, S. V., Tedesco, T., Sharma, A., Fusi, S., & Hussaini, S. A. (2026). Impaired spatial coding and neuronal hyperactivity in the medial entorhinal cortex of aged APP knock-in mice. Cell reports, 45(6), 117505. https://
BibTeX
@article{rodriguez2026im
author = {Rodriguez, Gustavo A and Aoun, Andrew and Rothenberg, Eva F and Shetler, C Oliver and Posani, Lorenzo and Vajram, Srujan V and Tedesco, Thomas and Sharma, Anurag and Fusi, Stefano and Hussaini, S Abid},
title = {{Impaired spatial coding and neuronal hyperactivity in the medial entorhinal cortex of aged APP knock-in mice}},
journal = {Cell reports},
year = {2026},
month = jun,
volume = {45},
number = {6},
pages = {117505},
publisher = {Cell Press},
issn = {2211-1247},
doi = {10.1016/
url = {https://
pmid = {42250220},
pmcid = {PMC13560757}
}
RIS
TY - JOUR
AU - Rodriguez, Gustavo A
AU - Aoun, Andrew
AU - Rothenberg, Eva F
AU - Shetler, C Oliver
AU - Posani, Lorenzo
AU - Vajram, Srujan V
AU - Tedesco, Thomas
AU - Sharma, Anurag
AU - Fusi, Stefano
AU - Hussaini, S Abid
TI - Impaired spatial coding and neuronal hyperactivity in the medial entorhinal cortex of aged APP knock-in mice
T2 - Cell reports
J2 - Cell Rep
PY - 2026
DA - 2026/
VL - 45
IS - 6
SP - 117505
SN - 2211-1247
PB - Cell Press
DO - 10.1016/
UR - https://
LA - en
ER -
CSL-JSON
{
"id": "10.1016/
"type": "article-journal",
"title": "Impaired spatial coding and neuronal hyperactivity in the medial entorhinal cortex of aged APP knock-in mice",
"container-title": "Cell reports",
"author": [
{
"family": "Rodriguez",
"given": "Gustavo A"
},
{
"family": "Aoun",
"given": "Andrew"
},
{
"family": "Rothenberg",
"given": "Eva F"
},
{
"family": "Shetler",
"given": "C Oliver"
},
{
"family": "Posani",
"given": "Lorenzo"
},
{
"family": "Vajram",
"given": "Srujan V"
},
{
"family": "Tedesco",
"given": "Thomas"
},
{
"family": "Sharma",
"given": "Anurag"
},
{
"family": "Fusi",
"given": "Stefano"
},
{
"family": "Hussaini",
"given": "S Abid"
}
],
"container-title-short":
"volume": "45",
"issue": "6",
"page": "117505",
"DOI": "10.1016/
"PMID": "42250220",
"PMCID": "PMC13560757",
"ISSN": "2211-1247",
"publisher": "Cell Press",
"URL": "https://
"language": "en",
"issued": {
"date-parts": [
[
2026,
6,
6
]
]
}
}
The tracing map gets a citation of its own once an author has validated it and it has a DOI.
Similar papers
The papers with a page that share the most with this one: the tools found in their code, their categories, datasets, cited references and authors, the rarest counting most.
- [1] doi:10.1016/j.celrep.2026.117646 [code]
- Medial entorhinal-hippocampal desynchronization parallels the emergence of memory impairment in a mouse model of Alzheimer's disease pathology.Journal: Cell reportsIn common: car, broom, emmeans, 7 other tools, Alzheimer's / dementia, mouse, 19 references
- [2] doi:10.1038/s41467-026-69866-3 [code]
- Selective weakening of population-coupled synaptic activity in vivo in a mouse model of amyloid-beta pathology.Journal: Nature communicationsIn common: patchwork, ggplot2, tidyverse, Alzheimer's / dementia, mouse, 17 references
- [3] doi:10.1016/j.isci.2026.116747 [code]
- Age and loneliness relate to reduced trust learning and alterations in amygdala function.Journal: iScienceIn common: Stan, brms, nlme, 9 other tools
- [4] doi:10.1111/ejn.70480 [code]
- Astrocyte Proximity Protects Synapses From Human Amyloid-Beta Induced Degeneration in a Mouse Ex Vivo Model of Early Alzheimer's Disease.Journal: The European journal of neuroscienceIn common: emmeans, lmerTest, lme4, 6 other tools, Alzheimer's / dementia, mouse, 6 references
- [5] doi:10.1038/s43587-026-01096-0 [code]
- Neuronal APOE4-induced early hippocampal network hyperexcitability in Alzheimer's disease pathogenesis.Journal: Nature agingIn common: pandas, Matplotlib, NumPy, Alzheimer's / dementia, mouse, 10 references
- [6] doi:10.1038/s41467-026-73865-9 [code]
- Histamine shapes the neurocomputational dynamics of human learning.Journal: Nature communicationsIn common: metafor, brms, easystats, 10 other tools
- [7] doi:10.1002/hbm.70605 [code]
- BrainEnrich: Revealing Biological Insights for Imaging-Derived Phenotypes Through Transcriptomic Enrichment.Journal: Human brain mappingIn common: JAGS, nlme, easystats, 10 other tools
- [8] doi:10.64898/2026.03.02.709173 [code]
- Corpus Callosum Dysgenesis impairs metacognition: evidence from multi-modality and multi-cohort replicationsJournal: bioRxiv (preprint)In common: JAGS, Stan, brms, 7 other tools
- [9] doi:10.1038/s41467-025-62798-4 [code]
- Distinct manifestations of excitatory-inhibitory imbalance associated with amyloid-β and tau in patients with Alzheimer’s diseaseJournal: n/aIn common: Alzheimer's / dementia, 11 references
- [10] doi:10.1126/sciadv.aec9291 [code]
- Computational mechanisms of perception in autism revealed using games inspired by rodent operant tasks.Journal: Science advancesIn common: Stan, nlme, easystats, 8 other tools
Contribute
The authors of this paper can claim it, correct its record and validate its tracing map, and the maintainers of its code (its owner, or a public member of its organization) correct what it says of their repository; anyone signed in can ask for its removal. Every request goes to OSCR's own machine, which answers it; your account page follows them.
Sign in with ORCID to claim this paper as one of its authors, correct its record or validate its tracing map: when the paper's metadata lists your ORCID iD, you are recognized at once. Maintainers of its code: sign in with GitHub, then claim the repository on your account page.
Claim this paper
Correct its record
Say what each link of this record is, remove the ones that are not the paper's, add the ones that are missing. The correction becomes a new version of the record, in its Versions section.
Validate its tracing map
You validate the map as this page shows it: 5 repositories of the authors' code, each at its verified commit and with its license, 360 scripts, and 2 matches between paragraphs and code (see the Code and Map sections). It then receives a DOI on Zenodo, with you (your ORCID iD) and OSCR as its creators; the code itself is not deposited.
The map's fingerprint: sha256:9a88427b932723cf…
Add the badge to its README
The badge links the code to this page. Copy one of these into the README of the paper's code: only you decide where it goes, and nothing is changed for you.
Markdown
[, paste the snippet at the top, then “Commit changes…” and, to review it first, “Create a new branch and start a pull request”. You open the pull request; OSCR asks for no permission.
Request its removal
To ask OSCR to remove this record, the copies of its authors' scripts or its tracing map, use the removal request page: signed in, you say who you are, what to remove and why, then review and confirm the request. Published rules decide every request (how).
Discussion, reproductions, activity
Discussion: questions and error reports about this paper and its code, from signed-in readers and its authors. It opens with sign-in.
Reproductions: reports from readers who ran the authors' code: what they reproduced, with which environment, commit and data. It opens with sign-in.
Activity: what happens around this paper: new versions of its record, its map's validation, discussions and reproductions. It opens with sign-in.
