Package: BayesRTMB 0.2.4

BayesRTMB: Bayesian Inference Using 'RTMB'

Provides tools for Markov chain Monte Carlo (MCMC) and Maximum A Posteriori (MAP) estimation utilizing the 'RTMB' package. It supports various statistical models including generalized linear mixed models, factor analysis, item response theory, and multidimensional unfolding. The package allows users to easily transition between frequentist and Bayesian paradigms using a unified interface. Automatic differentiation and Laplace approximation follow Kristensen et al. (2016) <doi:10.18637/jss.v070.i05>, and MCMC sampling uses the No-U-Turn Sampler described by Hoffman and Gelman (2014) <https://jmlr.org/papers/v15/hoffman14a.html>.

Authors:Hiroshi Shimizu [aut, cre]

BayesRTMB_0.2.4.tar.gz
BayesRTMB_0.2.4.zip(r-4.7-any)BayesRTMB_0.2.4.zip(r-4.6-any)BayesRTMB_0.2.4.zip(r-4.5-any)
BayesRTMB_0.2.4.tgz(r-4.6-any)BayesRTMB_0.2.4.tgz(r-4.5-any)
BayesRTMB_0.2.4.tar.gz(r-4.7-any)BayesRTMB_0.2.4.tar.gz(r-4.6-any)
BayesRTMB_0.2.4.tgz(r-4.6-emscripten)
manual.pdf |manual.html
DESCRIPTION |NEWS
card.svg |card.png
BayesRTMB/json (API)

# Install 'BayesRTMB' in R:
install.packages('BayesRTMB', repos = c('https://norimune.r-universe.dev', 'https://cloud.r-project.org'))

Bug tracker:https://github.com/norimune/bayesrtmb/issues

Pkgdown/docs site:https://norimune.github.io

Datasets:
  • beverage - Beverage Preference Data
  • BigFive - Big Five Personality Traits Data
  • debate - Debate Simulation Data
  • training - Social Skills Training Data

On CRAN:

Conda:

6.67 score 3 stars 15 scripts 396 downloads 92 exports 8 dependencies

Last updated from:e45ce3be0e. Checks:9 OK. Indexed: yes.

TargetResultTimeFilesSyslog
linux-devel-x86_64OK195
source / vignettesOK234
linux-release-x86_64OK191
macos-release-arm64OK231
macos-oldrel-arm64OK264
windows-devel-x86_64OK160
windows-release-x86_64OK172
windows-oldrel-x86_64OK152
wasm-releaseOK121

Exports:bayes_factorClassic_Fitconditional_effectsdiffusion_lpdfDimdistanceess_basicess_bulkess_tail95exp_mod_normal_lpdffabsgaussian_process_lpdfinv_logititem_curveitem_infolog_det_chollog_mixlog_softmaxlog_sum_explog_sum_exp_matrixlog1mlog1m_explog1p_explogitlsmeansmake_bw_from_ydifmake_glmer_re_termsmake_glmer_Z_matrixmake_init_mdumake_ydif_from_bwmap_estMAP_FitMCMC_Fitplot_acfplot_conditional_effectsplot_densplot_forestplot_item_curveplot_item_infoplot_lsmeansplot_mduplot_pairsplot_test_infoplot_traceprior_flatprior_jzsprior_normalprior_rhsprior_sspprior_uniformprior_weakquad_form_cholquad_form_diagquantile95r_hatread_mcmc_csvrestore_bw_from_ydifrhat_summaryrtmb_arrayrtmb_codertmb_corrrtmb_faRTMB_Fit_Basertmb_glmrtmb_glmerrtmb_irtrtmb_lmrtmb_lmerrtmb_loglinearrtmb_lrtrtmb_mdurtmb_mediationrtmb_mixturertmb_modelRTMB_Modelrtmb_tablertmb_ttestrtmb_vectorsafe_rtmb_modelsimple_effectssoftmaxsort_loadingssquared_distancestz_basissum_to_zerotest_infoto_centered_matrixto_centered_trito_longto_wideupgrade_fitVB_Fit

Dependencies:latticeMASSMatrixR6RcppRcppEigenRTMBTMB

