Package: macpan2 3.5.1

Ben Bolker

macpan2: Fast and Flexible Compartmental Modelling

Tools for building and calibrating compartmental models of infectious disease.

Authors:Steve Walker [aut], Weiguang Guan [aut], Jen Freeman [aut], Ben Bolker [cre, aut], Darren Flynn-Primrose [aut], David J.D. Earn [ctb], Jonathan Dushoff [ctb], Irena Papst [ctb], Michael Li [ctb], Kevin Zhao [ctb]

macpan2_3.5.1.tar.gz
macpan2_3.5.1.zip(r-4.7)macpan2_3.5.1.zip(r-4.6)macpan2_3.5.1.zip(r-4.5)
macpan2_3.5.1.tgz(r-4.6-x86_64)macpan2_3.5.1.tgz(r-4.6-arm64)macpan2_3.5.1.tgz(r-4.5-x86_64)macpan2_3.5.1.tgz(r-4.5-arm64)
macpan2_3.5.1.tar.gz(r-4.7-arm64)macpan2_3.5.1.tar.gz(r-4.7-x86_64)macpan2_3.5.1.tar.gz(r-4.6-arm64)macpan2_3.5.1.tar.gz(r-4.6-x86_64)
macpan2_3.5.1.tgz(r-4.6-emscripten)
manual.pdf |manual.html
DESCRIPTION |NEWS
card.svg |card.png
macpan2/json (API)

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

Bug tracker:https://github.com/canmod/macpan2/issues

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

Uses libs:
  • c++– GNU Standard C++ Library v3

On CRAN:

Conda:

compartmental-modelsepidemiologyforecastingmixed-effectsmodel-fittingoptimizationsimulationsimulation-modelingcpp

9.04 score 8 stars 1 packages 401 scripts 171 exports 11 dependencies

Last updated from:13837d8225. Checks:13 OK. Indexed: yes.

TargetResultTimeFilesSyslog
linux-devel-arm64OK439
linux-devel-x86_64OK466
source / vignettesOK623
linux-release-arm64OK432
linux-release-x86_64OK466
macos-release-arm64OK246
macos-release-x86_64OK527
macos-oldrel-arm64OK269
macos-oldrel-x86_64OK646
windows-develOK339
windows-releaseOK315
windows-oldrelOK305
wasm-releaseOK364

Exports:all_consistentall_equalall_not_equalBinaryOperatorCSVReaderdot_layoutempty_matrixempty_trajectoryengine_evalfind_all_pathsJSONReaderLogLogitmp_absolute_flowmp_adjacencymp_aggregatemp_binary_operatormp_cartesianmp_change_framemp_defaultmp_default_listmp_discrete_stochmp_dot_layoutmp_dynamic_modelmp_dynamic_simulatormp_dynamic_varsmp_effects_descrmp_eulermp_euler_multinomialmp_expandmp_extractmp_factorsmp_finalmp_final_listmp_fitmp_flow_framemp_flow_varsmp_forecastermp_functions_usedmp_generates_randomnessmp_groupmp_hazardmp_identitymp_indexmp_inflowmp_initialmp_initial_listmp_joinmp_kronecker_operatormp_labelsmp_layout_gridmp_layout_pathsmp_ledgersmp_linearmp_list_modelsmp_lnormmp_logmp_log_normalmp_log1pmp_logitmp_logit_normalmp_logitnormmp_lookupmp_model_docsmp_model_startermp_nbinommp_neg_binmp_nofitmp_normmp_normalmp_official_librarymp_opt_attemptedmp_optimizemp_optimized_specmp_optimizer_outputmp_other_dynamic_varsmp_outflowmp_parmp_parameterizationmp_per_capita_flowmp_per_capita_inflowmp_per_capita_outflowmp_poismp_poissonmp_positionsmp_print_aftermp_print_beforemp_print_duringmp_print_obj_fnmp_print_specmp_rbfmp_read_rdsmp_reducemp_referencemp_renamemp_rk4mp_rk4_oldmp_set_numbersmp_setdiffmp_show_modelsmp_sim_boundsmp_sim_offsetmp_simulatormp_slicesmp_sqrtmp_squaremp_state_dependence_framemp_state_flow_varsmp_state_varsmp_structured_vectormp_subsetmp_symmetricmp_time_scalemp_tmbmp_tmb_calibratormp_tmb_coefmp_tmb_deletemp_tmb_entire_librarymp_tmb_expr_listmp_tmb_fixef_covmp_tmb_implicit_backtransmp_tmb_implicit_transmp_tmb_insertmp_tmb_insert_backtransmp_tmb_insert_glm_timevarmp_tmb_insert_log_linearmp_tmb_insert_reportsmp_tmb_insert_transmp_tmb_librarymp_tmb_model_specmp_tmb_objectivemp_tmb_profilemp_tmb_updatemp_tmbstan_coefmp_trajmp_trajectorymp_trajectory_ensemblemp_trajectory_parmp_trajectory_replicatemp_trajectory_sdmp_trajectory_simmp_trianglemp_uncertainty_estimatedmp_unifmp_uniformmp_unionmp_versionmp_version_updatemp_zero_vectornlistnot_all_equalNULLReaderrbfReaderRReadershow_modelssi_example_codesi_example_objectsimple_simssparse_matrix_notationStringDataFromDottedStringDataFromFrameto_labelsto_nameto_name_pairsto_namesto_positionsto_stringto_valuesTransformTXTReader

