Skip to content

Commit

Permalink
Test merge and release (#30)
Browse files Browse the repository at this point in the history
* small updates

* Update vignette.Rmd

* attempt at residuals for family="fixed"

* fix docs

* update to allow DHARMa using predictive samples

* update citation

* fix bug in loo_residuals

* fix CI

* add track_progress argument to loo_residuals

* Update vignette.Rmd

* add upper and lower bounds for optimizer

* fix residuals demo

* Update vignette.Rmd

* update plots

* fix last commit

* Update dsem.R

* fit error in DHARMa vignette example

* add `stepwise_selection(.)`

* fix notes and warnings

* add `equations_to_text`

* update vignette to show `convert_equations`

* update DFA analysis using lag-and-equations syntax

* fix bug in docs

* update make_dsem_ram to use additive-kronecker

* try to fix CI error

* fix attempt-2

* attempt-3

* change DFA vignette back

* next attempt

* another fix attempt

* update citation and pkgdown yaml

* adding cAIC ...

... which only works when using models with measurement errors

* merging add_priors to dev branch

* fix merge

* add test-priors CI check

* test fix for R-CMD-check error

* add dsemRTMB

* add reduced-rank GMRF to dsemRTMB

* adding log_prior argument to dsemRTMB

* Update test_dsemRTMB.R

* finish initial dsemRTMB

* get dsemRTMB working as package

* allow vector-valued priors

* more simulator scratch-scripts

* adding obj$simulator(.) slot

* fix dsemRTMB to work without loading locally

* add run_time slot (to compare TMB and RTMB)

* fix error in sparseMatrix stuff

* updates for merge

* try making CI happy

* another attempt at R_CMD_check

* another try

* another try to R_CMD_check

* cautious update

* make check_win_devel(.) happy

* add CI for fixed and mapped parameters

and fix issue in dsemRTMB with these

* make check_win_devel(.) happy

* Update make_matrices.R

---------

Co-authored-by: Jim Thorson <James.T.Thorson@gmail.com>
  • Loading branch information
James-Thorson-NOAA and James-Thorson authored Jan 23, 2025
1 parent 298cbb7 commit 0876fa8
Show file tree
Hide file tree
Showing 43 changed files with 2,765 additions and 116 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/pkgdown.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@
# Need help debugging build failures? Start at https://github.com/r-lib/actions#where-to-find-help
on:
push:
branches: [main, dev]
branches: [main]
pull_request:
branches: [main, dev]
branches: [main]
release:
types: [published]
workflow_dispatch:
Expand Down
4 changes: 2 additions & 2 deletions .github/workflows/test-coverage.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ jobs:
GITHUB_PAT: ${{ secrets.GITHUB_TOKEN }}

steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4

- uses: r-lib/actions/setup-r@v2
with:
Expand Down Expand Up @@ -56,7 +56,7 @@ jobs:

- name: Upload test results
if: failure()
uses: actions/upload-artifact@v3
uses: actions/upload-artifact@v4
with:
name: coverage-test-failures
path: ${{ runner.temp }}/package
14 changes: 8 additions & 6 deletions DESCRIPTION
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
Package: dsem
Type: Package
Title: Fit Dynamic Structural Equation Models
Version: 1.3.0
Date: 2024-07-18
Version: 1.4.0
Date: 2025-01-10
Authors@R:
c(person(given = "James",
family = "Thorson",
Expand All @@ -14,6 +14,10 @@ Imports:
Matrix,
sem,
igraph,
RTMB (>= 1.7.0),
ggraph,
ggplot2,
grid,
methods
Depends:
R (>= 4.0.0),
Expand All @@ -26,12 +30,10 @@ Suggests:
gridExtra,
dynlm,
MARSS,
ggplot2,
ggpubr,
ggraph,
grid,
vars,
testthat
testthat,
DHARMa
Enhances:
rstan,
tmbstan
Expand Down
38 changes: 38 additions & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
Expand Up @@ -11,32 +11,70 @@ S3method(vcov,dsem)
export(TMBAIC)
export(as_fitted_DAG)
export(as_sem)
export(cAIC)
export(classify_variables)
export(convert_equations)
export(dsem)
export(dsemRTMB)
export(dsem_control)
export(list_parameters)
export(loo_residuals)
export(make_dfa)
export(make_dsem_ram)
export(parse_path)
export(stepwise_selection)
importFrom(Matrix,Cholesky)
importFrom(Matrix,Diagonal)
importFrom(Matrix,crossprod)
importFrom(Matrix,diag)
importFrom(Matrix,drop0)
importFrom(Matrix,kronecker)
importFrom(Matrix,mat2triplet)
importFrom(Matrix,solve)
importFrom(Matrix,sparseMatrix)
importFrom(Matrix,t)
importFrom(Matrix,tcrossprod)
importFrom(RTMB,AD)
importFrom(RTMB,ADREPORT)
importFrom(RTMB,ADoverload)
importFrom(RTMB,REPORT)
importFrom(RTMB,dbinom)
importFrom(RTMB,dgamma)
importFrom(RTMB,dgmrf)
importFrom(RTMB,dnorm)
importFrom(RTMB,dpois)
importFrom(TMB,MakeADFun)
importFrom(TMB,compile)
importFrom(TMB,dynlib)
importFrom(TMB,sdreport)
importFrom(TMB,summary.sdreport)
importFrom(ggplot2,aes)
importFrom(ggraph,create_layout)
importFrom(ggraph,geom_edge_arc)
importFrom(ggraph,geom_node_text)
importFrom(ggraph,ggraph)
importFrom(ggraph,rectangle)
importFrom(ggraph,theme_graph)
importFrom(grid,arrow)
importFrom(igraph,graph_from_data_frame)
importFrom(igraph,layout_)
importFrom(igraph,plot.igraph)
importFrom(igraph,with_sugiyama)
importFrom(methods,is)
importFrom(sem,sem)
importFrom(stats,"tsp<-")
importFrom(stats,.preformat.ts)
importFrom(stats,AIC)
importFrom(stats,logLik)
importFrom(stats,na.omit)
importFrom(stats,nlminb)
importFrom(stats,optimHess)
importFrom(stats,plogis)
importFrom(stats,pnorm)
importFrom(stats,rbinom)
importFrom(stats,rgamma)
importFrom(stats,rnorm)
importFrom(stats,rpois)
importFrom(stats,sd)
importFrom(stats,simulate)
importFrom(stats,time)
Expand Down
13 changes: 13 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,16 @@
# dsem 1.4.0

* Adding option for lower and upper bounds
* Adding `stepwise_selection` for automated stepwise model selection
* Adding `plot` option to use `ggraph` as alternative to previous `igraph`
option
* Adding `convert_equations` to extend `sem::specifyEquations` and simplify
specification for large models
* Adding argument `prior_negloglike` as interface to specify Bayesian priors
and/or likelihood penalties in `dsem`
* Adding `dsemRTMB` using RTMB as interchangeable alternative to `dsem` using
TMB

# dsem 1.3.0

* Adding option to specify constant marginal variance, as alternative to existing
Expand Down
122 changes: 122 additions & 0 deletions R/cAIC.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@

#' @title Calculate conditional AIC
#'
#' @description
#' Calculates the conditional Akaike Information criterion (cAIC).
#'
#' @param object Output from \code{\link{dsem}}
#' @param what Whether to return the cAIC or the effective degrees of freedom
#' (EDF) for each group of random effects.
#'
#' @details
#' cAIC is designed to optimize the expected out-of-sample predictive
#' performance for new data that share the same random effects as the
#' in-sample (fitted) data, e.g., spatial interpolation. In this sense,
#' it should be a fast approximation to optimizing the model structure
#' based on k-fold crossvalidation.
#' By contrast, \code{AIC} calculates the
#' marginal Akaike Information Criterion, which is designed to optimize
#' expected predictive performance for new data that have new random effects,
#' e.g., extrapolation, or inference about generative parameters.
#'
#' cAIC also calculates as a byproduct the effective degrees of freedom,
#' i.e., the number of fixed effects that would have an equivalent impact on
#' model flexibility as a given random effect.
#'
#' Both cAIC and EDF are calculated using Eq. 6 of Zheng Cadigan Thorson 2024.
#'
#' Note that, for models that include profiled fixed effects, these profiles
#' are turned off.
#'
#' @return
#' Either the cAIC, or the effective degrees of freedom (EDF) by group
#' of random effects
#'
#' @references
#'
#' **Deriving the general approximation to cAIC used here**
#'
#' Zheng, N., Cadigan, N., & Thorson, J. T. (2024).
#' A note on numerical evaluation of conditional Akaike information for
#' nonlinear mixed-effects models (arXiv:2411.14185). arXiv.
#' \doi{10.48550/arXiv.2411.14185}
#'
#' **The utility of EDF to diagnose hierarchical model behavior**
#'
#' Thorson, J. T. (2024). Measuring complexity for hierarchical
#' models using effective degrees of freedom. Ecology,
#' 105(7), e4327 \doi{10.1002/ecy.4327}
#'
#' @export
cAIC <-
function( object,
what = c("cAIC","EDF") ){

what = match.arg(what)
data = object$tmb_inputs$data

# Error checks
if(any(is.na(object$tmb_inputs$map$x_tj))){
stop("cAIC is not implemented when fixing states at data using family=`fixed`")
}

# Turn on all GMRF parameters
map = object$tmb_inputs$map
map$x_tj = factor(seq_len(prod(dim(data$y_tj))))

# Make sure profile = NULL
#if( is.null(object$internal$control$profile) ){
obj = object$obj
#}else{
obj = TMB::MakeADFun( data = data,
parameters = object$internal$parhat,
random = object$tmb_inputs$random,
map = map,
profile = NULL,
DLL="dsem",
silent = TRUE )
#}

# Weights = 0 is equivalent to data = NA
data$y_tj[] = NA
# Make obj_new
obj_new = TMB::MakeADFun( data = data,
parameters = object$internal$parhat,
map = map,
random = object$tmb_inputs$random,
DLL = "dsem",
profile = NULL )

#
par = obj$env$parList()
parDataMode <- obj$env$last.par
indx = obj$env$lrandom()
q = sum(indx)
p = length(object$opt$par)

## use - for Hess because model returns negative loglikelihood;
Hess_new = -Matrix::Matrix(obj_new$env$f(parDataMode,order=1,type="ADGrad"),sparse = TRUE)
#cov_Psi_inv = -Hess_new[indx,indx]; ## this is the marginal prec mat of REs;
Hess_new = Hess_new[indx,indx]

## Joint hessian etc
Hess = -Matrix::Matrix(obj$env$f(parDataMode,order=1,type="ADGrad"),sparse = TRUE)
Hess = Hess[indx,indx]
#negEDF = diag(as.matrix(solve(ddlj.r)) %*% ddlr.r)
negEDF = Matrix::diag(Matrix::solve(Hess, Hess_new))
#

if(what=="cAIC"){
jnll = obj$env$f(parDataMode)
cnll = jnll - obj_new$env$f(parDataMode)
cAIC = 2*cnll + 2*(p+q) - 2*sum(negEDF)
return(cAIC)
}
if(what=="EDF"){
#Sdims = object$tmb_inputs$tmb_data$Sdims
#group = rep.int( seq_along(Sdims), times=Sdims )
#names(negEDF) = names(obj$env$last.par)[indx]
EDF = length(negEDF) - sum(negEDF)
return(EDF)
}
}
Loading

0 comments on commit 0876fa8

Please sign in to comment.