BayesRTMB Quick Start
Purpose of This Page | 0. Installation and Environment Check | Windows Users | 1. Write a Minimal Model | 2. Create a Model Object | 3. Run MAP Estimation | 4. Inspect the Posterior with MCMC | Parallel MCMC | 5. Visualize MCMC Results | 6. Multiple Regression with a Wrapper Function | 7. Plot an Interaction | 8. Run a Frequentist t Test | 9. Compute a Bayes Factor with a JZS Prior | Next Steps

Last update: 2026-07-24
Started: 2026-04-27

BayesRTMB クイックスタート
このページの目的 | 0. インストールと環境確認 | Windows ユーザー向け | 1. 最小モデルを書く | 2. モデルオブジェクトを作る | 3. MAP 推定を行う | 4. MCMC で事後分布を見る | MCMC を並列化する場合 | 5. MCMC の結果を可視化する | 6. ラッパー関数で重回帰を行う | 7. 交互作用を図で確認する | 8. t 検定を頻度主義的に行う | 9. JZS prior で Bayes factor を計算する | 次に読むページ

Last update: 2026-07-24
Started: 2026-04-23

BayesRTMB の概要
BayesRTMB とは | 記事へのリンク | BayesRTMB でできること | 2つの入口 | ラッパー関数から始める | 自分でモデルを書く | 推定方法の使い分け | MCMC | MAP 推定 | 変分推論 | 頻度主義的分析 | ランダム効果と Laplace 近似 | モデル比較(bridge sampling / WAIC) | bridge sampling による周辺尤度と Bayes factor | WAIC によるモデル比較 | 次のステップ

Last update: 2026-07-24
Started: 2026-04-23

Hierarchical Models and GLMMs with rtmb_glmer()
Purpose | 1. A Minimal Random-Intercept Model | Omitting data | 2. Choosing an Inference Method | MCMC | MAP with Laplace Approximation | Variational Inference | Classical Estimation | 3. Formula Syntax and Visualization | Random Intercepts | Random Slopes | Multiple Grouping Factors | Conditional Effects | 4. Families | 5. Data Handling | Wide Data Can Be Converted Internally | Converting Variables to Factors | Centering Within Cluster | 6. Priors | prior_flat() | prior_normal() | prior_weak() | Regularized Priors | JZS Prior | 7. Residual Correlation | 8. ANOVA-Style Classical Workflows | 9. Inspecting Generated Code | 10. Model Comparison | 11. Related Articles

Last update: 2026-07-24
Started: 2026-05-18

Introduction to BayesRTMB
What is BayesRTMB? | Links to Articles | What BayesRTMB Can Do | Two Entry Points | Starting from Wrapper Functions | Writing Your Own Model | Choosing an Inference Method | MCMC | MAP Estimation | Variational Inference | Frequentist Analysis | Random Effects and Laplace Approximation | Model Comparison (Bridge Sampling / WAIC) | Marginal Likelihood and Bayes Factor by Bridge Sampling | Model Comparison by WAIC | Next Steps

Last update: 2026-07-24
Started: 2026-04-04

rtmb_glmer() で階層モデル・GLMM・分散分析を書く
1. rtmb_glmer() とは | 2. 最小例: ランダム切片モデル | data を省略する | 3. formula の書き方と可視化 | ワイド型データと factors | conditional_effects | 4. family の選び方 | 5. 推定法の使い分け | MCMC | MAP | VB | classic | 6. prior の設計 | prior_flat | prior_normal | prior_weak | prior_rhs と prior_ssp | prior_jzs | 7. 順序カテゴリモデル | 8. 異分散と残差相関 | 9. 分散分析・lsmeans・古典的 mixed model として使う | 10. print_code() で内部モデルを見る | 11. 実践上の注意点

Last update: 2026-07-24
Started: 2026-05-18

Wrapper Functions
1. rtmb_ttest (Bayesian t-test) | Checking the Generated Code | Calculating the Bayes Factor | 2. rtmb_lm (Linear Regression Analysis) | Recommended Settings for Weakly Informative Priors | 3. rtmb_glm (Generalized Linear Models) | Available Distributions (family) | 4. rtmb_glmer (Generalized Linear Mixed Models) | Regularization | 5. Post-Estimation Analysis (Interaction & Visualization) | Visualization with conditional_effects() | Simple Effects Analysis with simple_effects() | 6. rtmb_corr (Correlation Matrix Estimation) | 2-Variable Correlation and Bayes Factor | Correlation Matrix Estimation | 7. rtmb_fa (Exploratory Factor Analysis) | Factor Rotation | Factor Scores | Regularized Factor Analysis | 8. rtmb_irt (Item Response Theory) | Analysis Example (Graded Response Model) | Visualizing Item Response Curves | Item and Test Information | 9. Missing Data Handling | Example: FIML in Factor Analysis (rtmb_fa) | Example: Pairwise Deletion in Correlation (rtmb_corr) | Summary