Dependencies:cachemfastmaplatticeMASSMatrixmemoiseoorRcppRcppEigenrlangTMB

Multiplying Matrices in macpan2 Models
Overview | Standard Matrix Multiplication (%*%) | Kronecker Product (%x%) | Elementwise Multiplication with Recycling (*) | Example of Age-Structured Transmission with Elementwise Matrix Multiplication | Multiplying a Sparse Matrix with a Dense Matrix | Extracting Sparse Representation | Small Example of Sparse Matrix Multiplication | Example of Sparse Matrix Multiplication to Model Time-Varying Transmission Rate | Summary of Matrix Operations | When to Use Each

Last update: 2025-08-23
Started: 2025-07-30

Options
Potentially Useful | Logging and Verbosity | Output Data Formatting (for Scalar-Only Models) | Numerical Tolerances | Advanced | Simulation and Reproducibility | Time-Restricted Functions | Engine Control | Deprecated | No Longer or Not Yet Used

Last update: 2025-08-06
Started: 2025-02-19

Quickstart
Hello World | Creating a Simulator | Generating Simulations | Processing Results

Last update: 2025-08-06
Started: 2023-04-06

State-Dependent Rates
Decomposition of State-Dependent Rates | Example -- SIR | Product Models | Example -- SIR times age | Example -- SIR with multiple I-boxes times age | Example -- SIR with multiple I-boxes and partial immunity times age | Example | Bookkeeping (in progress)

Last update: 2025-07-31
Started: 2023-03-31

Structured SI Model with Kronecker Products in macpan2
Introduction | Utilities and Packages | Initial State Vectors | Model Parameters | Derived State Vectors | Per-Capita Transmission Matrix | Per-Capita Force of Infection | Absolute Flows | Allocation Matrices | Euler Step Update | Model Specification | Simulation and Plots | Limitations

Last update: 2025-07-31
Started: 2025-07-30

Calibrating Compartmental Models to Data
Hello, World | Step 0: set up simulator and generate 'data' | Step 1: add calibration information | Step 2: do the fit | Step 3: check the fit | Statistical Model

Last update: 2025-07-09
Started: 2023-06-09

FAQs
Introduction | Setup and Example Models and Data | Naming Conventions | What does macpan2 mean? | Why do most of the functions start with mp_? | Why do some of the functions start with mp_tmb_? | Calibration Details and Outputs | How does macpan2 fit models to data? | How does macpan2 derive confidence intervals? | What likelihood and prior distribution assumptions does macpan2 make? | Can I get a new model specification with fitted parameters as defaults, from a calibrated calibrator object? | Plotting Simulated Trajectories | How can I plot simulated trajectories? | How can I plot a calibrated model with the observed data used in the calibration? | Calibration Troubleshooting | Should I worry about NA/NaN function evaluation warnings? | What should I do if I do not converge? | How do I increase the number of iterations that the optimizer takes? | Parameter Estimation and Uncertainty | What can I do when my confidence intervals include zero for a parameter that should be positive? | Can I weight the importance of trajectories when fitting to more than one of them? | Dynamical Instabilities | What is the best way for me to keep my state variables from going negative? | Initial Conditions | My data start mid-epidemic: how do I know what the initial number of infectious individuals is? | Coding Style | What does |> mean? | Why do you put weird symbols at the start of lines? | Time Variation of Parameters | How can I use a known time series of values? | What if my time-series has missing values? | What can I do if I do not know the functional form of time-variation? | Under Reporting, Delayed Reporting, and Total Reporting | How should I account for under-reporting in macpan2? | How should I account for delayed reporting as well as under-reporting in macpan2? | Can macpan2 use hidden Markov models to account for reporting bias? | Stochastic Simulation | How can I set the seed for the random number generator? | Why do I keep getting the same result even though my model has randomness? | What are the mathematical details of the Euler multinomial process error model? | Does macpan2 implement the Gillespie algorithm? | More Process Error (incomplete)

