| Title: | Modular Monte Carlo Risk Analysis |
|---|---|
| Description: | Framework for building modular Monte Carlo risk analysis models. It extends the capabilities of 'mc2d' to facilitate working with multiple risk pathways, variates and scenarios. It provides tools to organize risk analysis in independent flexible modules, align multivariate mcnodes, automate the creation of mcnodes, visualise model structure, assess convergence, and perform sensitivity analysis. For more details see Ciria (2026) <https://nataliaciria.com/mcmodule/>. |
| Authors: | Natalia Ciria [aut, cre, cph] (ORCID: <https://orcid.org/0009-0006-2669-6634>), Alberto Allepuz [ths] (ORCID: <https://orcid.org/0000-0003-3518-1991>), Giovanna Ciaravino [ths] (ORCID: <https://orcid.org/0000-0002-5796-8093>) |
| Maintainer: | Natalia Ciria <[email protected]> |
| License: | GPL (>= 3) |
| Version: | 1.3.0.9000 |
| Built: | 2026-06-02 15:16:57 UTC |
| Source: | https://github.com/nataliaciria/mcmodule |
Adds a prefix to node names and their input references. Existing prefixes are preserved to avoid breaking references.
add_prefix(mcmodule, prefix = NULL, rewrite_module = NULL)add_prefix(mcmodule, prefix = NULL, rewrite_module = NULL)
mcmodule |
(mcmodule or list). mcmodule object or node_list to prefix. |
prefix |
(character, optional). Prefix to add to node names; defaults to mcmodule name. Default: NULL. |
rewrite_module |
(character, optional). Module name to rewrite prefixes for. Default: NULL. |
The mcmodule with prefixed node names.
print(names(imports_mcmodule$node_list)) imports_mcmodule_prefix<-purchase <- add_prefix(imports_mcmodule) print(names(imports_mcmodule_prefix$node_list))print(names(imports_mcmodule$node_list)) imports_mcmodule_prefix<-purchase <- add_prefix(imports_mcmodule) print(names(imports_mcmodule_prefix$node_list))
Aggregates node values across grouping variables using various methods (combined probability, sum, mean, or automatic selection). Returns an updated mcmodule with new aggregated node.
agg_totals( mcmodule, mc_name, agg_keys = NULL, agg_suffix = NULL, prefix = NULL, name = NULL, summary = TRUE, keep_variates = FALSE, agg_func = NULL )agg_totals( mcmodule, mc_name, agg_keys = NULL, agg_suffix = NULL, prefix = NULL, name = NULL, summary = TRUE, keep_variates = FALSE, agg_func = NULL )
mcmodule |
(mcmodule object). Module containing node list and data. |
mc_name |
(character). Name of node to aggregate. |
agg_keys |
(character vector, optional). Column names for grouping. If NULL, defaults to "scenario_id". Default: NULL. |
agg_suffix |
(character, optional). Suffix for aggregated node name. Default: "agg". |
prefix |
(character, optional). Prefix for output node name. Default: NULL. |
name |
(character, optional). Custom name for output node. Default: NULL. |
summary |
(logical). If TRUE, include summary statistics. Default: TRUE. |
keep_variates |
(logical). If TRUE, preserve individual variate values. Default: FALSE. |
agg_func |
(character, optional). Aggregation method: "prob" (combined probability), "sum", "avg", or NULL (automatic). Default: NULL. |
If sample-design nodes are aggregated, the resulting node will be equal to the original node, but with the "agg_total" type and summary statistics added.
mcmodule with new aggregated node added
imports_mcmodule <- agg_totals( imports_mcmodule, "no_detect", agg_keys = c("scenario_id", "pathogen") ) print(imports_mcmodule$node_list$no_detect_agg$summary)imports_mcmodule <- agg_totals( imports_mcmodule, "no_detect", agg_keys = c("scenario_id", "pathogen") ) print(imports_mcmodule$node_list$no_detect_agg$summary)
A dataset containing information about animal imports from three different regions.
animal_importsanimal_imports
A data frame with 3 rows and 4 columns:
Region of origin (nord, south, east)
Number of farms exporting animals
Mean number of animals exported per farm
Standard deviation of animals exported per farm
Simulated data for demonstration purposes
Combines probabilities of multiple independent events using the formula: P(at least one) = 1 - (1-P(A)) * (1-P(B)) * ... Automatically matches dimensions and keys.
at_least_one( mcmodule, mc_names, name = NULL, all_suffix = NULL, prefix = NULL, summary = TRUE )at_least_one( mcmodule, mc_names, name = NULL, all_suffix = NULL, prefix = NULL, summary = TRUE )
mcmodule |
(mcmodule object). Module containing node list and data frames. |
mc_names |
(character vector). Node names to combine. |
name |
(character, optional). Custom name for combined node. If NULL, auto-generated. Default: NULL. |
all_suffix |
(character). Suffix for auto-generated node name. Default: "all". |
prefix |
(character, optional). Prefix for output node name. Default: NULL. |
summary |
(logical). If TRUE, calculate summary statistics. Default: TRUE. |
Updated mcmodule with new combined probability node.
module <- list( node_list = list( p1 = list( mcnode = mcstoc(runif, min = mcdata(c(0.1, 0.2, 0.3), type = "0", nvariates = 3), max = mcdata(c(0.2, 0.3, 0.4), type = "0", nvariates = 3), nvariates = 3 ), data_name = "data_x", keys = c("category") ), p2 = list( mcnode = mcstoc(runif, min = mcdata(c(0.5, 0.6, 0.7), type = "0", nvariates = 3), max = mcdata(c(0.6, 0.7, 0.8), type = "0", nvariates = 3), nvariates = 3 ), data_name = "data_y", keys = c("category") ) ), data = list( data_x = data.frame( category = c("A", "B", "C"), scenario_id = c("0", "0", "0") ), data_y = data.frame( category = c("B", "B", "B"), scenario_id = c("0", "1", "2") ) ) ) module <- at_least_one(module, c("p1", "p2"), name = "p_combined") print(module$node_list$p_combined$summary)module <- list( node_list = list( p1 = list( mcnode = mcstoc(runif, min = mcdata(c(0.1, 0.2, 0.3), type = "0", nvariates = 3), max = mcdata(c(0.2, 0.3, 0.4), type = "0", nvariates = 3), nvariates = 3 ), data_name = "data_x", keys = c("category") ), p2 = list( mcnode = mcstoc(runif, min = mcdata(c(0.5, 0.6, 0.7), type = "0", nvariates = 3), max = mcdata(c(0.6, 0.7, 0.8), type = "0", nvariates = 3), nvariates = 3 ), data_name = "data_y", keys = c("category") ) ), data = list( data_x = data.frame( category = c("A", "B", "C"), scenario_id = c("0", "0", "0") ), data_y = data.frame( category = c("B", "B", "B"), scenario_id = c("0", "1", "2") ) ) ) module <- at_least_one(module, c("p1", "p2"), name = "p_combined") print(module$node_list$p_combined$summary)
Validates that an mctable contains required columns (mcnode, mc_func),
issues warnings for missing columns, and auto-fills missing optional columns
with NA.
check_mctable(data)check_mctable(data)
data |
(data frame). mctable with |
If mc_func is missing, all nodes are treated as deterministic (no uncertainty).
Optional columns are auto-filled with NA if absent. When sample_space
values are provided, they must use supported formats (c(...) or named
assignments such as min = X, max = Y).
The validated data frame with all standard mctable columns present,
with missing optional columns filled as NA.
Combines two mcmodule objects into a single mcmodule by merging their data and node lists.
combine_modules(mcmodule_x, mcmodule_y)combine_modules(mcmodule_x, mcmodule_y)
mcmodule_x |
(mcmodule object). First module. |
mcmodule_y |
(mcmodule object). Second module. |
An mcmodule object with combined data and node lists.
module_x <- list( data = list(data_x = data.frame(x = 1:3)), node_list = list( node1 = list(type = "in_node"), node2 = list(type = "out_node") ), modules = c("module_x"), exp = quote({node2 <- node1 * 2}) ) module_y <- list( data = list(data_y = data.frame(y = 4:6)), node_list = list(node3 = list(type = "out_node")), modules = c("module_y"), exp = quote({node3 <- node1 + node2}) ) module_xy <- combine_modules(module_x, module_y)module_x <- list( data = list(data_x = data.frame(x = 1:3)), node_list = list( node1 = list(type = "in_node"), node2 = list(type = "out_node") ), modules = c("module_x"), exp = quote({node2 <- node1 * 2}) ) module_y <- list( data = list(data_y = data.frame(y = 4:6)), node_list = list(node3 = list(type = "out_node")), modules = c("module_y"), exp = quote({node3 <- node1 + node2}) ) module_xy <- combine_modules(module_x, module_y)
Creates mcnodes based on mctable specifications and input data. Applies transformations and generates mcnodes in the calling environment.
create_mcnodes(data, mctable = set_mctable(), envir = parent.frame())create_mcnodes(data, mctable = set_mctable(), envir = parent.frame())
data |
(data frame). Input data containing variables for mcnode creation. |
mctable |
(data frame). Configuration table with columns: mcnode, mc_func, transformation, from_variable. |
envir |
(environment, optional). Environment where nodes are created. Default: parent.frame(). |
NULL (invisibly). mcnodes created in envir.
create_mcnodes( data = imports_data, mctable = imports_mctable )create_mcnodes( data = imports_data, mctable = imports_mctable )
Evaluates a model expression or list of expressions to produce an mcmodule
object containing simulation results and metadata. Expression may use
mc2d::mcstoc() and mc2d::mcdata() to create nodes inline; nvariates is automatically
inferred from the data unless sample_design is provided.
eval_module( exp, data = NULL, param_names = NULL, prev_mcmodule = NULL, summary = FALSE, mctable = set_mctable(), data_keys = set_data_keys(), match_keys = NULL, keys = NULL, overwrite_keys = NULL, sample_design = set_sample_design(), if_not_sampled = c("median", "mean", "max", "min"), use_variation = NULL )eval_module( exp, data = NULL, param_names = NULL, prev_mcmodule = NULL, summary = FALSE, mctable = set_mctable(), data_keys = set_data_keys(), match_keys = NULL, keys = NULL, overwrite_keys = NULL, sample_design = set_sample_design(), if_not_sampled = c("median", "mean", "max", "min"), use_variation = NULL )
exp |
(language or list). Model expression or list of expressions to evaluate. |
data |
(data frame). Input data; number of rows determines nvariates for
|
param_names |
(named character vector, optional). Names to rename parameters. Default: NULL. |
prev_mcmodule |
(mcmodule or list, optional). Previous module(s) for dependent calculations. Default: NULL. |
summary |
(logical). If TRUE, calculate summary statistics for output nodes. Default: FALSE. |
mctable |
(data frame). Reference table for mcnodes with |
data_keys |
(list). Data structure and keys for input data. Default:
|
match_keys |
(character vector, optional). Keys to match |
keys |
(character vector, optional). Explicit keys for input data. Default: NULL. |
overwrite_keys |
(logical or NULL). If NULL (default), becomes TRUE when
|
sample_design |
(matrix, data frame, or list, optional). Sampling
design used to create input nodes via |
if_not_sampled |
(character). How to fill input nodes that are required
by the expression but do not appear as columns in |
use_variation |
(character vector, optional). mcnode names to apply
|
mc2d::mcstoc() and mc2d::mcdata() may be used directly inside model expressions.
When these are used you should NOT explicitly supply nvariates, nvariates
will be inferred automatically as the number of rows in the input data.
If sample_design is provided, any inline nvariates argument is removed
and the default nvariates = 1 is used for inline nodes.
Other arguments are preserved, for example specify type = "0" when
providing data without variability/uncertainty (see mc2d::mcdata() and mc2d::mcstoc()).
By design, mcmodule supports type = "V" (the default, with variability) and type = "0" (no variability) nodes. Expressions that specify other node types ("U" or "VU") are not fully supported and downstream compatibility is not guaranteed.
An explicit mctable is optional but highly recommended. If no mctable is
provided, any model nodes that match column names in data will be built
from the data. If a mctable is provided and a node is
not found there but exists as a data column, a warning will be issued and
the node will be created from the data column. When sample_design is provided,
required inputs that match sample_design column names are also created from
sample_design even if they are not listed in mctable.
Within expressions reference input mcnodes by their bare names (e.g.
column1). Do not use data$column1 or data["column1"].
An mcmodule object (list) with elements:
data: List containing input data frames.
exp: List of evaluated expressions.
node_list: Named list of mcnode objects with metadata.
# Basic usage with single expression # Build a quoted expression using mcnodes defined in mctable or built with # mcstoc()/mcdata within the expression (do NOT set nvariates, it is # inferred from nrow(data) when evaluated by eval_module() unless # sample_design is provided, in which case inline nvariates defaults to 1). expr_example <- quote({ # Within-herd prevalence (assigned from a pre-built mcnode w_prev) infected <- w_prev # Estimate of clinic sensitivity clinic_sensi <- mcstoc(runif, min = 0.6, max = 0.8) # Probability an infected animal is tested in origin and not detected false_neg <- infected * test_origin * (1 - test_sensi) * (1 - clinic_sensi) # Probability an infected animal is not tested and not detected no_test <- infected * (1 - test_origin) * (1 - clinic_sensi) # no_detect: total probability an infected animal is not detected no_detect <- false_neg + no_test }) # Evaluate eval_module( exp = expr_example, data = imports_data, mctable = imports_mctable, data_keys = imports_data_keys )# Basic usage with single expression # Build a quoted expression using mcnodes defined in mctable or built with # mcstoc()/mcdata within the expression (do NOT set nvariates, it is # inferred from nrow(data) when evaluated by eval_module() unless # sample_design is provided, in which case inline nvariates defaults to 1). expr_example <- quote({ # Within-herd prevalence (assigned from a pre-built mcnode w_prev) infected <- w_prev # Estimate of clinic sensitivity clinic_sensi <- mcstoc(runif, min = 0.6, max = 0.8) # Probability an infected animal is tested in origin and not detected false_neg <- infected * test_origin * (1 - test_sensi) * (1 - clinic_sensi) # Probability an infected animal is not tested and not detected no_test <- infected * (1 - test_origin) * (1 - clinic_sensi) # no_detect: total probability an infected animal is not detected no_detect <- false_neg + no_test }) # Evaluate eval_module( exp = expr_example, data = imports_data, mctable = imports_mctable, data_keys = imports_data_keys )
Creates a data frame containing edge relationships between nodes in a Monte Carlo module network. Each row represents a directed edge from one node to another.
get_edge_table(mcmodule, inputs = FALSE)get_edge_table(mcmodule, inputs = FALSE)
mcmodule |
(mcmodule object). Module containing node relationships. |
inputs |
(logical). If TRUE, include non-node inputs (datasets, dataframes, and columns). Default: FALSE. |
A data frame with columns node_from and node_to representing
network edges.
edge_table <- get_edge_table(imports_mcmodule)edge_table <- get_edge_table(imports_mcmodule)
Retrieves nodes from a Monte Carlo module and assigns them to the parent environment
get_mcmodule_nodes(mcmodule, mc_names = NULL, envir = parent.frame())get_mcmodule_nodes(mcmodule, mc_names = NULL, envir = parent.frame())
mcmodule |
An mcmodule or mcnode_list object |
mc_names |
Optional vector of node names to retrieve |
envir |
Environment where MC nodes will be created (default: parent.frame()) |
A subset of the node list containing requested nodes
Creates a list of nodes based on a given model expression, handling input, output, and previous nodes with their properties and relationships.
get_node_list( exp, param_names = NULL, mctable = set_mctable(), data_keys = set_data_keys(), keys = NULL )get_node_list( exp, param_names = NULL, mctable = set_mctable(), data_keys = set_data_keys(), keys = NULL )
exp |
An R expression containing model calculations |
param_names |
Optional named vector for parameter renaming |
mctable |
Reference table for mcnodes, defaults to set_mctable() |
data_keys |
Data structure and keys, defaults to set_data_keys() |
keys |
Optional explicit keys for the input data (character vector) |
A list of class "mcnode_list" containing node information
Creates a data frame containing node information from a Monte Carlo module network. Includes node attributes, values, and relationships.
get_node_table(mcmodule, variate = 1, inputs = FALSE)get_node_table(mcmodule, variate = 1, inputs = FALSE)
mcmodule |
(mcmodule object). Module containing node information. |
variate |
(integer). Which variate to extract. Default: 1. |
inputs |
(logical). If TRUE, include non-node inputs (datasets, dataframes, and columns). Default: FALSE. |
A data frame containing node information and attributes.
node_table <- get_node_table(imports_mcmodule)node_table <- get_node_table(imports_mcmodule)
A dataset combining information about animal imports, pathogen prevalence, and test sensitivity across regions.
imports_dataimports_data
A data frame with 6 rows and 12 columns:
Pathogen identifier (a or b)
Region of origin (nord, south, east)
Minimum herd prevalence value
Maximum herd prevalence value
Minimum within-herd prevalence value
Maximum within-herd prevalence value
Number of farms exporting animals
Mean number of animals exported per farm
Standard deviation of animals exported per farm
Test used to detect infected animals at origin
Minimum test sensitivity value
Most likely test sensitivity value
Maximum test sensitivity value
Simulated data for demonstration purposes
A hierarchical data structure containing test sensitivity, animal import, and regional prevalence information, each with defined columns and keys.
imports_data_keysimports_data_keys
A list with three components:
List containing column names for test sensitivity data and "pathogen" as key
List containing column names for animal import data and "origin" as key
List containing column names for prevalence data with "pathogen" and "origin" as keys
Simulated data for demonstration purposes
A quoted R expression that calculates the probability of importing an infected animal from an infected herd, taking into account testing procedures and accuracy.
imports_expimports_exp
A quoted R expression containing the following variables:
Within-herd prevalence
Probability of testing at origin
Test sensitivity
Probability of animal being infected
Probability of false negative test result
Probability of no testing
Overall probability of non-detection
A list containing simulation results for pathogen testing of animal imports from different origins, including:
Within-herd prevalence (w_prev)
Test sensitivity (test_sensi)
Test origin probability (test_origin)
Infection probability (infected)
False negative probability (false_neg)
No test probability (no_test)
Non-detection probability (no_detect)
imports_mcmoduleimports_mcmodule
An mcmodule object with the following components:
Input data frame with 6 rows and 13 variables
Model expressions for calculating probabilities
List of Monte Carlo nodes with simulation results
Character vector of module names
Simulated data for demonstration purposes
A configured table of Monte Carlo nodes used for modeling import risk scenarios, particularly focused on animal disease transmission pathways.
imports_mctableimports_mctable
A data frame with 7 rows and 7 columns:
Node identifier used in Monte Carlo simulations
Human-readable description of what the node represents
R function used for random number generation (e.g., runif, rnorm, rpert)
Dependency reference to other variables if applicable
Mathematical transformations applied to the node values
Allowed values for the input. Use min/max for numeric ranges (e.g., min=0, max=1) and explicit vectors for factors/logicals (e.g., c("a", "b", "c") or c(TRUE, FALSE))
OAT variation expression using 'value' placeholder
Simulated data for demonstration purposes
Matches and aligns keys between two datasets for downstream operations.
keys_match(x, y, keys_names = NULL, match_scenario = TRUE)keys_match(x, y, keys_names = NULL, match_scenario = TRUE)
x |
First dataset containing keys to match |
y |
Second dataset containing keys to match |
keys_names |
Names of columns to use as matching keys. If NULL, uses common columns |
match_scenario |
(logical). If TRUE, exclude scenario_id from matching keys. If FALSE, include scenario_id. Default: TRUE. |
A list containing:
x |
First dataset with group IDs |
y |
Second dataset with group IDs |
xy |
Matched datasets with aligned group and scenario IDs |
Creates one mcdata mcnode per column in X, using ndvar = nrow(X).
This is useful when X is a design matrix generated by sensitivity::sensitivity
functions or sensobol::sobol_matrices().
matrix_to_mcnodes(X, envir = parent.frame())matrix_to_mcnodes(X, envir = parent.frame())
X |
(matrix or data frame). Input values with one mcnode per column. |
envir |
(environment, optional). Environment where nodes are created. Default: parent.frame(). |
NULL (invisibly). mcnodes created in envir.
X <- matrix(c(0.1, 0.2, 0.3, 10, 11, 12), ncol = 2) colnames(X) <- c("a", "b") matrix_to_mcnodes(X)X <- matrix(c(0.1, 0.2, 0.3, 10, 11, 12), ncol = 2) colnames(X) <- c("a", "b") matrix_to_mcnodes(X)
Compares an mcnode's what-if scenarios against a baseline scenario (default "0") using various comparison metrics. Returns an mcmodule with a new comparison node.
mc_compare( mcmodule, mc_name, baseline = "0", type = "difference", keys_names = NULL, name = NULL, prefix = NULL, suffix = "compared", summary = TRUE, align_uncertainty = TRUE )mc_compare( mcmodule, mc_name, baseline = "0", type = "difference", keys_names = NULL, name = NULL, prefix = NULL, suffix = "compared", summary = TRUE, align_uncertainty = TRUE )
mcmodule |
(mcmodule object). Module containing the node. |
mc_name |
(character). Name of the mcnode to compare. |
baseline |
(character). Baseline scenario ID to compare against. Default: "0". |
type |
(character). Type of comparison. One of:
|
keys_names |
(character vector, optional). Column names for grouping. If NULL, uses keys from the node. Default: NULL. |
name |
(character, optional). Name for the new comparison node. If NULL,
auto-generated from |
prefix |
(character, optional). Prefix for the auto-generated node name. Default: NULL. |
suffix |
(character). Suffix appended to auto-generated name. Default: "compared". |
summary |
(logical). If TRUE, compute summary statistics for the new node. Default: TRUE. |
align_uncertainty |
(logical). If TRUE, align uncertainty iterations between baseline and what-if nodes using rank correlation (Spearman). This ensures that the same uncertainty iteration in both nodes represents similar uncertainty realizations, making comparisons more meaningful when nodes have multivariate dimensions. Default: TRUE. |
This function compares what-if scenarios against a baseline by:
Filtering the baseline scenario (scenario_id == baseline)
Filtering what-if scenarios (scenario_id != baseline)
Matching them across scenarios using keys
Optionally aligning uncertainty iterations using rank correlation
Applying the selected comparison formula
Creating a new comparison node in the mcmodule
When align_uncertainty = TRUE, the function uses mc2d::cornode() to align
the uncertainty iterations between matched baseline and what-if nodes. For
multivariate nodes, correlation is applied independently to each variate.
For derived nodes with pre-computed summaries (types "filter", "compare",
or "agg_total"), scenario filtering and key alignment use the node's
summary by default as the source data.
The baseline scenario must contain all key combinations present in what-if scenarios. If what-if scenarios are missing key combinations present in baseline, those are interpreted as having baseline values (no change).
Updated mcmodule with a new comparison node containing:
mcnode: Comparison values as mcnode object
type: "compare"
baseline: Baseline scenario ID
compare_type: Type of comparison performed
param: Original node name
inputs: Original node name
keys: Same keys as original node
summary: Summary statistics (if summary = TRUE)
# Create example data with baseline and what-if scenarios example_data <- data.frame( origin = c("A", "B", "A", "B"), scenario_id = c("0", "0", "1", "1") ) # Create mcnodes for each scenario example_mcnode <- mc2d::mcstoc( runif, min = mc2d::mcdata(c(0.1, 0.2, 0.15, 0.25), type = "0", nvariates = 4), max = mc2d::mcdata(c(0.2, 0.3, 0.25, 0.35), type = "0", nvariates = 4), nvariates = 4 ) # Create mcmodule example_module <- list( data = list(example_data = example_data), node_list = list( risk = list( mcnode = example_mcnode, data_name = "example_data", keys = c("origin") ) ) ) # Compare what-if scenario "1" against baseline "0" result <- mc_compare( example_module, "risk", baseline = "0", type = "relative_reduction" ) # View comparison results result$node_list$risk_compared$summary# Create example data with baseline and what-if scenarios example_data <- data.frame( origin = c("A", "B", "A", "B"), scenario_id = c("0", "0", "1", "1") ) # Create mcnodes for each scenario example_mcnode <- mc2d::mcstoc( runif, min = mc2d::mcdata(c(0.1, 0.2, 0.15, 0.25), type = "0", nvariates = 4), max = mc2d::mcdata(c(0.2, 0.3, 0.25, 0.35), type = "0", nvariates = 4), nvariates = 4 ) # Create mcmodule example_module <- list( data = list(example_data = example_data), node_list = list( risk = list( mcnode = example_mcnode, data_name = "example_data", keys = c("origin") ) ) ) # Compare what-if scenario "1" against baseline "0" result <- mc_compare( example_module, "risk", baseline = "0", type = "relative_reduction" ) # View comparison results result$node_list$risk_compared$summary
Filters variates (data rows) from an mcnode based on logical conditions,
similar to dplyr::filter(). Can return a new node in the mcmodule or
return a filtered mcnode directly.
mc_filter( mcmodule = NULL, mc_name = NULL, ..., data = NULL, mcnode = NULL, name = NULL, prefix = NULL, suffix = "filtered", summary = TRUE )mc_filter( mcmodule = NULL, mc_name = NULL, ..., data = NULL, mcnode = NULL, name = NULL, prefix = NULL, suffix = "filtered", summary = TRUE )
mcmodule |
(mcmodule object, optional). Module containing the node. Default: NULL. |
mc_name |
(character, optional). Name of the mcnode in the module. |
... |
(expression). Logical conditions to filter by; evaluated in context of the data associated with the mcnode. |
data |
(data frame, optional). Input data frame. Default: NULL. |
mcnode |
(mcnode object, optional). mcnode to filter directly. Default: NULL. |
name |
(character, optional). Name for the new filtered node when adding to
mcmodule. If NULL, auto-generated from |
prefix |
(character, optional). Prefix for the auto-generated node name. Default: NULL. |
suffix |
(character). Suffix appended to auto-generated name. Default: "filtered". |
summary |
(logical). If TRUE, compute summary statistics for the new node. Default: TRUE. |
Call signatures:
To add filtered node to mcmodule: mc_filter(mcmodule, "node", conditions, name = "new_name")
To return filtered mcnode only: mc_filter(conditions, data = data, mcnode = mcnode)
Filter conditions work on variates (data rows); only rows meeting all conditions are retained in the resulting mcnode.
For derived nodes with pre-computed summaries (types "filter", "compare",
or "agg_total"), filtering uses the node's summary by default as the data
source (instead of mcmodule$data[[data_name]]) so variate alignment is
preserved.
Either:
Updated mcmodule with new filtered node (when mcmodule and name provided).
Filtered mcnode object (when only data and mcnode provided).
Either:
An updated mcmodule with a new filtered node (when mcmodule and name are provided)
A raw filtered mcnode object (when only data and mcnode are provided)
# Filter within an mcmodule and create new node imports_mcmodule <- mc_filter( imports_mcmodule, "w_prev", origin == "nord", name = "w_prev_countryA" ) # Filter and return raw mcnode (note: conditions before named args) w_prev <- imports_mcmodule$node_list$w_prev$mcnode w_prev_filtered <- mc_filter( origin == "nord", data = imports_data, mcnode = w_prev ) # Multiple filter conditions imports_mcmodule <- mc_filter( imports_mcmodule, "w_prev", origin == "nord", pathogen == "virus", name = "w_prev_countryA_virus" )# Filter within an mcmodule and create new node imports_mcmodule <- mc_filter( imports_mcmodule, "w_prev", origin == "nord", name = "w_prev_countryA" ) # Filter and return raw mcnode (note: conditions before named args) w_prev <- imports_mcmodule$node_list$w_prev$mcnode w_prev_filtered <- mc_filter( origin == "nord", data = imports_data, mcnode = w_prev ) # Multiple filter conditions imports_mcmodule <- mc_filter( imports_mcmodule, "w_prev", origin == "nord", pathogen == "virus", name = "w_prev_countryA_virus" )
Extracts key columns from a mcnode's associated data.
mc_keys(mcmodule, mc_name, keys_names = NULL)mc_keys(mcmodule, mc_name, keys_names = NULL)
mcmodule |
(mcmodule object). Module containing node. |
mc_name |
(character). Node name to extract keys from. |
keys_names |
(character vector, optional). Column names to extract. If NULL, uses all keys for the node. Default: NULL. |
Sample-design nodes are treated as row-aligned inputs: they have no data
name or key columns, and key extraction returns only scenario_id.
A data frame with scenario_id and requested key columns.
keys_df <- mc_keys(imports_mcmodule, "w_prev")keys_df <- mc_keys(imports_mcmodule, "w_prev")
Matches two mcnodes by aligning groups, scenarios, or adding missing groups across different scenarios.
mc_match( mcmodule, mc_name_x, mc_name_y, keys_names = NULL, match_scenario = TRUE )mc_match( mcmodule, mc_name_x, mc_name_y, keys_names = NULL, match_scenario = TRUE )
mcmodule |
(mcmodule object). Module containing nodes. |
mc_name_x |
(character). First mcnode name. |
mc_name_y |
(character). Second mcnode name. |
keys_names |
(character vector, optional). Column names for matching. Default: NULL. |
match_scenario |
(logical). If TRUE, scenario_id is used for alignment (default behavior). If FALSE, scenario_id is treated as a regular key, enabling cross-scenario matching. Default: TRUE. |
Matching proceeds in order:
Group matching — align nodes with same scenarios but different group order
Scenario matching — align nodes with same groups but different scenarios
Null matching — add missing groups across different scenarios
Sample-design nodes behave as 1-variate that can be matched directly.
A list containing matched nodes and combined keys (keys_xy).
test_module <- list( node_list = list( node_x = list( mcnode = mcstoc(runif, min = mcdata(c(1, 2, 3), type = "0", nvariates = 3), max = mcdata(c(2, 3, 4), type = "0", nvariates = 3), nvariates = 3 ), data_name = "data_x", keys = c("category") ), node_y = list( mcnode = mcstoc(runif, min = mcdata(c(5, 6, 7), type = "0", nvariates = 3), max = mcdata(c(6, 7, 8), type = "0", nvariates = 3), nvariates = 3 ), data_name = "data_y", keys = c("category") ) ), data = list( data_x = data.frame( category = c("A", "B", "C"), scenario_id = c("0", "0", "0") ), data_y = data.frame( category = c("B", "B", "B"), scenario_id = c("0", "1", "2") ) ) ) result <- mc_match(test_module, "node_x", "node_y")test_module <- list( node_list = list( node_x = list( mcnode = mcstoc(runif, min = mcdata(c(1, 2, 3), type = "0", nvariates = 3), max = mcdata(c(2, 3, 4), type = "0", nvariates = 3), nvariates = 3 ), data_name = "data_x", keys = c("category") ), node_y = list( mcnode = mcstoc(runif, min = mcdata(c(5, 6, 7), type = "0", nvariates = 3), max = mcdata(c(6, 7, 8), type = "0", nvariates = 3), nvariates = 3 ), data_name = "data_y", keys = c("category") ) ), data = list( data_x = data.frame( category = c("A", "B", "C"), scenario_id = c("0", "0", "0") ), data_y = data.frame( category = c("B", "B", "B"), scenario_id = c("0", "1", "2") ) ) ) result <- mc_match(test_module, "node_x", "node_y")
Matches an mcnode with a data frame by aligning groups, scenarios, or adding missing groups across different scenarios.
mc_match_data( mcmodule, mc_name, data, keys_names = NULL, match_scenario = TRUE )mc_match_data( mcmodule, mc_name, data, keys_names = NULL, match_scenario = TRUE )
mcmodule |
(mcmodule object). Module containing node. |
mc_name |
(character). Node name. |
data |
(data frame). Data to match with mcnode. |
keys_names |
(character vector, optional). Column names for matching. Default: NULL. |
match_scenario |
(logical). If TRUE, scenario_id is used for alignment (default behavior). If FALSE, scenario_id is treated as a regular key, enabling cross-scenario matching. Default: TRUE. |
Matching proceeds in order:
Group matching — same scenarios but different group order
Scenario matching — same groups but different scenarios
Null matching — add missing groups across different scenarios
Sample-design nodes behave as 1-variate that can be matched directly.
A list containing matched mcnode, matched data, and combined keys
(keys_xy).
test_data <- data.frame(pathogen=c("a","b"), inf_dc_min=c(0.05,0.3), inf_dc_max=c(0.08,0.4)) result<-mc_match_data(imports_mcmodule,"no_detect", test_data)test_data <- data.frame(pathogen=c("a","b"), inf_dc_min=c(0.05,0.3), inf_dc_max=c(0.08,0.4)) result<-mc_match_data(imports_mcmodule,"no_detect", test_data)
Generates an interactive network visualisation using visNetwork library. The visualisation includes interactive features for exploring model structure and relationships.
By default, nodes are colored as:
inputs (light blue, #B0DFF9): Input datasets, data frames, files, and columns
in_node (blue, #6ABDEB): Input nodes and scalar values
out_node (green, #A4CF96): Output nodes
filter (light purple, #E8A5E5): Filtered nodes created with mc_filter()
compare (medium purple, #D88FD5): Comparison nodes created with mc_compare()
trials_info (light orange, #FAE4CB): Trial, subset, and related information nodes
total (orange, #F39200): Total nodes created with at_least_one()
agg_total (dark orange, #C17816): Aggregated total nodes created with agg_totals()
mc_network( mcmodule, variate = 1, color_pal = NULL, color_by = NULL, legend = FALSE, inputs = FALSE )mc_network( mcmodule, variate = 1, color_pal = NULL, color_by = NULL, legend = FALSE, inputs = FALSE )
mcmodule |
(mcmodule object). Module containing network to visualise. |
variate |
(integer). Which variate to visualise. Default: 1. |
color_pal |
(character vector, optional). Custom colour palette for nodes. Default: NULL. |
color_by |
(character, optional). Column name to determine node colours. Default: NULL. |
legend |
(logical). If TRUE, show colours legend. Default: FALSE. |
inputs |
(logical). If TRUE, show non-node inputs. Default: FALSE. |
An interactive visNetwork object with highlighting of connected nodes, node selection and filtering by module, directional arrows, hierarchical layout, and draggable nodes.
network <- mc_network(mcmodule=imports_mcmodule)network <- mc_network(mcmodule=imports_mcmodule)
Creates a ggplot2 visualisation of Monte Carlo node data showing distributions as semi-transparent boxplots overlaid with scatter points representing individual uncertainty iterations.
mc_plot( mcmodule = NULL, mc_name = NULL, mcnode = NULL, data = NULL, keys_names = NULL, color_by = NULL, order_by = NULL, group_by = NULL, filter = NULL, threshold = NULL, scale = NULL, max_dots = 300, point_alpha = 0.4, boxplot_alpha = 0.3, color_pal = NULL )mc_plot( mcmodule = NULL, mc_name = NULL, mcnode = NULL, data = NULL, keys_names = NULL, color_by = NULL, order_by = NULL, group_by = NULL, filter = NULL, threshold = NULL, scale = NULL, max_dots = 300, point_alpha = 0.4, boxplot_alpha = 0.3, color_pal = NULL )
mcmodule |
(mcmodule object, optional). Module containing the node. |
mc_name |
(character, optional). Name of the mcnode in the module. |
mcnode |
(mcnode object, optional). mcnode to plot directly. |
data |
(data frame, optional). Input data. If NULL, extracted from |
keys_names |
(character vector, optional). Column names for grouping variates. If NULL, uses node keys from module or row indices. Default: NULL. |
color_by |
(character, optional). Column name to colour points and boxplot.
Must be in |
order_by |
(character, optional). Column name or "median" to reorder y-axis groups. If "median", groups ordered by median value. Default: NULL. |
group_by |
(character, optional). Column name to group variates (e.g., "commodity"). Variates organised so all scenarios per group appear together. Default: NULL. |
filter |
(expression, optional). Unquoted expression to filter variates
(e.g., |
threshold |
(numeric, optional). Reference value for vertical dashed line. Default: NULL. |
scale |
(character, optional). Transformation for x-axis: "identity" (default), "log10", "log", "sqrt", or "asinh". Default: NULL. |
max_dots |
(integer). Maximum dots per variate; exceeding this triggers representative sampling. Boxplots always use all simulations. Default: 300. |
point_alpha |
(numeric). Transparency for points (0–1). Default: 0.4. |
boxplot_alpha |
(numeric). Transparency for boxplots (0–1). Default: 0.3. |
color_pal |
(character vector, optional). Named vector of colours for
|
When color_by is NULL, scenarios are coloured by default:
— baseline scenario (scenario_id == "0"): blue (#6ABDEB);
— alternative scenarios: green (#A4CF96).
Boxplots show all uncertainty iterations for statistical accuracy;
scatter points are sampled to improve readability with many variates.
A ggplot2 object for further customisation and display.
# Basic plot using mcmodule and mc_name mc_plot(imports_mcmodule, "w_prev") # Plot with custom coloring and ordering mc_plot(imports_mcmodule, "w_prev", color_by = "origin", order_by = "median" ) # Plot with threshold and scale transformation mc_plot(imports_mcmodule, "no_detect", threshold = 0.5, scale = "log10" )# Basic plot using mcmodule and mc_name mc_plot(imports_mcmodule, "w_prev") # Plot with custom coloring and ordering mc_plot(imports_mcmodule, "w_prev", color_by = "origin", order_by = "median" ) # Plot with threshold and scale transformation mc_plot(imports_mcmodule, "no_detect", threshold = 0.5, scale = "log10" )
Computes summary statistics for an mcnode object, including mean, standard deviation, and quantiles. Can be called with an mcmodule and node name, or directly with an mcnode and data frame.
mc_summary( mcmodule = NULL, mc_name = NULL, keys_names = NULL, data = NULL, mcnode = NULL, sep_keys = TRUE, digits = NULL )mc_summary( mcmodule = NULL, mc_name = NULL, keys_names = NULL, data = NULL, mcnode = NULL, sep_keys = TRUE, digits = NULL )
mcmodule |
(mcmodule object, optional). Module containing the node. Default: NULL. |
mc_name |
(character, optional). Name of the mcnode in the module. |
keys_names |
(character vector, optional). Column names for grouping. Default: NULL. |
data |
(data frame, optional). Input data frame. Default: NULL. |
mcnode |
(mcnode object, optional). mcnode to summarise directly. Default: NULL. |
sep_keys |
(logical). If TRUE, keep keys in separate columns; if FALSE, combine into single column. Default: TRUE. |
digits |
(integer, optional). Number of significant digits for rounding. Default: NULL. |
This function can be called in two ways:
By providing an mcmodule and mc_name
By providing data and mcnode directly
For filtered nodes (type = "filter"), compared nodes (type = "compare"), and aggregated nodes (type = "agg_total"), this function returns the pre-calculated summary statistics that were computed when the node was created, rather than recalculating from the original data.
A data frame with summary statistics for each mcnode variate. Columns include:
mc_name: Node name.
Key columns (if sep_keys = TRUE) or single keys column (if FALSE).
mean: Average value.
sd: Standard deviation.
Quantile columns (2.5%, 25%, 50%, 75%, 97.5%).
# Use with mcmodule summary_basic <- mc_summary(imports_mcmodule, "w_prev") # Using custom keys and rounding summary_custom <- mc_summary(imports_mcmodule, "w_prev", keys_names = c("origin"), digits = 3 ) # Use with data and mcnode w_prev <- imports_mcmodule$node_list$w_prev$mcnode summary_direct <- mc_summary( data = imports_data, mcnode = w_prev, sep_keys = FALSE )# Use with mcmodule summary_basic <- mc_summary(imports_mcmodule, "w_prev") # Using custom keys and rounding summary_custom <- mc_summary(imports_mcmodule, "w_prev", keys_names = c("origin"), digits = 3 ) # Use with data and mcnode w_prev <- imports_mcmodule$node_list$w_prev$mcnode summary_direct <- mc_summary( data = imports_data, mcnode = w_prev, sep_keys = FALSE )
Analyses convergence in Monte Carlo simulations by computing standardised and raw differences between consecutive iterations to evaluate stability and convergence of statistical measures.
mcmodule_converg( mcmodule, from_quantile = 0.95, to_quantile = 1, conv_threshold = NULL, tiny_threshold = NULL, print_summary = TRUE, progress = FALSE, mc_names = NULL )mcmodule_converg( mcmodule, from_quantile = 0.95, to_quantile = 1, conv_threshold = NULL, tiny_threshold = NULL, print_summary = TRUE, progress = FALSE, mc_names = NULL )
mcmodule |
(mcmodule object). Module containing simulation results. |
from_quantile |
(numeric). Lower bound quantile for analysis. Default: 0.95. |
to_quantile |
(numeric). Upper bound quantile for analysis. Default: 1. |
conv_threshold |
(numeric, optional). Custom convergence threshold for standardised differences. Default: NULL. |
tiny_threshold |
(numeric). Threshold for identifying negligible differences, even if they don't meet the convergence threshold. Default: 0.0001. |
print_summary |
(logical). If TRUE, print convergence analysis summary. Default: TRUE. |
progress |
(logical). If TRUE, print progress information. Default: FALSE. |
mc_names |
(character vector, optional). Node names to include in analysis. If NULL (default), includes all nodes in the module. Default: NULL. |
The function performs the following:
Calculates convergence statistics for specified quantile range
Generates diagnostic plots for standardized and raw differences
Provides detailed convergence summary including:
Total nodes analyzed
Number and percentage of nodes converged at different thresholds
Maximum/minimum deviations
List of non-converged nodes (if any)
A data frame with convergence statistics. Each row represents one node. Key columns:
expression: Expression identifier.
variate: Variate (data row) identifier.
node: Node name.
max_dif_scaled: Maximum standardised difference.
max_dif: Maximum raw difference.
conv_01, conv_025, conv_05: Convergence at 1%, 2.5%, 5% thresholds.
## Not run: results <- mcmodule_converg(mc_results) results <- mcmodule_converg(mc_results, from_quantile = 0.90, conv_threshold = 0.01) ## End(Not run)## Not run: results <- mcmodule_converg(mc_results) results <- mcmodule_converg(mc_results, from_quantile = 0.90, conv_threshold = 0.01) ## End(Not run)
Computes correlation coefficients between mcmodule inputs and outputs using
tornado analysis (from the mc2d package). Supports multiple correlation methods
and captures warnings generated during calculation.
mcmodule_corr( mcmodule, output = NULL, by_exp = FALSE, match_variates = TRUE, variates_as_nsv = FALSE, mc_names = NULL, print_summary = TRUE, progress = FALSE, method = c("spearman", "kendall", "pearson"), use = "all.obs", lim = c(0.025, 0.975), plot = FALSE )mcmodule_corr( mcmodule, output = NULL, by_exp = FALSE, match_variates = TRUE, variates_as_nsv = FALSE, mc_names = NULL, print_summary = TRUE, progress = FALSE, method = c("spearman", "kendall", "pearson"), use = "all.obs", lim = c(0.025, 0.975), plot = FALSE )
mcmodule |
(mcmodule object). Module containing simulation results. |
output |
(character, optional). Output node name. If NULL (default), uses
the last node in |
by_exp |
(logical). If TRUE, calculate correlations by expression output; if FALSE, use global output (last node). Default: FALSE. |
match_variates |
(logical). If TRUE, match input nodes to output variates when data dimensions differ. Default: TRUE. |
variates_as_nsv |
(logical). If TRUE, combine all variates into one |
mc_names |
(character vector, optional). Node names to include in analysis. If NULL (default), includes all nodes in the module. Default: NULL. |
print_summary |
(logical). If TRUE, print correlation analysis summary. Default: TRUE. |
progress |
(logical). If TRUE, print progress information while running. Default: FALSE. |
method |
(character). Correlation coefficient type: "spearman" (default),
"kendall", or "pearson". See |
use |
(character). Method for handling missing values: "all.obs",
"complete.obs", or "pairwise.complete.obs". See |
lim |
(numeric vector). Quantiles for credible interval computation (reserved
for two-dimensional models). Default: |
plot |
(logical). If TRUE, plots a tornado plot generated from the
computed correlation table using |
A data frame with correlation coefficients and metadata. Columns include:
exp: Expression name
exp_n: Expression number
variate: Variate number
output: Output node names
input: Input node name
value: Correlation coefficient value
strength: Qualitative strength of association (Very strong, Strong, Moderate, Weak, Very weak/None)
method: Correlation method used (spearman, kendall, or pearson)
use: Method for handling missing values (passed to the correlation function)
warnings: Any warnings generated during correlation calculation (if present)
Additional columns for global keys (e.g., pathogen, origin)
mcmodule <- agg_totals( mcmodule = imports_mcmodule, mc_name = "no_detect", agg_keys = "pathogen" ) cor_results <- mcmodule_corr(mcmodule) # Use single method cor_results_spearman <- mcmodule_corr(mcmodule, method = "spearman")mcmodule <- agg_totals( mcmodule = imports_mcmodule, mc_name = "no_detect", agg_keys = "pathogen" ) cor_results <- mcmodule_corr(mcmodule) # Use single method cor_results_spearman <- mcmodule_corr(mcmodule, method = "spearman")
Validates that all mcnodes in a module have compatible dimensions for sensitivity analysis by checking uncertainty and variate dimensions.
mcmodule_dim_check(mcmodule, mc_names = NULL)mcmodule_dim_check(mcmodule, mc_names = NULL)
mcmodule |
(mcmodule object). Module containing nodes. |
mc_names |
(character vector, optional). Node names to check. If NULL, checks all nodes. Default: NULL. |
A list with: n_mcnodes (count), n_variate (variate count),
n_uncertainty (uncertainty simulation count).
Extracts comprehensive metadata about a Monte Carlo module, including:
Module composition (raw vs combined modules)
Input data per expression
Keys for each variate (data row)
Global data keys
mcmodule_info(mcmodule)mcmodule_info(mcmodule)
mcmodule |
A Monte Carlo module object |
A raw module has a single expression in mcmodule$exp.
A combined module has multiple expressions in mcmodule$exp, each
representing a component module that was combined via combine_modules().
For combined modules, module names are recursively extracted up to one level deep. This allows identifying all base modules even in deeply nested combinations.
A list with six elements:
is_combined |
Logical. TRUE if module is combined, FALSE if raw |
n_modules |
Integer. Number of component modules (1 for raw, >1 for combined) |
module_names |
Character vector. Names of all component modules (recursive) |
module_exp_data |
Data frame with module and expression information, including data_name |
data_keys |
Data frame with keys for each variate, including variate number and data_name |
global_keys |
Character vector of global key names used across the module |
# Get comprehensive module information info <- mcmodule_info(imports_mcmodule) str(info) # Access composition information info$is_combined info$n_modules info$module_names # Access index information head(info$module_exp_data) head(info$data_keys) info$global_keys# Get comprehensive module information info <- mcmodule_info(imports_mcmodule) str(info) # Access composition information info$is_combined info$n_modules info$module_names # Access index information head(info$module_exp_data) head(info$data_keys) info$global_keys
Transforms an mcmodule into a list of matrices, with one matrix per variate. Each matrix has uncertainty simulations as rows and mcnodes as columns.
mcmodule_to_matrices(mcmodule, mc_names = NULL)mcmodule_to_matrices(mcmodule, mc_names = NULL)
mcmodule |
(mcmodule object). Module to convert. |
mc_names |
(character vector, optional). Node names to include. If NULL, includes all nodes. Default: NULL. |
A list of matrices (one per variate). Each matrix has uncertainty simulations as rows and mcnodes as columns.
mc2d ObjectsConverts an mcmodule into one or more mc objects (from the mc2d package). Returns either one mc object per variate or a single mc object with all variates combined into the variability dimension.
mcmodule_to_mc( mcmodule, mc_names = NULL, match = FALSE, variates_as_nsv = FALSE )mcmodule_to_mc( mcmodule, mc_names = NULL, match = FALSE, variates_as_nsv = FALSE )
mcmodule |
(mcmodule object). Module to convert. |
mc_names |
(character vector, optional). Node names to include. If NULL, includes all nodes. Default: NULL. |
match |
(logical, unused). Reserved for future functionality. Default: FALSE. |
variates_as_nsv |
(logical). If TRUE, combine all variates into a single mc object by multiplying variates by uncertainty simulations in the variability dimension. If FALSE, return one mc object per variate. Default: FALSE. |
If variates_as_nsv = FALSE, a list of mc objects (one per variate).
If variates_as_nsv = TRUE, a single mc object with all variates combined
into the variability dimension. Each mc object is compatible with mc2d
package functions.
Creates a tornado-style plot from mcmodule_corr() results. For each input node,
the plot shows all variate-level correlations as small vertical ticks, a black
horizontal range line (min to max), a median marker, and a larger marker at the
maximum absolute correlation.
mcmodule_tornado( mcmodule = NULL, corr_results = NULL, output = NULL, by_exp = FALSE, match_variates = TRUE, variates_as_nsv = FALSE, print_summary = TRUE, progress = FALSE, method = c("spearman", "kendall", "pearson"), use = "all.obs", lim = c(0.025, 0.975), colour = "strength" )mcmodule_tornado( mcmodule = NULL, corr_results = NULL, output = NULL, by_exp = FALSE, match_variates = TRUE, variates_as_nsv = FALSE, print_summary = TRUE, progress = FALSE, method = c("spearman", "kendall", "pearson"), use = "all.obs", lim = c(0.025, 0.975), colour = "strength" )
mcmodule |
(mcmodule object, optional). Module used to compute correlations
when |
corr_results |
(data frame, optional). Output table from |
output |
(character, optional). Output node name. Passed to
|
by_exp |
(logical). Passed to |
match_variates |
(logical). Passed to |
variates_as_nsv |
(logical). Passed to |
print_summary |
(logical). Passed to |
progress |
(logical). Passed to |
method |
(character). Passed to |
use |
(character). Passed to |
lim |
(numeric vector). Passed to |
colour |
(character or logical). Colouring for max absolute points.
Default: "strength". If |
mcmodule_tornado() returns a ggplot object. Use mcmodule_corr() when you
need the correlation table; use mcmodule_tornado() when you need a plot
object that can be further customised.
Interpretation: In the tornado plot each point (one per variate) shows the
correlation between that input and the chosen output across the model variates.
The coloured point highlights the variate with the maximum absolute correlation
for each input and is used to rank inputs. The black point is the median
correlation across variates and the black horizontal line shows the range
(minimum to maximum) of correlations for that input. The grey horizontal line
connects the maximum-absolute point to the zero-correlation vertical line to
facilitate interpretation. Use mcmodule_corr() to inspect the numeric
per-variate correlations, the plot is designed to give a compact visual
summary.
A ggplot2 object.
Replaces NA and infinite values in mcnode objects with a specified value.
mcnode_na_rm(mcnode, na_value = 0)mcnode_na_rm(mcnode, na_value = 0)
mcnode |
An mcnode object containing NA or infinite values |
na_value |
Numeric value to replace NA and infinite values (default = 0) |
An mcnode object with NA and infinite values replaced by na_value
sample_mcnode <- mcstoc(runif, min = mcdata(c(NA, 0.2, -Inf), type = "0", nvariates = 3), max = mcdata(c(NA, 0.3, Inf), type = "0", nvariates = 3), nvariates = 3 ) # Replace NA and Inf with 0 clean_mcnode <- mcnode_na_rm(sample_mcnode)sample_mcnode <- mcstoc(runif, min = mcdata(c(NA, 0.2, -Inf), type = "0", nvariates = 3), max = mcdata(c(NA, 0.3, Inf), type = "0", nvariates = 3), nvariates = 3 ) # Replace NA and Inf with 0 clean_mcnode <- mcnode_na_rm(sample_mcnode)
Replaces an mcnode that is not found in the data or in the previous module with a specified value.
mcnode_null_rm(mcnode, null_value = 0)mcnode_null_rm(mcnode, null_value = 0)
mcnode |
An mcnode object containing NA or infinite values |
null_value |
Numeric value to replace NA and infinite values (default = 0) |
The mcnode if is found, otherwise the null_value
mcnode_null_rm(unexisting_mcnode)mcnode_null_rm(unexisting_mcnode)
Extract the bounds required by sensitivity::morris() from an mctable.
mctable_bounds( mctable = set_mctable(), mc_names = NULL, if_not_sampled = c("exclude", "median", "mean", "max", "min"), transformation = TRUE, n_probe = 1000 )mctable_bounds( mctable = set_mctable(), mc_names = NULL, if_not_sampled = c("exclude", "median", "mean", "max", "min"), transformation = TRUE, n_probe = 1000 )
mctable |
(data frame). Table containing at least |
mc_names |
(character vector, optional). Node names to include. If
|
if_not_sampled |
(character). How to handle nodes not listed in
|
transformation |
(logical). Whether to apply |
n_probe |
(integer). Number of probe draws used to approximate bounds
when |
Supports sampling only a subset of nodes via mc_names and controls how
non-sampled nodes are handled via if_not_sampled. If transformation is
enabled and mctable includes a transformation column, the function
computes bounds on the transformed values.
A list bounds with:
binf numeric vector of lower bounds (same order as factors).
bsup numeric vector of upper bounds (same order as factors).
factors character vector of factor names.
fixed named numeric vector with fixed values for non-sampled
factors when if_not_sampled != "exclude".
Create Sobol sampling matrices using sensobol::sobol_matrices() and an
mctable definition. The function generates quasi-random draws in [0, 1]
and then maps them to the target distributions defined in mctable$mc_func
(or mctable$func) and mctable$sample_space.
mctable_sobol_matrices( mctable = set_mctable(), N, matrices = c("A", "B", "AB"), order = c("first", "second", "third", "fourth"), type = c("QRN", "LHS", "R"), mc_names = NULL, ... )mctable_sobol_matrices( mctable = set_mctable(), N, matrices = c("A", "B", "AB"), order = c("first", "second", "third", "fourth"), type = c("QRN", "LHS", "R"), mc_names = NULL, ... )
mctable |
(data frame). Table containing at least |
N |
(integer). Base sample size (see |
matrices |
(character). Which Sobol matrices to create (see
|
order |
(character). Either |
type |
(character). Sampling design used by |
mc_names |
(character vector, optional). Node names to include. If
|
... |
Additional arguments passed to |
If the distribution function is missing but numeric bounds are available in
sample_space (e.g. min = 0, max = 1 or c(0, 1)), the function assumes a
uniform distribution (stats::runif).
A numeric matrix where each column is a model input distributed in
(0, 1) after mapping to the distributions defined in the mctable,
and each row is a sampling point. The matrix has the same layout/row
binding as sensobol::sobol_matrices().
Automatically determines the minimum number of variability iterations (ndvar) required for all input nodes in a Monte Carlo model to converge at the 5% threshold. Uses an iterative algorithm starting with 1,001 variates and adjusting up or down based on observed convergence.
optim_ndvar( mctable = set_mctable(), exp = NULL, mc_names = NULL, min_ndvar = 100, max_ndvar = 50000, start_ndvar = 1001, conv_threshold = 0.05, print_summary = TRUE, progress = FALSE )optim_ndvar( mctable = set_mctable(), exp = NULL, mc_names = NULL, min_ndvar = 100, max_ndvar = 50000, start_ndvar = 1001, conv_threshold = 0.05, print_summary = TRUE, progress = FALSE )
mctable |
(data frame). Table with |
exp |
(language or list). Optional model expression(s) to evaluate. Default: NULL, will create an expression multipling all input nodes. |
mc_names |
(character vector, optional). Specific node names to analyze. If NULL, analyzes all nodes. Default: NULL. |
min_ndvar |
(integer). Minimum allowed ndvar. Default: 100. |
max_ndvar |
(integer). Maximum allowed ndvar. Default: 50000. |
start_ndvar |
(integer). Initial ndvar to test. Default: 1001. |
conv_threshold |
(numeric). Convergence threshold at 5%. Default: 0.05. |
print_summary |
(logical). If TRUE, print optimization summary. Default: TRUE. |
progress |
(logical). If TRUE, print progress for each iteration. Default: FALSE. |
The optimization algorithm:
Starts with start_ndvar (default 1,001)
If convergence achieved: tries n/2 (lower bound search)
If convergence not achieved: tries 2n (upper bound search)
Continues until minimum converging ndvar is found
Warns if limits (min_ndvar, max_ndvar) are reached
A list containing:
optimal_ndvar: The minimum ndvar where all nodes converge.
converged: Logical indicating if convergence was achieved.
iterations: Data frame with each iteration's details (ndvar, converged, reason).
convergence_results: Convergence analysis results from mcmodule_converg().
# Define mctable mctable <- data.frame( mcnode = c("input_a", "input_b"), sample_space = c("min = 0, max = 1", "min = 10, max = 20") ) # Optimize ndvar result <- optim_ndvar( exp = quote({result <- input_a * input_b}), mctable = mctable ) result$optimal_ndvar# Define mctable mctable <- data.frame( mcnode = c("input_a", "input_b"), sample_space = c("min = 0, max = 1", "min = 10, max = 20") ) # Optimize ndvar result <- optim_ndvar( exp = quote({result <- input_a * input_b}), mctable = mctable ) result$optimal_ndvar
A dataset containing prevalence information for two pathogens across three regions.
prevalence_regionprevalence_region
A data frame with 6 rows and 4 columns:
Pathogen identifier (a or b)
Region of origin (nord, south, east)
Minimum herd prevalence value
Maximum herd prevalence value
Minimum within-herd prevalence value
Maximum within-herd prevalence value
Test used to detect infected animals at origin
Simulated data for demonstration purposes
Reset Global Data Keys
Clears and resets the global data keys to an empty state.
reset_data_keys()reset_data_keys()
NULL (invisibly). Clears global data_keys.
reset_data_keys()reset_data_keys()
Clears and resets the global mctable to an empty state with standard columns.
reset_mctable()reset_mctable()
Empty data frame with standard mctable columns.
Clears and resets the global sample design to NULL.
reset_sample_design()reset_sample_design()
NULL (invisibly). Clears global sample design.
reset_sample_design()reset_sample_design()
Manages a global data model by setting or retrieving data keys. The data model defines column names and their associated grouping keys for each data frame.
set_data_keys(data_keys = NULL)set_data_keys(data_keys = NULL)
data_keys |
(list, optional). List of data specifications. Each element is a named list with:
If NULL, returns the current global data model. Default: NULL. |
Current or newly set global data model (invisibly).
print(imports_data_keys) set_data_keys(imports_data_keys)print(imports_data_keys) set_data_keys(imports_data_keys)
Manages the global mctable (Monte Carlo nodes reference table) by setting or retrieving its value. The table stores metadata about mcnodes including descriptions, functions, and sensitivity analysis parameters.
set_mctable(data = NULL)set_mctable(data = NULL)
data |
(data frame, optional). mctable with at minimum an |
mctable columns are interpreted as follows:
mcnode: Name of the Monte Carlo node (required).
description: Human-readable description of the node.
mc_func: Distribution function used to create stochastic nodes
(for example runif, rpert). If missing/NA, node is deterministic.
from_variable: Source column name in data when different from
mcnode.
sample_space: Sampling definition used by mctable_bounds() and mctable_sobol_matrices().
Supported formats include c(...) and named bounds such as
min = X, max = Y.
transformation: R expression applied using value as placeholder
before node creation.
sensi_variation: OAT variation expression using value placeholder
in eval_module().
Current or newly set mctable. Columns include: mcnode (required), description, mc_func, from_variable, sample_space, transformation, sensi_variation.
# Get current MC table current_table <- set_mctable() # Set new MC table mct <- data.frame( mcnode = c("h_prev", "w_prev"), description = c("Herd prevalence", "Within herd prevalence"), mc_func = c("runif", "runif") ) set_mctable(mct)# Get current MC table current_table <- set_mctable() # Set new MC table mct <- data.frame( mcnode = c("h_prev", "w_prev"), description = c("Herd prevalence", "Within herd prevalence"), mc_func = c("runif", "runif") ) set_mctable(mct)
Manages a global sample design matrix/data frame by setting or retrieving it.
This object is typically a matrix with one column per input parameter and one row per sample, or
the output of sensitivity::sensitivity functions. It can be used as
default input in eval_module().
set_sample_design(data = NULL)set_sample_design(data = NULL)
data |
(matrix, data frame, or list, optional). Sample design to store
globally. Accepts a matrix/data frame or a list with a matrix in element |
Current or newly set sample design (list with elements sa and
X) or NULL if no sample design has been set.
# Get current sample design (NULL if not set) current_sample_design <- set_sample_design() # Set sample design X <- data.frame(a = c(0.1, 0.2), b = c(1, 2)) set_sample_design(X) # Reset sample design reset_sample_design()# Get current sample design (NULL if not set) current_sample_design <- set_sample_design() # Set sample design X <- data.frame(a = c(0.1, 0.2), b = c(1, 2)) set_sample_design(X) # Reset sample design reset_sample_design()
A dataset containing test sensitivity values for two pathogens.
test_sensitivitytest_sensitivity
A data frame with 2 rows and 4 columns:
Pathogen identifier (a or b)
Minimum test sensitivity value
Most likely test sensitivity value
Maximum test sensitivity value
Converts an mcnode to long format suitable for ggplot2 and tidyverse analysis. Each row represents one uncertainty iteration for one variate.
tidy_mcnode( mcmodule = NULL, mc_name = NULL, mcnode = NULL, data = NULL, keys_names = NULL, filter = NULL )tidy_mcnode( mcmodule = NULL, mc_name = NULL, mcnode = NULL, data = NULL, keys_names = NULL, filter = NULL )
mcmodule |
(mcmodule object, optional). Module containing the node. |
mc_name |
(character, optional). Name of the mcnode in the module. |
mcnode |
(mcnode object, optional). mcnode to convert directly. |
data |
(data frame, optional). Input data; extracted from |
keys_names |
(character vector, optional). Column names for grouping variates. If NULL, uses node keys from module or all available keys. Default: NULL. |
filter |
(expression, optional). Unquoted expression to filter variates
(e.g., |
Call signatures:
tidy_mcnode(mcmodule, \"node_name\")
tidy_mcnode(mcnode = mcnode, data = data)
tidy_mcnode(mcmodule, mcnode = mcnode)
A long data frame with columns:
All key columns from keys_names.
variate: Variate index (data row number).
simulation: Uncertainty iteration index.
value: mcnode value for that combination.
# Using mcmodule and node name long_data <- tidy_mcnode(imports_mcmodule, "w_prev") # Using with specific keys long_data <- tidy_mcnode(imports_mcmodule, "w_prev", keys_names = "origin" ) # Using mcnode and data directly w_prev <- imports_mcmodule$node_list$w_prev$mcnode long_data <- tidy_mcnode(mcnode = w_prev, data = imports_data) # Filter variates long_data <- tidy_mcnode(imports_mcmodule, "w_prev", filter = pathogen == "a" )# Using mcmodule and node name long_data <- tidy_mcnode(imports_mcmodule, "w_prev") # Using with specific keys long_data <- tidy_mcnode(imports_mcmodule, "w_prev", keys_names = "origin" ) # Using mcnode and data directly w_prev <- imports_mcmodule$node_list$w_prev$mcnode long_data <- tidy_mcnode(mcnode = w_prev, data = imports_data) # Filter variates long_data <- tidy_mcnode(imports_mcmodule, "w_prev", filter = pathogen == "a" )
Calculates probabilities and expected counts across hierarchical levels (trial, subset, set) in a structured population. Uses trial probabilities and handles nested sampling with conditional probabilities.
trial_totals( mcmodule, mc_names, trials_n, subsets_n = NULL, subsets_p = NULL, name = NULL, prefix = NULL, combine_prob = TRUE, all_suffix = NULL, level_suffix = c(trial = "trial", subset = "subset", set = "set"), mctable = set_mctable(), sample_design = set_sample_design(), agg_keys = NULL, agg_suffix = NULL, keep_variates = FALSE, summary = TRUE, data_name = NULL )trial_totals( mcmodule, mc_names, trials_n, subsets_n = NULL, subsets_p = NULL, name = NULL, prefix = NULL, combine_prob = TRUE, all_suffix = NULL, level_suffix = c(trial = "trial", subset = "subset", set = "set"), mctable = set_mctable(), sample_design = set_sample_design(), agg_keys = NULL, agg_suffix = NULL, keep_variates = FALSE, summary = TRUE, data_name = NULL )
mcmodule |
(mcmodule object). Module containing input data and node structure. |
mc_names |
(character vector). Node names to process. |
trials_n |
(character). Trial count column name. |
subsets_n |
(character, optional). Subset count column name. Default: NULL. |
subsets_p |
(character, optional). Subset prevalence column name. Default: NULL. |
name |
(character, optional). Custom name for output nodes. Default: NULL. |
prefix |
(character, optional). Prefix for output node names. Default: NULL. |
combine_prob |
(logical). If TRUE, combine probability of all nodes assuming independence. Default: TRUE. |
all_suffix |
(character). Suffix for combined node name. Default: "all". |
level_suffix |
(list, optional). Suffixes for each hierarchical level. Default: c(trial="trial", subset="subset", set="set"). |
mctable |
(data frame, optional). Monte Carlo nodes definitions. Default: set_mctable(). |
sample_design |
(matrix, data frame, or list, optional). Sampling
design used to create missing input nodes via |
agg_keys |
(character vector, optional). Column names for aggregation. Default: NULL. |
agg_suffix |
(character). Suffix for aggregated node names. Default: "hag". |
keep_variates |
(logical). If TRUE, preserve individual variate values. Default: FALSE. |
summary |
(logical). If TRUE, include summary statistics. Default: TRUE. |
data_name |
(character, optional). Data name used to create trials_n, subsets_n and subsets_p nodes if they don't exist in mcmodule. Default: NULL. |
Updated mcmodule object containing combined node probabilities and probabilities/counts at trial, subset, and set levels.
imports_mcmodule <- trial_totals( mcmodule = imports_mcmodule, mc_names = "no_detect", trials_n = "animals_n", subsets_n = "farms_n", subsets_p = "h_prev", mctable = imports_mctable ) print(imports_mcmodule$node_list$no_detect_set$summary)imports_mcmodule <- trial_totals( mcmodule = imports_mcmodule, mc_names = "no_detect", trials_n = "animals_n", subsets_n = "farms_n", subsets_p = "h_prev", mctable = imports_mctable ) print(imports_mcmodule$node_list$no_detect_set$summary)
Creates a formatted edge table suitable for visualisation with visNetwork.
visNetwork_edges(mcmodule, inputs = FALSE)visNetwork_edges(mcmodule, inputs = FALSE)
mcmodule |
(mcmodule object). Module containing node relationships. |
inputs |
(logical). If TRUE, include non-node inputs. Default: FALSE. |
A data frame containing edge information for visNetwork with columns: from, to, and id.
Creates a formatted node table for visualisation with visNetwork. Includes styling and formatting for interactive network display.
visNetwork_nodes( mcmodule, variate = 1, color_pal = NULL, color_by = NULL, inputs = FALSE )visNetwork_nodes( mcmodule, variate = 1, color_pal = NULL, color_by = NULL, inputs = FALSE )
mcmodule |
(mcmodule object). Module containing network structure. |
variate |
(integer). Which variate to extract. Default: 1. |
color_pal |
(character vector, optional). Custom colour palette for nodes. Default: NULL. |
color_by |
(character, optional). Column name to determine node colours. Default: NULL. |
inputs |
(logical). If TRUE, include non-node inputs. Default: FALSE. |
A data frame formatted for visNetwork with columns: id, label, color, grouping, expression, and title (hover text).
Applies a test function to each mcnode in an mcmodule and returns the names of nodes where the test returns TRUE. Useful for identifying nodes with specific properties (e.g., NA values, negative values).
which_mcnode(mcmodule, test_func)which_mcnode(mcmodule, test_func)
mcmodule |
(mcmodule object). Module containing node_list with mcnodes. |
test_func |
(function). Function that takes an mcnode and returns logical; TRUE if the condition is met. |
Character vector of mcnode names where test_func returns TRUE.
Empty vector if no nodes meet the condition.
which_mcnode_na(), which_mcnode_inf()
# Find nodes with negative values which_mcnode(imports_mcmodule, function(x) any(x < 0, na.rm = TRUE)) # Find nodes with values greater than 1 which_mcnode(imports_mcmodule, function(x) any(x > 1, na.rm = TRUE))# Find nodes with negative values which_mcnode(imports_mcmodule, function(x) any(x < 0, na.rm = TRUE)) # Find nodes with values greater than 1 which_mcnode(imports_mcmodule, function(x) any(x > 1, na.rm = TRUE))
Identifies which mcnodes within an mcmodule contain infinite values (Inf or -Inf). Useful for troubleshooting and debugging Monte Carlo models.
which_mcnode_inf(mcmodule)which_mcnode_inf(mcmodule)
mcmodule |
(mcmodule object). Module containing node_list. |
Character vector of mcnode names containing infinite values. Returns empty vector if no infinite values found.
which_mcnode(), which_mcnode_na(), mcnode_na_rm()
# Find nodes with infinite values in the imports_mcmodule which_mcnode_inf(imports_mcmodule) # Create a test mcmodule with Inf values test_mcnode_inf <- mcdata(c(0.1, Inf, 0.3), type = "0", nvariates = 3) test_mcnode_clean <- mcdata(c(0.1, 0.2, 0.3), type = "0", nvariates = 3) test_mcmodule <- list( node_list = list( node_a = list(mcnode = test_mcnode_inf), node_b = list(mcnode = test_mcnode_clean) ) ) which_mcnode_inf(test_mcmodule)# Find nodes with infinite values in the imports_mcmodule which_mcnode_inf(imports_mcmodule) # Create a test mcmodule with Inf values test_mcnode_inf <- mcdata(c(0.1, Inf, 0.3), type = "0", nvariates = 3) test_mcnode_clean <- mcdata(c(0.1, 0.2, 0.3), type = "0", nvariates = 3) test_mcmodule <- list( node_list = list( node_a = list(mcnode = test_mcnode_inf), node_b = list(mcnode = test_mcnode_clean) ) ) which_mcnode_inf(test_mcmodule)
mcnodes with Missing ValuesFind mcnodes with Missing Values
which_mcnode_na(mcmodule)which_mcnode_na(mcmodule)
mcmodule |
(mcmodule object). Module containing node_list. |
Identifies which mcnodes within an mcmodule contain NA values. Useful for troubleshooting and debugging Monte Carlo models.
Character vector of mcnode names containing NA values. Returns empty vector if no NAs found.
which_mcnode(), which_mcnode_inf(), mcnode_na_rm()
# Find nodes with NAs in the imports_mcmodule which_mcnode_na(imports_mcmodule) # Create a test mcmodule with NAs test_mcnode_na <- mcdata(c(0.1, NA, 0.3), type = "0", nvariates = 3) test_mcnode_clean <- mcdata(c(0.1, 0.2, 0.3), type = "0", nvariates = 3) test_mcmodule <- list( node_list = list( node_a = list(mcnode = test_mcnode_na), node_b = list(mcnode = test_mcnode_clean) ) ) which_mcnode_na(test_mcmodule)# Find nodes with NAs in the imports_mcmodule which_mcnode_na(imports_mcmodule) # Create a test mcmodule with NAs test_mcnode_na <- mcdata(c(0.1, NA, 0.3), type = "0", nvariates = 3) test_mcnode_clean <- mcdata(c(0.1, 0.2, 0.3), type = "0", nvariates = 3) test_mcmodule <- list( node_list = list( node_a = list(mcnode = test_mcnode_na), node_b = list(mcnode = test_mcnode_clean) ) ) which_mcnode_na(test_mcmodule)
Matches datasets by group and preserves baseline scenarios (scenario_id = 0) when scenarios differ between them.
wif_match(x, y, by = NULL)wif_match(x, y, by = NULL)
x |
(data frame). First dataset to match. |
y |
(data frame). Second dataset to match. |
by |
(character vector, optional). Grouping column name(s) to match on. If NULL, auto-detected from column names. Default: NULL. |
A list containing matched datasets with aligned scenario IDs. Element 1: matched version of x. Element 2: matched version of y.
x <- data.frame( category = c("a", "b", "a", "b"), scenario_id = c(0, 0, 1, 1), value = 1:4 ) y <- data.frame( category = c("a", "b", "a", "b"), scenario_id = c(0, 0, 2, 2), value = 5:8 ) # Automatic matching result <- wif_match(x, y)x <- data.frame( category = c("a", "b", "a", "b"), scenario_id = c(0, 0, 1, 1), value = 1:4 ) y <- data.frame( category = c("a", "b", "a", "b"), scenario_id = c(0, 0, 2, 2), value = 5:8 ) # Automatic matching result <- wif_match(x, y)