Last update: 2026-07-24
Started: 2026-04-27

ラッパー関数の使い方
ラッパー関数とは | ラッパー関数一覧 | 推定のイメージ | 頻度主義的分析 | S3メソッド | print_code() | 事後分析 | 欠損値の扱い (Missing Data Handling) | 分析例:因子分析における完全情報最尤法(FIML) | 分析例:相関分析におけるペアワイズ削除(Pairwise) | 次に読む記事

Last update: 2026-07-24
Started: 2026-04-27

BayesRTMB 分析リファレンス
0. このページの読み方 | 目的別クイックナビ | 1. 分析ワークフロー | 1.1 使い分けの目安 | 2. 関数一覧 | 2.1 モデル定義 | 2.2 ラッパー関数 | 2.3 推定メソッド | 3. fit object共通メソッド | 3.1 estimate(), EAP(), MAP() | 3.2 parsとcomponent | 4. MCMC_Fit | 4.1 主要メソッド | 4.2 draws() | 4.3 summary()とdiagnose() | 4.4 transformed_draws()とgenerated_quantities() | 4.5 bridge samplingとBayes factor | 4.6 WAIC | 5. MAP_Fit | 5.1 主要メソッド | 5.2 num_estimateとbest run | 5.3 optimize結果を初期値や固定値に使う | 5.4 profile() | 5.5 MAP_FitのWAIC | 6. VB_Fit | 6.1 主要メソッド | 6.2 num_estimateとbest estimate | 6.3 plot_elbo()による収束確認 | 6.4 VBのWAIC | 7. Classic_Fit | 7.1 主要メソッド | 7.2 ANOVA | 7.3 AIC, BIC, logLik | 7.4 robust_se() | 7.5 lsmeans() | 8. モデル比較と評価指標 | 8.1 Bayes factor | 8.2 WAIC | 8.3 AIC/BIC | 8.4 ELBO | 9. fixedによるパラメータ固定 | 9.1 固定するパラメータ名の確認 | 9.2 fixedの内部処理 | 9.3 fixedの制限 | 9.4 optimize結果を固定値として使う | 9.5 MCMC結果を固定値として使う | 9.6 fixedとBayes factor | 10. rtmb_codeのブロック | 10.1 setupに置くべき処理 | 10.2 transformに置くべき処理 | 10.3 generateに置くべき処理 | 10.4 transformとgenerateの使い分け | 11. パラメータ宣言と型 | 11.1 次元 | 11.2 制約 | 11.3 random = TRUE | 12. 分布一覧 | 12.1 連続分布 | 12.2 離散分布 | 12.3 多変量・行列分布 | 12.4 混合分布・特殊分布 | 13. 数学・安定化関数 | 14. ADテープ化とパフォーマンス | 14.1 setupを活用する | 14.2 ベクトル化を優先する | 14.3 apply系関数を避ける | 14.4 ifとifelseの注意 | 14.5 rtmb_vector()とrtmb_array() | 14.6 テープ化時間とAD評価速度 | 14.7 ADテープ内で避けたい書き方 | 15. 典型的な用途別レシピ | 15.1 MCMCの結果から推定値だけ欲しい | 15.2 初期値をMAPから作ってMCMCを回したい | 15.3 生成量だけを取り出したい | 15.4 random effectsを含めてdrawを取り出したい | 15.5 VBの収束を見たい | 15.6 classicで頻度主義的にモデル比較したい | 15.7 Bayes factorで係数の有無を比較したい | 15.8 fixed modelを明示的に作りたい | 15.9 古いfit objectを新しいクラスに更新したい | 15.10 並列でMCMCを回したい | 16. 注意点

Last update: 2026-07-03
Started: 2026-06-22