Last update: 2025-07-09
Started: 2024-11-06

Fitting to Real Data
Setup | One Scarlet Fever Outbreak in Ontario | SIR Model | Modify Model for Reality | Preparing the Data | Set up the Optimizer | Run the Optimization | Examine the fit | Fixing the Optimization Problem | Learning the Functional form of Time Variation in Transmission (New!) | References

Last update: 2025-07-09
Started: 2024-02-26

Specifying Likelihood and Prior Components
Calibration Defaults | Customizing the Objective Function | Use Cases | Priors on model parameters | Likelihoods on model parameters | Fixed distributional parameters | Fitting Distributional Parameters | Distributional Parameter Transformations | Priors on distributional parameters

Last update: 2025-07-09
Started: 2024-10-07

Design Concepts
Information Processing | Modularity | Engine-Agnostic Model Specification Language | Engine-Specific Model Specification Languages | General Dynamic Simulation with TMB | Model Library | Calibration | Specifying Data to Fit | Specifying Distributional Assumptions | Specifying Parameters to Fit | Alternative Trajectory Solvers | Euler Step | Mean Euler-Multinomial (a.k.a. Hazard Correction) | Runge-Kutta 4 | Time-Varying Parameters | Vectors in the TMB Engine | Model Structure and Bookkeeping | Structure in Expressions | Constructive Descriptions of Model Structure | Structured Vectors | Structure Encourages Reparameterization | Alternative Engines | Combining Expression Lists

Last update: 2025-06-02
Started: 2024-01-19

Engine-Agnostic Model Specification Grammar
Amuse bouche: a structured SIR model | Appetizer: specifying the basic SIR model | Main course: expanding the basic SIR with additional structure | Dessert: understanding model simulation in macpan2

Last update: 2025-06-02
Started: 2024-01-18

Advanced Calibration
'Hello, World': an easy (??) calibration exercise | Step 0: set up simulator and generate 'data' | Step 1: add calibration information | Step 2: do the fit | A slightly harder, more realistic example | Computing and plotting confidence and prediction intervals | Hamiltonian MC | Alternative confidence intervals | Irregular data; multiple data streams | 'Hello, World' the hard way | Step 0: recreate the simulator | Step 1: add observed data and slots for history etc. | Step 2: collect simulated values | Step 3: set up and compute objective function | Step 4: declare and/or transform parameters to be optimized, set starting values | Step 5: do the fit | Measles Data -- In-Progress | Challenging Logistic Variation in Transmission Rate | References

Last update: 2025-05-21
Started: 2024-02-22

The C++ Side
Prerequisites | Matrices | Parameters | Trajectory Simulation | Expressions | Parse Tables | Assignment | Assignment Parse Tables | Literals | Function Definitions | Objective Function

Last update: 2025-04-22
Started: 2022-08-25

Elementwise Binary Operators
The Problem | Definition of an Elementwise Binary Operator in the C++ Engine | Forcing a Binary Operator in R to have these Properties | Step 1 | Step 2 | Step 3 | Implementation and Examples

Last update: 2025-04-09
Started: 2022-11-02

Development Principles and Patterns
Introduction | Basics of the macpan2 Object Oriented Framework | Constructing and Using Objects | Defining Classes | Details | Objects | Class Definitions | Inheritance | Principles | Small Classes | Avoid Modifying Well-Tested Classes | Linear Inheritance | Shallow Inheritance Hierarchy | Balance Regeneration with Consistency | Patterns | Alternative Classes | Argument Fields | Static Fields | Standard Methods | Composition | Refresh Methods | Private Methods | Object Editing | Method Caching

