Movatterモバイル変換


[0]ホーム

URL:


Version:2.5.0
Date:2024-10-10
Title:Mathematical Modeling of Infectious Disease Dynamics
Description:Tools for simulating mathematical models of infectious disease dynamics. Epidemic model classes include deterministic compartmental models, stochastic individual-contact models, and stochastic network models. Network models use the robust statistical methods of exponential-family random graph models (ERGMs) from the Statnet suite of software packages in R. Standard templates for epidemic modeling include SI, SIR, and SIS disease types. EpiModel features an API for extending these templates to address novel scientific research aims. Full methods for EpiModel are detailed in Jenness et al. (2018, <doi:10.18637/jss.v084.i08>).
Maintainer:Samuel Jenness <samuel.m.jenness@emory.edu>
License:GPL-3
URL:https://www.epimodel.org/,https://epimodel.github.io/EpiModel/
BugReports:https://github.com/EpiModel/EpiModel/issues/
Depends:R (≥ 4.1), deSolve (≥ 1.21), networkDynamic (≥ 0.11.3),tergm (≥ 4.2.1), statnet.common (≥ 4.10.0)
Imports:graphics, grDevices, stats, utils, collections, doParallel,ergm (≥ 4.7.1), foreach, network (≥ 1.18.1), RColorBrewer,ape, lazyeval, ggplot2, tibble, methods, rlang, dplyr, coda,networkLite (≥ 1.0.5)
Suggests:ergm.ego (≥ 1.1.0), egor, knitr, ndtv, rmarkdown, shiny,testthat, progressr, tidyr
VignetteBuilder:knitr
LinkingTo:Rcpp, ergm
RoxygenNote:7.3.2
Encoding:UTF-8
NeedsCompilation:yes
Packaged:2024-10-11 14:08:46 UTC; sjennes
Author:Samuel Jenness [cre, aut], Steven M. Goodreau [aut], Martina Morris [aut], Adrien Le Guillou [aut], Chad Klumb [aut], Skye Bender-deMoll [ctb]
Repository:CRAN
Date/Publication:2024-10-11 17:50:02 UTC

Mathematical Modeling of Infectious Disease Dynamics

Description

Package: EpiModel
Type: Package
Version: 2.5.0
Date: 2024-10-10
License: GPL-3
LazyLoad: yes

Details

The EpiModel software package provides tools for building, solving, andvisualizing mathematical models of infectious disease dynamics. These toolsallow users to simulate epidemic models in multiple frameworks for bothpedagogical purposes ("base models") and novel research purposes("extension models").

Model Classes and Infectious Disease Types

EpiModel provides functionality for three classes of epidemic models:

EpiModel supports three infectious disease types to be run across all of thethree classes.

These basic disease types may be extended in any arbitrarily complex way tosimulate specific diseases for research questions.

Model Parameterization and Simulation

EpiModel uses three model setup functions for each model class to input thenecessary parameters, initial conditions, and control settings:

With the models parameterized, the functions for simulating epidemic modelsare:

Author(s)

Maintainer: Samuel Jennesssamuel.m.jenness@emory.edu

Authors:

Other contributors:

References

The EpiModel website is athttps://www.epimodel.org/, and the sourcecode is athttps://github.com/EpiModel/EpiModel. Bug reports andfeature requests are welcome.

Our primary methods paper on EpiModel is published in theJournal ofStatistical Software. If you use EpiModel for any research or teachingpurposes, please cite this reference:

Jenness SM, Goodreau SM, and Morris M. EpiModel: An R Package forMathematical Modeling of Infectious Disease over Networks. Journal ofStatistical Software. 2018; 84(8): 1-47.doi:10.18637/jss.v084.i08.

We have also developed two extension packages for modeling specific diseasedynamics. For HIV and bacterial sexually transmitted infections, we havedevelopedEpiModelHIV, which is available on Github athttps://github.com/EpiModel/EpiModelHIV. For COVID-19, we havedevelopedEpiModelCOVID, which is available athttps://github.com/EpiModel/EpiModelCOVID.

See Also

Useful links:


Definition for absdiffby ERGM Term

Description

This function defines and initializes the absdiffby ERGM termthat allows for representing homophily with respect to anon-binary attribute (e.g., age) differentially by a binaryattribute (e.g., sex).

Usage

InitErgmTerm.absdiffby(nw, arglist, ...)

Arguments

nw

An object of classnetwork.

arglist

A list of arguments as specified in theergm.usertermspackage framework.

...

Additional data passed into the function as specified in theergm.userterms package framework.

Details

This ERGM user term was written to allow for age-based homophily inpartnership formation that is asymmetric by sex. Theabsdiff componenttargets age-based homophily while theby component allows that to bestructured by a binary attribute such as "male", in order to enforce anoffset in the average difference. This allows, for example, a average agedifference in partnerships, but with males (on average) older than females.


Definition for absdiffnodemix ERGM Term

Description

This function defines and initializes the absdiffnodemix ERGMterm that allows for targeting homophily based on a non-binaryattribute (e.g., age) by combinations of a binary attribute(e.g., race).

Usage

InitErgmTerm.absdiffnodemix(nw, arglist, ...)

Arguments

nw

An object of classnetwork.

arglist

A list of arguments as specified in theergm.usertermspackage framework.

...

Additional data passed into the function as specified in theergm.userterms package framework.

Details

This ERGM user term was written to allow for age-based homophily inpartnership formation that is heterogeneous by race. Theabsdiffcomponent targets the distribution of age mixing on that continuousvariable, and thenodemix component differentiates this forblack-black, black-white, and white-white couples.


Definition for fuzzynodematch ERGM Term

Description

This function defines and initializes the fuzzynodematch ERGMterm that allows for generalized homophily.

Usage

InitErgmTerm.fuzzynodematch(nw, arglist, ...)

Arguments

nw

An object of classnetwork.

arglist

A list of arguments as specified in theergm.usertermspackage framework.

...

Additional data passed into the function as specified in theergm.userterms package framework.

Details

This ERGM user term was written to allow for generalized homophily.Theattr term argument should specify a character vertex attributeencoding the "venues" associated to each node. Thesplit argumentshould specify a string that separates different "venues" in the attributevalue for each node, as handled bystrsplit withfixed = TRUE.For example, ifsplit is"|" (the default), and the attributevalue for a given node is"a12|b476", then the associated venues forthis node are"a12" and"b476". The empty string"" isinterpreted as "no venues".

If thebinary term argument isFALSE (the default), the changestatistic for an on-toggle is the number of unique venues associated to bothnodes (informally speaking, this could be described as the number of venueson which the two nodes "match"); ifbinary isTRUE, the changestatistic for an on-toggle is1 if any venue is associated to bothnodes, and0 otherwise.


Fast Version of network::add.vertices for Edgelist-formatted Network

Description

This function performs a simple operation of updating theedgelist attributen that tracks the total networksize implicit in an edgelist representation of the network.

Usage

add_vertices(el, nv)

Arguments

el

A two-column matrix of current edges (edgelist) with an attributevariablen containing the total current network size.

nv

A integer equal to the number of nodes to add to the networksize at the given time step.

Details

This function is used inEpiModel modules to add vertices (nodes) tothe edgelist object to account for entries into the population (e.g., birthsand in-migration).

Value

Returns the matrix of current edges,el, with the population sizeattribute updated based on the number of new vertices specified innv.

Examples

## Not run: library("EpiModel")nw <- network_initialize(100)formation <- ~edgestarget.stats <- 50coef.diss <- dissolution_coefs(dissolution = ~offset(edges), duration = 20)x <- netest(nw, formation, target.stats, coef.diss, verbose = FALSE)param <- param.net(inf.prob = 0.3)init <- init.net(i.num = 10)control <- control.net(type = "SI", nsteps = 100, nsims = 5,                       tergmLite = TRUE)# networkLite representation after initializationdat <- crosscheck.net(x, param, init, control)dat <- initialize.net(x, param, init, control)# Check current network sizeattributes(dat$el[[1]])$n# Add 10 verticesdat$el[[1]] <- add_vertices(dat$el[[1]], 10)# Check new network sizeattributes(dat$el[[1]])$n## End(Not run)

Apportion Using the Largest Remainder Method

Description

Apportions a vector of values given a specified frequencydistribution of those values such that the length of the outputis robust to rounding and other instabilities.

Usage

apportion_lr(vector.length, values, proportions, shuffled = FALSE)

Arguments

vector.length

Length for the output vector.

values

Values for the output vector.

proportions

Proportion distribution with one number for each value.This must sum to 1.

shuffled

IfTRUE, randomly shuffle the order of the vector.

Value

A vector of lengthvector.length containing the apportionedvalues fromvalues.

Examples

## Not run: ## Example 1: Without roundingapportioned_vec_1 <- apportion_lr(4, c(1, 2, 3, 4, 5),                                     c(0.25, 0, 0.25, 0.25, 0.25))## Example 2: With roundingapportioned_vec_2 <- apportion_lr(5, c(1, 2, 3, 4, 5),                                     c(0.21, 0, 0.29, 0.25, 0.25))## End(Not run)

Arrivals: netsim Module

Description

This function simulates new arrivals into the networkfor use innetsim simulations.

Usage

arrivals.2g.net(dat, at)

Arguments

dat

Mainnetsim_dat object containing anetworkDynamicobject and other initialization information passed fromnetsim.

at

Current time step.

Value

The updatednetsim_dat main list object.

See Also

netsim


Arrivals: icm Module

Description

This function simulates arrival for use inicmsimulations.

Usage

arrivals.icm(dat, at)

Arguments

dat

Mainicm_dat class data object passed throughicmsimulations.

at

Current time step.

Value

The updatedicm_dat class main data object.

See Also

icm


Arrivals: Bipartite icm Module

Description

This function simulates arrival for use inicmsimulations.

Usage

arrivals.icm.bip(dat, at)

Arguments

dat

Mainicm_dat class data object passed throughicmsimulations.

at

Current time step.

Value

The updatedicm_dat class main data object.

See Also

icm


Arrivals: netsim Module

Description

This function simulates new arrivals into the networkfor use innetsim simulations.

Usage

arrivals.net(dat, at)

Arguments

dat

Mainnetsim_dat object containing anetworkDynamicobject and other initialization information passed fromnetsim.

at

Current time step.

Value

The updatednetsim_dat main list object.

See Also

netsim


Arrive New Nodes to the netsim_dat Object

Description

Arrive New Nodes to the netsim_dat Object

Usage

arrive_nodes(dat, nArrivals)

Arguments

dat

thenetsim_dat object

nArrivals

number of new nodes to arrive

Details

nArrivals new nodes are added to the network data stored onthenetsim_dat object. IftergmLite isFALSE, thesenodes are activated from the current timestep onward. Attributes for the newnodes must be set separately.

Note that this function only supports arriving new nodes; returning to anactive state nodes that were previously active in the network is notsupported.

Value

the updatednetsim_dat object withnArrivals new nodesadded


Extract Model Data for Deterministic Compartmental Models

Description

This function extracts a model run from an object of classdcm into a data frame using the genericas.data.frame function.

Usage

## S3 method for class 'dcm'as.data.frame(x, row.names = NULL, optional = FALSE, run, ...)

Arguments

x

AnEpiModel object of classdcm.

row.names

Seeas.data.frame.default.

optional

Seeas.data.frame.default.

run

Run number for model; used for multiple-run sensitivity models. Ifnot specified, will output data from all runs in a stacked data frame.

...

Seeas.data.frame.default.

Details

Model output fromdcm simulations are available as a dataframe with this helper function. The output data frame will includecolumns for time, the size of each compartment, the overall populationsize (the sum of compartment sizes), and the size of each flow.

For models with multiple runs (i.e., varying parameters - see example below),the default with therun parameter not specified will output all runsin a single stacked data frame.

Value

A data frame containing the data fromx.

Examples

## Example 1: One-group SIS model with varying act.rateparam <- param.dcm(inf.prob = 0.2, act.rate = seq(0.05, 0.5, 0.05),                   rec.rate = 1/50)init <- init.dcm(s.num = 500, i.num = 1)control <- control.dcm(type = "SIS", nsteps = 10)mod1 <- dcm(param, init, control)as.data.frame(mod1)as.data.frame(mod1, run = 1)as.data.frame(mod1, run = 10)## Example 2: Two-group SIR model with vital dynamicsparam <- param.dcm(inf.prob = 0.2, inf.prob.g2 = 0.1,                   act.rate = 3, balance = "g1",                   rec.rate = 1/50, rec.rate.g2 = 1/50,                   a.rate = 1/100, a.rate.g2 = NA,                   ds.rate = 1/100, ds.rate.g2 = 1/100,                   di.rate = 1/90, di.rate.g2 = 1/90,                   dr.rate = 1/100, dr.rate.g2 = 1/100)init <- init.dcm(s.num = 500, i.num = 1, r.num = 0,                 s.num.g2 = 500, i.num.g2 = 1, r.num.g2 = 0)control <- control.dcm(type = "SIR", nsteps = 10)mod2 <- dcm(param, init, control)as.data.frame(mod2)

Extract Model Data for Stochastic Models

Description

This function extracts model simulations for objects of classesicm andnetsim into a data frame usingthe genericas.data.frame function.

Usage

## S3 method for class 'icm'as.data.frame(  x,  row.names = NULL,  optional = FALSE,  out = "vals",  sim = NULL,  qval = NULL,  ...)## S3 method for class 'netsim'as.data.frame(  x,  row.names = NULL,  optional = FALSE,  out = "vals",  sim = NULL,  ...)

Arguments

x

AnEpiModel object of classicm ornetsim.

row.names

Seeas.data.frame.default.

optional

Seeas.data.frame.default.

out

Data output to data frame:"mean" for row means acrosssimulations,"sd" for row standard deviations acrosssimulations,"qnt" for row quantiles at the level specified inqval, or"vals" for values from individual simulations.

sim

Ifout="vals", the simulation number to output. If notspecified, then data from all simulations will be output.

qval

Quantile value required whenout="qnt".

...

Seeas.data.frame.default.

Details

These methods work for bothicm andnetsim class models. Theavailable output includes time-specific means, standard deviations,quantiles, and simulation values (compartment and flow sizes) from thesestochastic model classes. Means, standard deviations, and quantiles arecalculated by taking the row summary (i.e., each row of data is correspondsto a time step) across all simulations in the model output.

Value

A data frame containing the data fromx.

Examples

## Stochastic ICM SIS modelparam <- param.icm(inf.prob = 0.8, act.rate = 2, rec.rate = 0.1)init <- init.icm(s.num = 500, i.num = 1)control <- control.icm(type = "SIS", nsteps = 10,                       nsims = 3, verbose = FALSE)mod <- icm(param, init, control)# Default output all simulation runs, default to all in stacked data.frameas.data.frame(mod)as.data.frame(mod, sim = 2)# Time-specific means across simulationsas.data.frame(mod, out = "mean")# Time-specific standard deviations across simulationsas.data.frame(mod, out = "sd")# Time-specific quantile values across simulationsas.data.frame(mod, out = "qnt", qval = 0.25)as.data.frame(mod, out = "qnt", qval = 0.75)## Not run: ## Stochastic SI Network Modelnw <- network_initialize(n = 100)formation <- ~edgestarget.stats <- 50coef.diss <- dissolution_coefs(dissolution = ~offset(edges), duration = 20)est <- netest(nw, formation, target.stats, coef.diss, verbose = FALSE)param <- param.net(inf.prob = 0.5)init <- init.net(i.num = 10)control <- control.net(type = "SI", nsteps = 10, nsims = 3, verbose = FALSE)mod <- netsim(est, param, init, control)# Same data extraction methods as with ICMsas.data.frame(mod)as.data.frame(mod, sim = 2)as.data.frame(mod, out = "mean")as.data.frame(mod, out = "sd")as.data.frame(mod, out = "qnt", qval = 0.25)as.data.frame(mod, out = "qnt", qval = 0.75)## End(Not run)

Extract Timed Edgelists for netdx Objects

Description

This function extracts timed edgelists for objects of classnetdx into a data frame using the genericas.data.frame function.

Usage

## S3 method for class 'netdx'as.data.frame(x, row.names = NULL, optional = FALSE, sim, ...)

Arguments

x

AnEpiModel object of classnetdx.

row.names

Seeas.data.frame.default.

optional

Seeas.data.frame.default.

sim

The simulation number to output. If not specified, then data fromall simulations will be output.

...

Seeas.data.frame.default.

Value

A data frame containing the data fromx.

Examples

# Initialize and parameterize the network modelnw <- network_initialize(n = 100)formation <- ~edgestarget.stats <- 50coef.diss <- dissolution_coefs(dissolution = ~offset(edges), duration = 20)# Model estimationest <- netest(nw, formation, target.stats, coef.diss, verbose = FALSE)# Simulate the network with netdxdx <- netdx(est, nsims = 3, nsteps = 10, keep.tedgelist = TRUE,            verbose = FALSE)# Extract data from the first simulationas.data.frame(dx, sim = 1)# Extract data from all simulationsas.data.frame(dx)

Validate and Convert to epi.data.frame

Description

This methods ensures that thedata.frame is correctly formatted as anepi.data.frame

Usage

as.epi.data.frame(df)

Arguments

df

Adata.frame to convert into anepi.data.frame


Convert transmat Infection Tree into a network Object

Description

Converts a transmission matrix from theget_transmatfunction into anetwork::network class object.

Usage

## S3 method for class 'transmat'as.network(x, ...)

Arguments

x

An object of classtransmat to be converted into anetwork class object.

...

Unused.

Details

When converting from atransmat to anetwork object, thisfunctions copies the edge attributes within the transmission matrix('at','infDur','transProb','actRate', and'finalProb') into edge attributes on the network.

Value

Anetwork::network object.


Convert transmat Infection Tree into a phylo Object

Description

Converts a transmission matrix from theget_transmatfunction into aphylo class object.

Usage

## S3 method for class 'transmat'as.phylo(x, vertex.exit.times, ...)

Arguments

x

An object of classtransmat, the output fromget_transmat.

vertex.exit.times

Optional numeric vector providing the time ofdeparture of vertices, to be used to scale the lengths of branchesreaching to the tips. Index position on vector corresponds to networkid. NA indicates no departure, so branch will extend to the end of thetree.

...

Further arguments (unused).

Details

Converts atransmat object containing information about thehistory of a simulated infection into aape::phylo objectrepresentation suitable for plotting as a tree withplot.phylo. Each infection event becomes a 'node'(horizontal branch) in the resultingphylo tree, and each networkvertex becomes a 'tip' of the tree. The infection events are labeled with thevertex ID of the infector to make it possible to trace the path of infection.

The infection timing information is included to position the phylo-nodes,with the lines to the tips drawn to the max time value +1 (unlessvertex.exit.times are passed in it effectively assumes all verticesare active until the end of the simulation).

If thetransmat contains multiple infection seeds (there are multipletrees with separate root nodes), this function will return a list of classmultiPhylo, each element of which is aphylo object. Seeread.tree.

Value

Aphylo class object.

Examples

set.seed(13)# Fit a random mixing TERGM with mean degree of 1 and mean edge# duration of 20 time stepsnw <- network_initialize(n = 100)formation <- ~edgestarget.stats <- 50coef.diss <- dissolution_coefs(dissolution = ~offset(edges), duration = 20)est <- netest(nw, formation, target.stats, coef.diss, verbose = FALSE)# Parameterize the epidemic model as SI with one infected seedparam <- param.net(inf.prob = 0.5)init <- init.net(i.num = 1)control <- control.net(type = "SI", nsteps = 40, nsims = 1, verbose = FALSE)# Simulate the modelmod1 <- netsim(est, param, init, control)# Extract the transmission matrixtm <- get_transmat(mod1)head(tm, 15)# Convert to phylo object and plottmPhylo <- as.phylo.transmat(tm)par(mar = c(1,1,1,1))plot(tmPhylo, show.node.label = TRUE,              root.edge = TRUE,              cex = 0.75)

Convert an object to acumulative_edgelist

Description

Convert an object to acumulative_edgelist

Usage

as_cumulative_edgelist(x)

Arguments

x

An object to be converted to a cumulative edgelist

Details

The edges are active from timestart to timestop included. If stop isNA, the edge was not disolved in the simulation that generated the list.

Value

Acumulative_edgelist object, adata.frame with at least thefollowing columns:head,tail,start,stop.


Convert an Edgelist into a Tibble

Description

Convert an Edgelist into a Tibble

Usage

as_tibble_edgelist(el)

Arguments

el

An edgelist in matrix or data frame form.

Value

The edgelist in tibble form with two columns namedhead andtail.


Update Vertex Attributes for Incoming Vertices

Description

Updates the vertex attributes on a network for new nodesincoming into that network, based on a set of rules for eachattribute that the user specifies incontrol.net.

Usage

auto_update_attr(dat, newNodes, curr.tab)

Arguments

dat

Mainnetsim_dat object containing anetworkDynamicobject and other initialization information passed fromnetsim.

newNodes

Vector of nodal IDs for incoming nodes at the current timestep.

curr.tab

Current proportional distribution of all vertex attributes.

Value

The updatednetsim_dat main list object.

See Also

copy_nwattr_to_datattr,get_attr_prop,auto_update_attr.


RColorBrewer Color Ramp for EpiModel Plots

Description

Returns a vector of colors consistent with a high-brightness setof colors from anRColorBrewer palette.

Usage

brewer_ramp(n, plt, delete.lights = TRUE)

Arguments

n

Number of colors to return.

plt

RColorBrewer palette fromRColorBrewer::brewer.pal.

delete.lights

If TRUE, delete the lightest colors from the colorpalette; this helps with plotting in many high-contrast palettes.

Details

RColorBrewer provides easy access to helpful color palettes, but thebuilt-in palettes are limited to the set of colors in the existing palette.This function expands the palette size to any number of colors by fillingin the gaps. Also, colors within the "div" and "seq" set of palettes whosecolors are very light (close to white) are deleted by default for bettervisualization of plots.

Value

A vector of length equal ton with a range of color values consistentwith an RColorBrewer color palette.

See Also

RColorBrewer::RColorBrewer

Examples

# Shows a 100-color ramp for 4 RColorBrewer palettespar(mfrow = c(2, 2), mar=c(1, 1, 2, 1))pals <- c("Spectral", "Greys", "Blues", "Set1")for (i in seq_along(pals)) { plot(1:100, 1:100, type = "n", axes = FALSE, main = pals[i]) abline(v = 1:100, lwd = 6, col = brewer_ramp(100, pals[i]))}

Check that All Attributes in the Mainnetsim_dat Object are of EqualLength

Description

Check that All Attributes in the Mainnetsim_dat Object are of EqualLength

Usage

check_attr_lengths(dat)

Arguments

dat

Mainnetsim_dat object containing anetworkDynamicobject and other initialization information passed fromnetsim.

Value

invisible(TRUE) if everything is correct; an error if not.


Check Degree Distribution for Balance in Target Statistics

Description

Checks for consistency in the implied network statisticsof a two-group network in which the group size andgroup-specific degree distributions are specified.

Usage

check_degdist_bal(num.g1, num.g2, deg.dist.g1, deg.dist.g2)

Arguments

num.g1

Number of nodes in group 1.

num.g2

Number of nodes in group 2.

deg.dist.g1

Vector with fractional degree distribution for group 1.

deg.dist.g2

Vector with fractional degree distribution for group 2.

Details

This function outputs the number of nodes of degree 0 to g, where g is thelength of a fractional degree distribution vector, given that vector and thesize of the group. This utility is used to check for balance in implieddegree given that fractional distribution within two-group networksimulations, in which the degree-constrained counts must be equal acrossgroups.

Examples

# An unbalanced distributioncheck_degdist_bal(num.g1 = 500, num.g2 = 500,                  deg.dist.g2 = c(0.40, 0.55, 0.03, 0.02),                  deg.dist.g1 = c(0.48, 0.41, 0.08, 0.03))# A balanced distributioncheck_degdist_bal(num.g1 = 500, num.g2 = 500,                  deg.dist.g1 = c(0.40, 0.55, 0.04, 0.01),                  deg.dist.g2 = c(0.48, 0.41, 0.08, 0.03))

Check the format of the end.horizon control

Description

Check the format of the end.horizon control

Usage

check_end_horizon_control(dat)

Arguments

dat

Mainnetsim_dat object containing anetworkDynamicobject and other initialization information passed fromnetsim.

Value

TRUE invisibly on succes, errors otherwise


Create a TEA Variable for Infection Status forndtv Animations

Description

Creates a new color-named temporally-extended attribute (TEA)variable in anetworkDynamic object containing a diseasestatus TEA in numeric format.

Usage

color_tea(  nd,  old.var = "testatus",  old.sus = "s",  old.inf = "i",  old.rec = "r",  new.var = "ndtvcol",  new.sus,  new.inf,  new.rec,  verbose = TRUE)

Arguments

nd

An object of classnetworkDynamic.

old.var

Old TEA variable name.

old.sus

Status value for susceptible in old TEA variable.

old.inf

Status value for infected in old TEA variable.

old.rec

Status value for recovered in old TEA variable.

new.var

New TEA variable name to be stored innetworkDynamicobject.

new.sus

Status value for susceptible in new TEA variable.

new.inf

Status value for infected in new TEA variable.

new.rec

Status value for recovered in new TEA variable.

verbose

IfTRUE, print progress to console.

Details