BayesRTMB Analysis Reference
0. How To Read This Page | Goal-Oriented Quick Navigation | 1. Analysis Workflow | 1.1 Choosing An Estimation Method | 2. Function Overview | 2.1 Model Definition | 2.2 Wrapper Functions | 2.3 Estimation Methods | 3. Common Fit-Object Methods | 3.1 estimate(), EAP(), and MAP() | 3.2 pars And component | 4. MCMC_Fit | 4.1 Main Methods | 4.2 draws() | 4.3 summary() And diagnose() | 4.4 transformed_draws() And generated_quantities() | 4.5 Bridge Sampling And Bayes Factors | 4.6 WAIC | 5. MAP_Fit | 5.1 Main Methods | 5.2 num_estimate And The Best Run | 5.3 Using Optimization Results As Initial Or Fixed Values | 5.4 profile() | 5.5 WAIC For MAP Fits | 6. VB_Fit | 6.1 Main Methods | 6.2 num_estimate And Best Estimate | 6.3 Checking Convergence With plot_elbo() | 6.4 WAIC For VB Fits | 7. Classic_Fit | 7.1 Main Methods | 7.2 ANOVA | 7.3 AIC, BIC, And logLik | 7.4 robust_se() | 7.5 lsmeans() | 8. Model Comparison And Evaluation Criteria | 8.1 Bayes Factor | 8.2 WAIC | 8.3 AIC/BIC | 8.4 ELBO | 9. Fixing Parameters With fixed | 9.1 Checking Parameter Names | 9.2 Internal Handling Of fixed | 9.3 Limitations Of fixed | 9.4 Using Optimization Results As Fixed Values | 9.5 Using MCMC Results As Fixed Values | 9.6 fixed And Bayes Factors | 10. rtmb_code() Blocks | 10.1 What Belongs In setup | 10.2 What Belongs In transform | 10.3 What Belongs In generate | 10.4 Choosing Between transform And generate | 11. Parameter Declarations And Types | 11.1 Dimensions | 11.2 Constraints | 11.3 random = TRUE | 12. Distribution Overview | 12.1 Continuous Distributions | 12.2 Discrete Distributions | 12.3 Multivariate And Matrix Distributions | 12.4 Mixtures And Special Distributions | 13. Math And Stabilization Functions | 14. AD Taping And Performance | 14.1 Use setup | 14.2 Prefer Vectorization | 14.3 Avoid apply-Style Functions In AD Code | 14.4 Notes On if And ifelse | 14.5 rtmb_vector() And rtmb_array() | 14.6 Taping Time And AD Evaluation Speed | 14.7 Patterns To Avoid Inside AD Tapes | 15. Common Recipes | 15.1 Get Only Estimates From MCMC | 15.2 Use MAP Initial Values For MCMC | 15.3 Extract Only Generated Quantities | 15.4 Extract Draws Including Random Effects | 15.5 Check VB Convergence | 15.6 Compare Models With Classic Estimation | 15.7 Compare Coefficient Inclusion With A Bayes Factor | 15.8 Build A Fixed Model Explicitly | 15.9 Upgrade An Old Fit Object | 15.10 Run MCMC In Parallel | 16. Caveats

Last update: 2026-07-03
Started: 2026-06-23

Writing Model Codes
1. Overview of the Structure and Role of rtmb_code | 1-1. parameters block | 1-2. model block | 1-3. setup block | 1-4. transform block | 1-5. generate block | 2. Available Probability Distributions | 2-1. Common Probability Density and Mass Functions | 2-2. Advanced Probability Distributions | 2-3. Probability Distributions for Special Types | 2-4. User-Defined Distributions | 3. About Parameter Types (Dim) | 4. About Mathematical Functions | 5. AD-Compatible Working Containers | 6. Upgrading Saved Fit Objects | Conclusion

Last update: 2026-07-03
Started: 2026-04-27

モデルの書き方
最小モデル | rtmb_code の構造 | setup | parameters | transform | model | generate | 自作分布を使う | 回帰モデル | 中心化した回帰モデル | 事前分布を書く | 制約つきパラメータ | 階層モデル | 順序モデル | 混合分布モデル | よくある注意点 | data.frame と matrix | model ブロックを複雑にしすぎない | AD型に対する if 文 | 初期値 | random = TRUE | AD対応の作業用コンテナ | 保存済み fit object の更新 | 次に読む記事

