├── .Rbuildignore ├── .github ├── .gitignore └── workflows │ └── R-CMD-check.yaml ├── BayesianTools ├── tests │ ├── testthat │ │ ├── test-getSample.R │ │ ├── test-utils-Numerics.R │ │ ├── test-runMCMC.R │ │ ├── test-plotDiagnostic.R │ │ ├── test-marginalLikelihood.R │ │ ├── testFunctionalities.R │ │ ├── test-tracePlot.R │ │ ├── test-infinity.R │ │ ├── test-settingsDefault.R │ │ ├── test-marginalPlot.R │ │ ├── test-correlationPlot.R │ │ └── test-startValues.R │ └── testthat.R ├── .gitignore ├── inst │ └── examples │ │ ├── testLinearModel.R │ │ ├── GOF.R │ │ ├── plotSensitivityHelp.R │ │ ├── generateParallelExecuter.R │ │ ├── generateTestDensityMultiNormalHelp.R │ │ ├── plotTimeSeriesHelp.R │ │ ├── plotDiagnosticHelp.R │ │ ├── WAICHelp.R │ │ ├── tracePlotHelp.R │ │ ├── MetropolisHelp.R │ │ ├── getVolume.R │ │ ├── getSampleHelp.R │ │ ├── bridgesampleHelp.R │ │ ├── mcmcRun.R │ │ ├── correlationPlotHelp.R │ │ ├── marginalPlotHelp.R │ │ ├── DEfamilyHelp.R │ │ ├── proposalGeneratorHelp.R │ │ └── createPrior.R ├── vignettes │ ├── betaDensity.png │ ├── normalDensity.png │ └── uniformDensity.png ├── man │ ├── figures │ │ ├── betaDensity.png │ │ ├── normalDensity.png │ │ └── uniformDensity.png │ ├── VSEMgetDefaults.Rd │ ├── getPossibleSamplerTypes.Rd │ ├── sumSquare.Rd │ ├── betaFun.Rd │ ├── vsemC.Rd │ ├── factorMatrice.Rd │ ├── getPanels.Rd │ ├── getRmvnorm.Rd │ ├── thinMatrix.Rd │ ├── getSetup.Rd │ ├── stopParallel.Rd │ ├── VSEMcreatePAR.Rd │ ├── getBlockSettings.Rd │ ├── scaleMatrix.Rd │ ├── testDensityNormal.Rd │ ├── getBlock.Rd │ ├── testDensityMultiNormal.Rd │ ├── plotTimeSeriesResiduals.Rd │ ├── metropolisRatio.Rd │ ├── updateGroups.Rd │ ├── rescale.Rd │ ├── likelihoodIidNormal.Rd │ ├── testDensityInfinity.Rd │ ├── package-deprecated.Rd │ ├── createPosterior.Rd │ ├── generateCRvalues.Rd │ ├── combineChains.Rd │ ├── AdaptpCR.Rd │ ├── createSmcSamplerList.Rd │ ├── createMcmcSamplerList.Rd │ ├── mcmcMultipleChains.Rd │ ├── testDensityGelmanMeng.Rd │ ├── sampleEquallySpaced.Rd │ ├── logSumExp.Rd │ ├── testLinearModel.Rd │ ├── getCredibleIntervals.Rd │ ├── testDensityBanana.Rd │ ├── setupStartProposal.Rd │ ├── mergeChains.Rd │ ├── likelihoodAR1.Rd │ ├── sampleMetropolis.Rd │ ├── makeObjectClassCodaMCMC.Rd │ ├── Gfun.Rd │ ├── correctThin.Rd │ ├── getPredictiveDistribution.Rd │ ├── MAP.Rd │ ├── propFun.Rd │ ├── marginalPlotDensity.Rd │ ├── marginalPlotViolin.Rd │ ├── VSEMcreateLikelihood.Rd │ ├── updateProposalGenerator.Rd │ ├── getDharmaResiduals.Rd │ ├── plotSensitivity.Rd │ ├── Twalksteps.Rd │ ├── convertCoda.Rd │ ├── AM.Rd │ ├── DRAM.Rd │ ├── DR.Rd │ ├── tracePlot.Rd │ ├── DIC.Rd │ ├── M.Rd │ ├── generateTestDensityMultiNormal.Rd │ ├── TwalkMove.Rd │ ├── getPredictiveIntervals.Rd │ ├── createLikelihood.Rd │ ├── checkBayesianSetup.Rd │ ├── plotTimeSeries.Rd │ ├── getVolume.Rd │ ├── Twalk.Rd │ ├── plotDiagnostic.Rd │ ├── plotTimeSeriesResults.Rd │ ├── bridgesample.Rd │ ├── GOF.Rd │ └── generateParallelExecuter.Rd ├── .Rbuildignore ├── R │ ├── importPackages.R │ ├── RcppExports.R │ ├── benchmark.R │ ├── plotTrace.R │ ├── MAP.R │ ├── utilsFrancesco.R │ ├── mcmcMultipleChains.R │ ├── utils-Numerics.R │ ├── getVolume.R │ ├── codaFunctions.R │ ├── classSMCSamplerList.R │ ├── plotSensitivityOAT.R │ ├── classPosterior.R │ ├── classSmcSampler.R │ └── convertCoda.R ├── src │ ├── init.c │ ├── RcppExports.cpp │ └── vsem.cpp ├── DESCRIPTION └── _pkgdown.yml ├── Examples ├── ParticleMCMC │ └── Untitled.R ├── RandomEffectsModel_files │ └── figure-html │ │ ├── unnamed-chunk-2-1.png │ │ ├── unnamed-chunk-3-1.png │ │ ├── unnamed-chunk-4-1.png │ │ ├── unnamed-chunk-6-1.png │ │ └── unnamed-chunk-7-1.png ├── install.R ├── Old │ └── BT-MCMC-Auto-Demo.Rmd ├── postHocPrior.R └── BayesFactor.Rmd ├── Development ├── data.R ├── manualTests │ ├── Defaults │ │ ├── defaults.Rdata │ │ └── saveDefaults.R │ └── MetropolisTest.Rmd ├── vignette │ └── Test.Rnw ├── CreateData.R ├── DATASET.R ├── BayesFactor.R ├── Figures │ └── figures.R ├── testSuite.R └── BT-issues │ └── issue-222.R ├── Publications ├── readme.md └── SpeichEtAl-SMCForModelCalibration │ ├── readme_files │ └── figure-html │ │ └── unnamed-chunk-3-1.png │ ├── 6_prior_posterior_plots │ └── readme_files │ │ └── figure-html │ │ ├── unnamed-chunk-6-1.png │ │ ├── unnamed-chunk-7-1.png │ │ ├── unnamed-chunk-8-1.png │ │ ├── unnamed-chunk-9-1.png │ │ ├── unnamed-chunk-10-1.png │ │ └── unnamed-chunk-11-1.png │ ├── 5_launch_scripts │ ├── test_parallel_40_50ms_mult1.moab │ └── compare_smc_threePGN_mult1.moab │ ├── 1_reference_MCMC │ └── threePGN_gen_ref.r │ └── 4_parallelization │ ├── test_parallel_1_20ms.r │ ├── test_parallel_1_50ms.r │ ├── test_parallel_2plus_20ms.r │ └── test_parallel_2plus_50ms.r ├── docs ├── reference │ ├── AM.html │ ├── DE.html │ ├── DR.html │ ├── M.html │ ├── DEzs.html │ ├── DIC.html │ ├── DRAM.html │ ├── DREAM.html │ ├── GOF-5.png │ ├── GOF.html │ ├── MAP.html │ ├── Twalk.html │ ├── VSEM-9.png │ ├── VSEM.html │ ├── WAIC.html │ ├── vsemC.html │ ├── DREAMzs.html │ ├── VSEM-10.png │ ├── rescale.html │ ├── runMCMC.html │ ├── Metropolis.html │ ├── getPanels.html │ ├── getSample-5.png │ ├── getSample.html │ ├── getVolume.html │ ├── logSumExp.html │ ├── plotHist.html │ ├── runMCMC-13.png │ ├── runMCMC-14.png │ ├── runMCMC-15.png │ ├── smcSampler.html │ ├── tracePlot-9.png │ ├── tracePlot.html │ ├── violinPlot.html │ ├── bridgesample.html │ ├── convertCoda.html │ ├── correctThin.html │ ├── createPrior.html │ ├── histMarginal.html │ ├── marginalPlot.html │ ├── smcSampler-73.png │ ├── smcSampler-74.png │ ├── smcSampler-75.png │ ├── smcSampler-76.png │ ├── smcSampler-77.png │ ├── smcSampler-78.png │ ├── smcSampler-79.png │ ├── smcSampler-80.png │ ├── smcSampler-81.png │ ├── smcSampler-82.png │ ├── smcSampler-83.png │ ├── smcSampler-84.png │ ├── smcSampler-85.png │ ├── smcSampler-86.png │ ├── smcSampler-87.png │ ├── smcSampler-88.png │ ├── smcSampler-89.png │ ├── smcSampler-90.png │ ├── stopParallel.html │ ├── tracePlot-10.png │ ├── BayesianTools.html │ ├── VSEMcreatePAR.html │ ├── VSEMgetDefaults.html │ ├── correlationPlot.html │ ├── createBetaPrior.html │ ├── createBreakMat.html │ ├── createPosterior.html │ ├── likelihoodAR1.html │ ├── marginalPlot-5.png │ ├── metropolisRatio.html │ ├── plotSensitivity.html │ ├── plotTimeSeries-5.png │ ├── plotTimeSeries.html │ ├── testLinearModel.html │ ├── correlationPlot-6.png │ ├── createLikelihood.html │ ├── gelmanDiagnostics.html │ ├── sampleMetropolis.html │ ├── testDensityBanana.html │ ├── testDensityNormal.html │ ├── testLinearModel-5.png │ ├── VSEMcreateLikelihood.html │ ├── applySettingsDefault.html │ ├── checkBayesianSetup.html │ ├── createBayesianSetup.html │ ├── createPriorDensity.html │ ├── createSmcSamplerList.html │ ├── createUniformPrior.html │ ├── getCredibleIntervals.html │ ├── getDharmaResiduals.html │ ├── likelihoodIidNormal.html │ ├── marginalLikelihood-10.png │ ├── marginalLikelihood-9.png │ ├── marginalLikelihood.html │ ├── mcmcMultipleChains.html │ ├── package-deprecated.html │ ├── sampleEquallySpaced.html │ ├── setupStartProposal.html │ ├── testDensityInfinity.html │ ├── createMcmcSamplerList.html │ ├── getPredictiveIntervals.html │ ├── plotTimeSeriesResults.html │ ├── testDensityMultiNormal.html │ ├── createProposalGenerator-21.png │ ├── createProposalGenerator-22.png │ ├── createProposalGenerator-23.png │ ├── createProposalGenerator-24.png │ ├── createProposalGenerator-25.png │ ├── createProposalGenerator.html │ ├── generateParallelExecuter.html │ ├── getPossibleSamplerTypes.html │ ├── getPredictiveDistribution.html │ ├── plotTimeSeriesResiduals.html │ ├── updateProposalGenerator.html │ ├── createTruncatedNormalPrior.html │ ├── generateTestDensityMultiNormal.html │ ├── getMetropolisDefaultSettings.html │ ├── generateTestDensityMultiNormal-10.png │ └── generateTestDensityMultiNormal-9.png ├── articles │ └── BayesianTools_files │ │ └── figure-html │ │ ├── unnamed-chunk-9-1.png │ │ ├── unnamed-chunk-9-2.png │ │ ├── unnamed-chunk-9-3.png │ │ ├── unnamed-chunk-14-1.png │ │ ├── unnamed-chunk-15-1.png │ │ ├── unnamed-chunk-20-1.png │ │ ├── unnamed-chunk-20-2.png │ │ ├── unnamed-chunk-20-3.png │ │ ├── unnamed-chunk-20-4.png │ │ ├── unnamed-chunk-35-1.png │ │ └── unnamed-chunk-38-1.png ├── link.svg └── pkgdown.js ├── .travis.yml ├── BayesianTools.Rproj ├── .gitattributes ├── pkgdown_bootstrap.r ├── Test ├── BasicNormalTest.R └── BasicBTTest.R └── .gitignore /.Rbuildignore: -------------------------------------------------------------------------------- 1 | ^data-raw$ 2 | -------------------------------------------------------------------------------- /.github/.gitignore: -------------------------------------------------------------------------------- 1 | *.html 2 | -------------------------------------------------------------------------------- /BayesianTools/tests/testthat/test-getSample.R: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /BayesianTools/.gitignore: -------------------------------------------------------------------------------- 1 | .Rproj.user 2 | .Rhistory 3 | .RData 4 | -------------------------------------------------------------------------------- /Examples/ParticleMCMC/Untitled.R: -------------------------------------------------------------------------------- 1 | # particle MCMC with BT 2 | 3 | -------------------------------------------------------------------------------- /Development/data.R: -------------------------------------------------------------------------------- 1 | #' Example MCMC output 2 | #' 3 | #"mcmcOutput" 4 | -------------------------------------------------------------------------------- /Publications/readme.md: -------------------------------------------------------------------------------- 1 | # Core folder for publications using the BT package 2 | 3 | -------------------------------------------------------------------------------- /BayesianTools/inst/examples/testLinearModel.R: -------------------------------------------------------------------------------- 1 | x = c(1,2) 2 | y = testLinearModel(x) 3 | plot(y) 4 | -------------------------------------------------------------------------------- /docs/reference/AM.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/AM.html -------------------------------------------------------------------------------- /docs/reference/DE.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/DE.html -------------------------------------------------------------------------------- /docs/reference/DR.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/DR.html -------------------------------------------------------------------------------- /docs/reference/M.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/M.html -------------------------------------------------------------------------------- /docs/reference/DEzs.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/DEzs.html -------------------------------------------------------------------------------- /docs/reference/DIC.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/DIC.html -------------------------------------------------------------------------------- /docs/reference/DRAM.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/DRAM.html -------------------------------------------------------------------------------- /docs/reference/DREAM.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/DREAM.html -------------------------------------------------------------------------------- /docs/reference/GOF-5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/GOF-5.png -------------------------------------------------------------------------------- /docs/reference/GOF.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/GOF.html -------------------------------------------------------------------------------- /docs/reference/MAP.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/MAP.html -------------------------------------------------------------------------------- /docs/reference/Twalk.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/Twalk.html -------------------------------------------------------------------------------- /docs/reference/VSEM-9.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/VSEM-9.png -------------------------------------------------------------------------------- /docs/reference/VSEM.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/VSEM.html -------------------------------------------------------------------------------- /docs/reference/WAIC.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/WAIC.html -------------------------------------------------------------------------------- /docs/reference/vsemC.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/vsemC.html -------------------------------------------------------------------------------- /docs/reference/DREAMzs.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/DREAMzs.html -------------------------------------------------------------------------------- /docs/reference/VSEM-10.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/VSEM-10.png -------------------------------------------------------------------------------- /docs/reference/rescale.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/rescale.html -------------------------------------------------------------------------------- /docs/reference/runMCMC.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/runMCMC.html -------------------------------------------------------------------------------- /docs/reference/Metropolis.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/Metropolis.html -------------------------------------------------------------------------------- /docs/reference/getPanels.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/getPanels.html -------------------------------------------------------------------------------- /docs/reference/getSample-5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/getSample-5.png -------------------------------------------------------------------------------- /docs/reference/getSample.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/getSample.html -------------------------------------------------------------------------------- /docs/reference/getVolume.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/getVolume.html -------------------------------------------------------------------------------- /docs/reference/logSumExp.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/logSumExp.html -------------------------------------------------------------------------------- /docs/reference/plotHist.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/plotHist.html -------------------------------------------------------------------------------- /docs/reference/runMCMC-13.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/runMCMC-13.png -------------------------------------------------------------------------------- /docs/reference/runMCMC-14.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/runMCMC-14.png -------------------------------------------------------------------------------- /docs/reference/runMCMC-15.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/runMCMC-15.png -------------------------------------------------------------------------------- /docs/reference/smcSampler.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/smcSampler.html -------------------------------------------------------------------------------- /docs/reference/tracePlot-9.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/tracePlot-9.png -------------------------------------------------------------------------------- /docs/reference/tracePlot.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/tracePlot.html -------------------------------------------------------------------------------- /docs/reference/violinPlot.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/violinPlot.html -------------------------------------------------------------------------------- /docs/reference/bridgesample.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/bridgesample.html -------------------------------------------------------------------------------- /docs/reference/convertCoda.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/convertCoda.html -------------------------------------------------------------------------------- /docs/reference/correctThin.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/correctThin.html -------------------------------------------------------------------------------- /docs/reference/createPrior.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/createPrior.html -------------------------------------------------------------------------------- /docs/reference/histMarginal.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/histMarginal.html -------------------------------------------------------------------------------- /docs/reference/marginalPlot.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/marginalPlot.html -------------------------------------------------------------------------------- /docs/reference/smcSampler-73.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/smcSampler-73.png -------------------------------------------------------------------------------- /docs/reference/smcSampler-74.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/smcSampler-74.png -------------------------------------------------------------------------------- /docs/reference/smcSampler-75.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/smcSampler-75.png -------------------------------------------------------------------------------- /docs/reference/smcSampler-76.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/smcSampler-76.png -------------------------------------------------------------------------------- /docs/reference/smcSampler-77.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/smcSampler-77.png -------------------------------------------------------------------------------- /docs/reference/smcSampler-78.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/smcSampler-78.png -------------------------------------------------------------------------------- /docs/reference/smcSampler-79.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/smcSampler-79.png -------------------------------------------------------------------------------- /docs/reference/smcSampler-80.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/smcSampler-80.png -------------------------------------------------------------------------------- /docs/reference/smcSampler-81.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/smcSampler-81.png -------------------------------------------------------------------------------- /docs/reference/smcSampler-82.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/smcSampler-82.png -------------------------------------------------------------------------------- /docs/reference/smcSampler-83.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/smcSampler-83.png -------------------------------------------------------------------------------- /docs/reference/smcSampler-84.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/smcSampler-84.png -------------------------------------------------------------------------------- /docs/reference/smcSampler-85.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/smcSampler-85.png -------------------------------------------------------------------------------- /docs/reference/smcSampler-86.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/smcSampler-86.png -------------------------------------------------------------------------------- /docs/reference/smcSampler-87.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/smcSampler-87.png -------------------------------------------------------------------------------- /docs/reference/smcSampler-88.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/smcSampler-88.png -------------------------------------------------------------------------------- /docs/reference/smcSampler-89.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/smcSampler-89.png -------------------------------------------------------------------------------- /docs/reference/smcSampler-90.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/smcSampler-90.png -------------------------------------------------------------------------------- /docs/reference/stopParallel.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/stopParallel.html -------------------------------------------------------------------------------- /docs/reference/tracePlot-10.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/tracePlot-10.png -------------------------------------------------------------------------------- /docs/reference/BayesianTools.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/BayesianTools.html -------------------------------------------------------------------------------- /docs/reference/VSEMcreatePAR.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/VSEMcreatePAR.html -------------------------------------------------------------------------------- /docs/reference/VSEMgetDefaults.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/VSEMgetDefaults.html -------------------------------------------------------------------------------- /docs/reference/correlationPlot.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/correlationPlot.html -------------------------------------------------------------------------------- /docs/reference/createBetaPrior.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/createBetaPrior.html -------------------------------------------------------------------------------- /docs/reference/createBreakMat.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/createBreakMat.html -------------------------------------------------------------------------------- /docs/reference/createPosterior.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/createPosterior.html -------------------------------------------------------------------------------- /docs/reference/likelihoodAR1.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/likelihoodAR1.html -------------------------------------------------------------------------------- /docs/reference/marginalPlot-5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/marginalPlot-5.png -------------------------------------------------------------------------------- /docs/reference/metropolisRatio.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/metropolisRatio.html -------------------------------------------------------------------------------- /docs/reference/plotSensitivity.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/plotSensitivity.html -------------------------------------------------------------------------------- /docs/reference/plotTimeSeries-5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/plotTimeSeries-5.png -------------------------------------------------------------------------------- /docs/reference/plotTimeSeries.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/plotTimeSeries.html -------------------------------------------------------------------------------- /docs/reference/testLinearModel.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/testLinearModel.html -------------------------------------------------------------------------------- /docs/reference/correlationPlot-6.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/correlationPlot-6.png -------------------------------------------------------------------------------- /docs/reference/createLikelihood.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/createLikelihood.html -------------------------------------------------------------------------------- /docs/reference/gelmanDiagnostics.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/gelmanDiagnostics.html -------------------------------------------------------------------------------- /docs/reference/sampleMetropolis.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/sampleMetropolis.html -------------------------------------------------------------------------------- /docs/reference/testDensityBanana.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/testDensityBanana.html -------------------------------------------------------------------------------- /docs/reference/testDensityNormal.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/testDensityNormal.html -------------------------------------------------------------------------------- /docs/reference/testLinearModel-5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/testLinearModel-5.png -------------------------------------------------------------------------------- /BayesianTools/vignettes/betaDensity.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/BayesianTools/vignettes/betaDensity.png -------------------------------------------------------------------------------- /docs/reference/VSEMcreateLikelihood.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/VSEMcreateLikelihood.html -------------------------------------------------------------------------------- /docs/reference/applySettingsDefault.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/applySettingsDefault.html -------------------------------------------------------------------------------- /docs/reference/checkBayesianSetup.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/checkBayesianSetup.html -------------------------------------------------------------------------------- /docs/reference/createBayesianSetup.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/createBayesianSetup.html -------------------------------------------------------------------------------- /docs/reference/createPriorDensity.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/createPriorDensity.html -------------------------------------------------------------------------------- /docs/reference/createSmcSamplerList.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/createSmcSamplerList.html -------------------------------------------------------------------------------- /docs/reference/createUniformPrior.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/createUniformPrior.html -------------------------------------------------------------------------------- /docs/reference/getCredibleIntervals.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/getCredibleIntervals.html -------------------------------------------------------------------------------- /docs/reference/getDharmaResiduals.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/getDharmaResiduals.html -------------------------------------------------------------------------------- /docs/reference/likelihoodIidNormal.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/likelihoodIidNormal.html -------------------------------------------------------------------------------- /docs/reference/marginalLikelihood-10.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/marginalLikelihood-10.png -------------------------------------------------------------------------------- /docs/reference/marginalLikelihood-9.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/marginalLikelihood-9.png -------------------------------------------------------------------------------- /docs/reference/marginalLikelihood.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/marginalLikelihood.html -------------------------------------------------------------------------------- /docs/reference/mcmcMultipleChains.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/mcmcMultipleChains.html -------------------------------------------------------------------------------- /docs/reference/package-deprecated.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/package-deprecated.html -------------------------------------------------------------------------------- /docs/reference/sampleEquallySpaced.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/sampleEquallySpaced.html -------------------------------------------------------------------------------- /docs/reference/setupStartProposal.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/setupStartProposal.html -------------------------------------------------------------------------------- /docs/reference/testDensityInfinity.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/testDensityInfinity.html -------------------------------------------------------------------------------- /BayesianTools/man/figures/betaDensity.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/BayesianTools/man/figures/betaDensity.png -------------------------------------------------------------------------------- /BayesianTools/vignettes/normalDensity.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/BayesianTools/vignettes/normalDensity.png -------------------------------------------------------------------------------- /BayesianTools/vignettes/uniformDensity.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/BayesianTools/vignettes/uniformDensity.png -------------------------------------------------------------------------------- /docs/reference/createMcmcSamplerList.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/createMcmcSamplerList.html -------------------------------------------------------------------------------- /docs/reference/getPredictiveIntervals.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/getPredictiveIntervals.html -------------------------------------------------------------------------------- /docs/reference/plotTimeSeriesResults.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/plotTimeSeriesResults.html -------------------------------------------------------------------------------- /docs/reference/testDensityMultiNormal.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/testDensityMultiNormal.html -------------------------------------------------------------------------------- /BayesianTools/man/figures/normalDensity.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/BayesianTools/man/figures/normalDensity.png -------------------------------------------------------------------------------- /BayesianTools/man/figures/uniformDensity.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/BayesianTools/man/figures/uniformDensity.png -------------------------------------------------------------------------------- /BayesianTools/tests/testthat.R: -------------------------------------------------------------------------------- 1 | Sys.setenv("R_TESTS" = "") 2 | 3 | library(BayesianTools) 4 | library(testthat) 5 | 6 | test_check("BayesianTools") 7 | -------------------------------------------------------------------------------- /docs/reference/createProposalGenerator-21.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/createProposalGenerator-21.png -------------------------------------------------------------------------------- /docs/reference/createProposalGenerator-22.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/createProposalGenerator-22.png -------------------------------------------------------------------------------- /docs/reference/createProposalGenerator-23.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/createProposalGenerator-23.png -------------------------------------------------------------------------------- /docs/reference/createProposalGenerator-24.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/createProposalGenerator-24.png -------------------------------------------------------------------------------- /docs/reference/createProposalGenerator-25.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/createProposalGenerator-25.png -------------------------------------------------------------------------------- /docs/reference/createProposalGenerator.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/createProposalGenerator.html -------------------------------------------------------------------------------- /docs/reference/generateParallelExecuter.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/generateParallelExecuter.html -------------------------------------------------------------------------------- /docs/reference/getPossibleSamplerTypes.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/getPossibleSamplerTypes.html -------------------------------------------------------------------------------- /docs/reference/getPredictiveDistribution.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/getPredictiveDistribution.html -------------------------------------------------------------------------------- /docs/reference/plotTimeSeriesResiduals.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/plotTimeSeriesResiduals.html -------------------------------------------------------------------------------- /docs/reference/updateProposalGenerator.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/updateProposalGenerator.html -------------------------------------------------------------------------------- /Development/manualTests/Defaults/defaults.Rdata: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/Development/manualTests/Defaults/defaults.Rdata -------------------------------------------------------------------------------- /docs/reference/createTruncatedNormalPrior.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/createTruncatedNormalPrior.html -------------------------------------------------------------------------------- /docs/reference/generateTestDensityMultiNormal.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/generateTestDensityMultiNormal.html -------------------------------------------------------------------------------- /docs/reference/getMetropolisDefaultSettings.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/getMetropolisDefaultSettings.html -------------------------------------------------------------------------------- /docs/reference/generateTestDensityMultiNormal-10.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/generateTestDensityMultiNormal-10.png -------------------------------------------------------------------------------- /docs/reference/generateTestDensityMultiNormal-9.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/reference/generateTestDensityMultiNormal-9.png -------------------------------------------------------------------------------- /BayesianTools/.Rbuildignore: -------------------------------------------------------------------------------- 1 | C:/Users/Tankr_000/Documents/GitHub/BayesianTools/docs$ 2 | _pkgdown\.yml$ 3 | ^CRAN.md 4 | tests/testthat/Rplots.pdf 5 | vignettes/*.R 6 | vignettes/*.html -------------------------------------------------------------------------------- /BayesianTools/R/importPackages.R: -------------------------------------------------------------------------------- 1 | #' @import graphics 2 | #' @import stats 3 | #' @import DHARMa 4 | #' @import bridgesampling 5 | #' @importFrom utils flush.console methods modifyList 6 | NULL -------------------------------------------------------------------------------- /BayesianTools/inst/examples/GOF.R: -------------------------------------------------------------------------------- 1 | 2 | x = runif(500,-1,1) 3 | y = 0.2 + 0.9 *x + rnorm(500, sd = 0.5) 4 | 5 | summary(lm(y ~ x)) 6 | 7 | GOF(x,y) 8 | 9 | GOF(x,y, plot = TRUE) 10 | -------------------------------------------------------------------------------- /Examples/RandomEffectsModel_files/figure-html/unnamed-chunk-2-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/Examples/RandomEffectsModel_files/figure-html/unnamed-chunk-2-1.png -------------------------------------------------------------------------------- /Examples/RandomEffectsModel_files/figure-html/unnamed-chunk-3-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/Examples/RandomEffectsModel_files/figure-html/unnamed-chunk-3-1.png -------------------------------------------------------------------------------- /Examples/RandomEffectsModel_files/figure-html/unnamed-chunk-4-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/Examples/RandomEffectsModel_files/figure-html/unnamed-chunk-4-1.png -------------------------------------------------------------------------------- /Examples/RandomEffectsModel_files/figure-html/unnamed-chunk-6-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/Examples/RandomEffectsModel_files/figure-html/unnamed-chunk-6-1.png -------------------------------------------------------------------------------- /Examples/RandomEffectsModel_files/figure-html/unnamed-chunk-7-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/Examples/RandomEffectsModel_files/figure-html/unnamed-chunk-7-1.png -------------------------------------------------------------------------------- /docs/articles/BayesianTools_files/figure-html/unnamed-chunk-9-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/articles/BayesianTools_files/figure-html/unnamed-chunk-9-1.png -------------------------------------------------------------------------------- /docs/articles/BayesianTools_files/figure-html/unnamed-chunk-9-2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/articles/BayesianTools_files/figure-html/unnamed-chunk-9-2.png -------------------------------------------------------------------------------- /docs/articles/BayesianTools_files/figure-html/unnamed-chunk-9-3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/articles/BayesianTools_files/figure-html/unnamed-chunk-9-3.png -------------------------------------------------------------------------------- /docs/articles/BayesianTools_files/figure-html/unnamed-chunk-14-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/articles/BayesianTools_files/figure-html/unnamed-chunk-14-1.png -------------------------------------------------------------------------------- /docs/articles/BayesianTools_files/figure-html/unnamed-chunk-15-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/articles/BayesianTools_files/figure-html/unnamed-chunk-15-1.png -------------------------------------------------------------------------------- /docs/articles/BayesianTools_files/figure-html/unnamed-chunk-20-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/articles/BayesianTools_files/figure-html/unnamed-chunk-20-1.png -------------------------------------------------------------------------------- /docs/articles/BayesianTools_files/figure-html/unnamed-chunk-20-2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/articles/BayesianTools_files/figure-html/unnamed-chunk-20-2.png -------------------------------------------------------------------------------- /docs/articles/BayesianTools_files/figure-html/unnamed-chunk-20-3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/articles/BayesianTools_files/figure-html/unnamed-chunk-20-3.png -------------------------------------------------------------------------------- /docs/articles/BayesianTools_files/figure-html/unnamed-chunk-20-4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/articles/BayesianTools_files/figure-html/unnamed-chunk-20-4.png -------------------------------------------------------------------------------- /docs/articles/BayesianTools_files/figure-html/unnamed-chunk-35-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/articles/BayesianTools_files/figure-html/unnamed-chunk-35-1.png -------------------------------------------------------------------------------- /docs/articles/BayesianTools_files/figure-html/unnamed-chunk-38-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/docs/articles/BayesianTools_files/figure-html/unnamed-chunk-38-1.png -------------------------------------------------------------------------------- /BayesianTools/inst/examples/plotSensitivityHelp.R: -------------------------------------------------------------------------------- 1 | 2 | ll <- testDensityBanana 3 | bayesianSetup <- createBayesianSetup(likelihood = ll, lower = rep(-10, 2), upper = rep(10, 2)) 4 | 5 | plotSensitivity(bayesianSetup) 6 | -------------------------------------------------------------------------------- /Development/vignette/Test.Rnw: -------------------------------------------------------------------------------- 1 | %\VignetteEngine{knitr::knitr} 2 | %\VignetteEncoding{UTF-8} t 3 | %\VignetteIndexEntry{test}. 4 | 5 | \documentclass{article} 6 | 7 | \begin{document} 8 | 9 | asdf 10 | 11 | 12 | \end{document} -------------------------------------------------------------------------------- /Publications/SpeichEtAl-SMCForModelCalibration/readme_files/figure-html/unnamed-chunk-3-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/Publications/SpeichEtAl-SMCForModelCalibration/readme_files/figure-html/unnamed-chunk-3-1.png -------------------------------------------------------------------------------- /BayesianTools/inst/examples/generateParallelExecuter.R: -------------------------------------------------------------------------------- 1 | 2 | testDensityMultiNormal <- generateTestDensityMultiNormal() 3 | 4 | 5 | parDen <- generateParallelExecuter(testDensityMultiNormal)$parallelFun 6 | x = matrix(runif(9,0,1), nrow = 3) 7 | parDen(x) 8 | 9 | -------------------------------------------------------------------------------- /Examples/install.R: -------------------------------------------------------------------------------- 1 | library(devtools) 2 | install_url("https://dl.dropboxusercontent.com/s/ccvpnvblf3vzuvs/BayesianTools_0.0.0.9000.tar.gz", dependencies = T) 3 | 4 | library(BayesianTools) 5 | ?BayesianTools 6 | vignette("AQuickStart", package = "BayesianTools") 7 | 8 | -------------------------------------------------------------------------------- /Publications/SpeichEtAl-SMCForModelCalibration/6_prior_posterior_plots/readme_files/figure-html/unnamed-chunk-6-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/Publications/SpeichEtAl-SMCForModelCalibration/6_prior_posterior_plots/readme_files/figure-html/unnamed-chunk-6-1.png -------------------------------------------------------------------------------- /Publications/SpeichEtAl-SMCForModelCalibration/6_prior_posterior_plots/readme_files/figure-html/unnamed-chunk-7-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/Publications/SpeichEtAl-SMCForModelCalibration/6_prior_posterior_plots/readme_files/figure-html/unnamed-chunk-7-1.png -------------------------------------------------------------------------------- /Publications/SpeichEtAl-SMCForModelCalibration/6_prior_posterior_plots/readme_files/figure-html/unnamed-chunk-8-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/Publications/SpeichEtAl-SMCForModelCalibration/6_prior_posterior_plots/readme_files/figure-html/unnamed-chunk-8-1.png -------------------------------------------------------------------------------- /Publications/SpeichEtAl-SMCForModelCalibration/6_prior_posterior_plots/readme_files/figure-html/unnamed-chunk-9-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/Publications/SpeichEtAl-SMCForModelCalibration/6_prior_posterior_plots/readme_files/figure-html/unnamed-chunk-9-1.png -------------------------------------------------------------------------------- /Publications/SpeichEtAl-SMCForModelCalibration/6_prior_posterior_plots/readme_files/figure-html/unnamed-chunk-10-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/Publications/SpeichEtAl-SMCForModelCalibration/6_prior_posterior_plots/readme_files/figure-html/unnamed-chunk-10-1.png -------------------------------------------------------------------------------- /Publications/SpeichEtAl-SMCForModelCalibration/6_prior_posterior_plots/readme_files/figure-html/unnamed-chunk-11-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/florianhartig/BayesianTools/HEAD/Publications/SpeichEtAl-SMCForModelCalibration/6_prior_posterior_plots/readme_files/figure-html/unnamed-chunk-11-1.png -------------------------------------------------------------------------------- /BayesianTools/inst/examples/generateTestDensityMultiNormalHelp.R: -------------------------------------------------------------------------------- 1 | # sampling from the test function 2 | x = generateTestDensityMultiNormal(sample = TRUE, n = 1000)(1000) 3 | correlationPlot(x) 4 | marginalPlot(x) 5 | 6 | # generating the the density 7 | density = generateTestDensityMultiNormal(sample = FALSE) 8 | density(x[1,]) 9 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | before_install: 2 | - cd BayesianTools 3 | 4 | 5 | language: r 6 | r: 7 | - release 8 | 9 | cache: packages 10 | 11 | # Install nlopt package to help nloptr install 12 | # glpk-utils and libglpk-dev are needed because of DHARMa #166 13 | addons: 14 | apt: 15 | packages: 16 | - libnlopt-dev 17 | - glpk-utils 18 | - libglpk-dev 19 | -------------------------------------------------------------------------------- /BayesianTools/man/VSEMgetDefaults.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/VSEM.R 3 | \name{VSEMgetDefaults} 4 | \alias{VSEMgetDefaults} 5 | \title{returns the default values for the VSEM} 6 | \usage{ 7 | VSEMgetDefaults() 8 | } 9 | \value{ 10 | a data.frame 11 | } 12 | \description{ 13 | returns the default values for the VSEM 14 | } 15 | -------------------------------------------------------------------------------- /BayesianTools/man/getPossibleSamplerTypes.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/mcmcRun.R 3 | \name{getPossibleSamplerTypes} 4 | \alias{getPossibleSamplerTypes} 5 | \title{Returns possible sampler types} 6 | \usage{ 7 | getPossibleSamplerTypes() 8 | } 9 | \description{ 10 | Returns possible sampler types 11 | } 12 | \author{ 13 | Florian Hartig 14 | } 15 | -------------------------------------------------------------------------------- /BayesianTools/man/sumSquare.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/mcmcTwalk_helperFunctions.R 3 | \name{sumSquare} 4 | \alias{sumSquare} 5 | \title{Helper function for sum of x*x} 6 | \usage{ 7 | sumSquare(x) 8 | } 9 | \arguments{ 10 | \item{x}{vector of values} 11 | } 12 | \description{ 13 | Helper function for sum of x*x 14 | } 15 | \keyword{internal} 16 | -------------------------------------------------------------------------------- /BayesianTools/R/RcppExports.R: -------------------------------------------------------------------------------- 1 | # Generated by using Rcpp::compileAttributes() -> do not edit by hand 2 | # Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 3 | 4 | #' C version of the VSEM model 5 | #' @param par parameter vector 6 | #' @param PAR Photosynthetically active radiation (PAR) MJ /m2 /day 7 | #' @export 8 | vsemC <- function(par, PAR) { 9 | .Call(`_BayesianTools_vsemC`, par, PAR) 10 | } 11 | 12 | -------------------------------------------------------------------------------- /BayesianTools/inst/examples/plotTimeSeriesHelp.R: -------------------------------------------------------------------------------- 1 | # Create time series 2 | ts <- VSEMcreatePAR(1:100) 3 | 4 | # create fake "predictions" 5 | pred <- ts + rnorm(length(ts), mean = 0, sd = 2) 6 | 7 | # plot time series 8 | par(mfrow=c(1,2)) 9 | 10 | plotTimeSeries(observed = ts, main="Observed") 11 | plotTimeSeries(observed = ts, predicted = pred, main = "Observed and predicted") 12 | 13 | par(mfrow=c(1,1)) 14 | 15 | -------------------------------------------------------------------------------- /BayesianTools/man/betaFun.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/mcmcTwalk_helperFunctions.R 3 | \name{betaFun} 4 | \alias{betaFun} 5 | \title{Helper function for calculating beta} 6 | \usage{ 7 | betaFun(at) 8 | } 9 | \arguments{ 10 | \item{at}{"traverse" move proposal parameter.} 11 | } 12 | \description{ 13 | Helper function for calculating beta 14 | } 15 | \keyword{internal} 16 | -------------------------------------------------------------------------------- /BayesianTools/man/vsemC.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/RcppExports.R 3 | \name{vsemC} 4 | \alias{vsemC} 5 | \title{C version of the VSEM model} 6 | \usage{ 7 | vsemC(par, PAR) 8 | } 9 | \arguments{ 10 | \item{par}{parameter vector} 11 | 12 | \item{PAR}{Photosynthetically active radiation (PAR) MJ /m2 /day} 13 | } 14 | \description{ 15 | C version of the VSEM model 16 | } 17 | -------------------------------------------------------------------------------- /BayesianTools/R/benchmark.R: -------------------------------------------------------------------------------- 1 | # runBenchmark <- function(bayesianSetup, starvalues, particles){ 2 | # 3 | # 4 | # # MCMC 5 | # testSampler <- mcmcSampler(bayesianSetup = bayesianSetup, startvalue = c(1,1,0), optimize = T) 6 | # testSampler2 <- getSamples(testSampler, 10000, DRlevels =2) 7 | # plot(testSampler2) 8 | # 9 | # 10 | # 11 | # 12 | # smcSampler 13 | # 14 | # 15 | # 16 | # 17 | # 18 | # } -------------------------------------------------------------------------------- /BayesianTools/man/factorMatrice.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/proposalGenerator.R 3 | \name{factorMatrice} 4 | \alias{factorMatrice} 5 | \title{factorMatrice} 6 | \usage{ 7 | factorMatrice(sigma, method) 8 | } 9 | \arguments{ 10 | \item{sigma}{sigma} 11 | 12 | \item{method}{either "eigen", "svd" or "chol"} 13 | } 14 | \description{ 15 | factorMatrice 16 | } 17 | \keyword{internal} 18 | -------------------------------------------------------------------------------- /BayesianTools/man/getPanels.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/utils.R 3 | \name{getPanels} 4 | \alias{getPanels} 5 | \title{getPanels} 6 | \usage{ 7 | getPanels(x) 8 | } 9 | \arguments{ 10 | \item{x}{the desired number of panels} 11 | } 12 | \description{ 13 | Calculates the argument x for par(mfrow = x) for a desired number of panels 14 | } 15 | \author{ 16 | Florian Hartig 17 | } 18 | -------------------------------------------------------------------------------- /BayesianTools/man/getRmvnorm.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/proposalGenerator.R 3 | \name{getRmvnorm} 4 | \alias{getRmvnorm} 5 | \title{Produce multivariate normal proposal} 6 | \usage{ 7 | getRmvnorm(n = 1, R) 8 | } 9 | \arguments{ 10 | \item{n}{n} 11 | 12 | \item{R}{R} 13 | } 14 | \value{ 15 | X 16 | } 17 | \description{ 18 | Produce multivariate normal proposal 19 | } 20 | \keyword{internal} 21 | -------------------------------------------------------------------------------- /BayesianTools/man/thinMatrix.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/utils.R 3 | \name{thinMatrix} 4 | \alias{thinMatrix} 5 | \title{Function to thin matrices} 6 | \usage{ 7 | thinMatrix(mat, thin = "auto") 8 | } 9 | \arguments{ 10 | \item{mat}{matrix to thin} 11 | 12 | \item{thin}{thinning parameter} 13 | } 14 | \value{ 15 | thinned matrix 16 | } 17 | \description{ 18 | Function to thin matrices 19 | } 20 | \keyword{internal} 21 | -------------------------------------------------------------------------------- /BayesianTools/inst/examples/plotDiagnosticHelp.R: -------------------------------------------------------------------------------- 1 | \dontrun{ 2 | 3 | # Create bayesian setup with 4 | bayesianSetup <- createBayesianSetup(likelihood = testDensityNormal, 5 | prior = createUniformPrior(lower = -10, 6 | upper = 10)) 7 | # running MCMC 8 | out = runMCMC(bayesianSetup = bayesianSetup) 9 | 10 | # diagnostic plots 11 | plotDiagnostic(out) 12 | } 13 | -------------------------------------------------------------------------------- /BayesianTools/man/getSetup.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/utils.R 3 | \name{getSetup} 4 | \alias{getSetup} 5 | \title{Function to get the setup from a bayesianOutput} 6 | \usage{ 7 | getSetup(x) 8 | } 9 | \arguments{ 10 | \item{x}{bayesianOutput} 11 | } 12 | \value{ 13 | bayesianSetup 14 | } 15 | \description{ 16 | Function to get the setup from a bayesianOutput 17 | } 18 | \author{ 19 | Tankred Ott 20 | } 21 | \keyword{internal} 22 | -------------------------------------------------------------------------------- /BayesianTools/man/stopParallel.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/classBayesianSetup.R 3 | \name{stopParallel} 4 | \alias{stopParallel} 5 | \title{Function to close cluster in BayesianSetup} 6 | \usage{ 7 | stopParallel(bayesianSetup) 8 | } 9 | \arguments{ 10 | \item{bayesianSetup}{object of class BayesianSetup} 11 | } 12 | \description{ 13 | Function closes 14 | the parallel executer (if available) 15 | } 16 | \author{ 17 | Stefan Paul 18 | } 19 | -------------------------------------------------------------------------------- /BayesianTools.Rproj: -------------------------------------------------------------------------------- 1 | Version: 1.0 2 | 3 | RestoreWorkspace: Default 4 | SaveWorkspace: Default 5 | AlwaysSaveHistory: Default 6 | 7 | EnableCodeIndexing: Yes 8 | UseSpacesForTab: Yes 9 | NumSpacesForTab: 2 10 | Encoding: UTF-8 11 | 12 | RnwWeave: knitr 13 | LaTeX: pdfLaTeX 14 | 15 | BuildType: Package 16 | PackageUseDevtools: Yes 17 | PackagePath: BayesianTools 18 | PackageInstallArgs: --no-multiarch --with-keep.source 19 | PackageCheckArgs: --as-cran 20 | PackageRoxygenize: rd,collate,namespace 21 | -------------------------------------------------------------------------------- /BayesianTools/man/VSEMcreatePAR.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/VSEM.R 3 | \name{VSEMcreatePAR} 4 | \alias{VSEMcreatePAR} 5 | \title{Create a random radiation (PAR) time series} 6 | \usage{ 7 | VSEMcreatePAR(days = 1:(3 * 365)) 8 | } 9 | \arguments{ 10 | \item{days}{days to calculate the PAR for} 11 | } 12 | \description{ 13 | Create a random radiation (PAR) time series 14 | } 15 | \author{ 16 | David Cameron, R implementation by Florian Hartig 17 | } 18 | -------------------------------------------------------------------------------- /BayesianTools/man/getBlockSettings.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/blockUpdate.R 3 | \name{getBlockSettings} 4 | \alias{getBlockSettings} 5 | \title{getblockSettings} 6 | \usage{ 7 | getBlockSettings(blockUpdate) 8 | } 9 | \arguments{ 10 | \item{blockUpdate}{input settings} 11 | } 12 | \value{ 13 | list with block settings 14 | } 15 | \description{ 16 | Transforms the original settings in settings used in the model runs 17 | } 18 | \keyword{internal} 19 | -------------------------------------------------------------------------------- /BayesianTools/man/scaleMatrix.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/utils.R 3 | \name{scaleMatrix} 4 | \alias{scaleMatrix} 5 | \title{Function to scale matrices} 6 | \usage{ 7 | scaleMatrix(mat, min, max) 8 | } 9 | \arguments{ 10 | \item{mat}{matrix to scale} 11 | 12 | \item{min}{minimum value} 13 | 14 | \item{max}{maximum value} 15 | } 16 | \value{ 17 | sclaed matrix 18 | } 19 | \description{ 20 | Function to scale matrices 21 | } 22 | \keyword{internal} 23 | -------------------------------------------------------------------------------- /BayesianTools/man/testDensityNormal.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/testFunctions.R 3 | \name{testDensityNormal} 4 | \alias{testDensityNormal} 5 | \title{Normal likelihood} 6 | \usage{ 7 | testDensityNormal(x, sum = T) 8 | } 9 | \arguments{ 10 | \item{x}{a parameter vector of arbitrary length} 11 | 12 | \item{sum}{if likelihood should be summed or not} 13 | } 14 | \description{ 15 | Normal likelihood 16 | } 17 | \author{ 18 | Florian Hartig 19 | } 20 | -------------------------------------------------------------------------------- /BayesianTools/man/getBlock.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/blockUpdate.R 3 | \name{getBlock} 4 | \alias{getBlock} 5 | \title{Determine the parameters in the block update} 6 | \usage{ 7 | getBlock(blockSettings) 8 | } 9 | \arguments{ 10 | \item{blockSettings}{settings for block update} 11 | } 12 | \value{ 13 | vector containing the parameter to be updated 14 | } 15 | \description{ 16 | Determine the parameters in the block update 17 | } 18 | \keyword{internal} 19 | -------------------------------------------------------------------------------- /Development/CreateData.R: -------------------------------------------------------------------------------- 1 | # ensure WD is BayesianTools package 2 | 3 | library(BayesianTools) 4 | library(devtools) 5 | library(usethis) 6 | 7 | use_data_raw() 8 | 9 | ll <- generateTestDensityMultiNormal(sigma = "no correlation") 10 | bayesianSetup = createBayesianSetup(likelihood = ll, lower = rep(-10, 3), upper = rep(10, 3)) 11 | settings = list(iterations = 10000, nrChains = 3) 12 | mcmcOutput <- runMCMC(bayesianSetup = bayesianSetup, sampler = "DEzs", settings = settings) 13 | use_data(mcmcOutput, overwrite = TRUE, name = "mcmcRun", internal = T) 14 | -------------------------------------------------------------------------------- /Examples/Old/BT-MCMC-Auto-Demo.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: "BT-MCMC-Automatic-Demo" 3 | author: "Florian Hartig" 4 | date: "9 Jan 2016" 5 | output: html_document 6 | --- 7 | 8 | 9 | 10 | 11 | ```{r} 12 | 13 | 14 | testAutomatic <- automaticMCMC(likelihood = testDensityMultiNormal, prior = NULL, startvalues = list(c(1,3,0), c(1,3,0), c(1,3,0)), maxiter = 10000) 15 | 16 | class(testAutomatic) 17 | 18 | summary(testAutomatic) 19 | plot(testAutomatic) 20 | densityPlot(testAutomatic) 21 | 22 | rejectionRate(testAutomatic$mcmclist) 23 | 24 | 25 | ``` 26 | 27 | 28 | -------------------------------------------------------------------------------- /BayesianTools/man/testDensityMultiNormal.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/testFunctions.R 3 | \name{testDensityMultiNormal} 4 | \alias{testDensityMultiNormal} 5 | \title{3d Mutivariate Normal likelihood} 6 | \usage{ 7 | testDensityMultiNormal(x, sigma = "strongcorrelation") 8 | } 9 | \arguments{ 10 | \item{x}{a parameter vector of arbitrary length} 11 | 12 | \item{sigma}{either a correlation matrix, or "strongcorrelation", or "no correlation"} 13 | } 14 | \description{ 15 | 3d Mutivariate Normal likelihood 16 | } 17 | -------------------------------------------------------------------------------- /BayesianTools/tests/testthat/test-utils-Numerics.R: -------------------------------------------------------------------------------- 1 | context("Utils Numerics work") 2 | 3 | skip_on_cran() 4 | 5 | test_that("logSumExp", { 6 | 7 | x = rep(log(1),10) 8 | expect_equal(exp(BayesianTools:::logSumExp(x)), 10) 9 | expect_equal(exp(BayesianTools:::logSumExp(x,mean = T)), 1) 10 | 11 | x = c(rep(log(1),9), -Inf) 12 | expect_equal(exp(BayesianTools:::logSumExp(x)), 9) 13 | expect_equal(exp(BayesianTools:::logSumExp(x, mean = T)), 9/10) 14 | 15 | x = rep(-100, 100) 16 | expect_equal(log(sum(exp(x))), BayesianTools:::logSumExp(x)) 17 | 18 | }) 19 | 20 | -------------------------------------------------------------------------------- /BayesianTools/man/plotTimeSeriesResiduals.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/plotTimeSeries.R 3 | \name{plotTimeSeriesResiduals} 4 | \alias{plotTimeSeriesResiduals} 5 | \title{Plots residuals of a time series} 6 | \usage{ 7 | plotTimeSeriesResiduals(residuals, x = NULL, main = "residuals") 8 | } 9 | \arguments{ 10 | \item{residuals}{x} 11 | 12 | \item{x}{optional values for x axis (time)} 13 | 14 | \item{main}{title of the plot} 15 | } 16 | \description{ 17 | Plots residuals of a time series 18 | } 19 | \author{ 20 | Florian Hartig 21 | } 22 | -------------------------------------------------------------------------------- /BayesianTools/man/metropolisRatio.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/utils.R 3 | \name{metropolisRatio} 4 | \alias{metropolisRatio} 5 | \title{Function to calculate the metropolis ratio} 6 | \usage{ 7 | metropolisRatio(LP2, LP1, tempering = 1) 8 | } 9 | \arguments{ 10 | \item{LP2}{log posterior old position} 11 | 12 | \item{LP1}{log posterior of proposal} 13 | 14 | \item{tempering}{value for tempering} 15 | } 16 | \description{ 17 | Function to calculate the metropolis ratio 18 | } 19 | \author{ 20 | Florian Hartig 21 | } 22 | \keyword{internal} 23 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Set the default behavior, in case people don't have core.autocrlf set. 2 | * text=auto 3 | 4 | # Explicitly declare text files you want to always be normalized and converted 5 | # to native line endings on checkout. 6 | *.Rd text 7 | *.Rmd text 8 | *.R text 9 | *.r text 10 | *.Rproj text 11 | *.[Rr]md linguist-detectable 12 | *.yml text 13 | 14 | 15 | # Denote all files that are truly binary and should not be modified. 16 | *.Rdata binary 17 | *.RData binary 18 | *.rda binary 19 | *.rdb binary 20 | *.rds binary 21 | *.png binary 22 | *.jpg binary 23 | *.Rdx binary -------------------------------------------------------------------------------- /BayesianTools/man/updateGroups.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/blockUpdate.R 3 | \name{updateGroups} 4 | \alias{updateGroups} 5 | \title{Determine the groups of correlated parameters} 6 | \usage{ 7 | updateGroups(chain, blockSettings) 8 | } 9 | \arguments{ 10 | \item{chain}{MCMC chain including only the parameters (not logP,ll, logP)} 11 | 12 | \item{blockSettings}{list with settings} 13 | } 14 | \value{ 15 | groups 16 | } 17 | \description{ 18 | Determine the groups of correlated parameters 19 | } 20 | \author{ 21 | Stefan Paul 22 | } 23 | \keyword{internal} 24 | -------------------------------------------------------------------------------- /BayesianTools/man/rescale.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/utils.R 3 | \name{rescale} 4 | \alias{rescale} 5 | \title{Rescale} 6 | \usage{ 7 | rescale(x, from, to) 8 | } 9 | \arguments{ 10 | \item{x}{vector of values tp be scaled} 11 | 12 | \item{from}{vector of length 2, original interval (lower, upper)} 13 | 14 | \item{to}{vector of length 2, target interval (lower, upper)} 15 | } 16 | \description{ 17 | Rescales values in the interval "from" (lower, upper) to the new interval "to" (lower, upper). 18 | } 19 | \author{ 20 | Tankred Ott 21 | } 22 | \keyword{internal} 23 | -------------------------------------------------------------------------------- /BayesianTools/man/likelihoodIidNormal.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/classLikelihood.R 3 | \name{likelihoodIidNormal} 4 | \alias{likelihoodIidNormal} 5 | \title{Normal / Gaussian Likelihood function} 6 | \usage{ 7 | likelihoodIidNormal(predicted, observed, sd) 8 | } 9 | \arguments{ 10 | \item{predicted}{vector of predicted values} 11 | 12 | \item{observed}{vector of observed values} 13 | 14 | \item{sd}{standard deviation of the i.i.d. normal likelihood} 15 | } 16 | \description{ 17 | Normal / Gaussian Likelihood function 18 | } 19 | \author{ 20 | Florian Hartig 21 | } 22 | -------------------------------------------------------------------------------- /BayesianTools/inst/examples/WAICHelp.R: -------------------------------------------------------------------------------- 1 | bayesianSetup <- createBayesianSetup(likelihood = testDensityNormal, 2 | prior = createUniformPrior(lower = rep(-10,2), 3 | upper = rep(10,2))) 4 | 5 | # likelihood density needs to have option sum = FALSE 6 | 7 | testDensityNormal(c(1,1,1), sum = FALSE) 8 | bayesianSetup$likelihood$density(c(1,1,1), sum = FALSE) 9 | bayesianSetup$likelihood$density(matrix(rep(1,9), ncol = 3), sum = FALSE) 10 | 11 | # running MCMC 12 | 13 | out = runMCMC(bayesianSetup = bayesianSetup) 14 | 15 | WAIC(out) 16 | -------------------------------------------------------------------------------- /BayesianTools/man/testDensityInfinity.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/testFunctions.R 3 | \name{testDensityInfinity} 4 | \alias{testDensityInfinity} 5 | \title{Test function infinity ragged} 6 | \usage{ 7 | testDensityInfinity(x, error = F) 8 | } 9 | \arguments{ 10 | \item{x}{2-dim parameter vector} 11 | 12 | \item{error}{should error or infinity be returned} 13 | } 14 | \description{ 15 | Test function infinity ragged 16 | } 17 | \seealso{ 18 | \code{\link{generateTestDensityMultiNormal}} \cr 19 | \code{\link{testDensityBanana}} 20 | } 21 | \author{ 22 | Florian Hartig 23 | } 24 | -------------------------------------------------------------------------------- /BayesianTools/man/package-deprecated.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/VSEM.R 3 | \name{createMixWithDefaults} 4 | \alias{createMixWithDefaults} 5 | \title{Allows to mix a given parameter vector with a default parameter vector} 6 | \usage{ 7 | createMixWithDefaults(pars, defaults, locations) 8 | } 9 | \arguments{ 10 | \item{pars}{vector with new parameter values} 11 | 12 | \item{defaults}{vector with defaukt parameter values} 13 | 14 | \item{locations}{indices of the new parameter values} 15 | } 16 | \description{ 17 | This function is deprecated and will be removed by v0.2. 18 | } 19 | -------------------------------------------------------------------------------- /BayesianTools/src/init.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include // for NULL 4 | #include 5 | 6 | /* FIXME: 7 | Check these declarations against the C/Fortran source code. 8 | */ 9 | 10 | /* .Call calls */ 11 | extern SEXP _BayesianTools_vsemC(SEXP, SEXP); 12 | 13 | static const R_CallMethodDef CallEntries[] = { 14 | {"_BayesianTools_vsemC", (DL_FUNC) &_BayesianTools_vsemC, 2}, 15 | {NULL, NULL, 0} 16 | }; 17 | 18 | void R_init_BayesianTools(DllInfo *dll) 19 | { 20 | R_registerRoutines(dll, NULL, CallEntries, NULL, NULL); 21 | R_useDynamicSymbols(dll, FALSE); 22 | } 23 | -------------------------------------------------------------------------------- /BayesianTools/man/createPosterior.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/classPosterior.R 3 | \name{createPosterior} 4 | \alias{createPosterior} 5 | \title{Creates a standardized posterior class} 6 | \usage{ 7 | createPosterior(prior, likelihood) 8 | } 9 | \arguments{ 10 | \item{prior}{prior class} 11 | 12 | \item{likelihood}{Log likelihood density} 13 | } 14 | \description{ 15 | Creates a standardized posterior class 16 | } 17 | \details{ 18 | Function is internally used in \code{\link{createBayesianSetup}} to create a standarized posterior class. 19 | } 20 | \author{ 21 | Florian Hartig 22 | } 23 | -------------------------------------------------------------------------------- /BayesianTools/man/generateCRvalues.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/mcmcDREAM_helperFunctions.R 3 | \name{generateCRvalues} 4 | \alias{generateCRvalues} 5 | \title{Generates matrix of CR values based on pCR} 6 | \usage{ 7 | generateCRvalues(pCR, settings, Npop) 8 | } 9 | \arguments{ 10 | \item{pCR}{Vector of crossover probabilities. Needs to be of length nCR.} 11 | 12 | \item{settings}{settings list} 13 | 14 | \item{Npop}{number of chains} 15 | } 16 | \value{ 17 | Matrix with CR values 18 | } 19 | \description{ 20 | Generates matrix of CR values based on pCR 21 | } 22 | \keyword{internal} 23 | -------------------------------------------------------------------------------- /BayesianTools/man/combineChains.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/codaFunctions.R 3 | \name{combineChains} 4 | \alias{combineChains} 5 | \title{Function to combine chains} 6 | \usage{ 7 | combineChains(x, merge = T) 8 | } 9 | \arguments{ 10 | \item{x}{a list of MCMC chains} 11 | 12 | \item{merge}{logical determines whether chains should be merged} 13 | } 14 | \value{ 15 | combined chains 16 | } 17 | \description{ 18 | Function to combine chains 19 | } 20 | \note{ 21 | to combine several chains to a single McmcSamplerList, see \code{\link{createMcmcSamplerList}} 22 | } 23 | \keyword{internal} 24 | -------------------------------------------------------------------------------- /Development/manualTests/MetropolisTest.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Test of basic functions" 3 | author: "Florian Hartig" 4 | date: "10 Jun 2016" 5 | output: html_document 6 | --- 7 | 8 | ```{r} 9 | set.seed(1) 10 | library(BayesianTools) 11 | ``` 12 | 13 | 14 | # 2-d distribution 15 | 16 | ```{r, results='hide'} 17 | 18 | ll = function(x) sum(dnorm(x, log = T)) 19 | setup = createBayesianSetup(ll, lower = rep(-10,1000), upper = rep(10,1000)) 20 | 21 | settings = list(iterations = 1000, consoleUpdates = 1e+2, optimize = F) 22 | out <- runMCMC(bayesianSetup = setup, sampler = "Metropolis", settings = settings) 23 | ``` 24 | 25 | 26 | 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /BayesianTools/R/plotTrace.R: -------------------------------------------------------------------------------- 1 | #' Trace plot for MCMC class 2 | #' @param sampler an object of class MCMC sampler 3 | #' @param thin determines the thinning intervall of the chain 4 | #' @param ... additional parameters to pass on to the \code{\link{getSample}}, for example parametersOnly =F, or start = 1000 5 | #' @export 6 | #' @seealso \code{\link{marginalPlot}} \cr 7 | #' \code{\link{plotTimeSeries}} \cr 8 | #' \code{\link{correlationPlot}} 9 | #' @example /inst/examples/tracePlotHelp.R 10 | tracePlot <- function(sampler, thin = "auto", ...){ 11 | codaChain = getSample(sampler, coda = T, thin = thin, ...) 12 | plot(codaChain) 13 | } 14 | -------------------------------------------------------------------------------- /BayesianTools/man/AdaptpCR.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/mcmcDREAM_helperFunctions.R 3 | \name{AdaptpCR} 4 | \alias{AdaptpCR} 5 | \title{Adapts pCR values} 6 | \usage{ 7 | AdaptpCR(CR, delta, lCR, settings, Npop) 8 | } 9 | \arguments{ 10 | \item{CR}{Vector of crossover probabilities. Needs to be of length nCR.} 11 | 12 | \item{delta}{vector with differences} 13 | 14 | \item{lCR}{values to weight delta} 15 | 16 | \item{settings}{settings list} 17 | 18 | \item{Npop}{number of chains.} 19 | } 20 | \value{ 21 | Matrix with CR values 22 | } 23 | \description{ 24 | Adapts pCR values 25 | } 26 | \keyword{internal} 27 | -------------------------------------------------------------------------------- /BayesianTools/inst/examples/tracePlotHelp.R: -------------------------------------------------------------------------------- 1 | # set up and run the MCMC 2 | ll <- function(x) sum(dnorm(x, log = TRUE)) 3 | setup <- createBayesianSetup(likelihood = ll, lower = c(-10, -10), upper = c(10,10)) 4 | settings <- list(iterations = 2000) 5 | out <- runMCMC(bayesianSetup = setup, settings = settings, sampler = "Metropolis") 6 | 7 | # plot the trace 8 | tracePlot(sampler = out, thin = 10) 9 | tracePlot(sampler = out, thin = 50) 10 | 11 | # additional parameters can be passed on to getSample (see help) 12 | tracePlot(sampler = out, thin = 10, start = 500) 13 | # select parameter by index 14 | tracePlot(sampler = out, thin = 10, start = 500, whichParameters = 2) 15 | -------------------------------------------------------------------------------- /BayesianTools/man/createSmcSamplerList.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/classSMCSamplerList.R 3 | \name{createSmcSamplerList} 4 | \alias{createSmcSamplerList} 5 | \title{Convenience function to create an object of class SMCSamplerList from a list of mcmc samplers} 6 | \usage{ 7 | createSmcSamplerList(...) 8 | } 9 | \arguments{ 10 | \item{...}{a list of MCMC samplers} 11 | } 12 | \value{ 13 | a list of class smcSamplerList with each object being an smcSampler 14 | } 15 | \description{ 16 | Convenience function to create an object of class SMCSamplerList from a list of mcmc samplers 17 | } 18 | \author{ 19 | Florian Hartig 20 | } 21 | -------------------------------------------------------------------------------- /BayesianTools/man/createMcmcSamplerList.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/classMcmcSamplerList.R 3 | \name{createMcmcSamplerList} 4 | \alias{createMcmcSamplerList} 5 | \title{Convenience function to create an object of class mcmcSamplerList from a list of mcmc samplers} 6 | \usage{ 7 | createMcmcSamplerList(mcmcList) 8 | } 9 | \arguments{ 10 | \item{mcmcList}{a list with each object being an mcmcSampler} 11 | } 12 | \value{ 13 | Object of class "mcmcSamplerList" 14 | } 15 | \description{ 16 | Convenience function to create an object of class mcmcSamplerList from a list of mcmc samplers 17 | } 18 | \author{ 19 | Florian Hartig 20 | } 21 | -------------------------------------------------------------------------------- /BayesianTools/man/mcmcMultipleChains.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/mcmcMultipleChains.R 3 | \name{mcmcMultipleChains} 4 | \alias{mcmcMultipleChains} 5 | \title{Run multiple chains} 6 | \usage{ 7 | mcmcMultipleChains(bayesianSetup, settings, sampler) 8 | } 9 | \arguments{ 10 | \item{bayesianSetup}{Object of class "BayesianSetup"} 11 | 12 | \item{settings}{list with settings for sampler} 13 | 14 | \item{sampler}{character, either "Metropolis" or "DE"} 15 | } 16 | \value{ 17 | list containing the single runs ($sampler) and the chains in a coda::mcmc.list ($mcmc.list) 18 | } 19 | \description{ 20 | Run multiple chains 21 | } 22 | \keyword{internal} 23 | -------------------------------------------------------------------------------- /BayesianTools/inst/examples/MetropolisHelp.R: -------------------------------------------------------------------------------- 1 | 2 | # Running the metropolis via the runMCMC with a proposal covariance generated from the prior 3 | # (can be useful for complicated priors) 4 | 5 | ll = function(x) sum(dnorm(x, log = TRUE)) 6 | setup = createBayesianSetup(ll, lower = c(-10,-10), upper = c(10,10)) 7 | 8 | samples = setup$prior$sampler(1000) 9 | 10 | generator = createProposalGenerator(diag(1, setup$numPars)) 11 | generator = updateProposalGenerator(generator, samples, manualScaleAdjustment = 1, message = TRUE) 12 | 13 | settings = list(proposalGenerator = generator, optimize = FALSE, iterations = 500) 14 | 15 | out = runMCMC(bayesianSetup = setup, sampler = "Metropolis", settings = settings) 16 | -------------------------------------------------------------------------------- /BayesianTools/man/testDensityGelmanMeng.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/testFunctions.R 3 | \name{testDensityGelmanMeng} 4 | \alias{testDensityGelmanMeng} 5 | \title{GelmanMeng test function} 6 | \usage{ 7 | testDensityGelmanMeng(x, A = 1, B = 0, C1 = 3, C2 = 3, log = TRUE) 8 | } 9 | \arguments{ 10 | \item{x}{parameter vector} 11 | 12 | \item{A}{function parameter} 13 | 14 | \item{B}{function parameter} 15 | 16 | \item{C1}{function parameter} 17 | 18 | \item{C2}{function parameter} 19 | 20 | \item{log}{log 21 | 22 | A non-elliptical, bivariate density function proposed by Gelman and Meng (1991).} 23 | } 24 | \description{ 25 | GelmanMeng test function 26 | } 27 | -------------------------------------------------------------------------------- /BayesianTools/man/sampleEquallySpaced.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/utils.R 3 | \name{sampleEquallySpaced} 4 | \alias{sampleEquallySpaced} 5 | \title{Gets n equally spaced samples (rows) from a matrix or vector} 6 | \usage{ 7 | sampleEquallySpaced(x, numSamples) 8 | } 9 | \arguments{ 10 | \item{x}{matrix or vector} 11 | 12 | \item{numSamples}{number of samples (rows) to be drawn} 13 | } 14 | \description{ 15 | Gets n equally spaced samples (rows) from a matrix or vector 16 | } 17 | \details{ 18 | Gets n equally spaced samples (rows) from a matrix and returns a new matrix (or vector) containing those samples 19 | } 20 | \author{ 21 | Tankred Ott 22 | } 23 | \keyword{internal} 24 | -------------------------------------------------------------------------------- /BayesianTools/tests/testthat/test-runMCMC.R: -------------------------------------------------------------------------------- 1 | context("Test runMCMC interface") 2 | 3 | set.seed(1) 4 | library(BayesianTools) 5 | library(testthat) 6 | 7 | 8 | ll <- function(x) sum(dnorm(x, log = T)) 9 | bayesianSetup <- createBayesianSetup(likelihood = ll, lower = rep(-10, 4), upper = rep(10, 4)) 10 | 11 | settings = list(iterations = 5) 12 | out <- runMCMC(bayesianSetup = bayesianSetup, settings = settings) 13 | 14 | x = gelmanDiagnostics(out) 15 | summary(out) 16 | 17 | 18 | settings = list(iterations = 10, nrChains = 3) 19 | out <- runMCMC(bayesianSetup = bayesianSetup, settings = settings) 20 | gelmanDiagnostics(out) 21 | summary(out) 22 | 23 | 24 | expect_error(runMCMC(bayesianSetup = ll, settings = settings)) 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /BayesianTools/man/logSumExp.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/utils-Numerics.R 3 | \name{logSumExp} 4 | \alias{logSumExp} 5 | \title{Funktion to compute log(sum(exp(x))} 6 | \usage{ 7 | logSumExp(x, mean = F) 8 | } 9 | \arguments{ 10 | \item{x}{values at log scale} 11 | 12 | \item{mean}{logical, determines whether the mean should be used instead of the sum} 13 | } 14 | \description{ 15 | Funktion to compute log(sum(exp(x)) 16 | } 17 | \details{ 18 | This function computes log(sum(exp(x)), using the offset trick to avoid numeric overflow, see, e.g. http://jblevins.org/notes/log-sum-exp. The mean option allows calculating logMeanExp 19 | } 20 | \author{ 21 | Florian Hartig 22 | } 23 | \keyword{internal} 24 | -------------------------------------------------------------------------------- /BayesianTools/man/testLinearModel.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/testFunctions.R 3 | \name{testLinearModel} 4 | \alias{testLinearModel} 5 | \title{Fake model, returns a ax + b linear response to 2-param vector} 6 | \usage{ 7 | testLinearModel(x, env = NULL) 8 | } 9 | \arguments{ 10 | \item{x}{2-dim parameter vector} 11 | 12 | \item{env}{optional, environmental covariate} 13 | } 14 | \description{ 15 | Fake model, returns a ax + b linear response to 2-param vector 16 | } 17 | \examples{ 18 | x = c(1,2) 19 | y = testLinearModel(x) 20 | plot(y) 21 | } 22 | \seealso{ 23 | \code{\link{generateTestDensityMultiNormal}} \cr 24 | \code{\link{testDensityBanana}} 25 | } 26 | \author{ 27 | Florian Hartig 28 | } 29 | -------------------------------------------------------------------------------- /BayesianTools/inst/examples/getVolume.R: -------------------------------------------------------------------------------- 1 | bayesianSetup = createBayesianSetup( 2 | likelihood = generateTestDensityMultiNormal(sigma = "no correlation"), 3 | lower = rep(-10, 3), upper = rep(10, 3)) 4 | 5 | out <- runMCMC(bayesianSetup = bayesianSetup, sampler = "Metropolis", 6 | settings = list(iterations = 2000, message = FALSE)) 7 | 8 | getVolume(out, prior = TRUE) 9 | 10 | bayesianSetup = createBayesianSetup( 11 | likelihood = generateTestDensityMultiNormal(sigma = "strongcorrelation"), 12 | lower = rep(-10, 3), upper = rep(10, 3)) 13 | 14 | out <- runMCMC(bayesianSetup = bayesianSetup, sampler = "Metropolis", 15 | settings = list(iterations = 2000, message = FALSE)) 16 | 17 | getVolume(out, prior = TRUE) 18 | 19 | -------------------------------------------------------------------------------- /pkgdown_bootstrap.r: -------------------------------------------------------------------------------- 1 | library(pkgdown) 2 | 3 | # this doesn't work. I have no idea why. 4 | #setwd("./BayesianTools") 5 | 6 | # sink("_pkgdown.yml") 7 | # template_articles("./BayesianTools") 8 | # template_navbar("./BayesianTools") 9 | # template_reference("./BayesianTools") 10 | # 11 | # sink() 12 | # 13 | # dir = getwd() 14 | # if (!dir.exists("./docs")) dir.create("docs") 15 | # build_home(pkg = file.path(dir, "BayesianTools"), path = file.path(dir, "docs")) 16 | #setwd("..") 17 | 18 | setwd("BayesianTools") 19 | 20 | sink("../_pkgdown.yml") 21 | template_navbar(".") 22 | template_reference(".") 23 | template_articles(".") 24 | sink() 25 | 26 | if (!dir.exists("../docs")) dir.create("docs") 27 | build_site(path = "../docs") 28 | 29 | setwd("..") 30 | -------------------------------------------------------------------------------- /BayesianTools/man/getCredibleIntervals.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/mcmcConfidence.R 3 | \name{getCredibleIntervals} 4 | \alias{getCredibleIntervals} 5 | \title{Calculate confidence region from an MCMC or similar sample} 6 | \usage{ 7 | getCredibleIntervals(sampleMatrix, quantiles = c(0.025, 0.975)) 8 | } 9 | \arguments{ 10 | \item{sampleMatrix}{matrix of outcomes. Could be parameters or predictions} 11 | 12 | \item{quantiles}{quantiles to be calculated} 13 | } 14 | \description{ 15 | Calculate confidence region from an MCMC or similar sample 16 | } 17 | \seealso{ 18 | \code{\link{getPredictiveDistribution}} \cr 19 | \code{\link{getPredictiveIntervals}} \cr 20 | } 21 | \author{ 22 | Florian Hartig 23 | } 24 | -------------------------------------------------------------------------------- /BayesianTools/man/testDensityBanana.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/testFunctions.R 3 | \name{testDensityBanana} 4 | \alias{testDensityBanana} 5 | \title{Banana-shaped density function} 6 | \usage{ 7 | testDensityBanana(p) 8 | } 9 | \arguments{ 10 | \item{p}{2-dim parameter vector} 11 | } 12 | \description{ 13 | Banana-shaped density function 14 | } 15 | \note{ 16 | inspired from package FMEmcmc, seems to go back to Laine M (2008). Adaptive MCMC Methods with Applications in Environmental and Models. Finnish Meteorological Institute Contributions 69. ISBN 978-951-697-662-7. 17 | } 18 | \seealso{ 19 | \code{\link{generateTestDensityMultiNormal}} \cr 20 | \code{\link{testLinearModel}} 21 | } 22 | \author{ 23 | Florian Hartig 24 | } 25 | -------------------------------------------------------------------------------- /BayesianTools/man/setupStartProposal.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/mcmcRun.R 3 | \name{setupStartProposal} 4 | \alias{setupStartProposal} 5 | \title{Help function to find starvalues and proposalGenerator settings} 6 | \usage{ 7 | setupStartProposal(proposalGenerator = NULL, bayesianSetup, settings) 8 | } 9 | \arguments{ 10 | \item{proposalGenerator}{proposal generator} 11 | 12 | \item{bayesianSetup}{either an object of class bayesianSetup created by \code{\link{createBayesianSetup}} (recommended), or a log target function} 13 | 14 | \item{settings}{list with settings} 15 | } 16 | \description{ 17 | Help function to find starvalues and proposalGenerator settings 18 | } 19 | \author{ 20 | Florian Hartig 21 | } 22 | \keyword{internal} 23 | -------------------------------------------------------------------------------- /BayesianTools/man/mergeChains.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/classBayesianOutput.R 3 | \name{mergeChains} 4 | \alias{mergeChains} 5 | \title{Merge Chains} 6 | \usage{ 7 | mergeChains(l, ...) 8 | } 9 | \arguments{ 10 | \item{l}{a list with objects that can be accessed with \code{\link{getSample}}} 11 | 12 | \item{...}{arguments to be passed on to \code{\link{getSample}}} 13 | } 14 | \value{ 15 | a matrix 16 | } 17 | \description{ 18 | Merge a list of outputs from MCMC / SMC samplers 19 | } 20 | \details{ 21 | The function merges a list of outputs from MCMC / SMC samplers into a single matrix. Requirement is that the list contains classes for which the \code{\link{getSample}} function works 22 | } 23 | \author{ 24 | Florian Hartig 25 | } 26 | -------------------------------------------------------------------------------- /BayesianTools/tests/testthat/test-plotDiagnostic.R: -------------------------------------------------------------------------------- 1 | testthat::context("Test plotDiagnostic") 2 | bayesianSetup <- createBayesianSetup(likelihood = testDensityNormal, prior = createUniformPrior(lower = rep(-10,2), upper = rep(10,2))) 3 | 4 | # settings = list(nrChains = 1, iterations = 100) 5 | # outOneChain = runMCMC(bayesianSetup = bayesianSetup, settings = list(nrChains = 1, iterations = 100)) 6 | # outTwoChain = runMCMC(bayesianSetup = bayesianSetup, settings = list(nrChains = 2, iterations = 100)) 7 | # 8 | # outTwoChainDiffSamp = runMCMC(bayesianSetup = bayesianSetup, settings = list(nrChains = 2, iterations = 100), sampler = "DREAM") 9 | 10 | 11 | testthat::test_that("plotDiagnostic works for bayesianOutput", { 12 | testthat::expect_error(plotDiagnostic(matrix(0, ncol = 4, nrow = 2))) 13 | }) -------------------------------------------------------------------------------- /BayesianTools/man/likelihoodAR1.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/classLikelihood.R 3 | \name{likelihoodAR1} 4 | \alias{likelihoodAR1} 5 | \title{AR1 type likelihood function} 6 | \usage{ 7 | likelihoodAR1(predicted, observed, sd, a) 8 | } 9 | \arguments{ 10 | \item{predicted}{vector of predicted values} 11 | 12 | \item{observed}{vector of observed values} 13 | 14 | \item{sd}{standard deviation of the iid normal likelihood} 15 | 16 | \item{a}{temporal correlation in the AR1 model} 17 | } 18 | \description{ 19 | AR1 type likelihood function 20 | } 21 | \note{ 22 | The AR1 model considers the process: \cr y(t) = a y(t-1) + E \cr e = i.i.d. N(0,sd) \cr |a| < 1 \cr At the moment, no NAs are allowed in the time series. 23 | } 24 | \author{ 25 | Florian Hartig 26 | } 27 | -------------------------------------------------------------------------------- /BayesianTools/man/sampleMetropolis.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/mcmcMetropolis.R 3 | \name{sampleMetropolis} 4 | \alias{sampleMetropolis} 5 | \title{gets samples while adopting the MCMC proposal generator} 6 | \usage{ 7 | sampleMetropolis(mcmcSampler, iterations) 8 | } 9 | \arguments{ 10 | \item{mcmcSampler}{an mcmcSampler} 11 | 12 | \item{iterations}{iterations} 13 | } 14 | \description{ 15 | Function to sample with cobinations of the basic Metropolis-Hastings MCMC algorithm (Metropolis et al., 1953), a variation of the adaptive Metropolis MCMC (Haario et al., 2001), the delayed rejection algorithm (Tierney & Mira, 1999), and the delayed rejection adaptive Metropolis algorithm (DRAM, Haario et al), and the Metropolis within Gibbs 16 | } 17 | \author{ 18 | Florian Hartig 19 | } 20 | \keyword{internal} 21 | -------------------------------------------------------------------------------- /docs/link.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | 8 | 12 | 13 | -------------------------------------------------------------------------------- /BayesianTools/man/makeObjectClassCodaMCMC.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/codaFunctions.R 3 | \name{makeObjectClassCodaMCMC} 4 | \alias{makeObjectClassCodaMCMC} 5 | \title{Helper function to change an object to a coda mcmc class,} 6 | \usage{ 7 | makeObjectClassCodaMCMC(chain, start = 1, end = numeric(0), thin = 1) 8 | } 9 | \arguments{ 10 | \item{chain}{mcmc Chain} 11 | 12 | \item{start}{for mcmc samplers start value in the chain. For SMC samplers, start particle} 13 | 14 | \item{end}{for mcmc samplers end value in the chain. For SMC samplers, end particle} 15 | 16 | \item{thin}{thinning parameter} 17 | } 18 | \value{ 19 | object of class coda::mcmc 20 | } 21 | \description{ 22 | Helper function to change an object to a coda mcmc class, 23 | } 24 | \details{ 25 | Very similar to coda::mcmc but with less overhead 26 | } 27 | \keyword{internal} 28 | -------------------------------------------------------------------------------- /Development/DATASET.R: -------------------------------------------------------------------------------- 1 | ## code to prepare `DATASET` dataset goes here 2 | 3 | # note limitations of use_data https://github.com/r-lib/usethis/issues/789 4 | 5 | # usethis::proj_set("./BayesianTools/") does not work 6 | 7 | # workaround is to 8 | # create a new project in the package directory (I had my project one level above the package directory) 9 | # use the function outside an R project 10 | 11 | library(BayesianTools) 12 | 13 | ll <- generateTestDensityMultiNormal(sigma = "no correlation") 14 | bayesianSetup = createBayesianSetup(likelihood = ll, lower = rep(-10, 3), upper = rep(10, 3)) 15 | settings = list(iterations = 10000, nrChains = 3) 16 | mcmcOutput <- runMCMC(bayesianSetup = bayesianSetup, sampler = "DEzs", settings = settings) 17 | 18 | #use_data(mcmcOutput, overwrite = TRUE, name = "mcmcRun", internal = T) 19 | 20 | usethis::use_data("exampleMCMC", overwrite = TRUE) 21 | 22 | 23 | -------------------------------------------------------------------------------- /BayesianTools/src/RcppExports.cpp: -------------------------------------------------------------------------------- 1 | // Generated by using Rcpp::compileAttributes() -> do not edit by hand 2 | // Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 3 | 4 | #include 5 | 6 | using namespace Rcpp; 7 | 8 | #ifdef RCPP_USE_GLOBAL_ROSTREAM 9 | Rcpp::Rostream& Rcpp::Rcout = Rcpp::Rcpp_cout_get(); 10 | Rcpp::Rostream& Rcpp::Rcerr = Rcpp::Rcpp_cerr_get(); 11 | #endif 12 | 13 | // vsemC 14 | NumericMatrix vsemC(NumericVector par, NumericVector PAR); 15 | RcppExport SEXP _BayesianTools_vsemC(SEXP parSEXP, SEXP PARSEXP) { 16 | BEGIN_RCPP 17 | Rcpp::RObject rcpp_result_gen; 18 | Rcpp::RNGScope rcpp_rngScope_gen; 19 | Rcpp::traits::input_parameter< NumericVector >::type par(parSEXP); 20 | Rcpp::traits::input_parameter< NumericVector >::type PAR(PARSEXP); 21 | rcpp_result_gen = Rcpp::wrap(vsemC(par, PAR)); 22 | return rcpp_result_gen; 23 | END_RCPP 24 | } 25 | -------------------------------------------------------------------------------- /BayesianTools/inst/examples/getSampleHelp.R: -------------------------------------------------------------------------------- 1 | ll = function(x) sum(dnorm(x, log = TRUE)) 2 | 3 | setup = createBayesianSetup(ll, lower = c(-10,-10), upper = c(10,10)) 4 | 5 | settings = list(nrChains = 2, iterations = 1000) 6 | out <- runMCMC(bayesianSetup = setup, sampler = "DEzs", settings = settings) 7 | 8 | # population MCMCs divide the interations by the number of internal chains, 9 | # so the end of the 3 chains is 1000/3 = 334 10 | sample <- getSample(out, start = 100, end = 334, thin = 10) 11 | 12 | # sampling with number of samples instead of thinning and 13 | # returning a coda object 14 | sample <- getSample(out, start = 100, numSamples = 60, coda = TRUE) 15 | plot(sample) 16 | 17 | 18 | # MCMC with a single chain: 19 | settings_2 <- list(nrChains = 1, iterations = 1000) 20 | out_2 <- runMCMC(setup, sampler = "Metropolis", settings = settings_2) 21 | sample_2 <- getSample(out_2, numSamples = 100) 22 | 23 | -------------------------------------------------------------------------------- /BayesianTools/man/Gfun.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/mcmcTwalk_helperFunctions.R 3 | \name{Gfun} 4 | \alias{Gfun} 5 | \title{Helper function for blow and hop moves} 6 | \usage{ 7 | Gfun(case, npSel, pSel, h, x, x2) 8 | } 9 | \arguments{ 10 | \item{case}{Type of Twalk move. Either "hop" or "blow"} 11 | 12 | \item{npSel}{number of parameters that are changed.} 13 | 14 | \item{pSel}{vector containing information about which parameters are changed.} 15 | 16 | \item{h}{Parameter for "blow" and hop moves} 17 | 18 | \item{x}{parameter vector of chain 1} 19 | 20 | \item{x2}{parameter vector of chain 2} 21 | } 22 | \description{ 23 | Helper function for blow and hop moves 24 | } 25 | \references{ 26 | Christen, J. Andres, and Colin Fox. "A general purpose sampling algorithm for continuous distributions (the t-walk)." Bayesian Analysis 5.2 (2010): 263-281. 27 | } 28 | \keyword{internal} 29 | -------------------------------------------------------------------------------- /BayesianTools/man/correctThin.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/utils.R 3 | \name{correctThin} 4 | \alias{correctThin} 5 | \title{Checks if thin is consistent with nTotalSamples samples and if not corrects it.} 6 | \usage{ 7 | correctThin(nTotalSamples, thin, autoThinFraction = 0.001) 8 | } 9 | \arguments{ 10 | \item{nTotalSamples}{total number of rows/samples} 11 | 12 | \item{thin}{thinning} 13 | 14 | \item{autoThinFraction}{fraction of the data that will be sampled when thin is set to "auto". E.g. 0.5 means thin will be nTotalSamples * 0.5. The resulting thin value is rounded down to the next integer.} 15 | } 16 | \description{ 17 | Checks if thin is consistent with nTotalSamples samples and if not corrects it. 18 | } 19 | \details{ 20 | Checks if the thin argument is consistent with the data consisting of nTotalSamples samples/rows and corrects thin if not. 21 | } 22 | \author{ 23 | Tankred Ott 24 | } 25 | \keyword{internal} 26 | -------------------------------------------------------------------------------- /Development/BayesFactor.R: -------------------------------------------------------------------------------- 1 | library(BayesFactor) 2 | 3 | ## Sleep data from t test example 4 | data(sleep) 5 | plot(extra ~ group, data = sleep) 6 | 7 | ## Calculating BF for difference values of the prior 8 | 9 | scale = exp(seq(-2,2, len = 50)) 10 | bf = rep(NA, 50) 11 | for(i in 1:50) bf[i] = ttestBF(x = sleep$extra[sleep$group==1], y = sleep$extra[sleep$group==2], paired=TRUE, rscale = scale[i])@bayesFactor$bf 12 | plot(scale, bf, xlab= "prior scale", ylab = "BF") 13 | 14 | 15 | ModelB4 <- generalTestBF(SDI ~ C + A + RS + RT + Gender + Context + 16 | 17 | C:Gender:Context + 18 | 19 | A:Gender:Context+ 20 | 21 | RT:Gender:Context+ 22 | 23 | RS:Gender:Context, data= df.exlcude, 24 | 25 | whichRandom = ID) 26 | 27 | -------------------------------------------------------------------------------- /BayesianTools/man/getPredictiveDistribution.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/mcmcConfidence.R 3 | \name{getPredictiveDistribution} 4 | \alias{getPredictiveDistribution} 5 | \title{Calculates predictive distribution based on the parameters} 6 | \usage{ 7 | getPredictiveDistribution(parMatrix, model, numSamples = 1000) 8 | } 9 | \arguments{ 10 | \item{parMatrix}{matrix of parameter values} 11 | 12 | \item{model}{model / function to calculate predictions. Outcome should be a vector} 13 | 14 | \item{numSamples}{number of samples to be drawn} 15 | } 16 | \description{ 17 | Calculates predictive distribution based on the parameters 18 | } 19 | \details{ 20 | If numSamples is greater than the number of rows in parMatrix, or NULL, or FALSE, or less than 1 all samples in parMatrix will be used. 21 | } 22 | \seealso{ 23 | \code{\link{getPredictiveIntervals}} \cr 24 | \code{\link{getCredibleIntervals}} \cr 25 | } 26 | \author{ 27 | Florian Hartig 28 | } 29 | -------------------------------------------------------------------------------- /BayesianTools/man/MAP.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/MAP.R 3 | \name{MAP} 4 | \alias{MAP} 5 | \title{calculates the Maxiumum APosteriori value (MAP)} 6 | \usage{ 7 | MAP(bayesianOutput, ...) 8 | } 9 | \arguments{ 10 | \item{bayesianOutput}{an object of class BayesianOutput (mcmcSampler, smcSampler, or mcmcList)} 11 | 12 | \item{...}{optional values to be passed on the the getSample function} 13 | } 14 | \description{ 15 | calculates the Maxiumum APosteriori value (MAP) 16 | } 17 | \details{ 18 | Currently, this function simply returns the parameter combination with the highest posterior in the chain. A more refined option would be to take the MCMC sample and do additional calculations, e.g. use an optimizer, a kerne delnsity estimator, or some other tool to search / interpolate around the best value in the chain 19 | } 20 | \seealso{ 21 | \code{\link{WAIC}}, \code{\link{DIC}}, \code{\link{marginalLikelihood}} 22 | } 23 | \author{ 24 | Florian Hartig 25 | } 26 | -------------------------------------------------------------------------------- /BayesianTools/man/propFun.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/mcmcTwalk_helperFunctions.R 3 | \name{propFun} 4 | \alias{propFun} 5 | \title{Helper function to create proposal} 6 | \usage{ 7 | propFun(case, Npar, pn1, x, x2, beta = NULL, aw = NULL) 8 | } 9 | \arguments{ 10 | \item{case}{Type of Twalk move. Either "walk", "traverse", "hop" or "blow"} 11 | 12 | \item{Npar}{number of parameters} 13 | 14 | \item{pn1}{Probability determining the number of parameters that are changed.} 15 | 16 | \item{x}{parameter vector of chain 1} 17 | 18 | \item{x2}{parameter vector of chain 2} 19 | 20 | \item{beta}{parameter for "traverse" move proposals.} 21 | 22 | \item{aw}{"walk" move proposal parameter.} 23 | } 24 | \description{ 25 | Helper function to create proposal 26 | } 27 | \references{ 28 | Christen, J. Andres, and Colin Fox. "A general purpose sampling algorithm for continuous distributions (the t-walk)." Bayesian Analysis 5.2 (2010): 263-281. 29 | } 30 | \keyword{internal} 31 | -------------------------------------------------------------------------------- /Development/manualTests/Defaults/saveDefaults.R: -------------------------------------------------------------------------------- 1 | samp = getPossibleSamplerTypes() 2 | 3 | defaults = list() 4 | 5 | for(i in 1:(length(samp$BTname))){ 6 | defaults[[i]] = applySettingsDefault(sampler = samp$BTname[i]) 7 | } 8 | 9 | save(defaults, file = "./Development/manualTests/Defaults/defaults.Rdata") 10 | 11 | 12 | library(BayesianTools) 13 | 14 | load(file = "./Development/manualTests/Defaults/defaults.Rdata") 15 | 16 | newDefaults = list() 17 | samp = getPossibleSamplerTypes() 18 | 19 | for(i in 1:(length(samp$BTname))){ 20 | newDefaults[[i]] = applySettingsDefault(sampler = samp$BTname[i]) 21 | 22 | newDefaults[[i]][[length(newDefaults[[i]])]] = NULL 23 | defaults[[i]][[length(defaults[[i]])]] = NULL 24 | 25 | print(samp$BTname[i]) 26 | print("=======") 27 | print("not in new") 28 | print(defaults[[i]][which(! names(defaults[[i]]) %in% names(newDefaults[[i]]))]) 29 | print("not in old") 30 | print(newDefaults[[i]][which(! names(newDefaults[[i]]) %in% names(defaults[[i]]))]) 31 | print(" ") 32 | } 33 | 34 | -------------------------------------------------------------------------------- /BayesianTools/man/marginalPlotDensity.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/plotMarginals.R 3 | \name{marginalPlotDensity} 4 | \alias{marginalPlotDensity} 5 | \title{Plot marginals as densities} 6 | \usage{ 7 | marginalPlotDensity( 8 | posteriorMat, 9 | priorMat = NULL, 10 | xrange = NULL, 11 | col = c("#FC006299", "#00BBAA30"), 12 | singlePanel = TRUE, 13 | ... 14 | ) 15 | } 16 | \arguments{ 17 | \item{posteriorMat}{matrix with samples as rows and parameters as columns} 18 | 19 | \item{priorMat}{matrix (optional) with samples as rows and parameters as columns} 20 | 21 | \item{xrange}{vector or matrix (optional), determining the plotting range, with parameters as columns and min, max as rows} 22 | 23 | \item{col}{vector of colors for posterior and} 24 | 25 | \item{singlePanel}{logical, determining whether the parameter should be plotted in a single panel or each in its own panel} 26 | } 27 | \description{ 28 | Plot marginals as densities 29 | } 30 | \author{ 31 | Tankred Ott 32 | } 33 | \keyword{internal} 34 | -------------------------------------------------------------------------------- /BayesianTools/man/marginalPlotViolin.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/plotMarginals.R 3 | \name{marginalPlotViolin} 4 | \alias{marginalPlotViolin} 5 | \title{Plot marginals as violin plot} 6 | \usage{ 7 | marginalPlotViolin( 8 | posteriorMat, 9 | priorMat = NULL, 10 | xrange = NULL, 11 | col = c("#FC006299", "#00BBAA88"), 12 | singlePanel = TRUE, 13 | ... 14 | ) 15 | } 16 | \arguments{ 17 | \item{posteriorMat}{matrix with samples as rows and parameters as columns} 18 | 19 | \item{priorMat}{matrix (optional) with samples as rows and parameters as columns} 20 | 21 | \item{xrange}{vector or matrix (optional), determining the plotting range, with parameters as columns and min, max as rows} 22 | 23 | \item{col}{vector of colors for posterior and} 24 | 25 | \item{singlePanel}{logical, determining whether the parameter should be plotted in a single panel or each in its own panel} 26 | } 27 | \description{ 28 | Plot marginals as violin plot 29 | } 30 | \author{ 31 | Tankred Ott 32 | } 33 | \keyword{internal} 34 | -------------------------------------------------------------------------------- /BayesianTools/inst/examples/bridgesampleHelp.R: -------------------------------------------------------------------------------- 1 | means <- c(0, 1, 2) 2 | sds <- c(1, 0.6, 3) 3 | 4 | # log-likelihood 5 | ll <- function (x) { 6 | return(sum(dnorm(x, mean = means, sd = sds, log = TRUE))) 7 | } 8 | 9 | # lower and upper bounds for prior 10 | lb <- rep(-10, 3) 11 | ub <- rep(10, 3) 12 | 13 | # create setup and run MCMC 14 | setup <- createBayesianSetup(likelihood = ll, 15 | lower = lb, 16 | upper = ub) 17 | 18 | out <- runMCMC(bayesianSetup = setup, 19 | settings = list(iterations = 1000), 20 | sampler = "DEzs") 21 | 22 | # sample from MCMC output with "burn-in" of 25% 23 | sample <- getSample(out$chain, start = 250, numSamples = 500) 24 | 25 | # use bridge sampling to get marginal likelihood 26 | bs_result <- bridgesample(chain = sample, 27 | nParams = out$setup$numPars, 28 | lower = lb, 29 | upper = ub, 30 | posterior = out$setup$posterior$density) 31 | bs_result 32 | -------------------------------------------------------------------------------- /BayesianTools/inst/examples/mcmcRun.R: -------------------------------------------------------------------------------- 1 | ## Generate a test likelihood function. 2 | ll <- generateTestDensityMultiNormal(sigma = "no correlation") 3 | 4 | ## Create a BayesianSetup object from the likelihood 5 | ## is the recommended way of using the runMCMC() function. 6 | bayesianSetup <- createBayesianSetup(likelihood = ll, lower = rep(-10, 3), upper = rep(10, 3)) 7 | 8 | ## Finally we can run the sampler. To get possible settings 9 | ## for a sampler, see help or run applySettingsDefault(sampler = "Metropolis") 10 | settings = list(iterations = 1000, adapt = FALSE) # 11 | out <- runMCMC(bayesianSetup = bayesianSetup, sampler = "Metropolis", settings = settings) 12 | 13 | ## out is of class bayesianOutput. There are various standard functions 14 | # implemented for this output 15 | 16 | plot(out) 17 | correlationPlot(out) 18 | marginalPlot(out) 19 | summary(out) 20 | 21 | ## additionally, you can return the sample as a coda object, and make use of the coda functions 22 | # for plotting and analysis 23 | 24 | codaObject = getSample(out, start = 500, coda = TRUE) 25 | 26 | 27 | -------------------------------------------------------------------------------- /BayesianTools/man/VSEMcreateLikelihood.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/VSEM.R 3 | \name{VSEMcreateLikelihood} 4 | \alias{VSEMcreateLikelihood} 5 | \title{Create an example dataset, and from that a likelihood or posterior for the VSEM model} 6 | \usage{ 7 | VSEMcreateLikelihood(likelihoodOnly = F, plot = F, selection = c(1:6, 12)) 8 | } 9 | \arguments{ 10 | \item{likelihoodOnly}{switch to devide whether to create only a likelihood, or a full bayesianSetup with uniform priors.} 11 | 12 | \item{plot}{switch to decide whether data should be plotted} 13 | 14 | \item{selection}{vector containing the indices of the selected parameters} 15 | } 16 | \description{ 17 | Create an example dataset, and from that a likelihood or posterior for the VSEM model 18 | } 19 | \details{ 20 | The purpose of this function is to be able to conveniently create a likelihood for the VSEM model for demonstration purposes. The function creates example data --> likelihood --> BayesianSetup, where the latter is the 21 | } 22 | \author{ 23 | Florian Hartig 24 | } 25 | -------------------------------------------------------------------------------- /BayesianTools/man/updateProposalGenerator.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/proposalGenerator.R 3 | \name{updateProposalGenerator} 4 | \alias{updateProposalGenerator} 5 | \title{To update settings of an existing proposal genenerator} 6 | \usage{ 7 | updateProposalGenerator( 8 | proposal, 9 | chain = NULL, 10 | message = F, 11 | eps = 1e-10, 12 | manualScaleAdjustment = 1 13 | ) 14 | } 15 | \arguments{ 16 | \item{proposal}{an object of class proposalGenerator} 17 | 18 | \item{chain}{a chain to create the covariance matrix from (optional)} 19 | 20 | \item{message}{whether to print an updating message} 21 | 22 | \item{eps}{numeric tolerance for covariance} 23 | 24 | \item{manualScaleAdjustment}{optional adjustment for the covariance scale (multiplicative)} 25 | } 26 | \description{ 27 | To update settings of an existing proposal genenerator 28 | } 29 | \details{ 30 | The this function can be applied in 2 ways 1) update the covariance given an MCMC chain, and 2) update the proposal generator after parameters have been changed 31 | } 32 | -------------------------------------------------------------------------------- /BayesianTools/man/getDharmaResiduals.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/plotTimeSeries.R 3 | \name{getDharmaResiduals} 4 | \alias{getDharmaResiduals} 5 | \title{Creates a DHARMa object} 6 | \usage{ 7 | getDharmaResiduals(model, parMatrix, numSamples, observed, error, plot = TRUE) 8 | } 9 | \arguments{ 10 | \item{model}{function that calculates model predictions for a given parameter vector} 11 | 12 | \item{parMatrix}{a parameter matrix from which the simulations will be generated} 13 | 14 | \item{numSamples}{the number of samples} 15 | 16 | \item{observed}{a vector of observed values} 17 | 18 | \item{error}{function with signature f(mean, par) that generates error expectations from mean model predictions. Par is a vector from the matrix with the parameter samples (full length). f needs to know which of these parameters are parameters of the error function} 19 | 20 | \item{plot}{logical, determining whether the simulated residuals should be plotted} 21 | } 22 | \description{ 23 | Creates a DHARMa object 24 | } 25 | \author{ 26 | Tankred Ott 27 | } 28 | -------------------------------------------------------------------------------- /Development/Figures/figures.R: -------------------------------------------------------------------------------- 1 | png(filename = "man/figures/betaDensity.png", width = 290, height = 200) 2 | plot(density(rbeta(10000000,10,3)), main = "Beta Density with a = 10, b = 3") 3 | dev.off() 4 | png(filename = "man/figures/normalDensity.png", width = 290, height = 200) 5 | plot(density(rnorm(10000000,0,1)), main = "Normal Density with mean = 0, sd = 1") 6 | dev.off() 7 | png(filename = "man/figures/uniformDensity.png", width = 290, height = 200) 8 | plot(density(runif(10000000)), main = "Uniform Density") 9 | dev.off() 10 | 11 | 12 | 13 | png(filename = "vignettes/betaDensity.png", width = 200, height = 180) 14 | plot(density(rbeta(10000000,10,3)), main = "Beta Density with \n a = 10, b = 3", xlab = "n = 10000000") 15 | dev.off() 16 | png(filename = "vignettes/normalDensity.png", width = 200, height = 180) 17 | plot(density(rnorm(10000000,0,1)), main = "Normal Density with \n mean = 0, sd = 1", xlab = "n = 10000000") 18 | dev.off() 19 | png(filename = "vignettes/uniformDensity.png", width = 200, height = 180) 20 | plot(density(runif(10000000)), main = "Uniform Density", xlab = "n = 10000000") 21 | dev.off() 22 | -------------------------------------------------------------------------------- /Publications/SpeichEtAl-SMCForModelCalibration/5_launch_scripts/test_parallel_40_50ms_mult1.moab: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | ########## Begin MOAB/Slurm header ########## 3 | # 4 | # Give job a reasonable name 5 | #MOAB -N test_parallel_40_50ms_1 6 | # 7 | # Request number of nodes and CPU cores per node for job 8 | #MOAB -l nodes=2:ppn=20 9 | # 10 | # Estimated wallclock time for job 11 | #MOAB -l walltime=96:00:00 12 | # 13 | # Write standard output and errors in same file 14 | #MOAB -j oe 15 | # 16 | # 17 | ########### End MOAB header ########## 18 | 19 | echo "Working Directory: $PWD" 20 | echo "Running on host $HOSTNAME" 21 | echo "Job id: $MOAB_JOBID" 22 | echo "Job name: $MOAB_JOBNAME" 23 | echo "Number of nodes allocated to job: $MOAB_NODECOUNT" 24 | echo "Number of cores allocated to job: $MOAB_PROCCOUNT" 25 | 26 | # Load module 27 | module load math/R 28 | module load mpi/openmpi/2.1-intel-17.0 29 | 30 | # Start R program 31 | R CMD BATCH --no-save --no-restore '--args number=1 cores=40' ./scripts/test_parallel_2plus_50ms.r -------------------------------------------------------------------------------- /BayesianTools/man/plotSensitivity.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/plotSensitivityOAT.R 3 | \name{plotSensitivity} 4 | \alias{plotSensitivity} 5 | \title{Performs a one-factor-at-a-time sensitivity analysis for the posterior of a given bayesianSetup within the prior range.} 6 | \usage{ 7 | plotSensitivity(bayesianSetup, selection = NULL, equalScale = T) 8 | } 9 | \arguments{ 10 | \item{bayesianSetup}{An object of class BayesianSetup} 11 | 12 | \item{selection}{indices of selected parameters} 13 | 14 | \item{equalScale}{if T, y axis of all plots will have the same scale} 15 | } 16 | \description{ 17 | Performs a one-factor-at-a-time sensitivity analysis for the posterior of a given bayesianSetup within the prior range. 18 | } 19 | \note{ 20 | This function can also be used for sensitivity analysis of an arbitrary output - just create a BayesianSetup with this output. 21 | } 22 | \examples{ 23 | 24 | ll <- testDensityBanana 25 | bayesianSetup <- createBayesianSetup(likelihood = ll, lower = rep(-10, 2), upper = rep(10, 2)) 26 | 27 | plotSensitivity(bayesianSetup) 28 | } 29 | \author{ 30 | Florian Hartig 31 | } 32 | -------------------------------------------------------------------------------- /BayesianTools/R/MAP.R: -------------------------------------------------------------------------------- 1 | #' calculates the Maxiumum APosteriori value (MAP) 2 | #' @author Florian Hartig 3 | #' @param bayesianOutput an object of class BayesianOutput (mcmcSampler, smcSampler, or mcmcList) 4 | #' @param ... optional values to be passed on the the getSample function 5 | #' @details Currently, this function simply returns the parameter combination with the highest posterior in the chain. A more refined option would be to take the MCMC sample and do additional calculations, e.g. use an optimizer, a kerne delnsity estimator, or some other tool to search / interpolate around the best value in the chain 6 | #' @seealso \code{\link{WAIC}}, \code{\link{DIC}}, \code{\link{marginalLikelihood}} 7 | #' @export 8 | MAP <- function(bayesianOutput, ...){ 9 | 10 | samples = getSample(bayesianOutput, parametersOnly = F, ...) 11 | 12 | if("mcmcSamplerList" %in% class(bayesianOutput)) nPars <- bayesianOutput[[1]]$setup$numPars 13 | else nPars = bayesianOutput$setup$numPars 14 | 15 | best = which.max(samples[,nPars + 1]) 16 | 17 | return(list(parametersMAP = samples[best, 1:nPars], valuesMAP = samples[best, (nPars + 1):(nPars + 3)] )) 18 | 19 | } 20 | -------------------------------------------------------------------------------- /Publications/SpeichEtAl-SMCForModelCalibration/5_launch_scripts/compare_smc_threePGN_mult1.moab: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | ########## Begin MOAB/Slurm header ########## 3 | # 4 | # Give job a reasonable name 5 | #MOAB -N smc_threePGN3 6 | # 7 | # Request number of nodes and CPU cores per node for job 8 | #MOAB -l nodes=2:ppn=20 9 | # 10 | # Estimated wallclock time for job 11 | #MOAB -l walltime=72:00:00 12 | # 13 | # Write standard output and errors in same file 14 | #MOAB -j oe 15 | # 16 | # 17 | ########### End MOAB header ########## 18 | 19 | echo "Working Directory: $PWD" 20 | echo "Running on host $HOSTNAME" 21 | echo "Job id: $MOAB_JOBID" 22 | echo "Job name: $MOAB_JOBNAME" 23 | echo "Number of nodes allocated to job: $MOAB_NODECOUNT" 24 | echo "Number of cores allocated to job: $MOAB_PROCCOUNT" 25 | 26 | # Load module 27 | module load math/R 28 | module load mpi/openmpi/2.1-intel-17.0 29 | 30 | # Start R program 31 | #mpirun -np 1 R CMD BATCH --no-save --no-restore --slave ./scripts/threePGN_SMC.r 32 | R CMD BATCH --no-save --no-restore '--args number=1' ./scripts/threePGN_SMC_mult.r -------------------------------------------------------------------------------- /BayesianTools/inst/examples/correlationPlotHelp.R: -------------------------------------------------------------------------------- 1 | ## Generate a test likelihood function. 2 | ll <- generateTestDensityMultiNormal(sigma = "no correlation") 3 | 4 | ## Create a BayesianSetup object from the likelihood 5 | ## is the recommended way of using the runMCMC() function. 6 | bayesianSetup <- createBayesianSetup(likelihood = ll, lower = rep(-10, 3), upper = rep(10, 3)) 7 | 8 | ## Finally we can run the sampler and have a look 9 | settings = list(iterations = 1000) 10 | out <- runMCMC(bayesianSetup = bayesianSetup, sampler = "DEzs", settings = settings) 11 | 12 | ## Correlation density plots: 13 | correlationPlot(out) 14 | 15 | ## additional parameters can be passed to getSample (see ?getSample for further information) 16 | ## e.g. to select which parameters to show or thinning (faster plot) 17 | correlationPlot(out, scaleCorText = FALSE, thin = 100, start = 200, whichParameters = c(1,2)) 18 | 19 | ## text to display correlation will be not scaled to the strength of the correlation 20 | correlationPlot(out, scaleCorText = FALSE) 21 | 22 | ## We can also switch the method for calculating correllations 23 | correlationPlot(out, scaleCorText = FALSE, method = "spearman") 24 | 25 | 26 | -------------------------------------------------------------------------------- /BayesianTools/man/Twalksteps.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/mcmcTwalk_helperFunctions.R 3 | \name{Twalksteps} 4 | \alias{Twalksteps} 5 | \title{Main function that is executing and evaluating the moves} 6 | \usage{ 7 | Twalksteps(case, Npar, FUN, x, Eval, x2, Eval2, at, aw, pn1) 8 | } 9 | \arguments{ 10 | \item{case}{Type of Twalk move. Either "walk", "traverse", "hop" or "blow"} 11 | 12 | \item{Npar}{number of parameters} 13 | 14 | \item{FUN}{Log posterior density} 15 | 16 | \item{x}{parameter vector of chain 1} 17 | 18 | \item{Eval}{last evaluation of x} 19 | 20 | \item{x2}{parameter vector of chain 2} 21 | 22 | \item{Eval2}{last evaluation of x} 23 | 24 | \item{at}{"traverse" move proposal parameter.} 25 | 26 | \item{aw}{"walk" move proposal parameter.} 27 | 28 | \item{pn1}{Probability determining the number of parameters that are changed.} 29 | } 30 | \description{ 31 | Main function that is executing and evaluating the moves 32 | } 33 | \references{ 34 | Christen, J. Andres, and Colin Fox. "A general purpose sampling algorithm for continuous distributions (the t-walk)." Bayesian Analysis 5.2 (2010): 263-281. 35 | } 36 | \keyword{internal} 37 | -------------------------------------------------------------------------------- /BayesianTools/tests/testthat/test-marginalLikelihood.R: -------------------------------------------------------------------------------- 1 | context("Test marginalLikelihood") 2 | 3 | skip_on_cran() 4 | 5 | ll <- function(x, sum = TRUE){ 6 | if(sum) sum(dnorm(x, log = T)) 7 | else dnorm(x, log = T) 8 | } 9 | 10 | setup <- createBayesianSetup(ll, lower = c(-10,-10,-10), upper = c(10,10,10)) 11 | settings <- list(iterations=1000) 12 | 13 | out <- runMCMC(setup) 14 | 15 | testthat::test_that("marginalLikelihood with method 'Chib' runs without error", { 16 | expect_lt(marginalLikelihood(sampler = out, method = "Chib")$ln.ML, 100) 17 | }) 18 | 19 | testthat::test_that("marginalLikelihood with method 'HM' runs without error", { 20 | expect_lt(suppressWarnings(marginalLikelihood(sampler = out, method = "HM")$ln.ML), 100) 21 | }) 22 | 23 | testthat::test_that("marginalLikelihood with method 'Bridge' runs without error", { 24 | expect_lt(suppressWarnings(marginalLikelihood(sampler = out, method = "Bridge")$ln.ML), 100) 25 | }) 26 | 27 | testthat::test_that("marginalLikelihood with method 'Prior' runs without error", { 28 | expect_lt(marginalLikelihood(sampler = out, method = "Prior")$ln.ML, 100) 29 | expect_lt(marginalLikelihood(sampler = setup, method = "Prior")$ln.ML, 100) 30 | }) 31 | 32 | -------------------------------------------------------------------------------- /BayesianTools/R/utilsFrancesco.R: -------------------------------------------------------------------------------- 1 | as_mcmc.matrix = function(x, names, par = NULL) { 2 | dimnames(x)=list(NULL, names) 3 | if (is.null(par)) { 4 | attr(x, 'mcpar') = c(1, nrow(x), 1) 5 | } else { 6 | attr(x, 'mcpar') = par 7 | } 8 | class(x) = 'mcmc' 9 | return(x) 10 | } 11 | 12 | calc_mpsrf = function(x, end) { 13 | x = window(x, start(x), end, 1) 14 | Niter = niter(x) 15 | Nchain = nchain(x) 16 | Nvar = nvar(x) 17 | x = lapply(x, as.matrix) 18 | S2 = array(sapply(x, var, simplify=TRUE), dim=c(Nvar,Nvar,Nchain)) 19 | W = apply(S2, c(1,2), mean) 20 | xbar = matrix(sapply(x, apply, 2, mean, simplify=TRUE), nrow=Nvar, ncol=Nchain) 21 | B = Niter * var(t(xbar)) 22 | CW = chol(W) 23 | emax = eigen(backsolve(CW, t(backsolve(CW, B, transpose=TRUE)), transpose=TRUE), symmetric=TRUE, only.values=TRUE)$values[1] 24 | res = sqrt( (1 - 1/Niter) + (1 + 1/Nvar) * emax/Niter ) 25 | return(res) 26 | } 27 | 28 | mpsrf = function(x, step = 50, ...) { 29 | if (nchain(x) < 2 | nvar(x) == 1) 30 | stop("You need at least two chains and two parameters.") 31 | z = seq(start(x)-1+step, end(x), by = step) 32 | res = sapply(z, function(i) calc_mpsrf(x,i)) 33 | x = data.frame(z,MPSRF = res) 34 | return(x) 35 | } -------------------------------------------------------------------------------- /BayesianTools/tests/testthat/testFunctionalities.R: -------------------------------------------------------------------------------- 1 | context("Test basic functionalities") 2 | 3 | set.seed(1) 4 | library(BayesianTools) 5 | library(testthat) 6 | 7 | 8 | settings = list(iterations = 100) 9 | ll <- function(x) sum(dnorm(x, log = T)) 10 | 11 | testFunctions <-function(x){ 12 | print(x) 13 | summary(x) 14 | plot(x) 15 | marginalPlot(x) 16 | getSample(x) 17 | DIC(x) 18 | MAP(x) 19 | getVolume(x) 20 | marginalLikelihood(x) 21 | } 22 | 23 | 24 | # 1d par, 1d / 3d sampler 25 | bayesianSetup <- createBayesianSetup(likelihood = ll, lower = rep(-10, 1), upper = rep(10, 1)) 26 | 27 | out <- runMCMC(bayesianSetup = bayesianSetup, sampler = "Metropolis", settings = settings) 28 | testFunctions(out) 29 | 30 | out <- runMCMC(bayesianSetup = bayesianSetup, sampler = "DEzs", settings = settings) 31 | testFunctions(out) 32 | 33 | 34 | # 3d par, 1d / 3d sampler 35 | bayesianSetup <- createBayesianSetup(likelihood = ll, lower = rep(-10, 3), upper = rep(10, 3)) 36 | 37 | out <- runMCMC(bayesianSetup = bayesianSetup, sampler = "Metropolis", settings = settings) 38 | testFunctions(out) 39 | 40 | out <- runMCMC(bayesianSetup = bayesianSetup, sampler = "DEzs", settings = settings) 41 | testFunctions(out) 42 | 43 | 44 | -------------------------------------------------------------------------------- /BayesianTools/man/convertCoda.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/convertCoda.R 3 | \name{convertCoda} 4 | \alias{convertCoda} 5 | \title{Convert coda::mcmc objects to BayesianTools::mcmcSampler} 6 | \usage{ 7 | convertCoda(sampler, names = NULL, info = NULL, likelihood = NULL) 8 | } 9 | \arguments{ 10 | \item{sampler}{An object of class mcmc or mcmc.list} 11 | 12 | \item{names}{vector giving the parameter names (optional)} 13 | 14 | \item{info}{matrix (or list with matrices for mcmc.list objects) with three coloumns containing log posterior, log likelihood and log prior of the sampler for each time step (optional; but see Details)} 15 | 16 | \item{likelihood}{likelihood function used in the sampling (see Details)} 17 | } 18 | \description{ 19 | Function is used to make the plot and diagnostic functions 20 | available for coda::mcmc objects 21 | } 22 | \details{ 23 | The parameter 'likelihood' is optional for most functions but can be needed e.g for 24 | using the \code{\link{DIC}} function. 25 | 26 | Also the parameter info is optional for most uses. However for some functions (e.g. \code{\link{MAP}}) 27 | the matrix or single coloumns (e.g. log posterior) are necessary for the diagnostics. 28 | } 29 | -------------------------------------------------------------------------------- /BayesianTools/R/mcmcMultipleChains.R: -------------------------------------------------------------------------------- 1 | #' Run multiple chains 2 | #' @param bayesianSetup Object of class "BayesianSetup" 3 | #' @param settings list with settings for sampler 4 | #' @param sampler character, either "Metropolis" or "DE" 5 | #' @return list containing the single runs ($sampler) and the chains in a coda::mcmc.list ($mcmc.list) 6 | #' @keywords internal 7 | mcmcMultipleChains <- function(bayesianSetup, settings, sampler) { 8 | # Get number of chains 9 | nrChains <- settings$nrChains 10 | 11 | # Set settings$nrChains to one to avoid infinite loop 12 | settings$nrChains <- 1 13 | 14 | # Initialize output 15 | out <- list() 16 | out$sampler <- list() 17 | 18 | # Run sampler 19 | for (i in 1:nrChains) { 20 | out$sampler[[i]] <- 21 | runMCMC(bayesianSetup, sampler = sampler, settings = settings) 22 | } 23 | 24 | 25 | # Make coda::mcmc.list object 26 | for (i in 1:nrChains) { 27 | txtemp <- paste("coda::mcmc(out$sampler[[", i, "]]$chain)", sep = "") 28 | if (i == 1) 29 | tx = txtemp 30 | else 31 | tx <- paste(tx, txtemp, sep = ", ") 32 | } 33 | 34 | tx <- paste("coda::mcmc.list(", tx, ")", sep = "") 35 | out$mcmc.list <- eval(parse(text = tx)) 36 | 37 | 38 | return(out) 39 | } 40 | -------------------------------------------------------------------------------- /docs/pkgdown.js: -------------------------------------------------------------------------------- 1 | $(function() { 2 | $("#sidebar").stick_in_parent({offset_top: 40}); 3 | $('body').scrollspy({ 4 | target: '#sidebar', 5 | offset: 60 6 | }); 7 | 8 | var cur_path = paths(location.pathname); 9 | $("#navbar ul li a").each(function(index, value) { 10 | if (value.text == "Home") 11 | return; 12 | if (value.getAttribute("href") === "#") 13 | return; 14 | 15 | var path = paths(value.pathname); 16 | if (is_prefix(cur_path, path)) { 17 | // Add class to parent
  • , and enclosing
  • if in dropdown 18 | var menu_anchor = $(value); 19 | menu_anchor.parent().addClass("active"); 20 | menu_anchor.closest("li.dropdown").addClass("active"); 21 | } 22 | }); 23 | }); 24 | 25 | function paths(pathname) { 26 | var pieces = pathname.split("/"); 27 | pieces.shift(); // always starts with / 28 | 29 | var end = pieces[pieces.length - 1]; 30 | if (end === "index.html" || end === "") 31 | pieces.pop(); 32 | return(pieces); 33 | } 34 | 35 | function is_prefix(needle, haystack) { 36 | if (needle.length > haystack.lengh) 37 | return(false); 38 | 39 | for (var i = 0; i < haystack.length; i++) { 40 | if (needle[i] != haystack[i]) 41 | return(false); 42 | } 43 | 44 | return(true); 45 | } 46 | -------------------------------------------------------------------------------- /BayesianTools/man/AM.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/mcmcFrancesco.R 3 | \name{AM} 4 | \alias{AM} 5 | \title{The Adaptive Metropolis Algorithm} 6 | \usage{ 7 | AM( 8 | startValue = NULL, 9 | iterations = 10000, 10 | nBI = 0, 11 | parmin = NULL, 12 | parmax = NULL, 13 | FUN, 14 | f = 1, 15 | eps = 0 16 | ) 17 | } 18 | \arguments{ 19 | \item{startValue}{vector with the start values for the algorithm. Can be NULL if FUN is of class BayesianSetup. In this case startValues are sampled from the prior.} 20 | 21 | \item{iterations}{iterations to run} 22 | 23 | \item{nBI}{number of burnin} 24 | 25 | \item{parmin}{minimum values for the parameter vector or NULL if FUN is of class BayesianSetup} 26 | 27 | \item{parmax}{maximum values for the parameter vector or NULL if FUN is of class BayesianSetup} 28 | 29 | \item{FUN}{function to be sampled from or object of class bayesianSetup} 30 | 31 | \item{f}{scaling factor} 32 | 33 | \item{eps}{small number to avoid singularity} 34 | } 35 | \description{ 36 | The Adaptive Metropolis Algorithm (Haario et al. 2001) 37 | } 38 | \references{ 39 | Haario, Heikki, Eero Saksman, and Johanna Tamminen. "An adaptive Metropolis algorithm." Bernoulli (2001): 223-242. 40 | } 41 | \author{ 42 | Francesco Minunno 43 | } 44 | \keyword{internal} 45 | -------------------------------------------------------------------------------- /BayesianTools/R/utils-Numerics.R: -------------------------------------------------------------------------------- 1 | # inspired from https://gist.github.com/doobwa/941125 2 | # maybe replace with logSumExp {matrixStats} which might be faster? 3 | 4 | #' Funktion to compute log(sum(exp(x)) 5 | #' @author Florian Hartig 6 | #' @param x values at log scale 7 | #' @param mean logical, determines whether the mean should be used instead of the sum 8 | #' @details This function computes log(sum(exp(x)), using the offset trick to avoid numeric overflow, see, e.g. http://jblevins.org/notes/log-sum-exp. The mean option allows calculating logMeanExp 9 | #' 10 | #' @keywords internal 11 | logSumExp<- function(x, mean = F) { 12 | # 13 | 14 | nObs = length(x) 15 | 16 | if(any(x == Inf)) stop("BayesianTools::logSumExp: positive infinity values in log probabilities") 17 | if(any(x == -Inf )){ 18 | message("BayesianTools::logSumExp: encountered -Inf in logSumExp - value was removed") 19 | x = x[x != -Inf] 20 | } 21 | 22 | # seems that this created problems in the presence of small values, 23 | # doesn't seem to be a need to shift towards min 24 | # if ( max(abs(x)) > max(x) ) offset <- min(x) else offset <- max(x) 25 | offset <- max(x) 26 | if (mean == T) out = log(sum(exp(x - offset))/nObs) + offset 27 | else out = log(sum(exp(x - offset))) + offset 28 | return(out) 29 | } 30 | 31 | # Unit test in test-utils-Numerics -------------------------------------------------------------------------------- /Test/BasicNormalTest.R: -------------------------------------------------------------------------------- 1 | library(BayesianTools) 2 | 3 | ll <- generateTestDensityMultiNormal(sigma = "no correlation") 4 | 5 | ll <- function(par) return(0) 6 | 7 | bayesianSetup = createBayesianSetup(likelihood = ll, lower = rep(-10, 3), upper = rep(10, 3)) 8 | 9 | 10 | 11 | settings = list(iterations = 5000, nrChains= 3, message = FALSE, startValue = list(rep(-9, 3), rep(0, 3), rep(9, 3)), optimize = F) 12 | 13 | settings <- list(iterations = iter, adapt = T, DRlevels = 2, gibbsProbabilities = NULL, temperingFunction = NULL, optimize = T,nrChains= 1,burnin=7000,adaptationInterval=10) 14 | 15 | settings <- list(iterations = 10000, adapt = T, DRlevels = 2 , gibbsProbabilities = NULL, temperingFunction = NULL, optimize = T, nrChains= 1, burnin=2000, adaptationInterval=100) 16 | 17 | out <- runMCMC(bayesianSetup = bayesianSetup, sampler = "Metropolis", settings = settings) 18 | 19 | 20 | plot(out) 21 | 22 | 23 | getSeett 24 | 25 | 26 | 27 | applySettingsDefault(sampler = "Metropolis") 28 | 29 | 30 | ll <- generateTestDensityMultiNormal(sigma = "no correlation") 31 | bayesianSetup = createBayesianSetup(likelihood = ll, lower = rep(-10, 3), upper = rep(10, 3)) 32 | settings = list(iterations = 30000) 33 | out <- runMCMC(bayesianSetup = bayesianSetup, sampler = "DEzs", settings = settings) 34 | plot(out) 35 | x = getSample(out, coda = T, thin = "auto") 36 | -------------------------------------------------------------------------------- /BayesianTools/man/DRAM.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/mcmcFrancesco.R 3 | \name{DRAM} 4 | \alias{DRAM} 5 | \title{The Delayed Rejection Adaptive Metropolis Algorithm} 6 | \usage{ 7 | DRAM( 8 | startValue = NULL, 9 | iterations = 10000, 10 | nBI = 0, 11 | parmin = NULL, 12 | parmax = NULL, 13 | FUN, 14 | f = 1, 15 | eps = 0 16 | ) 17 | } 18 | \arguments{ 19 | \item{startValue}{vector with the start values for the algorithm. Can be NULL if FUN is of class BayesianSetup. In this case startValues are sampled from the prior.} 20 | 21 | \item{iterations}{iterations to run} 22 | 23 | \item{nBI}{number of burnin} 24 | 25 | \item{parmin}{minimum values for the parameter vector or NULL if FUN is of class BayesianSetup} 26 | 27 | \item{parmax}{maximum values for the parameter vector or NULL if FUN is of class BayesianSetup} 28 | 29 | \item{FUN}{function to be sampled from} 30 | 31 | \item{f}{scaling factor} 32 | 33 | \item{eps}{small number to avoid singularity or object of class bayesianSetup} 34 | } 35 | \description{ 36 | The Delayed Rejection Adaptive Metropolis Algorithm (Haario et al. 2001) 37 | } 38 | \references{ 39 | Haario, Heikki, Eero Saksman, and Johanna Tamminen. "An adaptive Metropolis algorithm." Bernoulli (2001): 223-242. 40 | } 41 | \author{ 42 | Francesco Minunno 43 | } 44 | \keyword{internal} 45 | -------------------------------------------------------------------------------- /BayesianTools/man/DR.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/mcmcFrancesco.R 3 | \name{DR} 4 | \alias{DR} 5 | \title{The Delayed Rejection Algorithm} 6 | \usage{ 7 | DR( 8 | startValue = NULL, 9 | iterations = 10000, 10 | nBI = 0, 11 | parmin = NULL, 12 | parmax = NULL, 13 | f1 = 1, 14 | f2 = 0.5, 15 | FUN 16 | ) 17 | } 18 | \arguments{ 19 | \item{startValue}{vector with the start values for the algorithm. Can be NULL if FUN is of class BayesianSetup. In this case startValues are sampled from the prior.} 20 | 21 | \item{iterations}{iterations to run} 22 | 23 | \item{nBI}{number of burnin} 24 | 25 | \item{parmin}{minimum values for the parameter vector or NULL if FUN is of class BayesianSetup} 26 | 27 | \item{parmax}{maximum values for the parameter vector or NULL if FUN is of class BayesianSetup} 28 | 29 | \item{f1}{scaling factor for first proposal} 30 | 31 | \item{f2}{scaling factor for second proposal} 32 | 33 | \item{FUN}{function to be sampled from or object of class bayesianSetup} 34 | } 35 | \description{ 36 | The Delayed Rejection Algorithm (Tierney and Mira, 1999) 37 | } 38 | \references{ 39 | Tierney, Luke, and Antonietta Mira. "Some adaptive Monte Carlo methods for Bayesian inference." Statistics in medicine 18.1718 (1999): 2507-2515. 40 | } 41 | \author{ 42 | Francesco Minunno 43 | } 44 | \keyword{internal} 45 | -------------------------------------------------------------------------------- /BayesianTools/man/tracePlot.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/plotTrace.R 3 | \name{tracePlot} 4 | \alias{tracePlot} 5 | \title{Trace plot for MCMC class} 6 | \usage{ 7 | tracePlot(sampler, thin = "auto", ...) 8 | } 9 | \arguments{ 10 | \item{sampler}{an object of class MCMC sampler} 11 | 12 | \item{thin}{determines the thinning intervall of the chain} 13 | 14 | \item{...}{additional parameters to pass on to the \code{\link{getSample}}, for example parametersOnly =F, or start = 1000} 15 | } 16 | \description{ 17 | Trace plot for MCMC class 18 | } 19 | \examples{ 20 | # set up and run the MCMC 21 | ll <- function(x) sum(dnorm(x, log = TRUE)) 22 | setup <- createBayesianSetup(likelihood = ll, lower = c(-10, -10), upper = c(10,10)) 23 | settings <- list(iterations = 2000) 24 | out <- runMCMC(bayesianSetup = setup, settings = settings, sampler = "Metropolis") 25 | 26 | # plot the trace 27 | tracePlot(sampler = out, thin = 10) 28 | tracePlot(sampler = out, thin = 50) 29 | 30 | # additional parameters can be passed on to getSample (see help) 31 | tracePlot(sampler = out, thin = 10, start = 500) 32 | # select parameter by index 33 | tracePlot(sampler = out, thin = 10, start = 500, whichParameters = 2) 34 | } 35 | \seealso{ 36 | \code{\link{marginalPlot}} \cr 37 | \code{\link{plotTimeSeries}} \cr 38 | \code{\link{correlationPlot}} 39 | } 40 | -------------------------------------------------------------------------------- /BayesianTools/man/DIC.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/DIC.R 3 | \name{DIC} 4 | \alias{DIC} 5 | \title{Deviance information criterion} 6 | \usage{ 7 | DIC(sampler, ...) 8 | } 9 | \arguments{ 10 | \item{sampler}{An object of class bayesianOutput (mcmcSampler, smcSampler, or mcmcList)} 11 | 12 | \item{...}{further arguments passed to \code{\link{getSample}}} 13 | } 14 | \description{ 15 | Deviance information criterion 16 | } 17 | \details{ 18 | Output: 19 | list with the following elements: \cr 20 | DIC : Deviance Information Criterion \cr 21 | IC : Bayesian Predictive Information Criterion \cr 22 | pD : Effective number of parameters (pD = Dbar - Dhat) \cr 23 | pV : Effective number of parameters (pV = var(D)/2) \cr 24 | Dbar : Expected value of the deviance over the posterior \cr 25 | Dhat : Deviance at the mean posterior estimate \cr 26 | } 27 | \references{ 28 | Spiegelhalter, D. J.; Best, N. G.; Carlin, B. P. & van der Linde, A. (2002) Bayesian measures of model complexity and fit. J. Roy. Stat. Soc. B, 64, 583-639.\cr\cr 29 | Gelman, A.; Hwang, J. & Vehtari, A. (2014) Understanding predictive information criteria for Bayesian models. Statistics and Computing, Springer US, 24, 997-1016-. 30 | } 31 | \seealso{ 32 | \code{\link{WAIC}}, \code{\link{MAP}}, \code{\link{marginalLikelihood}} 33 | } 34 | \author{ 35 | Florian Hartig 36 | } 37 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .Rproj.user 2 | .Rhistory 3 | .RData 4 | 5 | BayesianTools.Rcheck/ 6 | soobench/ 7 | 8 | *.html 9 | !docs/*.html 10 | !docs/*/*.html 11 | *.gz 12 | *.dll 13 | *.DS_Store 14 | *.pdf 15 | *.rdb 16 | *.rdx 17 | *.so 18 | *.o 19 | *.log 20 | 21 | BayesianTools/examples/ForestModel/ForestModel_cache/ 22 | 23 | BayesianTools/inst/doc/QuickStart.R 24 | 25 | BayesianTools/vignettes/QuickStart_files/ 26 | 27 | BayesianTools/examples/BT-VSEM_cache/ 28 | 29 | BayesianTools/vignettes/VSEM-Calibration_files/ 30 | 31 | BayesianTools/vignettes/VSEM-Calibration_cache/ 32 | BayesianTools/vignettes/AQuickStart.R 33 | 34 | BayesianTools/inst/doc/ 35 | 36 | BayesianTools/vignettes/ReferenceManual.R 37 | 38 | BayesianTools/vignettes/ReferenceManual_files/ 39 | 40 | BayesianTools/examples/16-TG14/TG14-v2.2_cache/ 41 | 42 | BayesianTools/examples/16-TG14/TG14-v2.2_files/ 43 | examples/16-TG14/TG14-v2.2_cache/ 44 | 45 | BayesianTools/examples/Effect_catchDuplicates-Dateien/MathJax.js 46 | 47 | examples/16-TG14/TG14-v2.2_files/figure-html 48 | 49 | BayesianTools/vignettes/BayesianTools_cache 50 | BayesianTools/src/vsem.o-6bf934a9 51 | 52 | Questions/ 53 | BayesianTools/vignettes/BayesianTools.R 54 | BayesianTools/vignettes/InterfacingAModel.R 55 | BayesianTools/data-raw/.Rapp.history 56 | Publications/SpeichEtAl-SMCForModelCalibration/6_plots/data 57 | Publications/SpeichEtAl-SMCForModelCalibration/6_plots/readme_cache 58 | -------------------------------------------------------------------------------- /BayesianTools/man/M.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/mcmcFrancesco.R 3 | \name{M} 4 | \alias{M} 5 | \title{The Metropolis Algorithm} 6 | \usage{ 7 | M( 8 | startValue = NULL, 9 | iterations = 10000, 10 | nBI = 0, 11 | parmin = NULL, 12 | parmax = NULL, 13 | f = 1, 14 | FUN, 15 | consoleUpdates = 1000 16 | ) 17 | } 18 | \arguments{ 19 | \item{startValue}{vector with the start values for the algorithm. Can be NULL if FUN is of class BayesianSetup. In this case startValues are sampled from the prior.} 20 | 21 | \item{iterations}{iterations to run} 22 | 23 | \item{nBI}{number of burnin} 24 | 25 | \item{parmin}{minimum values for the parameter vector or NULL if FUN is of class BayesianSetup} 26 | 27 | \item{parmax}{maximum values for the parameter vector or NULL if FUN is of class BayesianSetup} 28 | 29 | \item{f}{scaling factor} 30 | 31 | \item{FUN}{function to be sampled from or object of class bayesianSetup} 32 | 33 | \item{consoleUpdates}{interger, determines the frequency with which sampler progress is printed to the console} 34 | } 35 | \description{ 36 | The Metropolis Algorithm (Metropolis et al. 1953) 37 | } 38 | \references{ 39 | Metropolis, Nicholas, et al. "Equation of state calculations by fast computing machines." The journal of chemical physics 21.6 (1953): 1087-1092. 40 | } 41 | \author{ 42 | Francesco Minunno 43 | } 44 | \keyword{internal} 45 | -------------------------------------------------------------------------------- /BayesianTools/man/generateTestDensityMultiNormal.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/testFunctions.R 3 | \name{generateTestDensityMultiNormal} 4 | \alias{generateTestDensityMultiNormal} 5 | \title{Multivariate normal likelihood} 6 | \usage{ 7 | generateTestDensityMultiNormal( 8 | mean = c(0, 0, 0), 9 | sigma = "strongcorrelation", 10 | sample = F, 11 | n = 1, 12 | throwErrors = -1 13 | ) 14 | } 15 | \arguments{ 16 | \item{mean}{vector with the three mean values of the distribution} 17 | 18 | \item{sigma}{either a correlation matrix, or "strongcorrelation", or "no correlation"} 19 | 20 | \item{sample}{should the function create samples} 21 | 22 | \item{n}{number of samples to create} 23 | 24 | \item{throwErrors}{parameter for test purpose. Between 0 and 1 for proportion of errors} 25 | } 26 | \description{ 27 | Generates a 3 dimensional multivariate normal likelihood function. 28 | } 29 | \details{ 30 | 3-d multivariate normal density function with mean 2,4,0 and either strong correlation (default), or no correlation. 31 | } 32 | \examples{ 33 | # sampling from the test function 34 | x = generateTestDensityMultiNormal(sample = TRUE, n = 1000)(1000) 35 | correlationPlot(x) 36 | marginalPlot(x) 37 | 38 | # generating the the density 39 | density = generateTestDensityMultiNormal(sample = FALSE) 40 | density(x[1,]) 41 | } 42 | \seealso{ 43 | \code{\link{testDensityBanana}} \cr 44 | \code{\link{testLinearModel}} 45 | } 46 | \author{ 47 | Florian Hartig 48 | } 49 | -------------------------------------------------------------------------------- /Development/testSuite.R: -------------------------------------------------------------------------------- 1 | rosenbrock <- function (x) { 2 | if(!is.matrix(x)) x <- matrix(x, ncol = length(x)) 3 | s <- rep(0, nrow(x)) 4 | for(i in 1:(ncol(x) - 1)) { 5 | s <- s + (100 * (x[,i+1] - x[,i]^2) + (x[,i] - 1)^2) 6 | } 7 | return(s) 8 | } 9 | 10 | sphere <- function(x) { 11 | if(!is.matrix(x)) x <- matrix(x, ncol = length(x)) 12 | return(apply(x^2, 1, sum)) 13 | } 14 | 15 | m <- matrix(c(1,0.99,1.01,1,1,1.01), ncol = 2) 16 | 17 | m 18 | rosenbrock(m) 19 | 20 | m2 <- matrix(c(1,2,3,1,2,3), ncol = 2) 21 | apply(m2^2, 1, sum) 22 | 23 | sphere(c(0,0,0)) 24 | 25 | # x1 <- seq(-2,2, length.out = 100) 26 | # x2 <- x1 27 | x1 <- runif(100, -3, 3) 28 | x2 <- runif(100, -3, 3) 29 | # x <- as.matrix(cbind(x1,x2)) 30 | # y <- matrix(0, nrow = length(x1), ncol = length(x2)) 31 | # for(i in 1:length(x1)) { 32 | # for(j in 1:length(x2)) { 33 | # y[i,j] <- rosenbrock(c(x1[i], x2[j])) 34 | # } 35 | # } 36 | y <- rosenbrock(as.matrix(cbind(x1, x2))) 37 | 38 | contour(x1, x2, y) 39 | 40 | ll <- function(x) { 41 | # pred <- dnorm(rosenbrock(x), 0, 0.05, log = T) 42 | pred <- 0 - rosenbrock(x)^2 43 | return(sum(pred)) 44 | } 45 | 46 | ll2 <- function(x) { 47 | # pred <- dnorm(rosenbrock(x), 0, 0.05, log = T) 48 | pred <- 0 - sphere(x)^2 49 | return(sum(pred)) 50 | } 51 | 52 | setup <- createBayesianSetup(ll2, lower = c(-10,-10), upper = c(10, 10)) 53 | settings <- list(iterations = 100000) 54 | out <- runMCMC(setup, sampler = "DEzs", settings = settings) 55 | plot(out) 56 | 57 | 58 | -------------------------------------------------------------------------------- /BayesianTools/man/TwalkMove.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/mcmcTwalk_helperFunctions.R 3 | \name{TwalkMove} 4 | \alias{TwalkMove} 5 | \title{Wrapper for step function} 6 | \usage{ 7 | TwalkMove( 8 | Npar, 9 | FUN, 10 | x, 11 | Eval, 12 | x2, 13 | Eval2, 14 | at = 6, 15 | aw = 1.5, 16 | pn1 = min(Npar, 4)/Npar, 17 | Ptrav = 0.4918, 18 | Pwalk = 0.4918, 19 | Pblow = 0.0082, 20 | Phop = 0.0082 21 | ) 22 | } 23 | \arguments{ 24 | \item{Npar}{Number of parameters} 25 | 26 | \item{FUN}{Log posterior density} 27 | 28 | \item{x}{parameter vector of chain 1} 29 | 30 | \item{Eval}{last evaluation of x} 31 | 32 | \item{x2}{parameter vector of chain 2} 33 | 34 | \item{Eval2}{last evaluation of x} 35 | 36 | \item{at}{"traverse" move proposal parameter.} 37 | 38 | \item{aw}{"walk" move proposal parameter.} 39 | 40 | \item{pn1}{Probability determining the number of parameters that are changed.} 41 | 42 | \item{Ptrav}{Move probability of "traverse" moves, default to 0.4918} 43 | 44 | \item{Pwalk}{Move probability of "walk" moves, default to 0.4918} 45 | 46 | \item{Pblow}{Move probability of "blow" moves, default to 0.0082} 47 | 48 | \item{Phop}{Move probability of "hop" moves} 49 | } 50 | \description{ 51 | Wrapper for step function 52 | } 53 | \references{ 54 | Christen, J. Andres, and Colin Fox. "A general purpose sampling algorithm for continuous distributions (the t-walk)." Bayesian Analysis 5.2 (2010): 263-281. 55 | } 56 | \keyword{internal} 57 | -------------------------------------------------------------------------------- /Examples/postHocPrior.R: -------------------------------------------------------------------------------- 1 | # This example show how to post-hoc impose a prior on a MCMC sample from a likelihood with a flat prior 2 | 3 | library(BayesianTools) 4 | 5 | # likelihood sampled with flat prior 6 | 7 | ll = function(x) sum(dnorm(x, log = TRUE)) 8 | setup = createBayesianSetup(ll, lower = c(-100,-100), upper = c(100,100)) 9 | out <- runMCMC(bayesianSetup = setup, sampler = "DEzs") 10 | summary(out) 11 | 12 | 13 | # post-hoc impose prior by rejection / sampling 14 | 15 | prior = function(x) sum(dnorm(x, log = TRUE, mean = 2)) 16 | setup2 = createBayesianSetup(prior, lower = c(-100,-100), upper = c(100,100)) 17 | 18 | out2 = smcSampler(setup2, initialParticles = getSample(out, start = 1000, numSamples = 2000), iterations = 30) 19 | 20 | plot(out2, plotPrior = F) 21 | 22 | 23 | # Alternative with MCMC and createPrior, summarizes old MCMC via multivariateNormal 24 | 25 | oldPosterior = createPriorDensity(getSample(out, start = 1000, numSamples = 2000)) 26 | prior = function(x) sum(dnorm(x, log = TRUE, mean = 5)) 27 | 28 | 29 | setup3 = createBayesianSetup(likelihood = prior, prior = oldPosterior) 30 | 31 | out3 = runMCMC(bayesianSetup = setup3) 32 | summary(out3) 33 | 34 | 35 | # should be identical to 36 | 37 | ll = function(x) sum(dnorm(x, log = TRUE)) 38 | prior = createTruncatedNormalPrior(mean = c(2,2), sd = c(1,1), lower = c(-100,-100), upper = c(100,100) ) 39 | setup = createBayesianSetup(ll, prior) 40 | out <- runMCMC(bayesianSetup = setup, sampler = "DEzs") 41 | summary(out) 42 | 43 | 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /BayesianTools/inst/examples/marginalPlotHelp.R: -------------------------------------------------------------------------------- 1 | ## Generate a test likelihood function. 2 | ll <- generateTestDensityMultiNormal(sigma = "no correlation") 3 | 4 | ## Create a BayesianSetup 5 | bayesianSetup <- createBayesianSetup(likelihood = ll, lower = rep(-10, 3), upper = rep(10, 3)) 6 | 7 | ## Finally we can run the sampler and have a look 8 | settings = list(iterations = 1000, adapt = FALSE) 9 | out <- runMCMC(bayesianSetup = bayesianSetup, sampler = "Metropolis", settings = settings) 10 | 11 | marginalPlot(out, prior = TRUE) 12 | 13 | ## We can plot the marginals in several ways: 14 | ## violin plots 15 | marginalPlot(out, type = 'v', singlePanel = TRUE) 16 | marginalPlot(out, type = 'v', singlePanel = FALSE) 17 | marginalPlot(out, type = 'v', singlePanel = TRUE, prior = TRUE) 18 | 19 | ## density plot 20 | marginalPlot(out, type = 'd', singlePanel = TRUE) 21 | marginalPlot(out, type = 'd', singlePanel = FALSE) 22 | marginalPlot(out, type = 'd', singlePanel = TRUE, prior = TRUE) 23 | 24 | ## if you have a very wide prior you can use the xrange option to plot only 25 | ## a certain parameter range 26 | marginalPlot(out, type = 'v', singlePanel = TRUE, xrange = matrix(rep(c(-5, 5), 3), ncol = 3)) 27 | 28 | ##Further options 29 | # We can pass arguments to getSample (check ?getSample) and to the density and violin plots 30 | marginalPlot(out, type = 'v', singlePanel = TRUE, 31 | settings = list(col = c('#FC006299','#00BBAA88')), prior = TRUE) 32 | marginalPlot(out, type = 'v', singlePanel = TRUE, numSamples = 500) 33 | -------------------------------------------------------------------------------- /BayesianTools/man/getPredictiveIntervals.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/mcmcConfidence.R 3 | \name{getPredictiveIntervals} 4 | \alias{getPredictiveIntervals} 5 | \title{Calculates Bayesian credible (confidence) and predictive intervals based on parameter sample} 6 | \usage{ 7 | getPredictiveIntervals( 8 | parMatrix, 9 | model, 10 | numSamples = 1000, 11 | quantiles = c(0.025, 0.975), 12 | error = NULL 13 | ) 14 | } 15 | \arguments{ 16 | \item{parMatrix}{matrix of parameter values} 17 | 18 | \item{model}{model / function to calculate predictions. Outcome should be a vector} 19 | 20 | \item{numSamples}{number of samples to be drawn} 21 | 22 | \item{quantiles}{quantiles to calculate} 23 | 24 | \item{error}{function with signature f(mean, par) that generates error expectations from mean model predictions. Par is a vector from the matrix with the parameter samples (full length). f needs to know which of these parameters are parameters of the error function. If supplied, will calculate also predictive intervals additional to credible intervals} 25 | } 26 | \description{ 27 | Calculates Bayesian credible (confidence) and predictive intervals based on parameter sample 28 | } 29 | \details{ 30 | If numSamples is greater than the number of rows in parMatrix, or NULL, or FALSE, or less than 1 all samples in parMatrix will be used. 31 | } 32 | \seealso{ 33 | \code{\link{getPredictiveDistribution}} \cr 34 | \code{\link{getCredibleIntervals}} \cr 35 | } 36 | \author{ 37 | Florian Hartig 38 | } 39 | -------------------------------------------------------------------------------- /BayesianTools/tests/testthat/test-tracePlot.R: -------------------------------------------------------------------------------- 1 | testthat::context("Test tracePlot") 2 | 3 | skip_on_cran() 4 | 5 | ll <- generateTestDensityMultiNormal(sigma = "no correlation") 6 | 7 | bayesianSetup <- createBayesianSetup(likelihood = ll, lower = c(-10, -5, -7.5), upper = c(10, 7.5, 3)) 8 | 9 | settings = list(iterations = 2000, nrChains=2) 10 | 11 | out_1 <- runMCMC(bayesianSetup = bayesianSetup, sampler = "Metropolis", settings = list(iterations=2000)) 12 | out_2 <- runMCMC(bayesianSetup = bayesianSetup, sampler = "Metropolis", settings = settings) 13 | out_3 <- runMCMC(bayesianSetup = bayesianSetup, sampler = "DEzs", settings = settings) 14 | 15 | coda_1 <- getSample(out_1, coda = T) 16 | coda_2 <- getSample(out_2, coda = T) 17 | coda_3 <- getSample(out_3, coda = T) 18 | 19 | mat_1 <- getSample(out_1, coda = F) 20 | mat_2 <- getSample(out_2, coda = F) 21 | mat_3 <- getSample(out_3, coda = F) 22 | 23 | 24 | testthat::test_that("tracePlot works for bayesianOutput", { 25 | testthat::expect_error(tracePlot(out_1), NA) 26 | testthat::expect_error(tracePlot(out_2), NA) 27 | testthat::expect_error(tracePlot(out_3), NA) 28 | }) 29 | 30 | testthat::test_that("tracePlot works for coda", { 31 | testthat::expect_error(tracePlot(coda_1), NA) 32 | testthat::expect_error(tracePlot(coda_2), NA) 33 | testthat::expect_error(tracePlot(coda_3), NA) 34 | }) 35 | 36 | testthat::test_that("tracePlot works for matrix", { 37 | testthat::expect_error(tracePlot(coda_1), NA) 38 | testthat::expect_error(tracePlot(coda_2), NA) 39 | testthat::expect_error(tracePlot(coda_3), NA) 40 | }) -------------------------------------------------------------------------------- /Test/BasicBTTest.R: -------------------------------------------------------------------------------- 1 | library(BayesianTools) 2 | 3 | PAR <- VSEMcreatePAR(1:1000) 4 | plotTimeSeries(observed = PAR) 5 | 6 | 7 | refPars$upper = refPars$upper * 10 8 | 9 | refPars <- VSEMgetDefaults() 10 | refPars[12,] <- c(0.1, 0.001, 0.5) 11 | rownames(refPars)[12] <- "error-sd" 12 | head(refPars) 13 | 14 | referenceData <- VSEM(refPars$best[1:11], PAR) 15 | referenceData[,1] = 1000 * referenceData[,1] 16 | obs <- referenceData + rnorm(length(referenceData), sd = refPars$best[12]) 17 | oldpar <- par(mfrow = c(2,2)) 18 | for (i in 1:4) plotTimeSeries(observed = obs[,i], predicted = referenceData[,i], main = colnames(referenceData)[i]) 19 | 20 | 21 | parSel = c(1:12) 22 | 23 | likelihood <- function(x, sum = TRUE){ 24 | mix = refPars$best 25 | mix[parSel] = x 26 | predicted <- VSEM(mix[1:11], PAR) 27 | predicted[,1] = 1000 * predicted[,1] 28 | diff <- c(predicted[,1:4] - obs[,1:4]) 29 | llValues <- dnorm(diff, sd = mix[12], log = T) 30 | # if(runif(1) < 0.4) stop() 31 | if (sum == FALSE) return(llValues) 32 | else return(sum(llValues)) 33 | } 34 | 35 | 36 | prior <- createUniformPrior(lower = refPars$lower[parSel], upper = refPars$upper[parSel], best = refPars$best[parSel]) 37 | 38 | 39 | bayesianSetup <- createBayesianSetup(likelihood, prior, names = rownames(refPars)[parSel]) 40 | 41 | 42 | settings <- list(iterations = 10000, nrChains = 3) 43 | out <- runMCMC(bayesianSetup = bayesianSetup, sampler = "DREAMzs", settings = settings) 44 | 45 | 46 | x = getSample(out, start = 1000, end = 2000) 47 | 48 | 49 | 50 | plot(out) 51 | summary(out) 52 | 53 | -------------------------------------------------------------------------------- /BayesianTools/tests/testthat/test-infinity.R: -------------------------------------------------------------------------------- 1 | # context("Test samplers on likelihoods with infinities") 2 | # 3 | # 4 | # bayesianSetup = createBayesianSetup(likelihood = testDensityInfinity, lower = c(0, 0), upper = c(5, 5)) 5 | # 6 | # iter = 10000 7 | # start = 500 8 | # iterSMC = 400 9 | # 10 | # test_that("sampler work correct for likelihoods with infinities", { 11 | # 12 | # skip_on_cran() 13 | # 14 | # samp = getPossibleSamplerTypes() 15 | # 16 | # for(i in 1:length(samp$BTname)){ 17 | # # print(samp$BTname[i]) # Printing to console makes tests extremely slow 18 | # if(samp$univariatePossible[i] == T){ 19 | # settings = list(iterations = iter, consoleUpdates = 1e+8) 20 | # if(samp$BTname[i] == "SMC") settings = list(iterations = iterSMC, consoleUpdates = 1e+8) 21 | # invisible(capture.output(suppressMessages(out <- runMCMC(bayesianSetup = setup, sampler = samp$BTname[i], settings = settings)))) 22 | # 23 | # } 24 | # # plot(out) 25 | # # summary(out) 26 | # # marginalPlot(out) 27 | # # correlationPlot(out) 28 | # # DIC(out) 29 | # # marginalLikelihood(out) 30 | # 31 | # # x = getSample(out, numSamples = 10000) 32 | # # y <- rnorm(10000) ## TODO change 33 | # # for(z in 1:ncol(x)){ 34 | # # 35 | # # # ks <- ks.test(x[,z], pnorm)$p.value 36 | # # 37 | # # ks <- ks.boot(x[,z], y)$ks.boot.pvalue 38 | # # 39 | # # # Test that distribution is not significally different from gaussian 40 | # # expect_true(ks>0.05) 41 | # # 42 | # # } 43 | # 44 | # } 45 | # } 46 | # ) 47 | -------------------------------------------------------------------------------- /BayesianTools/src/vsem.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace Rcpp; 3 | 4 | // Below is a simple example of exporting a C++ function to R. You can 5 | // source this function into an R session using the Rcpp::sourceCpp 6 | // function (or via the Source button on the editor toolbar) 7 | 8 | // For more on using Rcpp click the Help button on the editor toolbar 9 | 10 | //' C version of the VSEM model 11 | //' @param par parameter vector 12 | //' @param PAR Photosynthetically active radiation (PAR) MJ /m2 /day 13 | //' @export 14 | // [[Rcpp::export]] 15 | NumericMatrix vsemC(NumericVector par, NumericVector PAR){ 16 | 17 | int numObs = PAR.size(); 18 | 19 | // Parameter definitions 20 | 21 | double KEXT = par[0]; 22 | double LAR = par[1]; 23 | double LUE = par[2]; 24 | double GAMMA = par[3]; 25 | double tauV = par[4]; 26 | double tauS = par[5]; 27 | double tauR = par[6]; // 1440; 28 | double Av = par[7]; //0.5; 29 | double Cv = par[8]; //3.0; 30 | double Cs = par[9]; //15; 31 | double Cr = par[10]; //3.0r; 32 | double G; 33 | double NEE; 34 | double NPP; 35 | 36 | NumericMatrix out(numObs, 4); 37 | 38 | for (int i = 0; i < numObs; ++i){ 39 | G = PAR[i] * LUE * (1 - exp(-KEXT*LAR*Cv)) ; 40 | NPP = (1-GAMMA)*G; 41 | Cv = Cv + Av*NPP - Cv/tauV; 42 | Cr = Cr + (1.0-Av)*NPP - Cr/tauR; 43 | Cs = Cs + Cr/tauR + Cv/tauV - Cs/tauS; 44 | NEE = (Cs/tauS + GAMMA*G) - G; 45 | out(i,0) = NEE; 46 | out(i,1) = Cv; 47 | out(i,2) = Cs; 48 | out(i,3) = Cr; 49 | } 50 | 51 | return out; 52 | } -------------------------------------------------------------------------------- /Publications/SpeichEtAl-SMCForModelCalibration/1_reference_MCMC/threePGN_gen_ref.r: -------------------------------------------------------------------------------- 1 | library(BayesianTools) 2 | library(threePGN) 3 | 4 | ################# 5 | # Generate reference data 6 | set.seed(123) 7 | 8 | firstRun <- r3pgn(siteData = data_site[1:3,], climate = data_climate, parameters = data_param[,2], outputs = c(1:5, 10:12, 26:27)) 9 | 10 | 11 | ref.ba <- firstRun$output[,,1][,3] + rnorm(nrow(firstRun$output[,,1]), sd=1) 12 | ref.gpp <- firstRun$output[,,1][,9] + rnorm(nrow(firstRun$output[,,1]), sd=1) 13 | 14 | ################# 15 | # Create Bayesian setup 16 | 17 | ref.pars <- c(data_param$mode, 1, 1) 18 | min.pars <- c(data_param$min, 0.2, 0.2) 19 | max.pars <- c(data_param$max, 2, 2) 20 | 21 | ##### Likelihood function 22 | likelihood <- function(ref.pars){ 23 | 24 | library(threePGN) 25 | pgrun <- r3pgn(siteData = data_site[1:3,], climate = data_climate, parameters = ref.pars[1:51], outputs = c(1:5,10:12, 26:27)) 26 | sim.ba <- pgrun$output[,,1][,3] 27 | sim.gpp <- pgrun$output[,,1][,9] 28 | 29 | like <- sum(dnorm(ref.ba-sim.ba, sd=ref.pars[52], log=TRUE)) + sum(dnorm(ref.gpp-sim.gpp, sd=ref.pars[53], log=TRUE)) 30 | return(like) 31 | } 32 | 33 | 34 | ##### Prior and setup 35 | prior <- createUniformPrior(lower = min.pars, upper = max.pars) 36 | pgSetup <- createBayesianSetup(likelihood = likelihood, prior = prior, parallel = FALSE) 37 | 38 | reference <- runMCMC(pgSetup, sampler = "DEzs", settings = list(nrChains=3, iterations = 2000000, thin=100)) 39 | save.list <- list(ref.ba, ref.gpp, reference) 40 | save(save.list, file = "./out/reference_threePGN_list.RData") -------------------------------------------------------------------------------- /BayesianTools/man/createLikelihood.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/classLikelihood.R 3 | \name{createLikelihood} 4 | \alias{createLikelihood} 5 | \title{Creates a standardized likelihood class#'} 6 | \usage{ 7 | createLikelihood( 8 | likelihood, 9 | names = NULL, 10 | parallel = F, 11 | catchDuplicates = T, 12 | sampler = NULL, 13 | parallelOptions = NULL 14 | ) 15 | } 16 | \arguments{ 17 | \item{likelihood}{Log likelihood density} 18 | 19 | \item{names}{Parameter names (optional)} 20 | 21 | \item{parallel}{parallelization , either i) no parallelization --> F, ii) native R parallelization --> T / "auto" will select n-1 of your available cores, or provide a number for how many cores to use, or iii) external parallelization --> "external". External means that the likelihood is already able to execute parallel runs in form of a matrix with} 22 | 23 | \item{catchDuplicates}{Logical, determines whether unique parameter combinations should only be evaluated once. Only used when the likelihood accepts a matrix with parameter as columns.} 24 | 25 | \item{sampler}{sampler} 26 | 27 | \item{parallelOptions}{list containing two lists. First "packages" determines the R packages necessary to run the likelihood function. Second "objects" the objects in the global envirnment needed to run the likelihood function (for details see \code{\link{createBayesianSetup}}).} 28 | } 29 | \description{ 30 | Creates a standardized likelihood class#' 31 | } 32 | \seealso{ 33 | \code{\link{likelihoodIidNormal}} \cr 34 | \code{\link{likelihoodAR1}} \cr 35 | } 36 | \author{ 37 | Florian Hartig 38 | } 39 | -------------------------------------------------------------------------------- /BayesianTools/tests/testthat/test-settingsDefault.R: -------------------------------------------------------------------------------- 1 | context("Test Settings Default") 2 | 3 | skip_on_cran() 4 | skip_on_ci() 5 | 6 | set.seed(1) 7 | library(BayesianTools) 8 | 9 | test_that("Default works in principle",{ 10 | settings <- list(iterations = 20000, adapt = T, DRlevels = 2, optimize = T, burnin=1000, adaptationInterval=10) 11 | x = applySettingsDefault(settings = settings, sampler = "Metropolis", check = FALSE) 12 | expect_type(x, "list") 13 | applySettingsDefault(settings = settings, sampler = "Metropolis", check = TRUE) 14 | } 15 | ) 16 | 17 | 18 | 19 | test_that("Wrong inputs are caught",{ 20 | skip_on_cran() 21 | 22 | ##################### 23 | # Adaptation before burnin 24 | 25 | settings <- list(iterations = 20000, adapt = T, DRlevels = 2, optimize = T, burnin=7000, adaptationInterval=10) 26 | 27 | expect_error({ 28 | # default adaptation is 3000, so the burnin is larger than that, should throw error 29 | applySettingsDefault(settings = settings, sampler = "Metropolis") 30 | }) 31 | 32 | # should not throw an error if the sampler doesn't adapt 33 | applySettingsDefault(settings = settings, sampler = "DE") 34 | 35 | 36 | ##################### 37 | # Burnin larger than iterations 38 | 39 | settings <- list(iterations = 2000, adapt = T, DRlevels = 2, optimize = T, burnin=2500, adaptationInterval=10) 40 | 41 | expect_error( applySettingsDefault(settings = settings, sampler = "Metropolis") ) 42 | expect_error( applySettingsDefault(settings = settings, sampler = "DE") ) 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | } 52 | ) 53 | 54 | 55 | 56 | -------------------------------------------------------------------------------- /BayesianTools/R/getVolume.R: -------------------------------------------------------------------------------- 1 | #' Calculate posterior volume 2 | #' @author Florian Hartig 3 | #' @param sampler an object of superclass bayesianOutput or any other class that has the getSample function implemented (e.g. Matrix) 4 | #' @param prior schould also prior volume be calculated 5 | #' @param method method for volume estimation. Currently, the only option is "MVN" 6 | #' @param ... additional parameters to pass on to the \code{\link{getSample}} 7 | #' @details The idea of this function is to provide an estimate of the "posterior volume", i.e. how "broad" the posterior is. One potential application is to the overall reduction of parametric uncertainty between different data types, or between prior and posterior. 8 | #' 9 | #' Implemented methods for volume estimation: 10 | #' 11 | #' Option "MVN" - in this option, the volume is calculated as the determinant of the covariance matrix of the prior / posterior sample. 12 | #' 13 | #' @example /inst/examples/getVolume.R 14 | #' @export 15 | getVolume <- function(sampler, prior = F, method = "MVN", ...){ 16 | 17 | x = getSample(sampler, ...) 18 | 19 | if(method == "MVN"){ 20 | nPars = ncol(x) 21 | postVol = det(cov(x)) 22 | }else stop("BayesianTools: unknown method argument in getVolume") 23 | 24 | if(prior == T){ 25 | x = sampler$setup$prior$sampler(5000) 26 | 27 | if(method == "MVN"){ 28 | nPars = ncol(x) 29 | priorVol = det(cov(x)) 30 | }else stop("BayesianTools: unknown method argument in getVolume") 31 | return(list(priorVol = priorVol, postVol = postVol)) 32 | }else return(postVol) 33 | } 34 | 35 | 36 | -------------------------------------------------------------------------------- /BayesianTools/man/checkBayesianSetup.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/classBayesianSetup.R 3 | \name{checkBayesianSetup} 4 | \alias{checkBayesianSetup} 5 | \title{Checks if an object is of class 'BayesianSetup'} 6 | \usage{ 7 | checkBayesianSetup(bayesianSetup, parallel = F) 8 | } 9 | \arguments{ 10 | \item{bayesianSetup}{either object of class bayesianSetup or a log posterior function} 11 | 12 | \item{parallel}{if bayesianSetup is a function, this will set the parallelization option for the class BayesianSetup that is created internally. If bayesianSetup is already a BayesianSetup, then this will check if parallel = T is requested but not supported by the BayesianSetup. This option is for internal use in the samplers} 13 | } 14 | \description{ 15 | Function used to assure that an object is of class 'BayesianSetup'. If you pass a function, it is coverted to an object of class 'BayesianSetup' (using \code{\link{createBayesianSetup}}) before it is returned. 16 | } 17 | \note{ 18 | The recommended option to use this function in the samplers is to have parallel with default NULL in the samplers, so that checkBayesianSetup with a function will create a bayesianSetup without parallelization, while it will do nothing with an existing BayesianSetup. If the user sets parallelization, it will set the approriate parallelization for a function, and check in case of an existing BayesianSetup. The checkBayesianSetup call in the samplers should then be followed by a check for parallel = NULL in sampler, in which case paralell can be set from the BayesianSetup 19 | } 20 | \seealso{ 21 | \code{\link{createBayesianSetup}} 22 | } 23 | \author{ 24 | Florian Hartig 25 | } 26 | -------------------------------------------------------------------------------- /Publications/SpeichEtAl-SMCForModelCalibration/4_parallelization/test_parallel_1_20ms.r: -------------------------------------------------------------------------------- 1 | arg <- commandArgs(TRUE) 2 | number <- eval(parse(text = arg)) 3 | 4 | library(BayesianTools) 5 | library(threePGN) 6 | 7 | # Load saved (synthetic) data and reference MCMC output (reference is not needed here, only BA and GPP) 8 | load("./out/reference_threePGN_list.RData") 9 | # Use only sample from reference; delete reference to free memory 10 | ref.sample <- getSample(save.list[[3]], start = 3333) 11 | ref.ba <- save.list[[1]] 12 | ref.gpp <- save.list[[2]] 13 | rm(save.list) 14 | 15 | 16 | ref.pars <- c(data_param$mode, 1, 1) 17 | min.pars <- c(data_param$min, 0.2, 0.2) 18 | max.pars <- c(data_param$max, 2, 2) 19 | 20 | out.file <- paste0("/home/fr/fr_fr/fr_ms1719/out/test_parallel/out", number ,"/1core.txt") 21 | 22 | 23 | 24 | #### Sleep 20ms 25 | likelihood <- function(ref.pars){ 26 | 27 | library(threePGN) 28 | pgrun <- r3pgn(siteData = data_site[1:3,], climate = data_climate, parameters = ref.pars[1:51], outputs = c(1:5,10:12, 26:27)) 29 | sim.ba <- pgrun$output[,,1][,3] 30 | sim.gpp <- pgrun$output[,,1][,9] 31 | 32 | like <- sum(dnorm(ref.ba-sim.ba, sd=ref.pars[52], log=TRUE)) + sum(dnorm(ref.gpp-sim.gpp, sd=ref.pars[53], log=TRUE)) 33 | Sys.sleep(0.02) 34 | return(like) 35 | } 36 | 37 | prior <- createUniformPrior(lower = min.pars, upper = max.pars) 38 | pgSetup <- createBayesianSetup(likelihood = likelihood, prior = prior, parallel = FALSE) 39 | 40 | time <- system.time(smc <- smcSampler(bayesianSetup = pgSetup, initialParticles = 50000, ess.limit = 50000 * 0.9, mutate.method = "DE", proposalScale = 0.1, resamplingSteps = 30))[3] 41 | 42 | cat("\n", file=out.file, append=TRUE) 43 | cat(c("sleep20ms", time), file = out.file, append = TRUE) 44 | -------------------------------------------------------------------------------- /Publications/SpeichEtAl-SMCForModelCalibration/4_parallelization/test_parallel_1_50ms.r: -------------------------------------------------------------------------------- 1 | arg <- commandArgs(TRUE) 2 | number <- eval(parse(text = arg)) 3 | 4 | library(BayesianTools) 5 | library(threePGN) 6 | 7 | # Load saved (synthetic) data and reference MCMC output (reference is not needed here, only BA and GPP) 8 | load("./out/reference_threePGN_list.RData") 9 | # Use only sample from reference; delete reference to free memory 10 | ref.sample <- getSample(save.list[[3]], start = 3333) 11 | ref.ba <- save.list[[1]] 12 | ref.gpp <- save.list[[2]] 13 | rm(save.list) 14 | 15 | 16 | ref.pars <- c(data_param$mode, 1, 1) 17 | min.pars <- c(data_param$min, 0.2, 0.2) 18 | max.pars <- c(data_param$max, 2, 2) 19 | 20 | out.file <- paste0("/home/fr/fr_fr/fr_ms1719/out/test_parallel/out", number ,"/1core.txt") 21 | 22 | 23 | 24 | #### Sleep 50ms 25 | likelihood <- function(ref.pars){ 26 | 27 | library(threePGN) 28 | pgrun <- r3pgn(siteData = data_site[1:3,], climate = data_climate, parameters = ref.pars[1:51], outputs = c(1:5,10:12, 26:27)) 29 | sim.ba <- pgrun$output[,,1][,3] 30 | sim.gpp <- pgrun$output[,,1][,9] 31 | 32 | like <- sum(dnorm(ref.ba-sim.ba, sd=ref.pars[52], log=TRUE)) + sum(dnorm(ref.gpp-sim.gpp, sd=ref.pars[53], log=TRUE)) 33 | Sys.sleep(0.05) 34 | return(like) 35 | } 36 | 37 | prior <- createUniformPrior(lower = min.pars, upper = max.pars) 38 | pgSetup <- createBayesianSetup(likelihood = likelihood, prior = prior, parallel = FALSE) 39 | 40 | time <- system.time(smc <- smcSampler(bayesianSetup = pgSetup, initialParticles = 50000, ess.limit = 50000 * 0.9, mutate.method = "DE", proposalScale = 0.1, resamplingSteps = 30))[3] 41 | 42 | cat("\n", file=out.file, append=TRUE) 43 | cat(c("sleep50ms", time), file = out.file, append = TRUE) 44 | -------------------------------------------------------------------------------- /BayesianTools/R/codaFunctions.R: -------------------------------------------------------------------------------- 1 | #' Function to combine chains 2 | #' 3 | #' @param x a list of MCMC chains 4 | #' @param merge logical determines whether chains should be merged 5 | #' @return combined chains 6 | #' 7 | #' @note to combine several chains to a single McmcSamplerList, see \code{\link{createMcmcSamplerList}} 8 | #' 9 | #' @keywords internal 10 | combineChains <- function(x, merge = T){ 11 | 12 | if(merge == T){ 13 | temp1 = as.matrix(x[[1]]) 14 | 15 | names = colnames(temp1) 16 | 17 | sel = seq(1, by = length(x), len = nrow(temp1) ) 18 | 19 | out = matrix(NA, nrow = length(x) * nrow(temp1), ncol = ncol(temp1)) 20 | out[sel, ] = temp1 21 | if (length(x) > 1){ 22 | for (i in 2:length(x)){ 23 | out[sel+i-1, ] = as.matrix(x[[i]]) 24 | } 25 | } 26 | 27 | colnames(out) = names 28 | 29 | } else{ 30 | 31 | out = as.matrix(x[[1]]) 32 | if (length(x) > 1){ 33 | for (i in 2:length(x)){ 34 | out = rbind(out, as.matrix(x[[i]])) 35 | } 36 | } 37 | } 38 | 39 | return(out) 40 | } 41 | 42 | 43 | 44 | #' Helper function to change an object to a coda mcmc class, 45 | #' 46 | #' @param chain mcmc Chain 47 | #' @param start for mcmc samplers start value in the chain. For SMC samplers, start particle 48 | #' @param end for mcmc samplers end value in the chain. For SMC samplers, end particle 49 | #' @param thin thinning parameter 50 | #' @return object of class coda::mcmc 51 | #' @details Very similar to coda::mcmc but with less overhead 52 | #' @keywords internal 53 | makeObjectClassCodaMCMC <- function (chain, start = 1, end = numeric(0), thin = 1){ 54 | attr(chain, "mcpar") <- c(start, end, thin) 55 | attr(chain, "class") <- "mcmc" 56 | chain 57 | } 58 | 59 | 60 | -------------------------------------------------------------------------------- /BayesianTools/DESCRIPTION: -------------------------------------------------------------------------------- 1 | Package: BayesianTools 2 | Title: General-Purpose MCMC and SMC Samplers and Tools for Bayesian Statistics 3 | Version: 0.1.8 4 | Date: 2023-01-30 5 | Authors@R: c(person("Florian", "Hartig", email = "florian.hartig@biologie.uni-regensburg.de", role = c("aut", "cre"), comment=c(ORCID="0000-0002-6255-9059")), person("Francesco", "Minunno", role = c("aut")), person("Stefan", " Paul", role = c("aut") ), person("David", "Cameron", role = "ctb"), person("Tankred", "Ott", role = "ctb"), person("Maximilian", "Pichler", role = "ctb")) 6 | Description: General-purpose MCMC and SMC samplers, as well as plots and 7 | diagnostic functions for Bayesian statistics, with a particular focus on 8 | calibrating complex system models. Implemented samplers include various 9 | Metropolis MCMC variants (including adaptive and/or delayed rejection MH), the 10 | T-walk, two differential evolution MCMCs, two DREAM MCMCs, and a sequential 11 | Monte Carlo (SMC) particle filter. 12 | Depends: 13 | R (>= 3.1.2) 14 | License: GPL-3 15 | Imports: 16 | coda, 17 | emulator, 18 | mvtnorm, 19 | tmvtnorm, 20 | IDPmisc, 21 | Rcpp (>= 0.12.12), 22 | ellipse, 23 | numDeriv, 24 | msm, 25 | MASS, 26 | Matrix, 27 | stats, 28 | utils, 29 | graphics, 30 | DHARMa, 31 | gap, 32 | bridgesampling 33 | Suggests: 34 | DEoptim, 35 | lhs, 36 | sensitivity, 37 | knitr, 38 | rmarkdown, 39 | roxygen2, 40 | testthat 41 | LinkingTo: Rcpp 42 | Roxygen: list(markdown = TRUE) 43 | RoxygenNote: 7.2.1 44 | URL: https://github.com/florianhartig/BayesianTools, https://florianhartig.github.io/BayesianTools/ 45 | BugReports: https://github.com/florianhartig/BayesianTools/issues 46 | VignetteBuilder: knitr 47 | Encoding: UTF-8 48 | -------------------------------------------------------------------------------- /BayesianTools/inst/examples/DEfamilyHelp.R: -------------------------------------------------------------------------------- 1 | library(BayesianTools) 2 | 3 | ll <- generateTestDensityMultiNormal(sigma = "no correlation") 4 | bayesianSetup <- createBayesianSetup(likelihood = ll, 5 | lower = rep(-10, 3), 6 | upper = rep(10, 3)) 7 | 8 | settings = list(iterations = 200) 9 | out <- runMCMC(bayesianSetup = bayesianSetup, sampler = "DEzs", settings = settings) 10 | summary(out) 11 | 12 | # DE family samplers are population MCMCs that run a number of internal chains 13 | # in parallel. Here examples how to change the internal chains 14 | # note that internal chains can be executedi n parallel 15 | settings = list(startValue = 4, iterations = 200) 16 | out <- runMCMC(bayesianSetup = bayesianSetup, sampler = "DEzs", settings = settings) 17 | summary(out) 18 | 19 | # Modify the start values of the internal chains (note that this is a matrix 20 | # of dim nChain * nPar) 21 | settings = list(startValue = matrix(rnorm(12), nrow = 4, ncol = 3), 22 | iterations = 200) 23 | out <- runMCMC(bayesianSetup = bayesianSetup, sampler = "DEzs", settings = settings) 24 | summary(out) 25 | 26 | # In the DE sampler family with Z matrix, the previous chains are written in 27 | # a common matrix, from which proposals are generated. Per default this matrix 28 | # is started with samples from the prior, but we can change this. Often useful 29 | # to improve sampler convergence, 30 | # see https://github.com/florianhartig/BayesianTools/issues/79 31 | settings = list(startValue = matrix(rnorm(12), nrow = 4, ncol = 3), 32 | Z = matrix(rnorm(300), nrow = 100, ncol = 3), 33 | iterations = 200) 34 | out <- runMCMC(bayesianSetup = bayesianSetup, sampler = "DEzs", settings = settings) 35 | summary(out) 36 | 37 | 38 | -------------------------------------------------------------------------------- /BayesianTools/tests/testthat/test-marginalPlot.R: -------------------------------------------------------------------------------- 1 | testthat::context("Test marginalPlot") 2 | 3 | testthat::skip_on_cran() 4 | testthat::skip_on_ci() 5 | 6 | testMarginalPlot <- function (x, priorSample) { 7 | 8 | marginalPlot(x, type = 'v', singlePanel = F) 9 | marginalPlot(x, type = 'v', singlePanel = T) 10 | marginalPlot(x, type = 'd', singlePanel = F) 11 | marginalPlot(x, type = 'd', singlePanel = T) 12 | 13 | marginalPlot(x, type = 'v', singlePanel = F, prior = F) 14 | marginalPlot(x, type = 'v', singlePanel = F, prior = T) 15 | marginalPlot(x, type = 'v', singlePanel = F, prior = priorSample) 16 | 17 | expect_error(marginalPlot(x, type = 'v', singlePanel = F, prior = c(1,2))) 18 | } 19 | 20 | setup <- createBayesianSetup(likelihood = testDensityNormal, 21 | lower = c(-10,-10,-10), upper = c(10,10,10)) 22 | settings <- list(iterations=10000) 23 | 24 | out <- runMCMC(setup) 25 | 26 | marginalPlot(out) 27 | marginalPlot(out, which = 1:2) 28 | 29 | 30 | 31 | 32 | out_mat <- suppressWarnings(getSample(out, numSamples = 10000)) 33 | out_coda <- suppressWarnings(getSample(out, numSamples = 10000, coda = T)) 34 | 35 | priorSample = setup$prior$sampler(10000) 36 | 37 | testthat::test_that("marginalPlot runs without throwing an error (bayesianOutput)", testMarginalPlot(out, priorSample)) 38 | testthat::test_that("marginalPlot runs without throwing an error (matrix)", testMarginalPlot(out_mat, priorSample)) 39 | testthat::test_that("marginalPlot runs without throwing an error (data.frame)", testMarginalPlot(data.frame(out_mat), priorSample)) 40 | testthat::test_that("marginalPlot runs without throwing an error (coda)", testMarginalPlot(out_coda, priorSample)) 41 | 42 | marginalPlot(out, type = "d", xrange = c(0,1)) 43 | marginalPlot(out, type = "d", prior = F) 44 | 45 | 46 | -------------------------------------------------------------------------------- /BayesianTools/man/plotTimeSeries.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/plotTimeSeries.R 3 | \name{plotTimeSeries} 4 | \alias{plotTimeSeries} 5 | \title{Plots a time series, with the option to include confidence and prediction band} 6 | \usage{ 7 | plotTimeSeries( 8 | observed = NULL, 9 | predicted = NULL, 10 | x = NULL, 11 | confidenceBand = NULL, 12 | predictionBand = NULL, 13 | xlab = "Time", 14 | ylab = "Observed / predicted values", 15 | ... 16 | ) 17 | } 18 | \arguments{ 19 | \item{observed}{observed values} 20 | 21 | \item{predicted}{predicted values} 22 | 23 | \item{x}{optional values for x axis (time)} 24 | 25 | \item{confidenceBand}{matrix with confidenceBand} 26 | 27 | \item{predictionBand}{matrix with predictionBand} 28 | 29 | \item{xlab}{a title for the x axis} 30 | 31 | \item{ylab}{a title for the y axis} 32 | 33 | \item{...}{further arguments passed to \code{\link[graphics]{plot}}} 34 | } 35 | \description{ 36 | Plots a time series, with the option to include confidence and prediction band 37 | } 38 | \details{ 39 | Values for confidence and prediction bands can be generated with \code{\link{getPredictiveIntervals}}. For a more elaborate version of this plot, see \code{\link{plotTimeSeriesResults}} 40 | } 41 | \examples{ 42 | # Create time series 43 | ts <- VSEMcreatePAR(1:100) 44 | 45 | # create fake "predictions" 46 | pred <- ts + rnorm(length(ts), mean = 0, sd = 2) 47 | 48 | # plot time series 49 | par(mfrow=c(1,2)) 50 | 51 | plotTimeSeries(observed = ts, main="Observed") 52 | plotTimeSeries(observed = ts, predicted = pred, main = "Observed and predicted") 53 | 54 | par(mfrow=c(1,1)) 55 | 56 | } 57 | \seealso{ 58 | \code{\link{marginalPlot}}, \code{\link{tracePlot}}, \code{\link{correlationPlot}} 59 | } 60 | \author{ 61 | Florian Hartig 62 | } 63 | -------------------------------------------------------------------------------- /BayesianTools/tests/testthat/test-correlationPlot.R: -------------------------------------------------------------------------------- 1 | testthat::context("Test correlationPlot") 2 | 3 | skip_on_cran() 4 | 5 | ll <- generateTestDensityMultiNormal(sigma = "no correlation") 6 | 7 | bayesianSetup <- createBayesianSetup(likelihood = ll, lower = c(-10, -5, -7.5), upper = c(10, 7.5, 3)) 8 | 9 | settings = list(iterations = 2000, nrChains=2) 10 | 11 | out_1 <- runMCMC(bayesianSetup = bayesianSetup, sampler = "Metropolis", settings = list(iterations=2000)) 12 | out_2 <- runMCMC(bayesianSetup = bayesianSetup, sampler = "Metropolis", settings = settings) 13 | out_3 <- runMCMC(bayesianSetup = bayesianSetup, sampler = "DEzs", settings = settings) 14 | 15 | 16 | 17 | 18 | testthat::test_that("correlationPlot works for bayesianOutput", { 19 | testthat::expect_error(correlationPlot(out_1), NA) 20 | testthat::expect_error(correlationPlot(out_2), NA) 21 | testthat::expect_error(correlationPlot(out_3), NA) 22 | 23 | }) 24 | 25 | testthat::test_that("correlationPlot works for various parameter combinations", { 26 | testthat::expect_error(correlationPlot(out_1, method = "spearman"), NA) 27 | testthat::expect_error(correlationPlot(out_1, method = "kendall"), NA) 28 | 29 | testthat::expect_error(correlationPlot(out_1, method = "spearman", density = "ellipse"), NA) 30 | testthat::expect_error(correlationPlot(out_1, method = "kendall", density = "corellipseCor"), NA) 31 | 32 | testthat::expect_error(correlationPlot(out_1, method = "spearman", density = "smooth", scaleCorText = F), NA) 33 | 34 | testthat::expect_error(correlationPlot(out_1, method = "kendall", density = "corellipseCor", whichParameters = c(1,2)), NA) 35 | 36 | testthat::expect_error(correlationPlot(out_1, method = "spearman", start = 200), NA) 37 | testthat::expect_error(correlationPlot(out_1, method = "kendall", start = 200, thin = 100), NA) 38 | }) -------------------------------------------------------------------------------- /Development/BT-issues/issue-222.R: -------------------------------------------------------------------------------- 1 | library(BayesianTools) 2 | 3 | 4 | ## Generate a test likelihood function. 5 | ll <- dnorm 6 | 7 | ## Create a BayesianSetup object from the likelihood 8 | ## is the recommended way of using the runMCMC() function. 9 | bayesianSetup <- createBayesianSetup(likelihood = ll, lower = -10, upper = 10) 10 | 11 | ## Finally we can run the sampler and have a look 12 | settings = list(iterations = 1000, adapt = FALSE, nrChains = 2) 13 | out <- runMCMC(bayesianSetup = bayesianSetup, sampler = "Metropolis", settings = settings) 14 | 15 | summary(out) 16 | 17 | 18 | ## out is of class bayesianOutput. There are various standard functions 19 | # implemented for this output 20 | 21 | plot(out) 22 | correlationPlot(out) 23 | marginalPlot(out) 24 | 25 | gelmanDiagnostics(out) 26 | 27 | summary(out) 28 | 29 | 30 | x = getSample(out, coda = T) 31 | plot(x) 32 | 33 | re 34 | 35 | coda::gelman.diag(x) 36 | coda::rejectionRate(x[[2]]) 37 | 38 | 39 | 40 | 41 | ll <- generateTestDensityMultiNormal(sigma = "no correlation") 42 | 43 | bayesianSetup <- createBayesianSetup(likelihood = ll, lower = rep(-10, 3), upper = rep(10, 3)) 44 | 45 | settings = list(iterations = 1000, adapt = FALSE, nrChains = 2) 46 | out <- runMCMC(bayesianSetup = bayesianSetup, sampler = "Metropolis", settings = settings) 47 | 48 | getSample(out, start = 1, end = 5, which = 1) 49 | 50 | 51 | 52 | summary(out) 53 | 54 | ## out is of class bayesianOutput. There are various standard functions 55 | # implemented for this output 56 | 57 | plot(out) 58 | correlationPlot(out) 59 | marginalPlot(out) 60 | 61 | 62 | ## additionally, you can return the sample as a coda object, and make use of the coda functions 63 | # for plotting and analysis 64 | 65 | codaObject = getSample(out, start = 500, coda = TRUE) 66 | coda::rejectionRate(codaObject) 67 | 68 | -------------------------------------------------------------------------------- /Publications/SpeichEtAl-SMCForModelCalibration/4_parallelization/test_parallel_2plus_20ms.r: -------------------------------------------------------------------------------- 1 | args <- commandArgs(TRUE) 2 | number <- eval(parse(text = args[1])) 3 | cores <- eval(parse(text = args[2])) 4 | 5 | library(BayesianTools) 6 | library(threePGN) 7 | 8 | # Load saved (synthetic) data and reference MCMC output (reference is not needed here, only BA and GPP) 9 | load("./out/reference_threePGN_list.RData") 10 | # Use only sample from reference; delete reference to free memory 11 | ref.sample <- getSample(save.list[[3]], start = 3333) 12 | ref.ba <- save.list[[1]] 13 | ref.gpp <- save.list[[2]] 14 | rm(save.list) 15 | 16 | 17 | ref.pars <- c(data_param$mode, 1, 1) 18 | min.pars <- c(data_param$min, 0.2, 0.2) 19 | max.pars <- c(data_param$max, 2, 2) 20 | 21 | out.file <- paste0("/home/fr/fr_fr/fr_ms1719/out/test_parallel/out", number, "/", cores, "cores.txt") 22 | 23 | set.seed(number) 24 | 25 | #### Sleep 20ms 26 | likelihood20 <- function(ref.pars){ 27 | 28 | library(threePGN) 29 | pgrun <- r3pgn(siteData = data_site[1:3,], climate = data_climate, parameters = ref.pars[1:51], outputs = c(1:5,10:12, 26:27)) 30 | sim.ba <- pgrun$output[,,1][,3] 31 | sim.gpp <- pgrun$output[,,1][,9] 32 | 33 | like <- sum(dnorm(ref.ba-sim.ba, sd=ref.pars[52], log=TRUE)) + sum(dnorm(ref.gpp-sim.gpp, sd=ref.pars[53], log=TRUE)) 34 | Sys.sleep(0.02) 35 | return(like) 36 | } 37 | 38 | prior <- createUniformPrior(lower = min.pars, upper = max.pars) 39 | pgSetup20 <- createBayesianSetup(likelihood = likelihood20, prior = prior, parallel = cores) 40 | 41 | time <- system.time(smc <- smcSampler(bayesianSetup = pgSetup20, initialParticles = 50000, ess.limit = 50000 * 0.9, mutate.method = "DE", proposalScale = 0.1, resamplingSteps = 30))[3] 42 | 43 | cat("\n", file=out.file, append=TRUE) 44 | cat(c("sleep20ms", time), file = out.file, append = TRUE) 45 | 46 | stopParallel(pgSetup20) 47 | 48 | -------------------------------------------------------------------------------- /Publications/SpeichEtAl-SMCForModelCalibration/4_parallelization/test_parallel_2plus_50ms.r: -------------------------------------------------------------------------------- 1 | args <- commandArgs(TRUE) 2 | number <- eval(parse(text = args[1])) 3 | cores <- eval(parse(text = args[2])) 4 | 5 | library(BayesianTools) 6 | library(threePGN) 7 | 8 | # Load saved (synthetic) data and reference MCMC output (reference is not needed here, only BA and GPP) 9 | load("./out/reference_threePGN_list.RData") 10 | # Use only sample from reference; delete reference to free memory 11 | ref.sample <- getSample(save.list[[3]], start = 3333) 12 | ref.ba <- save.list[[1]] 13 | ref.gpp <- save.list[[2]] 14 | rm(save.list) 15 | 16 | 17 | ref.pars <- c(data_param$mode, 1, 1) 18 | min.pars <- c(data_param$min, 0.2, 0.2) 19 | max.pars <- c(data_param$max, 2, 2) 20 | 21 | out.file <- paste0("/home/fr/fr_fr/fr_ms1719/out/test_parallel/out", number, "/", cores, "cores.txt") 22 | 23 | set.seed(number) 24 | 25 | #### Sleep 50ms 26 | likelihood50 <- function(ref.pars){ 27 | 28 | library(threePGN) 29 | pgrun <- r3pgn(siteData = data_site[1:3,], climate = data_climate, parameters = ref.pars[1:51], outputs = c(1:5,10:12, 26:27)) 30 | sim.ba <- pgrun$output[,,1][,3] 31 | sim.gpp <- pgrun$output[,,1][,9] 32 | 33 | like <- sum(dnorm(ref.ba-sim.ba, sd=ref.pars[52], log=TRUE)) + sum(dnorm(ref.gpp-sim.gpp, sd=ref.pars[53], log=TRUE)) 34 | Sys.sleep(0.05) 35 | return(like) 36 | } 37 | 38 | prior <- createUniformPrior(lower = min.pars, upper = max.pars) 39 | pgSetup50 <- createBayesianSetup(likelihood = likelihood50, prior = prior, parallel = cores) 40 | 41 | time <- system.time(smc <- smcSampler(bayesianSetup = pgSetup50, initialParticles = 50000, ess.limit = 50000 * 0.9, mutate.method = "DE", proposalScale = 0.1, resamplingSteps = 30))[3] 42 | 43 | cat("\n", file=out.file, append=TRUE) 44 | cat(c("sleep50ms", time), file = out.file, append = TRUE) 45 | 46 | stopParallel(pgSetup50) 47 | 48 | -------------------------------------------------------------------------------- /BayesianTools/tests/testthat/test-startValues.R: -------------------------------------------------------------------------------- 1 | context("Test start values/Z matrix inside prior range") 2 | 3 | skip_on_cran() 4 | 5 | test_that("test z matrix check", { 6 | ll = testDensityNormal 7 | bayesianSetup = createBayesianSetup(likelihood = ll, lower = 2, upper = 5) 8 | expect_warning(runMCMC(bayesianSetup, sampler = "DEzs",settings = list(iterations = 100, Z = matrix(6, nrow = 3, ncol =1), message = F))) 9 | expect_warning(runMCMC(bayesianSetup, sampler = "DREAMzs",settings = list(iterations = 100, Z = matrix(6, nrow = 3, ncol =1), message = F))) 10 | 11 | }) 12 | 13 | test_that("test start value check", { 14 | ll = testDensityNormal 15 | bayesianSetup = createBayesianSetup(likelihood = ll, lower = 2, upper = 5) 16 | expect_warning(runMCMC(bayesianSetup, sampler = "DREAMzs",settings = list(iterations = 100, startValue = matrix(6, nrow = 3, ncol =1), message = F))) 17 | expect_warning(runMCMC(bayesianSetup, sampler = "DREAM",settings = list(iterations = 100, startValue = matrix(1:4, nrow = 4, ncol =1), message = F, DEpairs = 2))) 18 | expect_warning(runMCMC(bayesianSetup, sampler = "DEzs",settings = list(iterations = 100, startValue = matrix(6, nrow = 3, ncol =1), message = F))) 19 | expect_warning(runMCMC(bayesianSetup, sampler = "DE",settings = list(iterations = 100, startValue = matrix(6, nrow = 3, ncol =1), message = F))) 20 | expect_warning(runMCMC(bayesianSetup, sampler = "Metropolis",settings = list(iterations = 100, startValue = matrix(6, nrow = 1, ncol =1), message = F))) 21 | 22 | density = function(par) return(dunif(par[1],0,5, log = T)) 23 | sampler = function(n=1) return(runif(n,-1,4)) 24 | prior = createPrior(sampler = sampler, density = density, lower = 0,upper = 5) 25 | bayesianSetup = createBayesianSetup(likelihood = ll, prior = prior) 26 | expect_warning(runMCMC(bayesianSetup, sampler = "DE",settings = list(iterations = 100, message = F))) 27 | }) 28 | -------------------------------------------------------------------------------- /BayesianTools/inst/examples/proposalGeneratorHelp.R: -------------------------------------------------------------------------------- 1 | testMatrix = matrix(rep(c(0,0,0,0), 1000), ncol = 4) 2 | testVector = c(0,0,0,0) 3 | 4 | 5 | ##Standard multivariate normal proposal generator 6 | 7 | testGenerator <- createProposalGenerator(covariance = c(1,1,1,1), message = TRUE) 8 | 9 | methods(class = "proposalGenerator") 10 | print(testGenerator) 11 | 12 | x = testGenerator$returnProposal(testVector) 13 | x 14 | 15 | x <- testGenerator$returnProposalMatrix(testMatrix) 16 | boxplot(x) 17 | 18 | ##Changing the covariance 19 | testGenerator$covariance = diag(rep(100,4)) 20 | testGenerator <- testGenerator$updateProposalGenerator(testGenerator, message = TRUE) 21 | 22 | testGenerator$returnProposal(testVector) 23 | x <- testGenerator$returnProposalMatrix(testMatrix) 24 | boxplot(x) 25 | 26 | 27 | ##-Changing the gibbs probabilities / probability to modify 1-n parameters 28 | 29 | testGenerator$gibbsProbabilities = c(1,1,0,0) 30 | testGenerator <- testGenerator$updateProposalGenerator(testGenerator) 31 | 32 | testGenerator$returnProposal(testVector) 33 | x <- testGenerator$returnProposalMatrix(testMatrix) 34 | boxplot(x) 35 | 36 | 37 | ##-Changing the gibbs weights / probability to pick each parameter 38 | 39 | testGenerator$gibbsWeights = c(0.3,0.3,0.3,100) 40 | testGenerator <- testGenerator$updateProposalGenerator(testGenerator) 41 | 42 | testGenerator$returnProposal(testVector) 43 | x <- testGenerator$returnProposalMatrix(testMatrix) 44 | boxplot(x) 45 | 46 | 47 | ##-Adding another function 48 | 49 | otherFunction <- function(x) sample.int(10,1) 50 | 51 | testGenerator <- createProposalGenerator( 52 | covariance = c(1,1,1), 53 | otherDistribution = otherFunction, 54 | otherDistributionLocation = c(0,0,0,1), 55 | otherDistributionScaled = TRUE 56 | ) 57 | 58 | testGenerator$returnProposal(testVector) 59 | x <- testGenerator$returnProposalMatrix(testMatrix) 60 | boxplot(x) 61 | table(x[,4]) 62 | -------------------------------------------------------------------------------- /BayesianTools/R/classSMCSamplerList.R: -------------------------------------------------------------------------------- 1 | #' Convenience function to create an object of class SMCSamplerList from a list of mcmc samplers 2 | #' @author Florian Hartig 3 | #' @param ... a list of MCMC samplers 4 | #' @return a list of class smcSamplerList with each object being an smcSampler 5 | #' @export 6 | createSmcSamplerList <- function(...){ 7 | smcList <- list(...) 8 | for (i in 1:length(smcList)){ 9 | if (! ("mcmcSampler" %in% class(smcList[[i]])) ) stop("list objects are not of class mcmcSampler") 10 | } 11 | class(smcList) = c("smcSamplerList", "bayesianOutput") 12 | return(smcList) 13 | } 14 | 15 | 16 | #' @method summary smcSamplerList 17 | #' @author Florian Hartig 18 | #' @export 19 | summary.smcSamplerList <- function(object, ...){ 20 | sample = getSample(object, parametersOnly = T, ...) 21 | summary(sample) 22 | } 23 | 24 | #' @method print smcSamplerList 25 | #' @author Florian Hartig 26 | #' @export 27 | print.smcSamplerList <- function(x, ...){ 28 | print("smcSamplerList - you can use the following methods to summarize, plot or reduce this class:") 29 | print(methods(class ="smcSamplerList")) 30 | } 31 | 32 | #' @method plot smcSamplerList 33 | #' @export 34 | plot.smcSamplerList <- function(x, ...){ 35 | marginalPlot(x, ...) 36 | } 37 | 38 | #' @export 39 | getSample.smcSamplerList <- function(sampler, parametersOnly = T, coda = F, start = 1, end = NULL, thin = 1, 40 | numSamples = NULL, whichParameters = NULL, reportDiagnostics = FALSE, ...){ 41 | 42 | out = list() 43 | 44 | for (i in 1:length(sampler)){ 45 | 46 | out[[i]] = getSample(sampler[[i]], parametersOnly = parametersOnly, whichParameters = whichParameters, start = start, end = end, thin = thin, 47 | numSamples = numSamples, coda = F, reportDiagnostics = F) 48 | 49 | } 50 | out = combineChains(out, merge =F) 51 | 52 | return(out) 53 | } 54 | 55 | 56 | 57 | 58 | 59 | -------------------------------------------------------------------------------- /.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, GitAction] 6 | pull_request: 7 | branches: [main, master] 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: 'release'} 22 | - {os: windows-latest, r: 'release'} 23 | - {os: windows-latest, r: 'devel'} 24 | - {os: ubuntu-latest, r: 'devel', http-user-agent: 'release'} 25 | - {os: ubuntu-latest, r: 'release'} 26 | - {os: ubuntu-latest, r: 'oldrel-1'} 27 | 28 | env: 29 | GITHUB_PAT: ${{ secrets.GITHUB_TOKEN }} 30 | R_KEEP_PKG_SOURCE: yes 31 | 32 | steps: 33 | - uses: actions/checkout@v3 34 | 35 | - uses: r-lib/actions/setup-pandoc@v2 36 | 37 | - uses: r-lib/actions/setup-r@v2 38 | with: 39 | r-version: ${{ matrix.config.r }} 40 | http-user-agent: ${{ matrix.config.http-user-agent }} 41 | use-public-rspm: true 42 | 43 | - uses: r-lib/actions/setup-r-dependencies@v2 44 | with: 45 | extra-packages: any::rcmdcheck 46 | needs: check 47 | working-directory: BayesianTools 48 | # second check with different rcmdcheck arguments. 49 | - uses: r-lib/actions/check-r-package@v2 50 | with: 51 | upload-snapshots: true 52 | working-directory: BayesianTools 53 | args: 'c("--no-multiarch", "--no-manual")' 54 | 55 | - uses: r-lib/actions/check-r-package@v2 56 | with: 57 | upload-snapshots: true 58 | working-directory: BayesianTools 59 | -------------------------------------------------------------------------------- /BayesianTools/man/getVolume.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/getVolume.R 3 | \name{getVolume} 4 | \alias{getVolume} 5 | \title{Calculate posterior volume} 6 | \usage{ 7 | getVolume(sampler, prior = F, method = "MVN", ...) 8 | } 9 | \arguments{ 10 | \item{sampler}{an object of superclass bayesianOutput or any other class that has the getSample function implemented (e.g. Matrix)} 11 | 12 | \item{prior}{schould also prior volume be calculated} 13 | 14 | \item{method}{method for volume estimation. Currently, the only option is "MVN"} 15 | 16 | \item{...}{additional parameters to pass on to the \code{\link{getSample}}} 17 | } 18 | \description{ 19 | Calculate posterior volume 20 | } 21 | \details{ 22 | The idea of this function is to provide an estimate of the "posterior volume", i.e. how "broad" the posterior is. One potential application is to the overall reduction of parametric uncertainty between different data types, or between prior and posterior. 23 | 24 | Implemented methods for volume estimation: 25 | 26 | Option "MVN" - in this option, the volume is calculated as the determinant of the covariance matrix of the prior / posterior sample. 27 | } 28 | \examples{ 29 | bayesianSetup = createBayesianSetup( 30 | likelihood = generateTestDensityMultiNormal(sigma = "no correlation"), 31 | lower = rep(-10, 3), upper = rep(10, 3)) 32 | 33 | out <- runMCMC(bayesianSetup = bayesianSetup, sampler = "Metropolis", 34 | settings = list(iterations = 2000, message = FALSE)) 35 | 36 | getVolume(out, prior = TRUE) 37 | 38 | bayesianSetup = createBayesianSetup( 39 | likelihood = generateTestDensityMultiNormal(sigma = "strongcorrelation"), 40 | lower = rep(-10, 3), upper = rep(10, 3)) 41 | 42 | out <- runMCMC(bayesianSetup = bayesianSetup, sampler = "Metropolis", 43 | settings = list(iterations = 2000, message = FALSE)) 44 | 45 | getVolume(out, prior = TRUE) 46 | 47 | } 48 | \author{ 49 | Florian Hartig 50 | } 51 | -------------------------------------------------------------------------------- /BayesianTools/man/Twalk.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/mcmcTwalk.R 3 | \name{Twalk} 4 | \alias{Twalk} 5 | \title{T-walk MCMC} 6 | \usage{ 7 | Twalk( 8 | bayesianSetup, 9 | settings = list(iterations = 10000, at = 6, aw = 1.5, pn1 = NULL, Ptrav = 0.4918, Pwalk 10 | = 0.4918, Pblow = 0.0082, burnin = 0, thin = 1, startValue = NULL, consoleUpdates = 11 | 100, message = TRUE) 12 | ) 13 | } 14 | \arguments{ 15 | \item{bayesianSetup}{Object of class 'bayesianSetup' or 'bayesianOuput'.} 16 | 17 | \item{settings}{list with parameter values.} 18 | 19 | \item{iterations}{Number of model evaluations} 20 | 21 | \item{at}{"traverse" move proposal parameter. Default to 6} 22 | 23 | \item{aw}{"walk" move proposal parameter. Default to 1.5} 24 | 25 | \item{pn1}{Probability determining the number of parameters that are changed} 26 | 27 | \item{Ptrav}{Move probability of "traverse" moves, default to 0.4918} 28 | 29 | \item{Pwalk}{Move probability of "walk" moves, default to 0.4918} 30 | 31 | \item{Pblow}{Move probability of "traverse" moves, default to 0.0082} 32 | 33 | \item{burnin}{number of iterations treated as burn-in. These iterations are not recorded in the chain.} 34 | 35 | \item{thin}{thinning parameter. Determines the interval in which values are recorded.} 36 | 37 | \item{startValue}{Matrix with start values} 38 | 39 | \item{consoleUpdates}{Intervall in which the sampling progress is printed to the console} 40 | 41 | \item{message}{logical determines whether the sampler's progress should be printed} 42 | } 43 | \value{ 44 | Object of class bayesianOutput. 45 | } 46 | \description{ 47 | T-walk MCMC 48 | } 49 | \details{ 50 | The probability of "hop" moves is 1 minus the sum of all other probabilities. 51 | } 52 | \references{ 53 | Christen, J. Andres, and Colin Fox. "A general purpose sampling algorithm for continuous distributions (the t-walk)." Bayesian Analysis 5.2 (2010): 263-281. 54 | } 55 | \author{ 56 | Stefan Paul 57 | } 58 | -------------------------------------------------------------------------------- /BayesianTools/man/plotDiagnostic.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/plotDiagnostic.R 3 | \name{plotDiagnostic} 4 | \alias{plotDiagnostic} 5 | \title{Diagnostic Plot} 6 | \usage{ 7 | plotDiagnostic( 8 | out, 9 | start = 50, 10 | numSamples = 100, 11 | window = 0.2, 12 | plotWAIC = F, 13 | plotPSRF = T, 14 | plotDIC = T, 15 | plotTrace = T, 16 | graphicParameters = NULL, 17 | ... 18 | ) 19 | } 20 | \arguments{ 21 | \item{out}{object of class "bayesianOutput"} 22 | 23 | \item{start}{start value for calculating DIC, WAIC, mPSRF and PSRF, default = 50} 24 | 25 | \item{numSamples}{for calculating WAIC, default = 10 because of high computational costs} 26 | 27 | \item{window}{plot range to show, vector of percents or only one value as start value for the window} 28 | 29 | \item{plotWAIC}{whether to calculate WAIC or not, default = T} 30 | 31 | \item{plotPSRF}{calculate and plot mPSRF/PSRF or not, default = T} 32 | 33 | \item{plotDIC}{calculate and plot DICor not, default = T} 34 | 35 | \item{plotTrace}{show trace plots or not, default = T} 36 | 37 | \item{graphicParameters}{graphic parameters as list for plot function} 38 | 39 | \item{...}{parameters to give to getSample} 40 | } 41 | \description{ 42 | This function plots the DIC, WAIC, mPSRF, PSRF(with upper C.I.) and traces of the parameters in dependence of iterations. DIC, WAIC are plotted separately for the chains and the trace plots also for the internal chains. 43 | } 44 | \examples{ 45 | \dontrun{ 46 | 47 | # Create bayesian setup with 48 | bayesianSetup <- createBayesianSetup(likelihood = testDensityNormal, 49 | prior = createUniformPrior(lower = -10, 50 | upper = 10)) 51 | # running MCMC 52 | out = runMCMC(bayesianSetup = bayesianSetup) 53 | 54 | # diagnostic plots 55 | plotDiagnostic(out) 56 | } 57 | } 58 | \author{ 59 | Maximilian Pichler 60 | } 61 | -------------------------------------------------------------------------------- /Examples/BayesFactor.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Bayes Factor" 3 | author: "Florian Hartig" 4 | date: "21 Jan 2016" 5 | output: html_document 6 | --- 7 | 8 | ```{r global_options, include=FALSE} 9 | knitr::opts_chunk$set(fig.width=6, fig.height=6, warning=FALSE, message=FALSE) 10 | ``` 11 | 12 | 13 | ```{r} 14 | library(BayesianTools) 15 | ``` 16 | 17 | 18 | Data linear Regression with quadratic and linear effect 19 | 20 | ```{r} 21 | sampleSize = 30 22 | x <- (-(sampleSize-1)/2):((sampleSize-1)/2) 23 | y <- 1 * x + 1*x^2 + rnorm(n=sampleSize,mean=0,sd=10) 24 | plot(x,y, main="Test Data") 25 | ``` 26 | 27 | Likelihoods for both 28 | 29 | ```{r} 30 | likelihood1 <- function(param){ 31 | pred = param[1] + param[2]*x + param[3] * x^2 32 | singlelikelihoods = dnorm(y, mean = pred, sd = 1/(param[4]^2), log = T) 33 | return(sum(singlelikelihoods)) 34 | } 35 | 36 | likelihood2 <- function(param){ 37 | pred = param[1] + param[2]*x 38 | singlelikelihoods = dnorm(y, mean = pred, sd = 1/(param[3]^2), log = T) 39 | return(sum(singlelikelihoods)) 40 | } 41 | ``` 42 | 43 | 44 | Posterior definitions 45 | 46 | 47 | ```{r} 48 | setUp1 <- createBayesianSetup(likelihood1, lower = c(-5,-5,-5,0.01), upper = c(5,5,5,30)) 49 | 50 | setUp2 <- createBayesianSetup(likelihood2, lower = c(-5,-5,0.01), upper = c(5,5,30)) 51 | ``` 52 | 53 | MCMC and marginal likelihood calculation 54 | 55 | ```{r, results = 'hide'} 56 | settings = list(iterations = 15000) 57 | out <- runMCMC(bayesianSetup = setUp1, sampler = "Metropolis", settings = settings) 58 | tracePlot(out, start = 5000) 59 | 60 | nbpar=2 61 | M1 = marginalLikelihood(out) 62 | M1 63 | 64 | settings = list(iterations = 15000) 65 | out <- runMCMC(bayesianSetup = setUp2, sampler = "Metropolis", settings = settings) 66 | tracePlot(out, start = 5000) 67 | nbpar=3 68 | M2 = marginalLikelihood(out) 69 | M2 70 | ``` 71 | 72 | Bayes factor (need to reverse the log) 73 | 74 | ```{r} 75 | exp(M1$marginalLikelihod - M2$marginalLikelihod) 76 | ``` 77 | 78 | 79 | 80 | 81 | -------------------------------------------------------------------------------- /BayesianTools/inst/examples/createPrior.R: -------------------------------------------------------------------------------- 1 | # The BT package includes a number of convenience functions to specify 2 | # prior distributions, including createUniformPrior, createTruncatedNormalPrior 3 | # etc. If you want to specify a prior that corresponds to one of these 4 | # distributions, you should use these functions, e.g.: 5 | 6 | prior <- createUniformPrior(lower = c(0,0), upper = c(0.4,5)) 7 | 8 | prior$density(c(2, 3)) # outside of limits -> -Inf 9 | prior$density(c(0.2, 2)) # within limits, -0.6931472 10 | 11 | # All default priors include a sampling function, i.e. you can create 12 | # samples from the prior via 13 | prior$sampler() 14 | # [1] 0.2291413 4.5410389 15 | 16 | # if you want to specify a prior that does not have a default function, 17 | # you should use the createPrior function, which expects a density and 18 | # optionally a sampler function: 19 | 20 | density = function(par){ 21 | d1 = dunif(par[1], -2,6, log =TRUE) 22 | d2 = dnorm(par[2], mean= 2, sd = 3, log =TRUE) 23 | return(d1 + d2) 24 | } 25 | 26 | sampler = function(n=1){ 27 | d1 = runif(n, -2,6) 28 | d2 = rnorm(n, mean= 2, sd = 3) 29 | return(cbind(d1,d2)) 30 | } 31 | 32 | prior <- createPrior(density = density, sampler = sampler, 33 | lower = c(-10,-20), upper = c(10,20), best = NULL) 34 | 35 | # note that the createPrior supports additional truncation 36 | 37 | 38 | # To use a prior in an MCMC, include it in a BayesianSetup 39 | 40 | set.seed(123) 41 | ll <- function(x) sum(dnorm(x, log = TRUE)) # multivariate normal ll 42 | bayesianSetup <- createBayesianSetup(likelihood = ll, prior = prior) 43 | 44 | settings = list(iterations = 100) 45 | out <- runMCMC(bayesianSetup = bayesianSetup, settings = settings) 46 | 47 | # use createPriorDensity to create a new (estimated) prior from MCMC output 48 | 49 | newPrior = createPriorDensity(out, method = "multivariate", 50 | eps = 1e-10, lower = c(-10,-20), 51 | upper = c(10,20), best = NULL, scaling = 0.5) 52 | 53 | -------------------------------------------------------------------------------- /BayesianTools/R/plotSensitivityOAT.R: -------------------------------------------------------------------------------- 1 | #' Performs a one-factor-at-a-time sensitivity analysis for the posterior of a given bayesianSetup within the prior range. 2 | #' @author Florian Hartig 3 | #' @param bayesianSetup An object of class BayesianSetup 4 | #' @param selection indices of selected parameters 5 | #' @param equalScale if T, y axis of all plots will have the same scale 6 | #' @note This function can also be used for sensitivity analysis of an arbitrary output - just create a BayesianSetup with this output. 7 | #' @example /inst/examples/plotSensitivityHelp.R 8 | #' @export 9 | plotSensitivity <- function(bayesianSetup, selection = NULL, equalScale = T){ 10 | 11 | if (is.null(selection)) selection = 1:bayesianSetup$numPars 12 | n = length(selection) 13 | 14 | post = list() 15 | lowS = bayesianSetup$prior$lower[selection] 16 | upS = bayesianSetup$prior$upper[selection] 17 | refPar = bayesianSetup$prior$best[selection] 18 | names = bayesianSetup$names[selection] 19 | fullRefPar <- bayesianSetup$prior$best 20 | 21 | minR = Inf 22 | maxR = -Inf 23 | 24 | for (j in 1:n){ 25 | post[[j]] <- data.frame(par = seq(lowS[j], upS[j], len = 20), resp = rep(NA, 20)) 26 | 27 | for (i in 1:20){ 28 | parS <- refPar 29 | parS[j] = post[[j]]$par[i] 30 | parS2 = fullRefPar 31 | parS2[selection] = parS 32 | post[[j]]$resp[i] = bayesianSetup$posterior$density(parS2) 33 | } 34 | minR = min(minR, post[[j]]$resp) 35 | maxR = max(maxR, post[[j]]$resp) 36 | } 37 | 38 | oldPar = par(mfrow = getPanels(n)) 39 | 40 | 41 | for (i in 1:n){ 42 | if(equalScale == T) plot(resp~par, xlab = names[i], type = "l", col = "red", data = post[[i]], ylim = c(minR, maxR), ylab = "Response") 43 | else plot(resp~par, xlab = names[i], type = "l", col = "red", data = post[[i]], ylab = "Response") 44 | 45 | abline(v = refPar[i]) 46 | } 47 | 48 | names(post) = names 49 | post$reference = refPar 50 | 51 | par(oldPar) 52 | return(post) 53 | } 54 | 55 | 56 | 57 | 58 | -------------------------------------------------------------------------------- /BayesianTools/R/classPosterior.R: -------------------------------------------------------------------------------- 1 | #' Creates a standardized posterior class 2 | #' @author Florian Hartig 3 | #' @param prior prior class 4 | #' @param likelihood Log likelihood density 5 | #' @details Function is internally used in \code{\link{createBayesianSetup}} to create a standarized posterior class. 6 | #' @export 7 | createPosterior <- function(prior, likelihood){ 8 | 9 | posterior <- function(x, returnAll = F){ 10 | 11 | if (is.vector(x)){ 12 | priorResult = prior$density(x) # Checking if outside prior to save calculation time 13 | if (! (priorResult == -Inf)) ll = likelihood$density(x) 14 | else ll = -Inf 15 | if (returnAll == F) return(ll + priorResult) 16 | else return(c(ll + priorResult, ll, priorResult)) 17 | 18 | } else if(is.matrix(x)){ 19 | 20 | priorResult = prior$density(x) # Checking first if outside the prior to save calculation time 21 | feasible <- (! priorResult == -Inf) 22 | if (dim(x)[2] == 1) llResult <- likelihood$density(matrix(x[feasible, ], ncol = 1)) 23 | else{ 24 | if(TRUE %in% feasible) llResult <- likelihood$density(x[feasible, ]) 25 | else llResult <- -Inf 26 | } 27 | post = priorResult 28 | ll = priorResult 29 | ll[!feasible] = NA 30 | ll[feasible] = llResult 31 | post[feasible] = post[feasible] + llResult 32 | post[!feasible] = -Inf 33 | if (returnAll == F) return(post) 34 | else{ 35 | out <- cbind(post, ll, priorResult) 36 | colnames(out) = c("posterior", "likelihood", "prior") 37 | return(out) 38 | } 39 | } 40 | else stop("parameter must be vector or matrix") 41 | } 42 | 43 | out<- list(density = posterior) 44 | class(out) <- "posterior" 45 | return(out) 46 | } 47 | 48 | # likelihood <- function(x)stop("a") 49 | # prior <- createPrior(function(x) sum(dunif(x, log = T))) 50 | # 51 | # x = createPosterior(prior, likelihood) 52 | # 53 | # x$density(c(0.2,0.2)) 54 | # prior$density(c(2,2)) 55 | # 56 | # 57 | # x = c(0.2,0.2) 58 | -------------------------------------------------------------------------------- /BayesianTools/man/plotTimeSeriesResults.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/plotTimeSeries.R 3 | \name{plotTimeSeriesResults} 4 | \alias{plotTimeSeriesResults} 5 | \title{Creates a time series plot typical for an MCMC / SMC fit} 6 | \usage{ 7 | plotTimeSeriesResults( 8 | sampler, 9 | model, 10 | observed, 11 | error = NULL, 12 | plotResiduals = TRUE, 13 | start = 1, 14 | prior = FALSE, 15 | ... 16 | ) 17 | } 18 | \arguments{ 19 | \item{sampler}{Either a) a matrix b) an MCMC object (list or not), or c) an SMC object} 20 | 21 | \item{model}{function that calculates model predictions for a given parameter vector} 22 | 23 | \item{observed}{observed values as vector} 24 | 25 | \item{error}{function with signature f(mean, par) that generates observations with error (error = stochasticity according to what is assumed in the likelihood) from mean model predictions. Par is a vector from the matrix with the parameter samples (full length). f needs to know which of these parameters are parameters of the error function. See example in \code{\link{VSEM}}} 26 | 27 | \item{plotResiduals}{logical determining whether residuals should be plotted} 28 | 29 | \item{start}{numeric start value for the plot (see \code{\link{getSample}})} 30 | 31 | \item{prior}{if a prior sampler is implemented, setting this parameter to TRUE will draw model parameters from the prior instead of the posterior distribution} 32 | 33 | \item{...}{further arguments passed to \code{\link[graphics]{plot}}} 34 | } 35 | \description{ 36 | Creates a time series plot typical for an MCMC / SMC fit 37 | } 38 | \examples{ 39 | # Create time series 40 | ts <- VSEMcreatePAR(1:100) 41 | 42 | # create fake "predictions" 43 | pred <- ts + rnorm(length(ts), mean = 0, sd = 2) 44 | 45 | # plot time series 46 | par(mfrow=c(1,2)) 47 | 48 | plotTimeSeries(observed = ts, main="Observed") 49 | plotTimeSeries(observed = ts, predicted = pred, main = "Observed and predicted") 50 | 51 | par(mfrow=c(1,1)) 52 | 53 | } 54 | \seealso{ 55 | \code{\link{getPredictiveIntervals}} 56 | } 57 | \author{ 58 | Florian Hartig 59 | } 60 | -------------------------------------------------------------------------------- /BayesianTools/man/bridgesample.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/marginalLikelihood.R 3 | \name{bridgesample} 4 | \alias{bridgesample} 5 | \title{Calculates the marginal likelihood of a chain via bridge sampling} 6 | \usage{ 7 | bridgesample(chain, nParams, lower = NULL, upper = NULL, posterior, ...) 8 | } 9 | \arguments{ 10 | \item{chain}{a single mcmc chain with samples as rows and parameters and posterior density as columns.} 11 | 12 | \item{nParams}{number of parameters} 13 | 14 | \item{lower}{optional - lower bounds of the prior} 15 | 16 | \item{upper}{optional - upper bounds of the prior} 17 | 18 | \item{posterior}{posterior density function} 19 | 20 | \item{...}{arguments passed to bridge_sampler} 21 | } 22 | \description{ 23 | Calculates the marginal likelihood of a chain via bridge sampling 24 | } 25 | \details{ 26 | This function uses "bridge_sampler" from the package "bridgesampling". 27 | } 28 | \examples{ 29 | means <- c(0, 1, 2) 30 | sds <- c(1, 0.6, 3) 31 | 32 | # log-likelihood 33 | ll <- function (x) { 34 | return(sum(dnorm(x, mean = means, sd = sds, log = TRUE))) 35 | } 36 | 37 | # lower and upper bounds for prior 38 | lb <- rep(-10, 3) 39 | ub <- rep(10, 3) 40 | 41 | # create setup and run MCMC 42 | setup <- createBayesianSetup(likelihood = ll, 43 | lower = lb, 44 | upper = ub) 45 | 46 | out <- runMCMC(bayesianSetup = setup, 47 | settings = list(iterations = 1000), 48 | sampler = "DEzs") 49 | 50 | # sample from MCMC output with "burn-in" of 25\% 51 | sample <- getSample(out$chain, start = 250, numSamples = 500) 52 | 53 | # use bridge sampling to get marginal likelihood 54 | bs_result <- bridgesample(chain = sample, 55 | nParams = out$setup$numPars, 56 | lower = lb, 57 | upper = ub, 58 | posterior = out$setup$posterior$density) 59 | bs_result 60 | } 61 | \seealso{ 62 | \code{\link{marginalLikelihood}} 63 | } 64 | \author{ 65 | Tankred Ott 66 | } 67 | \keyword{internal} 68 | -------------------------------------------------------------------------------- /BayesianTools/man/GOF.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/GOF.R 3 | \name{GOF} 4 | \alias{GOF} 5 | \title{Standard GOF metrics 6 | Startvalues for sampling with nrChains > 1 : if you want to provide different start values for the different chains, provide a list} 7 | \usage{ 8 | GOF(observed, predicted, plot = F, centered = T) 9 | } 10 | \arguments{ 11 | \item{observed}{observed values} 12 | 13 | \item{predicted}{predicted values} 14 | 15 | \item{plot}{should a plot be created} 16 | 17 | \item{centered}{if T, variables are centered to the mean of the observations, i.e. the intercept is for the mean value of the observation} 18 | } 19 | \value{ 20 | A list with the following entries: rmse = root mean squared error, mae = mean absolute error, slope = slope of regression, offset = intercept of regression, R2 = R2 of regression 21 | } 22 | \description{ 23 | Standard GOF metrics 24 | Startvalues for sampling with nrChains > 1 : if you want to provide different start values for the different chains, provide a list 25 | } 26 | \details{ 27 | The function considers observed ~ predicted and calculates 28 | \enumerate{ 29 | \item rmse = root mean squared error 30 | \item mae = mean absolute errorr 31 | \item a linear regression with slope, intercept and coefficient of determination R2 32 | } 33 | 34 | For the linear regression, centered = T means that variables will be centered around the mean value of the observation. This setting avoids a correlation between slope and intercept (that the intercept is != 0 as soon as the slope is !=0) 35 | } 36 | \note{ 37 | In principle, it is possible to plot observed ~ predicted and predicted ~ observed. However, if we assume that the error is mainly on the y axis (observations), i.e. that observations scatter around the true (ideal) value, we should plot observed ~ predicted. See Pineiro et al. (2008). How to evaluate models: observed vs. predicted or predicted vs. observed?. Ecological Modelling, 216(3-4), 316-322. 38 | } 39 | \examples{ 40 | 41 | x = runif(500,-1,1) 42 | y = 0.2 + 0.9 *x + rnorm(500, sd = 0.5) 43 | 44 | summary(lm(y ~ x)) 45 | 46 | GOF(x,y) 47 | 48 | GOF(x,y, plot = TRUE) 49 | } 50 | \author{ 51 | Florian Hartig 52 | } 53 | -------------------------------------------------------------------------------- /BayesianTools/man/generateParallelExecuter.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/BayesianSetupGenerateParallel.R 3 | \name{generateParallelExecuter} 4 | \alias{generateParallelExecuter} 5 | \title{Factory to generate a parallel executor of an existing function} 6 | \usage{ 7 | generateParallelExecuter( 8 | fun, 9 | parallel = F, 10 | parallelOptions = list(variables = "all", packages = "all", dlls = NULL) 11 | ) 12 | } 13 | \arguments{ 14 | \item{fun}{function to be changed to parallel execution} 15 | 16 | \item{parallel}{should a parallel R cluster be used? If set to T, the operating system will automatically detect the available cores and n-1 of the available n cores will be used. Alternatively, you can manually set the number of cores to be used} 17 | 18 | \item{parallelOptions}{a list containing three lists. \itemize{\item First, "packages": determines the R packages required to run the likelihood function. \item Second, "variables": the objects in the global environment needed to run the likelihood function. \item Third, "dlls": the DLLs needed to run the likelihood function (see Details).}} 19 | } 20 | \description{ 21 | Factory to generate a parallel executor of an existing function 22 | } 23 | \details{ 24 | For parallelization, if option T is selected, an automatic parallelization is tried via R. Alternatively, "external" can be selected on the assumption that the likelihood has already been parallelized. In the latter case, a matrix with parameters as columns must be accepted. You can also specify which packages, objects and DLLs are exported to the cluster. By default, a copy of your workspace is exported, but depending on your workspace, this can be inefficient. As an alternative, you can specify the environments and packages in the likelihood function (e.g. BayesianTools::VSEM() instead of VSEM()). 25 | } 26 | \note{ 27 | can be used to make functions compatible with library sensitivity 28 | } 29 | \examples{ 30 | 31 | testDensityMultiNormal <- generateTestDensityMultiNormal() 32 | 33 | 34 | parDen <- generateParallelExecuter(testDensityMultiNormal)$parallelFun 35 | x = matrix(runif(9,0,1), nrow = 3) 36 | parDen(x) 37 | 38 | } 39 | \author{ 40 | Florian Hartig 41 | } 42 | -------------------------------------------------------------------------------- /BayesianTools/R/classSmcSampler.R: -------------------------------------------------------------------------------- 1 | #' @author Florian Hartig 2 | #' @export 3 | getSample.smcSampler <- function(sampler, parametersOnly = T, coda = F, start = 1, end = NULL, thin = 1, numSamples = NULL, whichParameters = NULL, reportDiagnostics = FALSE, ...){ 4 | 5 | if(is.null(end)) end = nrow(sampler$particles) 6 | 7 | if(parametersOnly == T) { 8 | out = sampler$particles[start:end,] 9 | if(!is.null(sampler$setup$names)) colnames(out) = sampler$setup$names 10 | } 11 | else { 12 | out = cbind(sampler$particles[start:end,] , sampler$posterior[start:end,] ) 13 | if(!is.null(sampler$setup$names)) colnames(out) = c(sampler$setup$names, "Lposterior", "Llikelihood", "Lprior") 14 | } 15 | 16 | ######################## 17 | # THINNING 18 | if (thin == "auto"){ 19 | thin = max(floor(nrow(out) / 5000),1) 20 | } 21 | if(is.null(thin) || thin == F || thin < 1) thin = 1 22 | if (! thin == 1){ 23 | sel = seq(1,dim(out)[1], by = thin ) 24 | out = out[sel,] 25 | } 26 | # Sample size 27 | if(thin == 1 && !is.null(numSamples)){ 28 | if (numSamples > nrow(out)) { 29 | numSamples = nrow(out) 30 | warning("numSamples is greater than the total number of samples! All samples were selected.") 31 | } 32 | if (numSamples < 1) numSamples = 1; 33 | sel <- seq(1,dim(out)[1], len = numSamples) 34 | out <- out[sel,] 35 | } 36 | 37 | ############# 38 | 39 | if (!is.null(whichParameters)) out = out[,whichParameters] 40 | 41 | if(reportDiagnostics == T){ 42 | return(list(chain = out, start = start, end = end, thin = thin)) 43 | } else return(out) 44 | } 45 | 46 | #' @author Florian Hartig 47 | #' @method summary smcSampler 48 | #' @export 49 | summary.smcSampler<- function(object, ...){ 50 | sampler <- object 51 | print("SMC sampler output") 52 | summary(getSample(sampler, ...)) 53 | } 54 | 55 | #' @method plot smcSampler 56 | #' @export 57 | plot.smcSampler<- function(x, ...){ 58 | marginalPlot(x, ...) 59 | } 60 | 61 | #' @author Florian Hartig 62 | #' @method print smcSampler 63 | #' @export 64 | print.smcSampler <- function(x, ...){ 65 | print("smcSampler - you can use the following methods to summarize, plot or reduce this class:") 66 | print(methods(class ="smcSampler")) 67 | } 68 | 69 | 70 | -------------------------------------------------------------------------------- /BayesianTools/_pkgdown.yml: -------------------------------------------------------------------------------- 1 | navbar: 2 | title: BayesianTools 3 | type: default 4 | left: 5 | - icon: fa-home fa-lg 6 | href: index.html 7 | - text: Get Started 8 | href: articles/BayesianTools.html 9 | - text: Reference 10 | href: reference/index.html 11 | right: 12 | - icon: fa-github fa-lg 13 | href: https://github.com/florianhartig/BayesianTools 14 | 15 | reference: 16 | - title: All functions 17 | desc: ~ 18 | contents: 19 | - '`applySettingsDefault`' 20 | - '`BayesianTools`' 21 | - '`bridgesample`' 22 | - '`checkBayesianSetup`' 23 | - '`convertCoda`' 24 | - '`correlationPlot`' 25 | - '`createBayesianSetup`' 26 | - '`createBetaPrior`' 27 | - '`createLikelihood`' 28 | - '`createMcmcSamplerList`' 29 | - '`createPosterior`' 30 | - '`createPrior`' 31 | - '`createPriorDensity`' 32 | - '`createProposalGenerator`' 33 | - '`createSmcSamplerList`' 34 | - '`createTruncatedNormalPrior`' 35 | - '`createUniformPrior`' 36 | - '`DE`' 37 | - '`DEzs`' 38 | - '`DIC`' 39 | - '`DREAM`' 40 | - '`DREAMzs`' 41 | - '`gelmanDiagnostics`' 42 | - '`generateParallelExecuter`' 43 | - '`generateTestDensityMultiNormal`' 44 | - '`getCredibleIntervals`' 45 | - '`getDharmaResiduals`' 46 | - '`getPanels`' 47 | - '`getPossibleSamplerTypes`' 48 | - '`getPredictiveDistribution`' 49 | - '`getPredictiveIntervals`' 50 | - '`getSample`' 51 | - '`getVolume`' 52 | - '`GOF`' 53 | - '`likelihoodAR1`' 54 | - '`likelihoodIidNormal`' 55 | - '`logSumExp`' 56 | - '`MAP`' 57 | - '`marginalLikelihood`' 58 | - '`marginalPlot`' 59 | - '`Metropolis`' 60 | - '`metropolisRatio`' 61 | - '`createMixWithDefaults`' 62 | - '`plotSensitivity`' 63 | - '`plotTimeSeries`' 64 | - '`plotTimeSeriesResiduals`' 65 | - '`plotTimeSeriesResults`' 66 | - '`runMCMC`' 67 | - '`sampleMetropolis`' 68 | - '`smcSampler`' 69 | - '`stopParallel`' 70 | - '`testDensityBanana`' 71 | - '`testDensityInfinity`' 72 | - '`testDensityMultiNormal`' 73 | - '`testDensityNormal`' 74 | - '`testLinearModel`' 75 | - '`tracePlot`' 76 | - '`Twalk`' 77 | - '`updateProposalGenerator`' 78 | - '`VSEM`' 79 | - '`vsemC`' 80 | - '`VSEMcreateLikelihood`' 81 | - '`VSEMcreatePAR`' 82 | - '`VSEMgetDefaults`' 83 | - '`WAIC`' 84 | 85 | articles: 86 | - title: All vignettes 87 | desc: ~ 88 | contents: '`BayesianTools`' 89 | 90 | -------------------------------------------------------------------------------- /BayesianTools/R/convertCoda.R: -------------------------------------------------------------------------------- 1 | 2 | #' Convert coda::mcmc objects to BayesianTools::mcmcSampler 3 | #' @description Function is used to make the plot and diagnostic functions 4 | #' available for coda::mcmc objects 5 | #' @param sampler An object of class mcmc or mcmc.list 6 | #' @param names vector giving the parameter names (optional) 7 | #' @param info matrix (or list with matrices for mcmc.list objects) with three coloumns containing log posterior, log likelihood and log prior of the sampler for each time step (optional; but see Details) 8 | #' @param likelihood likelihood function used in the sampling (see Details) 9 | #' @details The parameter 'likelihood' is optional for most functions but can be needed e.g for 10 | #' using the \code{\link{DIC}} function. 11 | #' 12 | #' Also the parameter info is optional for most uses. However for some functions (e.g. \code{\link{MAP}}) 13 | #' the matrix or single coloumns (e.g. log posterior) are necessary for the diagnostics. 14 | #' @export 15 | 16 | convertCoda <- function(sampler, names = NULL, info = NULL, likelihood = NULL){ 17 | 18 | likelihood <- list(density = likelihood) 19 | 20 | if(inherits(sampler, "mcmc")){ 21 | 22 | if(is.null(names)){ 23 | names <- paste("Par",1:ncol(sampler)) 24 | } 25 | setup <- list(names = names, numPars = ncol(sampler), likelihood = likelihood) 26 | 27 | if(is.null(info)) info <- matrix(NA, nrow = nrow(sampler), ncol = 3) 28 | out <- list(chain = cbind(sampler,info), setup = setup) 29 | class(out) = c("mcmcSampler", "bayesianOutput") 30 | 31 | 32 | }else{ if(inherits(sampler, "mcmc.list")){ 33 | 34 | if(is.null(names)){ 35 | names <- paste("Par",1:ncol(sampler[[1]])) 36 | } 37 | setup <- list(names = names, numPars = ncol(sampler[[1]]), likelihood = likelihood) 38 | 39 | if(is.null(info)){ 40 | info <- list() 41 | for(i in 1:length(sampler)) info[[i]] <- matrix(NA, nrow = nrow(sampler[[1]]), ncol = 3) 42 | } 43 | 44 | chain <- list() 45 | for(i in 1:length(sampler)){ 46 | chain[[i]] <- cbind(sampler[[i]], info[[i]]) 47 | } 48 | class(chain) = "mcmc.list" 49 | out <- list(chain = chain, setup = setup) 50 | class(out) = c("mcmcSampler", "bayesianOutput") 51 | }else stop("sampler must be of class 'coda::mcmc' or 'coda::mcmc.list'") 52 | } 53 | return(out) 54 | 55 | } --------------------------------------------------------------------------------