Last update: 2025-03-19
Started: 2023-05-31

Example Models
Finding Example Models | Using Examples | Modifying Examples

Last update: 2025-02-20
Started: 2023-05-31

ODE Solvers, Process Error, and Difference Equations
Branching Flows and Process Error | Internal Design | ChangeComponent() classes | The change_frame() method | The flow_frame() method | ChangeModel() classes | UpdateMethod() classes | Relationship to Ordinary Differential Equation Solvers | Euler | Runge Kutta 4 | Euler-Multinomial | Hazard | Linearizing at Each Time-Step | Hazard in models including more than unbalanced per-capita flows

Last update: 2024-10-02
Started: 2024-03-05

Specifying Time-Varying Parameters
Baseline SIR Model | Piecewise Time Variation | Calibrating Time Variation Parameters | Radial Basis Functions for Flexible Time Variation (In-Progress) | Calibration | References

Last update: 2024-05-17
Started: 2023-05-31

Advanced Specification of Time-Varying Parameters
Baseline SIR Model | Piecewise Time Variation | Calibrating Time Variation Parameters | Radial Basis Functions for Flexible Time Variation (In-Progress) | Calibration | References

Last update: 2024-04-08
Started: 2024-04-08

Debugging
Choosing a Debugging Technique

Last update: 2024-01-18
Started: 2024-01-18

Composing Related Simulation Models
Introduction | Notation and Theory | Online Forecasting | Eigenvector State Initialization | Priors on R0 | Regenerating Versus Reparameterizing Models

Last update: 2023-06-14
Started: 2022-11-02

Article Status
Stable | Mature Draft | Working Draft | Stub

Last update: 2023-05-31
Started: 2023-05-31

Readme and manuals

Help Manual