Last update: 2026-07-03
Started: 2026-04-25

BayesRTMB の内部構造
1. 全体の流れ | 2. rtmb_code の各ブロック | data | setup | parameters | transform | model | generate | 3. パラメータ表現 | 4. ヤコビアン補正 | 5. RTMB の自動微分オブジェクト | 6. 推定メソッドごとの違い | sample | optimize | variational | classic | 7. optimize と classic の推定結果の違い | 8. Laplace 近似と random | 9. 標準誤差と区間推定 | 10. AD 型のコードを書くときの注意点 | パラメータに依存する if 文 | apply 系の関数 | setup と transform を使い分ける | 11. Stan、TMB、RTMB との関係 | 12. まとめ

Last update: 2026-06-23
Started: 2026-04-27

RTMB Internals and Inference Algorithms
1. Overall Flow | 2. Blocks in rtmb_code() | data | setup | parameters | transform | model | generate | 3. Parameter Representation | 4. Jacobian Correction | 5. RTMB Automatic Differentiation Objects | 6. Inference Methods | sample | optimize | variational | classic | 7. optimize() vs classic() | 8. Laplace Approximation and random | 9. Standard Errors and Intervals | 10. Writing AD-Friendly Code | Avoid parameter-dependent if statements | Be careful with apply-style functions | Use blocks for their intended purposes | 11. Relationship to Stan, TMB, and RTMB | 12. Summary

Last update: 2026-06-23
Started: 2026-05-18

Readme and manuals

Help Manual

