| 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.1.9000 |
| Built: | 2026-10-09 16:32:21 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))
agg_totals() was renamed to agg_variates() because the new name better
describes that the function aggregates mcnode variates across grouping
variables.
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 |
An |
mc_name |
Character. Name of node to aggregate. |
agg_keys |
Character vector, optional. Column names for grouping.
If |
agg_suffix |
Character, optional. Suffix for aggregated node name.
Default: |
prefix |
Character, optional. Prefix for output node name. Default: |
name |
Character, optional. Custom name for output node. Default: |
summary |
Logical. If |
keep_variates |
Logical. If |
agg_func |
Character or function, optional. Aggregation method:
|
An mcmodule object with a new aggregated node added.
Aggregates node values across grouping variables using various methods (combined probability, sum, mean, or a custom function). Returns an updated mcmodule with a new aggregated node.
agg_variates( mcmodule, mc_name, agg_keys = NULL, agg_suffix = NULL, prefix = NULL, name = NULL, summary = TRUE, keep_variates = FALSE, agg_func = NULL )agg_variates( mcmodule, mc_name, agg_keys = NULL, agg_suffix = NULL, prefix = NULL, name = NULL, summary = TRUE, keep_variates = FALSE, agg_func = NULL )
mcmodule |
An |
mc_name |
Character. Name of node to aggregate. |
agg_keys |
Character vector, optional. Column names for grouping.
If |
agg_suffix |
Character, optional. Suffix for aggregated node name.
Default: |
prefix |
Character, optional. Prefix for output node name. Default: |
name |
Character, optional. Custom name for output node. Default: |
summary |
Logical. If |
keep_variates |
Logical. If |
agg_func |
Character or function, optional. Aggregation method:
|
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.
An mcmodule object with a new aggregated node added.
Ross SM (2014). Introduction to Probability Models, 11th ed. Elsevier.
at_least_one() for combining probability nodes,
trial_totals() for repeated or hierarchical Bernoulli trials,
mc_filter() for selecting variates, and mc_summary() for node
summaries.
imports_mcmodule <- agg_variates( imports_mcmodule, "no_detect", agg_keys = c("scenario_id", "pathogen") ) print(imports_mcmodule$node_list$no_detect_agg$summary)imports_mcmodule <- agg_variates( imports_mcmodule, "no_detect", agg_keys = c("scenario_id", "pathogen") ) print(imports_mcmodule$node_list$no_detect_agg$summary)
Simulated data describing the number of farms exporting animals and the number of animals exported per farm from three hypothetical regions.
animal_importsanimal_imports
A data frame with 3 rows and 4 columns:
Region of origin: "nord", "south", or "east".
Number of farms exporting animals.
Mean number of animals exported per farm.
Standard deviation of the number of animals exported per farm.
Simulated data for demonstration purposes.
prevalence_region, test_sensitivity, imports_data
animal_importsanimal_imports
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.
Ross SM (2014). Introduction to Probability Models, 11th ed. Elsevier.
agg_variates() for aggregation across groups of variates,
trial_totals() for repeated or hierarchical Bernoulli trials,
mc_match() for aligning nodes by keys, and mc_summary() for node
summaries.
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(...), named
assignments such as min = X, max = Y, or a single numeric value such as
1).
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.
eval_module() for using one or more previous modules and
add_prefix() for distinguishing node names when needed.
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(). |
Distribution functions may be supplied as bare (function) or namespace-qualified names (package::function, and package:::function).
Configured transformation expressions are evaluated as R code.
NULL, invisibly. mcnodes are created in envir.
eval_module() for creating and evaluating a complete module and
matrix_to_mcnodes() for creating nodes from a sampling matrix.
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 named list). Model expression or named 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). A previous module or a list of previous modules for dependent calculations. Multiple modules are combined internally and must have unique node names. 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.
get_node_list() for inspecting expression dependencies,
create_mcnodes() and matrix_to_mcnodes() for input-node creation, and
mc_summary() for summarising evaluated nodes. See combine_modules() and
add_prefix() when preparing multiple previous modules.
# 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.
get_node_table() and mc_network() for the corresponding node
metadata and interactive visualisation.
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.
eval_module() for creating an mcmodule.
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.
eval_module() for evaluating the expression and
create_mcnodes() for constructing input nodes.
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, percentages = TRUE)get_node_table(mcmodule, variate = 1, inputs = FALSE, percentages = TRUE)
mcmodule |
(mcmodule object). Module containing node information. |
variate |
(positive integer). Variate (row) to extract from every stochastic node and input data frame. The default uses the first variate. Use another row number when the same row has the intended meaning across the module's data frames. This argument does not filter by key values; filter the module before plotting when row positions are not comparable. |
inputs |
(logical). If TRUE, include non-node inputs (datasets, dataframes, and columns). Default: FALSE. |
percentages |
(logical). If TRUE, eligible stochastic nodes whose values do not exceed 1 are displayed as percentages. Count and time nodes identified from their names are always displayed as numbers. If FALSE, all stochastic nodes are displayed as numbers. Default: TRUE. |
A data frame containing node information and attributes.
get_edge_table() for network edges, mc_filter() for selecting
variates by conditions, and mc_network() for interactive visualisation.
node_table <- get_node_table(imports_mcmodule)node_table <- get_node_table(imports_mcmodule)
A model-ready dataset combining animal movements, pathogen prevalence, and diagnostic-test sensitivity. Each row represents one combination of a hypothetical pathogen and region of origin.
imports_dataimports_data
A data frame with 6 rows and 13 columns:
Hypothetical pathogen identifier: "a" or "b".
Region of origin: "nord", "south", or "east".
Frequency with which animals are tested at origin.
Minimum herd prevalence.
Maximum herd prevalence.
Minimum within-herd prevalence.
Maximum within-herd prevalence.
Number of farms exporting animals.
Mean number of animals exported per farm.
Standard deviation of the number of animals exported per farm.
Minimum diagnostic-test sensitivity.
Most likely diagnostic-test sensitivity.
Maximum diagnostic-test sensitivity.
Simulated data for demonstration purposes. The dataset is created by joining prevalence_region, animal_imports, and test_sensitivity.
imports_data_keys, imports_mctable, imports_exp
imports_dataimports_data
A data-key specification describing the columns and identifying variables
associated with each source dataset in the animal-import example. These
keys allow mcmodule to associate input parameters with the appropriate
model variates.
imports_data_keysimports_data_keys
A named list with three components:
A list containing cols, the columns provided by
animal_imports, and keys, with origin as the identifying variable.
A list containing cols, the columns provided by
prevalence_region, and keys, with pathogen and origin as the
identifying variables.
A list containing cols, the columns provided by
test_sensitivity, and keys, with pathogen as the identifying
variable.
Created for the illustrative animal-import example.
imports_data, imports_mctable, imports_exp, eval_module()
imports_data_keys imports_data_keys$prevalence_region$keysimports_data_keys imports_data_keys$prevalence_region$keys
A quoted R expression that calculates the probability that an animal from an infected herd is infected but is not detected before import. Diagnostic test specificity is assumed to be 100 percent.
imports_expimports_exp
A quoted R expression that creates the following model nodes:
Probability that an animal from an infected herd is infected.
Probability that an infected animal is tested but returns a false-negative result.
Probability that an infected animal is not tested.
Overall probability that an infected animal is not detected before import.
Created for the illustrative animal-import example.
imports_data, imports_data_keys, imports_mctable,
eval_module()
imports_exp imports_module <- eval_module( exp = list(imports = imports_exp), data = imports_data, mctable = imports_mctable, data_keys = imports_data_keys )imports_exp imports_module <- eval_module( exp = list(imports = imports_exp), data = imports_data, mctable = imports_mctable, data_keys = imports_data_keys )
A pre-evaluated mcmodule object containing simulation results for the illustrative animal-import risk assessment. The module represents two hypothetical pathogens imported from three regions of origin and includes input nodes, intermediate calculations, and the probability that an infected animal is not detected before import.
imports_mcmoduleimports_mcmodule
An object of class mcmodule with the following components:
A named list containing the model input data.
A named list containing the evaluated model expression.
A named list of Monte Carlo input and output nodes with
their associated metadata. This includes w_prev, test_sensi,
test_origin, infected, false_neg, no_test, and no_detect.
Character vector identifying the modules represented in the object.
The object is generated from imports_data, imports_data_keys, imports_mctable, and imports_exp. It is provided so that package functions can be demonstrated without rebuilding the model each time.
Generated from simulated data for demonstration purposes.
imports_data, imports_data_keys, imports_mctable,
imports_exp, eval_module()
imports_mcmodule class(imports_mcmodule) names(imports_mcmodule$node_list) mc_summary(imports_mcmodule, "no_detect")imports_mcmodule class(imports_mcmodule) names(imports_mcmodule$node_list) mc_summary(imports_mcmodule, "no_detect")
A configured Monte Carlo node table for the illustrative animal-import risk assessment. It defines input nodes, probability distributions, source columns, transformations, and sensitivity-analysis ranges.
imports_mctableimports_mctable
A data frame with 7 rows and 7 columns:
Name of the Monte Carlo input node.
Description of the represented parameter.
Random-number generation function. NA identifies a
deterministic input.
Alternative source column used to create the node, where applicable.
Transformation applied to source values, where applicable.
Expression defining variation for one-at-a-time sensitivity analysis.
Sampling range or distribution arguments used for sample-design sensitivity analysis.
h_prev and w_prev use uniform distributions, test_sensi uses a PERT
distribution, and animals_n uses a normal distribution. farms_n is
deterministic. The test_origin_unk and test_origin nodes demonstrate
how categorical source data can be transformed into model inputs.
Simulated specifications for demonstration purposes.
imports_data, imports_data_keys, imports_exp, eval_module()
imports_mctableimports_mctable
A quoted R expression representing contamination introduced through an intrusion into the water distribution system. It calculates the ingested dose and individual infection probability conditional on an intrusion.
intrusion_expintrusion_exp
A quoted R expression that creates the following model nodes:
Daily ingested dose conditional on an intrusion.
Individual daily probability of infection conditional on an intrusion.
The probability and frequency of intrusion events are not applied inside
this expression. They can subsequently be incorporated with
trial_totals() using intrusion_prob and exposure_days from
water_data or water_group_data.
Created for the illustrative water-supply example.
water_data, water_group_data, water_data_keys,
water_group_data_keys, water_mctable, treatment_exp, eval_module(),
trial_totals()
intrusion_exp intrusion_module <- eval_module( exp = list(intrusion = intrusion_exp), data = water_data, mctable = water_mctable, data_keys = water_data_keys ) intrusion_group_module <- eval_module( exp = list(intrusion = intrusion_exp), data = water_group_data, mctable = water_mctable, data_keys = water_group_data_keys )intrusion_exp intrusion_module <- eval_module( exp = list(intrusion = intrusion_exp), data = water_data, mctable = water_mctable, data_keys = water_data_keys ) intrusion_group_module <- eval_module( exp = list(intrusion = intrusion_exp), data = water_group_data, mctable = water_mctable, data_keys = water_group_data_keys )
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 nsv = nrow(X).
This is useful when X is a design matrix generated by functions such as
sensitivity::morris() 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 are created in envir.
create_mcnodes() for creating nodes from data and an mctable,
and eval_module() for evaluating a complete module.
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. Won't be used if |
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. Won't be used if |
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.
mc_match() and mc_match_data() for aligning nodes using keys.
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 are recycled across variates when required for matching.
A list containing matched nodes and combined keys (keys_xy).
mc_keys() for extracting node keys, mc_match_data() for
matching a node to a data frame, and wif_match() for matching two data
frames with different scenarios.
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 are recycled across variates when required for matching.
A list containing matched mcnode, matched data, and combined keys
(keys_xy).
mc_keys() for extracting node keys, mc_match() for matching
two nodes, and wif_match() for matching two data frames with different
scenarios.
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 coloured 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 grey, #D3D3D3): Filtered nodes created with mc_filter().
compare (dark grey, #707070): Comparison nodes created with mc_compare().
trials_info (light orange, #FAE4CB): Trial, subset, and related information nodes used by trial_totals(), unless already classified as input or output nodes.#'
total (orange, #F39200): Total nodes created with at_least_one() or trial_totals().
agg_total (dark orange, #C17816): Aggregated total nodes created with agg_variates().
mc_network( mcmodule, variate = 1, color_pal = NULL, color_by = NULL, legend = FALSE, inputs = FALSE, percentages = TRUE )mc_network( mcmodule, variate = 1, color_pal = NULL, color_by = NULL, legend = FALSE, inputs = FALSE, percentages = TRUE )
mcmodule |
(mcmodule object). Module containing network to visualise. |
variate |
(positive integer). Variate (row) to visualise. The same row
number is used across the module; this argument does not filter variates
by key values. See |
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. |
percentages |
(logical). If TRUE, eligible stochastic nodes whose values do not exceed 1 are displayed as percentages. If FALSE, all stochastic nodes are displayed as numbers. Default: TRUE. |
An interactive visNetwork object with highlighting of connected nodes, node selection and filtering by module, directional arrows, hierarchical layout, and draggable nodes.
get_node_table() and get_edge_table() for the underlying tables,
mc_filter() for selecting variates by conditions, and
visNetwork::visNetwork() for the underlying visualisation.
network <- mc_network(mcmodule = imports_mcmodule) # Select a variate by its key values rather than its original row number. # The filtered node's first retained variate is displayed with variate = 1. selected_module <- mc_filter( imports_mcmodule, "w_prev", pathogen == "b", origin == "south", name = "w_prev_selected" ) selected_network <- mc_network(selected_module, variate = 1)network <- mc_network(mcmodule = imports_mcmodule) # Select a variate by its key values rather than its original row number. # The filtered node's first retained variate is displayed with variate = 1. selected_module <- mc_filter( imports_mcmodule, "w_prev", pathogen == "b", origin == "south", name = "w_prev_selected" ) selected_network <- mc_network(selected_module, variate = 1)
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. The digits and sep_keys options are
applied to a copy of the stored summary before it is returned.
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%).
mc_keys() for retrieving the keys associated with a node and
mc_plot() for visualising node distributions.
# 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_variates( 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_variates( 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() and other sampling
design functions 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, drop_constant = TRUE )mctable_bounds( mctable = set_mctable(), mc_names = NULL, if_not_sampled = c("exclude", "median", "mean", "max", "min"), transformation = TRUE, n_probe = 1000, drop_constant = TRUE )
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 grid points used to probe the
transformed range when |
drop_constant |
(logical). If |
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".
dropped character vector of factors removed by drop_constant.
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, transformation = TRUE, drop_constant = TRUE, ... )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, transformation = TRUE, drop_constant = TRUE, ... )
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
|
transformation |
(logical). Whether to apply |
drop_constant |
(logical). 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). Supported distribution functions are
runif, rnorm (mean, sd) and rpert (min, mode, max, optional
shape), also when namespace-qualified (e.g. mc2d::rpert). Categorical
sample_space vectors (e.g. c('always', 'sometimes', 'never')) are
supported when a numeric transformation is provided. A single numeric
value (e.g. 1, c(1), c('1') or value = 1) defines a constant input
(min = max), which is dropped when drop_constant = TRUE.
A numeric matrix where each column is a model input after mapping
to the distributions defined in the mctable (and transformation, if
applied), and each row is a sampling point. The matrix has the same
layout/row binding as sensobol::sobol_matrices(). Attribute "dropped"
contains the names of nodes removed by drop_constant.
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
Simulated estimates of herd prevalence, within-herd prevalence, and testing practices for two hypothetical pathogens in three regions of origin.
prevalence_regionprevalence_region
A data frame with 6 rows and 7 columns:
Hypothetical pathogen identifier: "a" or "b".
Region of origin: "nord", "south", or "east".
Minimum herd prevalence.
Maximum herd prevalence.
Minimum within-herd prevalence.
Maximum within-herd prevalence.
Frequency with which animals are tested at origin:
"always", "sometimes", "never", or "unknown".
Simulated data for demonstration purposes.
animal_imports, test_sensitivity, imports_data
prevalence_regionprevalence_region
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. A single numeric value (e.g. 1, c(1) or
value = 1) defines a constant input (min = max).
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()
Simulated minimum, most likely, and maximum diagnostic-test sensitivity values for two hypothetical pathogens.
test_sensitivitytest_sensitivity
A data frame with 2 rows and 4 columns:
Hypothetical pathogen identifier: "a" or "b".
Minimum diagnostic-test sensitivity.
Most likely diagnostic-test sensitivity.
Maximum diagnostic-test sensitivity.
Simulated data for demonstration purposes.
animal_imports, prevalence_region, imports_data
test_sensitivitytest_sensitivity
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" )
A quoted R expression representing the routine water-treatment pathway in the illustrative water-supply risk assessment. It calculates the treated Cryptosporidium concentration, ingested dose, individual infection probability, and number of person-day exposure trials.
treatment_exptreatment_exp
A quoted R expression that creates the following model nodes:
Cryptosporidium concentration remaining after treatment.
Daily ingested dose from treated water.
Individual daily probability of infection through the treatment pathway.
Number of person-day exposure trials, calculated as population multiplied by exposure days.
Created for the illustrative water-supply example.
water_data, water_group_data, water_data_keys,
water_group_data_keys, water_mctable, intrusion_exp, eval_module()
treatment_exp treatment_module <- eval_module( exp = list(treatment = treatment_exp), data = water_data, mctable = water_mctable, data_keys = water_data_keys )treatment_exp treatment_module <- eval_module( exp = list(treatment = treatment_exp), data = water_data, mctable = water_mctable, data_keys = water_data_keys )
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, if_not_sampled = c("median", "mean", "max", "min") )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, if_not_sampled = c("median", "mean", "max", "min") )
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 |
(named character vector, optional). Suffixes for each hierarchical level. Default: c(trial="trial", subset="subset", set="set"). |
mctable |
(data frame, optional). Monte Carlo node 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. |
if_not_sampled |
(character). How to compute the fixed value of
trials_n, subsets_n or subsets_p nodes that are defined in |
Updated mcmodule object containing combined node probabilities and probabilities/counts at trial, subset, and set levels.
Murray N (2004). Handbook on Import Risk Analysis for Animals and Animal Products, Volume 2: Quantitative Risk Assessment. OIE. https://rr-africa.woah.org/app/uploads/2018/03/handbook_on_import_risk_analysis_-_oie_-_vol_ii.pdf
Ross SM (2014). Introduction to Probability Models, 11th ed. Elsevier.
at_least_one() for combining independent probability nodes,
agg_variates() for aggregation across grouping keys, mc_match() for aligning
nodes by keys, and mc_summary() for node summaries.
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.
get_edge_table() and mc_network().
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, percentages = TRUE )visNetwork_nodes( mcmodule, variate = 1, color_pal = NULL, color_by = NULL, inputs = FALSE, percentages = TRUE )
mcmodule |
(mcmodule object). Module containing network structure. |
variate |
(positive integer). Variate (row) to extract. See
|
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. |
percentages |
(logical). If TRUE, eligible nodes are displayed as percentages; if FALSE, all nodes are displayed as numbers. Default: TRUE. |
A data frame formatted for visNetwork with columns: id, label, color, grouping, expression, and title (hover text).
get_node_table() and mc_network().
Simulated data for an illustrative quantitative microbial risk assessment of Cryptosporidium infection in a water distribution system. Each row represents one distribution zone under one management scenario.
water_datawater_data
A data frame with 4 rows and 15 columns:
Distribution-zone identifier.
Management-scenario identifier. "0" indicates the
baseline scenario.
Number of people exposed in the distribution zone.
Minimum Cryptosporidium concentration in source water, in oocysts per litre.
Most likely Cryptosporidium concentration in source water, in oocysts per litre.
Maximum Cryptosporidium concentration in source water, in oocysts per litre.
Minimum treatment performance, expressed as a log10 reduction value.
Most likely treatment performance, expressed as a log10 reduction value.
Maximum treatment performance, expressed as a log10 reduction value.
Daily consumption of unboiled tap water, in litres per person per day.
Daily probability that an intrusion affects the distribution zone.
Minimum Cryptosporidium concentration at the tap conditional on an intrusion, in oocysts per litre.
Maximum Cryptosporidium concentration at the tap conditional on an intrusion, in oocysts per litre.
Parameter of the exponential Cryptosporidium dose-response model.
Number of daily exposure events in the assessment period.
The example includes a baseline scenario, identified by "0", and a
hypothetical network-maintenance scenario that reduces the daily intrusion
probability by 80 percent.
Simulated data for demonstration purposes.
World Health Organization (2016). Quantitative microbial risk assessment: application for water safety management. https://www.who.int/publications/i/item/9789241565370
Messner MJ, Chappell CL, and Okhuysen PC (2001). Risk assessment for Cryptosporidium: a hierarchical Bayesian analysis of human dose-response data. Water Research, 35, 3934-3940. doi:10.1016/S0043-1354(01)00119-1
Besner MC, Prevost M, and Regli S (2011). Assessing the public health risk of microbial intrusion events in distribution systems. Water Research, 45, 961-979. doi:10.1016/j.watres.2010.10.035
water_group_data, water_data_keys, water_group_data_keys, water_mctable, treatment_exp, intrusion_exp
water_datawater_data
A data-key specification describing the columns and identifying variables
in water_data. The combination of zone and scenario_id uniquely
identifies each model variate.
water_data_keyswater_data_keys
A named list with one component:
A list containing cols, the column names available in
water_data, and keys, the columns zone and scenario_id that jointly
identify its rows.
Created for the illustrative water-supply example.
water_data, water_group_data_keys, water_mctable,
eval_module()
water_data_keys water_data_keys$water_data$keyswater_data_keys water_data_keys$water_data$keys
An expanded version of water_data for demonstrating multiple-group multilevel trials. Each distribution-zone and scenario combination is divided into groups with low, medium, and high daily water consumption.
water_group_datawater_group_data
A data frame with 12 rows and 16 columns:
Distribution-zone identifier.
Water-consumption group: "Low", "Medium", or
"High".
Management-scenario identifier. "0" denotes the
baseline scenario.
Number of people in the consumption group. Group populations sum to the corresponding population in water_data.
Minimum Cryptosporidium concentration in source water, in oocysts per litre.
Most likely Cryptosporidium concentration in source water, in oocysts per litre.
Maximum Cryptosporidium concentration in source water, in oocysts per litre.
Minimum treatment performance, expressed as a log10 reduction value.
Most likely treatment performance, expressed as a log10 reduction value.
Maximum treatment performance, expressed as a log10 reduction value.
Daily consumption of unboiled tap water for the consumption group, in litres per person per day.
Daily probability that an intrusion affects the distribution zone.
Minimum Cryptosporidium concentration at the tap conditional on an intrusion, in oocysts per litre.
Maximum Cryptosporidium concentration at the tap conditional on an intrusion, in oocysts per litre.
Parameter of the exponential Cryptosporidium dose-response model.
Number of daily exposure events in the assessment period.
The consumption groups contain 25, 50, and 25 percent of the corresponding zone population and consume 1.0, 1.5, and 2.0 litres of unboiled tap water per person per day, respectively.
The consumption groups in the same distribution zone share the occurrence
or absence of a daily intrusion event. Their conditional infection
probabilities differ because water_volume differs between groups. This
structure can be evaluated with trial_totals() by using population as
the number of trials and aggregating by zone and scenario_id.
Derived from water_data using hypothetical population shares and water-consumption values.
water_data, water_group_data_keys, water_mctable,
intrusion_exp, trial_totals()
water_group_data # Population is preserved within each zone and scenario. aggregate( population ~ zone + scenario_id, data = water_group_data, FUN = sum )water_group_data # Population is preserved within each zone and scenario. aggregate( population ~ zone + scenario_id, data = water_group_data, FUN = sum )
A data-key specification describing the columns and identifying variables
in water_group_data. The combination of zone, consumption_group, and
scenario_id uniquely identifies each model variate.
water_group_data_keyswater_group_data_keys
A named list with one component:
A list containing cols, the column names
available in water_group_data, and keys, the columns zone,
consumption_group, and scenario_id that jointly identify its rows.
Created for the illustrative water-supply example.
water_group_data, water_data_keys, water_mctable,
eval_module(), trial_totals()
water_group_data_keys water_group_data_keys$water_group_data$keyswater_group_data_keys water_group_data_keys$water_group_data$keys
A configured Monte Carlo node table for the illustrative water-supply risk assessment. It defines the input nodes, probability distributions, and sampling ranges used to evaluate the treatment and intrusion pathways.
water_mctablewater_mctable
A data frame with 8 rows and 7 columns:
Name of the Monte Carlo input node.
Description of the represented parameter.
Random-number generation function. NA identifies a
deterministic input.
Alternative source column used to create the node, where applicable.
Transformation applied to the source values, where applicable.
Expression defining variation for one-at-a-time sensitivity analysis.
Sampling range or distribution arguments used for sample-design sensitivity analysis.
source_conc and treatment_lrv use PERT distributions, while
intrusion_conc uses a uniform distribution. The remaining inputs are
deterministic in the main Monte Carlo model. The sample_space values
provide illustrative ranges for optional sample-design sensitivity
analyses.
Parameter ranges are illustrative. They do not represent a fitted model for a specific water system.
water_data, water_group_data, water_data_keys,
water_group_data_keys, treatment_exp, intrusion_exp, eval_module()
water_mctablewater_mctable
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.
mc_match() for matching two Monte Carlo nodes and
mc_match_data() for matching a node to a data frame.
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)