├── .Rbuildignore ├── .Rhistory ├── .github ├── .gitignore └── workflows │ ├── R-CMD-check.yaml │ └── pkgdown.yaml ├── .gitignore ├── DESCRIPTION ├── EMC2.Rproj ├── LICENSE.md ├── NAMESPACE ├── NEWS.md ├── R ├── EMC2-package.R ├── MRI.R ├── RcppExports.R ├── SBC.R ├── bridge_sampling.R ├── data.R ├── define_variants.R ├── design.R ├── design_plot.R ├── factor_analysis.R ├── fitting.R ├── get_type_objects.R ├── joint.R ├── likelihood.R ├── make_data.R ├── map.R ├── messaging.R ├── model_DDM.R ├── model_LBA.R ├── model_LNR.R ├── model_RDM.R ├── model_SDT.R ├── objects.R ├── plot_data.R ├── plotting.R ├── priors.R ├── s3_funcs.R ├── sampling.R ├── statistics.R ├── utils.R ├── variant_SEM.R ├── variant_blocked.R ├── variant_diag.R ├── variant_diag_gamma.R ├── variant_factor.R ├── variant_infnt_factor.R ├── variant_single.R └── variant_standard.R ├── README.md ├── data ├── forstmann.rda └── samples_LNR.rda ├── docs ├── 404.html ├── LICENSE.html ├── articles │ ├── Simulation-based-Calibration.html │ ├── Simulation-based-Calibration_files │ │ └── figure-html │ │ │ ├── unnamed-chunk-11-1.png │ │ │ ├── unnamed-chunk-13-1.png │ │ │ ├── unnamed-chunk-16-1.png │ │ │ ├── unnamed-chunk-16-2.png │ │ │ ├── unnamed-chunk-20-1.png │ │ │ ├── unnamed-chunk-20-2.png │ │ │ ├── unnamed-chunk-23-1.png │ │ │ ├── unnamed-chunk-23-2.png │ │ │ ├── unnamed-chunk-26-1.png │ │ │ ├── unnamed-chunk-26-2.png │ │ │ ├── unnamed-chunk-4-1.png │ │ │ ├── unnamed-chunk-7-1.png │ │ │ └── unnamed-chunk-8-1.png │ └── index.html ├── authors.html ├── deps │ ├── bootstrap-5.3.1 │ │ ├── bootstrap.bundle.min.js │ │ ├── bootstrap.bundle.min.js.map │ │ └── bootstrap.min.css │ ├── bootstrap-toc-1.0.1 │ │ └── bootstrap-toc.min.js │ ├── clipboard.js-2.0.11 │ │ └── clipboard.min.js │ ├── data-deps.txt │ ├── font-awesome-6.4.2 │ │ ├── css │ │ │ ├── all.css │ │ │ ├── all.min.css │ │ │ ├── v4-shims.css │ │ │ └── v4-shims.min.css │ │ └── webfonts │ │ │ ├── fa-brands-400.ttf │ │ │ ├── fa-brands-400.woff2 │ │ │ ├── fa-regular-400.ttf │ │ │ ├── fa-regular-400.woff2 │ │ │ ├── fa-solid-900.ttf │ │ │ ├── fa-solid-900.woff2 │ │ │ ├── fa-v4compatibility.ttf │ │ │ └── fa-v4compatibility.woff2 │ ├── headroom-0.11.0 │ │ ├── headroom.min.js │ │ └── jQuery.headroom.min.js │ ├── jquery-3.6.0 │ │ ├── jquery-3.6.0.js │ │ ├── jquery-3.6.0.min.js │ │ └── jquery-3.6.0.min.map │ └── search-1.0.0 │ │ ├── autocomplete.jquery.min.js │ │ ├── fuse.min.js │ │ └── mark.min.js ├── index.html ├── katex-auto.js ├── lightswitch.js ├── link.svg ├── news │ └── index.html ├── pkgdown.js ├── pkgdown.yml ├── reference │ ├── DDM.html │ ├── EMC2-package.html │ ├── EMC2.html │ ├── LBA.html │ ├── LNR.html │ ├── RDM.html │ ├── Rplot001.png │ ├── Rplot002.png │ ├── Rplot003.png │ ├── Rplot004.png │ ├── Rplot005.png │ ├── Rplot006.png │ ├── Rplot007.png │ ├── Rplot008.png │ ├── Rplot009.png │ ├── Rplot010.png │ ├── Rplot011.png │ ├── chain_n.html │ ├── check-1.png │ ├── check.html │ ├── compare.html │ ├── compare_subject.html │ ├── contr.anova.html │ ├── contr.bayes.html │ ├── contr.decreasing.html │ ├── contr.increasing.html │ ├── credible.html │ ├── design.html │ ├── ess_summary.html │ ├── fit.html │ ├── forstmann.html │ ├── gd_summary.html │ ├── get_BayesFactor.html │ ├── get_data.html │ ├── get_pars.html │ ├── hypothesis-1.png │ ├── hypothesis-2.png │ ├── hypothesis.html │ ├── index.html │ ├── init_chains.html │ ├── make_data.html │ ├── make_emc.html │ ├── make_random_effects.html │ ├── merge_chains.html │ ├── pairs_posterior-1.png │ ├── pairs_posterior-2.png │ ├── pairs_posterior.html │ ├── parameters.html │ ├── plot.emc-1.png │ ├── plot.emc-10.png │ ├── plot.emc-11.png │ ├── plot.emc-2.png │ ├── plot.emc-3.png │ ├── plot.emc-4.png │ ├── plot.emc-5.png │ ├── plot.emc-6.png │ ├── plot.emc-7.png │ ├── plot.emc-8.png │ ├── plot.emc-9.png │ ├── plot.emc.html │ ├── plot_pars-1.png │ ├── plot_pars-2.png │ ├── plot_pars-3.png │ ├── plot_pars.html │ ├── plot_relations-1.png │ ├── plot_relations.html │ ├── plot_sbc_ecdf.html │ ├── plot_sbc_hist.html │ ├── predict.emc.html │ ├── prior.html │ ├── profile_plot-1.png │ ├── profile_plot.html │ ├── recovery-1.png │ ├── recovery-2.png │ ├── recovery.html │ ├── run_bridge_sampling.html │ ├── run_emc.html │ ├── run_sbc.html │ ├── samples_LNR.html │ ├── subset.emc.html │ └── summary.emc.html ├── search.json └── sitemap.xml ├── man ├── DDM.Rd ├── DDMGNG.Rd ├── EMC2-package.Rd ├── LBA.Rd ├── LNR.Rd ├── RDM.Rd ├── SDT.Rd ├── auto_thin.Rd ├── chain_n.Rd ├── check.Rd ├── compare.Rd ├── compare_subject.Rd ├── contr.anova.Rd ├── contr.bayes.Rd ├── contr.decreasing.Rd ├── contr.increasing.Rd ├── credible.Rd ├── credint.Rd ├── design.Rd ├── ess_summary.Rd ├── fit.Rd ├── forstmann.Rd ├── gd_summary.Rd ├── get_BayesFactor.Rd ├── get_data.Rd ├── get_design.Rd ├── get_pars.Rd ├── get_prior.Rd ├── hypothesis.Rd ├── init_chains.Rd ├── make_data.Rd ├── make_emc.Rd ├── make_random_effects.Rd ├── mapped_pars.Rd ├── merge_chains.Rd ├── model_averaging.Rd ├── pairs_posterior.Rd ├── parameters.Rd ├── plot.emc.Rd ├── plot.emc.design.Rd ├── plot.emc.prior.Rd ├── plot_cdf.Rd ├── plot_density.Rd ├── plot_design.Rd ├── plot_pars.Rd ├── plot_relations.Rd ├── plot_sbc_ecdf.Rd ├── plot_sbc_hist.Rd ├── plot_stat.Rd ├── predict.emc.Rd ├── prior.Rd ├── prior_help.Rd ├── profile_plot.Rd ├── recovery.Rd ├── run_bridge_sampling.Rd ├── run_emc.Rd ├── run_sbc.Rd ├── sampled_pars.Rd ├── samples_LNR.Rd ├── subset.emc.Rd ├── summary.emc.Rd ├── summary.emc.design.Rd ├── summary.emc.prior.Rd └── update2version.Rd ├── pkgdown └── _pkgdown.yml ├── src ├── .DS_Store ├── .gitignore ├── Makevars ├── Makevars.win ├── RcppExports.cpp ├── fncs_seven.cpp ├── fncs_seven.h ├── gauss.h ├── hcubature.cpp ├── model_DDM.h ├── model_LBA.h ├── model_MRI.h ├── model_RDM.h ├── model_fMRI.h ├── model_lnr.h ├── mri.cpp ├── particle_ll.cpp ├── pdf_fncs.cpp ├── pdf_fncs.h ├── tools.cpp ├── tools.h ├── trend.h └── utility_functions.h ├── tests ├── testthat.R └── testthat │ ├── _snaps │ ├── Linux │ │ ├── fit.md │ │ └── variant_funs.md │ ├── S3.md │ ├── S3 │ │ └── prior-plot.svg │ ├── compare.md │ ├── customLL.md │ ├── joint.md │ ├── make_design.md │ ├── make_emc.md │ ├── model_functions.md │ ├── new_models.md │ ├── pairs_posterior │ │ └── pairs-plot.svg │ ├── plot_chains │ │ └── chain-plots.svg │ ├── plot_fit │ │ ├── cdf-plot-fit.svg │ │ ├── dens-plot-fit.svg │ │ └── stat-plot-fit.svg │ ├── plot_pars │ │ ├── density-alpha.svg │ │ └── density-plots.svg │ ├── plot_relations │ │ ├── plot-relations-cred.svg │ │ └── plot-relations-mean.svg │ └── profile │ │ └── profile-plot.svg │ ├── test-compare.R │ ├── test-customLL.R │ ├── test-fit.R │ ├── test-joint.R │ ├── test-make_design.R │ ├── test-make_emc.R │ ├── test-model_functions.R │ ├── test-new_models.R │ ├── test-pairs_posterior.R │ ├── test-plot_chains.R │ ├── test-plot_fit.R │ ├── test-plot_pars.R │ ├── test-plot_relations.R │ ├── test-profile.R │ ├── test-variant_funs.R │ └── test_S3.R └── vignettes ├── SBC_data ├── SBC_DDM.RData ├── SBC_DDM_single.RData ├── SBC_LBA.RData ├── SBC_LBA_single.RData ├── SBC_LNR.RData └── SBC_RDM.RData ├── Simulation-based-Calibration.Rmd └── refs.bib /.Rbuildignore: -------------------------------------------------------------------------------- 1 | ^EMC2\.Rproj$ 2 | ^\.Rproj\.user$ 3 | ^test_files$ 4 | ^LICENSE\.md$ 5 | ^\.github$ 6 | ^_pkgdown\.yml$ 7 | ^docs$ 8 | ^pkgdown$ 9 | ^\.RData$ 10 | ^\.json$ 11 | ^\.vscode$ 12 | ^paper$ 13 | ^\.settings\.json$ 14 | 15 | -------------------------------------------------------------------------------- /.github/.gitignore: -------------------------------------------------------------------------------- 1 | *.html 2 | -------------------------------------------------------------------------------- /.github/workflows/R-CMD-check.yaml: -------------------------------------------------------------------------------- 1 | # Workflow derived from https://github.com/r-lib/actions/tree/v2/examples 2 | # Need help debugging build failures? Start at https://github.com/r-lib/actions#where-to-find-help 3 | on: 4 | push: 5 | branches: [main, master, dev, testthat, testthat_system_test] 6 | pull_request: 7 | branches: [main, master, dev, testthat, testthat_system_test] 8 | 9 | name: R-CMD-check 10 | 11 | jobs: 12 | R-CMD-check: 13 | runs-on: ${{ matrix.config.os }} 14 | 15 | name: ${{ matrix.config.os }} (${{ matrix.config.r }}) 16 | 17 | strategy: 18 | fail-fast: false 19 | matrix: 20 | config: 21 | - {os: macos-latest, r: '4.4.1'} 22 | - {os: windows-latest, r: '4.4.1'} 23 | - {os: ubuntu-latest, r: '4.4.1'} 24 | 25 | env: 26 | GITHUB_PAT: ${{ secrets.GITHUB_TOKEN }} 27 | R_KEEP_PKG_SOURCE: yes 28 | 29 | steps: 30 | - uses: actions/checkout@v4 31 | 32 | - uses: r-lib/actions/setup-pandoc@v2 33 | 34 | - uses: r-lib/actions/setup-r@v2 35 | with: 36 | r-version: ${{ matrix.config.r }} 37 | http-user-agent: ${{ matrix.config.http-user-agent }} 38 | use-public-rspm: true 39 | 40 | - uses: r-lib/actions/setup-r-dependencies@v2 41 | with: 42 | extra-packages: any::rcmdcheck 43 | needs: check 44 | 45 | - uses: r-lib/actions/check-r-package@v2 46 | with: 47 | upload-snapshots: true 48 | build_args: 'c("--no-manual","--compact-vignettes=gs+qpdf")' 49 | -------------------------------------------------------------------------------- /.github/workflows/pkgdown.yaml: -------------------------------------------------------------------------------- 1 | # Workflow derived from https://github.com/r-lib/actions/tree/v2/examples 2 | # Need help debugging build failures? Start at https://github.com/r-lib/actions#where-to-find-help 3 | on: 4 | push: 5 | branches: [main, master] 6 | pull_request: 7 | branches: [main, master] 8 | release: 9 | types: [published] 10 | workflow_dispatch: 11 | 12 | name: pkgdown.yaml 13 | 14 | permissions: read-all 15 | 16 | jobs: 17 | pkgdown: 18 | runs-on: ubuntu-latest 19 | # Only restrict concurrency for non-PR jobs 20 | concurrency: 21 | group: pkgdown-${{ github.event_name != 'pull_request' || github.run_id }} 22 | env: 23 | GITHUB_PAT: ${{ secrets.GITHUB_TOKEN }} 24 | permissions: 25 | contents: write 26 | steps: 27 | - uses: actions/checkout@v4 28 | 29 | - uses: r-lib/actions/setup-pandoc@v2 30 | 31 | - uses: r-lib/actions/setup-r@v2 32 | with: 33 | use-public-rspm: true 34 | 35 | - uses: r-lib/actions/setup-r-dependencies@v2 36 | with: 37 | extra-packages: any::pkgdown, local::. 38 | needs: website 39 | 40 | - name: Build site 41 | run: pkgdown::build_site_github_pages(new_process = FALSE, install = FALSE) 42 | shell: Rscript {0} 43 | 44 | - name: Deploy to GitHub pages 🚀 45 | if: github.event_name != 'pull_request' 46 | uses: JamesIves/github-pages-deploy-action@v4.5.0 47 | with: 48 | clean: false 49 | branch: gh-pages 50 | folder: docs 51 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .Rproj.user 2 | *.Rhistory 3 | .Rhistory 4 | *.so 5 | *.o 6 | *.pdf 7 | .DS_Store 8 | docs 9 | .vscode 10 | settings.json 11 | paper -------------------------------------------------------------------------------- /DESCRIPTION: -------------------------------------------------------------------------------- 1 | Package: EMC2 2 | Title: Bayesian Hierarchical Analysis of Cognitive Models of Choice 3 | Version: 3.1.1 4 | Authors@R: 5 | c(person("Niek", "Stevenson", email = "niek.stevenson@gmail.com", 6 | role = c("aut", "cre"), comment = c(ORCID = "0000-0003-3206-7544")), 7 | person("Michelle", "Donzallaz", role = c("aut")), 8 | person("Andrew", "Heathcote", role = c("aut")), 9 | person("Steven", "Miletić", role = c("ctb")), 10 | person("Raphael", "Hartmann", role = c("ctb")), 11 | person("Karl C.", "Klauer", role=c("ctb")), 12 | person("Steven G.", "Johnson", role=c("ctb")), 13 | person("Jean M.", "Linhart", role=c("ctb")), 14 | person("Brian", "Gough", role=c("ctb")), 15 | person("Gerard", "Jungman", role=c("ctb")), 16 | person("Rudolf", "Schuerer", role=c("ctb")), 17 | person("Przemyslaw", "Sliwa", role=c("ctb")), 18 | person("Jason H.", "Stover", role=c("ctb"))) 19 | Description: Fit Bayesian (hierarchical) cognitive models 20 | using a linear modeling language interface using particle Metropolis Markov 21 | chain Monte Carlo sampling with Gibbs steps. The diffusion decision model (DDM), 22 | linear ballistic accumulator model (LBA), racing diffusion model (RDM), and the lognormal 23 | race model (LNR) are supported. Additionally, users can specify their own likelihood 24 | function and/or choose for non-hierarchical 25 | estimation, as well as for a diagonal, blocked or full multivariate normal 26 | group-level distribution to test individual differences. Prior specification 27 | is facilitated through methods that visualize the (implied) prior. 28 | A wide range of plotting functions assist in assessing model convergence and 29 | posterior inference. Models can be easily evaluated using functions 30 | that plot posterior predictions or using relative model comparison metrics 31 | such as information criteria or Bayes factors. 32 | References: Stevenson et al. (2024) . 33 | License: GPL (>= 3) 34 | URL: https://ampl-psych.github.io/EMC2/, https://github.com/ampl-psych/EMC2 35 | BugReports: https://github.com/ampl-psych/EMC2/issues 36 | Encoding: UTF-8 37 | Roxygen: list(markdown = TRUE) 38 | RoxygenNote: 7.3.2 39 | VignetteBuilder: knitr 40 | Suggests: 41 | testthat (>= 3.0.0), 42 | vdiffr, 43 | knitr, 44 | rmarkdown 45 | Config/testthat/edition: 3 46 | Imports: 47 | abind, 48 | coda, 49 | corpcor, 50 | graphics, 51 | grDevices, 52 | magic, 53 | MASS, 54 | matrixcalc, 55 | methods, 56 | msm, 57 | mvtnorm, 58 | parallel, 59 | stats, 60 | Matrix, 61 | Rcpp, 62 | Brobdingnag, 63 | corrplot, 64 | colorspace, 65 | psych, 66 | utils, 67 | lpSolve, 68 | WienR 69 | LinkingTo: 70 | Rcpp, RcppArmadillo 71 | Depends: 72 | R (>= 3.5.0) 73 | LazyData: true 74 | Config/testthat/parallel: true 75 | -------------------------------------------------------------------------------- /EMC2.Rproj: -------------------------------------------------------------------------------- 1 | Version: 1.0 2 | ProjectId: 42b229fb-3703-4f33-b607-b34debcfb187 3 | 4 | RestoreWorkspace: No 5 | SaveWorkspace: No 6 | AlwaysSaveHistory: Default 7 | 8 | EnableCodeIndexing: Yes 9 | UseSpacesForTab: Yes 10 | NumSpacesForTab: 2 11 | Encoding: UTF-8 12 | 13 | RnwWeave: Sweave 14 | LaTeX: pdfLaTeX 15 | 16 | AutoAppendNewline: Yes 17 | StripTrailingWhitespace: Yes 18 | LineEndingConversion: Posix 19 | 20 | BuildType: Package 21 | PackageUseDevtools: Yes 22 | PackageInstallArgs: --no-multiarch --with-keep.source 23 | PackageRoxygenize: rd,collate,namespace 24 | -------------------------------------------------------------------------------- /NEWS.md: -------------------------------------------------------------------------------- 1 | # EMC2 3.1.1 2 | 3 | ## New features 4 | 5 | * added thin to fit/run_emc which can either be set to TRUE to automatically thin based on ESS, or on a numeric to only keep 1/x samples 6 | 7 | * added probit/SDT model for bimanual choices 8 | 9 | ## Bug fixes 10 | 11 | * Rare bug in sampling removed 12 | 13 | * Small bug fixes in plot_data to make it more flexible 14 | 15 | * cleared up argumentation of run_emc/fit 16 | 17 | # EMC2 3.1.0 18 | 19 | ## New features 20 | 21 | * model_averaging function, which allows you to compare evidence for an effect across a set of models 22 | 23 | ## Bug fixes 24 | 25 | * Small hotfix in which creating proposals and the start of burn would 26 | sometimes fail for large number of subjects 27 | 28 | * Patched up old error in which model bounds weren't considered in data generation 29 | 30 | * Fixed error in which compare_subject would return IC for whole dataset for every subject. 31 | 32 | # EMC2 3.0.0 33 | 34 | ## New features 35 | 36 | * IMPORTANT: to keep your old samples compatible with current EMC2, run update2version() 37 | 38 | * IMPORTANT: Design and prior are now also S3 methods with their own S3 classes, see EMC2 paper 39 | 40 | * plot_fit is deprecated and has branched of into plot_density, plot_cdf and plot_stat 41 | 42 | * sampled_p_vector is deprecated and is now named sampled_pars 43 | 44 | * Added a design_plot function, which makes a plot of the proposed accumulation process 45 | 46 | * Sampling is completely reworked. Adaptive tuning of the number of particles 47 | and more stable convergence 48 | 49 | ## Bug Fixes 50 | 51 | * Fixed rare case where conditional MVN would break 52 | 53 | * Fixed bug in predict on joint models 54 | 55 | * Suppressed unwanted print statements in DDM estimation/prediction 56 | 57 | * Added more checks to a wide array of functions to ensure proper input format 58 | 59 | # EMC2 2.1.0 60 | 61 | ## New features 62 | 63 | * Added a website with vignettes, changelog and a reference 64 | 65 | * Added `run_sbc()` function to perform simulation-based calibration for a design 66 | 67 | * Added `prior_help()` to get more information on the prior for a certain `type` 68 | 69 | * Changed DDM implementation, which is faster and more accurate 70 | 71 | * Bridge sampling now also works for `type = "blocked"` 72 | 73 | ## Bug Fixes 74 | 75 | * Made bridge sampling for inverse-gamma and inverse-wishart more robust 76 | 77 | * Made `prior()` function work more generally 78 | -------------------------------------------------------------------------------- /R/EMC2-package.R: -------------------------------------------------------------------------------- 1 | #' @keywords internal 2 | "_PACKAGE" 3 | 4 | ## usethis namespace: start 5 | #' @importFrom abind abind 6 | #' @importFrom Brobdingnag as.brob 7 | #' @importFrom coda acfplot 8 | #' @importFrom coda as.mcmc 9 | #' @importFrom coda cumuplot 10 | #' @importFrom coda effectiveSize 11 | #' @importFrom coda gelman.diag 12 | #' @importFrom coda gelman.plot 13 | #' @importFrom coda mcmc 14 | #' @importFrom coda mcmc.list 15 | #' @importFrom coda traceplot 16 | #' @importFrom colorspace diverging_hcl 17 | #' @importFrom corrplot colorlegend 18 | #' @importFrom corrplot corrplot 19 | #' @importFrom graphics abline 20 | #' @importFrom graphics arrows 21 | #' @importFrom graphics hist pairs rect text 22 | #' @importFrom graphics legend 23 | #' @importFrom graphics lines 24 | #' @importFrom graphics mtext 25 | #' @importFrom graphics par 26 | #' @importFrom graphics plot.default 27 | #' @importFrom graphics points 28 | #' @importFrom graphics polygon 29 | #' @importFrom graphics segments 30 | #' @importFrom graphics title 31 | #' @importFrom grDevices adjustcolor 32 | #' @importFrom grDevices dev.off 33 | #' @importFrom grDevices pdf 34 | #' @importFrom lpSolve lp.assign 35 | #' @importFrom magic adiag 36 | #' @importFrom MASS ginv 37 | #' @importFrom Matrix nearPD 38 | #' @importFrom matrixcalc is.negative.semi.definite 39 | #' @importFrom methods is 40 | #' @importFrom mvtnorm dmvnorm 41 | #' @importFrom mvtnorm rmvnorm 42 | #' @importFrom parallel mclapply 43 | #' @importFrom psych fa.diagram 44 | #' @importFrom Rcpp sourceCpp 45 | #' @importFrom stats acf 46 | #' @importFrom stats aggregate 47 | #' @importFrom stats approxfun 48 | #' @importFrom stats as.dist 49 | #' @importFrom stats as.formula 50 | #' @importFrom stats cor 51 | #' @importFrom stats cov 52 | #' @importFrom stats cov2cor 53 | #' @importFrom stats cutree 54 | #' @importFrom stats dbinom 55 | #' @importFrom stats density 56 | #' @importFrom stats density.default 57 | #' @importFrom stats dexp 58 | #' @importFrom stats dgamma 59 | #' @importFrom stats dnorm 60 | #' @importFrom stats hclust 61 | #' @importFrom stats integrate 62 | #' @importFrom stats median 63 | #' @importFrom stats model.matrix 64 | #' @importFrom stats optimize 65 | #' @importFrom stats pexp 66 | #' @importFrom stats pnorm 67 | #' @importFrom stats predict 68 | #' @importFrom stats qbinom 69 | #' @importFrom stats qnorm 70 | #' @importFrom stats quantile 71 | #' @importFrom stats rbinom 72 | #' @importFrom stats rchisq 73 | #' @importFrom stats reshape 74 | #' @importFrom stats rexp 75 | #' @importFrom stats rgamma 76 | #' @importFrom stats rmultinom 77 | #' @importFrom stats rnorm 78 | #' @importFrom stats runif 79 | #' @importFrom stats sd 80 | #' @importFrom stats setNames 81 | #' @importFrom stats smooth.spline 82 | #' @importFrom stats terms 83 | #' @importFrom stats update 84 | #' @importFrom stats var 85 | #' @importFrom stats varimax 86 | #' @importFrom utils combn 87 | #' @importFrom WienR dWDM 88 | #' @importFrom WienR pWDM 89 | #' @importFrom WienR rWDM 90 | #' @useDynLib EMC2, .registration = TRUE 91 | ## usethis namespace: end 92 | NULL 93 | -------------------------------------------------------------------------------- /R/RcppExports.R: -------------------------------------------------------------------------------- 1 | # Generated by using Rcpp::compileAttributes() -> do not edit by hand 2 | # Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 3 | 4 | dlba <- function(t, A, b, v, sv, posdrift = TRUE) { 5 | .Call(`_EMC2_dlba`, t, A, b, v, sv, posdrift) 6 | } 7 | 8 | plba <- function(t, A, b, v, sv, posdrift = TRUE) { 9 | .Call(`_EMC2_plba`, t, A, b, v, sv, posdrift) 10 | } 11 | 12 | dWald <- function(t, v, B, A, t0) { 13 | .Call(`_EMC2_dWald`, t, v, B, A, t0) 14 | } 15 | 16 | pWald <- function(t, v, B, A, t0) { 17 | .Call(`_EMC2_pWald`, t, v, B, A, t0) 18 | } 19 | 20 | fft_convolve_equiv_cpp <- function(x, y, conj_flag = TRUE) { 21 | .Call(`_EMC2_fft_convolve_equiv_cpp`, x, y, conj_flag) 22 | } 23 | 24 | compute_gamma_diff_hrf <- function(tr, oversampling, time_length, onset, delay, undershoot, dispersion, u_dispersion, ratio) { 25 | .Call(`_EMC2_compute_gamma_diff_hrf`, tr, oversampling, time_length, onset, delay, undershoot, dispersion, u_dispersion, ratio) 26 | } 27 | 28 | compute_glover_hrf <- function(tr, oversampling, time_length, onset, delay, undershoot, dispersion, u_dispersion, ratio) { 29 | .Call(`_EMC2_compute_glover_hrf`, tr, oversampling, time_length, onset, delay, undershoot, dispersion, u_dispersion, ratio) 30 | } 31 | 32 | compute_glover_time_derivative <- function(tr, oversampling, time_length, onset, delay, undershoot, dispersion, u_dispersion, ratio, delta = 0.1) { 33 | .Call(`_EMC2_compute_glover_time_derivative`, tr, oversampling, time_length, onset, delay, undershoot, dispersion, u_dispersion, ratio, delta) 34 | } 35 | 36 | build_hrf_kernel <- function(hrf_model, tr, oversampling, time_length, onset, delay, undershoot, dispersion, u_dispersion, ratio) { 37 | .Call(`_EMC2_build_hrf_kernel`, hrf_model, tr, oversampling, time_length, onset, delay, undershoot, dispersion, u_dispersion, ratio) 38 | } 39 | 40 | compute_convolved_regressor <- function(exp_condition, hrf_model, frame_times, con_id, oversampling, min_onset, time_length, onset, delay, undershoot, dispersion, u_dispersion, ratio) { 41 | .Call(`_EMC2_compute_convolved_regressor`, exp_condition, hrf_model, frame_times, con_id, oversampling, min_onset, time_length, onset, delay, undershoot, dispersion, u_dispersion, ratio) 42 | } 43 | 44 | construct_design_matrix <- function(frame_times, events, hrf_model, min_onset, oversampling, time_length, onset, delay, undershoot, dispersion, u_dispersion, ratio, add_intercept) { 45 | .Call(`_EMC2_construct_design_matrix`, frame_times, events, hrf_model, min_onset, oversampling, time_length, onset, delay, undershoot, dispersion, u_dispersion, ratio, add_intercept) 46 | } 47 | 48 | calc_ll <- function(p_matrix, data, constants, designs, type, bounds, transforms, pretransforms, p_types, min_ll, trend) { 49 | .Call(`_EMC2_calc_ll`, p_matrix, data, constants, designs, type, bounds, transforms, pretransforms, p_types, min_ll, trend) 50 | } 51 | 52 | c_add_charvectors <- function(x, y) { 53 | .Call(`_EMC2_c_add_charvectors`, x, y) 54 | } 55 | 56 | -------------------------------------------------------------------------------- /R/joint.R: -------------------------------------------------------------------------------- 1 | 2 | single_out_joint <- function(joint_samples_list, i){ 3 | single_samples_list <- lapply(joint_samples_list, return_single_sampler, i) 4 | attr(single_samples_list[[1]]$prior, "design") <- get_design(joint_samples_list)[[i]] 5 | class(single_samples_list) <- "emc" 6 | return(single_samples_list) 7 | } 8 | 9 | return_single_sampler <- function(joint_samples, i){ 10 | par_names <- rownames(joint_samples$samples$alpha) 11 | prefix <- unique(gsub("[|].*", "", par_names))[i] 12 | idx <- grep(paste0(prefix, "|"), par_names, fixed = T) 13 | current_pars <- par_names[idx] 14 | replacement <- gsub(".*[|]", "", current_pars) 15 | single_samples <- joint_samples 16 | single_samples$samples <- base::rapply(joint_samples$samples, f = function(x) fix_single_object(x, prefix, current_pars, replacement), how = "replace") 17 | single_samples$par_names <- replacement 18 | single_samples$data <- lapply(joint_samples$data, FUN = function(x) return(x[[i]])) 19 | single_samples$model <- list(joint_samples$model[[i]]) 20 | single_samples$prior <- fix_single_prior(single_samples$prior, idx) 21 | return(single_samples) 22 | } 23 | 24 | fix_single_prior <- function(prior, idx){ 25 | out <- prior 26 | prior_names <- names(prior) 27 | for(name in prior_names){ 28 | obj <- prior[[name]] 29 | if(length(obj) > 1){ 30 | if(length(dim(obj)) == 2){ 31 | out[[name]] <- obj[idx, idx] 32 | } else{ 33 | out[[name]] <- obj[idx] 34 | } 35 | } 36 | } 37 | return(out) 38 | } 39 | 40 | 41 | fix_single_object <- function(object, prefix, current_pars, replacement){ 42 | # Recursively go through every object in the list 43 | # Check whether the names match the prefix 44 | # Unleash all my R powers 45 | dims <- dim(object) 46 | n_dims <- length(dims) 47 | if(n_dims > 1){ 48 | dim_names <- dimnames(object) 49 | for(i in 1:n_dims){ 50 | tmp_idx <- dim_names[[i]] %in% current_pars 51 | if(any(tmp_idx)){ 52 | object <- object[slice.index(object, i) %in% which(tmp_idx)] 53 | dims[i] <- sum(tmp_idx) 54 | dim(object) <- dims 55 | dim_names[[i]] <- replacement 56 | dimnames(object) <- dim_names # Give back to the community 57 | } 58 | } 59 | } 60 | return(object) 61 | } 62 | -------------------------------------------------------------------------------- /R/messaging.R: -------------------------------------------------------------------------------- 1 | accept_progress_bar <- function(min = 0, max = 1) { 2 | .val <- 0 3 | .killed <- FALSE 4 | .nb <- 0L 5 | .pc <- -1L # This ensures the initial value is displayed 6 | .ex <- 0 7 | component <- list( 8 | pchar = "=", 9 | prog_start = " |", 10 | prog_end = "| ", 11 | percent = "%3d%%", 12 | acc_sep = " | ", 13 | acc_msg = "New(%3d%%)" 14 | ) 15 | width <- c(1,2,2,4,3,9) # previous code was giving warnings 16 | width <- split(unname(width), names(component)) 17 | width$extras <- sum(unlist(width)) - width$pchar 18 | width$term <- getOption("width") 19 | width$progress <- trunc((width$term - width$extras) / width$pchar) 20 | 21 | if (max <= min) stop("must have 'max' > 'min'") 22 | 23 | # Handles an update to the progress bar 24 | up <- function(value, extra = 0) { 25 | if (!is.finite(value) || value < min || value > max) { 26 | return() 27 | } 28 | .val <<- value 29 | nb <- round(width$progress * (value - min) / (max - min)) 30 | pc <- round(100 * (value - min) / (max - min)) 31 | extra <- round(100 * extra) 32 | if (nb == .nb && pc == .pc && .ex == extra) { 33 | return() 34 | } 35 | # Clear the current progress bar 36 | cat(paste0("\r", strrep(" ", width$term))) 37 | # Write the updated progress bar 38 | cat(paste0( 39 | "\r", 40 | component$prog_start, 41 | strrep(component$pchar, nb), 42 | strrep(" ", width$pchar * (width$progress - nb)), 43 | component$prog_end, 44 | sprintf(component$percent, pc), 45 | component$acc_sep, 46 | sprintf(component$acc_msg, extra))) 47 | utils::flush.console() 48 | .nb <<- nb 49 | .pc <<- pc 50 | .ex <<- extra 51 | } 52 | 53 | get_value <- function() .val 54 | kill <- function() { 55 | if (!.killed) { 56 | cat("\n") 57 | utils::flush.console() 58 | .killed <<- TRUE 59 | } 60 | } 61 | up(0) # will check if in range 62 | 63 | structure(list(getVal = get_value, up = up, kill = kill), 64 | class = c("accept_progress_bar", "txtProgressBar")) 65 | } 66 | 67 | update_progress_bar <- function(pb, value, extra = 0) { 68 | if (!inherits(pb, "txtProgressBar")) { 69 | stop(gettextf( 70 | "'pb' is not from class %s", 71 | dQuote("txtProgressBar") 72 | ), 73 | domain = NA 74 | ) 75 | } 76 | oldval <- pb$getVal() 77 | pb$up(value, extra) 78 | invisible(oldval) 79 | } 80 | 81 | accept_rate <- function(pmwgs, window_size = 200) { 82 | n_samples <- pmwgs$samples$idx 83 | if (is.null(n_samples) || n_samples < 3) { 84 | return(array(0, dim(pmwgs$samples$alpha)[2])) 85 | } 86 | if (n_samples <= window_size) { 87 | start <- 1 88 | end <- n_samples 89 | } else { 90 | start <- n_samples - window_size + 1 91 | end <- n_samples 92 | } 93 | vals <- pmwgs$samples$alpha[1, , start:end] 94 | if (is.null(dim(vals))) return(mean(diff(vals)!=0)) 95 | apply( 96 | apply(vals, 1, diff) != 0, # If diff != 0 97 | 2, 98 | mean 99 | ) 100 | } 101 | -------------------------------------------------------------------------------- /R/model_SDT.R: -------------------------------------------------------------------------------- 1 | 2 | pPROBIT <- function(lt,ut,pars) 3 | # probability between lt and ut 4 | { 5 | pnorm(ut,mean=pars[,"mean"],sd=pars[,"sd"]) - pnorm(lt,mean=pars[,"mean"],sd=pars[,"sd"]) 6 | } 7 | 8 | 9 | rPROBIT <- function(lR,pars,p_types=c("mean","sd","threshold"),lt=-Inf) 10 | # lR is an empty latent response factor lR with one level for response. 11 | # pars is a matrix of corresponding parameter values named as in p_types 12 | # pars must be sorted so accumulators and parameter for each trial are in 13 | # contiguous rows. 14 | 15 | { 16 | if (!all(p_types %in% dimnames(pars)[[2]])) 17 | stop("pars must have columns ",paste(p_types,collapse = " ")) 18 | nr <- length(levels(lR)) # Number of responses 19 | n <- dim(pars)[1]/nr # Number of simulated trials 20 | first <- seq(1,dim(pars)[1]-nr+1,length.out=n) # pick out mean and sd 21 | threshold <- matrix(pars[,"threshold"],nrow=nr) # format thresholds 22 | threshold[dim(threshold)[1],] <- Inf 23 | pmat <- rbind(rnorm(n,pars[first,"mean"],pars[first,"sd"]), # sample normal 24 | rep(lt,dim(threshold)[2]),threshold) # lt ... ut 25 | pmat[dim(pmat)[1],] <- Inf 26 | R <- factor(apply(pmat,2,function(x){.bincode(x[1],x[-1])}), 27 | levels=1:length(levels(lR)),labels=levels(lR)) 28 | cbind.data.frame(R=R,rt=NA) 29 | } 30 | 31 | #' Gaussian Signal Detection Theory Model for Binary Responses 32 | #' 33 | #' Discrete binary choice based on continuous Gaussian latent, with no rt (rt 34 | #' must be set to NA in data). 35 | #' 36 | #' Model parameters are: 37 | #' mean (unbounded) 38 | #' sd (log scale) and 39 | #' threshold (unbounded). 40 | #' 41 | #' For identifiability in one condition two parameters must be fixed 42 | #' (conventionally mean=0 and sd = 1). When used with data that records only 43 | #' accuracy (so reponse bias cannot be evaluated) a single threshold must be 44 | #' assumed and fixed (e.g., threshold = 0). 45 | #' 46 | #' At present this model is not fully implemented in C, but as its likelihood 47 | #' requires only pnorm evaluation it is quite fast. 48 | #' 49 | #' @return A model list with all the necessary functions to sample 50 | #' @examples 51 | #' dprobit <- design(Rlevels = c("left","right"), 52 | #' factors=list(subjects=1,S=c("left","right")), 53 | #' formula=list(mean ~ 0+S, sd ~ 1,threshold ~ 1), 54 | #' matchfun=function(d)d$S==d$lR, 55 | #' constants=c(sd=log(1),threshold=0), 56 | #' model=SDT) 57 | #' 58 | #' p_vector <- sampled_pars(dprobit) 59 | #' @export 60 | 61 | SDT <- function(){ 62 | list( 63 | type="SDT", 64 | p_types=c("mean" = 0,"sd" = log(1),"threshold" = 0), 65 | # Trial dependent parameter transform 66 | transform=list(func=c(mean = "identity",sd = "exp",threshold="identity")), 67 | bound=list(minmax=cbind(mean=c(-Inf,Inf),sd = c(0, Inf), threshold=c(-Inf,Inf))), 68 | Ttransform = function(pars,dadm) { 69 | pars 70 | }, 71 | # Random function for discrete choices 72 | rfun=function(lR=NULL,pars) { 73 | rPROBIT(lR,pars) 74 | }, 75 | # probability of choice between lower and upper thresholds (lt & ut) 76 | pfun=function(lt,ut,pars) pPROBIT(lt,ut,pars), 77 | # quantile function, p = probability, used in making linear ROCs 78 | qfun=function(p) qnorm(p), 79 | # Likelihood, lb is lower bound threshold for first response 80 | log_likelihood=function(pars,dadm,model,min_ll=log(1e-10)){ 81 | log_likelihood_sdt(pars=pars, dadm = dadm, model = model, min_ll = min_ll, lb=-Inf) 82 | }) 83 | } 84 | -------------------------------------------------------------------------------- /R/utils.R: -------------------------------------------------------------------------------- 1 | # 2 | # augment <- function(s,da,design) 3 | # # Adds attributes to augmented data 4 | # # learn: empty array for Q values with dim = choice alternative (low,high) x 5 | # # stimulus x trials (max across stimuli) 6 | # # index: look up (row number) for stimuli in da, a matrix dim = max trials x 7 | # # stimulus matrix (rows for each choice alternative contiguous) 8 | # { 9 | # if (!is.null(design$adapt$stimulus)) { 10 | # targets <- design$adapt$stimulus$targets 11 | # par <- design$adapt$stimulus$output_name 12 | # maxn <- max(sapply(dimnames(targets)[[1]],function(x){table(da[da$subjects==s,x])})) 13 | # # da index x stimulus 14 | # out <- sapply(targets[1,],getIndex,cname=dimnames(targets)[[1]][1], 15 | # da=da[da$subjects==s,],maxn=maxn) 16 | # stimulus <- list(index=out) 17 | # # accumulator x stimulus x trials 18 | # stimulus$learn <- array(NA,dim=c(dim(targets),maxn/dim(targets)[1]), 19 | # dimnames=list(rownames(targets),targets[1,],NULL)) 20 | # stimulus$targets <- targets 21 | # stimulus$par <- par 22 | # } # add other types here 23 | # list(stimulus=stimulus) 24 | # } 25 | # 26 | # getIndex <- function(typei,cname,da,maxn) { 27 | # out <- which(da[,cname]==typei) 28 | # c(out,rep(NA,maxn-length(out))) 29 | # } 30 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # EMC2: Extended Models of Choice 2: 2 | 3 | The `R` package `EMC2` provides tools to perform Bayesian hierarchical analyses of the following cognitive models: Diffusion Decision Model (DDM), Linear Ballistic Accumulator Model (LBA), Racing Diffusion Model (RDM), and Lognormal Racing Model (LNR). Specifically, the package provides functionality for specifying individual model designs, estimating the models, examining convergence as well as model fit through posterior prediction methods. It also includes various plotting functions and relative model comparison methods such as Bayes factors. In addition, users can specify their own likelihood function and perform non-hierarchical estimation. The package uses particle metropolis Markov chain Monte Carlo sampling. For hierarchical models, it uses efficient Gibbs sampling at the population level and supports a variety of covariance structures, extending the work of Gunawan and colleagues (2020). 4 | 5 | ## Installation 6 | 7 | To install the R package, and its dependencies you can use 8 | 9 | `install.packages("EMC2")` 10 | 11 | Or for the development version: 12 | 13 | `remotes::install_github("ampl-psych/EMC2",dependencies=TRUE)` 14 | 15 | ## Workflow Overview 16 | 17 | Pictured below are the four phases of an `EMC2`cognitive model analysis with associated functions:. 18 | 19 |   20 | 21 | workflow-emc2 22 | 23 |   24 | 25 | For details, please see: 26 | 27 | Stevenson, N., Donzallaz, M. C., Innes, R. J., Forstmann, B., Matzke, D., & Heathcote, A. (2024, January 30). EMC2: An R Package for cognitive models of choice. https://doi.org/10.31234/osf.io/2e4dq 28 | 29 | ## Bug Reports, Contributing, and Feature Requests 30 | 31 | If you come across any bugs, or have ideas for extensions of `EMC2`, you can add them as an issue [here](https://github.com/ampl-psych/EMC2/issues). If you would like to contribute to the package's code, please submit a pull request. 32 | 33 | ## References 34 | 35 | Stevenson, N., Donzallaz, M. C., Innes, R. J., Forstmann, B., Matzke, D., & Heathcote, A. (2024, January 30). EMC2: An R Package for cognitive models of choice. https://doi.org/10.31234/osf.io/2e4dq 36 | 37 | Gunawan, D., Hawkins, G. E., Tran, M. N., Kohn, R., & Brown, S. D. (2020). New estimation approaches for the hierarchical Linear Ballistic Accumulator model. *Journal of Mathematical Psychology, 96,* 102368. https://doi.org/10.1016/j.jmp.2020.102368 38 | 39 | 40 | 41 | 42 | [![R-CMD-check](https://github.com/ampl-psych/EMC2/actions/workflows/R-CMD-check.yaml/badge.svg)](https://github.com/ampl-psych/EMC2/actions/workflows/R-CMD-check.yaml) 43 | 44 | 45 | -------------------------------------------------------------------------------- /data/forstmann.rda: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ampl-psych/EMC2/5a23740a614054ca634c11d12fd06d3def16e6aa/data/forstmann.rda -------------------------------------------------------------------------------- /data/samples_LNR.rda: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ampl-psych/EMC2/5a23740a614054ca634c11d12fd06d3def16e6aa/data/samples_LNR.rda -------------------------------------------------------------------------------- /docs/articles/Simulation-based-Calibration_files/figure-html/unnamed-chunk-11-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ampl-psych/EMC2/5a23740a614054ca634c11d12fd06d3def16e6aa/docs/articles/Simulation-based-Calibration_files/figure-html/unnamed-chunk-11-1.png -------------------------------------------------------------------------------- /docs/articles/Simulation-based-Calibration_files/figure-html/unnamed-chunk-13-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ampl-psych/EMC2/5a23740a614054ca634c11d12fd06d3def16e6aa/docs/articles/Simulation-based-Calibration_files/figure-html/unnamed-chunk-13-1.png -------------------------------------------------------------------------------- /docs/articles/Simulation-based-Calibration_files/figure-html/unnamed-chunk-16-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ampl-psych/EMC2/5a23740a614054ca634c11d12fd06d3def16e6aa/docs/articles/Simulation-based-Calibration_files/figure-html/unnamed-chunk-16-1.png -------------------------------------------------------------------------------- /docs/articles/Simulation-based-Calibration_files/figure-html/unnamed-chunk-16-2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ampl-psych/EMC2/5a23740a614054ca634c11d12fd06d3def16e6aa/docs/articles/Simulation-based-Calibration_files/figure-html/unnamed-chunk-16-2.png -------------------------------------------------------------------------------- /docs/articles/Simulation-based-Calibration_files/figure-html/unnamed-chunk-20-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ampl-psych/EMC2/5a23740a614054ca634c11d12fd06d3def16e6aa/docs/articles/Simulation-based-Calibration_files/figure-html/unnamed-chunk-20-1.png -------------------------------------------------------------------------------- /docs/articles/Simulation-based-Calibration_files/figure-html/unnamed-chunk-20-2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ampl-psych/EMC2/5a23740a614054ca634c11d12fd06d3def16e6aa/docs/articles/Simulation-based-Calibration_files/figure-html/unnamed-chunk-20-2.png -------------------------------------------------------------------------------- /docs/articles/Simulation-based-Calibration_files/figure-html/unnamed-chunk-23-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ampl-psych/EMC2/5a23740a614054ca634c11d12fd06d3def16e6aa/docs/articles/Simulation-based-Calibration_files/figure-html/unnamed-chunk-23-1.png -------------------------------------------------------------------------------- /docs/articles/Simulation-based-Calibration_files/figure-html/unnamed-chunk-23-2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ampl-psych/EMC2/5a23740a614054ca634c11d12fd06d3def16e6aa/docs/articles/Simulation-based-Calibration_files/figure-html/unnamed-chunk-23-2.png -------------------------------------------------------------------------------- /docs/articles/Simulation-based-Calibration_files/figure-html/unnamed-chunk-26-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ampl-psych/EMC2/5a23740a614054ca634c11d12fd06d3def16e6aa/docs/articles/Simulation-based-Calibration_files/figure-html/unnamed-chunk-26-1.png -------------------------------------------------------------------------------- /docs/articles/Simulation-based-Calibration_files/figure-html/unnamed-chunk-26-2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ampl-psych/EMC2/5a23740a614054ca634c11d12fd06d3def16e6aa/docs/articles/Simulation-based-Calibration_files/figure-html/unnamed-chunk-26-2.png -------------------------------------------------------------------------------- /docs/articles/Simulation-based-Calibration_files/figure-html/unnamed-chunk-4-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ampl-psych/EMC2/5a23740a614054ca634c11d12fd06d3def16e6aa/docs/articles/Simulation-based-Calibration_files/figure-html/unnamed-chunk-4-1.png -------------------------------------------------------------------------------- /docs/articles/Simulation-based-Calibration_files/figure-html/unnamed-chunk-7-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ampl-psych/EMC2/5a23740a614054ca634c11d12fd06d3def16e6aa/docs/articles/Simulation-based-Calibration_files/figure-html/unnamed-chunk-7-1.png -------------------------------------------------------------------------------- /docs/articles/Simulation-based-Calibration_files/figure-html/unnamed-chunk-8-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ampl-psych/EMC2/5a23740a614054ca634c11d12fd06d3def16e6aa/docs/articles/Simulation-based-Calibration_files/figure-html/unnamed-chunk-8-1.png -------------------------------------------------------------------------------- /docs/deps/bootstrap-toc-1.0.1/bootstrap-toc.min.js: -------------------------------------------------------------------------------- 1 | /*! 2 | * Bootstrap Table of Contents v1.0.1 (http://afeld.github.io/bootstrap-toc/) 3 | * Copyright 2015 Aidan Feldman 4 | * Licensed under MIT (https://github.com/afeld/bootstrap-toc/blob/gh-pages/LICENSE.md) */ 5 | !function(a){"use strict";window.Toc={helpers:{findOrFilter:function(e,t){var n=e.find(t);return e.filter(t).add(n).filter(":not([data-toc-skip])")},generateUniqueIdBase:function(e){return a(e).text().trim().replace(/\'/gi,"").replace(/[& +$,:;=?@"#{}|^~[`%!'<>\]\.\/\(\)\*\\\n\t\b\v]/g,"-").replace(/-{2,}/g,"-").substring(0,64).replace(/^-+|-+$/gm,"").toLowerCase()||e.tagName.toLowerCase()},generateUniqueId:function(e){for(var t=this.generateUniqueIdBase(e),n=0;;n++){var r=t;if(0')},createChildNavList:function(e){var t=this.createNavList();return e.append(t),t},generateNavEl:function(e,t){var n=a('');n.attr("href","#"+e),n.text(t);var r=a("
  • ");return r.append(n),r},generateNavItem:function(e){var t=this.generateAnchor(e),n=a(e),r=n.data("toc-text")||n.text();return this.generateNavEl(t,r)},getTopLevel:function(e){for(var t=1;t<=6;t++){if(1 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /docs/deps/font-awesome-6.4.2/webfonts/fa-brands-400.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ampl-psych/EMC2/5a23740a614054ca634c11d12fd06d3def16e6aa/docs/deps/font-awesome-6.4.2/webfonts/fa-brands-400.ttf -------------------------------------------------------------------------------- /docs/deps/font-awesome-6.4.2/webfonts/fa-brands-400.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ampl-psych/EMC2/5a23740a614054ca634c11d12fd06d3def16e6aa/docs/deps/font-awesome-6.4.2/webfonts/fa-brands-400.woff2 -------------------------------------------------------------------------------- /docs/deps/font-awesome-6.4.2/webfonts/fa-regular-400.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ampl-psych/EMC2/5a23740a614054ca634c11d12fd06d3def16e6aa/docs/deps/font-awesome-6.4.2/webfonts/fa-regular-400.ttf -------------------------------------------------------------------------------- /docs/deps/font-awesome-6.4.2/webfonts/fa-regular-400.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ampl-psych/EMC2/5a23740a614054ca634c11d12fd06d3def16e6aa/docs/deps/font-awesome-6.4.2/webfonts/fa-regular-400.woff2 -------------------------------------------------------------------------------- /docs/deps/font-awesome-6.4.2/webfonts/fa-solid-900.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ampl-psych/EMC2/5a23740a614054ca634c11d12fd06d3def16e6aa/docs/deps/font-awesome-6.4.2/webfonts/fa-solid-900.ttf -------------------------------------------------------------------------------- /docs/deps/font-awesome-6.4.2/webfonts/fa-solid-900.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ampl-psych/EMC2/5a23740a614054ca634c11d12fd06d3def16e6aa/docs/deps/font-awesome-6.4.2/webfonts/fa-solid-900.woff2 -------------------------------------------------------------------------------- /docs/deps/font-awesome-6.4.2/webfonts/fa-v4compatibility.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ampl-psych/EMC2/5a23740a614054ca634c11d12fd06d3def16e6aa/docs/deps/font-awesome-6.4.2/webfonts/fa-v4compatibility.ttf -------------------------------------------------------------------------------- /docs/deps/font-awesome-6.4.2/webfonts/fa-v4compatibility.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ampl-psych/EMC2/5a23740a614054ca634c11d12fd06d3def16e6aa/docs/deps/font-awesome-6.4.2/webfonts/fa-v4compatibility.woff2 -------------------------------------------------------------------------------- /docs/deps/headroom-0.11.0/jQuery.headroom.min.js: -------------------------------------------------------------------------------- 1 | /*! 2 | * headroom.js v0.9.4 - Give your page some headroom. Hide your header until you need it 3 | * Copyright (c) 2017 Nick Williams - http://wicky.nillia.ms/headroom.js 4 | * License: MIT 5 | */ 6 | 7 | !function(a){a&&(a.fn.headroom=function(b){return this.each(function(){var c=a(this),d=c.data("headroom"),e="object"==typeof b&&b;e=a.extend(!0,{},Headroom.options,e),d||(d=new Headroom(this,e),d.init(),c.data("headroom",d)),"string"==typeof b&&(d[b](),"destroy"===b&&c.removeData("headroom"))})},a("[data-headroom]").each(function(){var b=a(this);b.headroom(b.data())}))}(window.Zepto||window.jQuery); -------------------------------------------------------------------------------- /docs/katex-auto.js: -------------------------------------------------------------------------------- 1 | // https://github.com/jgm/pandoc/blob/29fa97ab96b8e2d62d48326e1b949a71dc41f47a/src/Text/Pandoc/Writers/HTML.hs#L332-L345 2 | document.addEventListener("DOMContentLoaded", function () { 3 | var mathElements = document.getElementsByClassName("math"); 4 | var macros = []; 5 | for (var i = 0; i < mathElements.length; i++) { 6 | var texText = mathElements[i].firstChild; 7 | if (mathElements[i].tagName == "SPAN") { 8 | katex.render(texText.data, mathElements[i], { 9 | displayMode: mathElements[i].classList.contains("display"), 10 | throwOnError: false, 11 | macros: macros, 12 | fleqn: false 13 | }); 14 | }}}); 15 | -------------------------------------------------------------------------------- /docs/lightswitch.js: -------------------------------------------------------------------------------- 1 | 2 | /*! 3 | * Color mode toggler for Bootstrap's docs (https://getbootstrap.com/) 4 | * Copyright 2011-2023 The Bootstrap Authors 5 | * Licensed under the Creative Commons Attribution 3.0 Unported License. 6 | * Updates for {pkgdown} by the {bslib} authors, also licensed under CC-BY-3.0. 7 | */ 8 | 9 | const getStoredTheme = () => localStorage.getItem('theme') 10 | const setStoredTheme = theme => localStorage.setItem('theme', theme) 11 | 12 | const getPreferredTheme = () => { 13 | const storedTheme = getStoredTheme() 14 | if (storedTheme) { 15 | return storedTheme 16 | } 17 | 18 | return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light' 19 | } 20 | 21 | const setTheme = theme => { 22 | if (theme === 'auto') { 23 | document.documentElement.setAttribute('data-bs-theme', (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light')) 24 | } else { 25 | document.documentElement.setAttribute('data-bs-theme', theme) 26 | } 27 | } 28 | 29 | function bsSetupThemeToggle () { 30 | 'use strict' 31 | 32 | const showActiveTheme = (theme, focus = false) => { 33 | var activeLabel, activeIcon; 34 | 35 | document.querySelectorAll('[data-bs-theme-value]').forEach(element => { 36 | const buttonTheme = element.getAttribute('data-bs-theme-value') 37 | const isActive = buttonTheme == theme 38 | 39 | element.classList.toggle('active', isActive) 40 | element.setAttribute('aria-pressed', isActive) 41 | 42 | if (isActive) { 43 | activeLabel = element.textContent; 44 | activeIcon = element.querySelector('span').classList.value; 45 | } 46 | }) 47 | 48 | const themeSwitcher = document.querySelector('#dropdown-lightswitch') 49 | if (!themeSwitcher) { 50 | return 51 | } 52 | 53 | themeSwitcher.setAttribute('aria-label', activeLabel) 54 | themeSwitcher.querySelector('span').classList.value = activeIcon; 55 | 56 | if (focus) { 57 | themeSwitcher.focus() 58 | } 59 | } 60 | 61 | window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => { 62 | const storedTheme = getStoredTheme() 63 | if (storedTheme !== 'light' && storedTheme !== 'dark') { 64 | setTheme(getPreferredTheme()) 65 | } 66 | }) 67 | 68 | window.addEventListener('DOMContentLoaded', () => { 69 | showActiveTheme(getPreferredTheme()) 70 | 71 | document 72 | .querySelectorAll('[data-bs-theme-value]') 73 | .forEach(toggle => { 74 | toggle.addEventListener('click', () => { 75 | const theme = toggle.getAttribute('data-bs-theme-value') 76 | setTheme(theme) 77 | setStoredTheme(theme) 78 | showActiveTheme(theme, true) 79 | }) 80 | }) 81 | }) 82 | } 83 | 84 | setTheme(getPreferredTheme()); 85 | bsSetupThemeToggle(); 86 | -------------------------------------------------------------------------------- /docs/link.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | 8 | 12 | 13 | -------------------------------------------------------------------------------- /docs/pkgdown.yml: -------------------------------------------------------------------------------- 1 | pandoc: '3.2' 2 | pkgdown: 2.1.0 3 | pkgdown_sha: ~ 4 | articles: 5 | Simulation-based-Calibration: Simulation-based-Calibration.html 6 | last_built: 2025-04-07T00:51Z 7 | urls: 8 | reference: https://ampl-psych.github.io/EMC2/reference 9 | article: https://ampl-psych.github.io/EMC2/articles 10 | -------------------------------------------------------------------------------- /docs/reference/EMC2.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /docs/reference/Rplot001.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ampl-psych/EMC2/5a23740a614054ca634c11d12fd06d3def16e6aa/docs/reference/Rplot001.png -------------------------------------------------------------------------------- /docs/reference/Rplot002.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ampl-psych/EMC2/5a23740a614054ca634c11d12fd06d3def16e6aa/docs/reference/Rplot002.png -------------------------------------------------------------------------------- /docs/reference/Rplot003.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ampl-psych/EMC2/5a23740a614054ca634c11d12fd06d3def16e6aa/docs/reference/Rplot003.png -------------------------------------------------------------------------------- /docs/reference/Rplot004.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ampl-psych/EMC2/5a23740a614054ca634c11d12fd06d3def16e6aa/docs/reference/Rplot004.png -------------------------------------------------------------------------------- /docs/reference/Rplot005.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ampl-psych/EMC2/5a23740a614054ca634c11d12fd06d3def16e6aa/docs/reference/Rplot005.png -------------------------------------------------------------------------------- /docs/reference/Rplot006.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ampl-psych/EMC2/5a23740a614054ca634c11d12fd06d3def16e6aa/docs/reference/Rplot006.png -------------------------------------------------------------------------------- /docs/reference/Rplot007.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ampl-psych/EMC2/5a23740a614054ca634c11d12fd06d3def16e6aa/docs/reference/Rplot007.png -------------------------------------------------------------------------------- /docs/reference/Rplot008.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ampl-psych/EMC2/5a23740a614054ca634c11d12fd06d3def16e6aa/docs/reference/Rplot008.png -------------------------------------------------------------------------------- /docs/reference/Rplot009.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ampl-psych/EMC2/5a23740a614054ca634c11d12fd06d3def16e6aa/docs/reference/Rplot009.png -------------------------------------------------------------------------------- /docs/reference/Rplot010.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ampl-psych/EMC2/5a23740a614054ca634c11d12fd06d3def16e6aa/docs/reference/Rplot010.png -------------------------------------------------------------------------------- /docs/reference/Rplot011.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ampl-psych/EMC2/5a23740a614054ca634c11d12fd06d3def16e6aa/docs/reference/Rplot011.png -------------------------------------------------------------------------------- /docs/reference/check-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ampl-psych/EMC2/5a23740a614054ca634c11d12fd06d3def16e6aa/docs/reference/check-1.png -------------------------------------------------------------------------------- /docs/reference/hypothesis-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ampl-psych/EMC2/5a23740a614054ca634c11d12fd06d3def16e6aa/docs/reference/hypothesis-1.png -------------------------------------------------------------------------------- /docs/reference/hypothesis-2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ampl-psych/EMC2/5a23740a614054ca634c11d12fd06d3def16e6aa/docs/reference/hypothesis-2.png -------------------------------------------------------------------------------- /docs/reference/pairs_posterior-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ampl-psych/EMC2/5a23740a614054ca634c11d12fd06d3def16e6aa/docs/reference/pairs_posterior-1.png -------------------------------------------------------------------------------- /docs/reference/pairs_posterior-2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ampl-psych/EMC2/5a23740a614054ca634c11d12fd06d3def16e6aa/docs/reference/pairs_posterior-2.png -------------------------------------------------------------------------------- /docs/reference/plot.emc-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ampl-psych/EMC2/5a23740a614054ca634c11d12fd06d3def16e6aa/docs/reference/plot.emc-1.png -------------------------------------------------------------------------------- /docs/reference/plot.emc-10.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ampl-psych/EMC2/5a23740a614054ca634c11d12fd06d3def16e6aa/docs/reference/plot.emc-10.png -------------------------------------------------------------------------------- /docs/reference/plot.emc-11.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ampl-psych/EMC2/5a23740a614054ca634c11d12fd06d3def16e6aa/docs/reference/plot.emc-11.png -------------------------------------------------------------------------------- /docs/reference/plot.emc-2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ampl-psych/EMC2/5a23740a614054ca634c11d12fd06d3def16e6aa/docs/reference/plot.emc-2.png -------------------------------------------------------------------------------- /docs/reference/plot.emc-3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ampl-psych/EMC2/5a23740a614054ca634c11d12fd06d3def16e6aa/docs/reference/plot.emc-3.png -------------------------------------------------------------------------------- /docs/reference/plot.emc-4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ampl-psych/EMC2/5a23740a614054ca634c11d12fd06d3def16e6aa/docs/reference/plot.emc-4.png -------------------------------------------------------------------------------- /docs/reference/plot.emc-5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ampl-psych/EMC2/5a23740a614054ca634c11d12fd06d3def16e6aa/docs/reference/plot.emc-5.png -------------------------------------------------------------------------------- /docs/reference/plot.emc-6.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ampl-psych/EMC2/5a23740a614054ca634c11d12fd06d3def16e6aa/docs/reference/plot.emc-6.png -------------------------------------------------------------------------------- /docs/reference/plot.emc-7.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ampl-psych/EMC2/5a23740a614054ca634c11d12fd06d3def16e6aa/docs/reference/plot.emc-7.png -------------------------------------------------------------------------------- /docs/reference/plot.emc-8.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ampl-psych/EMC2/5a23740a614054ca634c11d12fd06d3def16e6aa/docs/reference/plot.emc-8.png -------------------------------------------------------------------------------- /docs/reference/plot.emc-9.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ampl-psych/EMC2/5a23740a614054ca634c11d12fd06d3def16e6aa/docs/reference/plot.emc-9.png -------------------------------------------------------------------------------- /docs/reference/plot_pars-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ampl-psych/EMC2/5a23740a614054ca634c11d12fd06d3def16e6aa/docs/reference/plot_pars-1.png -------------------------------------------------------------------------------- /docs/reference/plot_pars-2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ampl-psych/EMC2/5a23740a614054ca634c11d12fd06d3def16e6aa/docs/reference/plot_pars-2.png -------------------------------------------------------------------------------- /docs/reference/plot_pars-3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ampl-psych/EMC2/5a23740a614054ca634c11d12fd06d3def16e6aa/docs/reference/plot_pars-3.png -------------------------------------------------------------------------------- /docs/reference/plot_relations-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ampl-psych/EMC2/5a23740a614054ca634c11d12fd06d3def16e6aa/docs/reference/plot_relations-1.png -------------------------------------------------------------------------------- /docs/reference/profile_plot-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ampl-psych/EMC2/5a23740a614054ca634c11d12fd06d3def16e6aa/docs/reference/profile_plot-1.png -------------------------------------------------------------------------------- /docs/reference/recovery-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ampl-psych/EMC2/5a23740a614054ca634c11d12fd06d3def16e6aa/docs/reference/recovery-1.png -------------------------------------------------------------------------------- /docs/reference/recovery-2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ampl-psych/EMC2/5a23740a614054ca634c11d12fd06d3def16e6aa/docs/reference/recovery-2.png -------------------------------------------------------------------------------- /man/DDM.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/model_DDM.R 3 | \name{DDM} 4 | \alias{DDM} 5 | \title{The Diffusion Decision Model} 6 | \usage{ 7 | DDM() 8 | } 9 | \value{ 10 | A model list with all the necessary functions for EMC2 to sample 11 | } 12 | \description{ 13 | Model file to estimate the Diffusion Decision Model (DDM) in EMC2. 14 | } 15 | \details{ 16 | Model files are almost exclusively used in \code{design()}. 17 | 18 | Default values are used for all parameters that are not explicitly listed in the \code{formula} 19 | argument of \code{design()}.They can also be accessed with \code{DDM()$p_types}.\tabular{llllll}{ 20 | \strong{Parameter} \tab \strong{Transform} \tab \strong{Natural scale} \tab \strong{Default} \tab \strong{Mapping} \tab \strong{Interpretation} \cr 21 | \emph{v} \tab - \tab [-Inf, Inf] \tab 1 \tab \tab Mean evidence-accumulation rate (drift rate) \cr 22 | \emph{a} \tab log \tab [0, Inf] \tab log(1) \tab \tab Boundary separation \cr 23 | \emph{t0} \tab log \tab [0, Inf] \tab log(0) \tab \tab Non-decision time \cr 24 | \emph{s} \tab log \tab [0, Inf] \tab log(1) \tab \tab Within-trial standard deviation of drift rate \cr 25 | \emph{Z} \tab probit \tab [0, 1] \tab qnorm(0.5) \tab \emph{z} = \emph{Z} x \emph{a} \tab Relative start point (bias) \cr 26 | \emph{SZ} \tab probit \tab [0, 1] \tab qnorm(0) \tab \emph{sz} = 2 x \emph{SZ} x min(\emph{a} x \emph{Z}, \emph{a} x (1-\emph{Z})) \tab Relative between-trial variation in start point \cr 27 | \emph{sv} \tab log \tab [0, Inf] \tab log(0) \tab \tab Between-trial standard deviation of drift rate \cr 28 | \emph{st0} \tab log \tab [0, Inf] \tab log(0) \tab \tab Between-trial variation (range) in non-decision time \cr 29 | } 30 | 31 | 32 | \code{a}, \code{t0}, \code{sv}, \code{st0}, \code{s} are sampled on the log scale because these parameters are strictly positive, 33 | \code{Z}, \code{SZ} and \code{DP} are sampled on the probit scale because they should be strictly between 0 and 1. 34 | 35 | \code{Z} is estimated as the ratio of bias to one boundary where 0.5 means no bias. 36 | \code{DP} comprises the difference in non-decision time for each response option. 37 | 38 | Conventionally, \code{s} is fixed to 1 to satisfy scaling constraints. 39 | 40 | See Ratcliff, R., & McKoon, G. (2008). 41 | The diffusion decision model: theory and data for two-choice decision tasks. 42 | \emph{Neural computation, 20}(4), 873-922. doi:10.1162/neco.2008.12-06-420. 43 | } 44 | \examples{ 45 | design_DDMaE <- design(data = forstmann,model=DDM, 46 | formula =list(v~0+S,a~E, t0~1, s~1, Z~1, sv~1, SZ~1), 47 | constants=c(s=log(1))) 48 | # For all parameters that are not defined in the formula, default values are assumed 49 | # (see Table above). 50 | 51 | } 52 | -------------------------------------------------------------------------------- /man/DDMGNG.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/model_DDM.R 3 | \name{DDMGNG} 4 | \alias{DDMGNG} 5 | \title{The GNG (go/nogo) Diffusion Decision Model} 6 | \usage{ 7 | DDMGNG() 8 | } 9 | \value{ 10 | A model list with all the necessary functions to sample 11 | } 12 | \description{ 13 | In the GNG paradigm one of the two possible choices results in a response 14 | being withheld (a non-response), which is indicated in the data by an NA for 15 | the rt, with the corresponding level of the R (response) factor still being 16 | specified. For example, suppose the go response is coded as "yes" and nogo is 17 | coded as "no", then for a non-response (R,rt) = ("no",NA) and for a response 18 | e.g., (R,rt) = ("yes",1.36). The GNG paradigm must also have a response 19 | } 20 | \details{ 21 | The model used is described in the following paper, with the addition of 22 | modeling the TIMEOUT (which is considered but not used in this paper). 23 | 24 | Gomez, P., Ratcliff, R., & Perea, M. (2007). A Model of the Go/No-Go Task. 25 | Journal of Experimental Psychology: General, 136(3), 389–413. 26 | https://doi.org/10.1037/0096-3445.136.3.389 27 | 28 | The likelihood of non-responses requires and evaluation of the DDM cdf, 29 | specifically 1 - p(hitting the yes boundary before TIMEOUT). 30 | 31 | To use these models three functions must be supplied in the design's function 32 | argument with the names TIMEOUT, Rnogo and Rgo. For example, assuming a 33 | 2.5 second timeout, and R factor with levels c("no","yes") and "no" mapping 34 | to a non-response. 35 | 36 | TIMEOUT=function(d)rep(2.5,nrow(d)) 37 | Rnogo=function(d)factor(rep("no",nrow(d)),levels=c("no","yes")) 38 | Rgo=function(d)factor(rep("yes",nrow(d)),levels=c("no","yes"))) 39 | 40 | See the help for DDM for further details. At present this model is not fully 41 | implemented in C, so is a little slower to use than the DDM, but not greatly. 42 | } 43 | \section{window (i.e., a length of time, TIMEOUT period, after which withholding is}{ 44 | assumed). 45 | } 46 | 47 | \examples{ 48 | dGNG <- design(Rlevels = c("left","right"), 49 | factors=list(subjects=1,S=c("left","right")), 50 | functions=list( 51 | TIMEOUT=function(d)rep(2.5,nrow(d)), 52 | # no go response level 53 | Rnogo=function(d)factor(rep("left",nrow(d)),levels=c("left","right")), 54 | # go response level 55 | Rgo=function(d)factor(rep("right",nrow(d)),levels=c("left","right"))), 56 | formula=list(v~S,a~1, Z~1, t0~1), 57 | model=DDMGNG) 58 | 59 | p_vector <- sampled_pars(dGNG) 60 | } 61 | -------------------------------------------------------------------------------- /man/EMC2-package.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/EMC2-package.R 3 | \docType{package} 4 | \name{EMC2-package} 5 | \alias{EMC2} 6 | \alias{EMC2-package} 7 | \title{EMC2: Bayesian Hierarchical Analysis of Cognitive Models of Choice} 8 | \description{ 9 | Fit Bayesian (hierarchical) cognitive models using a linear modeling language interface using particle Metropolis Markov chain Monte Carlo sampling with Gibbs steps. The diffusion decision model (DDM), linear ballistic accumulator model (LBA), racing diffusion model (RDM), and the lognormal race model (LNR) are supported. Additionally, users can specify their own likelihood function and/or choose for non-hierarchical estimation, as well as for a diagonal, blocked or full multivariate normal group-level distribution to test individual differences. Prior specification is facilitated through methods that visualize the (implied) prior. A wide range of plotting functions assist in assessing model convergence and posterior inference. Models can be easily evaluated using functions that plot posterior predictions or using relative model comparison metrics such as information criteria or Bayes factors. References: Stevenson et al. (2024) \doi{10.31234/osf.io/2e4dq}. 10 | } 11 | \seealso{ 12 | Useful links: 13 | \itemize{ 14 | \item \url{https://ampl-psych.github.io/EMC2/} 15 | \item \url{https://github.com/ampl-psych/EMC2} 16 | \item Report bugs at \url{https://github.com/ampl-psych/EMC2/issues} 17 | } 18 | 19 | } 20 | \author{ 21 | \strong{Maintainer}: Niek Stevenson \email{niek.stevenson@gmail.com} (\href{https://orcid.org/0000-0003-3206-7544}{ORCID}) 22 | 23 | Authors: 24 | \itemize{ 25 | \item Michelle Donzallaz 26 | \item Andrew Heathcote 27 | } 28 | 29 | Other contributors: 30 | \itemize{ 31 | \item Steven Miletić [contributor] 32 | \item Raphael Hartmann [contributor] 33 | \item Karl C. Klauer [contributor] 34 | \item Steven G. Johnson [contributor] 35 | \item Jean M. Linhart [contributor] 36 | \item Brian Gough [contributor] 37 | \item Gerard Jungman [contributor] 38 | \item Rudolf Schuerer [contributor] 39 | \item Przemyslaw Sliwa [contributor] 40 | \item Jason H. Stover [contributor] 41 | } 42 | 43 | } 44 | \keyword{internal} 45 | -------------------------------------------------------------------------------- /man/LNR.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/model_LNR.R 3 | \name{LNR} 4 | \alias{LNR} 5 | \title{The Log-Normal Race Model} 6 | \usage{ 7 | LNR() 8 | } 9 | \value{ 10 | A model list with all the necessary functions for EMC2 to sample 11 | } 12 | \description{ 13 | Model file to estimate the Log-Normal Race Model (LNR) in EMC2. 14 | } 15 | \details{ 16 | Model files are almost exclusively used in \code{design()}. 17 | 18 | Default values are used for all parameters that are not explicitly listed in the \code{formula} 19 | argument of \code{design()}.They can also be accessed with \code{LNR()$p_types}.\tabular{llllll}{ 20 | \strong{Parameter} \tab \strong{Transform} \tab \strong{Natural scale} \tab \strong{Default} \tab \strong{Mapping} \tab \strong{Interpretation} \cr 21 | \emph{m} \tab - \tab [-Inf, Inf] \tab 1 \tab \tab Scale parameter \cr 22 | \emph{s} \tab log \tab [0, Inf] \tab log(1) \tab \tab Shape parameter \cr 23 | \emph{t0} \tab log \tab [0, Inf] \tab log(0) \tab \tab Non-decision time \cr 24 | } 25 | 26 | 27 | Because the LNR is a race model, it has one accumulator per response option. 28 | EMC2 automatically constructs a factor representing the accumulators \code{lR} (i.e., the 29 | latent response) with level names taken from the \code{R} column in the data. 30 | 31 | In \code{design()}, \code{matchfun} can be used to automatically create a latent match 32 | (\code{lM}) factor with levels \code{FALSE} (i.e., the stimulus does not match the accumulator) 33 | and \code{TRUE} (i.e., the stimulus does match the accumulator). This is added internally 34 | and can also be used in the model formula, typically for parameters related to 35 | the rate of accumulation (see the example below). 36 | 37 | Rouder, J. N., Province, J. M., Morey, R. D., Gomez, P., & Heathcote, A. (2015). 38 | The lognormal race: A cognitive-process model of choice and latency with 39 | desirable psychometric properties. \emph{Psychometrika, 80}, 491-513. 40 | https://doi.org/10.1007/s11336-013-9396-3 41 | } 42 | \examples{ 43 | # When working with lM it is useful to design an "average and difference" 44 | # contrast matrix, which for binary responses has a simple canonical from: 45 | ADmat <- matrix(c(-1/2,1/2),ncol=1,dimnames=list(NULL,"d")) 46 | # We also define a match function for lM 47 | matchfun=function(d)d$S==d$lR 48 | # We now construct our design, with v ~ lM and the contrast for lM the ADmat. 49 | design_LNRmE <- design(data = forstmann,model=LNR,matchfun=matchfun, 50 | formula=list(m~lM + E,s~1,t0~1), 51 | contrasts=list(m=list(lM=ADmat))) 52 | # For all parameters that are not defined in the formula, default values are assumed 53 | # (see Table above). 54 | } 55 | -------------------------------------------------------------------------------- /man/SDT.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/model_SDT.R 3 | \name{SDT} 4 | \alias{SDT} 5 | \title{Gaussian Signal Detection Theory Model for Binary Responses} 6 | \usage{ 7 | SDT() 8 | } 9 | \value{ 10 | A model list with all the necessary functions to sample 11 | } 12 | \description{ 13 | Discrete binary choice based on continuous Gaussian latent, with no rt (rt 14 | must be set to NA in data). 15 | } 16 | \details{ 17 | Model parameters are: 18 | mean (unbounded) 19 | sd (log scale) and 20 | threshold (unbounded). 21 | 22 | For identifiability in one condition two parameters must be fixed 23 | (conventionally mean=0 and sd = 1). When used with data that records only 24 | accuracy (so reponse bias cannot be evaluated) a single threshold must be 25 | assumed and fixed (e.g., threshold = 0). 26 | 27 | At present this model is not fully implemented in C, but as its likelihood 28 | requires only pnorm evaluation it is quite fast. 29 | } 30 | \examples{ 31 | dprobit <- design(Rlevels = c("left","right"), 32 | factors=list(subjects=1,S=c("left","right")), 33 | formula=list(mean ~ 0+S, sd ~ 1,threshold ~ 1), 34 | matchfun=function(d)d$S==d$lR, 35 | constants=c(sd=log(1),threshold=0), 36 | model=SDT) 37 | 38 | p_vector <- sampled_pars(dprobit) 39 | } 40 | -------------------------------------------------------------------------------- /man/auto_thin.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/s3_funcs.R 3 | \name{auto_thin.emc} 4 | \alias{auto_thin.emc} 5 | \alias{auto_thin} 6 | \title{Automatically Thin an emc Object} 7 | \usage{ 8 | \method{auto_thin}{emc}(emc, stage = "sample", selection = c("alpha", "mu"), ...) 9 | 10 | auto_thin(emc, stage = "sample", selection = c("alpha", "mu"), ...) 11 | } 12 | \arguments{ 13 | \item{emc}{an emc object.} 14 | 15 | \item{stage}{A character string. Indicates from which sampling stage(s) to take the samples from (i.e. \code{preburn}, \code{burn}, \code{adapt}, \code{sample})} 16 | 17 | \item{selection}{Which parameter types (i.e. 'alpha' or 'mu' to consider when determining the effective sample size)} 18 | 19 | \item{...}{additional optional arguments} 20 | } 21 | \description{ 22 | Uses the effective sample size of \code{selection} to determine how much to optimally thin an emc object 23 | } 24 | -------------------------------------------------------------------------------- /man/chain_n.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/objects.R 3 | \name{chain_n} 4 | \alias{chain_n} 5 | \title{MCMC Chain Iterations} 6 | \usage{ 7 | chain_n(emc) 8 | } 9 | \arguments{ 10 | \item{emc}{A list, the output of \code{fit()}.} 11 | } 12 | \value{ 13 | A matrix 14 | } 15 | \description{ 16 | Returns a matrix with the number of samples per chain for each stage that is present 17 | in the emc object (i.e., \code{preburn}, \code{burn}, \code{adapt}, 18 | \code{sample}). The number of rows of the matrix reflects the number of chains 19 | and the number of columns the number of sampling stages. 20 | } 21 | \examples{ 22 | chain_n(samples_LNR) 23 | 24 | } 25 | -------------------------------------------------------------------------------- /man/check.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/s3_funcs.R 3 | \name{check.emc} 4 | \alias{check.emc} 5 | \alias{check} 6 | \title{Convergence Checks for an emc Object} 7 | \usage{ 8 | \method{check}{emc}( 9 | emc, 10 | selection = c("mu", "sigma2", "alpha"), 11 | digits = 3, 12 | plot_worst = TRUE, 13 | ... 14 | ) 15 | 16 | check(emc, ...) 17 | } 18 | \arguments{ 19 | \item{emc}{An emc object} 20 | 21 | \item{selection}{A Character vector. Indicates which parameter types to check (e.g., \code{alpha}, \code{mu}, \code{sigma2}, \code{correlation}).} 22 | 23 | \item{digits}{Integer. How many digits to round the ESS and Rhat to in the plots} 24 | 25 | \item{plot_worst}{Boolean. If \code{TRUE} also plots the chain plots for the worst parameter} 26 | 27 | \item{...}{Optional arguments that can be passed to \code{get_pars} or \code{plot.default} (see \code{par()})} 28 | } 29 | \value{ 30 | a list with the statistics for the worst converged parameter per selection 31 | } 32 | \description{ 33 | Runs a series of convergence checks, prints statistics to the console, and 34 | makes traceplots of the worst converged parameter per selection. 35 | } 36 | \details{ 37 | Note that the \code{Rhat} is calculated by doubling the number of chains by 38 | first splitting chains into first and second half, so it also a test of 39 | stationarity. 40 | 41 | Efficiency of sampling is indicated by the effective 42 | sample size (ESS) (from the \code{coda} R package). 43 | Full range of possible samples manipulations described in \code{get_pars}. 44 | } 45 | \examples{ 46 | check(samples_LNR) 47 | } 48 | -------------------------------------------------------------------------------- /man/compare.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/statistics.R 3 | \name{compare} 4 | \alias{compare} 5 | \title{Information Criteria and Marginal Likelihoods} 6 | \usage{ 7 | compare( 8 | sList, 9 | stage = "sample", 10 | filter = NULL, 11 | use_best_fit = TRUE, 12 | BayesFactor = TRUE, 13 | cores_for_props = 4, 14 | cores_per_prop = 1, 15 | print_summary = TRUE, 16 | digits = 0, 17 | digits_p = 3, 18 | ... 19 | ) 20 | } 21 | \arguments{ 22 | \item{sList}{List of samples objects} 23 | 24 | \item{stage}{A string. Specifies which stage the samples are to be taken from \code{"preburn"}, \code{"burn"}, \code{"adapt"}, or \code{"sample"}} 25 | 26 | \item{filter}{An integer or vector. If it's an integer, iterations up until the value set by \code{filter} will be excluded. 27 | If a vector is supplied, only the iterations in the vector will be considered.} 28 | 29 | \item{use_best_fit}{Boolean, defaults to \code{TRUE}, uses the minimal or mean likelihood (whichever is better) in the 30 | calculation, otherwise always uses the mean likelihood.} 31 | 32 | \item{BayesFactor}{Boolean, defaults to \code{TRUE}. Include marginal likelihoods as estimated using WARP-III bridge sampling. 33 | Usually takes a minute per model added to calculate} 34 | 35 | \item{cores_for_props}{Integer, how many cores to use for the Bayes factor calculation, here 4 is the default for the 4 different proposal densities to evaluate, only 1, 2 and 4 are sensible.} 36 | 37 | \item{cores_per_prop}{Integer, how many cores to use for the Bayes factor calculation if you have more than 4 cores available. Cores used will be cores_for_props * cores_per_prop. Best to prioritize cores_for_props being 4 or 2} 38 | 39 | \item{print_summary}{Boolean (default \code{TRUE}), print table of results} 40 | 41 | \item{digits}{Integer, significant digits in printed table for information criteria} 42 | 43 | \item{digits_p}{Integer, significant digits in printed table for model weights} 44 | 45 | \item{...}{Additional, optional arguments} 46 | } 47 | \value{ 48 | Matrix of effective number of parameters, mean deviance, deviance of 49 | mean, DIC, BPIC, Marginal Deviance (if \code{BayesFactor=TRUE}) and associated weights. 50 | } 51 | \description{ 52 | Returns the BPIC/DIC or marginal deviance (-2*marginal likelihood) for a list of samples objects. 53 | } 54 | \examples{ 55 | \donttest{ 56 | compare(list(samples_LNR), cores_for_props = 1) 57 | # Typically we would define a list of two (or more) different models: 58 | # # Here the full model is an emc object with the hypothesized effect 59 | # # The null model is an emc object without the hypothesized effect 60 | # design_full <- design(data = forstmann,model=DDM, 61 | # formula =list(v~0+S,a~E, t0~1, s~1, Z~1, sv~1, SZ~1), 62 | # constants=c(s=log(1))) 63 | # # Now without a ~ E 64 | # design_null <- design(data = forstmann,model=DDM, 65 | # formula =list(v~0+S,a~1, t0~1, s~1, Z~1, sv~1, SZ~1), 66 | # constants=c(s=log(1))) 67 | # 68 | # full_model <- make_emc(forstmann, design_full) 69 | # full_model <- fit(full_model) 70 | # 71 | # null_model <- make_emc(forstmann, design_null) 72 | # null_model <- fit(null_model) 73 | # sList <- list(full_model, null_model) 74 | # # By default emc uses 4 cores to parallelize marginal likelihood estimation across proposals 75 | # # So cores_per_prop = 3 results in 12 cores used. 76 | # compare(sList, cores_per_prop = 3) 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /man/compare_subject.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/statistics.R 3 | \name{compare_subject} 4 | \alias{compare_subject} 5 | \title{Information Criteria For Each Participant} 6 | \usage{ 7 | compare_subject( 8 | sList, 9 | stage = "sample", 10 | filter = 0, 11 | use_best_fit = TRUE, 12 | print_summary = TRUE, 13 | digits = 3 14 | ) 15 | } 16 | \arguments{ 17 | \item{sList}{List of samples objects} 18 | 19 | \item{stage}{A string. Specifies which stage the samples are to be taken from \code{"preburn"}, \code{"burn"}, \code{"adapt"}, or \code{"sample"}} 20 | 21 | \item{filter}{An integer or vector. If it's an integer, iterations up until the value set by \code{filter} will be excluded. 22 | If a vector is supplied, only the iterations in the vector will be considered.} 23 | 24 | \item{use_best_fit}{Boolean, defaults to \code{TRUE}, use minimal likelihood or mean likelihood 25 | (whichever is better) in the calculation, otherwise always uses the mean likelihood.} 26 | 27 | \item{print_summary}{Boolean (defaults to \code{TRUE}) print table of results} 28 | 29 | \item{digits}{Integer, significant digits in printed table} 30 | } 31 | \value{ 32 | List of matrices for each subject of effective number of parameters, 33 | mean deviance, deviance of mean, DIC, BPIC and associated weights. 34 | } 35 | \description{ 36 | Returns the BPIC/DIC based model weights for each participant in a list of samples objects 37 | } 38 | \examples{ 39 | # For a broader illustration see `compare`. 40 | # Here we just take two times the same model, but normally one would compare 41 | # different models 42 | compare_subject(list(m0 = samples_LNR, m1 = samples_LNR)) 43 | } 44 | -------------------------------------------------------------------------------- /man/contr.anova.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/design.R 3 | \name{contr.anova} 4 | \alias{contr.anova} 5 | \title{Anova Style Contrast Matrix} 6 | \usage{ 7 | contr.anova(n) 8 | } 9 | \arguments{ 10 | \item{n}{An integer. The number of items for which to create the contrast} 11 | } 12 | \value{ 13 | A contrast matrix. 14 | } 15 | \description{ 16 | Similar to \code{contr.helmert}, but then scaled to estimate differences between conditions. Use in \code{design()}. 17 | } 18 | \examples{ 19 | { 20 | design_DDMaE <- design(data = forstmann,model=DDM, contrasts = list(E = contr.anova), 21 | formula =list(v~S,a~E, t0~1, s~1, Z~1, sv~1, SZ~1), 22 | constants=c(s=log(1))) 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /man/contr.bayes.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/design.R 3 | \name{contr.bayes} 4 | \alias{contr.bayes} 5 | \title{Contrast Enforcing Equal Prior Variance on each Level} 6 | \usage{ 7 | contr.bayes(n) 8 | } 9 | \arguments{ 10 | \item{n}{An integer. The number of items for which to create the contrast} 11 | } 12 | \value{ 13 | A contrast matrix. 14 | } 15 | \description{ 16 | Typical contrasts impose different levels of marginal prior variance for the different levels. 17 | This contrast can be used to ensure that each level has equal marginal priors (Rouder, Morey, Speckman, & Province; 2012). 18 | } 19 | \examples{ 20 | { 21 | design_DDMaE <- design(data = forstmann,model=DDM, contrasts = list(E = contr.bayes), 22 | formula =list(v~S,a~E, t0~1, s~1, Z~1, sv~1, SZ~1), 23 | constants=c(s=log(1))) 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /man/contr.decreasing.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/design.R 3 | \name{contr.decreasing} 4 | \alias{contr.decreasing} 5 | \title{Contrast Enforcing Decreasing Estimates} 6 | \usage{ 7 | contr.decreasing(n) 8 | } 9 | \arguments{ 10 | \item{n}{an integer. The number of items for which to create the contrast.} 11 | } 12 | \value{ 13 | a contrast matrix. 14 | } 15 | \description{ 16 | Each level will be estimated as a reduction from the previous level 17 | } 18 | \examples{ 19 | { 20 | design_DDMaE <- design(data = forstmann,model=DDM, contrasts = list(E = contr.decreasing), 21 | formula =list(v~S,a~E, t0~1, s~1, Z~1, sv~1, SZ~1), 22 | constants=c(s=log(1))) 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /man/contr.increasing.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/design.R 3 | \name{contr.increasing} 4 | \alias{contr.increasing} 5 | \title{Contrast Enforcing Increasing Estimates} 6 | \usage{ 7 | contr.increasing(n) 8 | } 9 | \arguments{ 10 | \item{n}{an integer. The number of items for which to create the contrast.} 11 | } 12 | \value{ 13 | a contrast matrix. 14 | } 15 | \description{ 16 | Each level will be estimated additively from the previous level 17 | } 18 | \examples{ 19 | { 20 | design_DDMaE <- design(data = forstmann,model=DDM, contrasts = list(E = contr.increasing), 21 | formula =list(v~S,a~E, t0~1, s~1, Z~1, sv~1, SZ~1), 22 | constants=c(s=log(1))) 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /man/credible.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/s3_funcs.R 3 | \name{credible.emc} 4 | \alias{credible.emc} 5 | \alias{credible} 6 | \title{Posterior Credible Interval Tests} 7 | \usage{ 8 | \method{credible}{emc}( 9 | x, 10 | x_name = NULL, 11 | x_fun = NULL, 12 | x_fun_name = "fun", 13 | selection = "mu", 14 | y = NULL, 15 | y_name = NULL, 16 | y_fun = NULL, 17 | y_fun_name = "fun", 18 | x_subject = NULL, 19 | y_subject = NULL, 20 | mu = 0, 21 | alternative = c("less", "greater")[1], 22 | probs = c(0.025, 0.5, 0.975), 23 | digits = 2, 24 | p_digits = 3, 25 | print_table = TRUE, 26 | ... 27 | ) 28 | 29 | credible(x, ...) 30 | } 31 | \arguments{ 32 | \item{x}{An emc object} 33 | 34 | \item{x_name}{A character string. Name of the parameter to be tested for \code{x}} 35 | 36 | \item{x_fun}{Function applied to the MCMC chains to create 37 | variable to be tested.} 38 | 39 | \item{x_fun_name}{Name to give to quantity calculated by \code{x_fun}} 40 | 41 | \item{selection}{A character string designating parameter type (e.g. \code{alpha} or \code{covariance})} 42 | 43 | \item{y}{A second emc object} 44 | 45 | \item{y_name}{A character string. Name of the parameter to be tested for \code{y}} 46 | 47 | \item{y_fun}{Function applied to the MCMC chains to create 48 | variable to be tested.} 49 | 50 | \item{y_fun_name}{Name to give to quantity calculated by \code{y_fun}} 51 | 52 | \item{x_subject}{Integer or name selecting a subject} 53 | 54 | \item{y_subject}{Integer or name selecting a subject} 55 | 56 | \item{mu}{Numeric. \code{NULL} value for single sample test if \code{y} is not supplied (default 0)} 57 | 58 | \item{alternative}{\code{less} or \code{greater} determining direction of test probability} 59 | 60 | \item{probs}{Vector defining quantiles to return.} 61 | 62 | \item{digits}{Integer, significant digits for estimates in printed results} 63 | 64 | \item{p_digits}{Integer, significant digits for probability in printed results} 65 | 66 | \item{print_table}{Boolean (defaults to \code{TRUE}) for printing results table} 67 | 68 | \item{...}{Additional optional arguments that can be passed to \code{get_pars}} 69 | } 70 | \value{ 71 | Invisible results table with no rounding. 72 | } 73 | \description{ 74 | Modeled after \code{t.test}, returns the credible interval of the parameter or test 75 | and what proportion of the posterior distribution (or the difference in posterior distributions 76 | in case of a two sample test) overlaps with mu. 77 | For a one sample test provide \code{x} and for two sample also provide \code{y}. 78 | Note that for comparisons within one model, we recommend using \code{hypothesis()} if the priors 79 | were well chosen. 80 | } 81 | \examples{ 82 | { 83 | # Run a credible interval test (Bayesian ''t-test'') 84 | credible(samples_LNR, x_name = "m") 85 | # We can also compare between two sets of emc objects 86 | 87 | # # Now without a ~ E 88 | # design_null <- design(data = forstmann,model=DDM, 89 | # formula =list(v~0+S,a~1, t0~1, s~1, Z~1, sv~1, SZ~1), 90 | # constants=c(s=log(1))) 91 | # 92 | # null_model <- make_emc(forstmann, design_null) 93 | # null_model <- fit(null_model) 94 | # credible(x = null_model, x_name = "a", y = full_model, y_name = "a") 95 | # 96 | # # Or provide custom functions: 97 | # credible(x = full_model, x_fun = function(d) d["a_Eaccuracy"] - d["a_Eneutral"]) 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /man/credint.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/priors.R, R/s3_funcs.R 3 | \name{credint.emc.prior} 4 | \alias{credint.emc.prior} 5 | \alias{credint.emc} 6 | \alias{credint} 7 | \title{Posterior Quantiles} 8 | \usage{ 9 | \method{credint}{emc.prior}( 10 | x, 11 | selection = "mu", 12 | probs = c(0.025, 0.5, 0.975), 13 | digits = 3, 14 | N = 1000, 15 | covariates = NULL, 16 | ... 17 | ) 18 | 19 | \method{credint}{emc}(x, selection = "mu", probs = c(0.025, 0.5, 0.975), digits = 3, ...) 20 | 21 | credint(x, ...) 22 | } 23 | \arguments{ 24 | \item{x}{An emc or emc.prior object} 25 | 26 | \item{selection}{A Character vector. Indicates which parameter types to check (e.g., \code{alpha}, \code{mu}, \code{sigma2}, \code{correlation}).} 27 | 28 | \item{probs}{A vector. Indicates which quantiles to return from the posterior.} 29 | 30 | \item{digits}{Integer. How many digits to round the output to} 31 | 32 | \item{N}{An integer. Number of samples to use for the quantile calculation (only for prior.emc objects)} 33 | 34 | \item{covariates}{A list of covariates to use for the quantile calculation (only for prior.emc objects)} 35 | 36 | \item{...}{Optional additional arguments that can be passed to \code{get_pars}} 37 | } 38 | \value{ 39 | A list of posterior quantiles for each parameter group in the selected parameter type. 40 | } 41 | \description{ 42 | Returns the quantiles of the selected parameter type. 43 | Full range of possible samples manipulations described in \code{get_pars}. 44 | } 45 | \examples{ 46 | credint(samples_LNR) 47 | } 48 | -------------------------------------------------------------------------------- /man/ess_summary.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/s3_funcs.R 3 | \name{ess_summary.emc} 4 | \alias{ess_summary.emc} 5 | \alias{ess_summary} 6 | \title{Effective Sample Size} 7 | \usage{ 8 | \method{ess_summary}{emc}( 9 | emc, 10 | selection = "mu", 11 | stat = "min", 12 | stat_only = FALSE, 13 | digits = 1, 14 | ... 15 | ) 16 | 17 | ess_summary(emc, ...) 18 | } 19 | \arguments{ 20 | \item{emc}{An emc object} 21 | 22 | \item{selection}{A Character vector. Indicates which parameter types to check (e.g., \code{alpha}, \code{mu}, \code{sigma2}, \code{correlation}).} 23 | 24 | \item{stat}{A string. Should correspond to a function that can be applied to a vector, 25 | which will be performed on the vector/rows or columns of the matrix of the parameters} 26 | 27 | \item{stat_only}{Boolean. If \code{TRUE} will only return the result of the applied stat function, 28 | otherwise returns both the stat result and the result of the function on all parameters.} 29 | 30 | \item{digits}{Integer. How many digits to round the output to} 31 | 32 | \item{...}{Optional additional arguments that can be passed to \code{get_pars}} 33 | } 34 | \value{ 35 | A matrix or vector of ESS values for the selected parameter type. 36 | } 37 | \description{ 38 | Returns the effective sample size (ESS) of the selected parameter type. 39 | Full range of possible samples manipulations described in \code{get_pars}. 40 | } 41 | \examples{ 42 | ess_summary(samples_LNR, selection = "alpha") 43 | } 44 | -------------------------------------------------------------------------------- /man/forstmann.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/data.R 3 | \docType{data} 4 | \name{forstmann} 5 | \alias{forstmann} 6 | \title{Forstmann et al.'s Data} 7 | \format{ 8 | A data frame with 15818 rows and 5 variables: 9 | \describe{ 10 | \item{E}{Factor with 3 levels for Speed, Accuracy and 11 | Neutral} 12 | \item{R}{Factor with 2 levels for Left and Right responses} 13 | \item{S}{Factor with 2 levels for Left and Right trials} 14 | \item{rt}{reaction time for each trial as a double} 15 | \item{subjects}{integer ID for each subject} 16 | } 17 | } 18 | \source{ 19 | \url{https://www.pnas.org/doi/10.1073/pnas.0805903105} 20 | } 21 | \usage{ 22 | forstmann 23 | } 24 | \description{ 25 | A dataset containing the speed or accuracy manipulation for a Random Dot 26 | Motion experiment. 27 | } 28 | \details{ 29 | Details on the dataset can be found in the following paper: 30 | 31 | \strong{Striatum and pre-SMA facilitate decision-making under time pressure} 32 | 33 | Birte U. Forstmann, Gilles Dutilh, Scott Brown, Jane Neumann, 34 | D. Yves von Cramon, K. Richard Ridderinkhof, Eric-Jan Wagenmakers. 35 | 36 | \emph{Proceedings of the National Academy of Sciences Nov 2008, 105 (45) 37 | 17538-17542; DOI: 10.1073/pnas.0805903105} 38 | } 39 | \keyword{datasets} 40 | -------------------------------------------------------------------------------- /man/gd_summary.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/s3_funcs.R 3 | \name{gd_summary.emc} 4 | \alias{gd_summary.emc} 5 | \alias{gd_summary} 6 | \title{Gelman-Rubin Statistic} 7 | \usage{ 8 | \method{gd_summary}{emc}( 9 | emc, 10 | selection = "mu", 11 | omit_mpsrf = TRUE, 12 | stat = "max", 13 | stat_only = FALSE, 14 | digits = 3, 15 | ... 16 | ) 17 | 18 | gd_summary(emc, ...) 19 | } 20 | \arguments{ 21 | \item{emc}{An emc object} 22 | 23 | \item{selection}{A Character vector. Indicates which parameter types to check (e.g., \code{alpha}, \code{mu}, \code{sigma2}, \code{correlation}).} 24 | 25 | \item{omit_mpsrf}{Boolean. If \code{TRUE} also returns the multivariate point scale reduction factor (see \code{?coda::gelman.diag}).} 26 | 27 | \item{stat}{A string. Should correspond to a function that can be applied to a vector, 28 | which will be performed on the vector/rows or columns of the matrix of the parameters} 29 | 30 | \item{stat_only}{Boolean. If \code{TRUE} will only return the result of the applied stat function, 31 | otherwise returns both the stat result and the result of the function on all parameters.} 32 | 33 | \item{digits}{Integer. How many digits to round the output to} 34 | 35 | \item{...}{Optional additional arguments that can be passed to \code{get_pars}} 36 | } 37 | \value{ 38 | A matrix or vector of R-hat values for the selected parameter type. 39 | } 40 | \description{ 41 | Returns the Gelman-Rubin diagnostics (otherwise known as the R-hat) of the selected parameter type; 42 | i.e. the ratio of between to within MCMC chain variance. 43 | } 44 | \details{ 45 | See: Gelman, A and Rubin, DB (1992) 46 | Inference from iterative simulation using multiple sequences, \emph{Statistical Science}, 7, 457-511. 47 | 48 | Full range of possible samples manipulations described in \code{get_pars}. 49 | } 50 | \examples{ 51 | gd_summary(samples_LNR, selection = "correlation", stat = "mean", flatten = TRUE) 52 | } 53 | -------------------------------------------------------------------------------- /man/get_BayesFactor.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/statistics.R 3 | \name{get_BayesFactor} 4 | \alias{get_BayesFactor} 5 | \title{Bayes Factors} 6 | \usage{ 7 | get_BayesFactor(MLL1, MLL2) 8 | } 9 | \arguments{ 10 | \item{MLL1}{Numeric. Marginal likelihood of model 1. Obtained with \code{run_bridge_sampling()}} 11 | 12 | \item{MLL2}{Numeric. Marginal likelihood of model 2. Obtained with \code{run_bridge_sampling()}} 13 | } 14 | \value{ 15 | The BayesFactor for model 1 over model 2 16 | } 17 | \description{ 18 | returns the Bayes Factor for two models 19 | } 20 | \examples{ 21 | \donttest{ 22 | # Normally one would compare two different models 23 | # Here we use two times the same model: 24 | M1 <- M0 <- run_bridge_sampling(samples_LNR, both_splits = FALSE, cores_for_props = 1) 25 | get_BayesFactor(M1, M0) 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /man/get_data.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/s3_funcs.R 3 | \name{get_data.emc} 4 | \alias{get_data.emc} 5 | \alias{get_data} 6 | \title{Get Data} 7 | \usage{ 8 | \method{get_data}{emc}(emc) 9 | 10 | get_data(emc) 11 | } 12 | \arguments{ 13 | \item{emc}{an emc object} 14 | } 15 | \value{ 16 | A dataframe of the original data 17 | } 18 | \description{ 19 | Extracts data from an emc object 20 | } 21 | \details{ 22 | emc adds columns and rows to a dataframe in order to facilitate efficient likelihood calculations. 23 | This function will return the data as provided originally. 24 | } 25 | \examples{ 26 | get_data(samples_LNR) 27 | } 28 | -------------------------------------------------------------------------------- /man/get_design.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/priors.R, R/s3_funcs.R 3 | \name{get_design.emc.prior} 4 | \alias{get_design.emc.prior} 5 | \alias{get_design.emc} 6 | \alias{get_design} 7 | \title{Get Design} 8 | \usage{ 9 | \method{get_design}{emc.prior}(x) 10 | 11 | \method{get_design}{emc}(x) 12 | 13 | get_design(x) 14 | } 15 | \arguments{ 16 | \item{x}{an \code{emc} or \code{emc.prior} object} 17 | } 18 | \value{ 19 | A design with class emc.design 20 | } 21 | \description{ 22 | Extracts design from an emc object 23 | } 24 | \examples{ 25 | get_design(samples_LNR) 26 | } 27 | -------------------------------------------------------------------------------- /man/get_prior.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/s3_funcs.R 3 | \name{get_prior.emc} 4 | \alias{get_prior.emc} 5 | \alias{get_prior} 6 | \title{Get Prior} 7 | \usage{ 8 | \method{get_prior}{emc}(emc) 9 | 10 | get_prior(emc) 11 | } 12 | \arguments{ 13 | \item{emc}{an emc object} 14 | } 15 | \value{ 16 | A prior with class emc.prior 17 | } 18 | \description{ 19 | Extracts prior from an emc object 20 | } 21 | \examples{ 22 | get_prior(samples_LNR) 23 | } 24 | -------------------------------------------------------------------------------- /man/hypothesis.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/s3_funcs.R 3 | \name{hypothesis.emc} 4 | \alias{hypothesis.emc} 5 | \alias{hypothesis} 6 | \title{Within-Model Hypothesis Testing} 7 | \usage{ 8 | \method{hypothesis}{emc}( 9 | emc, 10 | parameter = NULL, 11 | H0 = 0, 12 | fun = NULL, 13 | selection = "mu", 14 | do_plot = TRUE, 15 | use_prior_lim = TRUE, 16 | N = 10000, 17 | prior_args = list(), 18 | ... 19 | ) 20 | 21 | hypothesis(emc, ...) 22 | } 23 | \arguments{ 24 | \item{emc}{An emc object} 25 | 26 | \item{parameter}{A string. A parameter which you want to compare to H0. Will not be used if a FUN is specified.} 27 | 28 | \item{H0}{An integer. The H0 value which you want to compare to} 29 | 30 | \item{fun}{A function. Specifies an operation to be performed on the sampled or mapped parameters.} 31 | 32 | \item{selection}{A Character string. Indicates which parameter type to use (e.g., \code{alpha}, \code{mu}, \code{sigma2}, \code{correlation}).} 33 | 34 | \item{do_plot}{Boolean. If \code{FALSE} will omit the prior-posterior plot and only return the savage-dickey ratio.} 35 | 36 | \item{use_prior_lim}{Boolean. If \code{TRUE} will use xlimits based on prior density, otherwise based on posterior density.} 37 | 38 | \item{N}{Integer. How many prior samples to draw} 39 | 40 | \item{prior_args}{A list. Optional additional arguments to be passed to plot.default for the plotting of the prior density (see \code{par()})} 41 | 42 | \item{...}{Optional arguments that can be passed to \code{get_pars}, \code{density}, or \code{plot.default} (see \code{par()})} 43 | } 44 | \value{ 45 | The Bayes factor for the hypothesis against H0. 46 | } 47 | \description{ 48 | Approximates the Bayes factor for parameter effects using the savage-dickey ratio. 49 | } 50 | \details{ 51 | Note this is different to the computation of the marginal deviance in \code{compare} 52 | since it only considers the group level effect and not the whole model (i.e. subject-level parameters). 53 | For details see: Wagenmakers, Lodewyckx, Kuriyal, & Grasman (2010). 54 | } 55 | \examples{ 56 | # Here the emc object has an effect parameter (e.g. m), 57 | # that maps onto a certain hypothesis. 58 | # The hypothesis here is that m is different from zero. 59 | # We can test whether there's a group-level effect on m: 60 | hypothesis(samples_LNR, parameter = "m") 61 | # Alternatively we can also test whether two parameters differ from each other 62 | mdiff <- function(p)diff(p[c("m","m_lMd")]) 63 | hypothesis(samples_LNR,fun=mdiff) 64 | } 65 | -------------------------------------------------------------------------------- /man/init_chains.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/sampling.R 3 | \name{init_chains} 4 | \alias{init_chains} 5 | \title{Initialize Chains} 6 | \usage{ 7 | init_chains( 8 | emc, 9 | start_mu = NULL, 10 | start_var = NULL, 11 | particles = 1000, 12 | cores_per_chain = 1, 13 | cores_for_chains = length(emc) 14 | ) 15 | } 16 | \arguments{ 17 | \item{emc}{An emc object made by \code{make_emc()}} 18 | 19 | \item{start_mu}{A vector. Mean of multivariate normal used in proposal distribution} 20 | 21 | \item{start_var}{A matrix. Variance covariance matrix of multivariate normal used in proposal distribution. 22 | Smaller values will lead to less deviation around the mean.} 23 | 24 | \item{particles}{An integer. Number of starting values} 25 | 26 | \item{cores_per_chain}{An integer. How many cores to use per chain. Parallelizes across participant calculations.} 27 | 28 | \item{cores_for_chains}{An integer. How many cores to use to parallelize across chains. Default is the number of chains.} 29 | } 30 | \value{ 31 | An emc object 32 | } 33 | \description{ 34 | Adds a set of start points to each chain. These start points are sampled from a user-defined multivariate 35 | normal across subjects. 36 | } 37 | \examples{ 38 | \donttest{ 39 | # Make a design and an emc object 40 | design_DDMaE <- design(data = forstmann,model=DDM, 41 | formula =list(v~0+S,a~E, t0~1, s~1), 42 | constants=c(s=log(1))) 43 | 44 | DDMaE <- make_emc(forstmann, design_DDMaE) 45 | # set up our mean starting points (same used across subjects). 46 | mu <- c(v_Sleft=-2,v_Sright=2,a=log(1),a_Eneutral=log(1.5),a_Eaccuracy=log(2), 47 | t0=log(.2)) 48 | # Small variances to simulate start points from a tight range 49 | var <- diag(0.05, length(mu)) 50 | # Initialize chains, 4 cores per chain, and parallelizing across our 3 chains as well 51 | # so 4*3 cores used. 52 | DDMaE <- init_chains(DDMaE, start_mu = mu, start_var = var, 53 | cores_per_chain = 1, cores_for_chains = 1) 54 | # Afterwards we can just use fit 55 | # DDMaE <- fit(DDMaE, cores_per_chain = 4) 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /man/make_data.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/make_data.R 3 | \name{make_data} 4 | \alias{make_data} 5 | \title{Simulate Data} 6 | \usage{ 7 | make_data( 8 | parameters, 9 | design = NULL, 10 | n_trials = NULL, 11 | data = NULL, 12 | expand = 1, 13 | mapped_p = FALSE, 14 | hyper = FALSE, 15 | ... 16 | ) 17 | } 18 | \arguments{ 19 | \item{parameters}{parameter vector used to simulate data. 20 | Can also be a matrix with one row per subject (with corresponding row names) 21 | or an emc object with sampled parameters 22 | (in which case posterior medians of \code{alpha} are used to simulate data)} 23 | 24 | \item{design}{Design list created by \code{design()}} 25 | 26 | \item{n_trials}{Integer. If \code{data} is not supplied, number of trials to create per design cell} 27 | 28 | \item{data}{Data frame. If supplied, the factors are taken from the data. Determines the number of trials per level of the design factors and can thus allow for unbalanced designs} 29 | 30 | \item{expand}{Integer. Replicates the \code{data} (if supplied) expand times to increase number of trials per cell.} 31 | 32 | \item{mapped_p}{If \code{TRUE} instead returns a data frame with one row per design 33 | cell and columns for each parameter specifying how they are mapped to the design cells.} 34 | 35 | \item{hyper}{If \code{TRUE} the supplied parameters must be a set of samples, from which the group-level will be used to generate subject level parameters. 36 | See also \code{make_random_effects} to generate subject-level parameters from a hyper distribution.} 37 | 38 | \item{...}{Additional optional arguments} 39 | } 40 | \value{ 41 | A data frame with simulated data 42 | } 43 | \description{ 44 | Simulates data based on a model design and a parameter vector (\code{p_vector}) by one of two methods: 45 | \enumerate{ 46 | \item Creating a fully crossed and balanced design specified by the design, 47 | with number of trials per cell specified by the \code{n_trials} argument 48 | \item Using the design of a data frame supplied, which allows creation 49 | of unbalanced and other irregular designs, and replacing previous data with 50 | simulated data 51 | } 52 | } 53 | \details{ 54 | To create data for multiple subjects see \code{?make_random_effects()}. 55 | } 56 | \examples{ 57 | # First create a design 58 | design_DDMaE <- design(factors = list(S = c("left", "right"), 59 | E = c("SPD", "ACC"), 60 | subjects = 1:30), 61 | Rlevels = c("left", "right"), model = DDM, 62 | formula =list(v~0+S,a~E, t0~1, s~1, Z~1, sv~1, SZ~1), 63 | constants=c(s=log(1))) 64 | # Then create a p_vector: 65 | parameters <- c(v_Sleft=-2,v_Sright=2,a=log(1),a_EACC=log(2), t0=log(.2), 66 | Z=qnorm(.5),sv=log(.5),SZ=qnorm(.5)) 67 | 68 | # Now we can simulate data 69 | data <- make_data(parameters, design_DDMaE, n_trials = 30) 70 | 71 | # We can also simulate data based on a specific dataset 72 | design_DDMaE <- design(data = forstmann,model=DDM, 73 | formula =list(v~0+S,a~E, t0~1, s~1, Z~1, sv~1, SZ~1), 74 | constants=c(s=log(1))) 75 | parameters <- c(v_Sleft=-2,v_Sright=2,a=log(1),a_Eneutral=log(1.5),a_Eaccuracy=log(2), 76 | t0=log(.2),Z=qnorm(.5),sv=log(.5),SZ=qnorm(.5)) 77 | 78 | data <- make_data(parameters, design_DDMaE, data = forstmann) 79 | } 80 | -------------------------------------------------------------------------------- /man/make_emc.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/fitting.R 3 | \name{make_emc} 4 | \alias{make_emc} 5 | \title{Make an emc Object} 6 | \usage{ 7 | make_emc( 8 | data, 9 | design, 10 | model = NULL, 11 | type = "standard", 12 | n_chains = 3, 13 | compress = TRUE, 14 | rt_resolution = 0.02, 15 | prior_list = NULL, 16 | par_groups = NULL, 17 | ... 18 | ) 19 | } 20 | \arguments{ 21 | \item{data}{A data frame, or a list of data frames. Needs to have the variable \code{subjects} as participant identifier.} 22 | 23 | \item{design}{A list with a pre-specified design, the output of \code{design()}.} 24 | 25 | \item{model}{A model list. If none is supplied, the model specified in \code{design()} is used.} 26 | 27 | \item{type}{A string indicating whether to run a \code{standard} group-level, \code{blocked}, \code{diagonal}, \code{factor}, or \code{single} (i.e., non-hierarchical) model.} 28 | 29 | \item{n_chains}{An integer. Specifies the number of mcmc chains to be run (has to be more than 1 to compute \code{rhat}).} 30 | 31 | \item{compress}{A Boolean, if \code{TRUE} (i.e., the default), the data is compressed to speed up likelihood calculations.} 32 | 33 | \item{rt_resolution}{A double. Used for compression, response times will be binned based on this resolution.} 34 | 35 | \item{prior_list}{A named list containing the prior. Default prior created if \code{NULL}. For the default priors, see \verb{?get_prior_\{type\}}.} 36 | 37 | \item{par_groups}{A vector. Only to be specified with type \code{blocked}, e.g., \code{c(1,1,1,2,2)} means the covariances 38 | of the first three and of the last two parameters are estimated as two separate blocks.} 39 | 40 | \item{...}{Additional, optional arguments.} 41 | } 42 | \value{ 43 | An uninitialized emc object 44 | } 45 | \description{ 46 | Creates an emc object by combining the data, prior, 47 | and model specification into a \code{emc} object that is needed in \code{fit()}. 48 | } 49 | \examples{ 50 | dat <- forstmann 51 | 52 | # function that takes the lR factor (named diff in the following function) and 53 | # returns a logical defining the correct response for each stimulus. In this 54 | # case the match is simply such that the S factor equals the latent response factor. 55 | matchfun <- function(d)d$S==d$lR 56 | 57 | # design an "average and difference" contrast matrix 58 | ADmat <- matrix(c(-1/2,1/2),ncol=1,dimnames=list(NULL,"diff")) 59 | 60 | # specify design 61 | design_LBABE <- design(data = dat,model=LBA,matchfun=matchfun, 62 | formula=list(v~lM,sv~lM,B~E+lR,A~1,t0~1), 63 | contrasts=list(v=list(lM=ADmat)),constants=c(sv=log(1))) 64 | 65 | # specify priors 66 | pmean <- c(v=1,v_lMdiff=1,sv_lMTRUE=log(.5), B=log(.5),B_Eneutral=log(1.5), 67 | B_Eaccuracy=log(2),B_lRright=0, A=log(0.25),t0=log(.2)) 68 | psd <- c(v=1,v_lMdiff=0.5,sv_lMTRUE=.5, 69 | B=0.3,B_Eneutral=0.3,B_Eaccuracy=0.3,B_lRright=0.3,A=0.4,t0=.5) 70 | prior_LBABE <- prior(design_LBABE, type = 'standard',pmean=pmean,psd=psd) 71 | 72 | # create emc object 73 | LBABE <- make_emc(dat,design_LBABE,type="standard", prior=prior_LBABE) 74 | 75 | } 76 | -------------------------------------------------------------------------------- /man/make_random_effects.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/make_data.R 3 | \name{make_random_effects} 4 | \alias{make_random_effects} 5 | \title{Generate Subject-Level Parameters} 6 | \usage{ 7 | make_random_effects( 8 | design, 9 | group_means, 10 | n_subj = NULL, 11 | variance_proportion = 0.2, 12 | covariances = NULL 13 | ) 14 | } 15 | \arguments{ 16 | \item{design}{A design list. The design as specified by \code{design()}} 17 | 18 | \item{group_means}{A numeric vector. The group level means for each parameter, in the same order as \code{sampled_pars(design)}} 19 | 20 | \item{n_subj}{An integer. The number of subjects to generate parameters for. If \code{NULL} will be inferred from design} 21 | 22 | \item{variance_proportion}{A double. Optional. If \code{covariances} are not specified, the variances will be created by multiplying the means by this number. The covariances will be 0.} 23 | 24 | \item{covariances}{A covariance matrix. Optional. Specify the intended covariance matrix.} 25 | } 26 | \value{ 27 | A matrix of subject-level parameters. 28 | } 29 | \description{ 30 | Simulates subject-level parameters in the format required by \code{make_data()}. 31 | } 32 | \examples{ 33 | # First create a design 34 | design_DDMaE <- design(data = forstmann,model=DDM, 35 | formula =list(v~0+S,a~E, t0~1, s~1, Z~1, sv~1, SZ~1), 36 | constants=c(s=log(1))) 37 | # Then create a group-level means vector: 38 | group_means =c(v_Sleft=-2,v_Sright=2,a=log(1),a_Eneutral=log(1.5),a_Eaccuracy=log(2), 39 | t0=log(.2),Z=qnorm(.5),sv=log(.5),SZ=qnorm(.5)) 40 | # Now we can create subject-level parameters 41 | subj_pars <- make_random_effects(design_DDMaE, group_means, n_subj = 19) 42 | 43 | # We can also define a covariance matrix to simulate from 44 | subj_pars <- make_random_effects(design_DDMaE, group_means, n_subj = 19, 45 | covariances = diag(.1, length(group_means))) 46 | 47 | # The subject level parameters can be used to generate data 48 | make_data(subj_pars, design_DDMaE, n_trials = 10) 49 | } 50 | -------------------------------------------------------------------------------- /man/mapped_pars.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/design.R, R/priors.R, R/s3_funcs.R 3 | \name{mapped_pars} 4 | \alias{mapped_pars} 5 | \alias{mapped_pars.emc.design} 6 | \alias{mapped_pars.emc.prior} 7 | \alias{mapped_pars.emc} 8 | \title{Parameter Mapping Back to the Design Factors} 9 | \usage{ 10 | mapped_pars( 11 | x, 12 | p_vector = NULL, 13 | model = NULL, 14 | digits = 3, 15 | remove_subjects = TRUE, 16 | covariates = NULL, 17 | ... 18 | ) 19 | 20 | \method{mapped_pars}{emc.design}( 21 | x, 22 | p_vector = NULL, 23 | model = NULL, 24 | digits = 3, 25 | remove_subjects = TRUE, 26 | covariates = NULL, 27 | ... 28 | ) 29 | 30 | \method{mapped_pars}{emc.prior}( 31 | x, 32 | p_vector = NULL, 33 | model = NULL, 34 | digits = 3, 35 | remove_subjects = TRUE, 36 | covariates = NULL, 37 | ... 38 | ) 39 | 40 | \method{mapped_pars}{emc}( 41 | x, 42 | p_vector = NULL, 43 | model = NULL, 44 | digits = 3, 45 | remove_subjects = TRUE, 46 | covariates = NULL, 47 | ... 48 | ) 49 | } 50 | \arguments{ 51 | \item{x}{an \code{emc}, \code{emc.prior} or \code{emc.design} object} 52 | 53 | \item{p_vector}{Optional. Specify parameter vector to get numeric mappings. 54 | Must be in the form of \code{sampled_pars(design)}} 55 | 56 | \item{model}{Optional model type (if not already specified in \code{design})} 57 | 58 | \item{digits}{Integer. Will round the output parameter values to this many decimals} 59 | 60 | \item{remove_subjects}{Boolean. Whether to include subjects as a factor in the design} 61 | 62 | \item{covariates}{Covariates specified in the design can be included here.} 63 | 64 | \item{...}{optional arguments} 65 | } 66 | \value{ 67 | Matrix with a column for each factor in the design and for each model parameter type (\code{p_type}). 68 | } 69 | \description{ 70 | Maps parameters of the cognitive model back to the experimental design. If p_vector 71 | is left unspecified will print a textual description of the mapping. 72 | Otherwise the p_vector can be created using \code{sampled_pars()}. 73 | The returned matrix shows whether/how parameters 74 | differ across the experimental factors. 75 | } 76 | \examples{ 77 | # First define a design: 78 | design_DDMaE <- design(data = forstmann,model=DDM, 79 | formula =list(v~0+S,a~E, t0~1, s~1, Z~1, sv~1, SZ~1), 80 | constants=c(s=log(1))) 81 | mapped_pars(design_DDMaE) 82 | # Then create a p_vector: 83 | p_vector=c(v_Sleft=-2,v_Sright=2,a=log(1),a_Eneutral=log(1.5),a_Eaccuracy=log(2), 84 | t0=log(.2),Z=qnorm(.5),sv=log(.5),SZ=qnorm(.5)) 85 | # This will map the parameters of the p_vector back to the design 86 | mapped_pars(design_DDMaE, p_vector) 87 | 88 | } 89 | -------------------------------------------------------------------------------- /man/merge_chains.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/objects.R 3 | \name{merge_chains} 4 | \alias{merge_chains} 5 | \title{Merge Samples} 6 | \usage{ 7 | merge_chains(emc) 8 | } 9 | \arguments{ 10 | \item{emc}{An emc object, commonly the output of \code{fit()}} 11 | } 12 | \value{ 13 | An unlisted emc object with all chains merged 14 | } 15 | \description{ 16 | Merges samples from all chains as one unlisted object. 17 | } 18 | \details{ 19 | Note that all sampling stages are included in the merged output, 20 | including iterations from the \code{preburn}, \code{burn}, and \code{adapt} stages. 21 | \code{merge_chains(emc)$samples$stage} shows the corresponding sampling stages. 22 | } 23 | -------------------------------------------------------------------------------- /man/model_averaging.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/statistics.R 3 | \name{model_averaging} 4 | \alias{model_averaging} 5 | \title{Model Averaging} 6 | \usage{ 7 | model_averaging(IC_for, IC_against) 8 | } 9 | \arguments{ 10 | \item{IC_for}{A numeric vector or the output of \code{compare}} 11 | 12 | \item{IC_against}{A numeric vector or the output of \code{compare}} 13 | } 14 | \value{ 15 | A \code{data.frame} with the following columns: 16 | \describe{ 17 | \item{\code{wFor}}{The aggregated weight of the models in favor.} 18 | \item{\code{wAgainst}}{The aggregated weight of the models against.} 19 | \item{\code{Factor}}{The Bayes factor (ratio of \code{wFor} to \code{wAgainst}).} 20 | } 21 | If \code{IC_for} is a data frame, a matrix with rows corresponding to each IC measure is returned. 22 | } 23 | \description{ 24 | Computes model weights and a Bayes factor by comparing two groups of models based on their 25 | Information Criterion (IC) values. The function works with either numeric vectors or data 26 | frames containing multiple IC measures (e.g., MD, BPIC, DIC). 27 | } 28 | \details{ 29 | When provided with numeric vectors, it computes the weights for the two groups by first 30 | converting the IC values into relative weights and then normalizing them. When provided with 31 | a data frame, it assumes that the data frame is the output of a call to \code{compare} 32 | and applies averaging to each IC metric 33 | } 34 | \examples{ 35 | # First set up some example models (normally these would be alternative models) 36 | samples_LNR2 <- subset(samples_LNR, length.out = 45) 37 | samples_LNR3 <- subset(samples_LNR, length.out = 40) 38 | samples_LNR4 <- subset(samples_LNR, length.out = 35) 39 | 40 | # Run compare on them, BayesFactor = F is set for speed. 41 | ICs <- compare(list(S1 = samples_LNR, S2 = samples_LNR2, 42 | S3 = samples_LNR3, S4 = samples_LNR4), BayesFactor = FALSE) 43 | 44 | # Model averaging can either be done with a vector of ICs: 45 | model_averaging(ICs$BPIC[1:2], ICs$BPIC[2:4]) 46 | 47 | # Or the output of compare: 48 | model_averaging(ICs[1:2,], ICs[3:4,]) 49 | 50 | } 51 | -------------------------------------------------------------------------------- /man/pairs_posterior.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/plotting.R 3 | \name{pairs_posterior} 4 | \alias{pairs_posterior} 5 | \title{Plot Within-Chain Correlations} 6 | \usage{ 7 | pairs_posterior( 8 | emc, 9 | selection = "alpha", 10 | scale_subjects = TRUE, 11 | do_plot = TRUE, 12 | N = 500, 13 | ... 14 | ) 15 | } 16 | \arguments{ 17 | \item{emc}{An emc object} 18 | 19 | \item{selection}{A Character string. Indicates which parameter type to 20 | plot (\code{alpha}, \code{mu}, \code{variance}, \code{covariance}, \code{correlation}).} 21 | 22 | \item{scale_subjects}{Boolean. To standardize each participant with \code{selection = "alpha"}, 23 | by subtracting the mean and divding by the standard deviation. This ensures the plot has every participant on the same scale.} 24 | 25 | \item{do_plot}{Boolean. Whether to plot the pairs plot, if \code{FALSE}, only the correlations 26 | are returned.} 27 | 28 | \item{N}{Integer for maximum number of iterations used (defaults to 500). 29 | If number of samples in stage or selection exceeds N, a random subset will be taken of size N} 30 | 31 | \item{...}{Optional arguments that can be passed to \code{get_pars}} 32 | } 33 | \value{ 34 | Invisibly returns a matrix with the correlations between the parameters. 35 | } 36 | \description{ 37 | Plots within-chain parameter correlations (upper triangle) and corresponding 38 | scatterplots (lower triangle) to visualize parameter sloppiness. 39 | } 40 | \details{ 41 | If \code{selection = alpha} the parameter chains are concatenated across participants, 42 | (after standardizing if \code{scale_subjects = TRUE}) and then correlated. 43 | } 44 | \examples{ 45 | \donttest{ 46 | # Plot the sloppiness for the individual-level subjects 47 | pairs_posterior(samples_LNR, selection = "alpha") 48 | 49 | # We can also choose group-level parameters and subsets of the parameter space 50 | pairs_posterior(samples_LNR, use_par = c("m", "t0"), selection = "sigma2") 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /man/parameters.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/priors.R, R/s3_funcs.R 3 | \name{parameters.emc.prior} 4 | \alias{parameters.emc.prior} 5 | \alias{parameters.emc} 6 | \alias{parameters} 7 | \title{Return Data Frame of Parameters} 8 | \usage{ 9 | \method{parameters}{emc.prior}(x, selection = "mu", N = 1000, covariates = NULL, ...) 10 | 11 | \method{parameters}{emc}(x, selection = "mu", N = NULL, resample = FALSE, ...) 12 | 13 | parameters(x, ...) 14 | } 15 | \arguments{ 16 | \item{x}{An emc or emc.prior object} 17 | 18 | \item{selection}{String designating parameter type (e.g. mu, sigma2, correlation, alpha)} 19 | 20 | \item{N}{Integer. How many samples to take from the posterior/prior. If \code{NULL} will return the full posterior} 21 | 22 | \item{covariates}{For priors, possible covariates in the design} 23 | 24 | \item{...}{Optional arguments that can be passed to \code{get_pars}} 25 | 26 | \item{resample}{Boolean. If \code{TRUE} will sample N samples from the posterior with replacement} 27 | } 28 | \value{ 29 | A data frame with one row for each sample 30 | (with a subjects column if selection = "alpha" and using draws from the posterior) 31 | } 32 | \description{ 33 | Return Data Frame of Parameters 34 | } 35 | \examples{ 36 | # For prior inference: 37 | # First set up a prior 38 | design_DDMaE <- design(data = forstmann,model=DDM, 39 | formula =list(v~0+S,a~E, t0~1, s~1, Z~1, sv~1, SZ~1), 40 | constants=c(s=log(1))) 41 | # Then set up a prior using make_prior 42 | p_vector=c(v_Sleft=-2,v_Sright=2,a=log(1),a_Eneutral=log(1.5),a_Eaccuracy=log(2), 43 | t0=log(.2),Z=qnorm(.5),sv=log(.5),SZ=qnorm(.5)) 44 | psd <- c(v_Sleft=1,v_Sright=1,a=.3,a_Eneutral=.3,a_Eaccuracy=.3, 45 | t0=.4,Z=1,sv=.4,SZ=1) 46 | # Here we left the variance prior at default 47 | prior_DDMaE <- prior(design_DDMaE,mu_mean=p_vector,mu_sd=psd) 48 | # Get our prior samples 49 | parameters(prior_DDMaE, N = 100) 50 | # For posterior inference: 51 | # Get 100 samples of the group-level mean (the default) 52 | parameters(samples_LNR, N = 100) 53 | # or from the individual-level parameters and mapped 54 | parameters(samples_LNR, selection = "alpha", map = TRUE) 55 | } 56 | -------------------------------------------------------------------------------- /man/plot.emc.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/s3_funcs.R 3 | \name{plot.emc} 4 | \alias{plot.emc} 5 | \title{Plot Function for emc Objects} 6 | \usage{ 7 | \method{plot}{emc}( 8 | x, 9 | stage = "sample", 10 | selection = c("mu", "sigma2", "alpha"), 11 | layout = NA, 12 | ... 13 | ) 14 | } 15 | \arguments{ 16 | \item{x}{An object of class \code{emc}} 17 | 18 | \item{stage}{A character string indicating the sampling stage to be summarized. 19 | Can be \code{preburn}, \code{burn}, \code{adapt}, or \code{sample}.} 20 | 21 | \item{selection}{A character vector indicating the parameter group(s). 22 | Defaults to \code{mu}, \code{sigma2}, and \code{alpha}.} 23 | 24 | \item{layout}{A vector indicating which layout to use as in par(mfrow = layout). If NA, will automatically generate an appropriate layout.} 25 | 26 | \item{...}{Optional arguments that can be passed to \code{get_pars} or \code{plot.default} (see \code{par()})} 27 | } 28 | \value{ 29 | A trace/acf plot of the selected MCMC chains 30 | } 31 | \description{ 32 | Makes trace plots for model parameters. 33 | } 34 | \details{ 35 | If an emc object that has not been run with \code{fit} yet is supplied 36 | prior plots will be returned. 37 | } 38 | \examples{ 39 | plot(samples_LNR) 40 | # Or trace autocorrelation for the second subject: 41 | plot(samples_LNR, subject = 2, selection = "alpha") 42 | 43 | # Can also plot the trace of for example the group-level correlation: 44 | plot(samples_LNR, selection = "correlation", col = c("green", "purple", "orange"), lwd = 2) 45 | } 46 | -------------------------------------------------------------------------------- /man/plot.emc.design.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/design.R 3 | \name{plot.emc.design} 4 | \alias{plot.emc.design} 5 | \title{Plot method for emc.design objects} 6 | \usage{ 7 | \method{plot}{emc.design}( 8 | x, 9 | p_vector, 10 | data = NULL, 11 | factors = NULL, 12 | plot_factor = NULL, 13 | n_data_sim = 10, 14 | functions = NULL, 15 | ... 16 | ) 17 | } 18 | \arguments{ 19 | \item{x}{An object of class \code{emc.design} containing the design to plot} 20 | 21 | \item{p_vector}{A named vector of parameter values to use for data generation} 22 | 23 | \item{data}{Optional data frame to overlay on the design plot. If NULL, data will be simulated.} 24 | 25 | \item{factors}{Character vector. Factors to use for varying parameters in the plot} 26 | 27 | \item{plot_factor}{Optional character. Make separate plots for each level of this factor} 28 | 29 | \item{n_data_sim}{Integer. If data is NULL, number of simulated datasets to generate for the plot. Default is 10.} 30 | 31 | \item{functions}{Optional named list of functions that create additional columns in the data} 32 | 33 | \item{...}{Additional arguments passed to \code{make_design_plot}} 34 | } 35 | \value{ 36 | No return value, called for side effect of plotting 37 | } 38 | \description{ 39 | Makes design illustration by plotting simulated data based on the design 40 | } 41 | -------------------------------------------------------------------------------- /man/plot.emc.prior.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/priors.R 3 | \name{plot.emc.prior} 4 | \alias{plot.emc.prior} 5 | \title{Plot a prior} 6 | \usage{ 7 | \method{plot}{emc.prior}( 8 | x, 9 | selection = "mu", 10 | do_plot = TRUE, 11 | covariates = NULL, 12 | layout = NA, 13 | N = 50000, 14 | ... 15 | ) 16 | } 17 | \arguments{ 18 | \item{x}{An \code{emc_prior} element} 19 | 20 | \item{selection}{A Character string. Indicates which parameter type to use (e.g., \code{alpha}, \code{mu}, \code{sigma2}, \code{correlation}).} 21 | 22 | \item{do_plot}{Boolean. If \code{FALSE} will only return prior samples and omit plotting.} 23 | 24 | \item{covariates}{dataframe/functions as specified by the design} 25 | 26 | \item{layout}{A vector indicating which layout to use as in par(mfrow = layout). If NA, will automatically generate an appropriate layout.} 27 | 28 | \item{N}{Integer. How many prior samples to draw} 29 | 30 | \item{...}{Optional arguments that can be passed to get_pars, histogram, plot.default (see par()), 31 | or arguments required for the types of models e.g. n_factors for type = "factor"} 32 | } 33 | \value{ 34 | An invisible mcmc.list object with prior samples of the selected type 35 | } 36 | \description{ 37 | Takes a prior object and plots the selected implied prior 38 | } 39 | \examples{ 40 | \donttest{ 41 | # First define a design for the model 42 | design_DDMaE <- design(data = forstmann,model=DDM, 43 | formula =list(v~0+S,a~E, t0~1, s~1, Z~1, sv~1, SZ~1), 44 | constants=c(s=log(1))) 45 | # Then set up a prior using make_prior 46 | p_vector=c(v_Sleft=-2,v_Sright=2,a=log(1),a_Eneutral=log(1.5),a_Eaccuracy=log(2), 47 | t0=log(.2),Z=qnorm(.5),sv=log(.5),SZ=qnorm(.5)) 48 | psd <- c(v_Sleft=1,v_Sright=1,a=.3,a_Eneutral=.3,a_Eaccuracy=.3, 49 | t0=.4,Z=1,sv=.4,SZ=1) 50 | # Here we left the variance prior at default 51 | prior_DDMaE <- prior(design_DDMaE,mu_mean=p_vector,mu_sd=psd) 52 | # Now we can plot all sorts of (implied) priors 53 | plot(prior_DDMaE, selection = "mu", N = 1e3) 54 | plot(prior_DDMaE, selection = "mu", mapped = FALSE, N=1e3) 55 | # We can also plot the implied prior on the participant level effects. 56 | plot(prior_DDMaE, selection = "alpha", col = "green", N = 1e3) 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /man/plot_cdf.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/plot_data.R 3 | \name{plot_cdf} 4 | \alias{plot_cdf} 5 | \title{Plot Defective Cumulative Distribution Functions} 6 | \usage{ 7 | plot_cdf( 8 | input, 9 | post_predict = NULL, 10 | prior_predict = NULL, 11 | subject = NULL, 12 | quants = c(0.025, 0.975), 13 | functions = NULL, 14 | factors = NULL, 15 | defective_factor = "R", 16 | n_cores = 1, 17 | n_post = 50, 18 | layout = NA, 19 | to_plot = c("data", "posterior", "prior")[1:2], 20 | use_lim = c("data", "posterior", "prior")[1:2], 21 | legendpos = c("top", "topright"), 22 | posterior_args = list(), 23 | prior_args = list(), 24 | ... 25 | ) 26 | } 27 | \arguments{ 28 | \item{input}{Either an \code{emc} object or a data frame, or a \emph{list} of such objects.} 29 | 30 | \item{post_predict}{Optional posterior predictive data (matching columns) or \emph{list} thereof.} 31 | 32 | \item{prior_predict}{Optional prior predictive data (matching columns) or \emph{list} thereof.} 33 | 34 | \item{subject}{Subset the data to a single subject (by index or name).} 35 | 36 | \item{quants}{Numeric vector of credible interval bounds (e.g. \code{c(0.025, 0.975)}).} 37 | 38 | \item{functions}{A function (or list of functions) that create new columns in the datasets or predictives} 39 | 40 | \item{factors}{Character vector of factor names to aggregate over; 41 | defaults to plotting full data set ungrouped by factors if \code{NULL}.} 42 | 43 | \item{defective_factor}{Name of the factor used for the defective CDF (default "R").} 44 | 45 | \item{n_cores}{Number of CPU cores to use if generating predictives from an \code{emc} object.} 46 | 47 | \item{n_post}{Number of posterior draws to simulate if needed for predictives.} 48 | 49 | \item{layout}{Numeric vector used in \code{par(mfrow=...)}; use \code{NA} for auto-layout.} 50 | 51 | \item{to_plot}{Character vector: any of \code{"data"}, \code{"posterior"}, \code{"prior"}.} 52 | 53 | \item{use_lim}{Character vector controlling which source(s) define \code{xlim}.} 54 | 55 | \item{legendpos}{Character vector controlling the positions of the legends} 56 | 57 | \item{posterior_args}{Optional list of graphical parameters for posterior lines/ribbons.} 58 | 59 | \item{prior_args}{Optional list of graphical parameters for prior lines/ribbons.} 60 | 61 | \item{...}{Other graphical parameters for the real data lines.} 62 | } 63 | \value{ 64 | Returns \code{NULL} invisibly. 65 | } 66 | \description{ 67 | Plots panels of cumulative distribution functions (CDFs) for each level of the specified 68 | defective factor in the data. The CDFs are \emph{defective}; each factor level's CDF 69 | scales only up to that level's proportion. Summed across levels, the maximum is 1. 70 | Optionally, posterior and/or prior predictive CDFs can be overlaid. 71 | } 72 | \examples{ 73 | # Plot defective CDF for data only 74 | # plot_cdf(forstmann, to_plot = "data") 75 | # 76 | # Plot with posterior predictions 77 | # plot_cdf(samples_LNR, to_plot = c("data","posterior"), n_post=10) 78 | # 79 | # Or a list of multiple emc objects ... 80 | } 81 | -------------------------------------------------------------------------------- /man/plot_density.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/plot_data.R 3 | \name{plot_density} 4 | \alias{plot_density} 5 | \title{Plot Defective Densities} 6 | \usage{ 7 | plot_density( 8 | input, 9 | post_predict = NULL, 10 | prior_predict = NULL, 11 | subject = NULL, 12 | quants = c(0.025, 0.975), 13 | functions = NULL, 14 | factors = NULL, 15 | defective_factor = "R", 16 | n_cores = 1, 17 | n_post = 50, 18 | layout = NA, 19 | to_plot = c("data", "posterior", "prior")[1:2], 20 | use_lim = c("data", "posterior", "prior")[1:2], 21 | legendpos = c("topright", "top"), 22 | posterior_args = list(), 23 | prior_args = list(), 24 | ... 25 | ) 26 | } 27 | \arguments{ 28 | \item{input}{Either an \code{emc} object or a data frame, or a \emph{list} of such objects.} 29 | 30 | \item{post_predict}{Optional posterior predictive data (matching columns) or \emph{list} thereof.} 31 | 32 | \item{prior_predict}{Optional prior predictive data (matching columns) or \emph{list} thereof.} 33 | 34 | \item{subject}{Subset the data to a single subject (by index or name).} 35 | 36 | \item{quants}{Numeric vector of credible interval bounds (e.g. \code{c(0.025, 0.975)}).} 37 | 38 | \item{functions}{A function (or list of functions) that create new columns in the datasets or predictives} 39 | 40 | \item{factors}{Character vector of factor names to aggregate over; 41 | defaults to plotting full data set ungrouped by factors if \code{NULL}.} 42 | 43 | \item{defective_factor}{Name of the factor used for the defective CDF (default "R").} 44 | 45 | \item{n_cores}{Number of CPU cores to use if generating predictives from an \code{emc} object.} 46 | 47 | \item{n_post}{Number of posterior draws to simulate if needed for predictives.} 48 | 49 | \item{layout}{Numeric vector used in \code{par(mfrow=...)}; use \code{NA} for auto-layout.} 50 | 51 | \item{to_plot}{Character vector: any of \code{"data"}, \code{"posterior"}, \code{"prior"}.} 52 | 53 | \item{use_lim}{Character vector controlling which source(s) define \code{xlim}.} 54 | 55 | \item{legendpos}{Character vector controlling the positions of the legends} 56 | 57 | \item{posterior_args}{Optional list of graphical parameters for posterior lines/ribbons.} 58 | 59 | \item{prior_args}{Optional list of graphical parameters for prior lines/ribbons.} 60 | 61 | \item{...}{Other graphical parameters for the real data lines.} 62 | } 63 | \description{ 64 | Plots panels that contain a set of densities for each level of the specified defective factor in the data. 65 | These densities are defective; their areas are relative to the respective 66 | proportions of the defective factor levels. Across all levels, the area sums to 1. 67 | Optionally, posterior/prior predictive densities can be overlaid. 68 | } 69 | \examples{ 70 | # Plot defective densities for each subject and the factor combination in the design: 71 | plot_density(forstmann) 72 | # or for one subject: 73 | plot_density(forstmann, subject = 1) 74 | # Now collapsing across subjects and using a different defective factor: 75 | plot_density(forstmann, factors = "S", defective_factor = "E") 76 | # Or plot posterior predictives 77 | plot_density(samples_LNR, n_post = 10) 78 | } 79 | -------------------------------------------------------------------------------- /man/plot_design.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/design.R, R/priors.R, R/s3_funcs.R 3 | \name{plot_design.emc.design} 4 | \alias{plot_design.emc.design} 5 | \alias{plot_design.emc.prior} 6 | \alias{plot_design} 7 | \alias{plot_design.emc} 8 | \title{Plot Design} 9 | \usage{ 10 | \method{plot_design}{emc.design}( 11 | x, 12 | data = NULL, 13 | factors = NULL, 14 | plot_factor = NULL, 15 | n_data_sim = 10, 16 | p_vector = NULL, 17 | functions = NULL, 18 | ... 19 | ) 20 | 21 | \method{plot_design}{emc.prior}( 22 | x, 23 | data = NULL, 24 | factors = NULL, 25 | plot_factor = NULL, 26 | n_data_sim = 10, 27 | p_vector = NULL, 28 | functions = NULL, 29 | ... 30 | ) 31 | 32 | plot_design( 33 | x, 34 | data = NULL, 35 | factors = NULL, 36 | plot_factor = NULL, 37 | n_data_sim = 10, 38 | p_vector = NULL, 39 | functions = NULL, 40 | ... 41 | ) 42 | 43 | \method{plot_design}{emc}( 44 | x, 45 | data = NULL, 46 | factors = NULL, 47 | plot_factor = NULL, 48 | n_data_sim = 10, 49 | p_vector = NULL, 50 | functions = NULL, 51 | ... 52 | ) 53 | } 54 | \arguments{ 55 | \item{x}{An \code{emc} or \code{emc.prior} object containing the design to plot} 56 | 57 | \item{data}{Optional data to overlay on the design plot} 58 | 59 | \item{factors}{Factors to use for varying parameters} 60 | 61 | \item{plot_factor}{Optional. Make separate plots for each level of this factor} 62 | 63 | \item{n_data_sim}{If data is provided, number of simulated datasets to generate for the plot. Default is 10.} 64 | 65 | \item{p_vector}{Only needed when x is an \code{emc.design} object, which parameters to use for data generation.} 66 | 67 | \item{functions}{A named list of functions that create additional columns in the data.} 68 | 69 | \item{...}{Additional arguments to pass to \code{make_design_plot}} 70 | } 71 | \value{ 72 | No return value. Just plots the design 73 | } 74 | \description{ 75 | Makes design illustration by plotting simulated data based on the design 76 | } 77 | -------------------------------------------------------------------------------- /man/plot_pars.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/plotting.R 3 | \name{plot_pars} 4 | \alias{plot_pars} 5 | \title{Plots Density for Parameters} 6 | \usage{ 7 | plot_pars( 8 | emc, 9 | layout = NA, 10 | selection = "mu", 11 | show_chains = FALSE, 12 | plot_prior = TRUE, 13 | N = 10000, 14 | use_prior_lim = !all_subjects, 15 | lpos = "topright", 16 | true_pars = NULL, 17 | all_subjects = FALSE, 18 | prior_args = list(), 19 | true_args = list(), 20 | ... 21 | ) 22 | } 23 | \arguments{ 24 | \item{emc}{An emc object} 25 | 26 | \item{layout}{A vector indicating which layout to use as in par(mfrow = layout). If NA, will automatically generate an appropriate layout.} 27 | 28 | \item{selection}{A Character string. Indicates which parameter type to use (e.g., \code{alpha}, \code{mu}, \code{sigma2}, \code{correlation}).} 29 | 30 | \item{show_chains}{Boolean (defaults to \code{FALSE}) plots a separate density for each chain.} 31 | 32 | \item{plot_prior}{Boolean. If \code{TRUE} will overlay prior density in the plot (default in red)} 33 | 34 | \item{N}{Integer. How many prior samples to draw} 35 | 36 | \item{use_prior_lim}{Boolean. If \code{TRUE} will use xlimits based on prior density, otherwise based on posterior density.} 37 | 38 | \item{lpos}{Character. Where to plot the contraction statistic.} 39 | 40 | \item{true_pars}{A vector or emc object. Can be used to visualize recovery. 41 | If a vector will plot a vertical line for each parameter at the appropriate place. 42 | If an emc object will plot the densities of the object as well, assumed to be the data-generating posteriors.} 43 | 44 | \item{all_subjects}{Boolean. Will plot the densities of all (selected) subjects overlaid with the group-level distribution} 45 | 46 | \item{prior_args}{A list. Optional additional arguments to be passed to plot.default for the plotting of the prior density (see \code{par()})} 47 | 48 | \item{true_args}{A list. Optional additional arguments to be passed to plot.default for the plotting of the true parameters (see \code{par()})} 49 | 50 | \item{...}{Optional arguments that can be passed to \code{get_pars}, \code{density}, or \code{plot.default} (see \code{par()})} 51 | } 52 | \value{ 53 | An invisible return of the contraction statistics for the selected parameter type 54 | } 55 | \description{ 56 | Plots the posterior and prior density for selected parameters of a model. 57 | Full range of samples manipulations described in \code{get_pars}. 58 | } 59 | \examples{ 60 | # Full range of possibilities described in get_pars 61 | plot_pars(samples_LNR) 62 | # Or plot all subjects 63 | plot_pars(samples_LNR, all_subjects = TRUE, col = 'purple') 64 | # Or plot recovery 65 | true_emc <- samples_LNR # This would normally be the data-generating samples 66 | plot_pars(samples_LNR, true_pars = true_emc, true_args = list(col = 'blue'), adjust = 2) 67 | } 68 | -------------------------------------------------------------------------------- /man/plot_relations.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/factor_analysis.R 3 | \name{plot_relations} 4 | \alias{plot_relations} 5 | \title{Plot Group-Level Relations} 6 | \usage{ 7 | plot_relations( 8 | emc = NULL, 9 | stage = "sample", 10 | plot_cred = TRUE, 11 | plot_means = TRUE, 12 | only_cred = FALSE, 13 | nice_names = NULL, 14 | ... 15 | ) 16 | } 17 | \arguments{ 18 | \item{emc}{An EMC2 object, commonly the output of \code{run_emc()}.} 19 | 20 | \item{stage}{Character. The stage from which to take the samples, defaults to 21 | the sampling stage \code{sample}.} 22 | 23 | \item{plot_cred}{Boolean. Whether to plot the 95 percent credible intervals or not} 24 | 25 | \item{plot_means}{Boolean. Whether to plot the means or not} 26 | 27 | \item{only_cred}{Boolean. Whether to only plot credible values} 28 | 29 | \item{nice_names}{Character string. Alternative names to give the parameters} 30 | 31 | \item{...}{Optional additional arguments} 32 | } 33 | \value{ 34 | No return value, creates a plot of group-level relations 35 | } 36 | \description{ 37 | An adjusted version of the \code{corrplot} package function \code{corrplot()} tailored 38 | to \code{EMC2} and the plotting of estimated correlations. 39 | } 40 | \examples{ 41 | # For a given set of hierarchical model samples we can make a 42 | # correlation matrix plot. 43 | plot_relations(samples_LNR, only_cred = TRUE, plot_cred = TRUE) 44 | # We can also only plot the correlations where the credible interval does not include zero 45 | plot_relations(samples_LNR, plot_means = TRUE, only_cred = TRUE) 46 | 47 | } 48 | -------------------------------------------------------------------------------- /man/plot_sbc_ecdf.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/SBC.R 3 | \name{plot_sbc_ecdf} 4 | \alias{plot_sbc_ecdf} 5 | \title{Plot the ECDF Difference in SBC Ranks} 6 | \usage{ 7 | plot_sbc_ecdf(ranks, layout = NA) 8 | } 9 | \arguments{ 10 | \item{ranks}{A list of named dataframes of the rank statistic} 11 | 12 | \item{layout}{Optional. A numeric vector specifying the layout using \code{par(mfrow = layout)}} 13 | } 14 | \value{ 15 | No returns 16 | } 17 | \description{ 18 | Plots the difference in observed cumulative rank statistics and the 19 | expected cumulative distribution of a uniform distribution. The blue 20 | shaded areas indicate the 95\% credible interval. 21 | } 22 | -------------------------------------------------------------------------------- /man/plot_sbc_hist.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/SBC.R 3 | \name{plot_sbc_hist} 4 | \alias{plot_sbc_hist} 5 | \title{Plot the Histogram of the Observed Rank Statistics of SBC} 6 | \usage{ 7 | plot_sbc_hist(ranks, bins = 10, layout = NA) 8 | } 9 | \arguments{ 10 | \item{ranks}{A list of named dataframes of the rank statistic} 11 | 12 | \item{bins}{An integer specifying the number of bins to use when plotting the histogram} 13 | 14 | \item{layout}{Optional. A numeric vector specifying the layout using \code{par(mfrow = layout)}} 15 | } 16 | \value{ 17 | No returns 18 | } 19 | \description{ 20 | Note that this plot is dependent on the number of bins, and a more general 21 | visualization is to use \code{plot_sbc_ecdf} 22 | } 23 | -------------------------------------------------------------------------------- /man/plot_stat.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/plot_data.R 3 | \name{plot_stat} 4 | \alias{plot_stat} 5 | \title{Plot Statistics on Data} 6 | \usage{ 7 | plot_stat( 8 | input, 9 | post_predict = NULL, 10 | prior_predict = NULL, 11 | stat_fun, 12 | stat_name = NULL, 13 | subject = NULL, 14 | factors = NULL, 15 | n_cores = 1, 16 | n_post = 50, 17 | quants = c(0.025, 0.5, 0.975), 18 | functions = NULL, 19 | layout = NA, 20 | to_plot = c("data", "posterior", "prior")[1:2], 21 | use_lim = c("data", "posterior", "prior")[1:2], 22 | legendpos = c("topleft", "top"), 23 | posterior_args = list(), 24 | prior_args = list(), 25 | ... 26 | ) 27 | } 28 | \arguments{ 29 | \item{input}{Either an \code{emc} object or a data frame, or a \emph{list} of such objects.} 30 | 31 | \item{post_predict}{Optional posterior predictive data (matching columns) or \emph{list} thereof.} 32 | 33 | \item{prior_predict}{Optional prior predictive data (matching columns) or \emph{list} thereof.} 34 | 35 | \item{stat_fun}{A function that can be applied to the data and returns a single value or a vector of values.} 36 | 37 | \item{stat_name}{The name of the calculated quantity} 38 | 39 | \item{subject}{Subset the data to a single subject (by index or name).} 40 | 41 | \item{factors}{Character vector of factor names to aggregate over; 42 | defaults to plotting full data set ungrouped by factors if \code{NULL}.} 43 | 44 | \item{n_cores}{Number of CPU cores to use if generating predictives from an \code{emc} object.} 45 | 46 | \item{n_post}{Number of posterior draws to simulate if needed for predictives.} 47 | 48 | \item{quants}{Numeric vector of credible interval bounds (e.g. \code{c(0.025, 0.975)}).} 49 | 50 | \item{functions}{A function (or list of functions) that create new columns in the datasets or predictives} 51 | 52 | \item{layout}{Numeric vector used in \code{par(mfrow=...)}; use \code{NA} for auto-layout.} 53 | 54 | \item{to_plot}{Character vector: any of \code{"data"}, \code{"posterior"}, \code{"prior"}.} 55 | 56 | \item{use_lim}{Character vector controlling which source(s) define \code{xlim}.} 57 | 58 | \item{legendpos}{Character vector controlling the positions of the legends} 59 | 60 | \item{posterior_args}{Optional list of graphical parameters for posterior lines/ribbons.} 61 | 62 | \item{prior_args}{Optional list of graphical parameters for prior lines/ribbons.} 63 | 64 | \item{...}{Other graphical parameters for the real data lines.} 65 | } 66 | \value{ 67 | an invisible data frame with the stat applied to the real data, posterior predictives and/or prior predictives 68 | } 69 | \description{ 70 | Plots panels that contain a set of densities for each level of the specified \code{factor} 71 | The densities represent the predicted data across the posterior, the vertical lines represent the real data. 72 | } 73 | \examples{ 74 | # For example plot the observed and predicted response accuracy 75 | # Can also apply more sophisticated statistics 76 | drt <- function(data) diff(tapply(data$rt,data[,c("E")],mean)) 77 | plot_stat(samples_LNR, stat_fun = drt, n_post = 10, stat_name = "RT diff Speed - A/N") 78 | 79 | } 80 | -------------------------------------------------------------------------------- /man/predict.emc.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/priors.R, R/s3_funcs.R 3 | \name{predict.emc.prior} 4 | \alias{predict.emc.prior} 5 | \alias{predict.emc} 6 | \title{Generate Posterior/Prior Predictives} 7 | \usage{ 8 | \method{predict}{emc.prior}(object, data = NULL, n_post = 50, n_cores = 1, n_trials = NULL, ...) 9 | 10 | \method{predict}{emc}( 11 | object, 12 | hyper = FALSE, 13 | n_post = 50, 14 | n_cores = 1, 15 | stat = c("random", "mean", "median")[1], 16 | ... 17 | ) 18 | } 19 | \arguments{ 20 | \item{object}{An emc or emc.prior object from which to generate predictives} 21 | 22 | \item{data}{A data frame needed to exactly match the original design} 23 | 24 | \item{n_post}{Integer. Number of generated datasets} 25 | 26 | \item{n_cores}{Integer. Number of cores across which there should be parallellized} 27 | 28 | \item{n_trials}{An integer. If \code{data} isn't provided (although preferred), 29 | can generate data based on \code{n_trials} per cell of \code{design}} 30 | 31 | \item{...}{Optional additional arguments passed to \code{get_pars} or \code{make_data}} 32 | 33 | \item{hyper}{Boolean. Defaults to \code{FALSE}. If \code{TRUE}, simulates from the group-level (\code{hyper}) 34 | parameters instead of the subject-level parameters.} 35 | 36 | \item{stat}{Character. Can be \code{mean}, \code{median} or \code{random} (i.e., the default). 37 | Will take either random samples from the chain(s) or use the mean or median of the parameter estimates.} 38 | } 39 | \value{ 40 | A list of simulated data sets of length \code{n_post} 41 | } 42 | \description{ 43 | Simulate \code{n_post} data sets using the posterior/prior parameter estimates 44 | } 45 | \examples{ 46 | \donttest{ 47 | # based on an emc object ran by fit() we can generate posterior predictives 48 | predict(samples_LNR, n_cores = 1, n_post = 10) 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /man/prior.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/priors.R 3 | \name{prior} 4 | \alias{prior} 5 | \title{Specify Priors for the Chosen Model} 6 | \usage{ 7 | prior( 8 | design, 9 | type = NULL, 10 | update = NULL, 11 | do_ask = NULL, 12 | fill_default = TRUE, 13 | ... 14 | ) 15 | } 16 | \arguments{ 17 | \item{design}{Design list for which a prior is constructed, typically the output of \code{design()}} 18 | 19 | \item{type}{Character. What type of group-level model you plan on using i.e. \code{diagonal}} 20 | 21 | \item{update}{Prior list from which to copy values} 22 | 23 | \item{do_ask}{Character. For which parameter types or hyperparameters to ask for prior specification, 24 | i.e. \code{Sigma}, \code{mu} or \code{loadings} for factor models, but \code{theta_mu_mean} or \code{A} also works.} 25 | 26 | \item{fill_default}{Boolean, If \code{TRUE} will fill all non-specified parameters, and parameters outside of \code{do_ask}, to default values} 27 | 28 | \item{...}{Either values to prefill, i.e. \code{theta_mu_mean = c(1:6)}, or additional arguments such as \code{n_factors = 2}} 29 | } 30 | \value{ 31 | A prior list object 32 | } 33 | \description{ 34 | These values are entered manually by default but can be recycled from another prior (given in the \code{update} argument). 35 | } 36 | \details{ 37 | Where a value is not supplied, the user is prompted to enter numeric values (or functions that evaluate to numbers). 38 | 39 | To get the prior help use \code{prior_help(type)}. With \code{type} e.g. 'diagonal'. 40 | } 41 | \examples{ 42 | # First define a design for the model 43 | design_DDMaE <- design(data = forstmann,model=DDM, 44 | formula =list(v~0+S,a~E, t0~1, s~1, Z~1, sv~1, SZ~1), 45 | constants=c(s=log(1))) 46 | # Then set up a prior using prior 47 | p_vector=c(v_Sleft=-2,v_Sright=2,a=log(1),a_Eneutral=log(1.5),a_Eaccuracy=log(2), 48 | t0=log(.2),Z=qnorm(.5),sv=log(.5),SZ=qnorm(.5)) 49 | psd <- c(v_Sleft=1,v_Sright=1,a=.3,a_Eneutral=.3,a_Eaccuracy=.3, 50 | t0=.4,Z=1,sv=.4,SZ=1) 51 | # Here we left the variance prior at default 52 | prior_DDMaE <- prior(design_DDMaE,mu_mean=p_vector,mu_sd=psd) 53 | # Also add a group-level variance prior: 54 | pscale <- c(v_Sleft=.6,v_Sright=.6,a=.3,a_Eneutral=.3,a_Eaccuracy=.3, 55 | t0=.2,Z=.5,sv=.4,SZ=.3) 56 | df <- .4 57 | prior_DDMaE <- prior(design_DDMaE,mu_mean=p_vector,mu_sd=psd, A = pscale, df = df) 58 | # If we specify a new design 59 | design_DDMat0E <- design(data = forstmann,model=DDM, 60 | formula =list(v~0+S,a~E, t0~E, s~1, Z~1, sv~1, SZ~1), 61 | constants=c(s=log(1))) 62 | # We can easily update the prior 63 | prior_DDMat0E <- prior(design_DDMat0E, update = prior_DDMaE) 64 | } 65 | -------------------------------------------------------------------------------- /man/prior_help.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/priors.R 3 | \name{prior_help} 4 | \alias{prior_help} 5 | \title{Prior Specification Information} 6 | \usage{ 7 | prior_help(type) 8 | } 9 | \arguments{ 10 | \item{type}{A character string indicating which 'type' of model to run (e.g. 'standard' or 'single')} 11 | } 12 | \value{ 13 | Invisible return with a list of all the information that is also printed 14 | } 15 | \description{ 16 | Prints information associated with the prior for certain 'type' 17 | } 18 | \examples{ 19 | prior_help('diagonal') 20 | } 21 | -------------------------------------------------------------------------------- /man/profile_plot.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/plotting.R 3 | \name{profile_plot} 4 | \alias{profile_plot} 5 | \title{Likelihood Profile Plots} 6 | \usage{ 7 | profile_plot( 8 | data, 9 | design, 10 | p_vector, 11 | range = 0.5, 12 | layout = NA, 13 | p_min = NULL, 14 | p_max = NULL, 15 | use_par = NULL, 16 | n_point = 100, 17 | n_cores = 1, 18 | round = 3, 19 | true_args = list(), 20 | ... 21 | ) 22 | } 23 | \arguments{ 24 | \item{data}{A dataframe. Experimental data used, needed for the design mapping} 25 | 26 | \item{design}{A design list. Created using \code{design}.} 27 | 28 | \item{p_vector}{Named vector of parameter values (typically created with \code{sampled_pars(design)})} 29 | 30 | \item{range}{Numeric. The max and min will be p_vector + range/2 and p_vector - range/2, unless specified in p_min or p_max.} 31 | 32 | \item{layout}{A vector indicating which layout to use as in par(mfrow = layout). If NA, will automatically generate an appropriate layout.} 33 | 34 | \item{p_min}{Named vector. If specified will instead use these values for minimum range of the selected parameters.} 35 | 36 | \item{p_max}{Named vector. If specified will instead use these values for maximum range of the selected parameters.} 37 | 38 | \item{use_par}{Character vector. If specified will only plot the profiles for the specified parameters.} 39 | 40 | \item{n_point}{Integer. Number of evenly spaced points at which to calculate likelihood} 41 | 42 | \item{n_cores}{Number of likelihood points evenly spaced between the minimum and maximum likelihood range.} 43 | 44 | \item{round}{Integer. To how many digits will the output be rounded.} 45 | 46 | \item{true_args}{A list. Optional additional arguments that can be passed to plot.default for the plotting of the true vertical line.} 47 | 48 | \item{...}{Optional additional arguments that can be passed to plot.default.} 49 | } 50 | \value{ 51 | Vector with highest likelihood point, input and mismatch between true and highest point 52 | } 53 | \description{ 54 | Creates likelihood profile plots from a design and the experimental data by 55 | varying one model parameter while holding all others constant. 56 | } 57 | \examples{ 58 | \donttest{ 59 | # First create a design 60 | design_DDMaE <- design(data = forstmann,model=DDM, 61 | formula =list(v~0+S,a~E, t0~1, s~1, Z~1, sv~1, SZ~1), 62 | constants=c(s=log(1))) 63 | # Then create a p_vector: 64 | p_vector=c(v_Sleft=-2,v_Sright=2,a=log(.95),a_Eneutral=log(1.5),a_Eaccuracy=log(2), 65 | t0=log(.25),Z=qnorm(.5),sv=log(.5),SZ=qnorm(.5)) 66 | # Make a profile plot for some parameters. Specifying a custom range for t0. 67 | profile_plot(p_vector = p_vector, p_min = c(t0 = -1.35), 68 | p_max = c(t0 = -1.45), use_par = c("a", "t0", "SZ"), 69 | data = forstmann, design = design_DDMaE, n_point = 10) 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /man/recovery.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/s3_funcs.R 3 | \name{recovery.emc} 4 | \alias{recovery.emc} 5 | \alias{recovery} 6 | \title{Recovery Plots} 7 | \usage{ 8 | \method{recovery}{emc}( 9 | emc, 10 | true_pars, 11 | selection = "mu", 12 | layout = NA, 13 | do_CI = TRUE, 14 | correlation = "pearson", 15 | stat = "rmse", 16 | digits = 3, 17 | CI = 0.95, 18 | ci_plot_args = list(), 19 | ... 20 | ) 21 | 22 | recovery(emc, ...) 23 | } 24 | \arguments{ 25 | \item{emc}{An emc object} 26 | 27 | \item{true_pars}{A vector of data-generating parameters or an emc object with data-generating samples} 28 | 29 | \item{selection}{A Character vector. Indicates which parameter types to plot (e.g., \code{alpha}, \code{mu}, \code{sigma2}, \code{correlation}).} 30 | 31 | \item{layout}{A vector indicating which layout to use as in par(mfrow = layout). If NA, will automatically generate an appropriate layout.} 32 | 33 | \item{do_CI}{Boolean. If \code{TRUE} will also include bars representing the credible intervals} 34 | 35 | \item{correlation}{Character. Which correlation to include in the plot. Options are either \code{pearson} or \code{spearman}} 36 | 37 | \item{stat}{Character. Which statistic to include in the plot. Options are either \code{rmse} or \code{coverage}} 38 | 39 | \item{digits}{Integer. How many digits to round the statistic and correlation in the plot to} 40 | 41 | \item{CI}{Numeric. The size of the credible intervals. Default is .95 (95\%).} 42 | 43 | \item{ci_plot_args}{A list. Optional additional arguments to be passed to plot.default for the plotting of the credible intervals (see \code{par()})} 44 | 45 | \item{...}{Optional arguments that can be passed to \code{get_pars} or \code{plot.default} (see \code{par()})} 46 | } 47 | \value{ 48 | Invisible list with RMSE, coverage, and Pearson and Spearman correlations. 49 | } 50 | \description{ 51 | Plots recovery of data generating parameters/samples. 52 | Full range of samples manipulations described in \code{get_pars} 53 | } 54 | \examples{ 55 | # Make up some values that resemble posterior samples 56 | # Normally this would be true values that were used to simulate the data 57 | # Make up some values that resemble posterior samples 58 | # Normally this would be true values that were used to simulate the data 59 | pmat <- matrix(rnorm(12, mean = c(-1, -.6, -.4, -1.5), sd = .01), ncol = 4, byrow = TRUE) 60 | # Conventionally this would be created before one makes data with true values 61 | recovery(samples_LNR, pmat, correlation = "pearson", stat = "rmse", selection = "alpha") 62 | # Similarly we can plot recovery of other parameters with a set of true samples 63 | true_samples <- samples_LNR # Normally this would be data-generating samples 64 | recovery(samples_LNR, true_samples, correlation = "pearson", stat = "rmse", 65 | selection = "correlation", cex = 1.5, 66 | ci_plot_args = list(lty = 3, length = .2, lwd = 2, col = "brown")) 67 | } 68 | -------------------------------------------------------------------------------- /man/run_bridge_sampling.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/bridge_sampling.R 3 | \name{run_bridge_sampling} 4 | \alias{run_bridge_sampling} 5 | \title{Estimating Marginal Likelihoods Using WARP-III Bridge Sampling} 6 | \usage{ 7 | run_bridge_sampling( 8 | emc, 9 | stage = "sample", 10 | filter = NULL, 11 | repetitions = 1, 12 | cores_for_props = 4, 13 | cores_per_prop = 1, 14 | both_splits = TRUE, 15 | ... 16 | ) 17 | } 18 | \arguments{ 19 | \item{emc}{An emc object with a set of converged samples} 20 | 21 | \item{stage}{A character indicating which stage to use, defaults to \code{sample}} 22 | 23 | \item{filter}{An integer or vector. If integer, it will exclude up until 24 | that integer. If vector it will include everything in that range.} 25 | 26 | \item{repetitions}{An integer. How many times to repeat the bridge sampling scheme. Can help get an estimate of stability of the estimate.} 27 | 28 | \item{cores_for_props}{Integer. Warp-III evaluates the posterior over 4 different proposal densities. If you have the CPU, 4 cores will do this in parallel, 2 is also already helpful.} 29 | 30 | \item{cores_per_prop}{Integer. Per density we can also parallelize across subjects. Eventual cores will be \code{cores_for_props} * \code{cores_per_prop}. For efficiency users should prioritize cores_for_props being 4.} 31 | 32 | \item{both_splits}{Boolean. Bridge sampling uses a proposal density and a target density. We can estimate the stability of our samples and therefore MLL estimate, by running 2 bridge sampling iterations 33 | The first one uses the first half of the samples as the proposal and the second half as the target, the second run uses the opposite. If this is is set to \code{FALSE}, it will only run bridge sampling once and 34 | it will instead do an odd-even iterations split to get a more reasonable estimate for just one run.} 35 | 36 | \item{...}{Additional, optional more in-depth hyperparameters} 37 | } 38 | \value{ 39 | A vector of length repetitions which contains the marginal log likelihood estimates per repetition 40 | } 41 | \description{ 42 | Uses bridge sampling that matches a proposal distribution to the first three moments 43 | of the posterior distribution to get an accurate estimate of the marginal likelihood. 44 | The marginal likelihood can be used for computing Bayes factors and posterior model probabilities. 45 | } 46 | \details{ 47 | If not enough posterior samples were collected using \code{fit()}, 48 | bridge sampling can be unstable. It is recommended to run 49 | \code{run_bridge_sampling()} several times with the \code{repetitions} argument 50 | and to examine how stable the results are. 51 | 52 | It can be difficult to converge bridge sampling for exceptionally large models, 53 | because of a large number of subjects (> 100) and/or cognitive model parameters. 54 | 55 | For a practical introduction: 56 | 57 | Gronau, Q. F., Heathcote, A., & Matzke, D. (2020). Computing Bayes factors 58 | for evidence-accumulation models using Warp-III bridge sampling. 59 | \emph{Behavior research methods}, 52(2), 918-937. doi.org/10.3758/s13428-019-01290-6 60 | 61 | For mathematical background: 62 | 63 | Meng, X.-L., & Wong, W. H. (1996). Simulating ratios of normalizing 64 | constants via a simple identity: A theoretical exploration. \emph{Statistica Sinica}, 65 | 6, 831-860. http://www3.stat.sinica.edu.tw/statistica/j6n4/j6n43/j6n43.htm 66 | 67 | Meng, X.-L., & Schilling, S. (2002). Warp bridge sampling. 68 | \emph{Journal of Computational and Graphical Statistics}, 69 | 11(3), 552-586. doi.org/10.1198/106186002457 70 | } 71 | \examples{ 72 | \donttest{ 73 | # After `fit` has converged on a specific model 74 | # We can take those samples and calculate the marginal log-likelihood for them 75 | MLL <- run_bridge_sampling(samples_LNR, cores_for_props = 1, both_splits = FALSE) 76 | # This will run on 2*4 cores (since 4 is the default for ``cores_for_props``) 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /man/run_sbc.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/SBC.R 3 | \name{run_sbc} 4 | \alias{run_sbc} 5 | \title{Simulation-Based Calibration} 6 | \usage{ 7 | run_sbc( 8 | design_in, 9 | prior_in, 10 | replicates = 250, 11 | trials = 100, 12 | n_subjects = 30, 13 | plot_data = FALSE, 14 | verbose = TRUE, 15 | fileName = NULL, 16 | ... 17 | ) 18 | } 19 | \arguments{ 20 | \item{design_in}{An emc design list. The design of the model to be used in SBC} 21 | 22 | \item{prior_in}{An emc prior list. The prior for the design to be used in SBC} 23 | 24 | \item{replicates}{Integer. The number of samples to draw from the prior} 25 | 26 | \item{trials}{Integer. The number of trials of the simulated data (per subject)} 27 | 28 | \item{n_subjects}{Integer. Only used for hierarchical models. The number of subjects to be used in data generation of each replicate} 29 | 30 | \item{plot_data}{Boolean. Whether to plot the data simulated (aggregated across subjects)} 31 | 32 | \item{verbose}{Verbose. Whether to print progress related messages} 33 | 34 | \item{fileName}{Character. Highly recommended, saves temporary results to the fileName} 35 | 36 | \item{...}{A list of optional additional arguments that can be passed to \code{fit} and \code{make_emc}} 37 | } 38 | \value{ 39 | The ranks and prior samples. For hierarchical models also the prior-generated subject-level parameters. 40 | } 41 | \description{ 42 | Runs SBC for an EMC2 model and associated design. Returns 43 | normalized rank (between 0 and 1) and prior samples. For hierarchical models the group-level mean and 44 | the (implied) group-level (co-)variance are returned. 45 | For non-hierarchical models only the subject-level parameters rank is returned. 46 | } 47 | -------------------------------------------------------------------------------- /man/sampled_pars.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/design.R, R/priors.R, R/s3_funcs.R 3 | \name{sampled_pars} 4 | \alias{sampled_pars} 5 | \alias{sampled_pars.emc.design} 6 | \alias{sampled_pars.emc.prior} 7 | \alias{sampled_pars.emc} 8 | \title{Get Model Parameters from a Design} 9 | \usage{ 10 | sampled_pars( 11 | x, 12 | model = NULL, 13 | doMap = TRUE, 14 | add_da = FALSE, 15 | all_cells_dm = FALSE 16 | ) 17 | 18 | \method{sampled_pars}{emc.design}( 19 | x, 20 | model = NULL, 21 | doMap = TRUE, 22 | add_da = FALSE, 23 | all_cells_dm = FALSE 24 | ) 25 | 26 | \method{sampled_pars}{emc.prior}( 27 | x, 28 | model = NULL, 29 | doMap = TRUE, 30 | add_da = FALSE, 31 | all_cells_dm = FALSE 32 | ) 33 | 34 | \method{sampled_pars}{emc}( 35 | x, 36 | model = NULL, 37 | doMap = TRUE, 38 | add_da = FALSE, 39 | all_cells_dm = FALSE 40 | ) 41 | } 42 | \arguments{ 43 | \item{x}{an \code{emc.design} object made with \code{design()} or an \code{emc} object.} 44 | 45 | \item{model}{a model list. Defaults to the model specified in the design list.} 46 | 47 | \item{doMap}{logical. If \code{TRUE} will also include an attribute \code{map} 48 | with the design matrices that perform the mapping back to the design} 49 | 50 | \item{add_da}{Boolean. Whether to include the relevant data columns in the map attribute} 51 | 52 | \item{all_cells_dm}{Boolean. Whether to include all levels of a factor in the mapping attribute, 53 | even when one is dropped in the design} 54 | } 55 | \value{ 56 | Named vector. 57 | } 58 | \description{ 59 | Makes a vector with zeroes, with names and length corresponding to the 60 | model parameters of the design. 61 | } 62 | \examples{ 63 | # First define a design 64 | design_DDMaE <- design(data = forstmann,model=DDM, 65 | formula =list(v~0+S,a~E, t0~1, s~1, Z~1, sv~1, SZ~1), 66 | constants=c(s=log(1))) 67 | # Then for this design get which cognitive model parameters are sampled: 68 | sampled_pars(design_DDMaE) 69 | 70 | } 71 | -------------------------------------------------------------------------------- /man/samples_LNR.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/data.R 3 | \docType{data} 4 | \name{samples_LNR} 5 | \alias{samples_LNR} 6 | \title{LNR Model of Forstmann Data (First 3 Subjects)} 7 | \format{ 8 | An emc object. An emc object is a list with a 9 | specific structure and elements, as outlined below. 10 | \describe{ 11 | \item{data}{A list of dataframes, one for each subject included} 12 | \item{par_names}{A character vector containing the model parameter names} 13 | \item{n_pars}{The number of parameters in the model} 14 | \item{n_subjects}{The number of unique subject ID's in the data} 15 | \item{model}{A list containing the model functions} 16 | \item{nuisance}{A logical vector indicating which parameters are nuisance parameters} 17 | \item{subjects}{A vector containing the unique subject ID's} 18 | \item{type}{The type of model e.g., "standard" or "diagonal"} 19 | \item{prior}{A list that holds the prior for \code{theta_mu} (the model 20 | parameters). Contains the mean (\code{theta_mu_mean}), covariance matrix 21 | (\code{theta_mu_var}), degrees of freedom (\code{v}), and scale (\code{A}) 22 | and inverse covariance matrix (\code{theta_mu_invar})} 23 | \item{samples}{A list with defined structure containing the samples, see 24 | the Samples Element section for more detail} 25 | \item{sampler_nuis}{A sampler list for nuisance parameters (in this case there are none), 26 | similarly structured to the overall samples list of one of the MCMC chains.} 27 | } 28 | } 29 | \source{ 30 | \url{https://www.pnas.org/doi/10.1073/pnas.0805903105} 31 | } 32 | \usage{ 33 | samples_LNR 34 | } 35 | \description{ 36 | An emc object with a limited number of samples and subjects of the Forstmann dataset. 37 | The object is a nested list of lenght three, each list containing the MCMC samples 38 | of the respective chain. The MCMC samples are stored in the samples element. 39 | } 40 | \section{Samples Element}{ 41 | 42 | 43 | The samples element of a emc object contains the different types of samples 44 | estimated by EMC2. These include the three main types of samples 45 | \code{theta_mu}, \code{theta_var} and \code{alpha} as well as a number of 46 | other items which are detailed here. 47 | \describe{ 48 | \item{theta_mu}{samples used for estimating the model parameters (group 49 | level), an array of size (n_pars x n_samples)} 50 | \item{theta_var}{samples used for estimating the parameter covariance 51 | matrix, an array of size (n_pars x n_pars x n_samples)} 52 | \item{alpha}{samples used for estimating the subject random effects, an 53 | array of size (n_pars x n_subjects x n_samples)} 54 | \item{stage}{A vector containing what PMwG stage each sample was drawn in} 55 | \item{subj_ll}{The winning particles log-likelihood for each subject and 56 | sample} 57 | \item{a_half}{Mixing weights used during the Gibbs step when creating a 58 | new sample for the covariance matrix} 59 | \item{last_theta_var_inv}{The inverse of the last samples covariance 60 | matrix} 61 | \item{idx}{The index of the last sample drawn} 62 | } 63 | } 64 | 65 | \keyword{datasets} 66 | -------------------------------------------------------------------------------- /man/subset.emc.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/s3_funcs.R 3 | \name{subset.emc} 4 | \alias{subset.emc} 5 | \title{Shorten an emc Object} 6 | \usage{ 7 | \method{subset}{emc}( 8 | x, 9 | stage = "sample", 10 | filter = NULL, 11 | thin = 1, 12 | keep_stages = FALSE, 13 | length.out = NULL, 14 | ... 15 | ) 16 | } 17 | \arguments{ 18 | \item{x}{an emc object} 19 | 20 | \item{stage}{A character string. Indicates from which sampling stage(s) to take the samples from (i.e. \code{preburn}, \code{burn}, \code{adapt}, \code{sample})} 21 | 22 | \item{filter}{Integer or numeric vector. If an integer is supplied, iterations 23 | up until that integer are removed. If a vector is supplied, the iterations 24 | within the range are kept.} 25 | 26 | \item{thin}{An integer. By how much to thin the chains} 27 | 28 | \item{keep_stages}{Boolean. If \code{TRUE}, will not remove samples from unselected stages.} 29 | 30 | \item{length.out}{Integer. Alternatively to thinning, you can also select a 31 | desired length of the MCMC chains, which will be thinned appropriately.} 32 | 33 | \item{...}{additional optional arguments} 34 | } 35 | \value{ 36 | A shortened emc object 37 | } 38 | \description{ 39 | Shorten an emc Object 40 | } 41 | \examples{ 42 | subset(samples_LNR, length.out = 10) 43 | } 44 | -------------------------------------------------------------------------------- /man/summary.emc.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/s3_funcs.R 3 | \name{summary.emc} 4 | \alias{summary.emc} 5 | \title{Summary Statistics for emc Objects} 6 | \usage{ 7 | \method{summary}{emc}( 8 | object, 9 | selection = c("mu", "sigma2", "alpha"), 10 | probs = c(0.025, 0.5, 0.975), 11 | digits = 3, 12 | ... 13 | ) 14 | } 15 | \arguments{ 16 | \item{object}{An object of class \code{emc}} 17 | 18 | \item{selection}{A character string indicating the parameter type 19 | Defaults to \code{mu}, \code{sigma2}, and \code{alpha}. See below for more information.} 20 | 21 | \item{probs}{The quantiles to be computed. Defaults to the the 2.5\%, 50\% and 97.5\% quantiles.} 22 | 23 | \item{digits}{An integer specifying rounding of output.} 24 | 25 | \item{...}{Optional arguments that can be passed to \code{get_pars}} 26 | } 27 | \value{ 28 | A list of summary output. 29 | } 30 | \description{ 31 | Computes quantiles, \code{Rhat} and \code{ESS} for selected model parameters. 32 | } 33 | \details{ 34 | Note that if \code{selection = alpha} and \code{by_subject = TRUE} (default) 35 | is used, summary statistics are computed at the individual level. 36 | to the console but summary statistics for all subjects are returned by the 37 | function. 38 | 39 | If an emc object that has not been run with \code{fit} yet is supplied, summary of 40 | the design will be returned. 41 | } 42 | -------------------------------------------------------------------------------- /man/summary.emc.design.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/design.R 3 | \name{summary.emc.design} 4 | \alias{summary.emc.design} 5 | \title{Summary method for emc.design objects} 6 | \usage{ 7 | \method{summary}{emc.design}(object, ...) 8 | } 9 | \arguments{ 10 | \item{object}{An object of class \code{emc.design} containing the design to summarize} 11 | 12 | \item{...}{Additional arguments (not used)} 13 | } 14 | \value{ 15 | Invisibly returns the design matrices 16 | } 17 | \description{ 18 | Prints a summary of the design object, including sampled parameters and design matrices. 19 | For continuous covariates just prints one row, instead of all covariates. 20 | } 21 | -------------------------------------------------------------------------------- /man/summary.emc.prior.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/priors.R 3 | \name{summary.emc.prior} 4 | \alias{summary.emc.prior} 5 | \title{Summary method for emc.prior objects} 6 | \usage{ 7 | \method{summary}{emc.prior}(object, ...) 8 | } 9 | \arguments{ 10 | \item{object}{An object of class 'emc.prior' containing prior specifications} 11 | 12 | \item{...}{Additional arguments passed to other methods (not currently used)} 13 | } 14 | \value{ 15 | Invisibly returns NULL. Called for its side effect of printing the summary. 16 | } 17 | \description{ 18 | Prints a summary of the prior specification, including descriptions of the prior types 19 | and their associated hyperparameters. 20 | } 21 | \examples{ 22 | # Take a prior object 23 | prior <- get_prior(samples_LNR) 24 | summary(prior) 25 | 26 | } 27 | \seealso{ 28 | \code{\link{prior}} for creating prior objects 29 | } 30 | -------------------------------------------------------------------------------- /man/update2version.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/design.R 3 | \name{update2version} 4 | \alias{update2version} 5 | \title{Update EMC Objects to the Current Version} 6 | \usage{ 7 | update2version(emc) 8 | } 9 | \arguments{ 10 | \item{emc}{An EMC object to update} 11 | } 12 | \value{ 13 | An updated EMC object compatible with the current version 14 | } 15 | \description{ 16 | This function updates EMC objects created with older versions of the package to be compatible with the current version. 17 | } 18 | \examples{ 19 | # Update the model to current version 20 | updated_model <- update2version(samples_LNR) 21 | 22 | } 23 | -------------------------------------------------------------------------------- /pkgdown/_pkgdown.yml: -------------------------------------------------------------------------------- 1 | url: https://ampl-psych.github.io/EMC2/ 2 | template: 3 | bootstrap: 5 4 | light-switch: true 5 | 6 | bibliography: refs.bib 7 | 8 | reference: 9 | - title: Models 10 | - contents: 11 | - DDM 12 | - LBA 13 | - LNR 14 | - RDM 15 | - DDMGNG 16 | - SDT 17 | - title: Design and Mapping 18 | - contents: 19 | - design 20 | - mapped_pars 21 | - sampled_pars 22 | - plot_design 23 | - plot.emc.design 24 | - summary.emc.design 25 | - get_design 26 | - title: Prior Specification 27 | - contents: 28 | - prior 29 | - summary.emc.prior 30 | - plot.emc.prior 31 | - predict.emc.prior 32 | - get_prior 33 | - prior_help 34 | - credint.emc.prior 35 | - title: Estimation 36 | - contents: 37 | - init_chains 38 | - make_emc 39 | - fit 40 | - run_emc 41 | - title: Model checking 42 | - contents: 43 | - check 44 | - summary.emc 45 | - credint.emc 46 | - ess_summary 47 | - gd_summary 48 | - chain_n 49 | - plot.emc 50 | - pairs_posterior 51 | - title: Posterior Inference 52 | - contents: 53 | - credint 54 | - parameters 55 | - get_pars 56 | - plot_pars 57 | - plot_relations 58 | - merge_chains 59 | - subset.emc 60 | - auto_thin.emc 61 | - title: Data Generation and Recovery 62 | - contents: 63 | - predict.emc 64 | - recovery 65 | - make_data 66 | - make_random_effects 67 | - recovery 68 | - get_data.emc 69 | - profile_plot 70 | - title: Model Fit 71 | - contents: 72 | - plot_density 73 | - plot_cdf 74 | - plot_stat 75 | - title: Model Comparison 76 | - contents: 77 | - compare 78 | - compare_subject 79 | - model_averaging 80 | - run_bridge_sampling 81 | - get_BayesFactor 82 | - credible 83 | - hypothesis 84 | 85 | - title: Contrasts 86 | - contents: 87 | - matches("contr") 88 | 89 | - title: Simulation-based calibration 90 | - contents: 91 | - matches("sbc") 92 | 93 | - title: miscellaneous 94 | - contents: 95 | - update2version 96 | 97 | - title: Included data 98 | - contents: 99 | - forstmann 100 | - samples_LNR 101 | 102 | # navbar: 103 | # structure: 104 | # left: [search] 105 | # right: [reference, articles] 106 | # 107 | # articles: 108 | # - title: Simulation-based calibration 109 | # contents: 110 | # - Simulation-based Calibration 111 | 112 | 113 | -------------------------------------------------------------------------------- /src/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ampl-psych/EMC2/5a23740a614054ca634c11d12fd06d3def16e6aa/src/.DS_Store -------------------------------------------------------------------------------- /src/.gitignore: -------------------------------------------------------------------------------- 1 | *.o 2 | *.so 3 | *.dll 4 | -------------------------------------------------------------------------------- /src/Makevars: -------------------------------------------------------------------------------- 1 | PKG_CPPFLAGS = $(RCPP_ARMA_CXXFLAGS) 2 | PKG_LIBS = $(RCPP_ARMA_LIBS) 3 | //CXX_STD = C++11 4 | -------------------------------------------------------------------------------- /src/Makevars.win: -------------------------------------------------------------------------------- 1 | PKG_CPPFLAGS = $(RCPP_ARMA_CXXFLAGS) 2 | PKG_LIBS = $(LAPACK_LIBS) $(BLAS_LIBS) $(RCPP_ARMA_LIBS) $(FLIBS) 3 | //CXX_STD = C++11 4 | -------------------------------------------------------------------------------- /src/fncs_seven.cpp: -------------------------------------------------------------------------------- 1 | 2 | // Chair of Social Psychology, University of Freiburg 3 | // Authors: Christoph Klauer and Raphael Hartmann 4 | 5 | #include "tools.h" 6 | #include "pdf_fncs.h" 7 | #include "fncs_seven.h" 8 | #include "gauss.h" 9 | #include 10 | 11 | 12 | /* DENSITY */ 13 | 14 | /* dependencies */ 15 | 16 | /* integrand density */ 17 | int int_ddiff(unsigned dim, const double *x, void *p, unsigned fdim, double *retval) { 18 | my_params *params = static_cast(p); 19 | double t = (params->t); 20 | int low_or_up = (params->low_or_up); 21 | double a = (params->a); 22 | double v = (params->v); 23 | double t0 = (params->t0); 24 | double w = (params->w); 25 | double sw = (params->sw); 26 | double sv = (params->sv); 27 | double st = (params->st); 28 | double errorW = (params->errorW); 29 | int K = (params->K); 30 | int epsFLAG = (params->epsFLAG); 31 | // double *val_ptr = (params->val_ptr); 32 | 33 | // usually: 0 = s (v); 1 = u (w), 2 = v (t), depending on whether sv, sw, or st = 0 34 | //double temp = sv ? pow(x[0], 2) : 0; 35 | //double y = sv ? x[0] / (1 - temp) : 0; 36 | //double nu = sv ? v + sv * y : v; 37 | //double omega = sv ? (sw ? w + sw * (x[1] - 0.5) : w) : (sw ? w + sw * (x[0] - 0.5) : w); 38 | //double tau = sv ? ( sw ? (st ? t0 + st * x[2] : t0) : (st ? t0 + st * x[1] : t0) ) : ( sw ? (st ? t0 + st * x[1] : t0) : (st ? t0 + st * x[0] : t0) ); 39 | // usually: 0 = omega (w), 1 = tau (t0), depending on whether sv, sw, or st = 0 40 | double omega = sw ? w + sw * (x[0] - 0.5) : w; 41 | double tau = sw ? (st ? t0 + st * x[1] : t0) : (st ? t0 + st * x[0] : t0); 42 | 43 | if (t - tau <= 0) retval[0] = 0.0; 44 | else { 45 | double ldW = dwiener(low_or_up * (t - tau), a, v, omega, sv, errorW, K, epsFLAG); 46 | double temp2 = 0; 47 | //if (sv) temp2 = -0.5 * pow(y, 2) - M_LN_SQRT_PI - 0.5 * M_LN2 + log1p(temp) - 2 * log1p(-temp); 48 | double integrand = exp(ldW + temp2); 49 | retval[0] = integrand; 50 | } 51 | return 0; 52 | } 53 | 54 | /* calculate density for 7-param diffusion */ 55 | void ddiff(int choice, double t, int low_or_up, double a, double v, double t0, double w, double sw, double sv, double st, double myerr, int K, int epsFLAG, int Neval, double *derivF, double *Rerr) { 56 | 57 | //double result; 58 | //double error; 59 | 60 | double value; 61 | // double valueln; 62 | 63 | double *val_ptr = &value; 64 | double errorW = myerr*0.1; 65 | 66 | my_params params = {t, low_or_up, a, v, t0, w, sw, sv, st, errorW, K, epsFLAG, val_ptr}; 67 | 68 | int dim = (sw!=0)+(st!=0); 69 | 70 | double *xmin = (double*)R_Calloc(dim, double); 71 | double *xmax = (double*)R_Calloc(dim, double); 72 | 73 | // 0 = s (v); 1 = u (w), 2 = v (w) 74 | // if(sv) { 75 | // xmin[0] = -1; xmax[0] = 1; 76 | // for (int i = 1; i < dim; i++) { 77 | // xmin[i] = 0; 78 | // xmax[i] = 1; 79 | // } 80 | // } else { 81 | for (int i = 0; i < dim; i++) { 82 | xmin[i] = 0; 83 | xmax[i] = 1; 84 | } 85 | // } 86 | if (st) xmax[dim-1] = fmin(1.0, (t-t0)/st); 87 | 88 | double reltol = 0.0; 89 | 90 | double abstol = myerr*0.9; 91 | 92 | double val, err; 93 | 94 | int Meval = Neval; 95 | 96 | // printf("%u-dim integral, tolerance = %g\n", dim, tol); 97 | hcubature(int_ddiff, ¶ms, dim, xmin, xmax, Meval, abstol, reltol, &val, &err); 98 | 99 | //if(err > abstol) Rprintf("absolute error not achieved: %g < %g\n", abstol, err); 100 | 101 | R_Free(xmin); R_Free(xmax); 102 | *derivF = val; 103 | if (*Rerr < err+errorW) *Rerr = err+errorW; 104 | 105 | } 106 | -------------------------------------------------------------------------------- /src/fncs_seven.h: -------------------------------------------------------------------------------- 1 | 2 | // Chair of Social Psychology, University of Freiburg 3 | // Authors: Christoph Klauer and Raphael Hartmann 4 | 5 | #ifndef FNCS_SEVEN_H 6 | #define FNCS_SEVEN_H 7 | 8 | 9 | 10 | /* dependencies for Wrapper */ 11 | int int_ddiff(unsigned, const double *, void *, unsigned, double *); 12 | /*-----------------------------------------------*/ 13 | 14 | 15 | 16 | /* Wrapper */ 17 | void ddiff(int, double, int, double, double, double, double, double, double, double, double, int, int, int, double *, double *); 18 | /*-----------------------------------------------*/ 19 | 20 | #endif 21 | -------------------------------------------------------------------------------- /src/gauss.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using std::setw; 6 | using std::cout; 7 | using std::vector; 8 | 9 | 10 | 11 | static const double xd7[8] = { -9.9145537112081263920685469752598e-01, 12 | -9.4910791234275852452618968404809e-01, 13 | -8.6486442335976907278971278864098e-01, 14 | -7.415311855993944398638647732811e-01, 15 | -5.8608723546769113029414483825842e-01, 16 | -4.0584515137739716690660641207707e-01, 17 | -2.0778495500789846760068940377309e-01, 18 | 0.0 }; 19 | 20 | static const double wd7[8] = { 2.2935322010529224963732008059913e-02, 21 | 6.3092092629978553290700663189093e-02, 22 | 1.0479001032225018383987632254189e-01, 23 | 1.4065325971552591874518959051021e-01, 24 | 1.6900472663926790282658342659795e-01, 25 | 1.9035057806478540991325640242055e-01, 26 | 2.0443294007529889241416199923466e-01, 27 | 2.0948214108472782801299917489173e-01 }; 28 | 29 | static const double gwd7[4] = { 1.2948496616886969327061143267787e-01, 30 | 2.797053914892766679014677714229e-01, 31 | 3.8183005050511894495036977548818e-01, 32 | 4.1795918367346938775510204081658e-01 }; 33 | 34 | struct one_d { 35 | double result; 36 | double err; 37 | int kdivide = 0; 38 | }; 39 | 40 | struct GenzMalik { 41 | vector> p[4]; 42 | double w[5]; 43 | double wd[4]; 44 | }; 45 | 46 | void combination(int* c, int n, int p, int x); 47 | 48 | int choose(int n, int k); 49 | 50 | void gauss_kronrod(double a, double b, one_d& out, void* pars, int integrand(unsigned dim, const double* x, void* p, unsigned fdim, double* retval)); 51 | 52 | void combos(int k, double lambda, int n, vector>& p); 53 | 54 | void increment(vector& index, int k, double lambda, int n, int* c, vector& temp); 55 | 56 | void signcombos(int k, double lambda, int n, vector>& p); 57 | 58 | void make_GenzMalik(int n, GenzMalik& g); 59 | 60 | void integrate_GenzMalik(GenzMalik g, int n, const double* a, const double* b, one_d& out, void* pars, double integrand(double* x, void* pars)); 61 | 62 | int hcubature(int integrand(unsigned dim, const double* x, void* p, unsigned fdim, double* retval), void* pars, unsigned n, const double* a, const double* b, 63 | size_t maxEval, double reqAbsError, double reqRelError, double* val, double* err); -------------------------------------------------------------------------------- /src/model_DDM.h: -------------------------------------------------------------------------------- 1 | #ifndef DDM_wien 2 | #define DDM_wien 3 | 4 | #include 5 | using namespace Rcpp; 6 | #include "utility_functions.h" 7 | #include "pdf_fncs.h" 8 | #include "fncs_seven.h" 9 | #include "tools.h" 10 | 11 | NumericVector d_DDM_Wien(NumericVector rts, IntegerVector Rs, NumericMatrix pars, LogicalVector is_ok){ 12 | int Epsflag = 1; 13 | double eps = 5e-3; 14 | int K = 0; 15 | int Neval = 6000; 16 | int choice = 0; //the type of integration method to choose. 17 | //0 = "v", 1 = "a", 2= "sv", 3 = "t0", 4 = "st0", 5 = "s", 6 = "Z", 7 = "SZ", 18 | int N = rts.length(); 19 | NumericVector out(N); 20 | for(int i = 0; i < N; i++){ 21 | if(is_ok[i] == FALSE){ 22 | out[i] = R_NegInf; 23 | } else{ 24 | // we divide v, a and sv by s to introduce the scaling parameter s 25 | double pm = (Rs[i]==1) ? -1 : 1; 26 | // if sz and st0 are zero we can use simple and fast dwiener function 27 | if(pars(i,7) == 0 && pars(i, 4) == 0){ 28 | double new_rt = rts[i] - pars(i,3); 29 | if(new_rt > 0){ 30 | out[i] = dwiener(new_rt*pm, pars(i, 1)/pars(i,5), pars(i, 0)/pars(i,5), pars(i, 6), pars(i, 2)/pars(i,5), eps, K, Epsflag); 31 | } else{ 32 | out[i] = R_NegInf; 33 | } 34 | } else{ // otherwise use ddiff function with integration 35 | double Rval; 36 | double Rerr; 37 | double sz = (pars(i,6) < (1 - pars(i,6))) ? 2*pars(i,7)*pars(i,6) : 2*pars(i,7)*(1-pars(i,6)); 38 | ddiff(choice, rts[i], pm, pars(i, 1)/pars(i,5), pars(i, 0)/pars(i,5), pars(i, 3), pars(i, 6), sz, pars(i, 2)/pars(i,5), pars(i,4), eps, K, Epsflag, Neval, &Rval, &Rerr); 39 | out[i] = log(Rval); 40 | } 41 | } 42 | } 43 | return(out); 44 | } 45 | 46 | 47 | #endif 48 | -------------------------------------------------------------------------------- /src/model_fMRI.h: -------------------------------------------------------------------------------- 1 | // #ifndef fmri_h 2 | // #define fmri_h 3 | // 4 | // #include 5 | // #include "utility_functions.h" 6 | // 7 | // using namespace Rcpp; 8 | // 9 | // 10 | // 11 | // double c_log_likelihood_fMRI(NumericVector pars, DataFrame data, NumericMatrix designMatrix, double min_ll){ 12 | // int n = data.nrow(); 13 | // NumericVector data_use = data["Str"]; 14 | // NumericVector y_hat(n); 15 | // NumericVector out(n); 16 | // int n_regr = designMatrix.ncol(); 17 | // for(int i = 0; i < n_regr; i ++){ 18 | // y_hat = y_hat + designMatrix(_, i) * pars[i]; 19 | // } 20 | // double mean_y_hat = mean(y_hat); 21 | // for(int j = 0; j < n; j ++){ 22 | // out[j] = R::dnorm4(data_use[j], y_hat[j] - mean_y_hat, exp(pars[n_regr]) + 0.001, true); 23 | // } 24 | // out[out < min_ll] = min_ll; 25 | // return(sum(out)); 26 | // } 27 | // 28 | // #endif 29 | -------------------------------------------------------------------------------- /src/model_lnr.h: -------------------------------------------------------------------------------- 1 | #ifndef lnr_h 2 | #define lnr_h 3 | 4 | #include 5 | #include "utility_functions.h" 6 | 7 | using namespace Rcpp; 8 | 9 | NumericVector plnr_c(NumericVector rts, NumericMatrix pars, LogicalVector idx, double min_ll, LogicalVector is_ok){ 10 | // 0 = m, 1 = s, 2 = t0 11 | int n = sum(idx); 12 | NumericVector out(n); 13 | int k = 0; 14 | for(int i = 0; i < rts.length(); i++){ 15 | if(idx[i] == TRUE){ 16 | if(NumericVector::is_na(pars(i,0))){ 17 | out[k] = 0; // This is a bit tricky, but helps with assigning missing values a zero (instead of min_ll value) 18 | // which is important for RACE 19 | } else if((rts[i] - pars(i,2) > 0) && (is_ok[i] == TRUE)){ 20 | out[k] = R::plnorm(rts[i] - pars(i,2), pars(i, 0), pars(i, 1), TRUE, FALSE); 21 | } else{ 22 | out[k] = min_ll; 23 | } 24 | k++; 25 | } 26 | } 27 | 28 | return(out); 29 | } 30 | 31 | NumericVector dlnr_c(NumericVector rts, NumericMatrix pars, LogicalVector idx, double min_ll, LogicalVector is_ok){ 32 | int n = sum(idx); 33 | NumericVector out(n); 34 | int k = 0; 35 | for(int i = 0; i < rts.length(); i++){ 36 | if(idx[i] == TRUE){ 37 | if(NumericVector::is_na(pars(i,0))){ 38 | out[k] = 0; // This is a bit tricky, but helps with assigning missing values a zero (instead of min_ll value) 39 | // which is important for RACE 40 | } else if((rts[i] - pars(i,2) > 0) && (is_ok[i] == TRUE)){ 41 | out[k] = R::dlnorm(rts[i] - pars(i,2), pars(i, 0), pars(i, 1), FALSE); 42 | } else{ 43 | out[k] = min_ll; 44 | } 45 | k++; 46 | } 47 | 48 | } 49 | 50 | return(out); 51 | } 52 | 53 | 54 | #endif 55 | -------------------------------------------------------------------------------- /src/pdf_fncs.cpp: -------------------------------------------------------------------------------- 1 | 2 | // Chair of Social Psychology, University of Freiburg 3 | // Authors: Christoph Klauer and Raphael Hartmann 4 | 5 | #include "tools.h" 6 | #include "pdf_fncs.h" 7 | #include 8 | 9 | 10 | /* DENSITY */ 11 | 12 | /* calculate number of terms needed for short t */ 13 | double ks(double t, double w, double eps) { 14 | double K1 = (sqrt(2.0 * t) + w) / 2.0; 15 | double u_eps = fmin(-1.0, M_LN2 + M_LNPI + 2.0 * std::log(t) + 2.0 * (eps)); 16 | double arg = -t * (u_eps - sqrt(-2.0 * u_eps - 2.0)); 17 | double K2 = (arg > 0) ? 0.5 * (sqrt(arg) - w) : K1; 18 | return ceil(fmax(K1, K2)); 19 | } 20 | 21 | /* calculate number of terms needed for large t */ 22 | double kl(double q, double v, double w, double err) { 23 | double K1 = 1.0 / (M_PI * sqrt(q)), K2=0.0; 24 | double temp = -2.0 * (std::log(M_PI * q) + err); 25 | if (temp>=0) K2 = sqrt(temp/(pow(M_PI, 2) * q)); 26 | return ceil(fmax(K1,K2)); 27 | } 28 | 29 | /* calculate terms of the sum for short t */ 30 | double logfs(double t, double w, int K) { 31 | if (w == 0) return -INFINITY; 32 | double fplus = -INFINITY, fminus = -INFINITY, twot = 2.0 * t; 33 | if (K > 0) 34 | for (int k = K; k >= 1; k--) { 35 | double temp1 = w + 2.0 * k, temp2 = w - 2.0 * k; 36 | 37 | fplus = logsum(std::log(temp1) - pow(temp1, 2) / twot, fplus); 38 | fminus = logsum(std::log(-temp2) - pow(temp2, 2) / twot, fminus); 39 | } 40 | fplus = logsum(std::log(w) - pow(w, 2) / twot, fplus); 41 | return -0.5 * M_LN2 - M_LN_SQRT_PI - 1.5 * std::log(t) + logdiff(fplus, fminus); 42 | } 43 | 44 | /* calculate terms of the sum for large t */ 45 | double logfl(double q, double v, double w, int K) { 46 | if (w == 0) return -INFINITY; 47 | double fplus = -INFINITY, fminus = -INFINITY; 48 | double halfq = q / 2.0; 49 | for (int k = K; k >= 1; k--) { 50 | double temp = k * M_PI; 51 | double check = sin(temp * w); 52 | if (check > 0) fplus = logsum(std::log(static_cast(k)) - pow(temp, 2) * halfq + std::log(check), fplus); 53 | else fminus = logsum(std::log(static_cast(k)) - pow(temp, 2) * halfq + std::log(-check), fminus); 54 | } 55 | return logdiff(fplus, fminus) + M_LNPI; 56 | } 57 | 58 | /* calculate density */ 59 | double dwiener(double q, double a, double vn, double wn, double sv, double err, int K, int epsFLAG) { 60 | if (q == 0.0) { 61 | return -INFINITY; 62 | } 63 | double kll, kss, ans, v, w; 64 | if(!epsFLAG && K==0) { 65 | err = -27.63102; // exp(err) = 1.e-12 66 | epsFLAG = 1; 67 | } 68 | else if(!epsFLAG && K>0) err = -27.63102; // exp(err) = 1.e-12 69 | else if(epsFLAG) err = std::log(err); 70 | 71 | if (q >= 0) { 72 | w = 1.0 - wn; 73 | v = -vn; 74 | } 75 | else { 76 | q = fabs(q); 77 | w = wn; 78 | v = vn; 79 | } 80 | 81 | double q_asq = q / pow(a, 2); 82 | ans = 0.0; 83 | 84 | /* calculate the number of terms needed for short t*/ 85 | double eta_sqr = pow(sv, 2); 86 | double temp = 1 + eta_sqr * q; 87 | double lg1 = (eta_sqr * pow(a * w, 2) - 2 * a * v * w - pow(v, 2) * q) / 2.0 / temp - 2 *std::log(a) - 0.5 *std::log(temp); 88 | //double lg1 = (-v * a * w - (pow(v, 2)) * q / 2.0) - 2.0*std::log(a); 89 | double es = (err - lg1); 90 | kss = ks(q_asq, w, es); 91 | /* calculate the number of terms needed for large t*/ 92 | double el = es; 93 | kll = kl(q_asq, v, w, el); 94 | 95 | // if small t is better 96 | if (2 * kss <= kll) { 97 | if((epsFLAG && kss(kss)); 99 | } 100 | // if large t is better 101 | else { 102 | if((epsFLAG && kll(kll)); 104 | } 105 | 106 | return ans; 107 | } 108 | -------------------------------------------------------------------------------- /src/pdf_fncs.h: -------------------------------------------------------------------------------- 1 | 2 | // Chair of Social Psychology, University of Freiburg 3 | // Authors: Christoph Klauer and Raphael Hartmann 4 | 5 | #ifndef PDF_FNCS_H 6 | #define PDF_FNCS_H 7 | 8 | 9 | 10 | /* dependencies for DENSITY */ 11 | double ks(double, double, double); 12 | double kl(double, double, double, double); 13 | double logfs(double, double, int); 14 | double logfl(double, double, double, int); 15 | /*-----------------------------------------------*/ 16 | 17 | /* DENSITY */ 18 | double dwiener(double, double, double, double, double, double, int, int); 19 | /*-----------------------------------------------*/ 20 | 21 | #endif 22 | -------------------------------------------------------------------------------- /tests/testthat.R: -------------------------------------------------------------------------------- 1 | # This file is part of the standard setup for testthat. 2 | # It is recommended that you do not modify it. 3 | # 4 | # Where should you do additional test configuration? 5 | # Learn more about the roles of various files in: 6 | # * https://r-pkgs.org/tests.html 7 | # * https://testthat.r-lib.org/reference/test_package.html#special-files 8 | 9 | library(testthat) 10 | library(EMC2) 11 | 12 | test_check("EMC2") 13 | -------------------------------------------------------------------------------- /tests/testthat/_snaps/Linux/fit.md: -------------------------------------------------------------------------------- 1 | # fit 2 | 3 | Code 4 | LNR_s[[1]]$samples$theta_mu[, idx] 5 | Output 6 | m m_lMd s t0 7 | -1.0271948 -0.6080783 -0.6522856 -1.8681377 8 | 9 | --- 10 | 11 | Code 12 | LNR_s[[1]]$samples$alpha[, , idx] 13 | Output 14 | as1t bd6t 15 | m -0.7921730 -0.9270306 16 | m_lMd -0.2941218 -0.5577956 17 | s -1.0147461 -0.5239832 18 | t0 -2.2704198 -1.6390127 19 | 20 | --- 21 | 22 | Code 23 | LNR_s[[1]]$samples$theta_var[, , idx] 24 | Output 25 | m m_lMd s t0 26 | m 0.0181819208 0.01072774 -0.005814797 -0.0007747914 27 | m_lMd 0.0107277436 0.01311526 -0.012487756 -0.0127846529 28 | s -0.0058147969 -0.01248776 0.035674357 0.0319079134 29 | t0 -0.0007747914 -0.01278465 0.031907913 0.0388690465 30 | 31 | -------------------------------------------------------------------------------- /tests/testthat/_snaps/S3.md: -------------------------------------------------------------------------------- 1 | # priorS3 2 | 3 | Code 4 | prior 5 | Output 6 | Mean and variance of the prior on the transformed parameters: 7 | m ~ 𝑁(0, 1) 8 | m_lMd ~ 𝑁(0, 1) 9 | s ~ 𝑁(0, 1) 10 | t0 ~ 𝑁(0, 1) 11 | 12 | For detailed info use summary() 13 | 14 | --- 15 | 16 | Code 17 | summary(prior) 18 | Output 19 | mu - Group-level mean 20 | 21 | mean of the group-level mean prior : 22 | m m_lMd s t0 23 | 0 0 0 0 24 | variance of the group-level mean prior : 25 | m m_lMd s t0 26 | m 1 0 0 0 27 | m_lMd 0 1 0 0 28 | s 0 0 1 0 29 | t0 0 0 0 1 30 | 31 | Sigma - Group-level covariance matrix 32 | 33 | degrees of freedom on the group-level (co-)variance prior, 2 leads to uniform correlations. Single value : 34 | [1] 2 35 | scale on the group-level variance prior, larger values lead to larger variances : 36 | m m_lMd s t0 37 | 0.3 0.3 0.3 0.3 38 | 39 | 40 | # designS3 41 | 42 | Code 43 | design 44 | Output 45 | m ~ lM 46 | s ~ 1 47 | t0 ~ 1 48 | 49 | --- 50 | 51 | Code 52 | summary(design) 53 | Output 54 | 55 | Sampled Parameters: 56 | [1] "m" "m_lMd" "s" "t0" 57 | 58 | Design Matrices: 59 | $m 60 | lM m m_lMd 61 | TRUE 1 0.5 62 | FALSE 1 -0.5 63 | 64 | $s 65 | s 66 | 1 67 | 68 | $t0 69 | t0 70 | 1 71 | 72 | 73 | -------------------------------------------------------------------------------- /tests/testthat/_snaps/compare.md: -------------------------------------------------------------------------------- 1 | # compare 2 | 3 | Code 4 | compare(list(samples_LNR), cores_for_props = 1) 5 | Output 6 | MD wMD DIC wDIC BPIC wBPIC EffectiveN meanD Dmean minD 7 | 1 -174 1 -615 1 -579 1 35 -650 -657 -686 8 | 9 | # savage-dickey 10 | 11 | Code 12 | round(hypothesis(samples_LNR, parameter = "m", do_plot = F, H0 = -1), 2) 13 | Output 14 | [1] 0.05 15 | 16 | --- 17 | 18 | Code 19 | round(hypothesis(samples_LNR, fun = function(d) d["m"] - d["m_lMd"], H0 = -0.5, 20 | do_plot = F), 2) 21 | Output 22 | [1] 0.08 23 | 24 | -------------------------------------------------------------------------------- /tests/testthat/_snaps/customLL.md: -------------------------------------------------------------------------------- 1 | # custom_ll 2 | 3 | Code 4 | init_chains(custom_emc, cores_for_chains = 1, particles = 10) 5 | Output 6 | Iterations: 7 | preburn burn adapt sample 8 | [1,] 0 0 0 0 9 | [2,] 0 0 0 0 10 | [3,] 0 0 0 0 11 | 12 | Subjects: 13 | [1] "as1t" "bd6t" "bl1t" 14 | 15 | Parameters: 16 | [1] "muL" "muR" "sdL" "sdR" 17 | 18 | -------------------------------------------------------------------------------- /tests/testthat/_snaps/joint.md: -------------------------------------------------------------------------------- 1 | # joint 2 | 3 | Code 4 | init_chains(joint, particles = 10, cores_for_chains = 1)[[1]]$samples 5 | Output 6 | $theta_mu 7 | [,1] 8 | 1|m -0.9685927 9 | 1|m_lMd 0.7061091 10 | 1|s 1.4890213 11 | 1|t0 -1.8150926 12 | 2|m 0.3304096 13 | 2|m_lMd -1.1421557 14 | 2|s 0.1571934 15 | 2|t0 -2.0654072 16 | 17 | $theta_var 18 | , , 1 19 | 20 | 1|m 1|m_lMd 1|s 1|t0 2|m 21 | 1|m 0.0776323497 0.0003990772 0.0007227846 0.0010725497 0.0008620178 22 | 1|m_lMd 0.0003990772 0.0615447712 0.0073914077 0.0063064531 -0.0039161189 23 | 1|s 0.0007227846 0.0073914077 0.0612645493 0.0069415172 0.0111249539 24 | 1|t0 0.0010725497 0.0063064531 0.0069415172 0.0627796927 0.0112157411 25 | 2|m 0.0008620178 -0.0039161189 0.0111249539 0.0112157411 0.0299426688 26 | 2|m_lMd -0.0230251625 -0.0032451299 -0.0065891498 -0.0312854994 0.0006023507 27 | 2|s -0.0116750757 -0.0140062790 -0.0031471142 -0.0046122054 0.0088149797 28 | 2|t0 -0.0334053929 -0.0093476137 -0.0241196322 -0.0006361415 -0.0045744971 29 | 2|m_lMd 2|s 2|t0 30 | 1|m -0.0230251625 -0.0116750757 -0.0334053929 31 | 1|m_lMd -0.0032451299 -0.0140062790 -0.0093476137 32 | 1|s -0.0065891498 -0.0031471142 -0.0241196322 33 | 1|t0 -0.0312854994 -0.0046122054 -0.0006361415 34 | 2|m 0.0006023507 0.0088149797 -0.0045744971 35 | 2|m_lMd 0.0893905606 0.0295926364 0.0084111037 36 | 2|s 0.0295926364 0.0458372775 -0.0001726855 37 | 2|t0 0.0084111037 -0.0001726855 0.0606188060 38 | 39 | 40 | $a_half 41 | [,1] 42 | 1|m 1.2202851 43 | 1|m_lMd 1.5173712 44 | 1|s 0.6497974 45 | 1|t0 1.0913531 46 | 2|m 0.5025341 47 | 2|m_lMd 1.7087224 48 | 2|s 1.2044677 49 | 2|t0 0.3491948 50 | 51 | $alpha 52 | , , 1 53 | 54 | as1t bd6t bl1t 55 | 1|m -1.1376682 -1.10507416 -0.9795738 56 | 1|m_lMd 0.6098439 0.06767273 0.2799529 57 | 1|s 1.1023325 1.47070474 0.9897062 58 | 1|t0 -1.4760924 -1.49173271 -1.5738540 59 | 2|m 0.5635816 0.07877702 0.5117758 60 | 2|m_lMd -0.8927786 -0.92491041 -1.0505185 61 | 2|s 0.1645025 0.18856539 0.3240196 62 | 2|t0 -2.0002208 -1.67546259 -1.4563534 63 | 64 | 65 | $stage 66 | [1] "init" 67 | 68 | $subj_ll 69 | [,1] 70 | as1t -1733.795 71 | bd6t -1744.282 72 | bl1t -1647.458 73 | 74 | $last_theta_var_inv 75 | [,1] [,2] [,3] [,4] [,5] [,6] 76 | [1,] 20.109106 2.1036418 5.4707734 1.4382122 -2.3036699 3.4535920 77 | [2,] 2.103642 18.9580585 -0.5792818 -3.0833482 2.3641027 -2.7418722 78 | [3,] 5.470773 -0.5792818 22.4775149 -0.4069596 -7.8751887 0.6191409 79 | [4,] 1.438212 -3.0833482 -0.4069596 21.9890162 -8.1631489 8.9901033 80 | [5,] -2.303670 2.3641027 -7.8751887 -8.1631489 42.1557126 -1.3545027 81 | [6,] 3.453592 -2.7418722 0.6191409 8.9901033 -1.3545027 18.8909467 82 | [7,] 4.547250 7.3108044 3.8756965 -2.6309851 -8.4618998 -10.9501264 83 | [8,] 12.957747 4.3994812 11.1956269 -1.4849982 -0.7790166 -0.9335345 84 | [,7] [,8] 85 | [1,] 4.547250 12.9577474 86 | [2,] 7.310804 4.3994812 87 | [3,] 3.875697 11.1956269 88 | [4,] -2.630985 -1.4849982 89 | [5,] -8.461900 -0.7790166 90 | [6,] -10.950126 -0.9335345 91 | [7,] 33.929624 6.1251750 92 | [8,] 6.125175 28.8428512 93 | 94 | $idx 95 | [1] 1 96 | 97 | 98 | -------------------------------------------------------------------------------- /tests/testthat/_snaps/make_design.md: -------------------------------------------------------------------------------- 1 | # design 2 | 3 | Code 4 | str(design_data, give.attr = FALSE) 5 | Output 6 | List of 9 7 | $ Flist :List of 5 8 | ..$ :Class 'formula' language v ~ lM 9 | ..$ :Class 'formula' language sv ~ lM 10 | ..$ :Class 'formula' language B ~ E + lR 11 | ..$ :Class 'formula' language t0 ~ E2 + CO 12 | ..$ :Class 'formula' language A ~ 1 13 | $ Ffactors :List of 3 14 | ..$ subjects: chr [1:19] "as1t" "bd6t" "bl1t" "hsft" ... 15 | ..$ E : chr [1:3] "speed" "neutral" "accuracy" 16 | ..$ S : chr [1:2] "left" "right" 17 | $ Rlevels : chr [1:2] "left" "right" 18 | $ Clist :List of 1 19 | ..$ v:List of 1 20 | .. ..$ lM: num [1:2, 1] -0.5 0.5 21 | $ matchfun :function (d) 22 | $ constants : Named num [1:2] 0 -Inf 23 | $ Fcovariates:List of 1 24 | ..$ CO: NULL 25 | $ Ffunctions :List of 1 26 | ..$ E2:function (d) 27 | $ model :function () 28 | 29 | --- 30 | 31 | Code 32 | str(design_custom, give.attr = FALSE) 33 | Output 34 | List of 9 35 | $ Flist :List of 3 36 | ..$ :Class 'formula' language m ~ 0 + S 37 | ..$ :Class 'formula' language s ~ 1 38 | ..$ :Class 'formula' language t0 ~ 1 39 | $ Ffactors :List of 2 40 | ..$ S : chr [1:2] "left" "right" 41 | ..$ subjects: int [1:3] 1 2 3 42 | $ Rlevels : chr [1:2] "left" "right" 43 | $ Clist : NULL 44 | $ matchfun : NULL 45 | $ constants : Named num 0 46 | $ Fcovariates: NULL 47 | $ Ffunctions : NULL 48 | $ model :function () 49 | 50 | -------------------------------------------------------------------------------- /tests/testthat/_snaps/new_models.md: -------------------------------------------------------------------------------- 1 | # DDMGNG 2 | 3 | Code 4 | init_chains(emc, particles = 10, cores_per_chain = 1)[[1]]$samples 5 | Output 6 | $alpha 7 | , , 1 8 | 9 | 1 10 | v 0.7732297 11 | v_Sright 0.6825030 12 | a -0.2179361 13 | Z -0.6387820 14 | t0 -1.6570450 15 | 16 | 17 | $stage 18 | [1] "init" 19 | 20 | $subj_ll 21 | [,1] 22 | 1 -34.14854 23 | 24 | $idx 25 | [1] 1 26 | 27 | 28 | --- 29 | 30 | Code 31 | make_data(p_vector, dGNG, n_trials = 10) 32 | Output 33 | subjects S trials R rt 34 | 1 1 left 1 left NA 35 | 2 1 right 1 left NA 36 | 3 1 left 2 left NA 37 | 4 1 right 2 right 0.7486671 38 | 5 1 left 3 left NA 39 | 6 1 right 3 right 1.0350038 40 | 7 1 left 4 left NA 41 | 8 1 right 4 right 0.4898115 42 | 9 1 left 5 left NA 43 | 10 1 right 5 right 0.7117752 44 | 11 1 left 6 left NA 45 | 12 1 right 6 left NA 46 | 13 1 left 7 left NA 47 | 14 1 right 7 right 1.2646380 48 | 15 1 left 8 left NA 49 | 16 1 right 8 right 0.4848544 50 | 17 1 left 9 left NA 51 | 18 1 right 9 right 0.4545908 52 | 19 1 left 10 left NA 53 | 20 1 right 10 right 0.5352639 54 | 55 | # probit 56 | 57 | Code 58 | init_chains(emc, particles = 10, cores_per_chain = 1)[[1]]$samples 59 | Output 60 | $alpha 61 | , , 1 62 | 63 | 1 64 | mean_Sleft -1.8345288 65 | mean_Sright 0.5068369 66 | 67 | 68 | $stage 69 | [1] "init" 70 | 71 | $subj_ll 72 | [,1] 73 | 1 -9.816787 74 | 75 | $idx 76 | [1] 1 77 | 78 | 79 | --- 80 | 81 | Code 82 | make_data(p_vector, dprobit, n_trials = 10) 83 | Output 84 | subjects S trials R rt 85 | 1 1 left 1 left NA 86 | 3 1 right 1 right NA 87 | 5 1 left 2 right NA 88 | 7 1 right 2 left NA 89 | 9 1 left 3 right NA 90 | 11 1 right 3 left NA 91 | 13 1 left 4 left NA 92 | 15 1 right 4 right NA 93 | 17 1 left 5 right NA 94 | 19 1 right 5 right NA 95 | 21 1 left 6 left NA 96 | 23 1 right 6 left NA 97 | 25 1 left 7 left NA 98 | 27 1 right 7 right NA 99 | 29 1 left 8 left NA 100 | 31 1 right 8 left NA 101 | 33 1 left 9 left NA 102 | 35 1 right 9 right NA 103 | 37 1 left 10 left NA 104 | 39 1 right 10 right NA 105 | 106 | -------------------------------------------------------------------------------- /tests/testthat/test-compare.R: -------------------------------------------------------------------------------- 1 | RNGkind("L'Ecuyer-CMRG") 2 | set.seed(123) 3 | 4 | test_that("compare", { 5 | expect_snapshot( 6 | compare(list(samples_LNR), cores_for_props = 1) 7 | ) 8 | }) 9 | 10 | test_that("savage-dickey", { 11 | expect_snapshot( 12 | round(hypothesis(samples_LNR, parameter = "m", do_plot = F, H0 = -1), 2)) 13 | expect_snapshot( 14 | round(hypothesis(samples_LNR, fun = function(d) d["m"] - d["m_lMd"], 15 | H0 = -0.5, do_plot = F), 2)) 16 | }) 17 | -------------------------------------------------------------------------------- /tests/testthat/test-customLL.R: -------------------------------------------------------------------------------- 1 | # Simple normal likelihood, the first half of the parameters are the means, 2 | # the second half the variances. We exp them to ensure positive variances 3 | custom_ll <- function(pars, dadm, ...){ 4 | idx <- dadm$S == "left" 5 | ll_left <- dnorm(dadm$rt[idx], pars[1], exp(pars[3])) 6 | ll_right <- dnorm(dadm$rt[!idx], pars[2], exp(pars[4])) 7 | return(sum(log(c(ll_left, ll_right)))) 8 | } 9 | 10 | 11 | library(EMC2) 12 | pars <- c("muL", "muR", "sdL", "sdR") 13 | 14 | 15 | design <- design(model = custom_ll, custom_p_vector = pars) 16 | 17 | # using nuisance = 3:4 18 | custom_emc <- make_emc(get_data(samples_LNR), design, type = "standard", nuisance_non_hyper = 3:4) 19 | 20 | RNGkind("L'Ecuyer-CMRG") 21 | set.seed(123) 22 | test_that("custom_ll", { 23 | expect_snapshot(init_chains(custom_emc, cores_for_chains = 1, particles = 10)) 24 | }) 25 | -------------------------------------------------------------------------------- /tests/testthat/test-fit.R: -------------------------------------------------------------------------------- 1 | # When working with lM it is useful to design an "average and difference" 2 | # contrast matrix, which for binary responses has a simple canonical from: 3 | ADmat <- matrix(c(-1/2,1/2),ncol=1,dimnames=list(NULL,"d")) 4 | # We also define a match function for lM 5 | matchfun=function(d)d$S==d$lR 6 | 7 | # Drop most subjects 8 | dat <- forstmann[forstmann$subjects %in% unique(forstmann$subjects)[1:2],] 9 | dat$subjects <- droplevels(dat$subjects) 10 | 11 | design_LNR <- design(data = dat,model=LNR,matchfun=matchfun, 12 | formula=list(m~lM,s~1,t0~1), 13 | contrasts=list(m=list(lM=ADmat))) 14 | 15 | LNR_s <- make_emc(dat, design_LNR, rt_resolution = 0.05, n_chains = 2) 16 | 17 | RNGkind("L'Ecuyer-CMRG") 18 | set.seed(123) 19 | LNR_s <- fit(LNR_s, cores_for_chains = 1, stop_criteria = list( 20 | preburn = list(iter = 10), burn = list(mean_gd = 2.5), adapt = list(min_unique = 20), 21 | sample = list(iter = 25)), verbose = FALSE, particle_factor = 30, step_size = 25) 22 | idx <- LNR_s[[1]]$samples$idx 23 | 24 | test_that("fit", { 25 | expect_snapshot( 26 | LNR_s[[1]]$samples$theta_mu[,idx], variant = Sys.info()[1] 27 | ) 28 | expect_snapshot( 29 | LNR_s[[1]]$samples$alpha[,,idx], variant = Sys.info()[1] 30 | ) 31 | expect_snapshot( 32 | LNR_s[[1]]$samples$theta_var[,,idx], variant = Sys.info()[1] 33 | ) 34 | }) 35 | -------------------------------------------------------------------------------- /tests/testthat/test-joint.R: -------------------------------------------------------------------------------- 1 | # Simple joint test 2 | # Take the first entry of the design list 3 | # emc stores a design list (with length 1 for non-joint models) 4 | # or for joint models length x where x is the number of joint components 5 | design_in <- get_design(samples_LNR)[[1]] 6 | prior_in <- get_prior(samples_LNR) 7 | data_in <- get_data(samples_LNR) 8 | 9 | prior_joint <- prior(list(design_in, design_in)) 10 | 11 | joint <- make_emc(list(data_in, data_in), list(design_in, design_in), prior_list = prior_joint) 12 | RNGkind("L'Ecuyer-CMRG") 13 | set.seed(123) 14 | test_that("joint", { 15 | expect_snapshot(init_chains(joint, particles = 10, cores_for_chains = 1)[[1]]$samples) 16 | }) 17 | -------------------------------------------------------------------------------- /tests/testthat/test-make_design.R: -------------------------------------------------------------------------------- 1 | design_data <- design(data = data.frame(forstmann, CO = 1:nrow(forstmann)), 2 | model=LBA,matchfun=function(d)d$S==d$lR, 3 | formula=list(v~lM,sv~lM,B~E+lR,t0~E2 + CO), 4 | contrasts=list(v = list(lM=matrix(c(-1/2,1/2),ncol=1,dimnames=list(NULL,"d")))), 5 | constants=c(sv=log(1)), 6 | functions = list( 7 | E2 = function(d) factor(d$E!="speed",labels=c("speed","nonspeed")) 8 | )) 9 | 10 | 11 | design_custom <- design(factors = list(S = c("left", "right"), 12 | subjects = 1:3), 13 | Rlevels = c("left", "right"), model = LNR, 14 | formula =list(m~0+S,s~1, t0~1), 15 | constants=c(s=log(1))) 16 | 17 | test_that("design", { 18 | expect_snapshot( 19 | str(design_data, give.attr = FALSE) 20 | ) 21 | expect_snapshot( 22 | str(design_custom, give.attr = FALSE) 23 | ) 24 | }) 25 | -------------------------------------------------------------------------------- /tests/testthat/test-make_emc.R: -------------------------------------------------------------------------------- 1 | matchfun <- function(d)d$S==d$lR 2 | # design an "average and difference" contrast matrix 3 | ADmat <- matrix(c(-1/2,1/2),ncol=1,dimnames=list(NULL,"diff")) 4 | 5 | # specify design 6 | design_LBABE <- design(data = forstmann,model=LBA, 7 | formula=list(v~1,sv~1,B~E+lR,A~1,t0~1), 8 | constants=c(sv=log(1))) 9 | 10 | pmean <- c(v=1, B=log(.5),B_Eneutral=log(1.5), 11 | B_Eaccuracy=log(2),B_lRright=0, A=log(0.25),t0=log(.2)) 12 | psd <- c(v=1, 13 | B=0.3,B_Eneutral=0.3,B_Eaccuracy=0.3,B_lRright=0.3,A=0.4,t0=.5) 14 | prior_LBABE <- prior(design_LBABE, type = 'standard',pmean=pmean,psd=psd) 15 | emc <- make_emc(forstmann,design_LBABE,type="standard", prior=prior_LBABE, 16 | compress = FALSE) 17 | 18 | test_that("make_emc", { 19 | expect_snapshot(str(emc, give.attr = F)) 20 | }) 21 | -------------------------------------------------------------------------------- /tests/testthat/test-model_functions.R: -------------------------------------------------------------------------------- 1 | # When working with lM it is useful to design an "average and difference" 2 | # contrast matrix, which for binary responses has a simple canonical from: 3 | ADmat <- matrix(c(-1/2,1/2),ncol=1,dimnames=list(NULL,"d")) 4 | # We also define a match function for lM 5 | matchfun=function(d)d$S==d$lR 6 | 7 | dat <- forstmann[forstmann$subjects %in% unique(forstmann$subjects)[1:2],] 8 | dat$subjects <- droplevels(dat$subjects) 9 | 10 | # First race models 11 | design_LNR <- design(data = dat,model=LNR,matchfun=matchfun, 12 | formula=list(m~lM + E,s~1,t0~1), 13 | contrasts=list(m=list(lM=ADmat))) 14 | 15 | p_LNR <- c(m=-1,m_lMd=2, m_Eneutral = .1, m_Eaccuracy = .1, s = .5, t0=log(.2)) 16 | 17 | design_LBA <- design(data = dat,model=LBA,matchfun=matchfun, 18 | formula=list(v~lM,sv~lM,B~E+lR,A~1,t0~1), 19 | contrasts=list(v=list(lM=ADmat)),constants=c(sv=log(1))) 20 | 21 | p_LBA <- c(v=1.5,v_lMd=1, sv_lMTRUE = log(.5), B = log(2), B_Eneutral = .5, 22 | B_Eaccuracy = .3, B_lRright = 0, A = log(.4), t0=log(.2)) 23 | 24 | 25 | design_RDM <- design(data = dat,model=RDM,matchfun=matchfun, 26 | formula=list(v~lM,s~lM,B~E+lR,A~1,t0~1), 27 | contrasts=list(v=list(lM=ADmat)),constants=c(s=log(1))) 28 | 29 | p_RDM <- c(v=.5,v_lMd=1, s_lMTRUE = log(.5), B = log(2), B_Eneutral = .5, 30 | B_Eaccuracy = .3, B_lRright = 0, A = log(.4), t0=log(.2)) 31 | 32 | # Also DDM 33 | design_DDM <- design(data = dat,model=DDM, 34 | formula =list(v~0+S,a~E, t0~1, s~1, Z~1, sv~1, SZ~1), 35 | constants=c(s=log(1))) 36 | 37 | p_DDM <- c(v_Sleft = -2, v_Sright = 2, a = log(2), a_Eneutral = .3, a_Eaccuracy = .3, t0 = log(.2), 38 | Z = qnorm(.5), sv = 1, SZ = qnorm(.3)) 39 | 40 | LNR_s <- make_emc(dat, design_LNR, compress = F, n_chains = 1) 41 | LBA_s <- make_emc(dat, design_LBA, compress = F, n_chains = 1) 42 | RDM_s <- make_emc(dat, design_RDM, compress = F, n_chains = 1) 43 | DDM_s <- make_emc(dat, design_DDM, compress = F, n_chains = 1) 44 | 45 | test_that("LNR", { 46 | RNGkind("L'Ecuyer-CMRG") 47 | set.seed(123) 48 | expect_snapshot(init_chains(LNR_s, particles = 10, cores_per_chain = 1)[[1]]$samples) 49 | expect_snapshot(make_data(p_LNR, design_LNR, n_trials = 10)) 50 | }) 51 | 52 | test_that("LBA", { 53 | RNGkind("L'Ecuyer-CMRG") 54 | set.seed(123) 55 | expect_snapshot(init_chains(LBA_s, particles = 10, cores_per_chain = 1)[[1]]$samples) 56 | expect_snapshot(make_data(p_LBA, design_LBA, n_trials = 10)) 57 | }) 58 | 59 | 60 | test_that("RDM", { 61 | RNGkind("L'Ecuyer-CMRG") 62 | set.seed(123) 63 | expect_snapshot(init_chains(RDM_s, particles = 10, cores_per_chain = 1)[[1]]$samples) 64 | expect_snapshot(make_data(p_RDM, design_RDM, n_trials = 10)) 65 | }) 66 | 67 | 68 | test_that("DDM", { 69 | RNGkind("L'Ecuyer-CMRG") 70 | set.seed(123) 71 | expect_snapshot(init_chains(DDM_s, particles = 10, cores_per_chain = 1)[[1]]$samples) 72 | expect_snapshot(make_data(p_DDM, design_DDM, n_trials = 10)) 73 | }) 74 | -------------------------------------------------------------------------------- /tests/testthat/test-new_models.R: -------------------------------------------------------------------------------- 1 | dGNG <- design(Rlevels = c("left","right"), 2 | factors=list(subjects=1,S=c("left","right")), 3 | functions=list( 4 | TIMEOUT=function(d)rep(2.5,nrow(d)), 5 | Rnogo=function(d)factor(rep("left",nrow(d)),levels=c("left","right")), # no go response level 6 | Rgo=function(d)factor(rep("right",nrow(d)),levels=c("left","right"))), # go response level 7 | formula=list(v~S,a~1, Z~1, t0~1), 8 | model=DDMGNG) 9 | 10 | p_vector <- sampled_pars(dGNG,doMap=F) 11 | p_vector[1:5] <- c(0,1,log(1),qnorm(.5),log(.4)) 12 | 13 | RNGkind("L'Ecuyer-CMRG") 14 | set.seed(123) 15 | 16 | sdat <- make_data(p_vector,dGNG,n_trials=10) 17 | emc <- make_emc(sdat,dGNG,type="single", compress = FALSE, n_chains = 1) 18 | 19 | test_that("DDMGNG", { 20 | expect_snapshot(init_chains(emc, particles = 10, cores_per_chain = 1)[[1]]$samples) 21 | expect_snapshot(make_data(p_vector,dGNG,n_trials=10)) 22 | }) 23 | 24 | 25 | dprobit <- design(Rlevels = c("left","right"), 26 | factors=list(subjects=1,S=c("left","right")), 27 | formula=list(mean ~ 0+S, sd ~ 1,threshold ~ 1), 28 | matchfun=function(d)d$S==d$lR, 29 | constants=c(sd=log(1),threshold=0), 30 | model=SDT) 31 | 32 | p_vector <- sampled_pars(dprobit,doMap=F) 33 | p_vector[1:2] <- c(-1,1) 34 | sdat <- make_data(p_vector,dprobit,n_trials=10) 35 | emc <- make_emc(sdat,dprobit,type="single", compress = F, n_chains = 1) 36 | 37 | test_that("probit", { 38 | expect_snapshot(init_chains(emc, particles = 10, cores_per_chain = 1)[[1]]$samples) 39 | expect_snapshot(make_data(p_vector,dprobit,n_trials=10)) 40 | }) 41 | -------------------------------------------------------------------------------- /tests/testthat/test-pairs_posterior.R: -------------------------------------------------------------------------------- 1 | test_that("pairs_posterior", { 2 | vdiffr::expect_doppelganger("pairs_plot", pairs_posterior(samples_LNR, selection = "sigma2")) 3 | }) 4 | 5 | -------------------------------------------------------------------------------- /tests/testthat/test-plot_chains.R: -------------------------------------------------------------------------------- 1 | test_that("plot_chains", { 2 | vdiffr::expect_doppelganger("chain_plots", plot(samples_LNR, selection = "mu")) 3 | }) 4 | 5 | 6 | -------------------------------------------------------------------------------- /tests/testthat/test-plot_fit.R: -------------------------------------------------------------------------------- 1 | RNGkind("L'Ecuyer-CMRG") 2 | set.seed(123) 3 | # Generate some prior predictives 4 | dat <- get_data(samples_LNR) 5 | pp <- predict(get_prior(samples_LNR), n_post = 25, data = dat) 6 | drt <- function(data) diff(tapply(data$rt,data[,c("S")],mean)) 7 | 8 | test_that("plot_fit", { 9 | vdiffr::expect_doppelganger("CDF_plot_fit", plot_cdf(dat, prior_predict = pp, factors = c("S", "E"), layout = c(2,3), use_lim = c('data'))) 10 | vdiffr::expect_doppelganger("dens_plot_fit", plot_density(dat, prior_predict = pp, defective_factor = "E")) 11 | vdiffr::expect_doppelganger("stat_plot_fit", plot_stat(samples_LNR, to_plot = c('data', 'posterior'), stat_fun=drt,stat_name="RT diff Left vs Right", 12 | n_post = 10)) 13 | }) 14 | -------------------------------------------------------------------------------- /tests/testthat/test-plot_pars.R: -------------------------------------------------------------------------------- 1 | test_that("plot_pars", { 2 | RNGkind("L'Ecuyer-CMRG") 3 | set.seed(123) 4 | vdiffr::expect_doppelganger("density_plots", plot_pars(samples_LNR, selection = "sigma2")) 5 | vdiffr::expect_doppelganger("density_alpha", plot_pars(samples_LNR, all_subjects = T)) 6 | }) 7 | -------------------------------------------------------------------------------- /tests/testthat/test-plot_relations.R: -------------------------------------------------------------------------------- 1 | test_that("plot_relations", { 2 | vdiffr::expect_doppelganger("plot_relations_cred", plot_relations(samples_LNR, only_cred = TRUE, plot_cred = TRUE)) 3 | vdiffr::expect_doppelganger("plot_relations_mean", plot_relations(samples_LNR, plot_means = TRUE, only_cred = FALSE)) 4 | }) 5 | -------------------------------------------------------------------------------- /tests/testthat/test-profile.R: -------------------------------------------------------------------------------- 1 | RNGkind("L'Ecuyer-CMRG") 2 | set.seed(123) 3 | test_that("profile_plot", { 4 | vdiffr::expect_doppelganger("profile_plot", 5 | profile_plot(get_data(samples_LNR), get_design(samples_LNR)[[1]], credint(samples_LNR, probs = .5)[[1]])) 6 | }) 7 | -------------------------------------------------------------------------------- /tests/testthat/test-variant_funs.R: -------------------------------------------------------------------------------- 1 | # When working with lM it is useful to design an "average and difference" 2 | # contrast matrix, which for binary responses has a simple canonical from: 3 | ADmat <- matrix(c(-1/2,1/2),ncol=1,dimnames=list(NULL,"d")) 4 | # We also define a match function for lM 5 | matchfun=function(d)d$S==d$lR 6 | 7 | # Drop most subjects 8 | dat <- forstmann[forstmann$subjects %in% unique(forstmann$subjects)[1:2],] 9 | dat$subjects <- droplevels(dat$subjects) 10 | 11 | design_LNR <- design(data = dat,model=LNR,matchfun=matchfun, 12 | formula=list(m~lM,s~1,t0~1), 13 | contrasts=list(m=list(lM=ADmat))) 14 | 15 | # create emc objects for the different types 16 | LNR_factor <- make_emc(dat, design_LNR, rt_resolution = 0.05, n_chains = 2, type = "factor", 17 | n_factors = 2) 18 | LNR_diag <- make_emc(dat, design_LNR, rt_resolution = 0.05, n_chains = 2, type = "diagonal") 19 | LNR_blocked <- make_emc(dat, design_LNR, rt_resolution = 0.05, n_chains = 2, type = "blocked", 20 | par_groups = c(1,2,3,3)) 21 | LNR_single <- make_emc(dat, design_LNR, rt_resolution = 0.05, n_chains = 2, type = "single") 22 | 23 | # Set seed for mclapply 24 | RNGkind("L'Ecuyer-CMRG") 25 | set.seed(123) 26 | # Run the models for the different variants 27 | # Only preburn, so bit risky since adapt could fail 28 | N <- 50 29 | 30 | LNR_factor <- init_chains(LNR_factor, cores_for_chains = 1, particles = 10) 31 | LNR_factor <- run_emc(LNR_factor, cores_for_chains = 1, stop_criteria = list(iter = N), stage = "preburn", particle_factor = 25) 32 | 33 | LNR_diag <- init_chains(LNR_diag, cores_for_chains = 1, particles = 10) 34 | LNR_diag <- run_emc(LNR_diag, cores_for_chains = 1, stop_criteria = list(iter = N), stage = "preburn", particle_factor = 25) 35 | 36 | LNR_blocked <- init_chains(LNR_blocked, cores_for_chains = 1, particles = 10) 37 | LNR_blocked <- run_emc(LNR_blocked, cores_for_chains = 1, stop_criteria = list(iter = N), stage = "preburn", particle_factor = 25) 38 | 39 | LNR_single <- init_chains(LNR_single, cores_for_chains = 1, particles = 10) 40 | LNR_single <- run_emc(LNR_single, cores_for_chains = 1, stop_criteria = list(iter = N), stage = "preburn", particle_factor = 25) 41 | 42 | 43 | idx <- N + 1 44 | 45 | test_that("run_factor", { 46 | expect_snapshot( 47 | LNR_factor[[1]]$samples$theta_lambda[,,idx], variant = Sys.info()[1] 48 | ) 49 | expect_snapshot( 50 | LNR_factor[[1]]$samples$alpha[,,idx], variant = Sys.info()[1] 51 | ) 52 | expect_snapshot( 53 | LNR_factor[[1]]$samples$theta_mu[,idx],variant = Sys.info()[1] 54 | ) 55 | expect_snapshot( 56 | LNR_factor[[1]]$samples$theta_var[,,idx], variant = Sys.info()[1] 57 | ) 58 | }) 59 | 60 | test_that("run_diag", { 61 | expect_snapshot( 62 | LNR_diag[[1]]$samples$alpha[,,idx], variant = Sys.info()[1] 63 | ) 64 | expect_snapshot( 65 | LNR_diag[[1]]$samples$theta_mu[,idx], variant = Sys.info()[1] 66 | ) 67 | expect_snapshot( 68 | LNR_diag[[1]]$samples$theta_var[,,idx], variant = Sys.info()[1] 69 | ) 70 | }) 71 | 72 | test_that("run_blocked", { 73 | expect_snapshot( 74 | LNR_blocked[[1]]$samples$alpha[,,idx], variant = Sys.info()[1] 75 | ) 76 | expect_snapshot( 77 | LNR_blocked[[1]]$samples$theta_mu[,idx], variant = Sys.info()[1] 78 | ) 79 | expect_snapshot( 80 | LNR_blocked[[1]]$samples$theta_var[,,idx], variant = Sys.info()[1] 81 | ) 82 | }) 83 | 84 | test_that("run_single", { 85 | expect_snapshot( 86 | LNR_single[[1]]$samples$alpha[,,idx], variant = Sys.info()[1] 87 | ) 88 | }) 89 | 90 | test_that("run_bridge", { 91 | expect_snapshot( 92 | compare(list(single = LNR_single, diag = LNR_diag, factor = LNR_factor, 93 | blocked = LNR_blocked), stage = "preburn", cores_for_props = 1), 94 | variant = Sys.info()[1] 95 | ) 96 | }) 97 | -------------------------------------------------------------------------------- /tests/testthat/test_S3.R: -------------------------------------------------------------------------------- 1 | prior <- get_prior(samples_LNR) 2 | design <- get_design(samples_LNR) 3 | 4 | 5 | RNGkind("L'Ecuyer-CMRG") 6 | set.seed(123) 7 | test_that("priorS3", { 8 | expect_snapshot(prior) 9 | expect_snapshot(summary(prior)) 10 | vdiffr::expect_doppelganger("prior_plot", plot(prior)) 11 | }) 12 | 13 | test_that("designS3", { 14 | expect_snapshot(design) 15 | expect_snapshot(summary(design)) 16 | }) 17 | -------------------------------------------------------------------------------- /vignettes/SBC_data/SBC_DDM.RData: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ampl-psych/EMC2/5a23740a614054ca634c11d12fd06d3def16e6aa/vignettes/SBC_data/SBC_DDM.RData -------------------------------------------------------------------------------- /vignettes/SBC_data/SBC_DDM_single.RData: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ampl-psych/EMC2/5a23740a614054ca634c11d12fd06d3def16e6aa/vignettes/SBC_data/SBC_DDM_single.RData -------------------------------------------------------------------------------- /vignettes/SBC_data/SBC_LBA.RData: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ampl-psych/EMC2/5a23740a614054ca634c11d12fd06d3def16e6aa/vignettes/SBC_data/SBC_LBA.RData -------------------------------------------------------------------------------- /vignettes/SBC_data/SBC_LBA_single.RData: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ampl-psych/EMC2/5a23740a614054ca634c11d12fd06d3def16e6aa/vignettes/SBC_data/SBC_LBA_single.RData -------------------------------------------------------------------------------- /vignettes/SBC_data/SBC_LNR.RData: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ampl-psych/EMC2/5a23740a614054ca634c11d12fd06d3def16e6aa/vignettes/SBC_data/SBC_LNR.RData -------------------------------------------------------------------------------- /vignettes/SBC_data/SBC_RDM.RData: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ampl-psych/EMC2/5a23740a614054ca634c11d12fd06d3def16e6aa/vignettes/SBC_data/SBC_RDM.RData -------------------------------------------------------------------------------- /vignettes/refs.bib: -------------------------------------------------------------------------------- 1 | @article{talts2018validating, 2 | title={Validating Bayesian inference algorithms with simulation-based calibration}, 3 | author={Talts, Sean and Betancourt, Michael and Simpson, Daniel and Vehtari, Aki and Gelman, Andrew}, 4 | journal={arXiv preprint arXiv:1804.06788}, 5 | year={2018}, 6 | } 7 | 8 | @Manual{Sigmann2022, 9 | title = {rtdists: Response Time Distributions}, 10 | author = {Henrik Singmann and Scott Brown and Matthew Gretton and Andrew Heathcote}, 11 | year = {2022}, 12 | note = {R package version 0.11-5}, 13 | url = {https://CRAN.R-project.org/package=rtdists}, 14 | } 15 | 16 | @Manual{Hartmann2023, 17 | title = {WienR: Derivatives of the First-Passage Time Density and Cumulative 18 | Distribution Function, and Random Sampling from the (Truncated) 19 | First-Passage Time Distribution}, 20 | author = {Raphael Hartmann and Karl C. Klauer}, 21 | year = {2023}, 22 | note = {R package version 0.3-15}, 23 | url = {https://CRAN.R-project.org/package=WienR}, 24 | } 25 | 26 | @article{Gelman2006Sep, 27 | author = {Gelman, Andrew}, 28 | title = {{Prior distributions for variance parameters in hierarchical models (comment on article by Browne and Draper)}}, 29 | journal = {Bayesian Analysis}, 30 | volume = {1}, 31 | number = {3}, 32 | pages = {515--534}, 33 | year = {2006}, 34 | issn = {1936-0975}, 35 | publisher = {International Society for Bayesian Analysis}, 36 | doi = {10.1214/06-BA117A} 37 | } 38 | 39 | @article{Huang2013Jun, 40 | author = {Huang, Alan and Wand, M. P.}, 41 | title = {{Simple Marginally Noninformative Prior Distributions for Covariance Matrices}}, 42 | journal = {Bayesian Analysis}, 43 | volume = {8}, 44 | number = {2}, 45 | pages = {439--452}, 46 | year = {2013}, 47 | issn = {1936-0975}, 48 | publisher = {International Society for Bayesian Analysis}, 49 | doi = {10.1214/13-BA815} 50 | } 51 | 52 | @article{carpenter2017stan, 53 | title={Stan: A probabilistic programming language}, 54 | author={Carpenter, Bob and Gelman, Andrew and Hoffman, Matthew D and Lee, Daniel and Goodrich, Ben and Betancourt, Michael and Brubaker, Marcus and Guo, Jiqiang and Li, Peter and Riddell, Allen}, 55 | journal={Journal of Statistical Software}, 56 | volume={76}, 57 | number={1}, 58 | year={2017}, 59 | publisher={Columbia Univ., New York, NY (United States); Harvard Univ., Cambridge, MA (United States)} 60 | } 61 | --------------------------------------------------------------------------------