Help pageTopics
Automatic Differentiation Variational Inference (ADVI)ADVI_method
Calculate Bayes Factorbayes_factor
Beverage Preference Databeverage
Big Five Personality Traits DataBigFive
Classic fit objectClassic_Fit
Calculate Conditional Effectsconditional_effects
Calculate conditional effects for MCMC fit objectsconditional_effects.mcmc_fit
Debate Simulation Datadebate
Diffusion model log-probability density functiondiffusion_lpdf
Define parameter dimensions and typesDim
Euclidean distancedistance
Probability Distributions for RTMB Modelsdistributions
Basic Effective Sample Size for a single chain or pooled chainsess_basic
Calculate Bulk Effective Sample Sizeess_bulk
Calculate Tail Effective Sample Size (at 2.5% and 97.5% quantiles)ess_tail95
Exponentially modified normal log-probability density functionexp_mod_normal_lpdf
Smooth absolute value functionfabs
Gaussian Process Log-Density (Squared Exponential Kernel)gaussian_process_lpdf
Generate Random Initial Valuesgenerate_random_init
Inverse logit functioninv_logit
Calculate Item Response Curve / Category Response Curveitem_curve
Item Response Curve for RTMB_Fit_Baseitem_curve.RTMB_Fit_Base
Calculate Item Information Functionitem_info
Item Information Function for RTMB_Fit_Baseitem_info.RTMB_Fit_Base
Log determinant of a Cholesky factorlog_det_chol
Log mixture of two probabilitieslog_mix
Log-softmax functionlog_softmax
Log-sum-exp functionlog_sum_exp
Log-sum-exp function for matrices (row-wise)log_sum_exp_matrix
Log of one minus xlog1m
Log of one minus exponential of xlog1m_exp
Log of one plus exponential of xlog1p_exp
Logit functionlogit
Least Squares Means (Marginal Means)lsmeans
Make Best and Worst Responses from Best-Worst Pair Indicesmake_bw_from_ydif restore_bw_from_ydif
Prepare GLMM Formula Componentsmake_glmer_re_terms
Reconstruct an Observation-Level Random-Effect Design Matrixmake_glmer_Z_matrix
Create Initial Values for Multidimensional Unfoldingmake_init_mdu
Make Best-Worst Pair Indices from Best and Worst Responsesmake_ydif_from_bw
Maximum A Posteriori (MAP) Estimatemap_est
MAP fit objectMAP_Fit
Mathematical and Matrix Utility Functions for RTMB Modelsmath_functions
MCMC fit objectMCMC_Fit
Parameter Types and Constraints in RTMB Modelsparameter_types
Code block for parameter definitionsparameters_code
Plot autocorrelation for one variable across chainsplot_acf
Plot conditional effectsplot_conditional_effects
Plot posterior densities for MCMC samplesplot_dens
Plot parameter estimates and credible intervals (Forest Plot)plot_forest
Plot item/category response curvesplot_item_curve
Plot item information functionsplot_item_info
Plot least-squares marginal meansplot_lsmeans
Plot Multidimensional Unfolding Configurationplot_mdu
Plot pairs for posterior samplesplot_pairs
Plot test information functionplot_test_info
Plot MCMC trace plotsplot_trace
Plot method for ce_rtmb class (Base R)plot.ce_rtmb
Plot marginal means with error barsplot.rtmb_lsmeans
Print method for bayes_factor objectsprint.bayes_factor
Print method for bayes_factor_rtmb objectsprint.bayes_factor_rtmb
Print method for ce_rtmb class (automatically calls plot)print.ce_rtmb
Print simple effectsprint.ce_simple
print for summary_BayesRTMB classprint.summary_BayesRTMB
Specify a flat priorprior_flat
Specify a JZS (Jeffrey-Zellner-Siow) prior for t-testsprior_jzs
Specify normal/exponential priors for MAP and Bayesian inferenceprior_normal
Specify a Regularized Horseshoe prior for continuous shrinkageprior_rhs
Specify a Spike-and-Slab prior for variable selectionprior_ssp
Specify a flat priorprior_uniform
Specify a weakly informative priorprior_weak
Quadratic form using a Cholesky factorquad_form_chol
Quadratic form with a diagonal matrixquad_form_diag
Calculate 95% Quantilesquantile95
Calculate Rank-normalized Split-R-hatr_hat
Restore MCMC Fit from CSVread_mcmc_csv
Summarize MCMC R-hat Valuesrhat_summary rhat_summary.default rhat_summary.mcmc_fit
Create an AD-compatible arrayrtmb_array
Define an RTMB Model with Stan-like Syntaxrtmb_code
Fit a Correlation Model using RTMBrtmb_corr
RTMB-based Factor Analysis Wrapperrtmb_fa
Base class for RTMB Fit objectsRTMB_Fit_Base
RTMB-based GLM wrapper function (no random effects)rtmb_glm
RTMB-based GLMM wrapper functionrtmb_glmer
RTMB-based IRT (Item Response Theory) Wrapperrtmb_irt
RTMB-based Linear Regression wrapper functionrtmb_lm
RTMB-based Linear Mixed Model (LMM) wrapper functionrtmb_lmer
RTMB-based Log-linear analysis (Poisson regression)rtmb_loglinear
Fit a Latent Rank Theory (LRT) Modelrtmb_lrt
RTMB-based Multidimensional Unfolding Wrapperrtmb_mdu
RTMB-based Mediation Analysis Wrapperrtmb_mediation
Mixture Model Wrapper for RTMBrtmb_mixture
Create an RTMB_Model Objectrtmb_model
RTMB model objectRTMB_Model RTMB_Model-class
Guidelines for Writing RTMB-Compatible Codertmb_syntax
RTMB-based Contingency Table Analysis (Chi-squared Test)rtmb_table
RTMB-based Bayesian two-sample t-test wrapper functionrtmb_ttest
Create an AD-compatible vectorrtmb_vector
Common Features and Arguments of RTMB Wrapper Functionsrtmb_wrappers
Safe RTMB model construction (with error message translation)safe_rtmb_model
Calculate Simple Effectssimple_effects
Simple effects for MCMC fit objectssimple_effects.mcmc_fit
Softmax functionsoftmax
Sort and display factor loadings neatlysort_loadings
Squared Euclidean distancesquared_distance
stz basis functionstz_basis
Sum-to-zero transformationsum_to_zero
Summary method for ce_rtmb classsummary.ce_rtmb
Calculate Test Information Functiontest_info
Vector to centered matrix (RTMB compatible)to_centered_matrix
Vector to centered triangular matrix (RTMB compatible)to_centered_tri
Convert Wide Data to Long Formatto_long
Vector to lower triangular matrix (RTMB compatible)to_lower_tri
Convert Long Data to Wide Formatto_wide
Social Skills Training Datatraining
Transformed Code Wrapper for RTMBtransform_code
Upgrade a saved fit object to the current BayesRTMB class definitionsupgrade_fit
Pre-validation of data and parametersvalidate_data
VB fit objectVB_Fit