Thendtv package (https://cran.r-project.org/package=ndtv)produces animated visuals for dynamic networks with evolving edge structuresand nodal attributes. Nodal attribute dynamics inndtv movies requirea temporally extended attribute (TEA) containing a standard R color for eachnode at each time step. By default, theEpiModel package uses TEAs tostore disease status history in network model simulations run innetsim. But that status TEA is in numeric format (0, 1, 2).Thecolor_tea function transforms those numeric values of that diseasestatus TEA into a TEA with color values in order to visualize status changesinndtv.

The convention inplot.netsim is to color the susceptiblenodes as blue, infected nodes as red, and recovered nodes as green. Alternatecolors may be specified using thenew.sus,new.inf, andnew.rec parameters, respectively.

Using thecolor_tea function with anetsim object requires thatTEAs for disease status be used and that thenetworkDynamic object besaved in the output:tergmListe must be set toFALSE incontrol.net.

Value

The updated object of classnetworkDynamic.

See Also

netsim and thendtv package documentation.


Update Either the "param" or "control" List

Description

Update Either the "param" or "control" List

Usage

common_updater(dat, type)

Arguments

dat

Mainnetsim_dat object containing anetworkDynamicobject and other initialization information passed fromnetsim.

type

Either"param" or"control".

Value

The updatednetsim_dat main list object.


Plot Compartment Diagram for Epidemic Models

Description

Plots a compartment flow diagram for deterministic compartmentalmodels, stochastic individual contact models, and stochasticnetwork models.

Usage

comp_plot(x, at, digits, ...)## S3 method for class 'netsim'comp_plot(x, at = 1, digits = 3, ...)## S3 method for class 'icm'comp_plot(x, at = 1, digits = 3, ...)## S3 method for class 'dcm'comp_plot(x, at = 1, digits = 3, run = 1, ...)

Arguments

x

AnEpiModel object of classdcm,icm, ornetsim.

at

Time step for model statistics.

digits

Number of significant digits to print.

...

Additional arguments passed to plot (not currently used).

run

Model run number, fordcm class models with multiple runs(sensitivity analyses).

Details

Thecomp_plot function provides a visual summary of an epidemic modelat a specific time step. The information contained incomp_plot is thesame as in thesummary functions for a model, but presentedgraphically as a compartment flow diagram.

Fordcm class plots, specify the model run number if the modelcontains multiple runs, as in a sensitivity analysis. Foricm andnetsim class plots, therun argument is not used; the plotsshow the means and standard deviations across simulations at the specifiedtime step.

These plots are currently limited to one-group models for each of the threemodel classes. That functionality may be expanded in future softwarereleases.

Examples

## Example 1: DCM SIR model with varying act.rateparam <- param.dcm(inf.prob = 0.2, act.rate = 5:7,                   rec.rate = 1/3, a.rate = 1/90, ds.rate = 1/100,                   di.rate = 1/35, dr.rate = 1/100)init <- init.dcm(s.num = 1000, i.num = 1, r.num = 0)control <- control.dcm(type = "SIR", nsteps = 25, verbose = FALSE)mod1 <- dcm(param, init, control)comp_plot(mod1, at = 25, run = 3)## Example 2: ICM SIR model with 3 simulationsparam <- param.icm(inf.prob = 0.2, act.rate = 3, rec.rate = 1/50,                   a.rate = 1/100, ds.rate = 1/100,                   di.rate = 1/90, dr.rate = 1/100)init <- init.icm(s.num = 500, i.num = 1, r.num = 0)control <- control.icm(type = "SIR", nsteps = 25,                       nsims = 3, verbose = FALSE)mod2 <- icm(param, init, control)comp_plot(mod2, at = 25, digits = 1)

Control Settings for Deterministic Compartmental Models

Description

Sets the controls for deterministic compartmental modelssimulated withdcm.

Usage

control.dcm(  type,  nsteps,  dt = 1,  odemethod = "rk4",  dede = FALSE,  new.mod = NULL,  sens.param = TRUE,  print.mod = FALSE,  verbose = FALSE,  ...)

Arguments

type

Disease type to be modeled, with the choice of"SI" forSusceptible-Infected diseases,"SIR" forSusceptible-Infected-Recovered diseases, and"SIS" forSusceptible-Infected-Susceptible diseases.

nsteps

Number of time steps to solve the model over or vector of timesto solve the model over. If the number of time steps, then this mustbe a positive integer of length 1.

dt

Time unit for model solutions, with the default of 1. Modelsolutions for fractional time steps may be obtained by setting this toa number between 0 and 1.

odemethod

Ordinary differential equation (ODE) integration method,with the default of the "Runge-Kutta 4" method (seedeSolve::odefor other options).

dede

IfTRUE, use the delayed differential equation solver,which allows for time-lagged variables.

new.mod

If not running a base model type, a function with a newmodel to be simulated (see details).

sens.param

IfTRUE, evaluate arguments in parameters withlength greater than 1 as sensitivity analyses, with one model run pervalue of the parameter. IfFALSE, one model will be run withparameters of arbitrary length (the model may error unless the modelfunction is designed to accomodate parameter vectors).

print.mod

IfTRUE, print the model form to the console.

verbose

IfTRUE, print model progress to the console.

...

additional control settings passed to model.

Details

control.dcm sets the required control settings for any deterministiccompartmental models solved with thedcm function. Controls arerequired for both base model types and original models. For all base models,thetype argument is a necessary parameter and it has no default.

Value

AnEpiModel object of classcontrol.dcm.

New Model Functions

The form of the model function for base models may be displayed with theprint.mod argument set toTRUE. In this case, the model willnot be run. These model forms may be used as templates to write originalmodel functions.

These new models may be input and solved withdcm using thenew.mod argument, which requires as input a model function.

See Also

Useparam.dcm to specify model parameters andinit.dcm to specify the initial conditions. Run theparameterized model withdcm.


Control Settings for Stochastic Individual Contact Models

Description

Sets the controls for stochastic individual contact modelssimulated withicm.

Usage

control.icm(  type,  nsteps,  nsims = 1,  initialize.FUN = initialize.icm,  infection.FUN = NULL,  recovery.FUN = NULL,  departures.FUN = NULL,  arrivals.FUN = NULL,  prevalence.FUN = NULL,  verbose = FALSE,  verbose.int = 0,  skip.check = FALSE,  ...)

Arguments

type

Disease type to be modeled, with the choice of"SI" forSusceptible-Infected diseases,"SIR" forSusceptible-Infected-Recovered diseases, and"SIS" forSusceptible-Infected-Susceptible diseases.

nsteps

Number of time steps to solve the model over. This must be apositive integer.

nsims

Number of simulations to run.

initialize.FUN

Module to initialize the model at the outset, with thedefault function ofinitialize.icm.

infection.FUN

Module to simulate disease infection, with the defaultfunction ofinfection.icm.

recovery.FUN

Module to simulate disease recovery, with the defaultfunction ofrecovery.icm.

departures.FUN

Module to simulate departures or exits, with thedefault function ofdepartures.icm.

arrivals.FUN

Module to simulate arrivals or entries, with the defaultfunction ofarrivals.icm.

prevalence.FUN

Module to calculate disease prevalence at each timestep, with the default function ofprevalence.icm.

verbose

IfTRUE, print model progress to the console.

verbose.int

Time step interval for printing progress to console, where0 (the default) prints completion status of entire simulation andpositive integerx prints progress after everyx timesteps.

skip.check

IfTRUE, skips the default error checking for thestructure and consistency of the parameter values, initial conditions,and control settings before running base epidemic models. Settingthis toFALSE is recommended when running models with newmodules specified.

...

Additional control settings passed to model.

Details

control.icm sets the required control settings for any stochasticindividual contact model solved with theicm function. Controlsare required for both base model types and when passing original processmodules. For all base models, thetype argument is a necessary parameterand it has no default.

Value

AnEpiModel object of classcontrol.icm.

New Modules

Base ICM models use a set of module functions that specifyhow the individual agents in the population are subjected to infection,recovery, demographics, and other processes. Core modules are those listed inthe.FUN arguments. For each module, there is a default function usedin the simulation. The default infection module, for example, is contained intheinfection.icm function.

For original models, one may substitute replacement module functions for anyof the default functions. New modules may be added to the workflow at eachtime step by passing a module function via the... argument.

See Also

Useparam.icm to specify model parameters andinit.icm to specify the initial conditions. Run theparameterized model withicm.


Control Settings for Stochastic Network Models

Description

Sets the controls for stochastic network models simulated withnetsim.

Usage

control.net(  type,  nsteps,  start = 1,  nsims = 1,  ncores = 1,  resimulate.network = FALSE,  tergmLite = FALSE,  cumulative.edgelist = FALSE,  truncate.el.cuml = 0,  attr.rules,  epi.by,  initialize.FUN = initialize.net,  resim_nets.FUN = resim_nets,  summary_nets.FUN = summary_nets,  infection.FUN = NULL,  recovery.FUN = NULL,  departures.FUN = NULL,  arrivals.FUN = NULL,  nwupdate.FUN = nwupdate.net,  prevalence.FUN = prevalence.net,  verbose.FUN = verbose.net,  module.order = NULL,  save.nwstats = TRUE,  nwstats.formula = "formation",  save.transmat = TRUE,  save.network,  save.run = FALSE,  save.cumulative.edgelist = FALSE,  save.other,  verbose = TRUE,  verbose.int = 1,  skip.check = FALSE,  raw.output = FALSE,  tergmLite.track.duration = FALSE,  set.control.ergm = control.simulate.formula(MCMC.burnin = 2e+05),  set.control.tergm = control.simulate.formula.tergm(),  save.diss.stats = TRUE,  dat.updates = NULL,  ...)

Arguments

type

Disease type to be modeled, with the choice of"SI" for Susceptible-Infecteddiseases,"SIR" for Susceptible-Infected-Recovered diseases, and"SIS" forSusceptible-Infected-Susceptible diseases.

nsteps

Number of time steps to simulate the model over. This must be a positive integerthat is equal to the final step of a simulation. If a simulation is restarted withstartargument, this number must be at least one greater than that argument's value.

start

For models with network resimulation, time point to start up the simulation. Forrestarted simulations, this must be one greater than the final time step in the priorsimulation and must be less than the value innsteps.

nsims

The total number of disease simulations.

ncores

Number of processor cores to run multiple simulations on, using theforeach anddoParallel implementations.

resimulate.network

IfTRUE, resimulate the network at each time step. This is requiredwhen the epidemic or demographic processes impact the network structure (e.g., vitaldynamics).

tergmLite

Logical indicating usage of eithertergm (tergmLite = FALSE), ortergmLite(tergmLite = TRUE). Default ofFALSE.

cumulative.edgelist

IfTRUE, calculates a cumulative edgelist within the networksimulation module. This is used when tergmLite is used and the entire networkDynamicobject is not used.

truncate.el.cuml

Number of time steps of the cumulative edgelist to retain. See help forupdate_cumulative_edgelist for options.

attr.rules

A list containing the rules for setting the attributes of incoming nodes, withone list element per attribute to be set (see details below).

epi.by

A character vector of length 1 containing a nodal attribute for which subgroupstratified prevalence summary statistics are calculated. This nodal attribute must becontained in the network model formation formula, otherwise it is ignored.

initialize.FUN

Module to initialize the model at time 1, with the default function ofinitialize.net.

resim_nets.FUN

Module to resimulate the network at each time step, with the defaultfunction ofresim_nets.

summary_nets.FUN

Module to extract summary statistics of the networkat each time step, with the default function ofsummary_nets.

infection.FUN

Module to simulate disease infection, with the default function ofinfection.net.

recovery.FUN

Module to simulate disease recovery, with the default function ofrecovery.net.

departures.FUN

Module to simulate departure or exit, with the default function ofdepartures.net.

arrivals.FUN

Module to simulate arrivals or entries, with the default function ofarrivals.net.

nwupdate.FUN

Module to handle updating of network structure and nodal attributes due toexogenous epidemic model processes, with the default function ofnwupdate.net.

prevalence.FUN

Module to calculate disease prevalence at each time step, with the defaultfunction ofprevalence.net.

verbose.FUN

Module to print simulation progress to screen, with the default function ofverbose.net.

module.order

A character vector of module names that lists modules in the order in whichthey should be evaluated within each time step. IfNULL, the modules will be evaluatedas follows: first any new modules supplied through... in the order in which they arelisted, then the built-in modules in the order in which they are listed as argumentsabove.initialize.FUN will always be run first andverbose.FUN will always be run last.

save.nwstats

IfTRUE, save network statistics in a data frame. The statistics to besaved are specified in thenwstats.formula argument.

nwstats.formula

A right-hand sided ERGM formula that includes network statistics ofinterest, with the default to the formation formula terms. Supportsmultilayerspecification.

save.transmat

IfTRUE, complete transmission matrix is saved at simulation end.

save.network

IfTRUE, networkDynamic or networkLite object is saved at simulation end.

save.run

IfTRUE, therun sublist ofdat is saved, allowing asimulation to restart from this output.

save.cumulative.edgelist

IfTRUE, thecumulative.edgelist is saved at simulation end.

save.other

A character vector of elements on thenetsim_dat main data list to save outafter each simulation. One example for base models is the attribute list,"attr", atthe final time step.

verbose

IfTRUE, print model progress to the console.

verbose.int

Time step interval for printing progress to console, where0 printscompletion status of entire simulation and positive integerx prints progress aftereveryx time steps. The default is to print progress after each time step.

skip.check

IfTRUE, skips the default error checking for the structure and consistencyof the parameter values, initial conditions, and control settings before running baseepidemic models. Setting this toFALSE is recommended when running models with newmodules specified.

raw.output

IfTRUE,netsim will output a list of raw data (one per simulation) insteadof a cleaned and formattednetsim object.

tergmLite.track.duration

IfTRUE, track duration information for models intergmLitesimulations. Supportsmultilayer specification.

set.control.ergm

Control arguments passed toergm::simulate_formula.network. Innetsim,this is only used when initializing the network withedapprox = TRUE. All othersimulations innetsim usetergm. Supportsmultilayer specification.

set.control.tergm

Control arguments passed totergm::simulate_formula.network. See thehelp file fornetdx for details and examples on specifying this parameter. Supportsmultilayer specification.

save.diss.stats

IfTRUE,netsim will compute and save duration and dissolutionstatistics for plotting and printing, providedsave.network isTRUE,tergmLite isFALSE, and the dissolution model is homogeneous.

dat.updates

EitherNULL, a single function taking argumentsdat,at, andnetwork, or a list of functions of length one greaterthan the number of networks being simulated, with each function inthe list taking argumentsdat andat. Heredat is the mainnetsim_dat class object,at is the current timestep, andnetworkis an index indicating the current position within the sequence ofnetwork (re)simulations on each time step. If a single function ispassed, it will be called before the first network is simulated andafter each network is simulated, withnetwork = 0L before the firstnetwork is simulated and withnetwork = i after theith networkis simulated. If a list of functions is passed, the first functionwill be called before the first network is simulated, and thei + 1th function will be called after theith network issimulated. (Note thatat = 0L is used for initial cross-sectionalsimulations insim_nets_t1.) The function(s) should return thenetsim_dat object with any updates needed to correctly represent thenetwork states for calls tosimulate and/orsummary. This can beuseful if nodal attributes appearing in one network model depend onnodal degrees in a different network.

...

Additional control settings passed to model.

Details

control.net sets the required control settings for any network model solved with thenetsimfunction. Controls are required for both base model types and when passing original processmodules. For an overview of control settings for base models, consult theNetwork Modeling for Epidemics course materials Forall base models, thetype argument is a necessary parameter and it has no default.

Value

An EpiModel object of classcontrol.net.

The attr.rules Argument

Theattr.rules parameter is used to specify the rules for how nodal attribute values forincoming nodes should be set. These rules are only necessary for models in which there areincoming nodes (i.e., arrivals). There are three rules available for each attribute value:

Checkpointing Simulations

netsim has a built-in checkpoint system to prevent losing computation work if the function isinterrupted (SIGINT, power loss, time limit exceeded on a computation cluster). When enabled,each simulation will be saved every.checkpoint.steps time steps. Then, if a checkpoint enabledsimulation is launched again withnetsim, it will restart at the last checkpoint available inthe saved data.

To enable the checkpoint capabilities ofnetsim, two control arguments have to be set:.checkpoint.steps, which is a positive number of time steps to be run between each file save;and.checkpoint.dir, which is the path to a directory to save the checkpointed data. If.checkpoint.dir directory does not exist,netsim will attempt to create it on the firstcheckpoint save. With these two controls defined, one can simply re-runnetsim with the samearguments to restart a set of simulations that were interrupted.

Simulations are checkpointed individually: for example, if 3 simulations are run on a single core,the first 2 are finished, then the interruption occurs during the third,netsim will onlyrestart the third one from the last checkpoint.

A.checkpoint.compress argument can be set to overwrite thecompress argument insaveRDSused to save the checkpointed data. The current default forsaveRDS isgunzip (gz), whichprovides fast compression that usually works well onnetsim objects.

By default, ifnetsim reaches the end of all simulations, the checkpoint data directory and itscontent are removed before returning thenetsim object. The.checkpoint.keep argument can beset toTRUE to prevent this removal to inspect the raw simulation objects.

New Modules

Base network models use a set of module functions that specify how the individual nodes in thenetwork are subjected to infection, recovery, demographics, and other processes. Core modules arethose listed in the.FUN arguments. For each module, there is a default function used inthe simulation. The default infection module, for example, is contained in theinfection.netfunction.

For original models, one may substitute replacement module functions for any of the defaultfunctions. New modules may be added to the workflow at each time step by passing a module functionvia the... argument. Consult theExtending EpiModelsection of the Network Modeling for Epidemics course materials.One may remove existing modules, such asarrivals.FUN, from the workflow by settingthe parameter value for that argument toNULL.

End Horizon

netsim implements an "End Horizon" mechanism, where a set of modules areremoved from the simulation at a specific time step. This is enabled throughtheend.horizon parameter tocontrol.net.

This parameter must receive alist with fieldsat, the time step at whichthe end horizon occurs, andmodules, a character vector with the names ofthe modules to remove. (e.g 'list(at = 208, modules = c("arrivals.FUN","infections.FUN")))

See Also

Useparam.net to specify model parameters andinit.net to specify the initial conditions.Run the parameterized model withnetsim.


Copy Vertex Attributes from thenetsim_dat List to the NetworkObjects

Description

Copies the vertex attributes stored on the mainattr listof thenetsim_dat object to each of the network objectsstored on thenetsim_dat object.

Usage

copy_datattr_to_nwattr(dat)

Arguments

dat

Mainnetsim_dat object containing anetworkDynamicobject and other initialization information passed fromnetsim.

Value

The updatednetsim_dat main list object.

See Also

get_formula_term_attr,get_attr_prop,auto_update_attr, andcopy_nwattr_to_datattr.


Copy Vertex Attributes From Network tonetsim_dat List

Description

Copies the vertex attributes stored on the network object to themainattr list in thenetsim_dat data object.

Usage

copy_nwattr_to_datattr(dat, nw)

Arguments

dat

Mainnetsim_dat object containing anetworkDynamicobject and other initialization information passed fromnetsim.

nw

Network from which to copy vertex attributes.

Value

The updatednetsim_dat main list object.

See Also

get_formula_term_attr,get_attr_prop,auto_update_attr, andcopy_datattr_to_nwattr.


Create a Minimal netsim_dat Main List Object for a Network Model

Description

This helper function populates anetsim_dat main listobject with the minimal required elements. All parameters areoptional. When none are given the resulting object is only ashell list of classnetsim_dat with the different namedelements defined as empty lists.

Usage

create_dat_object(  param = list(),  init = list(),  control = list(),  run = list())

Arguments

param

AnEpiModel object of classparam.net.

init

AnEpiModel object of classinit.net.

control

AnEpiModel object of classcontrol.net.

run

Alist that will contains the objects created bynetsim that are required for between step communication. Thislist must be preserved for restarting models.

Value

Anetsim_dat main list object.


Make a list of EpiModel scenarios from a data.frame of scenarios

Description

An EpiModel scenario allows one or multiple set of parameters to be appliedto a model a predefined timesteps. They are usually used by a researcher whowants to model counterfactuals using a pre calibrated model.

Usage

create_scenario_list(scenarios.df)

Arguments

scenarios.df

adata.frame

Value

a list of EpiModel scenarios

scenarios.df

Thescenarios.df is adata.frame of values to be used asparameters.

It must contain a ".at" column, specifying when the changes should occur.It requires the "updater" module of EpiModel.See, vignette. If the ".at"value of a row is less than two, the changes will be applied to theparameter list iteself. The second mandatory column is ".scenario.id". Itis used to distinguish the different scenarios. If multiple rows share thesame ".scenario.id", the resulting scenario will contain one updater per row.This permits modifying parameters at multiple points in time. (e.g. anintervention limited in time).

The other column names must correspond either to:the name of one parameter if this parameter is of size 1 or the name of theparameter with "_1", "_2", "N" with the second part being the position ofthe value for a parameter of size > 1. This means that the parameter namescannot contain any underscore "". (e.g "a.rate", "d.rate_1", "d.rate_2")


Cross Checking of Inputs for Deterministic Compartmental Models

Description

This function checks that the three parameter lists fromparam.dcm,init.dcm, andcontrol.dcm are consistent.

Usage

crosscheck.dcm(param, init, control)

Arguments

param

AnEpiModel object of classparam.dcm.

init

AnEpiModel object of classinit.dcm.

control

AnEpiModel object of classcontrol.dcm.

Value

This function returns no objects.


Cross Checking of Inputs for Stochastic Individual Contact Models

Description

This function checks that the three parameter lists fromparam.icm,init.icm, andcontrol.icm are consistent.

Usage

crosscheck.icm(param, init, control)

Arguments

param

AnEpiModel object of classparam.icm.

init

AnEpiModel object of classinit.icm.

control

AnEpiModel object of classcontrol.icm.

Value

This function returns no objects.


Cross Checking of Inputs for Stochastic Network Models

Description

This function checks that the estimation object fromnetest and the three parameter lists fromparam.net,init.net, andcontrol.net are consistent.

Usage

crosscheck.net(x, param, init, control)

Arguments

x

AnEpiModel object of classnetest.

param

AnEpiModel object of classparam.net.

init

AnEpiModel object of classinit.net.

control

AnEpiModel object of classcontrol.net.

Value

This function returns no objects.


Deterministic Compartmental Models

Description

Solves deterministic compartmental epidemic models forinfectious disease.

Usage

dcm(param, init, control)

Arguments

param

Model parameters, as an object of classparam.dcm.

init

Initial conditions, as an object of classinit.dcm.

control

Control settings, as an object of classcontrol.dcm.

Details

Thedcm function uses the ordinary differential equation solver inthedeSolve package to model disease as a deterministic compartmentalsystem. The parameterization for these models follows the standard approachinEpiModel, with epidemic parameters, initial conditions, and controlsettings.

Thedcm function performs modeling of both base model types andoriginal models with new structures. Base model types include one-groupand two-group models with disease types for Susceptible-Infected (SI),Susceptible-Infected-Recovered (SIR), and Susceptible-Infected-Susceptible(SIS). Both base and original models require theparam,init, andcontrol inputs.

Value

A list of classdcm with the following elements:

References

Soetaert K, Petzoldt T, Setzer W. Solving Differential Equations inR: Package deSolve. Journal of Statistical Software. 2010; 33(9): 1-25.doi:10.18637/jss.v033.i09.

See Also

Extract the model results withas.data.frame.dcm.Summarize the time-specific model results withsummary.dcm.Plot the model results withplot.dcm. Plot a compartment flowdiagram withcomp_plot.

Examples

## Example 1: SI Model (One-Group)# Set parametersparam <- param.dcm(inf.prob = 0.2, act.rate = 0.25)init <- init.dcm(s.num = 500, i.num = 1)control <- control.dcm(type = "SI", nsteps = 500)mod1 <- dcm(param, init, control)mod1plot(mod1)## Example 2: SIR Model with Vital Dynamics (One-Group)param <- param.dcm(inf.prob = 0.2, act.rate = 5,                   rec.rate = 1/3, a.rate = 1/90, ds.rate = 1/100,                   di.rate = 1/35, dr.rate = 1/100)init <- init.dcm(s.num = 500, i.num = 1, r.num = 0)control <- control.dcm(type = "SIR", nsteps = 500)mod2 <- dcm(param, init, control)mod2plot(mod2)## Example 3: SIS Model with act.rate Sensitivity Parameterparam <- param.dcm(inf.prob = 0.2, act.rate = seq(0.1, 0.5, 0.1),                   rec.rate = 1/50)init <- init.dcm(s.num = 500, i.num = 1)control <- control.dcm(type = "SIS", nsteps = 500)mod3 <- dcm(param, init, control)mod3plot(mod3)## Example 4: SI Model with Vital Dynamics (Two-Group)param <- param.dcm(inf.prob = 0.4,  inf.prob.g2 = 0.1,                   act.rate = 0.25, balance = "g1",                   a.rate = 1/100, a.rate.g2 = NA,                   ds.rate = 1/100, ds.rate.g2 = 1/100,                   di.rate = 1/50, di.rate.g2 = 1/50)init <- init.dcm(s.num = 500, i.num = 1,                 s.num.g2 = 500, i.num.g2 = 0)control <- control.dcm(type = "SI", nsteps = 500)mod4 <- dcm(param, init, control)mod4plot(mod4)

Deterministic Compartmental Model Functions

Description

These functions parameterize the base deterministiccompartmental models solved using thedcmfunction.

Usage

mod_SI_1g_cl(t, t0, parms)mod_SI_1g_op(t, t0, parms)mod_SI_2g_cl(t, t0, parms)mod_SI_2g_op(t, t0, parms)mod_SIR_1g_cl(t, t0, parms)mod_SIR_1g_op(t, t0, parms)mod_SIR_2g_cl(t, t0, parms)mod_SIR_2g_op(t, t0, parms)mod_SIS_1g_cl(t, t0, parms)mod_SIS_1g_op(t, t0, parms)mod_SIS_2g_cl(t, t0, parms)mod_SIS_2g_op(t, t0, parms)

Arguments

t

Time vector, passed into model function internally throughdcm via the control settings incontrol.dcm.

t0

Initial conditions for model, passed into model function internallythroughdcm via the initial conditions ininit.dcm.

parms

Model parameters, passed into model function internally throughdcm via the parameter settings inparam.dcm.

Details

This help page shows the names of all the base deterministic compartmentalmodel functions supported in EpiModel. Base models are those alreadyprogrammed interally within the software. The model functions may be printedto see their internal structure, either directly on the console or by usingtheprint.mod argument incontrol.dcm.

The naming convention for the models listed here follows the format:mod_<disease type>_<number of groups>_<vital dynamics>. The supporteddisease types are SI, SIS, and SIR; the number of groups are 1 or 2; and thevital dynamic options are closed (fixed population composition) or open (witharrivals and departures).


Deduplicate a cumulative edgelist by combining overlapping edges

Description

Deduplicate a cumulative edgelist by combining overlapping edges

Usage

dedup_cumulative_edgelist(el)

Arguments

el

A cumulative edgelist with potentially overlapping edges

Value

A cumulative edgelist with no overlapping edges


Delete Elements from Attribute List

Description

Deletes elements from the main attribute list.

Usage

delete_attr(dat, ids)

Arguments

dat

Either thenetsim_dat class object passed throughnetsim simulations, or the main data object passed throughicm simulations.

ids

ID numbers to delete from the list.

Value

The updatednetsim_dat main list object.


Remove Edges That Include Specified Vertices

Description

Given a current two-column matrix of edges and a vector ofvertex IDs, this function removes any rows of the edgelist inwhich the IDs are present.

Usage

delete_edges(el, vid)

Arguments

el

A two-column matrix of current edges (edgelist).

vid

A vector of vertex IDs whose edges are to be deleted from theedgelist.

Value

Returns an updated edgelist object, with any edges including the specifiedvertices removed.


Fast Version of network::delete.vertices for Edgelist-formattedNetwork

Description

Given a current two-column matrix of edges and a vector of IDsto delete from the matrix, this function first removes any rowsof the edgelist in which the IDs are present and then permutesdownward the index of IDs on the edgelist that were numericallylarger than the IDs deleted.

Usage

delete_vertices(el, vid)

Arguments

el

A two-column matrix of current edges (edgelist) with an attributevariablen containing the total current network size.

vid

A vector of IDs to delete from the edgelist.

Details

This function is used inEpiModel modules to remove vertices (nodes)from the edgelist object to account for exits from the population (e.g.,deaths and out-migration).

Value

Returns an updated edgelist object,el, with the edges of deletedvertices removed from the edgelist and the ID numbers of the remaining edgespermuted downward.

Examples

## Not run: library("EpiModel")set.seed(12345)nw <- network_initialize(100)formation <- ~edgestarget.stats <- 50coef.diss <- dissolution_coefs(dissolution = ~offset(edges), duration = 20)x <- netest(nw, formation, target.stats, coef.diss, verbose = FALSE)param <- param.net(inf.prob = 0.3)init <- init.net(i.num = 10)control <- control.net(type = "SI", nsteps = 100, nsims = 5,                       tergmLite = TRUE)# Set seed for reproducibilityset.seed(123456)# networkLite representation structure after initializationdat <- crosscheck.net(x, param, init, control)dat <- initialize.net(x, param, init, control)# Current edgeshead(dat$el[[1]], 20)# Remove nodes 1 and 2nodes.to.delete <- 1:2dat$el[[1]] <- delete_vertices(dat$el[[1]], nodes.to.delete)# Newly permuted edgeshead(dat$el[[1]], 20)## End(Not run)

Depart Nodes from the netsim_dat Object

Description

Depart Nodes from the netsim_dat Object

Usage

depart_nodes(dat, departures)

Arguments

dat

thenetsim_dat object

departures

the vertex ids of nodes to depart

Details

IftergmLite isFALSE, the vertex idsdepartures are deactivated (from the current timestep onward) in eachnetworkDynamic stored indat$nw. IftergmLite isTRUE, the vertex idsdepartures are deleted fromdat$el,dat$attr, anddat$net_attr.

Value

the updatednetsim_dat object with the nodes indepartures departed


Departures: netsim Module

Description

This function simulates departure for use innetsimsimulations.

Usage

departures.2g.net(dat, at)

Arguments

dat

Mainnetsim_dat object containing anetworkDynamicobject and other initialization information passed fromnetsim.

at

Current time step.

Value

The updatednetsim_dat main list object.

See Also

netsim


Departure: icm Module

Description

This function simulates departure for use inicmsimulations.

Usage

departures.icm(dat, at)

Arguments

dat

Mainicm_dat class data object passed throughicmsimulations.

at

Current time step.

Value

The updatedicm_dat class main data object.

See Also

icm


Departure: Bipartite icm Module

Description

This function simulates departure for use inicmsimulations.

Usage

departures.icm.bip(dat, at)

Arguments

dat

Mainicm_dat class data object passed throughicmsimulations.

at

Current time step.

Value

The updatedicm_dat class main data object.

See Also

icm


Departures: netsim Module

Description

This function simulates departure for use innetsimsimulations.

Usage

departures.net(dat, at)

Arguments

dat

Mainnetsim_dat object containing anetworkDynamicobject and other initialization information passed fromnetsim.

at

Current time step.

Value

The updatednetsim_dat main list object.

See Also

netsim


Discordant Edgelist

Description

This function returns adata.frame with a discordantedgelist, defined as the set of edges in which the status of thetwo partners is one susceptible and one infected.

Usage

discord_edgelist(dat, at, network = 1, infstat = "i", include.network = FALSE)

Arguments

dat

Mainnetsim_dat object containing anetworkDynamicobject and other initialization information passed fromnetsim.

at

Current time step.

network

In case of models with multiple networks, the network to pullthe current edgelist from. Default ofnetwork = 1.

infstat

Character vector of disease status values that are consideredinfectious, defining the SI pairs.

include.network

Should thenetwork value be included as thefinal column of the discordant edgelist?

Details

This internal function works within the parentinfection.netfunction to pull the current edgelist from the dynamic network object, lookup the disease status of the head and tails on the edge, and subset the listto those edges with one susceptible and one infected node.

EpiModel v2.0.3 extended the function by allowing flexibility in thedefinition what disease status counts as infectious, with theinfstatparameter. For extension models with multiple infectious states, this can bea vector of length greater than 1:infstat = c("i", "a").

Value

This function returns adata.frame with the following columns:

The output from this function is added to the transmissiondata.frameobject that is requested as output innetsim simulations withthesave.trans=TRUE argument.

See Also

netsim,infection.net


Dissolution Coefficients for Stochastic Network Models

Description

Calculates dissolution coefficients, given a dissolution modeland average edge duration, to pass as offsets to an ERGM/TERGMmodel fit innetest.

Usage

dissolution_coefs(dissolution, duration, d.rate = 0)

Arguments

dissolution

Right-hand sided STERGM dissolution formula(seenetest). See below for list of supporteddissolution models.

duration

A vector of mean edge durations in arbitrary time units.

d.rate

Departure or exit rate from the population, as a singlehomogeneous rate that applies to the entire population.

Details

This function performs two calculations for dissolution coefficientsused in a network model estimated withnetest:

  1. Transformation: the mean durations of edges in a network aremathematically transformed to logit coefficients.

  2. Adjustment: in a dynamic network simulation in an openpopulation (in which there are departures), it is further necessary toadjust these coefficients; this upward adjustment accounts fordeparture as a competing risk to edge dissolution.

The current dissolution models supported by this function and in networkmodel estimation innetest are as follows:

Value

A list of classdisscoef with the following elements:

Examples

## Homogeneous dissolution model with no departuresdissolution_coefs(dissolution = ~offset(edges), duration = 25)## Homogeneous dissolution model with departuresdissolution_coefs(dissolution = ~offset(edges), duration = 25,                  d.rate = 0.001)## Heterogeneous dissolution model in which same-race edges have## shorter duration compared to mixed-race edges, with no departuresdissolution_coefs(dissolution = ~offset(edges) + offset(nodematch("race")),                  duration = c(20, 10))## Heterogeneous dissolution model in which same-race edges have## shorter duration compared to mixed-race edges, with departuresdissolution_coefs(dissolution = ~offset(edges) + offset(nodematch("race")),                  duration = c(20, 10), d.rate = 0.001)## Not run: ## Extended example for differential homophily by age group# Set up the network with nodes categorized into 5 age groupsnw <- network_initialize(n = 1000)age.grp <- sample(1:5, 1000, TRUE)nw <- set_vertex_attribute(nw, "age.grp", age.grp)# durations = non-matched, age.grp1 & age.grp1, age.grp2 & age.grp2, ...# TERGM will include differential homophily by age group with nodematch term# Target stats for the formation model are overall edges, and then the number# matched within age.grp 1, age.grp 2, ..., age.grp 5form <- ~edges + nodematch("age.grp", diff = TRUE)target.stats <- c(450, 100, 125, 40, 80, 100)# Target stats for the dissolution model are duration of non-matched edges,# then duration of edges matched within age.grp 1, age.grp 2, ..., age.grp 5durs <- c(60, 30, 80, 100, 125, 160)diss <- dissolution_coefs(~offset(edges) +                            offset(nodematch("age.grp", diff = TRUE)),                          duration = durs)# Fit the TERGMfit <- netest(nw, form, target.stats, diss)# Full diagnostics to evaluate model fitdx <- netdx(fit, nsims = 10, ncores = 4, nsteps = 300)print(dx)# Simulate one long time series to examine timed edgelistdx <- netdx(fit, nsims = 1, nsteps = 5000, keep.tedgelist = TRUE)# Extract timed-edgelistte <- as.data.frame(dx)head(te)# Limit to non-censored edgeste <- te[which(te$onset.censored == FALSE & te$terminus.censored == FALSE),         c("head", "tail", "duration")]head(te)# Look up the age group of head and tail nodeste$ag.head <- age.grp[te$head]te$ag.tail <- age.grp[te$tail]head(te)# Recover average edge durations for age-group pairingmean(te$duration[te$ag.head != te$ag.tail])mean(te$duration[te$ag.head == 1 & te$ag.tail == 1])mean(te$duration[te$ag.head == 2 & te$ag.tail == 2])mean(te$duration[te$ag.head == 3 & te$ag.tail == 3])mean(te$duration[te$ag.head == 4 & te$ag.tail == 4])mean(te$duration[te$ag.head == 5 & te$ag.tail == 5])durs## End(Not run)

Table of Edge Censoring

Description

Outputs a table of the number and percent of edges that areleft-censored, right-censored, both-censored, or uncensored foranetworkDynamic object.

Usage

edgelist_censor(el)

Arguments

el

A timed edgelist with start and end times extracted from anetworkDynamic object using theas.data.frame.networkDynamic function.

Details

Given a STERGM simulation over a specified number of time steps, the edgeswithin that simulation may be left-censored (started before the first step),right-censored (continued after the last step), right and left-censored, oruncensored. The amount of censoring will increase when the average edgeduration approaches the length of the simulation.

Value

A 4 x 2 table containing the number and percent of edges inelthat are left-censored, right-censored, both-censored, or uncensored.

Examples

# Initialize and parameterize network modelnw <- network_initialize(n = 100)formation <- ~edgestarget.stats <- 50coef.diss <- dissolution_coefs(dissolution = ~offset(edges), duration = 20)# Model estimationest <- netest(nw, formation, target.stats, coef.diss, verbose = FALSE)# Simulate the network and extract a timed edgelistdx <- netdx(est, nsims = 1, nsteps = 100, keep.tedgelist = TRUE,      verbose = FALSE)el <- as.data.frame(dx)# Calculate censoringedgelist_censor(el)

Adjustment for the Edges Coefficient with Changing Network Size

Description

Adjusts the edges coefficient in a dynamic network modelsimulated innetsim to preserve the meandegree of nodes in the network. Requiresat >= 2.Maintains thenum(.g2) epi fields (initialized insim_nets_t1) for computing the coefficientadjustment.

Usage

edges_correct(dat, at)

Arguments

dat

Mainnetsim_dat object containing anetworkDynamicobject and other initialization information passed fromnetsim.

at

Current time step.

Value

The updatednetsim_dat main list object.


Function to run the user-provided epi trackers

Description

see the "Working with Custom Attributes and Summary Statistics in EpiModel"vignette.

Usage

epi_trackers(dat)

Arguments

dat

Mainnetsim_dat object containing anetworkDynamicobject and other initialization information passed fromnetsim.

Value

The updatednetsim_dat main list object.

Thetracker.list list

.tracker.list is a list of NAMED functions stored in thecontrol list of the mainnetsim_dat class object.

Tracker Functions

This function will apply the tracker functions present in the control list.tracker.list. Each tracker must be a function with EXACTLY oneargument: thenetsim_dat main list object. They must return a VALUE oflength one (numeric, logical or character).

See Also

netsim

Examples

## Not run: # Create some trackersepi_prop_infected <- function(dat) {  # we need two attributes for our calculation: `status` and `active`  needed_attributes <- c("status", "active")  # we use `with` to simplify code  output <- with(EpiModel::get_attr_list(dat, needed_attributes), {    pop <- active == 1             # we only look at active nodes    cond <- status == "i"   # which are infected    # how many are `infected` among the `active`    sum(cond & pop, na.rm = TRUE) / sum(pop, na.rm = TRUE)  })  return(output)}epi_s_num <- function(dat) {  needed_attributes <- c("status")  output <- with(get_attr_list(dat, needed_attributes), {    sum(status == "s", na.rm = TRUE)  })  return(output)}# Store the trackers in a named list. The names will be used as column names# for in the `epi` listsome.trackers <- list(  prop_infected = epi_prop_infected,  s_num         = epi_s_num)# Make a simple SI model with custom trackerscontrol <- EpiModel::control.net(  type = "SI",  nsims = 1,  nsteps = 50,  verbose = FALSE,  .tracker.list = some.trackers)param <- EpiModel::param.net(  inf.prob = 0.3,  act.rate = 0.1)nw <- network_initialize(n = 50)nw <- set_vertex_attribute(nw, "race", rbinom(50, 1, 0.5))est <- EpiModel::netest(  nw,  formation = ~edges,  target.stats = 25,  coef.diss = dissolution_coefs(~offset(edges), 10, 0),  verbose = FALSE)init <- EpiModel::init.net(i.num = 10)sim <- EpiModel::netsim(est, param, init, control)d <- as.data.frame(sim)d## End(Not run)

EpiModel Web

Description

Runs a web browser-based GUI of deterministic compartmentalmodels, stochastic individual contact models, and basic networkmodels.

Usage

epiweb(class, ...)

Arguments

class

Model class, with options of"dcm","icm", and"net".

...

Additional arguments passed toshiny::runApp.

Details

epiweb runs a web-based GUI of one-group deterministic compartmentalmodels, stochastic individual contact models, and stochastic network modelswith user input on model type, state sizes, and parameters. Model output maybe plotted, summarized, and saved as raw data using the coreEpiModelfunctionality for these model classes. These applications are built usingtheshiny package framework.

References

RStudio. shiny: Web Application Framework for R. R package version 1.0.5.2015.https://shiny.posit.co/.

See Also

dcm,icm,netsim

Examples

## Not run: ## Deterministic compartmental modelsepiweb(class = "dcm")## Stochastic individual contact modelsepiweb(class = "icm")## Stochastic network modelsepiweb(class = "net")## End(Not run)

Format One Parameter for Printing with theprint.param.xxxFunctions

Description

Format One Parameter for Printing with theprint.param.xxxFunctions

Usage

format_param(param_name, param_value)

Arguments

param_name

The name of the parameter to print.

param_value

The value of the parameter to print.


Generate Values for Random Parameters

Description

This function uses the generative functions in therandom.params list to create values for the parameters.

Usage

generate_random_params(param, verbose = FALSE)

Arguments

param

Theparam argument received by thenetsimfunctions.

verbose

Should the function output the generated values(default = FALSE)?

Value

A fully instantiatedparam list.

random.params

Therandom.params argument to theparam.net functionmust be a named list of functions that each return a value that can be usedas the argument with the same name. In the example below,param_randomis a function factory provided by EpiModel foract.rate andfortx.halt.part.prob we provide bespoke functions. A function factoryis a function that returns a new function(see https://adv-r.hadley.nz/function-factories.html).

Generator Functions

The functions used insiderandom_params must be 0 argument functionsreturning a valid value for the parameter with the same name.

param_random_set

Therandom_params list can optionally contain aparam_random_set element. It must be adata.frame of possiblevalues to be used as parameters.

The column names must correspond either to:the name of one parameter, if this parameter is of size 1; or the name of oneparameter with "_1", "2", etc. appended, with the number representing theposition of the value, if this parameter is of size > 1. This means that theparameter names cannot contain any underscores "" if you intend to useparam_random_set.

The point of theparam.random.setdata.frame is to allow therandom parameters to be correlated. To achieve this, a whole row of thedata.frame is selected for each simulation.

Examples

## Not run: ## Example with only the generator function# Define random parameter listmy_randoms <- list(  act.rate = param_random(c(0.25, 0.5, 0.75)),  tx.prob = function() rbeta(1, 1, 2),  stratified.test.rate = function() c(    rnorm(1, 0.05, 0.01),    rnorm(1, 0.15, 0.03),    rnorm(1, 0.25, 0.05)  ))# Parameter model with fixed and random parametersparam <- param.net(inf.prob = 0.3, random.params = my_randoms)# Below, `tx.prob` is set first to 0.3 then assigned a random value using# the function from `my_randoms`. A warning notifying of this overwrite is# therefore produced.param <- param.net(tx.prob = 0.3, random.params = my_randoms)# Parameters are drawn automatically in netsim by calling the function# within netsim_loop. Demonstrating draws here but this is not used by# end user.paramDraw <- generate_random_params(param, verbose = TRUE)paramDraw## Addition of the `param.random.set` `data.frame`# This function will generate sets of correlated parameters generate_correlated_params <- function() {   param.unique <- runif(1)   param.set.1 <- param.unique + runif(2)   param.set.2 <- param.unique * rnorm(3)   return(list(param.unique, param.set.1, param.set.2)) } # Data.frame set of random parameters : correlated_params <- t(replicate(10, unlist(generate_correlated_params()))) correlated_params <- as.data.frame(correlated_params) colnames(correlated_params) <- c(   "param.unique",   "param.set.1_1", "param.set.1_2",   "param.set.2_1", "param.set.2_2", "param.set.2_3" )# Define random parameter list with the `param.random.set` elementmy_randoms <- list(  act.rate = param_random(c(0.25, 0.5, 0.75)),  param.random.set = correlated_params)# Parameter model with fixed and random parametersparam <- param.net(inf.prob = 0.3, random.params = my_randoms)# Parameters are drawn automatically in netsim by calling the function# within netsim_loop. Demonstrating draws here but this is not used by# end user.paramDraw <- generate_random_params(param, verbose = TRUE)paramDraw## End(Not run)

ggplot2 Geom for Quantile Bands

Description

Plots quantile bands given a data.frame with stochastic modelresults fromicm ornetsim.

Usage

geom_bands(mapping, lower = 0.25, upper = 0.75, alpha = 0.25, ...)

Arguments

mapping

Standard aesthetic mappingaes() input for ggplot2.

lower

Lower quantile for the time series.

upper

Upper quantile for the time series.

alpha

Transparency of the ribbon fill.

...

Additional arguments passed tostat_summary.

Details

This is a wrapper aroundggplot::stat_summary with a ribbon geom asaesthetic output.

Examples

param <- param.icm(inf.prob = 0.2, act.rate = 0.25)init <- init.icm(s.num = 500, i.num = 1)control <- control.icm(type = "SI", nsteps = 250, nsims = 5)mod1 <- icm(param, init, control)df <- as.data.frame(mod1)df.mean <- as.data.frame(mod1, out = "mean")library(ggplot2)ggplot() +   geom_line(data = df, mapping = aes(time, i.num, group = sim),   alpha = 0.25, lwd = 0.25, color = "firebrick") +   geom_bands(data = df, mapping = aes(time, i.num),              lower = 0.1, upper = 0.9, fill = "firebrick") +   geom_line(data = df.mean, mapping = aes(time, i.num)) +   theme_minimal()

Returns an adjacency list from an edge list

Description

Returns an adjacency list from an edge list

Usage

get_adj_list(el, n_nodes)

Arguments

el

An edge list as a data.frame with columnshead andtail

n_nodes

The size number of node in the network

Details

The adjacency list is alist of lengthn_nodes. The entry for each nodeis a integer vector containing the index of all the nodes connected to it.This layout makes it directly subsetable in O(1) at the expanse of memoryusage.To get all connections to the nodes 10 and 15 :⁠unlist(adj_list[c(10, 15)]⁠

Value

An adjacency list for the network


Get Arguments from EpiModel Parameterization Functions

Description

Returns a list of argument names and values for use forparameter processing functions.

Usage

get_args(formal.args, dot.args)

Arguments

formal.args

The output offormals(sys.function()).

dot.args

The output oflist(...).

Value

A list of argument names and values.


Extract the Attributes History from Network Simulations

Description

Extract the Attributes History from Network Simulations

Usage

get_attr_history(sims)

Arguments

sims

AnEpiModel object of classnetsim.

Value

A list ofdata.frames, one for each "measure" recorded in thesimulation by therecord_attr_history function.

Examples

## Not run: # With `sims` the result of a `netsim` callget_attr_history(sims)## End(Not run)

Proportional Table of Vertex Attributes

Description

Calculates the proportional distribution of each vertexattribute contained in a network.

Usage

get_attr_prop(dat, nwterms)

Arguments

dat

Mainnetsim_dat object containing anetworkDynamicobject and other initialization information passed fromnetsim.

nwterms

Vector of attributes on the network object, usually asoutput ofget_formula_term_attr.

Value

A table containing the proportional distribution of each attribute innwterms.

See Also

get_formula_term_attr,copy_nwattr_to_datattr,auto_update_attr.


Returns all the node connected directly or indirectly to a set of nodes

Description

Returns all the node connected directly or indirectly to a set of nodes

Usage

get_connected_nodes(adj_list, nodes)

Arguments

adj_list

The network represented as an adjacency list

nodes

A set of nodes

Value

A vector of nodes indexes that are connected together with the onesprovided in thenodes argument. Thenodes themselves are notlisted in this output


Return the Cumulative Degree of a Set of Index Nodes

Description

Return the Cumulative Degree of a Set of Index Nodes

Usage

get_cumulative_degree(  dat,  index_posit_ids,  networks = NULL,  truncate = Inf,  only.active.nodes = FALSE)

Arguments

dat

Mainnetsim_dat object containing anetworkDynamicobject and other initialization information passed fromnetsim.

index_posit_ids

The positional IDs of the indexes of interest.

networks

Numerical indexes of the networks to extract the partnerships from. (May be > 1for models with multi-layer networks.) IfNULL, extract from all networks.

truncate

After how many time steps a partnership that is no longeractive should be removed from the output.

only.active.nodes

IfTRUE, then inactive (e.g., deceased) partners will be removed fromthe output.

Value

Adata.frame with 2 columns:

Cumulative Degree

The cumulative degree of a node is the number of edges connected to thisnode at during the time window. The time window is by default all the stepsstored in thecumulative_edgelist or set by thetruncate parameter.


Get a Cumulative Edgelist From a Specified Network

Description

Get a Cumulative Edgelist From a Specified Network

Usage

get_cumulative_edgelist(dat, network)

Arguments

dat

Mainnetsim_dat object containing anetworkDynamicobject and other initialization information passed fromnetsim.

network

Numerical index of the network from which the cumulativeedgelist should be extracted. (May be > 1 for models withmultiple overlapping networks.)

Value

A cumulative edgelist indata.frame form with 4 columns:


Get the Cumulative Edgelists of a Model

Description

Get the Cumulative Edgelists of a Model

Usage

get_cumulative_edgelists_df(dat, networks = NULL)

Arguments

dat

Mainnetsim_dat object containing anetworkDynamicobject and other initialization information passed fromnetsim.

networks

Numerical indexes of the networks to extract the partnershipsfrom. (May be > 1 for models with multiple overlappingnetworks.) IfNULL, extract from all networks.

Value

Adata.frame with 5 columns:


Return the Current Timestep

Description

Return the Current Timestep

Usage

get_current_timestep(dat)

Arguments

dat

Mainnetsim_dat object containing anetworkDynamicobject and other initialization information passed fromnetsim.

Value

The current timestep.


Get Individual Degree from Network or Edgelist

Description

A fast method for querying the current degree of all individualswithin a network.

Usage

get_degree(x)

Arguments

x

Either an object of classnetwork oredgelistgenerated from a network. Ifx is an edgelist, then it mustcontain an attribute for the total network size,n.

Details

Individual-level data on the current degree of nodes within a network isoften useful for summary statistics. Given anetwork class object,net, one way to look up the current degree is to get a summary of theERGM term,sociality, as in:summary(net ~ sociality(nodes = NULL)). But that is computationallyinefficient for a number of reasons. This function provides a fast method forgenerating the vector of degrees using a query of the edgelist. It is evenfaster if the parameterx is already transformed into an edgelist.

Value

A vector of length equal to the total network size, containing thecurrent degree of each node in the network.

Examples

nw <- network_initialize(n = 500)set.seed(1)fit <- ergm(nw ~ edges, target.stats = 250)sim <- simulate(fit)# Slow ERGM-based methodergm.method <- unname(summary(sim ~ sociality(nodes = NULL)))ergm.method# Fast tabulate method with network objectdeg.net <- get_degree(sim)deg.net# Even faster if network already transformed into an edgelistel <- as.edgelist(sim)deg.el <- get_degree(el)deg.elidentical(as.integer(ergm.method), deg.net, deg.el)

Get Discordant Edgelist Based on Specified Status Variable

Description

This function returns adata.frame with a discordantedgelist, defined as the set of edges for which the status attributeof interest is discordant between the two partners.

Usage

get_discordant_edgelist(  dat,  status.attr,  head.status,  tail.status,  networks = NULL)

Arguments

dat

Mainnetsim_dat object containing anetworkDynamicobject and other initialization information passed fromnetsim.

status.attr

The name of the status attribute of interest.

head.status

The value(s) ofstatus.attr for which to look for the head of the edge.Can be a single value or a vector.

tail.status

The value(s) ofstatus.attr for which to look for the tail of the edge.Can be a single value or a vector.

networks

Numerical indexes of the networks to extract the partnershipsfrom. (May be > 1 for models with multiple overlappingnetworks.) IfNULL, extract from all networks.

Details

This is a generalized version of thediscord_edgelist function.It creates an edgelist of current partnerships in which the status attributeof interest (as specified by the parameterstatus.attr) of one partner matchesthe value (or one of the values) of thehead.status parameter while thecorresponding status attribute of the other partner matches the value (orone of the values) of thetail.status parameter.

Value

Adata.frame with the following columns:

See Also

discord_edgelist


Get an Edgelist From the Specified Network

Description

This function outputs an edgelist from the specified network,selecting the method depending on the stored network type.

Usage

get_edgelist(dat, network)

Arguments

dat

Mainnetsim_dat object containing anetworkDynamicobject and other initialization information passed fromnetsim.

network

Numerical index of the network from which the edgelist shouldbe extracted. (May be > 1 for models with multiple overlappingnetworks.)

Value

An edgelist in matrix form with two columns. Each column contains theposit_ids (seeget_posit_ids) of the nodes in each edge.


Get the Edgelist(s) from the Specified Network(s)

Description

Get the Edgelist(s) from the Specified Network(s)

Usage

get_edgelists_df(dat, networks = NULL)

Arguments

dat

Mainnetsim_dat object containing anetworkDynamicobject and other initialization information passed fromnetsim.

networks

Numerical indexes of the networks to extract the partnershipsfrom. (May be > 1 for models with multiple overlappingnetworks.) IfNULL, extract from all networks.

Value

Adata.frame with the following columns:


Output ERGM Formula Attributes into a Character Vector

Description

Given a formation formula for a network model, outputs acharacter vector of vertex attributes to be used innetsim simulations.

Usage

get_formula_term_attr(form, nw)

Arguments

form

An ERGM model formula.

nw

A network object.

Value

A character vector of vertex attributes.


Get the List of Modules

Description

Get the List of Modules

Usage

get_modules(dat)

Arguments

dat

Mainnetsim_dat object containing anetworkDynamicobject and other initialization information passed fromnetsim.

Value

A named list of modules to be run by the model


Extract Network Objects from Network Simulations

Description

Extracts the network object from either a network epidemic modelobject generated withnetsim, a network diagnosticsimulation generated withnetdx, or anetsim_datobject used internally innetsim. Fornetdx ornetsim withtergmLite == FALSE, the extractednetwork object is anetworkDynamic, which can becollapsed down to a staticnetwork object with thecollapse andat arguments. Fornetsim withtergmLite == TRUE, the extracted network object is thefinalnetworkLite, thecollapse argument should beFALSE, and theat argument should be missing. Fornetsim_dat, thecollapse andat argumentsare not supported, and the network object is either the currentnetworkLite (iftergmLite == TRUE) or the currentnetworkDynamic (iftergmLite == FALSE).

Usage

get_network(x, ...)## S3 method for class 'netdx'get_network(x, sim = 1, collapse = FALSE, at, ...)## S3 method for class 'netsim'get_network(x, sim = 1, network = 1, collapse = FALSE, at, ...)## S3 method for class 'netsim_dat'get_network(x, network = 1L, ...)

Arguments

x

AnEpiModel object of classnetsim,netdx, ornetsim_dat.

...

Additional arguments.

sim

Simulation number of extracted network, fornetdx andnetsim.

collapse

IfTRUE, collapse thenetworkDynamic object toa staticnetwork object at a specified time step. Applicable tonetdx objects andnetsim objects withtergmLite == FALSE.

at

Ifcollapse isTRUE, the time step at which theextracted network should be collapsed. Applicable tonetdxobjects andnetsim objects withtergmLite == FALSE.

network

Network number, fornetsim ornetsim_dat objectswith multiple overlapping networks (advanced use, and not applicabletonetdx objects).

Details

This function requires that the network object is saved during the networksimulation while running eithernetsim ornetdx.For the former, that is specified by setting thesave.networkparameter incontrol.net toTRUE. For the latter, thatis specified with thekeep.tnetwork parameter directly innetdx.

Value

Fornetdx ornetsim withtergmLite == FALSE, anetworkDynamic object (ifcollapse = FALSE) or astaticnetwork object (ifcollapse = TRUE). Fornetsim withtergmLite == TRUE ornetsim_dat withtergmLite == TRUE, anetworkLite object. Fornetsim_dat withtergmLite == FALSE, anetworkDynamic object.

Examples

# Set up network and TERGM formulanw <- network_initialize(n = 100)nw <- set_vertex_attribute(nw, "group", rep(1:2, each = 50))formation <- ~edgestarget.stats <- 50coef.diss <- dissolution_coefs(dissolution = ~offset(edges), duration = 20)# Estimate the modelest <- netest(nw, formation, target.stats, coef.diss)# Run diagnostics, saving the networkDynamic objectsdx <- netdx(est, nsteps = 10, nsims = 3, keep.tnetwork = TRUE,            verbose = FALSE)# Extract the network for simulation 2 from dx objectget_network(dx, sim = 2)# Extract and collapse the network from simulation 1 at time step 5get_network(dx, collapse = TRUE, at = 5)# Parameterize the epidemic model, and simulate itparam <- param.net(inf.prob = 0.3, inf.prob.g2 = 0.15)init <- init.net(i.num = 10, i.num.g2 = 10)control <- control.net(type = "SI", nsteps = 10, nsims = 3, verbose = FALSE)mod <- netsim(est, param, init, control)# Extract the network for simulation 2 from mod objectget_network(mod, sim = 2)## Extract and collapse the network from simulation 1 at time step 5get_network(mod, collapse = TRUE, at = 5)

Get Network Attributes from a Network Object

Description

Gets all network attributes except"mnext" from itsnetwork argument.

Usage

get_network_attributes(x)

Arguments

x

An object of classnetwork ornetworkLite.

Details

This function is used inEpiModel workflows to copy relevant networkattributes from the network object to thenetsim_dat object wheninitializingnetsim runs.

Value

Returns the named list of network attributes.

Examples

nw <- network_initialize(100)get_network_attributes(nw)

Output Network Attributes into a Character Vector

Description

Given a simulated network, outputs a character vector of vertexattributes to be used innetsim simulations.

Usage

get_network_term_attr(nw)

Arguments

nw

A network object.

Value

A character vector of vertex attributes.


Extract Network Model Parameters

Description

Extracts a list of network model parameters saved in theinitialization module.

Usage

get_nwparam(x, network = 1)

Arguments

x

Mainnetsim_dat data object used innetsim simulations.

network

Network number, for simulations with multiple networksrepresenting the population.


Extract Network Statistics from netsim or netdx Object

Description

Extracts network statistics from a network epidemic modelsimulated withnetsim or a network diagnostics objectsimulated withnetdx. Statistics can be returned eitheras a single data frame or as a list of matrices (one matrixfor each simulation).

Usage

get_nwstats(x, sim, network = 1, mode = c("data.frame", "list"))

Arguments

x

AnEpiModel object of classnetsim ornetdx.

sim

A vector of simulation numbers from the extracted object.

network

Network number, fornetsim objects with multipleoverlapping networks (advanced use, and not applicable tonetdxobjects).

mode

Either"data.frame" or"list", indicating thedesired output.

Value

A data frame or list of matrices containing the network statistics.

Examples

# Two-group Bernoulli random graph TERGMnw <- network_initialize(n = 100)nw <- set_vertex_attribute(nw, "group", rep(1:2, each = 50))formation <- ~edgestarget.stats <- 50coef.diss <- dissolution_coefs(dissolution = ~offset(edges), duration = 20)est <- netest(nw, formation, target.stats, coef.diss, verbose = FALSE)dx <- netdx(est, nsim = 3, nsteps = 10, verbose = FALSE,            nwstats.formula = ~edges + isolates)get_nwstats(dx)get_nwstats(dx, sim = 1)# SI epidemic modelparam <- param.net(inf.prob = 0.3, inf.prob.g2 = 0.15)init <- init.net(i.num = 10, i.num.g2 = 10)control <- control.net(type = "SI", nsteps = 10, nsims = 3,                       nwstats.formula = ~edges + meandeg + degree(0:5),                       verbose = FALSE)mod <- netsim(est, param, init, control)# Extract the network statistics from all or sets of simulationsget_nwstats(mod)get_nwstats(mod, sim = 2)get_nwstats(mod, sim = c(1, 3))# On the fly summary statssummary(get_nwstats(mod))colMeans(get_nwstats(mod))

Extract the Parameter Set from Network Simulations

Description

Extract the Parameter Set from Network Simulations

Usage

get_param_set(sims)

Arguments

sims

AnEpiModel object of classnetsim.

Value

Adata.frame with one row per simulation and one column perparameter or parameter element where the parameters are of size > 1.

Output Format

The outputteddata.frame has one row per simulation and the columnscorrespond to the parameters used in this simulation.

The column name will match the parameter name if it is a size 1 parameter orif the parameter is of size > 1, there will be N columns (with N being thesize of the parameter) namedparameter.name_1,parameter.name_2, ...,parameter.name_N.

Examples

# Setup networknw <- network_initialize(n = 50)est <- netest(  nw, formation = ~edges,  target.stats = c(25),  coef.diss = dissolution_coefs(~offset(edges), 10, 0),  verbose = FALSE)init <- init.net(i.num = 10)n <- 5related.param <- data.frame(  dummy.param = rbeta(n, 1, 2)) my.randoms <- list(   act.rate = param_random(c(0.25, 0.5, 0.75)),   dummy.param = function() rbeta(1, 1, 2),   dummy.strat.param = function() c(     rnorm(1, 0, 10),     rnorm(1, 10, 1)   ) )param <- param.net(  inf.prob = 0.3,  dummy = c(0, 1, 2),  random.params = my.randoms)control <- control.net(type = "SI", nsims = 3, nsteps = 5, verbose = FALSE)mod <- netsim(est, param, init, control)get_param_set(mod)

Return the Historical Contacts (Partners) of a Set of Index Nodes

Description

From a full cumulative edgelist that contains the history of contacts (both persistent andone-time), this function returns a data frame containing details of the index (head) and partner(tail) nodes, along with start and stop time steps for the partnership and the network location.

Usage

get_partners(  dat,  index_posit_ids,  networks = NULL,  truncate = Inf,  only.active.nodes = FALSE)

Arguments

dat

Mainnetsim_dat object containing anetworkDynamicobject and other initialization information passed fromnetsim.

index_posit_ids

The positional IDs of the indexes of interest.

networks

Numerical indexes of the networks to extract the partnerships from. (May be > 1for models with multi-layer networks.) IfNULL, extract from all networks.

truncate

After how many time steps a partnership that is no longeractive should be removed from the output.

only.active.nodes

IfTRUE, then inactive (e.g., deceased) partners will be removed fromthe output.

Details

Note thatget_partners takes as input the positional IDs of the indexes of interest but returnsthe unique IDs. That is by design, because whileget_partners would be expected to be calledfor active nodes, some partners (contacts) of nodes may be inactive in the network history.Therefore, both index and partner IDs are returned as unique IDs for consistency. To convertbetween a positional to a unique ID, you may useget_posit_ids; to convert between aunique ID to a positional ID, you may useget_unique_ids.

Value

Adata.frame with 5 columns:


Extract Network Simulations

Description

Subsets the entirenetsim object to a subset ofsimulations, essentially functioning like a reverse ofmerge.

Usage

get_sims(x, sims, var)

Arguments

x

An object of classnetsim.

sims

Either a numeric vector of simulation numbers to retain in theoutput object, or"mean", which selects the one simulation withthe value of the variable specified invar closest to the meanofvar across all simulations.

var

A character vector of variables to retain fromx ifsims is a numeric vector, or a single variable name forselecting the average simulation from the set ifsims = "mean".

Value

An updated object of classnetsim containing only thesimulations specified insims and the variables specified invar.

Examples

# Network model estimationnw <- network_initialize(n = 100)formation <- ~edgestarget.stats <- 50coef.diss <- dissolution_coefs(dissolution = ~offset(edges), duration = 20)est1 <- netest(nw, formation, target.stats, coef.diss, verbose = FALSE)# Epidemic modelparam <- param.net(inf.prob = 0.3)init <- init.net(i.num = 10)control <- control.net(type = "SI", nsteps = 10, nsims = 3, verbose.int = 0)mod1 <- netsim(est1, param, init, control)# Get sim 2s.g2 <- get_sims(mod1, sims = 2)# Get sims 2 and 3 and keep only a subset of variabless.g2.small <- get_sims(mod1, sims = 2:3, var = c("i.num", "si.flow"))# Extract the mean simulation for the variable i.numsim.mean <- get_sims(mod1, sims = "mean", var = "i.num")

Return an adjacency list of subnets

Description

Return an adjacency list of subnets

Usage

get_subnet_adj_list(adj_list)

Arguments

adj_list

A normal adjacency list

Details

A graph with 4 components: 1, 2, 3, 4, and 5 and 6, 7, 8 would yield a listlike so:1: 2, 3, 42: 13: 14: 15: numeric(0)6: 7, 87: 6,8: 6

This format speeds up the construction of reachable sets on dense networks

Value

An adjacency list where only the first node of a subnet contains thesubnet and all other contain only the first node


Get Vertex Attribute on Network Object

Description

Gets a vertex attribute from an object of classnetwork.This functions simplifies the related function in thenetwork package.

Usage

get_vertex_attribute(x, attrname)

Arguments

x

An object of class network.

attrname

The name of the attribute to get.

Details

This function is used inEpiModel workflows to query vertexattributes on an initialized empty network object (seenetwork_initialize).

Value

Returns an object of classnetwork.

Examples

nw <- network_initialize(100)nw <- set_vertex_attribute(nw, "age", runif(100, 15, 65))get_vertex_attribute(nw, "age")

Stochastic Individual Contact Models

Description

Simulates stochastic individual contact epidemic models forinfectious disease.

Usage

icm(param, init, control)

Arguments

param

Model parameters, as an object of classparam.icm.

init

Initial conditions, as an object of classinit.icm.

control

Control settings, as an object of classcontrol.icm.

Details

Individual contact models are intended to be the stochastic microsimulationanalogs to deterministic compartmental models. ICMs simulate disease spreadon individual agents in discrete time as a function of processes withstochastic variation. The stochasticity is inherent in all transitionprocesses: infection, recovery, and demographics.

Theicm function performs modeling of both the base model typesand original models. Base model types include one-group and two-groupmodels with disease types for Susceptible-Infected (SI),Susceptible-Infected-Recovered (SIR), and Susceptible-Infected-Susceptible(SIS). Original models may be built by writing new process modules thateither take the place of existing modules (for example, disease recovery),or supplement the set of existing processes with a new one contained in anoriginal module.

Value

A list of classicm with the following elements:

See Also

Extract the model results withas.data.frame.icm.Summarize the time-specific model results withsummary.icm.Plot the model results withplot.icm. Plot a compartment flowdiagram withcomp_plot.

Examples

## Not run: ## Example 1: SI Modelparam <- param.icm(inf.prob = 0.2, act.rate = 0.25)init <- init.icm(s.num = 500, i.num = 1)control <- control.icm(type = "SI", nsteps = 500, nsims = 10)mod1 <- icm(param, init, control)mod1plot(mod1)## Example 2: SIR Modelparam <- param.icm(inf.prob = 0.2, act.rate = 0.25, rec.rate = 1/50)init <- init.icm(s.num = 500, i.num = 1, r.num = 0)control <- control.icm(type = "SIR", nsteps = 500, nsims = 10)mod2 <- icm(param, init, control)mod2plot(mod2)## Example 3: SIS Modelparam <- param.icm(inf.prob = 0.2, act.rate = 0.25, rec.rate = 1/50)init <- init.icm(s.num = 500, i.num = 1)control <- control.icm(type = "SIS", nsteps = 500, nsims = 10)mod3 <- icm(param, init, control)mod3plot(mod3)## Example 4: SI Model with Vital Dynamics (Two-Group)param <- param.icm(inf.prob = 0.4,  inf.prob.g2 = 0.1,                   act.rate = 0.25, balance = "g1",                   a.rate = 1/100, a.rate.g2 = NA,                   ds.rate = 1/100, ds.rate.g2 = 1/100,                   di.rate = 1/50, di.rate.g2 = 1/50)init <- init.icm(s.num = 500, i.num = 1,                 s.num.g2 = 500, i.num.g2 = 0)control <- control.icm(type = "SI", nsteps = 500, nsims = 10)mod4 <- icm(param, init, control)mod4plot(mod4)## End(Not run)

Group Numbers for Two-Group Network

Description

Outputs group numbers given ID numbers for a two-group network.

Usage

idgroup(nw, ids)

Arguments

nw

Object of classnetwork ornetworkDynamic.

ids

Vector of ID numbers for which the group numbershould be returned.

Value

A vector containing the group number for each of the specified nodes.

Examples

nw <- network_initialize(n = 10)nw <- set_vertex_attribute(nw, "group", rep(1:2, each = 5))idgroup(nw)idgroup(nw, ids = c(3, 6))

Increment the Current Timestep

Description

This function adds 1 to the timestep counter stored in thenetsim_dat main list object.

Usage

increment_timestep(dat)

Arguments

dat

Mainnetsim_dat object containing anetworkDynamicobject and other initialization information passed fromnetsim.

Value

The updatednetsim_dat main list object.

Mutability

This DOES NOT modify thenetsim_dat object in place. The result mustbe assigned back todat in order to be registered:dat <- increment_timestep(dat).


Primary Infection Module for netsim

Description

This function simulates the main infection process given thecurrent state of the partnerships and disease in the system.

Usage

infection.2g.net(dat, at)

Arguments

dat

Mainnetsim_dat object containing anetworkDynamicobject and other initialization information passed fromnetsim.

at

Current time step.

Details

The main steps in this infection module are as follows:

  1. Get IDs for current infected and susceptibles given the currentdisease status.

  2. Calldiscord_edgelist to get the current discordantedgelist given step 1.

  3. Determine the transmission rates (e.g., as a function of group).

  4. Pull the number of acts per partnership in a time step from theact.rate parameter.

  5. Calculate the final transmission probabilities given the transmissionrates and act rates.

  6. Randomly transmit on the discordant edgelist.

  7. Conduct bookkeeping for new infections to update status on the nodesand calculate disease incidence.

Value

The updatednetsim_dat main list object.

See Also

discord_edgelist is used withininfection.netto obtain a discordant edgelist.


Primary Infection Module for icm

Description

This function simulates the main infection process given thecurrent state of the actors in the system.

Usage

infection.icm(dat, at)

Arguments

dat

Mainicm_dat class data object passed throughicmsimulations.

at

Current time step.

Value

The updatedicm_dat class main data object.


Primary Infection Module for icm

Description

This function simulates the main infection process given thecurrent state of the actors in the system.

Usage

infection.icm.bip(dat, at)

Arguments

dat

Mainicm_dat class data object passed throughicmsimulations.

at

Current time step.

Value

The updatedicm_dat class main data object.


Primary Infection Module for netsim

Description

This function simulates the main infection process given thecurrent state of the partnerships and disease in the system.

Usage

infection.net(dat, at)

Arguments

dat

Mainnetsim_dat object containing anetworkDynamicobject and other initialization information passed fromnetsim.

at

Current time step.

Details

The main steps in this infection module are as follows:

  1. Get IDs for current infected and susceptible nodes given the currentdisease status.

  2. Calldiscord_edgelist to get the current discordantedgelist given step 1.

  3. Determine the transmission rates (e.g., as a function of group).

  4. Pull the number of acts per partnership in a time step from theact.rate parameter.

  5. Calculate the final transmission probabilities given the transmissionrates and act rates.

  6. Randomly transmit on the discordant edgelist.

  7. Conduct bookkeeping for new infections to update status on the nodesand calculate disease incidence.

Value

The updatednetsim_dat main list object.

See Also

discord_edgelist is used withininfection.netto obtain a discordant edgelist.


Initial Conditions for Deterministic Compartmental Models

Description

Sets the initial conditions for deterministic compartmentalmodels simulated withdcm.

Usage

init.dcm(s.num, i.num, r.num, s.num.g2, i.num.g2, r.num.g2, ...)

Arguments

s.num

Number of initial susceptible persons. For two-group models,this is the number of initial group 1 susceptible persons.

i.num

Number of initial infected persons. For two-group models, thisis the number of initial group 1 infected persons.

r.num

Number of initial recovered persons. For two-group models, thisis the number of initial group 1 recovered persons. This parameter isonly used for theSIR model type.

s.num.g2

Number of initial susceptible persons in group 2. Thisparameter is only used for two-group models.

i.num.g2

Number of initial infected persons in group 2. This parameteris only used for two-group models.

r.num.g2

Number of initial recovered persons in group 2. Thisparameter is only used for two-groupSIR models.

...

Additional initial conditions passed to model.

Details

The initial conditions for a model solved withdcm should beinput into theinit.dcm function. This function handles initialconditions for both base model types and original models.

Original models may use the parameter names listed as arguments here, a newset of names, or a combination of both. With new models, initial conditionsmust be input in the same order that the solved derivatives from the modelare output.

Value

AnEpiModel object of classinit.dcm.

See Also

Useparam.dcm to specify model parameters andcontrol.dcm to specify the control settings. Run theparameterized model withdcm.


Initial Conditions for Stochastic Individual Contact Models

Description

Sets the initial conditions for stochastic individual contactmodels simulated withicm.

Usage

init.icm(s.num, i.num, r.num, s.num.g2, i.num.g2, r.num.g2, ...)

Arguments

s.num

Number of initial susceptible persons. For two-group models,this is the number of initial group 1 susceptible persons.

i.num

Number of initial infected persons. For two-group models, thisis the number of initial group 1 infected persons.

r.num

Number of initial recovered persons. For two-group models, thisis the number of initial group 1 recovered persons. This parameter isonly used for theSIR model type.

s.num.g2

Number of initial susceptible persons in group 2. Thisparameter is only used for two-group models.

i.num.g2

Number of initial infected persons in group 2. This parameteris only used for two-group models.

r.num.g2

Number of initial recovered persons in group 2. Thisparameter is only used for two-groupSIR models.

...

Additional initial conditions passed to model.

Details

The initial conditions for a model solved withicm should beinput into theinit.icm function. This function handles initialconditions for both base models and original models using new modules.

Value

AnEpiModel object of classinit.icm.

See Also

Useparam.icm to specify model parameters andcontrol.icm to specify the control settings. Run theparameterized model withicm.


Initial Conditions for Stochastic Network Models

Description

Sets the initial conditions for stochastic network modelssimulated withnetsim.

Usage

init.net(i.num, r.num, i.num.g2, r.num.g2, status.vector, infTime.vector, ...)

Arguments

i.num

Number of initial infected persons. For two-group models, thisis the number of initial group 1 infected persons.

r.num

Number of initial recovered persons. For two-group models, thisis the number of initial group 1 recovered persons. This parameter isonly used for theSIR model type.

i.num.g2

Number of initial infected persons in group 2. This parameteris only used for two-group models.

r.num.g2

Number of initial recovered persons in group 2. Thisparameter is only used for two-groupSIR models.

status.vector

A vector of length equal to the size of the inputnetwork, containing the status of each node. Setting status hereoverrides any inputs passed in the.num arguments.

infTime.vector

A vector of length equal to the size of the inputnetwork, containing the (historical) time of infection for each ofthose nodes with a current status of"i". Can only be used ifstatus.vector is used, and must containNA values forany nodes whose status is not"i".

...

Additional initial conditions passed to model.

Details

The initial conditions for a model solved withnetsim should beinput into theinit.net function. This function handles initialconditions for both base models and new modules. For an overview ofspecifying initial conditions across a variety of base network models,consult theNetwork Modeling for Epidemicstutorials.

Value

AnEpiModel object of classinit.net.

See Also

Useparam.net to specify model parameters andcontrol.net to specify the control settings. Run theparameterized model withnetsim.

Examples

# Example of using status.vector and infTime.vector togethern <- 100status <- sample(c("s", "i"), size = n, replace = TRUE, prob = c(0.8, 0.2))infTime <- rep(NA, n)infTime[which(status == "i")] <- -rgeom(sum(status == "i"), prob = 0.01) + 2init.net(status.vector = status, infTime.vector = infTime)

Network Data and Stats Initialization

Description

This function initializes the network data and stats on the mainnetsim_dat class data object.

Usage

init_nets(dat, x)

Arguments

dat

A main data object of classnetsim_dat obtained fromcreate_dat_object, including thecontrolargument.

x

Either a fitted network model object of classnetest, or alist of such objects.

Value

Anetsim_dat class main data object with network data andstats initialized.


Disease Status Initialization Module for icm

Description

This function sets the initial disease status on thenetwork given the specified initial conditions.

Usage

init_status.icm(dat)

Arguments

dat

Mainicm_dat class data object passed throughicmsimulations.

Value

The updatedicm_dat class main data object.

See Also

This is an initialization module foricm.


Disease Status Initialization Module for netsim

Description

This function sets the initial disease status on thenetwork given the specified initial conditions.

Usage

init_status.net(dat)

Arguments

dat

Mainnetsim_dat object containing anetworkDynamicobject and other initialization information passed fromnetsim.

Details

This internal function sets, either randomly or deterministically, the nodesthat are infected att_1, the starting time of network simulations. Ifthe number to be initially infected is passed, this function sets the initialnumber infected based on the number specified, either as a set of randomdraws from a binomial distribution or as the exact number specified. Ineither case, the specific nodes infected are a random sample from thenetwork. In contrast, a set of specific nodes may be infected by passing avector containing the status of each node tonetsim.

For the initially infected nodes, this module sets the time of infection ast_1, the starting time of network simulations. For models with vitaldynamics, the infection time for those initially infected nodes is a randomdraw from an exponential distribution with the rate parameter defined by thedi.rate argument. For models without vital dynamics, the infectiontime is a random draw from a uniform distribution of integers with a minimumof 1 and a maximum of the number of time steps in the model. In both cases,to set the infection times to be in the past, these times are multiplied by-1, and 2 is added to allow for possible infection times up until step 2,when the disease simulation time loop starts.

Value

The updatednetsim_dat main list object.

See Also

This is an initialization module fornetsim.


Initialization: icm Module

Description

This function initializes the mainicm_dat class dataobject, and simulates disease status and other attributes.

Usage

initialize.icm(param, init, control)

Arguments

param

AnEpiModel object of classparam.icm.

init

AnEpiModel object of classinit.icm.

control

AnEpiModel object of classcontrol.icm.

Value

The updatedicm_dat class main data object.


Initialization: netsim Module

Description

This function initializes the mainnetsim_dat class dataobject on which data are stored, simulates the initial state ofthe networks, and simulates disease status and other attributes.

Usage

initialize.net(x, param, init, control, s)

Arguments

x

Ifcontrol$start == 1, either a fitted network model objectof classnetest or a list of such objects. Ifcontrol$start > 1, an object of classnetsim. Whenmultiple networks are used, the node sets (including network sizeand nodal attributes) are assumed to be the same for all networks.

param

AnEpiModel object of classparam.net.

init

AnEpiModel object of classinit.net.

control

AnEpiModel object of classcontrol.net.

s

Simulation number, used for restarting dependent simulations.

Details

When re-initializing a simulation, thenetsim object passedtoinitialize.net must contain the elementsparam,nwparam,epi,coef.form, andnum.nw.

Value

Anetsim_dat class main data object.


Extract Transmissions Matrix from Network Epidemic Model

Description

Extracts the matrix of transmission data for each transmissionevent that occurred within a network epidemic model.

Usage

is.transmat(x)get_transmat(x, sim = 1, deduplicate = TRUE)

Arguments

x

AnEpiModel object of classnetsim.

sim

Simulation number of extracted network.

deduplicate

IfTRUE, randomly select one transmission event inthe case that multiple events current per newly infected agent withina time step.

Value

A data frame with the following standard columns:

Examples

## Simulate SI epidemic on two-group Bernoulli random graphnw <- network_initialize(n = 100)nw <- set_vertex_attribute(nw, "group", rep(1:2, each = 50))formation <- ~edgestarget.stats <- 50coef.diss <- dissolution_coefs(dissolution = ~offset(edges), duration = 20)est <- netest(nw, formation, target.stats, coef.diss, verbose = FALSE)param <- param.net(inf.prob = 0.3, inf.prob.g2 = 0.15)init <- init.net(i.num = 10, i.num.g2 = 10)control <- control.net(type = "SI", nsteps = 10, nsims = 3, verbose = FALSE)mod <- netsim(est, param, init, control)## Extract the transmission matrix from simulation 2get_transmat(mod, sim = 2)

Are These Nodes Active (Positional IDs)

Description

Are These Nodes Active (Positional IDs)

Usage

is_active_posit_ids(dat, posit_ids)

Arguments

dat

Mainnetsim_dat object containing anetworkDynamicobject and other initialization information passed fromnetsim.

posit_ids

A vector of node positional identifiers.

Value

A logical vector with TRUE if the node is still active and FALSEotherwise.


Are These Nodes Active (Unique IDs)

Description

Are These Nodes Active (Unique IDs)

Usage

is_active_unique_ids(dat, unique_ids)

Arguments

dat

Mainnetsim_dat object containing anetworkDynamicobject and other initialization information passed fromnetsim.

unique_ids

A vector of node unique identifiers.

Value

A logical vector with TRUE if the node is still active and FALSEotherwise.


Populate the Module List After the Initialization Module is run

Description

Populate the Module List After the Initialization Module is run

Usage

make_module_list(dat)

Arguments

dat

Mainnetsim_dat object containing anetworkDynamicobject and other initialization information passed fromnetsim.

Value

The updatednetsim_dat main list object.


Create a Summary Table of Simulation Statistics

Description

Create a Summary Table of Simulation Statistics

Usage

make_stats_table(stats, targets)

Arguments

stats

A list of simulated statistics matrices, of length equal to thenumber of simulations performed. Each matrix should have one row for eachsimulated network ifdynamic == FALSE, one row for each time stepifdynamic == TRUE, and one column for each statistic. The columnsshould be named for the statistics they correspond to, with all matriceshaving the same statistics, in the same order. Each matrix may have anattr-style attribute named"ess" attached, giving theeffective sample sizes for the columns of the matrix; if this attribute isNULL, then the effective sample sizes will be computed within thecall tomake_stats_table.

targets

A vector of target values for the statistics instats.May be named (in which case targets will be matched to statistics based oncolumn names in matrices instats) or unnamed (in which casetargets will be matched to statistics based on position, and the number oftargets must equal the number of columns).

Value

Adata.frame summarizing the simulated statistics.


Write Out Test Progress to Console

Description

Writes the name of a test and... to console to show testprogress.

Usage

mcat(test)

Arguments

test

Character string with the name of a test.


Merge Data across Stochastic Individual Contact Model Simulations

Description

Merges epidemiological data from two independent simulations ofstochastic individual contact models fromicm.

Usage

## S3 method for class 'icm'merge(x, y, ...)

Arguments

x

AnEpiModel object of classicm.

y

AnotherEpiModel object of classicm, with theidentical model parameterization asx.

...

Additional merge arguments (not used).

Details

This merge function combines the results of two independent simulations oficm class models, simulated under separate function calls. Themodel parameterization between the two calls must be exactly the same, exceptfor the number of simulations in each call. This allows for manualparallelization of model simulations.

This merge function does not work the same as the default merge, which allowsfor a combined object where the structure differs between the input elements.Instead, the function checks that objects are identical in modelparameterization in every respect (except number of simulations) and bindsthe results.

Value

AnEpiModel object of classicm containing thedata from bothx andy.

Examples

param <- param.icm(inf.prob = 0.2, act.rate = 0.8)init <- init.icm(s.num = 1000, i.num = 100)control <- control.icm(type = "SI", nsteps = 10,                       nsims = 3, verbose = FALSE)x <- icm(param, init, control)control <- control.icm(type = "SI", nsteps = 10,                       nsims = 1, verbose = FALSE)y <- icm(param, init, control)z <- merge(x, y)# Examine separate and merged dataas.data.frame(x)as.data.frame(y)as.data.frame(z)

Merge Model Simulations across netsim Objects

Description

Merges epidemiological data from two independent simulations ofstochastic network models fromnetsim.

Usage

## S3 method for class 'netsim'merge(  x,  y,  keep.transmat = TRUE,  keep.network = TRUE,  keep.nwstats = TRUE,  keep.other = TRUE,  param.error = TRUE,  keep.diss.stats = TRUE,  ...)

Arguments

x

AnEpiModel object of classnetsim.

y

AnotherEpiModel object of classnetsim,with the identical model parameterization asx.

keep.transmat

IfTRUE, keep the transmission matrices from theoriginalx andy elements. Note: transmission matricesonly saved when (save.transmat == TRUE).

keep.network

IfTRUE, keep thenetworkDynamic objectsfrom the originalx andy elements. Note: networkonly saved when (tergmLite == FALSE).

keep.nwstats

IfTRUE, keep the network statistics (as set bythenwstats.formula parameter incontrol.netsim) fromthe originalx andy elements.

keep.other

IfTRUE, keep the other simulation elements (as setby thesave.other parameter incontrol.netsim) from theoriginalx andy elements.

param.error

IfTRUE, ifx andy have differentparams (inparam.net) or controls (passed incontrol.net) an error will prevent the merge. UseFALSE to override that check.

keep.diss.stats

IfTRUE, keepdiss.stats from theoriginalx andy objects.

...

Additional merge arguments (not currently used).

Details

This merge function combines the results of two independent simulations ofnetsim class models, simulated under separate function calls.The model parameterization between the two calls must be exactly the same,except for the number of simulations in each call. This allows for manualparallelization of model simulations.

This merge function does not work the same as the default merge, which allowsfor a combined object where the structure differs between the input elements.Instead, the function checks that objects are identical in modelparameterization in every respect (except number of simulations) and bindsthe results.

Value

AnEpiModel object of classnetsim containingthe data from bothx andy.

Examples

# Network modelnw <- network_initialize(n = 100)coef.diss <- dissolution_coefs(dissolution = ~offset(edges), duration = 10)est <- netest(nw, formation = ~edges, target.stats = 25,              coef.diss = coef.diss, verbose = FALSE)# Epidemic modelsparam <- param.net(inf.prob = 1)init <- init.net(i.num = 1)control <- control.net(type = "SI", nsteps = 20, nsims = 2,                       save.nwstats = TRUE,                       nwstats.formula = ~edges + degree(0),                       verbose = FALSE)x <- netsim(est, param, init, control)y <- netsim(est, param, init, control)# Mergingz <- merge(x, y)# Examine separate and merged dataas.data.frame(x)as.data.frame(y)as.data.frame(z)

Modules for Stochastic Individual Contact Models

Description

Stochastic individual contact models of infectious disease simulate epidemicsin which contacts between individuals are instantaneous events in discretetime. They are intended to be the stochastic microsimulation analogs todeterministic compartmental models.

Theicm function handles both the simulation tasks. Within thisfunction are a series of modules that initialize the simulation and thensimulate new infections, recoveries, and vital dynamics at each time step. Amodule also handles the basic bookkeeping calculations for diseaseprevalence.

Writing original ICMs will require modifying the existing modules oradding new modules to the workflow inicm. The existing modulesmay be used as a template for replacement or new modules.

This help page presents a brief overview of the module functions in the orderin which they are used withinicm, in order to help guide usersin writing their own module functions. These module functions are not shownon the help index since they are not called directly by the end-user. Tounderstand these functions in more detail, review the separate help pageslisted below.

Initialization Module

This function sets up agent attributes, like disease status, on the networkat the starting time step of disease simulation,t_1. Formultiple-simulation function calls, these are reset at the beginning of eachsimulation.

Disease Status Modification Modules

The main disease simulation occurs at each time step given the current stateof the population at that step. Infection of agents is simulated as afunction of disease parameters and population composition. Recovery of agentsis likewise simulated with respect to infected nodes. These functions alsoanalyze the flows for summary measures such as disease incidence.

Demographic Modules

Vital dynamics such as arrival and departure processes are simulated at eachtime step to update entries into and exits from the population. These areused in open-population ICMs.

Bookkeeping Module

Simulations require bookkeeping at each time step to calculate thesummary epidemiological statistics used in the model output analysis.


Modules for Stochastic Network Models

Description

Stochastic network models of infectious disease in EpiModel requirestatistical modeling of networks, simulation of those networks forwardthrough time, and simulation of epidemic dynamics on top of those evolvingnetworks. Thenetsim function handles both the network andepidemic simulation tasks. Within this function are a series of modules thatinitialize the simulation and then simulate new infections, recoveries, anddemographics on the network. Modules also handle the resimulation of thenetwork and some bookkeeping calculations for disease prevalence.

Writing original network models that expand upon our "base" model set willrequire modifying the existing modules or adding new modules to the workflowinnetsim. The existing modules may be used as a template forreplacement or new modules.

This help page provides an orientation to these module functions, in theorder in which they are used withinnetsim, to help guide usersin writing their own functions. These module functions are not shownon the help index since they are not called directly by the end-user. Tounderstand these functions in more detail, review the separate help pageslisted below.

Initialization Module

This function sets up nodal attributes, like disease status, on the networkat the starting time step of disease simulation,t_1. Formultiple-simulation function calls, these are reset at the beginning of eachindividual simulation.

Disease Status Modification Modules

The main disease simulation occurs at each time step given the current stateof the network at that step. Infection of nodes is simulated as a function ofattributes of the nodes and the edges. Recovery of nodes is likewisesimulated as a function of nodal attributes of those infected nodes. Thesefunctions also calculate summary flow measures such as disease incidence.

Demographic Modules

Demographics such as arrival and departure processes are simulated at eachtime step to update entries into and exits from the network. These are usedin epidemic models with network feedback, in which the network is resimulatedat each time step to account for the nodal changes affecting the edges.

Network Resimulation Module

In dependent network models, the network object is resimulated at each timestep to account for changes in the size of the network (changed throughentries and exits), and the disease status of the nodes.

Bookkeeping Module

Network simulations require bookkeeping at each time step to calculate thesummary epidemiological statistics used in the model output analysis.

One- & Two-Group Modules

If epidemictype is supplied withincontrol.net,EpiModel defaults each of the base epidemic and demographic modules describedabove (arrivals.FUN, departures.FUN, infection.FUN, recovery.FUN) to thecorrect .net function based on variables passed toparam.net(e.g. num.g2, denoting population size of group two, would select thetwo-group variants of the aforementioned modules). Two-group modules aredenoted by a .2g affix (e.g., recovery.2g.net)


Specify Controls by Network

Description

This utility function allows specification of certainnetsim controls to vary by network. Thenetsim control arguments currently supportingmultilayer specifications arenwstats.formula,set.control.ergm,set.control.tergm, andtergmLite.track.duration.

Usage

multilayer(...)

Arguments

...

control arguments to apply to each network, with the index of thenetwork corresponding to the index of the control argument

Value

an object of classmultilayer containing the specifiedcontrol arguments


Add New Epidemiology Variables

Description

Inspired bydplyr::mutate,mutate_epi adds newvariables to the epidemiological and related variables withinsimulated model objects of any class inEpiModel.

Usage

mutate_epi(x, ...)

Arguments

x

AnEpiModel object of classdcm,icm, ornetsim.

...

Name-value pairs of expressions (see examples below).

Value

The updatedEpiModel object of classdcm,icm,ornetsim.

Examples

# DCM exampleparam <- param.dcm(inf.prob = 0.2, act.rate = 0.25)init <- init.dcm(s.num = 500, i.num = 1)control <- control.dcm(type = "SI", nsteps = 500)mod1 <- dcm(param, init, control)mod1 <- mutate_epi(mod1, prev = i.num/num)plot(mod1, y = "prev")# Network model examplenw <- network_initialize(n = 100)nw <- set_vertex_attribute(nw, "group", rep(1:2, each = 50))formation <- ~edgestarget.stats <- 50coef.diss <- dissolution_coefs(dissolution = ~offset(edges), duration = 20)est1 <- netest(nw, formation, target.stats, coef.diss, verbose = FALSE)param <- param.net(inf.prob = 0.3, inf.prob.g2 = 0.15)init <- init.net(i.num = 1, i.num.g2 = 0)control <- control.net(type = "SI", nsteps = 10, nsims = 3,                       verbose = FALSE)mod1 <- netsim(est1, param, init, control)mod1# Add the prevalences to the datasetmod1 <- mutate_epi(mod1, i.prev = i.num / num,                         i.prev.g2 = i.num.g2 / num.g2)plot(mod1, y = c("i.prev", "i.prev.g2"), qnts = 0.5, legend = TRUE)# Add incidence rate per 100 person years (assume time step = 1 week)mod1 <- mutate_epi(mod1, ir100 = 5200*(si.flow + si.flow.g2) /                                      (s.num + s.num.g2))as.data.frame(mod1)as.data.frame(mod1, out = "mean")

Functions to Access and Edit the Main netsim_dat Object in Network Models

Description

Theseget_,set_,append_, andadd_functions allow a safe and efficient way to retrieve and mutatethe mainnetsim_dat class object of network models(typical variable namedat).

Usage

get_attr_list(dat, item = NULL)get_attr(dat, item, posit_ids = NULL, override.null.error = FALSE)add_attr(dat, item)set_attr(dat, item, value, posit_ids = NULL, override.length.check = FALSE)append_attr(dat, item, value, n.new)remove_node_attr(dat, posit_ids)get_epi_list(dat, item = NULL)get_epi(dat, item, at = NULL, override.null.error = FALSE)add_epi(dat, item)set_epi(dat, item, at, value)get_param_list(dat, item = NULL)get_param(dat, item, override.null.error = FALSE)add_param(dat, item)set_param(dat, item, value)get_control_list(dat, item = NULL)get_control(dat, item, override.null.error = FALSE)get_network_control(dat, network, item, override.null.error = FALSE)add_control(dat, item)set_control(dat, item, value)get_init_list(dat, item = NULL)get_init(dat, item, override.null.error = FALSE)add_init(dat, item)set_init(dat, item, value)append_core_attr(dat, at, n.new)

Arguments

dat

Mainnetsim_dat object containing anetworkDynamicobject and other initialization information passed fromnetsim.

item

A character vector containing the name of the element to access(forget_ functions), create (foradd_ functions), oredit (forset_ andappend_ functions). Can be of length> 1 forget_*_list functions.

posit_ids

Forset_attr andget_attr, a numeric vector ofposit_ids to subset the desireditem.

override.null.error

If TRUE,get_ will return NULL if theitem does not exist instead of throwing an error.(default = FALSE).

value

New value to be attributed in theset_ andappend_functions.

override.length.check

If TRUE,set_attr allows the modificationof theitem size. (default = FALSE).

n.new

Forappend_core_attr, the number of new nodes to initiatewith core attributes; forappend_attr, the number of newelements to append at the end ofitem.

at

Forget_epi, the timestep at which to access the specifieditem; forset_epi, the timestep at which to add the newvalue for the epi outputitem; forappend_core_attr, thecurrent time step.

network

index of network for which to get control

Value

A vector or a list of vectors forget_ functions; the mainlist object forset_,append_, andadd_functions.

Core Attribute

Theappend_core_attr function initializes the attributes necessary forEpiModel to work (the four core attributes are: "active", "unique_id","entrTime", and "exitTime"). These attributes are used in the initializationphase of the simulation, to create the nodes (seeinitialize.net); and also used when adding nodes during thesimulation (seearrivals.net).

Mutability

Theset_,append_, andadd_ functions DO NOT modify thenetsim_dat object in place. The result must be assigned back todat in order to be registered:dat <- set_*(dat, item, value).

set_ andappend_ vsadd_

Theset_ andappend_ functions edit a pre-existing element orcreate a new one if it does not exist already by calling theadd_functions internally.

Examples

dat <- create_dat_object(control = list(nsteps = 150))dat <- append_core_attr(dat, 1, 100)dat <- add_attr(dat, "age")dat <- set_attr(dat, "age", runif(100))dat <- set_attr(dat, "status", rbinom(100, 1, 0.9))dat <- append_attr(dat, "status", 1, 10)dat <- append_attr(dat, "age", NA, 10)get_attr_list(dat)get_attr_list(dat, c("age", "active"))get_attr(dat, "status")get_attr(dat, "status", c(1, 4))dat <- add_epi(dat, "i.num")dat <- set_epi(dat, "i.num", 150, 10)dat <- set_epi(dat, "s.num", 150, 90)get_epi_list(dat)get_epi_list(dat, c("i.num", "s.num"))get_epi(dat, "i.num")get_epi(dat, "i.num", c(1, 4))dat <- add_param(dat, "x")dat <- set_param(dat, "x", 0.4)dat <- set_param(dat, "y", 0.8)get_param_list(dat)get_param_list(dat, c("x", "y"))get_param(dat, "x")dat <- add_init(dat, "x")dat <- set_init(dat, "x", 0.4)dat <- set_init(dat, "y", 0.8)get_init_list(dat)get_init_list(dat, c("x", "y"))get_init(dat, "x")dat <- add_control(dat, "x")dat <- set_control(dat, "x", 0.4)dat <- set_control(dat, "y", 0.8)get_control_list(dat)get_control_list(dat, c("x", "y"))get_control(dat, "x")

Dynamic Network Model Diagnostics

Description

Runs dynamic diagnostics on an ERGM/STERGM estimated withnetest.

Usage

netdx(  x,  nsims = 1,  dynamic = TRUE,  nsteps,  nwstats.formula = "formation",  set.control.ergm = control.simulate.formula(),  set.control.tergm = control.simulate.formula.tergm(),  sequential = TRUE,  keep.tedgelist = FALSE,  keep.tnetwork = FALSE,  verbose = TRUE,  ncores = 1,  skip.dissolution = FALSE)

Arguments

x

AnEpiModel object of classnetest.

nsims

Number of simulations to run.

dynamic

IfTRUE, runs dynamic diagnostics. IfFALSE andthenetest object was fit with the Edges Dissolutionapproximation method, simulates from the static ERGM fit.

nsteps

Number of time steps per simulation (dynamic simulations only).

nwstats.formula

A right-hand sided ERGM formula with the networkstatistics of interest. The default is the formation formula of thenetwork model contained inx.

set.control.ergm

Control arguments passed toergm'ssimulate_formula.network (see details).

set.control.tergm

Control arguments passed totergm'ssimulate_formula.network (see details).

sequential

For static diagnostics (dynamic=FALSE): ifFALSE, each of thensims simulated Markov chains beginsat the initial network; ifTRUE, the end of one simulation isused as the start of the next.

keep.tedgelist

IfTRUE, keep the timed edgelist generated fromthe dynamic simulations. Returned in the form of a list of matrices,with one entry per simulation. Accessible at⁠$edgelist⁠.

keep.tnetwork

IfTRUE, keep the full networkDynamic objectsfrom the dynamic simulations. Returned in the form of a list of nDobjects, with one entry per simulation. Accessible at⁠$network⁠.

verbose

IfTRUE, print progress to the console.

ncores

Number of processor cores to run multiple simulationson, using theforeach anddoParallel implementations.

skip.dissolution

IfTRUE, skip over the calculations ofduration and dissolution stats innetdx.

Details

Thenetdx function handles dynamic network diagnostics for networkmodels fit with thenetest function. Given the fitted model,netdx simulates a specified number of dynamic networks for a specifiednumber of time steps per simulation. The network statistics innwstats.formula are saved for each time step. Summary statistics forthe formation model terms, as well as dissolution model and relationalduration statistics, are then calculated and can be accessed when printing orplotting thenetdx object. Seeprint.netdx andplot.netdxfor details on printing and plotting.

Value

A list of classnetdx.

Control Arguments

Models fit with the full STERGM method innetest (setting theedapprox argument toFALSE) require only a call totergm'ssimulate_formula.network. Control parameters for thosesimulations may be set usingset.control.tergm innetdx.The parameters should be input through thecontrol.simulate.formula.tergmfunction, with the available parameters listed in thetergm::control.simulate.formula.tergm help page in thetergmpackage.

Models fit with the ERGM method with the edges dissolution approximation(settingedapprox toTRUE) require a call first toergm'ssimulate_formula.network for simulating an initialnetwork, and second totergm'ssimulate_formula.network forsimulating that static network forward through time. Control parameters maybe set for both processes innetdx. For the first, the parametersshould be input through thecontrol.simulate.formula() function, withthe available parameters listed in theergm::control.simulate.formula helppage in theergm package. For the second, parameters should be inputthrough thecontrol.simulate.formula.tergm() function, with theavailable parameters listed in thetergm::control.simulate.formula.tergmhelp page in thetergm package. An example is shown below.

See Also

Plot these model diagnostics withplot.netdx.

Examples

## Not run: # Network initialization and model parameterizationnw <- network_initialize(n = 100)formation <- ~edgestarget.stats <- 50coef.diss <- dissolution_coefs(dissolution = ~ offset(edges), duration = 25)# Estimate the modelest <- netest(nw, formation, target.stats, coef.diss, verbose = FALSE)# Static diagnostics on the ERGM fitdx1 <- netdx(est,  nsims = 1e4, dynamic = FALSE,  nwstats.formula = ~ edges + meandeg + concurrent)dx1plot(dx1, method = "b", stats = c("edges", "concurrent"))# Dynamic diagnostics on the STERGM approximationdx2 <- netdx(est,  nsims = 5, nsteps = 500,  nwstats.formula = ~ edges + meandeg + concurrent,  set.control.ergm = control.simulate.formula(MCMC.burnin = 1e6))dx2plot(dx2, stats = c("edges", "meandeg"), plots.joined = FALSE)plot(dx2, type = "duration")plot(dx2, type = "dissolution", qnts.col = "orange2")plot(dx2, type = "dissolution", method = "b", col = "bisque")# Dynamic diagnostics on a more complex modelnw <- network_initialize(n = 1000)nw <- set_vertex_attribute(nw, "neighborhood", rep(1:10, 100))formation <- ~edges + nodematch("neighborhood", diff = TRUE)target.stats <- c(800, 45, 81, 24, 16, 32, 19, 42, 21, 24, 31)coef.diss <- dissolution_coefs(dissolution = ~offset(edges) +                    offset(nodematch("neighborhood", diff = TRUE)),                    duration = c(52, 58, 61, 55, 81, 62, 52, 64, 52, 68, 58))est2 <- netest(nw, formation, target.stats, coef.diss, verbose = FALSE)dx3 <- netdx(est2, nsims = 5, nsteps = 100)print(dx3)plot(dx3)plot(dx3, type = "duration", plots.joined = TRUE, qnts = 0.2, legend = TRUE)plot(dx3, type = "dissolution", mean.smooth = FALSE, mean.col = "red")## End(Not run)

Dynamic Network Model Estimation

Description

Estimates statistical network models using the exponentialrandom graph modeling (ERGM) framework with extensions fordynamic/temporal models (STERGM).

Usage

netest(  nw,  formation,  target.stats,  coef.diss,  constraints,  coef.form = NULL,  edapprox = TRUE,  set.control.ergm = control.ergm(),  set.control.tergm = control.tergm(),  set.control.ergm.ego = NULL,  verbose = FALSE,  nested.edapprox = TRUE,  ...)

Arguments

nw

An object of classnetwork oregor, with the latterindicating anergm.ego fit.

formation

Right-hand sided STERGM formation formula in the form~edges + ..., where... are additional network statistics.

target.stats

Vector of target statistics for the formation model, withone number for each network statistic in the model. Ignored iffitting viaergm.ego.

coef.diss

An object of classdisscoef output from thedissolution_coefs function.

constraints

Right-hand sided formula specifying constraints for themodeled network, in the form~..., where... areconstraint terms. By default, no constraints are set.

coef.form

Vector of coefficients for the offset terms in the formationformula.

edapprox

IfTRUE, use the indirect edges dissolutionapproximation method for the dynamic model fit, otherwise use themore time-intensive full STERGM estimation (see details). Fornw of classegor, onlyedapprox = TRUE is supported.

set.control.ergm

Control arguments passed toergm (see details).

set.control.tergm

Control arguments passed totergm (see details).

set.control.ergm.ego

Control arguments passed toergm.ego (seedetails).

verbose

IfTRUE, print model fitting progress to console.

nested.edapprox

Logical. Ifedapprox = TRUE the dissolutionmodel is an initial segment of the formation model (see details).

...

Additional arguments passed to other functions.

Details

netest is a wrapper function for theergm,ergm.ego, andtergmfunctions that estimate static and dynamic network models. Network modelestimation is the first step in simulating a stochastic network epidemic modelinEpiModel. The output fromnetest is a necessary input for running theepidemic simulations innetsim. With a fitted network model, one shouldalways first proceed to model diagnostics, available through thenetdxfunction, to check model fit. A detailed description of fitting thesemodels, along with examples, may be found in theNetwork Modeling for Epidemicstutorials.

Value

A fitted network model object of classnetest.

Edges Dissolution Approximation

The edges dissolution approximation method is described in Carnegie et al.This approximation requires that the dissolution coefficients are known, thatthe formation model is being fit to cross-sectional data conditional on thosedissolution coefficients, and that the terms in the dissolution model are asubset of those in the formation model. Under certain additional conditions,the formation coefficients of a STERGM model are approximately equal to thecoefficients of that same model fit to the observed cross-sectional data asan ERGM, minus the corresponding coefficients in the dissolution model. Theapproximation thus estimates this ERGM (which is typically much faster thanestimating a STERGM) and subtracts the dissolution coefficients.

The conditions under which this approximation best hold are when there arefew relational changes from one time step to another; i.e. when eitheraverage relational durations are long, or density is low, or both.Conveniently, these are the same conditions under which STERGM estimation isslowest. Note that the same approximation is also used to obtain startingvalues for the STERGM estimate when the latter is being conducted. Theestimation does not allow for calculation of standard errors, p-values, orlikelihood for the formation model; thus, this approach is of most use whenthe main goal of estimation is to drive dynamic network simulations ratherthan to conduct inference on the formation model. The user is stronglyencouraged to examine the behavior of the resulting simulations to confirmthat the approximation is adequate for their purposes. For an example, seethe vignette for the packagetergm.

It has recently been found that subtracting a modified version of thedissolution coefficients from the formation coefficients provides a moreprincipled approximation, and this is now the form of the approximationapplied bynetest. The modified values subtracted from the formationcoefficients are equivalent to the (crude) dissolution coefficients withtheir target durations increased by 1. Thenested.edapprox argumenttoggles whether to implement this modified version by appending thedissolution terms to the formation model and appending the relevant values tothe vector of formation model coefficients (value =FALSE), whereasthe standard version subtracts the relevant values from the initial formationmodel coefficients (value =TRUE).

Control Arguments

Theergm,ergm.ego, andtergm functions allow control settings for themodel fitting process. When fitting a STERGM directly (settingedapprox toFALSE), control parameters may be passed to thetergm function with theset.control.tergm argument innetest.The controls should be input through thecontrol.tergm() function,with the available parameters listed in thetergm::control.tergm helppage in thetergm package.

When fitting a STERGM indirectly (settingedapprox toTRUE), controlsettings may be passed to theergm function usingset.control.ergm,or to theergm.ego function usingset.control.ergm.ego. The controlsshould be input through thecontrol.ergm() andcontrol.ergm.ego()functions, respectively, with the available parameters listed in theergm::control.ergm help page in theergm package and theergm.ego::control.ergm.ego help page in theergm.egopackage. An example is below.

References

Krivitsky PN, Handcock MS. "A Separable Model for Dynamic Networks." JRSS(B).2014; 76.1: 29-46.

Carnegie NB, Krivitsky PN, Hunter DR, Goodreau SM. An Approximation Methodfor Improving Dynamic Network Model Fitting. Journal of Computational andGraphical Statistics. 2014; 24(2): 502-519.

Jenness SM, Goodreau SM and Morris M. EpiModel: An R Package for MathematicalModeling of Infectious Disease over Networks. Journal of StatisticalSoftware. 2018; 84(8): 1-47.

See Also

Usenetdx to diagnose the fitted network model, andnetsimto simulate epidemic spread over a simulated dynamic networkconsistent with the model fit.

Examples

# Initialize a network of 100 nodesnw <- network_initialize(n = 100)# Set formation formulaformation <- ~edges + concurrent# Set target statistics for formationtarget.stats <- c(50, 25)# Obtain the offset coefficientscoef.diss <- dissolution_coefs(dissolution = ~offset(edges), duration = 10)# Estimate the STERGM using the edges dissolution approximationest <- netest(nw, formation, target.stats, coef.diss,              set.control.ergm = control.ergm(MCMC.burnin = 1e5,                                              MCMC.interval = 1000))est# To estimate the STERGM directly, use edapprox = FALSE# est2 <- netest(nw, formation, target.stats, coef.diss, edapprox = FALSE)

Stochastic Network Models

Description

Simulates stochastic network epidemic models for infectiousdisease.

Usage

netsim(x, param, init, control)

Arguments

x

Ifcontrol$start == 1, either a fitted network model objectof classnetest or a list of such objects. Ifcontrol$start > 1, an object of classnetsim. Whenmultiple networks are used, the node sets (including network sizeand nodal attributes) are assumed to be the same for all networks.

param

Model parameters, as an object of classparam.net.

init

Initial conditions, as an object of classinit.net.

control

Control settings, as an object of classcontrol.net.

Details

Stochastic network models explicitly represent phenomena within and acrossedges (pairs of nodes that remain connected) over time. This enables edges tohave duration, allowing for repeated transmission-related acts within thesame dyad, specification of edge formation and dissolution rates, controlover the temporal sequencing of multiple edges, and specification ofnetwork-level features. A detailed description of these models, along withexamples, is found in theNetwork Modeling for Epidemicscourse materials.

Thenetsim function performs modeling of both the base model typesand original models. Base model types include one-group and two-group modelswith disease types for Susceptible-Infected (SI), Susceptible-Infected-Recovered (SIR),and Susceptible-Infected-Susceptible (SIS).

Original models may be parameterized by writing new process modules thateither take the place of existing modules (for example, disease recovery), orsupplement the set of existing processes with a new one contained in a newmodule. This functionality is documented in theExtending EpiModelsection of theNetwork Modeling for Epidemicscourse materials. The list of modules withinnetsim available formodification is listed inmodules.net.

Value

A list of classnetsim with the following elements:

Ifcontrol$raw.output == TRUE: A list of the raw (pre-processed)netsim_dat objects, for use in simulation continuation.

References

Jenness SM, Goodreau SM and Morris M. EpiModel: An R Package for MathematicalModeling of Infectious Disease over Networks. Journal of StatisticalSoftware. 2018; 84(8): 1-47.

See Also

Extract the model results withas.data.frame.netsim.Summarize the time-specific model results withsummary.netsim. Plot the model results withplot.netsim.

Examples

## Not run: ## Example 1: SI Model without Network Feedback# Network model estimationnw <- network_initialize(n = 100)nw <- set_vertex_attribute(nw, "group", rep(1:2, each = 50))formation <- ~edgestarget.stats <- 50coef.diss <- dissolution_coefs(dissolution = ~offset(edges), duration = 20)est1 <- netest(nw, formation, target.stats, coef.diss, verbose = FALSE)# Epidemic modelparam <- param.net(inf.prob = 0.3, inf.prob.g2 = 0.15)init <- init.net(i.num = 10, i.num.g2 = 10)control <- control.net(type = "SI", nsteps = 100, nsims = 5, verbose.int = 0)mod1 <- netsim(est1, param, init, control)# Print, plot, and summarize the resultsmod1plot(mod1)summary(mod1, at = 50)## Example 2: SIR Model with Network Feedback# Recalculate dissolution coefficient with departure ratecoef.diss <- dissolution_coefs(dissolution = ~offset(edges), duration = 20,                               d.rate = 0.0021)# Reestimate the model with new coefficientest2 <- netest(nw, formation, target.stats, coef.diss)# Reset parameters to include demographic ratesparam <- param.net(inf.prob = 0.3, inf.prob.g2 = 0.15,                   rec.rate = 0.02, rec.rate.g2 = 0.02,                   a.rate = 0.002, a.rate.g2 = NA,                   ds.rate = 0.001, ds.rate.g2 = 0.001,                   di.rate = 0.001, di.rate.g2 = 0.001,                   dr.rate = 0.001, dr.rate.g2 = 0.001)init <- init.net(i.num = 10, i.num.g2 = 10,                 r.num = 0, r.num.g2 = 0)control <- control.net(type = "SIR", nsteps = 100, nsims = 5,                       resimulate.network = TRUE, tergmLite = TRUE)# Simulate the model with new network fitmod2 <- netsim(est2, param, init, control)# Print, plot, and summarize the resultsmod2plot(mod2)summary(mod2, at = 40)## End(Not run)

Message to Find in Which Module acondition Occurred

Description

This function returns a formatted string describing when, where,and why an error, message, or warning occurred.

Usage

netsim_cond_msg(cond, module, at, msg)

Arguments

cond

The type ofcondition handled (message, warning, error).

module

The name of the module where thecondition occurred.

at

The time step thecondition occurred.

msg

Thecondition's message.

Value

A formatted string describing where and when theconditionoccurred as well as thecondition's message.


Handle the Logging of Traceback and Dumping of Frames on Error

Description

Ifcontrol$.traceback.on.error == TRUE, this function prints the tracebackof the current simulation to STDIN. This is useful whenncores > 1 or inHPC settings.Ifcontrol$.dump.frames.on.error == TRUE, this function saves a debuggingdump for "postmortem debugging". The dumps are named"dump_%Y%m%d_%H%M%S_s.rda" and stored at the root of the working directory.

Usage

netsim_error_logger(dat, s)

Arguments

dat

Mainnetsim_dat object containing anetworkDynamicobject and other initialization information passed fromnetsim.

s

The number of the simulation that failed

Value

Nothing, after logging and dumping frames, the function gives thecontrol back to the general error handler


Initialize Network Object

Description

Initialize an undirected network object for use in EpiModelworkflows.

Usage

network_initialize(n)

Arguments

n

Network size.

Details

This function is used inEpiModel workflows to initialize an emptynetwork object. The network attributesdirected,bipartite,hyper,loops, andmultiple are set toFALSE.

Value

Returns an object of classnetwork.

Examples

nw <- network_initialize(100)nw

Dynamic Network Updates

Description

This function handles all calls to the network object containedon the mainnetsim_dat object handled innetsim.

Usage

nwupdate.net(dat, at)

Arguments

dat

Mainnetsim_dat object containing anetworkDynamicobject and other initialization information passed fromnetsim.

at

Current time step.

Value

The updatednetsim_dat main list object.


Helper to use adata.frame to initialize some attributes

Description

Usesdat$init$init_attr to overwrite some attributes of thenodes at initialization

Usage

overwrite_attrs(dat)

Arguments

dat

Mainnetsim_dat object containing anetworkDynamicobject and other initialization information passed fromnetsim.

Details

If aninit_attrdata.frame is present indat$init, use it to overwritethe attributes it contains.init_attr must have a number of rows equal to the number of nodes in themodel as the attributes will be overwritten one to one, ensuring the correctordering.init_attr columns MUST have a corresponding attribute already initialized.See "R/default_attributes.R" for adding new attributes to the model.init_attr is removed fromdat$init at the end of the function to free upits memory.

Value

The updatednetsim_dat main list object.


Grow a Vector to a Given Size, Padding it With Empty Elements

Description

Grow a vector to a given size, padding it withNULL iforig is alistand withNA otherwise

Usage

padded_vector(orig, size)

Arguments

orig

A vector to grow.

size

The final size of the vector.

Value

A vector of sizesize padded withNULLs orNAs at the end.


Epidemic Parameters for Deterministic Compartmental Models

Description

Sets the epidemic parameters for deterministic compartmentalmodels simulated withdcm.

Usage

param.dcm(  inf.prob,  inter.eff,  inter.start,  act.rate,  rec.rate,  a.rate,  ds.rate,  di.rate,  dr.rate,  inf.prob.g2,  act.rate.g2,  rec.rate.g2,  a.rate.g2,  ds.rate.g2,  di.rate.g2,  dr.rate.g2,  balance,  ...)

Arguments

inf.prob

Probability of infection per transmissible act betweena susceptible and an infected person. In two-group models, this is theprobability of infection for the group 1 members.

inter.eff

Efficacy of an intervention which affects the per-actprobability of infection. Efficacy is defined as 1 - the relativehazard of infection given exposure to the intervention, compared to noexposure.

inter.start

Time step at which the intervention starts, between 1 andthe number of time steps specified in the model. This will default to1 ifinter.eff is defined but this parameter is not.

act.rate

Average number of transmissible acts per person per unittime. For two-group models, this is the number of acts per group 1person per unit time; a balance between the acts in groups 1 and 2 isnecessary, and set using thebalance parameter (see details).

rec.rate

Average rate of recovery with immunity (inSIR models)or re-susceptibility (inSIS models). The recovery rate is thereciprocal of the disease duration. For two-group models, this is therecovery rate for group 1 persons only. This parameter is only usedforSIR andSIS models.

a.rate

Arrival or entry rate. For one-group models, the arrival rateis the rate of new arrivals per person per unit time. For two-groupmodels, the arrival rate is parameterized as a rate per group 1person per unit time, with thea.rate.g2 rate set as describedbelow.

ds.rate

Departure or exit rate for susceptible persons. For two-groupmodels, it is the rate for the group 1 susceptible persons only.

di.rate

Departure or exit rate for infected persons. For two-groupmodels, it is the rate for the group 1 infected persons only.

dr.rate

Departure or exit rate for recovered persons. For two-groupmodels, it is the rate for the group 1 recovered persons only. Thisparameter is only used forSIR models.

inf.prob.g2

Probability of infection per transmissible actbetween a susceptible group 2 person and an infected group 1 person.It is the probability of infection to group 2 members.

act.rate.g2

Average number of transmissible acts per group 2 personper unit time; a balance between the acts in groups 1 and 2 isnecessary, and set using thebalance parameter (see details).

rec.rate.g2

Average rate of recovery with immunity (inSIRmodels) or re-susceptibility (inSIS models) for group 2persons. This parameter is only used for two-groupSIR andSIS models.

a.rate.g2

Arrival or entry rate for group 2. This may either bespecified numerically as the rate of new arrivals per group 2 personsper unit time, or asNA in which case the group 1 rate,a.rate, governs the group 2 rate. The latter is used when,for example, the first group is conceptualized as female, and thefemale population size determines the arrival rate. Such arrivals areevenly allocated between the two groups.

ds.rate.g2

Departure or exit rate for group 2 susceptible persons.

di.rate.g2

Departure or exit rate for group 2 infected persons.

dr.rate.g2

Departure or exit rate for group 2 recovered persons. Thisparameter is only used forSIR model types.

balance

For two-group models, balance theact.rate to the rateset for group 1 (withbalance="g1") or group 2 (withbalance="g2"). See details.

...

Additional arguments passed to model.

Details

param.dcm sets the epidemic parameters for deterministic compartmentalmodels solved with thedcm function. The models may use thebase types, for which these parameters are used, or original modelspecifications for which these parameters may be used (but not necessarily).

For base models, the model specification will be selected as a functionof the model parameters entered here and the control settings incontrol.dcm. One-group and two-group models are available,where the former assumes a homogeneous mixing in the population and thelatter assumes some form of heterogeneous mixing between two distinctpartitions in the population (e.g., men and women). Specifying any group twoparameters (those with a.g2) implies the simulation of a two-groupmodel. All the parameters for a desired model type must be specified, even ifthey are zero.

Value

AnEpiModel object of classparam.dcm.

Act Balancing

In two-group models, a balance between the number of acts for group 1 membersand those for group 2 members must be maintained. With purely heterogeneousmixing, the product of one group size and act rate must equal the product ofthe other group size and act rate:N_1 \alpha_1 = N_2 \alpha_2, whereN_i is the group size and\alpha_i the group-specific act rateat timet. Thebalance parameter here specifies which group'sact rate should control the others with respect to balancing.

Sensitivity Analyses

dcm has been designed to easily run DCM sensitivity analyses, where aseries of models varying one or more of the model parameters is run. This ispossible by setting any parameter as a vector of length greater than one.

New Model Types

An original model may use either the existing model parameters named here,an original set of parameters, or a combination of both. The...argument allows the user to pass an arbitrary set of new model parameters intoparam.dcm. Whereas there are strict checks for base models that themodel parameters are valid, parameter validity is the user's responsibilitywith these original models.

See Also

Useinit.dcm to specify the initial conditions andcontrol.dcm to specify the control settings. Run theparameterized model withdcm.


Epidemic Parameters for Stochastic Individual Contact Models

Description

Sets the epidemic parameters for stochastic individual contactmodels simulated withicm.

Usage

param.icm(  inf.prob,  inter.eff,  inter.start,  act.rate,  rec.rate,  a.rate,  ds.rate,  di.rate,  dr.rate,  inf.prob.g2,  act.rate.g2,  rec.rate.g2,  a.rate.g2,  ds.rate.g2,  di.rate.g2,  dr.rate.g2,  balance,  ...)

Arguments

inf.prob

Probability of infection per transmissible act betweena susceptible and an infected person. In two-group models, this is theprobability of infection for the group 1 members.

inter.eff

Efficacy of an intervention which affects the per-actprobability of infection. Efficacy is defined as 1 - the relativehazard of infection given exposure to the intervention, compared to noexposure.

inter.start

Time step at which the intervention starts, between 1 andthe number of time steps specified in the model. This will default to1 ifinter.eff is defined but this parameter is not.

act.rate

Average number of transmissible acts per person per unittime. For two-group models, this is the number of acts per group 1person per unit time; a balance between the acts in groups 1 and 2 isnecessary, and set using thebalance parameter (see details).

rec.rate

Average rate of recovery with immunity (inSIR models)or re-susceptibility (inSIS models). The recovery rate is thereciprocal of the disease duration. For two-group models, this is therecovery rate for group 1 persons only. This parameter is only usedforSIR andSIS models.

a.rate

Arrival or entry rate. For one-group models, the arrival rateis the rate of new arrivals per person per unit time. For two-groupmodels, the arrival rate is parameterized as a rate per group 1person per unit time, with thea.rate.g2 rate set as describedbelow.

ds.rate

Departure or exit rate for susceptible persons. For two-groupmodels, it is the rate for the group 1 susceptible persons only.

di.rate

Departure or exit rate for infected persons. For two-groupmodels, it is the rate for the group 1 infected persons only.

dr.rate

Departure or exit rate for recovered persons. For two-groupmodels, it is the rate for the group 1 recovered persons only. Thisparameter is only used forSIR models.

inf.prob.g2

Probability of infection per transmissible actbetween a susceptible group 2 person and an infected group 1 person.It is the probability of infection to group 2 members.

act.rate.g2

Average number of transmissible acts per group 2 personper unit time; a balance between the acts in groups 1 and 2 isnecessary, and set using thebalance parameter (see details).

rec.rate.g2

Average rate of recovery with immunity (inSIRmodels) or re-susceptibility (inSIS models) for group 2persons. This parameter is only used for two-groupSIR andSIS models.

a.rate.g2

Arrival or entry rate for group 2. This may either bespecified numerically as the rate of new arrivals per group 2 personsper unit time, or asNA in which case the group 1 rate,a.rate, governs the group 2 rate. The latter is used when,for example, the first group is conceptualized as female, and thefemale population size determines the arrival rate. Such arrivals areevenly allocated between the two groups.

ds.rate.g2

Departure or exit rate for group 2 susceptible persons.

di.rate.g2

Departure or exit rate for group 2 infected persons.

dr.rate.g2

Departure or exit rate for group 2 recovered persons. Thisparameter is only used forSIR model types.

balance

For two-group models, balance theact.rate to the rateset for group 1 (withbalance="g1") or group 2 (withbalance="g2"). See details.

...

Additional arguments passed to model.

Details

param.icm sets the epidemic parameters for the stochastic individualcontact models simulated with theicm function. Modelsmay use the base types, for which these parameters are used, or new processmodules which may use these parameters (but not necessarily).

For base models, the model specification will be chosen as a result ofthe model parameters entered here and the control settings incontrol.icm. One-group and two-group models are available,where the former assumes a homogeneous mixing in the population and thelatter assumes some form of heterogeneous mixing between two distinctpartitions in the population (e.g., men and women). Specifying any group twoparameters (those with a.g2) implies the simulation of a two-groupmodel. All the parameters for a desired model type must be specified, even ifthey are zero.

Value

AnEpiModel object of classparam.icm.

Act Balancing

In two-group models, a balance between the number of acts for group 1 membersand those for group 2 members must be maintained. With purely heterogeneousmixing, the product of one group size and act rate must equal the product ofthe other group size and act rate:N_1 \alpha_1 = N_2 \alpha_2, whereN_i is the group size and\alpha_i the group-specific act rateat timet. Thebalance parameter here specifies which group'sact rate should control the others with respect to balancing.

New Modules

To build original models outside of the base models, new process modulesmay be constructed to replace the existing modules or to supplement theexisting set. These are passed into the control settings incontrol.icm. New modules may use either the existing modelparameters named here, an original set of parameters, or a combination ofboth. The... allows the user to pass an arbitrary set of originalmodel parameters intoparam.icm. Whereas there are strict checks withdefault modules for parameter validity, these checks are the user'sresponsibility with new modules.

See Also

Useinit.icm to specify the initial conditions andcontrol.icm to specify the control settings. Run theparameterized model withicm.


Epidemic Parameters for Stochastic Network Models

Description

Sets the epidemic parameters for stochastic network modelssimulated withnetsim.

Usage

param.net(  inf.prob,  inter.eff,  inter.start,  act.rate,  rec.rate,  a.rate,  ds.rate,  di.rate,  dr.rate,  inf.prob.g2,  rec.rate.g2,  a.rate.g2,  ds.rate.g2,  di.rate.g2,  dr.rate.g2,  ...)

Arguments

inf.prob

Probability of infection per transmissible act betweena susceptible and an infected person. In two-group models, this is theprobability of infection to the group 1 nodes. This may also be avector of probabilities, with each element corresponding to theprobability in that time step of infection (see Time-VaryingParameters below).

inter.eff

Efficacy of an intervention which affects the per-actprobability of infection. Efficacy is defined as 1 - the relativehazard of infection given exposure to the intervention, compared to noexposure.

inter.start

Time step at which the intervention starts, between 1 andthe number of time steps specified in the model. This will default to1 ifinter.eff is defined but this parameter is not.

act.rate

Average number of transmissible actsper partnershipper unit time (seeact.rate Parameter below). This may also bea vector of rates, with each element corresponding to the rate inthat time step of infection (see Time-Varying Parameters below).

rec.rate

Average rate of recovery with immunity (inSIR models)or re-susceptibility (inSIS models). The recovery rate is thereciprocal of the disease duration. For two-group models, this is therecovery rate for group 1 persons only. This parameter is only usedforSIR andSIS models. This may also be a vectorof rates, with each element corresponding to the rate in that timestep of infection (see Time-Varying Parameters below).

a.rate

Arrival or entry rate. For one-group models, the arrival rateis the rate of new arrivals per person per unit time. For two-groupmodels, the arrival rate is parameterized as a rate per group 1person per unit time, with thea.rate.g2 rate set as describedbelow.

ds.rate

Departure or exit rate for susceptible persons. For two-groupmodels, it is the rate for group 1 susceptible persons only.

di.rate

Departure or exit rate for infected persons. For two-groupmodels, it is the rate for group 1 infected persons only.

dr.rate

Departure or exit rate for recovered persons. For two-groupmodels, it is the rate for group 1 recovered persons only. Thisparameter is only used forSIR models.

inf.prob.g2

Probability of transmission given a transmissible actbetween a susceptible group 2 person and an infected group 1 person.It is the probability of transmission to group 2 members.

rec.rate.g2

Average rate of recovery with immunity (inSIRmodels) or re-susceptibility (inSIS models) for group 2persons. This parameter is only used for two-groupSIR andSIS models.

a.rate.g2

Arrival or entry rate for group 2. This may either bespecified numerically as the rate of new arrivals per group 2 personper unit time, or asNA, in which case the group 1 rate,a.rate, governs the group 2 rate. The latter is used when, forexample, the first group is conceptualized as female, and the femalepopulation size determines the arrival rate. Such arrivals are evenlyallocated between the two groups.

ds.rate.g2

Departure or exit rate for group 2 susceptible persons.

di.rate.g2

Departure or exit rate for group 2 infected persons.

dr.rate.g2

Departure or exit rate for group 2 recovered persons. Thisparameter is only used forSIR model types.

...

Additional arguments passed to model.

Details

param.net sets the epidemic parameters for the stochastic networkmodels simulated with thenetsim function. Modelsmay use the base types, for which these parameters are used, or new processmodules which may use these parameters (but not necessarily). A detaileddescription of network model parameterization for base models is found intheNetwork Modeling for Epidemicstutorials.

For base models, the model specification will be chosen as a result ofthe model parameters entered here and the control settings incontrol.net. One-group and two-group models are available,where the latter assumes a heterogeneous mixing between two distinctpartitions in the population (e.g., men and women). Specifying any two-groupparameters (those with a.g2) implies the simulation of a two-groupmodel. All the parameters for a desired model type must be specified, even ifthey are zero.

Value

AnEpiModel object of classparam.net.

Theact.rate Parameter

A key difference between these network models and DCM/ICM classes is thetreatment of transmission events. With DCM and ICM, contacts or partnershipsare mathematically instantaneous events: they have no duration in time, andthus no changes may occur within them over time. In contrast, network modelsallow for partnership durations defined by the dynamic network model,summarized in the model dissolution coefficients calculated indissolution_coefs. Therefore, theact.rate parameter hasa different interpretation here, where it is the number of transmissible actsper partnership per unit time.

Time-Varying Parameters

Theinf.prob,act.rate,rec.rate arguments (and their.g2 companions) may be specified as time-varying parameters by passingin a vector of probabilities or rates, respectively. The value in eachposition on the vector then corresponds to the probability or rate at thatdiscrete time step for the infected partner. For example, aninf.probofc(0.5, 0.5, 0.1) would simulate a 0.5 transmission probability forthe first two time steps of a person's infection, followed by a 0.1 for thethird time step. If the infected person has not recovered or exited thepopulation by the fourth time step, the third element in the vector willcarry forward until one of those events occurs or the simulation ends. Forfurther examples, see theNetwork Modeling for Epidemics tutorials.

Random Parameters

In addition to deterministic parameters in either fixed or time-varyingvarieties above, one may also include a generator for random parameters.These might include a vector of potential parameter values or a statisticaldistribution definition; in either case, one draw from the generator wouldbe completed per individual simulation. This is possible by passing a listnamedrandom.params intoparam.net, with each element ofrandom.params a named generator function. See the help page andexamples ingenerate_random_params. A simple factory functionfor sampling is provided withparam_random but any functionwill do.

Using a Parameter data.frame

It is possible to set input parameters using a specifically formatteddata.frame object. The first 3 columns of thisdata.frame mustbe:

In addition to these 3 columns, thedata.frame can contain any numberof other columns, such asdetails orsource columns to documentparameter meta-data. However, these extra columns will not be used byEpiModel.

This data.frame is then passed in toparam.net under adata.frame.parameters argument. Further details and examples areprovided in the "Working with Model Parameters in EpiModel" vignette.

Parameters with New Modules

To build original models outside of the base models, new process modulesmay be constructed to replace the existing modules or to supplement theexisting set. These are passed into the control settings incontrol.net. New modules may use either the existing modelparameters named here, an original set of parameters, or a combination ofboth. The... allows the user to pass an arbitrary set of originalmodel parameters intoparam.net. Whereas there are strict checks withdefault modules for parameter validity, this becomes a userresponsibility when using new modules.

See Also

Useinit.net to specify the initial conditions andcontrol.net to specify the control settings. Run theparameterized model withnetsim.

Examples

## Example SIR model parameterization with fixed and random parameters# Network model estimationnw <- network_initialize(n = 100)formation <- ~edgestarget.stats <- 50coef.diss <- dissolution_coefs(dissolution = ~offset(edges), duration = 20)est <- netest(nw, formation, target.stats, coef.diss, verbose = FALSE)# Random epidemic parameter list (here act.rate values are sampled uniformly# with helper function param_random, and inf.prob follows a general Beta# distribution with the parameters shown below)my_randoms <- list(  act.rate = param_random(1:3),  inf.prob = function() rbeta(1, 1, 2))# Parameters, initial conditions, and control settingsparam <- param.net(rec.rate = 0.02, random.params = my_randoms)# Printing parameters shows both fixed and and random parameter functionsparam# Set initial conditions and controlsinit <- init.net(i.num = 10, r.num = 0)control <- control.net(type = "SIR", nsteps = 10, nsims = 3, verbose = FALSE)# Simulate the modelsim <- netsim(est, param, init, control)# Printing the sim object shows the randomly drawn values for each simulationsim# Parameter sets can be extracted with:get_param_set(sim)

Parameters List for Stochastic Network Models from a FormattedData Frame

Description

Sets the epidemic parameters for stochastic network models withnetsim using a specially formatted data frame ofparameters.

Usage

param.net_from_table(long.param.df)

Arguments

long.param.df

Adata.frame of parameters. See details for theexpected format.

Value

A list object of classparam.net, which can be passed tonetsim.

long.param.df

It is possible to set input parameters using a specifically formatteddata.frame object. The first 3 columns of thisdata.frame mustbe:

In addition to these 3 columns, thedata.frame can contain any numberof other columns, such asdetails orsource columns to documentparameter meta-data. However, these extra columns will not be used byEpiModel.


Coerce a list of parameters to along.param.df

Description

Coerce a list of parameters to along.param.df

Usage

param.net_to_table(params)

Arguments

params

A list of parameters to be formatted into along.param.df

Value

Adata.frame of parameters.

long.param.df

It is possible to set input parameters using a specifically formatteddata.frame object. The first 3 columns of thisdata.frame mustbe:

In addition to these 3 columns, thedata.frame can contain any numberof other columns, such asdetails orsource columns to documentparameter meta-data. However, these extra columns will not be used byEpiModel.


Create a Value Sampler for Random Parameters

Description

This function returns a 0 argument function that can be used asa generator function in therandom.params argument of theparam.net function.

Usage

param_random(values, prob = NULL)

Arguments

values

A vector of values to sample from.

prob

A vector of weights to use during sampling. IfNULL,all values have the same probability of being picked(default =NULL).

Value

A 0 argument generator function to sample one of the values from thevalues vector.

See Also

param.net andgenerate_random_params

Examples

# Define function with equal sampling probabilitya <- param_random(1:5)a()# Define function with unequal sampling probabilityb <- param_random(1:5, prob = c(0.1, 0.1, 0.1, 0.1, 0.6))b()

Plot Data from a Deterministic Compartmental Epidemic Model

Description

Plots epidemiological data from a deterministic compartmentepidemic model solved withdcm.

Usage

## S3 method for class 'dcm'plot(  x,  y = NULL,  popfrac = FALSE,  run = NULL,  col = NULL,  lwd = NULL,  lty = NULL,  alpha = 0.9,  legend = NULL,  leg.name = NULL,  leg.cex = 0.8,  grid = FALSE,  add = FALSE,  main = "",  xlim = NULL,  ylim = NULL,  xlab = "Time",  ylab = NULL,  ...)

Arguments

x

AnEpiModel object of classdcm.

y

Output compartments or flows fromdcm object to plot.

popfrac

IfTRUE, plot prevalence of values rather than numbers(see details).

run

Run number to plot, for models with multiple runs(default is run 1).

col

Color for lines, either specified as a single color in a standardR color format, or alternatively as a color palette fromRColorBrewer::RColorBrewer (see details).

lwd

Line width for output lines.

lty

Line type for output lines.

alpha

Transparency level for lines, where 0 = transparent and1 = opaque (seeadjustcolor function).

legend

Type of legend to plot. Values are"n" for no legend,"full" for full legend, and"lim" for limited legend(see details).

leg.name

Character string to use for legend, with the defaultdetermined automatically based on they input.

leg.cex

Legend scale size.

grid

IfTRUE, a grid is added to the background of plot(seegrid for details), with default of nx by ny.

add

IfTRUE, new plot window is not called and lines are addedto existing plot window.

main

a main title for the plot, see alsotitle.

xlim

the x limits (x1, x2) of the plot. Note thatx1 > x2is allowed and leads to a ‘reversed axis’.

The default value,NULL, indicates that the range of thefinite values to be plotted should be used.

ylim

the y limits of the plot.

xlab

a label for the x axis, defaults to a description ofx.

ylab

a label for the y axis, defaults to a description ofy.

...

Additional arguments to pass to main plot window (seeplot.default).

Details

This function plots epidemiological outcomes from a deterministiccompartmental model solved withdcm. Depending on the number ofmodel runs (sensitivity analyses) and number of groups, the default plot isthe fractional proportion of each compartment in the model over time. Thespecific compartments or flows to plot may be set using theyparameter, and in multiple run models the specific run may also be specified.

Thepopfrac Argument

Compartment prevalence is the size of a compartment over some denominator.To plot the raw numbers from any compartment, usepopfrac=FALSE; thisis the default. Thepopfrac parameter calculatesand plots the denominators of all specified compartments using these rules:

  1. for one-group models, the prevalence of any compartment is the compartmentsize divided by the total population size; 2) for two-group models, theprevalence of any compartment is the compartment size divided by the groupsize.

Color Palettes

Sincedcm supports multiple run sensitivity models, plottingthe results of such models uses a complex color scheme for distinguishingruns. This is accomplished using theRColorBrewer::RColorBrewer colorpalettes, which include a range of linked colors using named palettes. Forplot.dcm, one may either specify a brewer color palette listed inRColorBrewer::brewer.pal.info, or, alternatively, a vector of standard Rcolors (named, hexidecimal, or positive integers; seecol2rgb).

Plot Legends

There are three automatic legend types available, and the legend isadded by default for plots. To turn off the legend, uselegend="n". Toplot a legend with values for every line in a sensitivity analysis, uselegend="full". With models with many runs, this may be visuallyoverwhelming. In those cases, uselegend="lim" to plot a legendlimited to the highest and lowest values of the varying parameter in themodel. In cases where the default legend names are not helpful, one mayoverride those names with theleg.name argument.

See Also

dcm,RColorBrewer::brewer.pal.info

Examples

# Deterministic SIR model with varying act rateparam <- param.dcm(inf.prob = 0.2, act.rate = 1:10,                   rec.rate = 1/3, a.rate = 0.011, ds.rate = 0.01,                   di.rate = 0.03, dr.rate = 0.01)init <- init.dcm(s.num = 1000, i.num = 1, r.num = 0)control <- control.dcm(type = "SIR", nsteps = 100, dt = 0.25)mod <- dcm(param, init, control)# Plot disease prevalence by defaultplot(mod)# Plot prevalence of susceptiblesplot(mod, y = "s.num", popfrac = TRUE, col = "Greys")# Plot number of susceptiblesplot(mod, y = "s.num", popfrac = FALSE, col = "Greys", grid = TRUE)# Plot multiple runs of multiple compartments togetherplot(mod, y = c("s.num", "i.num"),     run = 5, xlim = c(0, 50), grid = TRUE)plot(mod, y = c("s.num", "i.num"),     run = 10, lty = 2, legend = "n", add = TRUE)

Plot Epidemic Model Results From a Netsim Data.Frame

Description

This function is a wrapper aroundplot.netsim accepting adata.frame obtain withas.data.frame(netsim_object).

Usage

## S3 method for class 'epi.data.frame'plot(  x,  y = NULL,  sims = NULL,  legend = NULL,  mean.col = NULL,  qnts.col = NULL,  sim.lwd = NULL,  sim.col = NULL,  sim.alpha = NULL,  popfrac = FALSE,  qnts = 0.5,  qnts.alpha = 0.5,  qnts.smooth = TRUE,  mean.line = TRUE,  mean.smooth = TRUE,  add = FALSE,  mean.lwd = 2,  mean.lty = 1,  xlim = NULL,  ylim = NULL,  main = NULL,  xlab = NULL,  ylab = NULL,  sim.lines = FALSE,  grid = FALSE,  leg.cex = 0.8,  ...)

Arguments

x

Adata.frame obtain withas.data.frame(netsim_object).

y

Output compartments or flows fromnetsim object to plot.

sims

Iftype="epi" or"formation", a vector ofsimulation numbers to plot. Iftype="network", a singlesimulation number for which to plot the network, or else"min"to plot the simulation number with the lowest disease prevalence,"max" for the simulation with the highest disease prevalence,or"mean" for the simulation with the prevalence closest to themean across simulations at the specified time step.

legend

IfTRUE, plot default legend.

mean.col

Vector of any standard R color format for mean lines.

qnts.col

Vector of any standard R color format for polygons.

sim.lwd

Line width for simulation lines.

sim.col

Vector of any standard R color format for simulation lines.

sim.alpha

Transparency level for simulation lines, where0 = transparent and 1 = opaque (seeadjustcolor function).

popfrac

IfTRUE, plot prevalence of values rather than numbers(see details).

qnts

If numeric, plot polygon of simulation quantiles based on therange implied by the argument (see details). IfFALSE, suppresspolygon from plot.

qnts.alpha

Transparency level for quantile polygons, where 0 =transparent and 1 = opaque (seeadjustcolor function).

qnts.smooth

IfTRUE, use a loess smoother on quantile polygons.

mean.line

IfTRUE, plot mean of simulations across time.

mean.smooth

IfTRUE, use a loess smoother on the mean line.

add

IfTRUE, new plot window is not called and lines are addedto existing plot window.

mean.lwd

Line width for mean lines.

mean.lty

Line type for mean lines.

xlim

the x limits (x1, x2) of the plot. Note thatx1 > x2is allowed and leads to a ‘reversed axis’.

The default value,NULL, indicates that the range of thefinite values to be plotted should be used.

ylim

the y limits of the plot.

main

a main title for the plot, see alsotitle.

xlab

a label for the x axis, defaults to a description ofx.

ylab

a label for the y axis, defaults to a description ofy.

sim.lines

IfTRUE, plot individual simulation lines. Default isto plot lines for one-group models but not for two-group models.

grid

IfTRUE, a grid is added to the background of plot(seegrid for details), with default of nx by ny.

leg.cex

Legend scale size.

...

Additional arguments to pass.


Plot Data from a Stochastic Individual Contact Epidemic Model

Description

Plots epidemiological data from a stochastic individual contactmodel simulated withicm.

Usage

## S3 method for class 'icm'plot(  x,  y = NULL,  popfrac = FALSE,  sim.lines = FALSE,  sims = NULL,  sim.col = NULL,  sim.lwd = NULL,  sim.alpha = NULL,  mean.line = TRUE,  mean.smooth = TRUE,  mean.col = NULL,  mean.lwd = 2,  mean.lty = 1,  qnts = 0.5,  qnts.col = NULL,  qnts.alpha = 0.5,  qnts.smooth = TRUE,  legend = TRUE,  leg.cex = 0.8,  grid = FALSE,  add = FALSE,  xlim = NULL,  ylim = NULL,  main = "",  xlab = "Time",  ylab = NULL,  ...)

Arguments

x

AnEpiModel model object of classicm.

y

Output compartments or flows fromicm object to plot. ——-

popfrac

IfTRUE, plot prevalence of values rather than numbers(see details).

sim.lines

IfTRUE, plot individual simulation lines. Default isto plot lines for one-group models but not for two-group models.

sims

A vector of simulation numbers to plot.

sim.col

Vector of any standard R color format for simulation lines.

sim.lwd

Line width for simulation lines.

sim.alpha

Transparency level for simulation lines, where0 = transparent and 1 = opaque (seeadjustcolor function).

mean.line

IfTRUE, plot mean of simulations across time.

mean.smooth

IfTRUE, use a loess smoother on the mean line.

mean.col

Vector of any standard R color format for mean lines.

mean.lwd

Line width for mean lines.

mean.lty

Line type for mean lines.

qnts

If numeric, plot polygon of simulation quantiles based on therange implied by the argument (see details). IfFALSE, suppresspolygon from plot.

qnts.col

Vector of any standard R color format for polygons.

qnts.alpha

Transparency level for quantile polygons, where 0 =transparent and 1 = opaque (seeadjustcolor function).

qnts.smooth

IfTRUE, use a loess smoother on quantile polygons.

legend

IfTRUE, plot default legend.

leg.cex

Legend scale size.

grid

IfTRUE, a grid is added to the background of plot(seegrid for details), with default of nx by ny.

add

IfTRUE, new plot window is not called and lines are addedto existing plot window.

xlim

the x limits (x1, x2) of the plot. Note thatx1 > x2is allowed and leads to a ‘reversed axis’.

The default value,NULL, indicates that the range of thefinite values to be plotted should be used.

ylim

the y limits of the plot.

main

a main title for the plot, see alsotitle.

xlab

a label for the x axis, defaults to a description ofx.

ylab

a label for the y axis, defaults to a description ofy.

...

Additional arguments to pass.

Details

This plotting function will extract the epidemiological output from a modelobject of classicm and plot the time series data of diseaseprevalence and other results. The summary statistics that the functioncalculates and plots are individual simulation lines, means of the individualsimulation lines, and quantiles of those individual simulation lines. Themean line, toggled on withmean.line=TRUE, is calculated as the rowmean across simulations at each time step.

Compartment prevalences are the size of a compartment over some denominator.To plot the raw numbers from any compartment, usepopfrac=FALSE; thisis the default for any plots of flows. Thepopfrac parametercalculates and plots the denominators of all specified compartments usingthese rules: 1) for one-group models, the prevalence of any compartment isthe compartment size divided by the total population size; 2) for two-groupmodels, the prevalence of any compartment is the compartment size divided bythe group population size. For any prevalences that are not automaticallycalculated, themutate_epi function may be used to add newvariables to theicm object to plot or analyze.

The quantiles show the range of outcome values within a certain specifiedquantile range. By default, the interquartile range is shown: that is themiddle 50\middle 95\where they are plotted by default, specifyqnts=FALSE.

See Also

icm

Examples

## Example 1: Plotting multiple compartment values from SIR modelparam <- param.icm(inf.prob = 0.5, act.rate = 0.5, rec.rate = 0.02)init <- init.icm(s.num = 500, i.num = 1, r.num = 0)control <- control.icm(type = "SIR", nsteps = 100,                       nsims = 3, verbose = FALSE)mod <- icm(param, init, control)plot(mod, grid = TRUE)## Example 2: Plot only infected with specific output from SI modelparam <- param.icm(inf.prob = 0.25, act.rate = 0.25)init <- init.icm(s.num = 500, i.num = 10)control <- control.icm(type = "SI", nsteps = 100,                       nsims = 3, verbose = FALSE)mod2 <- icm(param, init, control)# Plot prevalenceplot(mod2, y = "i.num", mean.line = FALSE, sim.lines = TRUE)# Plot incidencepar(mfrow = c(1, 2))plot(mod2, y = "si.flow", mean.smooth = TRUE, grid = TRUE)plot(mod2, y = "si.flow", qnts.smooth = FALSE, qnts = 1)

Plot Dynamic Network Model Diagnostics

Description

Plots dynamic network model diagnostics calculated innetdx.

Usage

## S3 method for class 'netdx'plot(  x,  type = "formation",  method = "l",  sims = NULL,  stats = NULL,  duration.imputed = TRUE,  sim.lines = FALSE,  sim.col = NULL,  sim.lwd = NULL,  mean.line = TRUE,  mean.smooth = TRUE,  mean.col = NULL,  mean.lwd = 2,  mean.lty = 1,  qnts = 0.5,  qnts.col = NULL,  qnts.alpha = 0.5,  qnts.smooth = TRUE,  targ.line = TRUE,  targ.col = NULL,  targ.lwd = 2,  targ.lty = 2,  plots.joined = NULL,  legend = NULL,  grid = FALSE,  ...)

Arguments

x

AnEpiModel object of classnetdx.

type

Plot type, with options of"formation" for networkmodel formation statistics,"duration" for dissolution modelstatistics for average edge duration, or"dissolution" fordissolution model statistics for proportion of ties dissolved per timestep.

method

Plot method, with options of"l" for line plots and"b" for box plots.

sims

A vector of simulation numbers to plot.

stats

Statistics to plot. Fortype = "formation",statsare among those specified in the call tonetdx;fortype = "duration", "dissolution",stats are amongthose of the dissolution model (withoutoffset()). The defaultis to plot all statistics.

duration.imputed

Iftype = "duration", a logical indicatingwhether or not to impute starting times for relationships extant atthe start of the simulation. Defaults toTRUE whentype = "duration".

sim.lines

IfTRUE, plot individual simulation lines. Default isto plot lines for one-group models but not for two-group models.

sim.col

Vector of any standard R color format for simulation lines.

sim.lwd

Line width for simulation lines.

mean.line

IfTRUE, plot mean of simulations across time.

mean.smooth

IfTRUE, use a loess smoother on the mean line.

mean.col

Vector of any standard R color format for mean lines.

mean.lwd

Line width for mean lines.

mean.lty

Line type for mean lines.

qnts

If numeric, plot polygon of simulation quantiles based on therange implied by the argument (see details). IfFALSE, suppresspolygon from plot.

qnts.col

Vector of any standard R color format for polygons.

qnts.alpha

Transparency level for quantile polygons, where 0 =transparent and 1 = opaque (seeadjustcolor function).

qnts.smooth

IfTRUE, use a loess smoother on quantile polygons.

targ.line

IfTRUE, plot target or expected value line forthe statistic of interest.

targ.col

Vector of standard R colors for target statistic lines, withdefault colors based onRColorBrewer color palettes.

targ.lwd

Line width for the line showing the target statistic values.

targ.lty

Line type for the line showing the target statistic values.

plots.joined

IfTRUE, combine all statistics in one plot,versus one plot per statistic ifFALSE.

legend

IfTRUE, plot default legend.

grid

IfTRUE, a grid is added to the background of plot(seegrid for details), with default of nx by ny.

...

Additional arguments to pass.

Details

The plot function fornetdx objects will generate plots of two typesof model diagnostic statistics that run as part of the diagnostic toolswithin that function. Theformation plot shows the summary statisticsrequested innwstats.formula, where the default includes thosestatistics in the network model formation formula specified in the originalcall tonetest.

Theduration plot shows the average age of existing edges at each timestep, up until the maximum time step requested. The age is used as anestimator of the average duration of edges in the equilibrium state. Whenduration.imputed = FALSE, edges that exist at the beginning of thesimulation are assumed to start with an age of 1, yielding a burn-in periodbefore the observed mean approaches its target. Whenduration.imputed = TRUE, expected ages prior to the start of thesimulation are calculated from the dissolution model, typically eliminatingthe need for a burn-in period.

Thedissolution plot shows the proportion of the extant ties that aredissolved at each time step, up until the maximum time step requested.Typically, the proportion of ties that are dissolved is the reciprocal of themean relational duration. This plot thus contains similar information to thatin the duration plot, but should reach its expected value more quickly, sinceit is not subject to censoring.

Theplots.joined argument will control whether the statisticsare joined in one plot or plotted separately, assuming there are multiplestatistics in the model. The default is based on the number of networkstatistics requested. The layout of the separate plots within the larger plotwindow is also based on the number of statistics.

See Also

netdx

Examples

## Not run: # Network initialization and model parameterizationnw <- network_initialize(n = 500)nw <- set_vertex_attribute(nw, "sex", rbinom(500, 1, 0.5))formation <- ~edges + nodematch("sex")target.stats <- c(500, 300)coef.diss <- dissolution_coefs(dissolution = ~offset(edges) +                  offset(nodematch("sex")), duration = c(50, 40))# Estimate the modelest <- netest(nw, formation, target.stats, coef.diss, verbose = FALSE)# Static diagnosticsdx1 <- netdx(est, nsims = 1e4, dynamic = FALSE,             nwstats.formula = ~edges + meandeg + concurrent +                                nodefactor("sex", levels = NULL) +                                nodematch("sex"))dx1# Plot diagnosticsplot(dx1)plot(dx1, stats = c("edges", "concurrent"), mean.col = "black",     sim.lines = TRUE, plots.joined = FALSE)plot(dx1, stats = "edges", method = "b",     col = "seagreen3", grid = TRUE)# Dynamic diagnosticsdx2 <- netdx(est, nsims = 10, nsteps = 500,             nwstats.formula = ~edges + meandeg + concurrent +                                nodefactor("sex", levels = NULL) +                                nodematch("sex"))dx2# Formation statistics plots, joined and separateplot(dx2, grid = TRUE)plot(dx2, type = "formation", plots.joined = TRUE)plot(dx2, type = "formation", sims = 1, plots.joined = TRUE,     qnts = FALSE, sim.lines = TRUE, mean.line = FALSE)plot(dx2, type = "formation", plots.joined = FALSE,     stats = c("edges", "concurrent"), grid = TRUE)plot(dx2, method = "b", col = "bisque", grid = TRUE)plot(dx2, method = "b", stats = "meandeg", col = "dodgerblue")# Duration statistics plotpar(mfrow = c(1, 2))# With duration imputedplot(dx2, type = "duration", sim.line = TRUE, sim.lwd = 0.3,     targ.lty = 1, targ.lwd = 0.5)# Without duration imputedplot(dx2, type = "duration", sim.line = TRUE, sim.lwd = 0.3,     targ.lty = 1, targ.lwd = 0.5, duration.imputed = FALSE)# Dissolution statistics plotplot(dx2, type = "dissolution", qnts = 0.25, grid = TRUE)plot(dx2, type = "dissolution", method = "b", col = "pink1")## End(Not run)

Plot Data from a Stochastic Network Epidemic Model

Description

Plots epidemiological and network data from a stochastic networkmodel simulated withnetsim.

Usage

## S3 method for class 'netsim'plot(  x,  type = "epi",  y = NULL,  popfrac = FALSE,  sim.lines = FALSE,  sims = NULL,  sim.col = NULL,  sim.lwd = NULL,  sim.alpha = NULL,  mean.line = TRUE,  mean.smooth = TRUE,  mean.col = NULL,  mean.lwd = 2,  mean.lty = 1,  qnts = 0.5,  qnts.col = NULL,  qnts.alpha = 0.5,  qnts.smooth = TRUE,  legend = NULL,  leg.cex = 0.8,  grid = FALSE,  add = FALSE,  network = 1,  at = 1,  col.status = FALSE,  shp.g2 = NULL,  vertex.cex = NULL,  stats = NULL,  targ.line = TRUE,  targ.col = NULL,  targ.lwd = 2,  targ.lty = 2,  plots.joined = NULL,  duration.imputed = TRUE,  method = "l",  main = NULL,  xlim = NULL,  xlab = NULL,  ylim = NULL,  ylab = NULL,  ...)

Arguments

x

AnEpiModel model object of classnetsim.

type

Type of plot:"epi" for epidemic model results,"network" for a static network plot (plot.network),or"formation","duration", or"dissolution" fornetwork formation, duration, or dissolution statistics.

y

Output compartments or flows fromnetsim object to plot.

popfrac

IfTRUE, plot prevalence of values rather than numbers(see details).

sim.lines

IfTRUE, plot individual simulation lines. Default isto plot lines for one-group models but not for two-group models.

sims

Iftype="epi" or"formation", a vector ofsimulation numbers to plot. Iftype="network", a singlesimulation number for which to plot the network, or else"min"to plot the simulation number with the lowest disease prevalence,"max" for the simulation with the highest disease prevalence,or"mean" for the simulation with the prevalence closest to themean across simulations at the specified time step.

sim.col

Vector of any standard R color format for simulation lines.

sim.lwd

Line width for simulation lines.

sim.alpha

Transparency level for simulation lines, where0 = transparent and 1 = opaque (seeadjustcolor function).

mean.line

IfTRUE, plot mean of simulations across time.

mean.smooth

IfTRUE, use a loess smoother on the mean line.

mean.col

Vector of any standard R color format for mean lines.

mean.lwd

Line width for mean lines.

mean.lty

Line type for mean lines.

qnts

If numeric, plot polygon of simulation quantiles based on therange implied by the argument (see details). IfFALSE, suppresspolygon from plot.

qnts.col

Vector of any standard R color format for polygons.

qnts.alpha

Transparency level for quantile polygons, where 0 =transparent and 1 = opaque (seeadjustcolor function).

qnts.smooth

IfTRUE, use a loess smoother on quantile polygons.

legend

IfTRUE, plot default legend.

leg.cex

Legend scale size.

grid

IfTRUE, a grid is added to the background of plot(seegrid for details), with default of nx by ny.

add

IfTRUE, new plot window is not called and lines are addedto existing plot window.

network

Network number, for simulations with multiple networksrepresenting the population.

at

Iftype = "network", time step for network graph.

col.status

IfTRUE andtype="network", automatic diseasestatus colors (blue = susceptible, red = infected, green = recovered).

shp.g2

Iftype = "network" andx is for a two-group model,shapes for the Group 2 vertices, with acceptable inputs of "triangle"and "square". Group 1 vertices will remain circles.

vertex.cex

Relative size of plotted vertices iftype="network",with implicit default of 1.

stats

Iftype="formation","duration","dissolution", statisticsto plot. Fortype = "formation",stats are among thosespecified innwstats.formula ofcontrol.net; fortype = "duration", "dissolution",stats are among thoseof the dissolution model (withoutoffset()). The default isto plot all statistics.

targ.line

IfTRUE, plot target or expected value line forthe statistic of interest.

targ.col

Vector of standard R colors for target statistic lines, withdefault colors based onRColorBrewer color palettes.

targ.lwd

Line width for the line showing the target statistic values.

targ.lty

Line type for the line showing the target statistic values.

plots.joined

IfTRUE andtype="formation","duration","dissolution", combine allstatistics in one plot, versus one plot per statistic ifFALSE.

duration.imputed

Iftype = "duration", a logical indicatingwhether or not to impute starting times for relationships extant atthe start of the simulation. Defaults toTRUE whentype = "duration".

method

Plot method fortype="formation", "duration", "dissolution",with options of"l" for line plots and"b" for box plots.

main

a main title for the plot, see alsotitle.

xlim

the x limits (x1, x2) of the plot. Note thatx1 > x2is allowed and leads to a ‘reversed axis’.

The default value,NULL, indicates that the range of thefinite values to be plotted should be used.

xlab

a label for the x axis, defaults to a description ofx.

ylim

the y limits of the plot.

ylab

a label for the y axis, defaults to a description ofy.

...

Additional arguments to pass.

Details

This plot function can produce three types of plots with a stochastic networkmodel simulated throughnetsim:

  1. type="epi": epidemic model results (e.g., diseaseprevalence and incidence) may be plotted.

  2. type="network": a static network plot will begenerated. A static network plot of a dynamic network is across-sectional extraction of that dynamic network at a specifictime point. This plotting function wraps thenetwork::plot.network function in thenetwork package.Consult the help page forplot.network for all of the plottingparameters. In addition, four plotting parameters specific tonetsim plots are available:sim,at,col.status, andshp.g2.

  3. type="formation": summary network statistics relatedto the network model formation are plotted. These plots are similarto the formation plots fornetdx objects. When running anetsim simulation, one must specify there thatsave.nwstats=TRUE; the plot here will then show the networkstatistics requested explicitly innwstats.formula, or will usethe formation formula set innetest otherwise.

  4. type="duration","dissolution": as inplot.netdx; supported inplot.netsim only whenthe dissolution model is~offset(edges),tergmLite isFALSE, andsave.network isTRUE.

Whentype="epi", this plotting function will extract theepidemiological output from a model object of classnetsim and plotthe time series data of disease prevalence and other results. The summarystatistics that the function calculates and plots are individual simulationlines, means of the individual simulation lines, and quantiles of thoseindividual simulation lines. The mean line, toggled on withmean.line=TRUE, is calculated as the row mean across simulations ateach time step.

Compartment prevalences are the size of a compartment over some denominator.To plot the raw numbers from any compartment, usepopfrac=FALSE; thisis the default for any plots of flows. Thepopfrac parametercalculates and plots the denominators of all specified compartments usingthese rules: 1) for one-group models, the prevalence of any compartment isthe compartment size divided by the total population size; 2) for two-groupmodels, the prevalence of any compartment is the compartment size divided bythe group population size. For any prevalences that are not automaticallycalculated, themutate_epi function may be used to add newvariables to thenetsim object to plot or analyze.