Help pageTopics
Binary OperatorBinaryOperator mp_binary_operator
Comparison Functionsall_consistent all_equal all_not_equal comparison not_all_equal
Distributionsdistribution mp_lnorm mp_logitnorm mp_logit_normal mp_log_normal mp_nbinom mp_neg_bin mp_norm mp_normal mp_pois mp_poisson mp_unif mp_uniform
Create a Graph from a Model Specificationdot_layout mp_dot_layout
Empty Matrixempty_matrix
Empty Trajectoryempty_trajectory
Engine Evaluationengine_eval
Functions Available in the Simulation Engineassign block c cbind cbind_lag cbind_time check_finite clamp col_sums convolution cos cumsum dbinom divide_safe dnbinom dnorm dpois engine_functions exp from_diag group_sums invlogit last log logit matrix mean pgamma pnorm print proportions rbind rbind_lag rbind_time rbinom recycle rep reulermultinom rnbinom rnorm round row_sums rpois sd seq sin sparse_mat_mult sqrt sum t time_group time_step time_var to_diag unpack `%*%` `%x%` `(` `*` `+` `-` `/` `:` `[` `^`
Find all Paths Through Compartmentsfind_all_paths
Fitting Distributional Parametersfit_distr_params mp_fit mp_nofit
LedgersLedgerDefinition
Specify Absolute Flow Between Compartments (Experimental)mp_absolute_flow
Adjacency Matrixmp_adjacency
Aggregate an Indexmp_aggregate
Cartesian Product of Index Tablesmp_cartesian
Data Frame Describing Each Change to Each State Variablemp_change_frame
Default Valuesmp_default mp_default_list
Dynamic Modelmp_dynamic_model
TMB Simulator from Dynamic Modelmp_dynamic_simulator
Describe Statistical Effectsmp_add_effects_descr mp_effects_descr
Expand Modelmp_expand mp_reduce
Extract Indexmp_extract
Factor an Indexmp_factors
Final Valuesmp_final mp_final_list
Data Frame Describing Compartmental Model Flowsmp_flow_frame
Make a Forecastermp_forecaster
Functions Used by an Object for Communicating with a Computational Enginemp_functions_used mp_generates_randomness
Group an Indexmp_group
Model Quantity Index Tablemp_index names.Index print.Index
Initial Values of Variables Immediately Before the Simulation Loopmp_initial mp_initial_list
Join Indexesmp_join
Kronecker Operatormp_kronecker_operator
Index Labelsmp_labels
Flow Diagram Grid Layout (experimental)mp_layout_grid
Flow Diagram Grid Layout (experimental)mp_layout_paths
Bundle up Ledgersmp_ledgers
Linear Chain Productmp_linear
Lookupmp_lookup
Browse Model Docsmp_model_docs
Copy Existing Model as a Starting Pointmp_model_starter
Optimization Attemptedmp_opt_attempted
Optimize Simulation Modelmp_optimize
Optimized Model Specificationmp_optimized_spec
Optimizer Outputmp_optimizer_output
Fit Parametersmp_par
Description of Model Parameterizationmp_parameterization
Specify Flow Into, Out Of, and Between Compartmentsmp_inflow mp_outflow mp_per_capita_flow mp_per_capita_inflow mp_per_capita_outflow
Position Vectorsmp_positions
Print Objective Functionmp_print_obj_fn
Print Model Specificationmp_print_after mp_print_before mp_print_during mp_print_spec
Fit a Time-Varying Parameter with Radial Basis Functionsmp_rbf
Read Serialized Model Specificationmp_read_rds
Reference Indexmp_reference
Rename Index Columnsmp_rename
Print a Table of Existing Modelsmp_list_models mp_show_models show_models
Simulation Boundsmp_sim_bounds
Simulation Offsetsmp_sim_offset
Create a Simulatormp_simulator
Slice an indexmp_slices
Self Cartesian Productmp_square
Data Frame Describing State Dependent Per-Capita Flow Ratesmp_state_dependence_frame
Structured Vectorsmp_set_numbers mp_structured_vector
Subset of Indexesmp_setdiff mp_subset
Symmetric Self Cartesian Productmp_symmetric
Time Scalemp_time_scale
Get Underlying TMB Objectmp_tmb
Make a Calibratormp_tmb_calibrator
TMB Model Coefficient Tablemp_tmb_coef
Expression Listmp_tmb_expr_list
Covariance of Fixed Effect Estimatesmp_tmb_fixef_cov
Transform a TMB Model Specificationmp_tmb_delete mp_tmb_insert mp_tmb_update
Insert Back Transformations of Model Parametersmp_tmb_implicit_backtrans mp_tmb_insert_backtrans
Insert GLM Time Variationmp_tmb_insert_glm_timevar
Insert Log Linear Model of Time Variation (Experimental)mp_tmb_insert_log_linear
Transform a TMB Model Specification to Account for Reporting Biasmp_tmb_insert_reports
Insert Basic Transformations of Model Variablesmp_tmb_implicit_trans mp_tmb_insert_trans
Read Item from a Model Librarymp_official_library mp_tmb_entire_library mp_tmb_library
Create TMB Model Specificationmp_tmb_model_spec
Value of the Objective Function of a Modelmp_tmb_objective
TMB Likelihood Profilingmp_tmb_profile
Model Coefficient Table with stanmp_tmbstan_coef
Trajectory Specificationmp_traj
Simulate Dynamical Model Trajectoriesmp_trajectory mp_trajectory_ensemble mp_trajectory_par mp_trajectory_replicate mp_trajectory_sd mp_trajectory_sim
Self Cartesian Product Excluding One Off-Diagonal Sidemp_triangle
Uncertainty Estimatedmp_uncertainty_estimated
Union of Indexesmp_union
Dynamic Variable Namesmp_dynamic_vars mp_flow_vars mp_other_dynamic_vars mp_state_flow_vars mp_state_vars mp_vars
Version of 'macpan2'mp_version
Version Updatemp_version_update
Zero Vectormp_zero_vector
Names and Labelsnames_and_labels to_labels to_name to_names to_name_pairs to_values
Self Naming Listnlist
Radial Basis Functionsrbf
ReaderCSVReader JSONReader NULLReader Reader RReader TXTReader
SI Examplesi_example si_example_code si_example_object
Simple Iterated Simulationsimple_sims
Extract Sparse Matrix Notation from a Dense Matrixsparse_matrix_notation
Change How State Variables are Updatedmp_discrete_stoch mp_euler mp_euler_multinomial mp_hazard mp_rk4 mp_rk4_old state_updates
String Dataprint.StringData StringData StringDataFromDotted StringDataFromFrame
To Positionsto_positions
To Stringto_string
TransformIdentity Log Logit Transform
Link Functions and Transformationmp_identity mp_log mp_log1p mp_logit mp_sqrt transform_distr_param