The quantiles show the range of outcome values within a certain specifiedquantile range. By default, the interquartile range is shown: that is themiddle 50\middle 95\where they are plotted by default, specifyqnts=FALSE.

Whentype="network", this function will plot cross sections of thesimulated networks at specified time steps. Because it is only possible toplot one time step from one simulation at a time, it is necessary to enterthese in theat andsims parameters. To aid in visualizingrepresentative and extreme simulations at specific time steps, thesims parameter may be set to"mean" to plot the simulation inwhich the disease prevalence is closest to the average across allsimulations,"min" to plot the simulation in which the prevalence islowest, and"max" to plot the simulation in which the prevalence ishighest.

See Also

network::plot.network,mutate_epi

Examples

## SI Model without Network Feedback# Initialize network and set network model parametersnw <- network_initialize(n = 100)nw <- set_vertex_attribute(nw, "group", rep(1:2, each = 50))formation <- ~edgestarget.stats <- 50coef.diss <- dissolution_coefs(dissolution = ~offset(edges), duration = 20)# Estimate the network modelest <- netest(nw, formation, target.stats, coef.diss, verbose = FALSE)# Simulate the epidemic modelparam <- param.net(inf.prob = 0.3, inf.prob.g2 = 0.15)init <- init.net(i.num = 10, i.num.g2 = 10)control <- control.net(type = "SI", nsteps = 20, nsims = 3,                       verbose = FALSE, save.nwstats = TRUE,                       nwstats.formula = ~edges + meandeg + concurrent)mod <- netsim(est, param, init, control)# Plot epidemic trajectoryplot(mod)plot(mod, type = "epi", grid = TRUE)plot(mod, type = "epi", popfrac = TRUE)plot(mod, type = "epi", y = "si.flow", qnts = 1, ylim = c(0, 4))# Plot static networkspar(mar = c(0, 0, 0, 0))plot(mod, type = "network", vertex.cex = 1.5)# Automatic coloring of infected nodes as redpar(mfrow = c(1, 2), mar = c(0, 0, 2, 0))plot(mod, type = "network", main = "Min Prev | Time 50",     col.status = TRUE, at = 20, sims = "min", vertex.cex = 1.25)plot(mod, type = "network", main = "Max Prev | Time 50",     col.status = TRUE, at = 20, sims = "max", vertex.cex = 1.25)# Automatic shape by group number (circle = group 1)par(mar = c(0, 0, 0, 0))plot(mod, type = "network", at = 20, col.status = TRUE,     shp.g2 = "square")plot(mod, type = "network", at = 20, col.status = TRUE,     shp.g2 = "triangle", vertex.cex = 2)# Plot formation statisticspar(mfrow = c(1,1), mar = c(3,3,1,1), mgp = c(2,1,0))plot(mod, type = "formation", grid = TRUE)plot(mod, type = "formation", plots.joined = FALSE)plot(mod, type = "formation", sims = 2:3)plot(mod, type = "formation", plots.joined = FALSE,     stats = c("edges", "concurrent"))plot(mod, type = "formation", stats = "meandeg",     mean.lwd = 1, qnts.col = "seagreen", mean.col = "black")

Plot transmat Infection Tree in Three Styles

Description

Plots the transmission matrix tree from fromget_transmatin one of three styles: a phylogram, a directed network, ora transmission timeline.

Usage

## S3 method for class 'transmat'plot(x, style = c("phylo", "network", "transmissionTimeline"), ...)

Arguments

x

Atransmat object to be plotted.

style

Character name of plot style. One of"phylo","network", or"transmissionTimeline".

...

Additional plot arguments to be passed to lower-level plotfunctions (plot.network,plot.phylo, ortransmissionTimeline).

Details

Thephylo plot requires theape package. ThetransmissionTimeline plot requires that thendtv package.

See Also

network::plot.network,plot.phylo,transmissionTimeline.


Get Epidemic Output from icm Model

Description

This function provides all active model state sizes fromthe network at the specified time step, output to a list ofvectors.

Usage

prevalence.icm(dat, at)

Arguments

dat

Mainicm_dat class data object passed throughicmsimulations.

at

Current time step.

Value

The updatedicm_dat class main data object.


Get Epidemic Output from icm Model

Description

This function provides all active model state sizes fromthe network at the specified time step, output to a list ofvectors.

Usage

prevalence.icm.bip(dat, at)

Arguments

dat

Mainicm_dat class data object passed throughicmsimulations.

at

Current time step.

Value

The updatedicm_dat class main data object.


Get Epidemic Output from netsim Model

Description

Provides all active model state sizes from the network at thespecified time step, output to a list of vectors.

Usage

prevalence.net(dat, at)

Arguments

dat

Mainnetsim_dat object containing anetworkDynamicobject and other initialization information passed fromnetsim.

at

Current time step.

Details

This network utility is used during thenetsim simulationprocess to efficiently query the current size of each state or compartmentin the model at any given timestep. For a two-group network, the currentstate size for each group and overall is provided.

Value

The updatednetsim_dat main list object.


Utility Function for Printing netdx Object

Description

Prints basic information and statistics from anetdxobject.

Usage

## S3 method for class 'netdx'print(x, digits = 3, ...)

Arguments

x

an object of classnetdx

digits

number of digits to print in statistics tables

...

additional arguments (currently ignored)

Details

Given anetdx object,print.netdx prints the diagnostic method(static/dynamic), number of simulations, and (if dynamic) the number of timesteps per simulation used in generating thenetdx object, as well asprinting the formation statistics table and (if present) the duration anddissolution statistics tables. The statistics tables are interpreted asfollows.

Each row has the name of a particular network statistic. In the formationtable, these correspond to actual network statistics in the obvious way.In the duration and dissolution tables, these correspond to dissolutionmodel dyad types: in a homogeneous dissolution model, all dyads are of theedges type; in a heterogeneous dissolution model, a dyad with anonzeronodematch ornodemix change statistic in thedissolution model has type equal to that statistic, and has type equal toedges otherwise. The statistics of interest for the duration anddissolution tables are, respectively, the mean age of extant edges and theedge dissolution rate, broken down by dissolution model dyad type. (Thecurrent convention is to treat the mean age and dissolution rate for aparticular dissolution dyad type as 0 on time steps with no edges of thattype; this behavior may be changed in the future.)

The columns are namedTarget,Sim Mean,Pct Diff,Sim SE,Z Score,SD(Sim Means), andSD(Statistic). TheSim Mean column refers to the meanstatistic value, across all time steps in all simulations in the dynamiccase, and across all sampled networks in all simulations in the static case.TheSim SE column refers to the standard error in the mean, estimatedusingcoda::effectiveSize. TheTargetcolumn indicates the target value (if present) for the statistic, and thePct Diff column gives(Sim Mean - Target)/Target whenTarget is present. TheZ Score column gives(Sim Mean - Target)/(Sim SE). TheSD(Sim Means) column givesthe empirical standard deviation across simulations of the mean statisticvalue within simulation, andSD(Statistic) gives the empiricalstandard deviation of the statistic value across all the simulated data.


Description

Print Helper For Network Stats Tables

Usage

print_nwstats_table(nwtable, digits)

Arguments

nwtable

A formation or dissolution statisticsdata.frame.

digits

Argument to be passed toround.


Save a List of netsim Data to Output List Format

Description

This function transfers the data from a list of the mainnetsim_dat objects to the outputout object at theend of all simulations innetsim.

Usage

process_out.net(dat_list)

Arguments

dat_list

A list of mainnetsim_dat objects innetsimsimulations.

Value

A list of classnetsim with the following elements:


Get the Forward or Backward Reachable Nodes for a Set of Nodes

Description

These functions return the Forward or Backward Reachable Nodes of a set ofnodes in a network over a time. Warning, these functions ignore nodes withoutedges in the period of interest. See the⁠Number of Nodes⁠ section fordetails It is much faster than iteratingtsna::tPath. The distance between to each node can be back calculatedusing the length of the reachable set at each time step and the fact that thereachable sets are ordered by the time to arrival.

Usage

get_forward_reachable(  el_cuml,  from_step,  to_step,  nodes = NULL,  dense_optim = "auto")get_backward_reachable(  el_cuml,  from_step,  to_step,  nodes = NULL,  dense_optim = "auto")

Arguments

el_cuml

a cumulative edgelist object. That is a data.frame with atleast columns: head, tail, start and stop. Start and stop are inclusive.

from_step

the beginning of the time period.

to_step

the end of the time period.

nodes

the subset of nodes to calculate the FRP for. (default = NULL,all nodes)

dense_optim

pre-process the adjacency list to speed up thecomputations on dense networks. "auto" (default), enable theoptimisation whenn_edges > n_nodes. "yes" always enables and "no"always disables. The overhead of the optimization is not worth it onsparse networks.

Value

A named list containing:reached: the set of reachable nodes for each of thenodes.lengths: A matrix oflength(nodes) rows and one column per timestep + 1with the length of the reachable set at each step fromfrom_step - 1toto_step. The first column is always one as the set of reachablesat the beginning is just the node itself.

Number of Nodes

To speed up the calculations and lower the memory usage, these functionsonly take into account nodes with edges in the cumulative edgelist over theperiod of interest. The nodes are identified in thereached andlengthssublists by names (e.g.node_1093). Nodes without any edges are thereforenot calculated as the only node they reach is themselve (length of 1).Take this fact into account when exploring the distribution of ForwardReachable Paths for example. As the nodes with FRP == 1 are not in theoutput.

Time and Memory Use

These functions may be used to efficiently calculate multiple sets ofreachable nodes. As cumulative edgelists are way smaller than fullnetworkDynamic objects, theses functions are suited for large and densenetworks.Also, as long as the size of thenodes set is greater than 5, thesesfunctions are faster than iterating overtsna::tPath.

Displaying Progress

These functions are using theprogressr packageto display its progression. Useprogressr::with_progress({ fwd_reach <- get_forward_reachable(el, from = 1, to = 260) })to display the progress bar. Or see theprogressr packagefor more information and customization.

Examples

## Not run: # load a network dynamic objectnd <- readRDS("nd_obj.Rds")# convert it to a cumulative edgelistel_cuml <- as_cumulative_edgelist(nd)# sample 100 node indexesnnodes <- max(el_cuml$head, el_cuml$tail)nodes <- sample(nnodes, 100)# `get_forward_reachable` uses steps [from_step, to_step] inclusiveel_fwd <- get_forward_reachable(el_cuml, 1, 52, nodes)[["reached"]]# check if the results are consistent with `tsna::tPath`nodes <- strsplit(names(el_fwd), "_")for (i in seq_along(el_fwd)) {  node <- as.integer(nodes[[i]][2])  t_fwd <- tsna::tPath(    nd, v = node,    start = 1, end = 52 + 1, # tPath works from [start, end) right exclusive    direction = "fwd"  )  t_fwd_set <- which(t_fwd$tdist < Inf)  if(!setequal(el_fwd[[i]], t_fwd_set))    stop("Missmatch on node: ", node)}# Backward:el_bkwd <- get_backward_reachable(el_cuml, 1, 52, nodes = 1)[["reached"]]nodes <- strsplit(names(el_bkwd), "_")t_bkwd <- tsna::tPath(  nd, v = nodes[i][2],  start = 1, end = 52 + 1,  direction = "bkwd", type = "latest.depart")t_bkwd_set <- which(t_bkwd$tdist < Inf)setequal(el_bkwd[[1]], t_bkwd_set)## End(Not run)

Record Attribute History

Description

This function records values specific to a time-step and a group of nodes.In the records, theposit_ids are converted tounique_ids whichallows the recording of data for nodes that are no longer in the network bythe end of the run. The records are stored indat[["attr.history"]]wheredat is the mainnetsim_dat class object, and can beaccessed from thenetsim object withget_attr_history.

Usage

record_attr_history(dat, at, attribute, posit_ids, values)

Arguments

dat

Mainnetsim_dat object containing anetworkDynamicobject and other initialization information passed fromnetsim.

at

The time where the recording happens.

attribute

The name of the value to record.

posit_ids

A numeric vector of posit_ids to which the measure applies.(seeget_posit_ids).

values

The values to be recorded.

Details

See the "Time-Varying Parameters" section of the "Working With ModelParameters" vignette.

Value

The updatednetsim_dat main list object.

Examples

## Not run: # This function must be used inside a custom moduledat <- record_attr_history(dat, at, "attr_1", get_posit_ids(dat), 5)some_nodes <- get_posit_ids(dat)some_nodes <- some_nodes[runif(length(some_nodes)) < 0.2]dat <- record_attr_history(  dat, at,  "attr_2",  some_nodes,  rnorm(length(some_nodes)))## End(Not run)

Record an Arbitrary Object During a Simulation

Description

This function records any object during a simulation to allow itsinspection afterward. The records are stored indat[["raw.records"]]during the simulation, wheredat is the mainnetsim_dat classobject, and in thenetsim object under theraw.recordscollections::queue object.

Usage

record_raw_object(dat, at, label, object)

Arguments

dat

Mainnetsim_dat object containing anetworkDynamicobject and other initialization information passed fromnetsim.

at

The time where the recording happens.

label

The name to give to the recorded object.

object

The object to be recorded.

Details

See the "Time-Varying Parameters" section of the "Working With ModelParameters" vignette.

Value

The updatednetsim_dat main list object.

Examples

## Not run: dat <- record_raw_object(dat, at, "a.df", data.frame(x = 2:200))dat <- record_raw_object(dat, at, "a.message", "I recorded something")## End(Not run)

Recovery: netsim Module

Description

This function simulates recovery from the infected stateeither to a distinct recovered state (SIR model type) or backto a susceptible state (SIS model type), for use innetsim.

Usage

recovery.2g.net(dat, at)

Arguments

dat

Mainnetsim_dat object containing anetworkDynamicobject and other initialization information passed fromnetsim.

at

Current time step.

Value

The updatednetsim_dat main list object.


Recovery: icm Module

Description

This function simulates recovery from the infected stateeither to a distinct recovered state (SIR model type) or backto a susceptible state (SIS model type), for use inicm.

Usage

recovery.icm(dat, at)

Arguments

dat

Mainicm_dat class data object passed throughicmsimulations.

at

Current time step.

Value

The updatedicm_dat class main data object.


Recovery: icm Module

Description

This function simulates recovery from the infected stateeither to a distinct recovered state (SIR model type) or backto a susceptible state (SIS model type), for use inicm.

Usage

recovery.icm.bip(dat, at)

Arguments

dat

Mainicm_dat class data object passed throughicmsimulations.

at

Current time step.

Value

The updatedicm_dat class main data object.


Recovery: netsim Module

Description

This function simulates recovery from the infected stateeither to a distinct recovered state (SIR model type) or backto a susceptible state (SIS model type), for use innetsim.

Usage

recovery.net(dat, at)

Arguments

dat

Mainnetsim_dat object containing anetworkDynamicobject and other initialization information passed fromnetsim.

at

Current time step.

Value

The updatednetsim_dat main list object.


Remove a Set of Modules From the Module List

Description

Remove a Set of Modules From the Module List

Usage

remove_modules(dat, names.to.remove)

Arguments

dat

Mainnetsim_dat object containing anetworkDynamicobject and other initialization information passed fromnetsim.

names.to.remove

a character vector containing the name of the modulesto remove.

Value

The updatednetsim_dat main list object.


Resimulate Dynamic Network at Time 2+

Description

This function resimulates the dynamic network in stochasticnetwork models simulated innetsim with dependencebetween the epidemic and demographic processes and the networkstructure.

Usage

resim_nets(dat, at)

Arguments

dat

Mainnetsim_dat object containing anetworkDynamicobject and other initialization information passed fromnetsim.

at

Current time step.

Value

The updatednetsim_dat main list object.


Save dcm Data to Output List Format

Description

This function transfers the data from the maindfobject to the outputout object at the end of eachrun indcm.

Usage

saveout.dcm(df, s, param, control, out = NULL)

Arguments

df

Main object indcm simulations.

s

Current run number.

param

Param list set inparam.dcm.

control

Control list set incontrol.dcm.

out

Out list passed back in for updating at runs 2+.

Value

A list with the following elements:


Save icm Data to Output List Format

Description

This function transfers the data from the mainicm_datclass data object to the outputout object at the end ofeach simulation inicm.

Usage

saveout.icm(dat, s, out = NULL)

Arguments

dat

Mainicm_dat class data object passed throughicmsimulations.

s

Current simulation number.

out

Out list passed back in for updating at simulations 2+.

Value

A list with the following elements:


Save netsim Data to Output List Format

Description

This function transfers the data from the mainnetsim_datobject to the outputout object at the end of eachsimulation innetsim.

Usage

saveout.net(dat, s, out = NULL)

Arguments

dat

Mainnetsim_dat object containing anetworkDynamicobject and other initialization information passed fromnetsim.

s

Current simulation number.

out

Out list passed back in for updating at simulations 2+.

Value

A list with the following elements:


Set the Current Timestep

Description

Changes the current timestep in thenetsim_dat object.Use with caution. This function exists to work around unforeseencorner cases. In most situation,increment_timestep ispreferred.

Usage

set_current_timestep(dat, timestep)

Arguments

dat

Mainnetsim_dat object containing anetworkDynamicobject and other initialization information passed fromnetsim.

timestep

The new value for the timestep.

Value

The updatednetsim_dat main list object.

Mutability

This DOES NOT modify thenetsim_dat object in place. The result mustbe assigned back todat in order to be registered:dat <- increment_timestep(dat).


Set the List of Modules

Description

Set the List of Modules

Usage

set_modules(dat, modules)

Arguments

dat

Mainnetsim_dat object containing anetworkDynamicobject and other initialization information passed fromnetsim.

modules

A named list of modules to be run by the model

Value

The updatednetsim_dat main list object.


Set Network State During netsim Simulation

Description

This function updates thenetsim_dat object given anetwork representing the current state of the simulation.

Usage

set_network(x, ...)## S3 method for class 'netsim_dat'set_network(x, network = 1L, nw, ...)

Arguments

x

anetsim_dat object

network

the index of the network to set onx

nw

the value of the network to set onx

Details

If runningtergmLite simulation, this function updatesx$el[[network]] and (iftergmLite.track.duration isTRUEfor the network indexnetwork) the network attributes"time"and"lasttoggle" inx$net_attr[[network]]. If not runningtergmLite simulation, this function updates thenetworkDynamicobject stored inx$nw[[network]]. The inputnw should be ofclassnetworkLite when runningtergmLite simulation, and ofclassnetworkDynamic when not runningtergmLite simulation.

Value

thenetsim_dat object with the network state updated


Save Transmission Matrix

Description

This function appends the transmission matrix created duringinfection.net andinfection.2g.net.

Usage

set_transmat(dat, del, at)

Arguments

dat

Mainnetsim_dat object containing anetworkDynamicobject and other initialization information passed fromnetsim.

del

Discordant edgelist created withininfection.net andinfection.2g.net.

at

Current time step.

Details

This internal function works within the parentinfection.netfunctions to save the transmission matrix created at time stepat tothe mainnetsim_dat class objectdat.

Value

The updatednetsim_dat main list object.


Set Vertex Attribute on Network Object

Description

Sets a vertex attribute on an object of classnetwork.This function simplifies the related function in thenetwork package.

Usage

set_vertex_attribute(x, attrname, value, v)

Arguments

x

An object of class network.

attrname

The name of the attribute to set.

value

A vector of values of the attribute to be set.

v

IDs for the vertices whose attributes are to be altered.

Details

This function is used inEpiModel workflows to set vertex attributeson an initialized empty network object (seenetwork_initialize.

Value

Returns an object of classnetwork.

Examples

nw <- network_initialize(100)nw <- set_vertex_attribute(nw, "age", runif(100, 15, 65))nw

Initialize Networks Used in netsim

Description

This function initializes the networks used innetsim. The initial edge set for a given networkis obtained either from simulating the cross-sectional model(ifedapprox == TRUE) or from thenewnetworkelement of thenetest object (ifedapprox == FALSE). Once the initial edge sets aredetermined, the first time step is simulated ifresimulate.network == TRUE, and all time steps aresimulated ifresimulate.network == FALSE. Initializes thenum(.g2) epi fields used inedges_correct for computing edge coefficientadjustments.

Usage

sim_nets_t1(dat)

Arguments

dat

Mainnetsim_dat object containing anetworkDynamicobject and other initialization information passed fromnetsim.

Value

The updatednetsim_dat main list object.


Simulate a Network for a Specified Number of Time Steps

Description

This function simulates a dynamic network over one or multipletime steps for TERGMs or one or multiple cross-sectional networkpanels for ERGMs, for use innetsim modeling.Network statistics are also extracted and saved ifsave.nwstats == TRUE andresimulate.network == FALSE.

Usage

simulate_dat(dat, at, network = 1L, nsteps = 1L)

Arguments

dat

Mainnetsim_dat object containing anetworkDynamicobject and other initialization information passed fromnetsim.

at

Current time step.

network

index of the network to simulate

nsteps

number of time steps to simulate

Value

The updatednetsim_dat main list object.


Stable Sampling Function

Description

Provides a sampling function useful for dynamic simulations, inwhich the length of the input vector may be multiple lengths andthe size of the sample may be 0.

Usage

ssample(x, size, replace = FALSE, prob = NULL)

Arguments

x

Either a vector of one or more elements from which to choose, or apositive integer.

size

Non-negative integer giving the number of items to choose.

replace

Should sampling be with replacement?

prob

Vector of probability weights for obtaining the elements of thevector being sampled.

Value

A vector containing the sampled value(s).


Summary Model Statistics

Description

Extracts and prints model statistics solved withdcm.

Usage

## S3 method for class 'dcm'summary(object, at, run = 1, digits = 3, ...)

Arguments

object

AnEpiModel object of classdcm.

at

Time step for model statistics.

run

Model run number, fordcm class models with multiple runs(sensitivity analyses).

digits

Number of significant digits to print.

...

Additional summary function arguments (not used).

Details

This function provides summary statistics for the main epidemiologicaloutcomes (state and transition size and prevalence) from adcm model.Time-specific summary measures are provided, so it is necessary to input atime of interest. For multiple-run models (sensitivity analyses), input amodel run number. See examples below.

See Also

dcm

Examples

## Deterministic SIR model with varying act.rateparam <- param.dcm(inf.prob = 0.2, act.rate = 2:4, rec.rate = 1/3,                   a.rate = 0.011, ds.rate = 0.01,                   di.rate = 0.03, dr.rate = 0.01)init <- init.dcm(s.num = 1000, i.num = 1, r.num = 0)control <- control.dcm(type = "SIR", nsteps = 50)mod <- dcm(param, init, control)summary(mod, at = 25, run = 1)summary(mod, at = 25, run = 3)summary(mod, at = 26, run = 3)

Summary Model Statistics

Description

Extracts and prints model statistics simulated withicm.

Usage

## S3 method for class 'icm'summary(object, at, digits = 3, ...)

Arguments

object

AnEpiModel object of classicm.

at

Time step for model statistics.

digits

Number of significant digits to print.

...

Additional summary function arguments.

Details

This function provides summary statistics for the main epidemiologicaloutcomes (state and transition size and prevalence) from anicm model.Time-specific summary measures are provided, so it is necessary to input atime of interest.

See Also

icm

Examples

## Stochastic ICM SI model with 3 simulationsparam <- param.icm(inf.prob = 0.2, act.rate = 1)init <- init.icm(s.num = 500, i.num = 1)control <- control.icm(type = "SI", nsteps = 50,                       nsims = 5, verbose = FALSE)mod <- icm(param, init, control)summary(mod, at = 25)summary(mod, at = 50)

Summary for Network Model Fit

Description

Prints the summary model fit statistics for an ERGM or STERGMfit.

Usage

## S3 method for class 'netest'summary(object, ...)

Arguments

object

AnEpiModel object of classnetest.

...

Additional summary function arguments.

Details

This function is simply a wrapper function forsummary.ergm.Additionally, if the edges dissolution approximation was used to fit thetemporal ERGM, then the dissolution coefficient information will be printed.

If thefit object is attached to thenetest object, thensummary.netest will callsummary onfit using the... passed tosummary.netest. Otherwise,summary.netest will print the stored summary of the fit generatedin the originalnetest call, using the... passed tonetest.


Summary Model Statistics

Description

Extracts and prints model statistics simulated withnetsim.

Usage

## S3 method for class 'netsim'summary(object, at, digits = 3, ...)

Arguments

object

AnEpiModel object of classnetsim.

at

Time step for model statistics.

digits

Number of significant digits to print.

...

Additional summary function arguments.

Details

This function provides summary statistics for the main epidemiologicaloutcomes (state and transition size and prevalence) from anetsimmodel. Time-specific summary measures are provided, so it is necessary toinput a time of interest.

See Also

netsim

Examples

## Not run: ## SI Model without Network Feedback# Initialize network and set network model parametersnw <- network_initialize(n = 100)nw <- set_vertex_attribute(nw, "group", rep(1:2, each = 50))formation <- ~edgestarget.stats <- 50coef.diss <- dissolution_coefs(dissolution = ~offset(edges), duration = 20)# Estimate the ERGM models (see help for netest)est1 <- netest(nw, formation, target.stats, coef.diss, verbose = FALSE)# Parameters, initial conditions, and controls for modelparam <- param.net(inf.prob = 0.3, inf.prob.g2 = 0.15)init <- init.net(i.num = 10, i.num.g2 = 10)control <- control.net(type = "SI", nsteps = 100, nsims = 5, verbose.int = 0)# Run the model simulationmod <- netsim(est1, param, init, control)summary(mod, at = 1)summary(mod, at = 50)summary(mod, at = 100)## End(Not run)

Extract Summary Statistics of Networks Used in netsim

Description

This function callssummary on each network beingsimulated innetsim, providedsave.nwstats andresimulate.network are bothTRUE. It records thestatistics represented bynwstats.formula indat$stats$nwstats, wheredat is the mainnetsim_dat class object.

Usage

summary_nets(dat, at)

Arguments

dat

Mainnetsim_dat object containing anetworkDynamicobject and other initialization information passed fromnetsim.

at

Current time step.

Value

The updatednetsim_dat main list object.


Convert Timed Edgelist to Matrix of Toggles

Description

Convert Timed Edgelist to Matrix of Toggles

Usage

tedgelist_to_toggles(tedgelist)

Arguments

tedgelist

A timed edgelist, as produced bynetworkDynamic::as.data.frame.networkDynamic.

Value

The matrix of toggles corresponding totedgelist.


Test the Model Output from a Stochastic Individual Contact Model

Description

Tests whether the model output from an individual contact modelis consistent with key balancing equations for compartment andflow sizes for each simulation for each time step.

Usage

test_icm(x)

Arguments

x

An object of classicm.


Test the Model Output from a Network Model

Description

Tests whether the model output from a network model isconsistent with key balancing equations for compartment andflow sizes for each simulation for each time step.

Usage

test_net(x)

Arguments

x

An object of classnetsim.


Convert Matrix of Toggles to Dissolution and Duration Statistics

Description

Convert Matrix of Toggles to Dissolution and Duration Statistics

Usage

toggles_to_diss_stats(toggles, coef.diss, nsteps, nw, time.start = 0L)

Arguments

toggles

A matrix of toggles, as produced bytedgelist_to_toggles.

coef.diss

Dissolution coefficients used in the simulation.

nsteps

Number of time steps in the simulation.

nw

Network used in the simulation.

time.start

Starting time for the simulation.

Value

Named list containing dissolution and duration statistics matricesand other related information.


Function to Trigger the End Horizon

Description

Function to Trigger the End Horizon

Usage

trigger_end_horizon(dat)

Arguments

dat

Mainnetsim_dat object containing anetworkDynamicobject and other initialization information passed fromnetsim.

Details

This function triggers the end horizon if a controlend.horizon exists anditsat value is equal to the current timestep. The end horizon consists onthe removal of a set of modules from the module list.

Value

The updatednetsim_dat main list object.


Function to Reduce the Size of anetest Object

Description

Trims formula environments from thenetest object.Optionally converts thenewnetwork element of thenetest object to anetworkLite class, and removesthefit element (if present) from thenetestobject.

Usage

trim_netest(  object,  as.networkLite = TRUE,  keep.fit = FALSE,  keep = character(0))

Arguments

object

Anetest class object.

as.networkLite

IfTRUE, convertsobject$newnetworkto anetworkLite.

keep.fit

IfFALSE, removes theobject$fit (if present)on thenetest object.

keep

Character vector of object names to keep in formula environments.By default, all objects are removed.

Details

With larger, more complex network structures with epidemic models, it isgenerally useful to reduce the memory footprint of the fitted TERGM modelobject (estimated withnetest). This utility function removesall but the bare essentials needed for simulating a network model withnetsim.

The function always trims the environments ofobject$constraints andobject$coef.diss$dissolution.

When bothedapprox = TRUE andnested.edapprox = TRUE in thenetest call, also trims the environments ofobject$formulaandobject$formation.

When bothedapprox = TRUE andnested.edapprox = FALSE in thenetest call, also trims the environments ofobject$formula,environment(object$formation)$formation, andenvironment(object$formation)$dissolution.

Whenedapprox = FALSE in thenetest call, also trims theenvironments ofobject$formation,environment(object$formula)$formation andenvironment(object$formula)$dissolution.

By default all objects are removed from these trimmed environments. Specificobjects may be retained by passing their names as thekeep argument.For the output oftrim_netest to be usable innetsimsimulation, any objects referenced in the formulas should be included in thekeep argument.

Ifas.networkLite = TRUE, convertsobject$newnetwork to anetworkLite object. Ifkeep.fit = FALSE, removesfit (ifpresent) fromobject.

Value

Anetest object with formula environments trimmed, optionally with thenewnetwork element converted to anetworkLite and thefit element removed.

Examples

nw <- network_initialize(n = 100)formation <- ~edges + concurrenttarget.stats <- c(50, 25)coef.diss <- dissolution_coefs(dissolution = ~offset(edges), duration = 10)est <- netest(nw, formation, target.stats, coef.diss,              set.control.ergm = control.ergm(MCMC.burnin = 1e5,                                              MCMC.interval = 1000))print(object.size(est), units = "KB")est.small <- trim_netest(est)print(object.size(est.small), units = "KB")

Truncate Simulation Time Series

Description

Left-truncates simulation epidemiological summary statisticsand network statistics at a specified time step.

Usage

truncate_sim(x, at)

Arguments

x

Object of classnetsim oricm.

at

Time step at which to left-truncate the time series.

Details

This function would be used when running a follow-up simulation from timestepsb toc after a burn-in period from timea tob, where the final time window of interest for data analysis isb toc only.

Value

The updated object of classnetsim oricm.

Examples

param <- param.icm(inf.prob = 0.2, act.rate = 0.25)init <- init.icm(s.num = 500, i.num = 1)control <- control.icm(type = "SI", nsteps = 200, nsims = 1)mod1 <- icm(param, init, control)df <- as.data.frame(mod1)print(df)plot(mod1)mod1$control$nstepsmod2 <- truncate_sim(mod1, at = 150)df2 <- as.data.frame(mod2)print(df2)plot(mod2)mod2$control$nsteps

Convert Unique Identifiers to/from Positional Identifiers

Description

EpiModel refers to its nodes either by positional identifiers(posit_ids), which describe the position of a node in theattr vector, or by unique identifiers(unique_ids), which allow references to nodes even afterthey are deactivated.

Usage

get_unique_ids(dat, posit_ids = NULL)get_posit_ids(dat, unique_ids = NULL)

Arguments

dat

Mainnetsim_dat object containing anetworkDynamicobject and other initialization information passed fromnetsim.

posit_ids

A vector of node positional identifiers (default = NULL).

unique_ids

A vector of node unique identifiers (default = NULL).

Value

A vector of unique or positional identifiers.

All elements

Whenunique_ids orposit_ids is NULL (default)the full list of positional IDs or unique IDs is returned.

Deactivated nodes

When providingunique_ids of deactivated nodes toget_posit_ids,NAs are returned instead and a warning isproduced.


Update a Cumulative Edgelist of the Specified Network

Description

Update a Cumulative Edgelist of the Specified Network

Usage

update_cumulative_edgelist(dat, network, truncate = 0)

Arguments

dat

Mainnetsim_dat object containing anetworkDynamicobject and other initialization information passed fromnetsim.

network

Numerical index of the network for which the cumulativeedgelist will be updated. (May be > 1 for models withmultiple overlapping networks.)

truncate

After how many time steps a partnership that is no longeractive should be removed from the output.

Value

The updatednetsim_dat main list object.

Truncation

To avoid storing a cumulative edgelist too long, thetruncateparameter defines a number of steps after which an edge that is no longeractive is truncated out of the cumulative edgelist.Whentruncate = Inf, no edges are ever removed. Whentruncate = 0, only the active edges are kept. You may want thisbehavior to keep track of the active edges' start step.


Adjust Dissolution Component of Network Model Fit

Description

Adjusts the dissolution component of a dynamic ERGM fit usingthenetest function with the edges dissolutionapproximation method.

Usage

update_dissolution(old.netest, new.coef.diss, nested.edapprox = TRUE)

Arguments

old.netest

An object of classnetest, from thenetest function.

new.coef.diss

An object of classdisscoef, from thedissolution_coefs function.

nested.edapprox

Logical. Ifedapprox = TRUE the dissolutionmodel is an initial segment of the formation model (see details innetest).

Details

Fitting an ERGM is a computationally intensive process when the modelincludes dyad dependent terms. With the edges dissolution approximationmethod of Carnegie et al, the coefficients for a temporal ERGM areapproximated by fitting a static ERGM and adjusting the formationcoefficients to account for edge dissolution. This function provides a veryefficient method to adjust the coefficients of that model when one wants touse a different dissolution model; a typical use case may be to fit severaldifferent models with different average edge durations as targets. Theexample below exhibits that case.

Value

An updated network model object of classnetest.

Examples

## Not run: nw <- network_initialize(n = 1000)# Two dissolutions: an average duration of 300 versus 200diss.300 <- dissolution_coefs(~offset(edges), 300, 0.001)diss.200 <- dissolution_coefs(~offset(edges), 200, 0.001)# Fit the two reference modelsest300 <- netest(nw = nw,                formation = ~edges,                target.stats = c(500),                coef.diss = diss.300)est200 <- netest(nw = nw,                formation = ~edges,                target.stats = c(500),                coef.diss = diss.200)# Alternatively, update the 300 model with the 200 coefficientsest200.compare <- update_dissolution(est300, diss.200)identical(est200$coef.form, est200.compare$coef.form)## End(Not run)

Update Listx Using the Elements of Listnew.x.

Description

Update Listx Using the Elements of Listnew.x.

Usage

update_list(x, new.x)

Arguments

x

A list.

new.x

A list.

Details

This function updates listx by name. Ifx andnew.xelements are not named, the function will not work properly. If a function isprovided to replace an element that was originally not a function, thisfunction will be applied to the original value.

Value

The fullx list with the modifications added bynew.x.


Update Model Parameters for Stochastic Network Models

Description

Updates epidemic model parameters originally set withparam.net and adds new parameters.

Usage

update_params(param, new.param.list)

Arguments

param

Object of classparam.net, output from function of samename.

new.param.list

Named list of new parameters to add to originalparameters.

Details

This function can update any original parameters specified withparam.net and add new parameters. This function would be usedif the inputs toparam.net were a long list of fixed modelparameters that needed supplemental replacements or additions for particularmodel runs (e.g., changing an intervention efficacy parameter but leaving allother parameters fixed).

Thenew.param.list object should be a named list object containingnamed parameters matching those already inx (in which case thoseoriginal parameter values will be replaced) or not matching (in which casenew parameters will be added toparam).

Value

An updated list object of classparam.net, which can be passed to theEpiModel functionnetsim.

Examples

x <- param.net(inf.prob = 0.5, act.rate = 2)y <- list(inf.prob = 0.75, dx.rate = 0.2)z <- update_params(x, y)print(z)

Create the Unique Identifiers for New Nodes

Description

This function is called byappend_core_attr andappends newunique_ids to the created nodes. It also keeps track ofthe already usedunique_ids with thedat$run$last_unique_idvariable.

Usage

update_unique_ids(dat, n.new)

Arguments

dat

Mainnetsim_dat object containing anetworkDynamicobject and other initialization information passed fromnetsim.

n.new

The number of new nodes to giveunique_ids to.

Value

The updatednetsim_dat main list object.


Apply a scenario object to a param.net object

Description

Apply a scenario object to a param.net object

Usage

use_scenario(param, scenario)

Arguments

param

Object of classparam.net, output from function of samename.

scenario

a scenario object usually created from adata.frame ofscenarios using thecreate_scenario_list function. See the vignette"network-model-scenarios".

Value

An updated list object of classparam.net, which can be passed to theEpiModel functionnetsim.

scenario

A scenario is a list containing an "id" field, the name of the scenario anda ".param.updater.list" containing a list of updaters that modifies theparameters of the model at given time steps. If a scenario contains aparameter not defined in theparam object, an error will be produced.See the vignette "model-parameters" for the technical detail of theirimplementation.


Progress Print Module for Deterministic Compartmental Models

Description

This function prints progress from deterministic compartmentalmodels simulated withdcm to the console.

Usage

verbose.dcm(x, type, s = 1)

Arguments

x

If thetype is "startup", then an object of classcontrol.dcm, otherwise the maindf object indcmruns.

type

Progress type, either of "startup" for starting messages beforeall runs, or "progress" for time step specific messages.

s

Current run number, if type is "progress".


Progress Print Module for Stochastic Individual Contact Models

Description

This function prints progress from stochastic individual contactmodels simulated withicm to the console.

Usage

verbose.icm(x, type, s = 1, at = 2)

Arguments

x

If thetype is "startup", then an object of classcontrol.icm; otherwise, an object of classicm_dat, themain data object inicm simulations.

type

Progress type, either of "startup" for starting messages beforeall simulations, or "progress" for time step specific messages.

s

Current simulation number, if type is "progress".

at

Current time step, if type is "progress".


Progress Print Module for Stochastic Network Models

Description

This function prints progress from stochastic network modelssimulated withnetsim to the console.

Usage

verbose.net(x, type, s = 1, at = 2)

Arguments

x

If thetype is "startup", then an object of classcontrol.net; otherwise, an object of classnetsim_dat,the main data object innetsim simulations.

type

Progress type, either of "startup" for starting messages beforeall simulations, or "progress" for time step specific messages.

s

Current simulation number, if type is "progress".

at

Current time step, if type is "progress".


[8]ページ先頭

©2009-2025 Movatter.jp