| Title: | Utility Functions for 'CDMetaPOP' |
| Version: | 2.0.0 |
| Date: | 2026-10-07 |
| Description: | Provides a set of helper functions to launch, analyze, and visualize the output files of 'CDMetaPOP' https://computationalecologylab.github.io/cdmetapop_web/. |
| Imports: | ggplot2, R6, tidyr, tidyselect, dplyr, adegenet, gdistance, graph4lg, poppr, shiny, shinyBS, terra |
| License: | GPL-2 | GPL-3 [expanded from: GPL (≥ 2)] |
| Encoding: | UTF-8 |
| Suggests: | knitr, pkgload, rmarkdown, tidyverse, testthat (≥ 3.0.0) |
| Config/testthat/edition: | 3 |
| VignetteBuilder: | knitr |
| Config/roxygen2/version: | 8.0.0 |
| Language: | en-US |
| RoxygenNote: | 8.0.0 |
| NeedsCompilation: | no |
| Packaged: | 2026-11-03 02:16:53 UTC; domi |
| Author: | Dominique Alò |
| Maintainer: | Dominique Alò <dominiquealo@gmail.com> |
| Repository: | CRAN |
| Date/Publication: | 2026-11-03 03:30:02 UTC |
Default values for one ClassVars column, for a given set of age classes
Description
Looks up .cv_as1_defaults by age-class index. Age classes beyond what
ClassVarsAS1.csv defines (i.e. above age 5) have no principled default,
so the last defined default (age 5) is recycled, with a warning.
Usage
.cv_default_for(field, ages)
Parse ;-separated parts as numbers, erroring on anything unparseable
Description
Parse ;-separated parts as numbers, erroring on anything unparseable
Usage
.dv_as_numbers(parts, field, what)
Arguments
field, what |
Used only to build the error message. |
Validate one DiseaseVars value against its column's rule
Description
Checks only what can be judged from the value itself; rules that depend on
another column (e.g. a state index against n_states) are deferred to
.dv_cross_check().
Usage
.dv_check_value(rule, val, field)
Check the cross-field DiseaseVars rules
Description
Returns a character vector of problem descriptions (empty if consistent)
rather than erroring, so the caller can choose severity: construction and
the launch-time writer treat these as errors, while a single-column
assignment only warns. That split exists because consistency cannot be
maintained assignment-by-assignment – moving from 3 to 4 compartments
needs n_states and initial_conditions to change separately, and
whichever was set first would otherwise be rejected.
Usage
.dv_cross_check(df)
Arguments
df |
A one-row DiseaseVars data frame (header-keyed). |
Look up one field's value in a DiseaseVars data frame
Description
The stored table is keyed by header text while fields are snake_case, so
every internal read goes through this mapping (mirrors PatchVars' use of
.pv_headers[match(field, .pv_fields) + 1], without the id-column offset).
Usage
.dv_get(df, field)
Report cross-field problems as an error or a warning
Description
Report cross-field problems as an error or a warning
Usage
.dv_report_cross(problems, strict)
Arguments
problems |
Output of |
strict |
|
Split a ;-delimited DiseaseVars cell
Description
Split a ;-delimited DiseaseVars cell
Usage
.dv_split(x)
Validate a single (post-'|'/'~'-split) PopVars value against its column's base type rule
Description
Internal helper called once per innermost segment by
.validate_popv_field() – mirrors PatchVars' .pv_check_segment(), with
additional types for PopVars-specific mechanisms (see .popv_rules'
doc comment above for "alleles"/"colon_tokens"/"growth_loo"/
"prob_or_wrightfisher"/"yn_or_prob").
Usage
.popv_check_segment(rule, seg, field, i)
Normalize one batch's xyfilename entry into a flat list of items
Description
Mirrors PatchVars' .pv_normalize_class_vars_patch(): accepts a
PatchVars object, a character string (|-split, each segment resolved
via .popv_resolve_object_segment()), or a list/vector of such items.
Usage
.popv_normalize_object_row(x, resolve = TRUE)
Resolve one xyfilename |-segment to a live PatchVars object or a path
Description
Mirrors PatchVars' .pv_resolve_class_vars_segment(): if seg is the
name of a PatchVars object in .GlobalEnv, return that object (a live
reference); otherwise return seg unchanged, to be treated as a literal
path. xyfilename is the only PopVars field that resolves an object by
name (the matrix fields never do — see .validate_popv_matrix_field()).
Usage
.popv_resolve_object_segment(seg, resolve = TRUE)
Arguments
seg |
A single character segment, or already a |
resolve |
If |
Validate a single (post-'|'-split) PatchVars value against its column's base type rule
Description
Internal helper called once per '|'-separated segment by
.validate_pv_field() – so each segment of e.g. "0.5|N|0.2" is
checked independently against the column's normal bounds/"N"/"E" rule,
the same as if it were the column's only value for that patch.
Usage
.pv_check_segment(rule, seg, field, i)
Arguments
rule |
One element of |
seg |
A single character segment (already split on |
field, i |
Column name and patch row index, for error messages only. |
Value
invisible(NULL); throws on invalid input.
Report which disease columns are still unset
Description
CDMetaPOP needs all eight disease columns present together (see the note at
the top of this file), so a partially filled set cannot produce a runnable
file. Returns the names of the unset ones when SOME but not all are set, and
character(0) when none or all are – the caller warns rather than errors,
since an object part-way through being filled in is a legitimate
intermediate state and CDMetaPOP reports the real problem at launch.
Usage
.pv_disease_unset(df)
Arguments
df |
The stored (58-column) data frame. |
Normalize one patch's class_vars entry into a flat list of items
Description
A "item" is either a ClassVars object or a literal character path.
Handles every shape class_vars/its per-patch elements can arrive in: a
bare ClassVars object; a bare (possibly |-joined) character string,
whose segments are each resolved via .pv_resolve_class_vars_segment();
or a list/vector of multiple such items (multiple timepoints for this
one patch, to be re-joined with | at write time) – recursing so
arbitrarily nested combinations flatten correctly. Uses c() to
concatenate (not unlist()), since unlist() would try to simplify
away the R6 objects living in the list.
Usage
.pv_normalize_class_vars_patch(x, resolve = TRUE)
Arguments
x |
One patch's worth of |
resolve |
Forwarded to |
Value
A flat list, each element a ClassVars object or character path.
Normalize one patch's disease_file entry into a flat list of items
Description
The disease_file counterpart of .pv_normalize_class_vars_patch(); |
separates DiseaseVars files that take effect at successive cdclimate time
steps (CDMetaPOP splits this cell with the same split_or_get() call it
uses for class_vars).
Usage
.pv_normalize_disease_file_patch(x, resolve = TRUE)
Resolve one class_vars |-segment to a live object or a literal path
Description
If seg is the name of a ClassVars object that exists in the global
environment, that object is returned (a live reference – later edits to
it are still reflected when this PatchVars object is eventually
written). Otherwise seg is returned unchanged, to be treated as a
literal file path (the same fallback genes_initialize already uses).
Usage
.pv_resolve_class_vars_segment(seg, resolve = TRUE)
Arguments
seg |
A single character segment. |
resolve |
If |
Details
Deliberately searches .GlobalEnv specifically, not the caller's
environment via parent.frame(): R6 active binding assignment does not
reliably preserve the original call site's environment once the
assignment happens from inside a user-defined function (confirmed
empirically – see chat history), so a call-stack-based lookup would
silently fail for very plausible usage patterns (e.g. building a
PatchVars graph inside a setup function). Searching .GlobalEnv only is
less magic but predictable: works for the common top-level/interactive
workflow this package targets, and the documented limitation (build at
the top level, or pass objects directly instead of by name) is the
tradeoff. Revisit if testers hit this often.
Value
Either a ClassVars object, or seg unchanged.
Resolve one disease_file |-segment to a live object or a literal path
Description
The disease_file counterpart of .pv_resolve_class_vars_segment(), with
the same .GlobalEnv-only lookup and the same rationale – see that
function's documentation. Kept as a separate function rather than
generalizing both: each class already carries its own copy of this pattern
(.popv_resolve_object_segment(), .rv_resolve_popvars_segment()), so a
per-field copy here follows the established shape. Worth unifying across
all four if a fifth reference field ever appears.
Usage
.pv_resolve_disease_file_segment(seg, resolve = TRUE)
Arguments
seg |
A single character segment, or already a |
resolve |
If |
Value
Either a DiseaseVars object, or seg unchanged.
Validate a single (post-'|'-split) RunVars value against its column's rule
Description
Internal helper called once per '|'-separated segment by
.validate_rv_field() – mirrors PopVars' .popv_check_segment(), but
with only the four rule types RunVars actually uses.
Usage
.rv_check_segment(rule, seg, field, i)
Normalize one run's Popvars entry into a flat list of items
Description
A "item" is either a PopVars object or a literal character path. Unlike
PopVars' object fields (which split on |), Popvars splits on ; –
the delimiter CDMetaPOP uses to list multiple PopVars files, one per
species, for a multispecies run. Handles a bare PopVars object; a bare
(possibly ;-joined) character string, each segment resolved via
.rv_resolve_popvars_segment(); or a list/vector of multiple such items;
recursing so nested combinations flatten correctly.
Usage
.rv_normalize_popvars_row(x, resolve = TRUE)
Resolve one Popvars ;-segment to a live PopVars object or a literal
path
Description
Mirrors PopVars' .popv_resolve_object_segment() (and PatchVars'
.pv_resolve_class_vars_segment()): if seg is the name of a PopVars
object in the global environment, that object is returned (a live
reference); otherwise seg is returned unchanged, to be treated as a
literal file path. Searches .GlobalEnv only, for the same reasons
documented in .pv_resolve_class_vars_segment().
Usage
.rv_resolve_popvars_segment(seg, resolve = TRUE)
Arguments
seg |
A single character segment, or already a |
resolve |
If |
Validate and normalize one ClassVars column
Description
Internal helper used by every ClassVars active binding. Validation happens here, at assignment time in R, rather than being deferred to CDMetaPOP – the goal is to catch malformed input before it is ever written to a csv or handed to Python.
Usage
.validate_cv_field(field, values, n)
Arguments
field |
snake_case column name (must be in |
values |
Vector of values to validate; recycled to length |
n |
Expected length (the number of age classes already defined on the object). |
Value
A validated vector of length n: numeric if the column's rule
forbids "N"/"~" values, character otherwise (since "N" and
"~"-joined values cannot be stored as numeric).
Validate and normalize one plain-value DiseaseVars column
Description
Unlike the other classes' field validators there is no row count to recycle against: the file has exactly one row, so exactly one value is accepted. The original string is stored verbatim as character (the literal text CDMetaPOP expects).
Usage
.validate_dv_field(field, value)
Arguments
field |
Column name (a key in |
value |
A single value. |
Validate and normalize the transition_rates column
Description
Accepts either a single raw matrix (numeric or character) or a filepath
string, and is stored as a one-element list column (an R6-style payload
cannot live in an atomic vector). Checked here: squareness, and that every
cell is a number or a "mu;sigma" pair. NOT checked here: the matrix's
dimension against n_states/transmission_mode, which is a cross-field
rule (see .dv_cross_check()).
Usage
.validate_dv_transition_rates(value)
Validate and normalize one plain-value PopVars column
Description
Mirrors PatchVars' .validate_pv_field(): splits on '|' first (if
allow_pipe), then '~' within each '|'-segment (if allow_tilde),
validating each innermost segment independently via
.popv_check_segment(), but always storing the whole original string
verbatim as character (the literal text CDMetaPOP expects).
Usage
.validate_popv_field(field, values, n)
Arguments
field |
Column name (must be a key in |
values |
Vector of values to validate; recycled to length |
n |
Expected length (the number of batches already defined on the object). |
Validate and normalize one matrix-or-path column
Description
Matrix fields (.popv_matrix_fields: the five movement matrices plus
correlation_matrix/subpopmort_file) accept, per batch row, one of:
a single raw
matrix(a lone value, no|/~);a filepath string (which may itself carry
|/~delimiters; stored verbatim, since CDMetaPOP reads the literal text);the literal
"N", only for fields in.popv_matrix_allow_N. Stored as a list column with ONE item per batch (matrix, path string, or"N") – not a flat list of items, since a matrix is never combined with anything (multiple-matrices-over-time/per-sex must be supplied as filepaths; see Key Design Decision 4 / Parking Lot). A list/vector of lengthnassigns one value per batch; a single matrix/string is recycled across all batches.
Usage
.validate_popv_matrix_field(field, values, n)
Arguments
field |
One of |
values |
A single value, or a list/vector of length |
n |
Expected length (the number of batches). |
Validate and normalize the xyfilename object-or-path column
Description
Stored as a list column (R6 objects cannot live in an atomic vector).
Each element is itself a flat list of one or more items, normalized by
.popv_normalize_object_row() – mirrors PatchVars' .validate_pv_class_vars().
Usage
.validate_popv_object_field(field, values, n, resolve = TRUE)
Arguments
values |
A single value, or a list/vector of length |
n |
Expected length (the number of batches). |
resolve |
Forwarded to |
Validate and normalize the class_vars column
Description
Each per-patch element may be a ClassVars() object directly, a
character string (a literal path, the name of a ClassVars object in
the global environment, or several of either joined with | for
CDMetaPOP's temporal-change mechanism – see .pv_resolve_class_vars_segment()),
or a list/vector of multiple such items for the same patch. Stored as a
list column (rather than an atomic vector) since R6 objects cannot be
stored in a plain character/numeric vector; each element is itself a
flat list of one or more items, normalized by
.pv_normalize_class_vars_patch().
Usage
.validate_pv_class_vars(values, n, resolve = TRUE)
Arguments
values |
A single value, or a list/vector of length |
n |
Expected length (the number of patches). |
resolve |
Forwarded to |
Value
A list of length n, each element itself a list of items.
Validate and normalize the disease_file column
Description
The disease_file counterpart of .validate_pv_class_vars(): a list
column whose per-patch elements are each a flat list of DiseaseVars
objects and/or paths. Several patches may reference the SAME DiseaseVars
object, which is the usual case for a spatially uniform disease model.
Usage
.validate_pv_disease_file(values, n, resolve = TRUE)
Validate and normalize one PatchVars column
Description
Internal helper used by every PatchVars active binding except
class_vars, which is handled separately by .validate_pv_class_vars()
since it is the one column that can hold R6 objects rather than plain
values, and so cannot be stored as a vector in private$data the way
every other column is.
Usage
.validate_pv_field(field, values, n)
Arguments
field |
snake_case column name (must be in |
values |
Vector of values to validate; recycled to length |
n |
Expected length (the number of patches already defined on the object). |
Details
If the column's rule has allow_pipe = TRUE, a value may be a single
|-separated string representing multiple values over time (CDMetaPOP's
cdclimate mechanism); each segment is validated independently via
.pv_check_segment(), but the whole string is stored verbatim (since
that is the literal text CDMetaPOP expects), which is why every
pipe-allowed column is stored as character regardless of its base type.
Value
A validated vector of length n: numeric only for x/y (the
sole free_numeric, non-pipe-allowed columns), character otherwise.
Validate and normalize one plain-value RunVars column
Description
Mirrors PopVars' .validate_popv_field() but only splits on | (RunVars
has no ~/: fields). Each |-separated segment is validated
independently via .rv_check_segment(), but the whole original string is
stored verbatim as character (the literal text CDMetaPOP expects).
Usage
.validate_rv_field(field, values, n)
Arguments
field |
Column name (a key in |
values |
Vector of values; recycled to length |
n |
Expected length (the number of runs already defined). |
Validate and normalize the Popvars column
Description
Stored as a list column (R6 objects cannot live in an atomic vector).
Each element is itself a flat list of one or more items (multiple
species per run), normalized by .rv_normalize_popvars_row(). Mirrors
PopVars' .validate_popv_object_field().
Usage
.validate_rv_popvars(values, n, resolve = TRUE)
Arguments
values |
A single value, or a list/vector of length |
n |
Expected length (the number of runs). |
resolve |
Forwarded to |
Create a ClassVars object
Description
Constructs an R6 object representing a CDMetaPOP ClassVars.csv input
file: one row per age/size class, with one column per class-level
parameter (mortality, migration, fecundity, etc.). Columns are edited as
a whole after construction via $, e.g.
myclassvars$age_mortality_out <- c(0, 0, 0.5). **To build the ClassVars object from an
existing ClassVars csv file, use the 'path' argument or the read_cdmetapop() function.
Usage
ClassVars(
ages = 0:5,
body_size_mean = c(31, 53, 92, 123, 147, 184),
body_size_std = c(0, 5, 0, 10, 10, 10),
distribution = c(0.5, 0.25, 0.125, 0.0625, 0.03, 0.015),
sex_ratio = rep(".50~.50", 6),
age_mortality_out = rep(0, 6),
age_mortality_out_stdev = rep(0, 6),
age_mortality_back = c(0, 0, 0, 0, 0, 1),
age_mortality_back_stdev = rep(0, 6),
size_mortality_out = rep(0, 6),
size_mortality_out_stdev = rep(0, 6),
size_mortality_back = rep(0, 6),
size_mortality_back_stdev = rep(0, 6),
migration_out_prob = c(0, 0.1, 0.3, 0.5, 1, 1),
migration_back_prob = rep(1, 6),
straying_prob = rep(0.2, 6),
dispersal_prob = rep(0.2, 6),
maturation = c(0, 1, 1, 1, 1, 1),
fecundity_ind = c(0, 5, 5, 10, 10, 10),
fecundity_ind_stdev = rep(0, 6),
fecundity_leslie = c(0, 2.5, 10, 11.7, 11.743, 15),
fecundity_leslie_stdev = rep(0, 6),
capture_out_prob = rep("N", 6),
capture_back_prob = rep("N", 6),
path = NULL
)
Arguments
ages |
Integer vector of sequential age classes starting at 0
(e.g. |
body_size_mean, body_size_std |
Mean and standard deviation of body size (units chosen by the user) at initialization, per age class. |
distribution |
Proportion of the population distributed to each
age class at initialization. Each value in |
sex_ratio |
Sex ratio per age class, as a |
age_mortality_out, age_mortality_back |
Age-specific mortality
probability |
age_mortality_out_stdev, age_mortality_back_stdev |
Standard
deviation for the above; numeric, |
size_mortality_out, size_mortality_back |
Size-specific mortality
probability |
size_mortality_out_stdev, size_mortality_back_stdev |
Standard
deviation for the above; numeric, |
migration_out_prob, migration_back_prob, straying_prob, dispersal_prob |
Movement probabilities |
maturation |
Probability |
fecundity_ind, fecundity_ind_stdev |
Mean and standard deviation of individual-based fecundity (litter/egg count) per age class if sizeans from 'RunVars' = '"N"'. |
fecundity_leslie, fecundity_leslie_stdev |
Mean and standard deviation of Leslie-matrix fecundity per age class. |
capture_out_prob, capture_back_prob |
Capture/detection probability
|
path |
Optional path to an existing ClassVars csv file. If supplied,
the object is built from that file, with the age classes taken from its
rows (so |
Details
Any column argument left as NULL defaults to the corresponding values
in example_files/classvars/ClassVarsAS1.csv, matched to each requested
age class (recycling the age-5 default, with a warning, for age classes
beyond what that file defines).
Value
An R6 ClassVars object.
Examples
# Default 6-age-class object, matching ClassVarsAS1.csv:
myclassvars <- ClassVars()
# 3 age classes, defaults taken from ClassVarsAS1.csv's first 3 rows:
myclassvars <- ClassVars(ages = c(0, 1, 2))
# Edit a column in place:
myclassvars$age_mortality_out <- c(0, 0, 0.5)
# Add an age class (copies the last row; edit afterward):
myclassvars$add_row()
# or equivalently:
add_rows(myclassvars)
# Build from an existing ClassVars csv, overriding one column:
## Not run:
myclassvars <- ClassVars(path = "classvars/ClassVars_AS1.csv", maturation = 1)
## End(Not run)
Create a DiseaseVars object
Description
Constructs an R6 object representing a CDMetaPOP DiseaseVars.csv input
file, referenced per patch by PatchVars()'s disease_file column. Columns may be edited after
construction, e.g. mydiseasevars$start_disease <- 10. To build the
object from an existing DiseaseVars file, use the path argument or the
read_cdmetapop() function.
Usage
DiseaseVars(
n_states = "3",
initial_conditions = "0.9;0.1;0.0",
transition_rates = "otherfiles/disease/TransitionMatrix_SIR.csv",
susceptible_states = "0",
infection_states = "1",
death_states = "N",
initial_conditions_offspring = "Susceptible",
start_disease = "0",
transmission_mode = "Direct",
disease_resistant = "N",
disease_tolerant = "N",
path = NULL
)
Arguments
n_states |
Number of disease compartments (a whole number, 1 or more). State 0 is always the initial susceptible state. |
initial_conditions |
Proportion of individuals initialized in each
state at the start of the simulation, joined by |
transition_rates |
The state-to-state transition matrix: either a
square |
susceptible_states |
State index considered susceptible, or several
joined by |
infection_states |
State index considered infectious, or several
joined by |
death_states |
State index used for mortality
or |
initial_conditions_offspring |
How newborns' disease states are
assigned: |
start_disease |
Time step at which disease transmission begins (a non-negative whole number). |
transmission_mode |
|
disease_resistant |
The transition(s) modified by the resistance
locus, each written |
disease_tolerant |
Same as |
path |
Optional path to an existing DiseaseVars csv file. If supplied,
the object is built from that file. Any column arguments supplied
alongside |
Details
Any column argument left unsupplied defaults to the basic 3-state SIR model from the user manual's disease quick-start.
The file holds only one row. add_rows() is not available for Disease parameters.
Disease models may vary by patch by providing different DiseaseVars objects to
different patches.
The disease module must also be turned on in PopVars(), by setting
implement_disease to "Out", "Back", or "Both", and each patch must
reference a disease file in PatchVars().
Delimiters: ; is the only delimiter used in this file, separating the
initial state proportions in initial_conditions and indicating which comparments
correspond to which disease state. To vary disease parameters over time,
use the | delimited in PatchVars()'s disease_file column.
States are numbered from 0, and state 0 is assumed to be the initial
susceptible state. With n_states = 3 the valid compartment numbers are 0, 1, and 2.
Under "Indirect" transmission the environmental reservoir occupies one
additional index (n_states), which must be included in transition_rates and
can be the state named for disease_resistant/disease_tolerant.
Value
An R6 DiseaseVars object.
Examples
# The default 3-state SIR model:
mydiseasevars <- DiseaseVars()
# Start the disease dynamics at year 10 instead of year 0:
mydiseasevars$start_disease <- 10
# An SIR model supplying the transition matrix directly. Rows are the state
# moved TO, columns the state moved FROM: 0.5 is the S -> I rate and 0.2 the
# I -> R rate.
transitions <- matrix(0, nrow = 3, ncol = 3)
transitions[2, 1] <- 0.5
transitions[3, 2] <- 0.2
mydiseasevars <- DiseaseVars(transition_rates = transitions)
# Add vertical transmission from infected mothers:
mydiseasevars$initial_conditions_offspring <- "Vertical;0.3"
# Build from an existing DiseaseVars csv, overriding one column:
## Not run:
mydiseasevars <- DiseaseVars(
path = "otherfiles/disease/DiseaseVars_SIR.csv",
start_disease = 5
)
## End(Not run)
Create a PatchVars object
Description
Constructs an R6 object representing a CDMetaPOP PatchVars.csv input
file: one row per patch, with one column per patch-level parameter
(carrying capacity, mortality, migration, growth, fitness, etc.). Columns
are edited as a whole after construction via $, e.g.
mypatchvars$k <- c(300, 300, 500). **To build the PatchVars object from an
existing PatchVars csv file, use the 'path' argument or the read_cdmetapop() function.
Usage
PatchVars(
patch_id = 1:7,
x = c(2540470.832, 2536859.926, 2532969.44, 2539041.489, 2535011.582, 2545325.475,
2527429.642),
y = c(712452.2021, 708059.4624, 705413.5711, 728416.6747, 720257.8531, 726552.0418,
708511.8011),
subpatch_no = c("1", "1", "2", "2", "3", "3", "3"),
k = rep(300, 7),
k_stdev = rep(0, 7),
n0 = rep(150, 7),
natal_grounds = rep(1, 7),
migration_grounds = rep(1, 7),
genes_initialize = c("genes/allelefrequencyA.csv", rep("random", 6)),
class_vars = rep("classvars/ClassVars_AS1.csv", 7),
mortality_out = rep(0, 7),
mortality_out_stdev = rep(0, 7),
mortality_back = rep(0, 7),
mortality_back_stdev = rep(0, 7),
mortality_eggs = rep(0, 7),
mortality_eggs_stdev = rep(0, 7),
migration_out_prob = rep(1, 7),
set_migration = rep("Y", 7),
migration_back_prob = rep(1, 7),
straying_prob = rep(1, 7),
dispersal_prob = rep(1, 7),
growth_temp_out = rep(1, 7),
growth_temp_out_stdev = c(0, 0.2, 0.1, 1, 0.4, 0.2, 0),
grow_days_out = c(155, 150, 150, 150, 150, 150, 150),
grow_days_out_stdev = c(0, 20, 20, 20, 20, 20, 20),
growth_temp_back = c(14, 18, 22, 8, 8, 8, 8),
growth_temp_back_stdev = rep(0, 7),
grow_days_back = c(210, 150, 150, 150, 150, 150, 150),
grow_days_back_stdev = c(0, 20, 20, 20, 20, 20, 20),
capture_prob_out = rep("N", 7),
capture_prob_back = rep("N", 7),
habitat_out = rep(1, 7),
habitat_back = rep(1, 7),
fitness_AA = rep(0, 7),
fitness_Aa = rep(0, 7),
fitness_aa = rep(0, 7),
fitness_BB = rep(0, 7),
fitness_Bb = rep(0, 7),
fitness_bb = rep(0, 7),
fitness_AABB = rep(0, 7),
fitness_AaBB = rep(0, 7),
fitness_aaBB = rep(0, 7),
fitness_AABb = rep(0, 7),
fitness_AaBb = rep(0, 7),
fitness_aaBb = rep(0, 7),
fitness_AAbb = rep(0, 7),
fitness_Aabb = rep(0, 7),
fitness_aabb = rep(0, 7),
comp_coef = rep("0.5;0.1", 7),
disease_file = NULL,
env_res = NULL,
resistant_CC = NULL,
resistant_Cc = NULL,
resistant_cc = NULL,
tolerant_DD = NULL,
tolerant_Dd = NULL,
tolerant_dd = NULL,
resolve_class_vars = TRUE,
resolve_disease_file = TRUE,
path = NULL
)
Arguments
patch_id |
Integer vector of sequential patches starting at 1 (e.g.
|
x, y |
Coordinate locations for each patch. The only columns besides
|
subpatch_no |
Identifier (numeric or character) tagging individuals
to a particular region; reported in output files. Does not support
|
k, k_stdev |
Carrying capacity and its annual standard deviation. |
n0 |
Number of individuals to initialize the patch at year 0. |
natal_grounds, migration_grounds |
|
genes_initialize |
Genotype initialization. Per patch, a value is
|
class_vars |
A |
mortality_out, mortality_back, mortality_eggs |
Density-independent
mortality |
mortality_out_stdev, mortality_back_stdev, mortality_eggs_stdev |
Standard deviation for the above; numeric, |
migration_out_prob |
Emigration probability |
set_migration |
|
migration_back_prob, straying_prob, dispersal_prob |
Movement
probabilities |
growth_temp_out, growth_temp_back |
Temperature values influencing
body size growth; numeric or |
growth_temp_out_stdev, growth_temp_back_stdev |
Standard deviation for the above; numeric. |
grow_days_out, grow_days_back |
Growing days |
grow_days_out_stdev, grow_days_back_stdev |
Standard deviation for the above; numeric. |
capture_prob_out, capture_prob_back |
Capture/detection probability
|
habitat_out, habitat_back |
Habitat quality values for the plasticity module. |
fitness_AA, fitness_Aa, fitness_aa, fitness_BB, fitness_Bb, fitness_bb, fitness_AABB, fitness_AaBB, fitness_aaBB, fitness_AABb, fitness_AaBb, fitness_aaBb, fitness_AAbb, fitness_Aabb, fitness_aabb |
Genotype-specific
fitness/selection values; format depends on |
comp_coef |
Lotka-Volterra competition coefficient(s) for
multispecies applications, |
disease_file |
A |
env_res |
Starting pathogen load in each patch's environmental
reservoir (a non-negative number). Only used when the referenced
|
resistant_CC, resistant_Cc, resistant_cc |
Transition rate for each
genotype at the disease-resistance locus, overriding the matching cell of
the |
tolerant_DD, tolerant_Dd, tolerant_dd |
As the |
resolve_class_vars |
If TRUE, strings entered for class_vars will be checked against the global environment for ClassVars objects of the same name (primarily helpful for temporal changes e.g., "classvars1|classvars2"). If FALSE, class_vars entries must be ClassVars objects or they will be treated as filepaths. |
resolve_disease_file |
As |
path |
Optional path to an existing PatchVars csv file. If supplied,
the object is built from that file, with the patches taken from its rows
(so |
Details
Any column argument left as NULL defaults to the corresponding values
in example_files/patchvars/PatchVarsS1.csv, matched to each requested
patch (recycling the patch-7 default, with a warning, for patches beyond
what that file defines). The eight disease arguments are the exception:
they have no default and are left out of the file entirely unless set (see
Details).
Disease columns. disease_file, env_res, and the six
resistant_*/tolerant_* rates are only part of a PatchVars file when the
disease module is on. CDMetaPOP requires all eight together: it expects
exactly 50 columns when PopVars()'s implement_disease is "N" and
exactly 58 when it is "Out", "Back", or "Both", and rejects either
shape in the other mode. So leaving them unset – the default – produces
the 50-column non-disease file, setting all eight produces the 58-column
one, and setting only some warns, since no file with a partial set can run.
They are absent from PatchVarsS1.csv, which is why they alone have no
default values. Disease states, transition rates, and compartments are
defined in the referenced DiseaseVars() file, not here; these columns only
say which model each patch follows and give the per-patch, per-genotype
values.
Temporal changes via "|": CDMetaPOP lets most PatchVars columns
specify a value that changes based on values in the RunVars object (cdclimate
module), by giving multiple values separated by | in one cell, e.g.
mypatchvars$mortality_out <- "0|0.2|0.5" (mortality is 0 at first,
then 0.2, then 0.5, switching at the timesteps configured in RunVars).
This applies to every column except x, y, patch_id, and
subpatch_no. Because this is a single delimited string, not a
vector, it must always be entered as one quoted character value (e.g.
"0|0.2|0.5"), even for columns that are otherwise numeric – assigning
a plain numeric vector like c(0, 0.2, 0.5) would instead be interpreted
as three different patches' worth of values, not one patch's value over
time. Each |-separated segment is validated independently against the
column's usual rule (numeric bounds, "N"/"E", etc.).
class_vars and genes_initialize may also be entered as strings,
for consistency with every other column's "|" mechanism above, even
though they conceptually reference other R objects/files rather than
plain values. For class_vars specifically: each |-separated segment
of the string is checked against the name of every ClassVars object
that exists in the global environment; if one matches, that object is
used, otherwise the segment is treated as a literal file path, same as
genes_initialize always is. For example, mypatchvars$class_vars <- "cv_year0|cv_year5" will use the actual cv_year0/cv_year5 objects
if they exist as that-named variables in your global environment, or
otherwise treat those strings as paths to existing ClassVars csv files.
Building your ClassVars objects inside a function rather than at the
global level will not be found this way (only the global
environment is searched, deliberately – see
.pv_resolve_class_vars_segment()); in that case, assign the actual
object(s) directly instead (e.g. mypatchvars$class_vars <- cv_year0,
or list(cv_year0, cv_year5) for multiple), without quoting.
A literal path string could, in principle, coincidentally match the name
of an unrelated ClassVars object in your global environment and get
resolved to that object instead of being treated as text. As a
precaution, it's good practice to keep ClassVars/allele-frequency csv
files in their own subdirectories (e.g. classvars/, genes/)
regardless of how you plan to reference them – this keeps the two
namespaces (file paths vs. object names) from ever plausibly colliding.
Value
An R6 PatchVars object.
Examples
# Default 7-patch object, matching PatchVarsS1.csv:
mypatchvars <- PatchVars()
# 3 patches, defaults taken from PatchVarsS1.csv's first 3 rows:
mypatchvars <- PatchVars(patch_id = 1:3)
# 3 patches with one column defined and other columns as defaults:
mypatchvars <- PatchVars(patch_id = 1:3, natal_grounds = c(1,1,0))
# Edit a column in place:
mypatchvars$k <- c(300, 300, 500)
# Add a patch (copies the last row; edit afterward):
mypatchvars$add_row()
# or equivalently:
add_rows(mypatchvars)
# Build from an existing PatchVars csv, overriding one column:
## Not run:
mypatchvars <- PatchVars(path = "patchvars/PatchVarsS1.csv", k = 500)
## End(Not run)
Create a PopVars object
Description
Constructs an R6 object representing a CDMetaPOP PopVars.csv input
file. Unlike ClassVars() (rows = age classes) and PatchVars() (rows =
patches), each row of a PopVars object is its own independent "batch" simulation set.
CDMetaPOP runs each RunVars row (a "run") x each PopVars row (a
"batch") as a separate simulation (see the user manual's run-parameters
section). Columns may be edited as a whole via $, e.g.
mypopvars$matemoveno <- c(6, 6, 4, 6). **To build the PopVars object from an
existing PopVars csv file, use the 'path' argument or the read_cdmetapop() function.
Usage
PopVars(
n_batches = 4,
xyfilename = c("patchvars/PatchVars.csv", "patchvars/PatchVars_anadromy.csv",
"patchvars/PatchVars.csv", "patchvars/PatchVars.csv"),
mate_cdmat = c("cdmats/Patch7_CdmatrixS1.csv", "cdmats/Patch7_CdmatrixS1.csv",
"cdmats/Patch7_CdmatrixS1.csv", "cdmats/Patch7_CdmatrixS1.csv"),
matemoveno = c("6", "6", "4", "6"),
matemoveparA = c("1.346", "1.346", "1.346", "1.346"),
matemoveparB = c("202.4846", "202.4846", "202.4846", "202.4846"),
matemoveparC = c("6", "6", "6", "6"),
matemovethresh = c("6000", "6000", "6000", "6000"),
migrateout_cdmat = c("cdmats/Patch7_Probmatrix_onewayBarriersXRiverineS1.csv",
"cdmats/Patch7_Probmatrix_onewayBarriersXRiverineS1.csv",
"cdmats/Patch7_Probmatrix_onewayBarriersXRiverineS1.csv",
"cdmats/Patch7_Probmatrix_onewayBarriersXRiverineS1.csv"),
migratemoveOutno = c("4", "4", "9", "9"),
migratemoveOutparA = c("0", "0", "0", "0"),
migratemoveOutparB = c("0", "0", "0", "0"),
migratemoveOutparC = c("0", "0", "0", "0"),
migratemoveOutthresh = c("max~max", "max~max", "max~max", "max~max"),
migrateback_cdmat = c("cdmats/Patch7_Probmatrix_onewayBarriersXRiverineS1.csv",
"cdmats/Patch7_Probmatrix_onewayBarriersXRiverineS1.csv",
"cdmats/Patch7_Probmatrix_onewayBarriersXRiverineS1.csv",
"cdmats/Patch7_Probmatrix_onewayBarriersXRiverineS1.csv"),
migratemoveBackno = c("4", "4", "9", "9"),
migratemoveBackparA = c("0", "0", "0", "0"),
migratemoveBackparB = c("0", "0", "0", "0"),
migratemoveBackparC = c("0", "0", "0", "0"),
migratemoveBackthresh = c("max~max", "max~max", "max~max", "max~max"),
stray_cdmat = c("cdmats/Patch7_CdmatrixS1.csv", "cdmats/Patch7_CdmatrixS1.csv",
"cdmats/Patch7_CdmatrixS1.csv", "cdmats/Patch7_CdmatrixS1.csv"),
StrayBackno = c("1", "1", "4", "2"),
StrayBackparA = c("0.01", "0.01", "0.01", "0.01"),
StrayBackparB = c("0.01", "0.01", "0.01", "0.01"),
StrayBackparC = c("0", "0", "0", "0"),
StrayBackthresh = c("max", "max", "max", "max"),
disperseLocal_cdmat = c("cdmats/Patch7_Probmatrix_Dispersal.csv",
"cdmats/Patch7_Probmatrix_Dispersal.csv", "cdmats/Patch7_CdmatrixS1.csv",
"cdmats/Patch7_CdmatrixS1.csv"),
disperseLocalno = c("9", "9", "2", "2"),
disperseLocalparA = c("0.01", "0.01", "0.01", "0.01"),
disperseLocalparB = c("0.01", "0.01", "0.01", "0.01"),
disperseLocalparC = c("0", "0", "0", "0"),
disperseLocalthresh = c("max", "max", "max", "max"),
HomeAttempt = c("mortality", "mortality", "mortality", "mortality"),
sex_chromo = c("2", "2", "2", "2"),
sexans = c("Y", "Y", "Y", "H"),
selfans = c("N", "N", "N", "0.5"),
Freplace = c("Y", "Y", "Y", "Y"),
Mreplace = c("Y", "Y", "Y", "Y"),
AssortativeMate_Model = c("1", "1", "1", "1"),
AssortativeMate_Factor = c("1", "1", "1", "1"),
mature_default = c("age3|age6|age3", "age3", "size300", "N"),
mature_eqn_slope = c("0.13~0.06|0.13~0.06|0.13~0.06", "0.0539", "0.13~0.06",
"0.13~0.06"),
mature_eqn_int = c("-20.28~-8.09|-20.28~-8.09|-20.28~-8.09", "-6.313", "-20.28~-8.09",
"-20.28~-8.09"),
offno = c("2", "2", "2", "2"),
offans_InheritClassVars = c("random", "random", "random", "random"),
equalClutchSize = c("N", "N", "N", "N"),
Egg_Freq_Mean = c("1", "1", "1", "0.5"),
Egg_Freq_StDev = c("1", "1", "0", "0.1"),
Egg_Mean_ans = c("linear", "linear", "exp", "exp"),
Egg_Mean_par1 = c("-445", "-445", "126.07", "126.07"),
Egg_Mean_par2 = c("3.78", "3.78", "0.0061", "0.0061"),
Egg_Mortality = c("N", "0.62", "0.62", "0"),
Egg_Mortality_StDev = c("0", "0", "0.18", "0"),
Egg_FemaleProb = c("0.5", "0.5", "0.5", "0.5"),
startGenes = c("0", "0", "0", "0"),
loci = c("2", "2", "2", "2"),
alleles = c("2", "2", "2", "2"),
muterate = c("0", "0", "0", "0"),
mutationtype = c("random", "random", "random", "random"),
mtdna = c("N", "N", "N", "N"),
cdevolveans = c("N", "N", "N", "N"),
startSelection = c("0", "0", "0", "0"),
implementSelection = c("Out:Back", "Out:Back", "Eggs", "Back"),
betaFile_selection = c("N", "N", "N", "N"),
plasticgeneans = c("N", "N", "N", "N"),
plasticSignalResponse = c("0", "0", "0", "0"),
plasticBehavioralResponse = c("0", "0", "0", "0"),
startPlasticgene = c("0", "0", "0", "0"),
implementPlasticgene = c("Back:0", "Back:0", "Back", "Back"),
growth_option = c("temperature", "temperature", "temperature", "temperature"),
growth_Loo = c("400", "400", "250", "250"),
growth_R0 = c("0.47", "0.47", "0.57", "0.57"),
growth_temp_max = c("10.5", "10.5", "12", "12"),
growth_temp_CV = c("0.33", "0.33", "0.25", "0.25"),
growth_temp_t0 = c("-0.075", "-0.075", "-0.196", "-0.196"),
popmodel = c("packing", "anadromy", "logistic_back", "N"),
popmodel_par1 = c("-0.6821", "-0.6821", "-0.6821", "-0.6821"),
correlation_matrix = c("N", "N", "N", "N"),
subpopmort_file = c("N", "N", "N", "N"),
egg_delay = c("0", "0", "0", "0"),
egg_add = c("mating", "mating", "mating", "mating"),
implement_disease = c("N", "N", "N", "N"),
resolve_xyfilename = TRUE,
path = NULL
)
Arguments
n_batches |
Number of independent batches. Defaults to 4,
matching |
xyfilename |
A |
mate_cdmat, migrateout_cdmat, migrateback_cdmat, stray_cdmat, disperseLocal_cdmat |
A cost-distance/probability |
matemoveno, migratemoveOutno, migratemoveBackno, StrayBackno, disperseLocalno |
Movement function code, |
matemoveparA, matemoveparB, matemoveparC, migratemoveOutparA, migratemoveOutparB, migratemoveOutparC, migratemoveBackparA, migratemoveBackparB, migratemoveBackparC, StrayBackparA, StrayBackparB, StrayBackparC, disperseLocalparA, disperseLocalparB, disperseLocalparC |
Movement function parameters A/B/C (meaning depends on the
corresponding |
matemovethresh, migratemoveOutthresh, migratemoveBackthresh, StrayBackthresh, disperseLocalthresh |
Movement threshold: |
HomeAttempt |
How a migrant that cannot return home is handled:
|
sex_chromo |
Number of sex chromosome combinations: |
sexans |
Reproduction mode: |
selfans |
Selfing: |
Freplace, Mreplace |
Mating-with-replacement flags, |
AssortativeMate_Model |
Assortative mating model: |
AssortativeMate_Factor |
Assortative mating factor, |
mature_default |
Default maturation trigger, e.g. |
mature_eqn_slope, mature_eqn_int |
Size-based maturation probability function parameters. |
offno |
Offspring-count draw choice: |
offans_InheritClassVars |
How offspring inherit |
equalClutchSize |
|
Egg_Freq_Mean, Egg_Freq_StDev |
Egg-laying frequency mean/standard deviation. |
Egg_Mean_ans |
Size-based fecundity function: |
Egg_Mean_par1, Egg_Mean_par2 |
Parameters for the above function. |
Egg_Mortality, Egg_Mortality_StDev |
Egg mortality |
Egg_FemaleProb |
Probability an egg is female, |
startGenes |
Time unit genetic exchange begins. |
loci |
Number of loci (>= 2) |
alleles |
number of starting alleles per
locus (>= 2), or |
muterate |
Allele mutation rate, |
mutationtype |
Mutation model: |
mtdna |
|
cdevolveans |
Selection model/mechanism (open-ended; see manual for
the full grammar, e.g. |
startSelection |
Time unit selection begins. |
implementSelection |
Timing of selection e.g., 'Out', 'Back', 'Eggs', 'Out:Back:Eggs', etc. |
betaFile_selection |
Polygenic-selection beta-value file path, or
|
plasticgeneans |
Phenotypic plasticity signal/response spec (open-
ended; see manual), or |
plasticSignalResponse, plasticBehavioralResponse |
Plasticity signal trigger value and behavioral response threshold. |
startPlasticgene |
Time unit the plastic process begins. |
implementPlasticgene |
Timing of plastic gene implementation ('Out', 'Back', or 'Out:Back') |
growth_option |
Growth function: |
growth_Loo |
Von Bertalanffy L-infinity, or two |
growth_R0, growth_temp_max, growth_temp_CV, growth_temp_t0 |
Remaining growth function parameters. |
popmodel |
Population growth model: |
popmodel_par1 |
Parameter for the |
correlation_matrix |
Patch-level correlation matrix: a |
subpopmort_file |
Sub-population dispersal mortality matrix: a
|
egg_delay |
Integer >= 0: years between mating and gestation/emergence. |
egg_add |
|
implement_disease |
Disease module timing: |
resolve_xyfilename |
If TRUE, strings entered for xyfilename will be checked against the global environment for PatchVars objects of the same name (primarily helpful for temporal changes e.g., "patchvars1|patchvars2"). If FALSE, xyfilename entries must be PatchVars objects or they will be treated as filepaths. |
path |
Optional path to an existing PopVars csv file. If supplied, the
object is built from that file, with the number of batches taken from its
row count (so |
Details
Any column argument left unsupplied defaults to the corresponding values
in example_files/popvars/PopVars.csv, matched to each requested
batch (recycling the row-4 default, with a warning, for rows
beyond what that file defines).
CDMetaPOP reads PopVars.csv headers as dictionary keys, so every column
name below is used verbatim as both the data frame's column name and this
function's argument name.
Delimiters: most columns support CDMetaPOP's | (temporal change) and/or ~ (per-sex) mechanisms.
A few fields use other manual-documented delimiters for a specific
purpose: alleles and implementSelection/implementPlasticgene use
: (per-locus allele counts; ':'-joined timing keywords, respectively),
and growth_Loo uses ; for its two genotype-linked values
(Loo_1;Loo_2) – see .popv_rules' doc comment in class_popvars.R for
the full per-field delimiter design and known open questions.
xyfilename (PatchVars.csv file pointer) accepts a PatchVars()
object directly, a character path, or the name of a PatchVars object in
.GlobalEnv (see PatchVars()'s Details for the identical class_vars
name-resolution mechanism and its caveats).
Matrix fields (mate_cdmat, migrateout_cdmat, migrateback_cdmat,
stray_cdmat, disperseLocal_cdmat, correlation_matrix,
subpopmort_file) each accept, per batch, ONE of: a single raw R
matrix; a file path; or sometimes "N". When providin a matrix as an R variable, the cdclimate and per-sex options are not available.
To vary a matrix over time (the | cdclimate mechanism) or by
sex (~), you must supply file paths, not matrices (e.g.
pv$mate_cdmat <- "surface0.csv|surface5.csv").
When a matrix is supplied, it is written to a csv by
launch_cdmetapop() (named after the R variable; see the package's file
organization documentation). If you want control over a
matrix file's location/format, supply a path and provide the file separately.
Value
An R6 PopVars object.
Examples
# 1 batch, defaults taken from PopVars.csv's first row:
mypopvars <- PopVars(n_batches = 1)
# Default 4-batch object, matching PopVars.csv:
mypopvars <- PopVars()
# Edit a column in place (one value per batch):
mypopvars$matemoveno <- c(6, 6, 4, 6)
# Add a batch (copies the last row; edit afterward):
mypopvars$add_row()
# or equivalently:
add_rows(mypopvars)
# Build from an existing PopVars csv, overriding one column:
## Not run:
mypopvars <- PopVars(path = "popvars/PopVars.csv", matemoveno = 6)
## End(Not run)
Create a RunVars object
Description
Constructs an R6 object representing a CDMetaPOP RunVars.csv input file
– the top of CDMetaPOP's input-file hierarchy. Each row is a separate simulation
"run", and its Popvars field references one or more PopVars()
objects/files. CDMetaPOP executes every run x every
PopVars batch x every Monte Carlo replicate (mcruns) as a separate
simulation. Columns may be edited as a whole after construction,
e.g. myrunvars$runtime <- c(5, 5, 10). **To build the PopVars object from an existing PopVars file,
use the 'path' argument or the read_cdmetapop() function.
Usage
RunVars(
n_runs = 4,
Popvars = c("popvars/PopVars.csv", "popvars/PopVars.csv",
"popvars/PopVars_IntroducePopulation.csv", "popvars/PopVars_Climate.csv"),
sizecontrol = c("Y", "N", "N", "N"),
constMortans = c("1", "1", "1", "1"),
mcruns = c("1", "1", "1", "2"),
runtime = c("5", "5", "5", "5"),
output_years = c("1", "1", "1", "1"),
gridformat = c("cdpop", "cdpop", "cdpop", "cdpop"),
gridsampling = c("Sample", "Sample", "Sample", "Sample"),
summaryOutput = c("N", "N", "N", "N"),
cdclimgentime = c("0|1|2", "0|1|2", "0|5", "0|4|8"),
startcomp = c("0", "0", "0", "0"),
implementcomp = c("Back", "Back", "Back", "Back"),
ncores = c("1", "1", "1", "2"),
resolve_popvars = TRUE,
path = NULL
)
Arguments
n_runs |
Number of runs (rows). Defaults to 4, matching
|
Popvars |
A |
sizecontrol |
|
constMortans |
How constant mortality events compound: |
mcruns |
Number of Monte Carlo replicates (positive integer). |
runtime |
Simulation run time in generations/years (positive integer). |
output_years |
Time steps to write output: a single integer
(e.g. |
gridformat |
Genotype output format: |
gridsampling |
|
summaryOutput |
|
cdclimgentime |
CDClimate module switch times: |
startcomp |
Year Lotka-Volterra competition begins (non-negative integer, multispecies runs only). |
implementcomp |
When to implement competition: |
ncores |
Number of cores for parallel Monte Carlo processing (positive integer). |
resolve_popvars |
If TRUE, strings entered for PopVars will be checked against the global environment for PopVars objects of the same name (primarily helpful for multispecies structure e.g., "popvars1;popvars2"). If FALSE, PopVars entries must be PopVars objects or they will be treated as filepaths. |
path |
Optional path to an existing RunVars csv file. If supplied, the
object is built from that file, with the number of runs taken from its
row count (so |
Details
Any column argument left unsupplied defaults to the corresponding values
in example_files/RunVars.csv, matched to the last row in the example file.
CDMetaPOP reads RunVars.csv headers as dictionary keys (like
PopVars.csv, unlike ClassVars.csv/PatchVars.csv), so every column
name is used verbatim as both the data frame column name and this
function's argument.
Delimiters: output_years and cdclimgentime support temporal variation over time with
| (see user manual for more details).
Popvars is an object-or-path field: it accepts a PopVars() object
directly, a file path to an existing PopVars.csv file, the name of a PopVars object in
.GlobalEnv, or, for a multispecies run,
several of any of these joined with ; (e.g.
"popvars/PopVarsS1.csv;popvars/PopVarsS2.csv"), or a list of them.
Value
An R6 RunVars object.
Examples
# 1 run, defaults taken from RunVars.csv's first row:
myrunvars <- RunVars(n_runs = 1)
# Default 4-run object, matching RunVars.csv:
myrunvars <- RunVars()
# Edit a column in place (one value per run):
myrunvars$runtime <- c(5, 5, 10, 10)
# Add a run (copies the last row; edit afterward):
myrunvars$add_row()
# or equivalently:
add_rows(myrunvars)
# Build from an existing RunVars csv, overriding one column:
## Not run:
myrunvars <- RunVars(path = "RunVars.csv", runtime = 10)
## End(Not run)
Add one or more rows to a cdmetapopR input-file object
Description
Generic function used to add rows to a ClassVars(),
PatchVars(), PopVars(), or RunVars() object. Adds n new rows,
each initialized as a copy of the current last row; edit the new row(s)
afterward via the column active bindings (e.g.
myclassvars$maturation <- ...). What a "row" represents depends on the
class: an age class (ClassVars()), a patch (PatchVars()), a batch
(PopVars()), or a run (RunVars()).
Usage
add_rows(x, n = 1)
Arguments
x |
A cdmetapopR input-file object: a |
n |
Number of rows to add. Defaults to |
Details
A DiseaseVars() object holds exactly one row – CDMetaPOP reads a single
disease model from DiseaseVars.csv and ignores any further rows – so
calling this on one is an error rather than a no-op. Create another
DiseaseVars() object to describe a second disease model.
Value
x, invisibly (modified in place, since x is an R6 object).
Examples
myclassvars <- ClassVars()
add_rows(myclassvars)
myclassvars$ages
Determine the proportions of the age structure of the population
Description
This function summarizes the proportions of the age structure in the simulated population. It is calculated counting the values in the column 'age' of the chosen 'ind' generation.
Usage
age_structure_proportions(
path = system.file("extdata", "Example_dat", package = "cdmetapopR"),
runs = 1,
gen = 49,
species = 0
)
Arguments
path |
path to the simulation folder |
runs |
integer referring to the number of montecarlo simulations output files to examine. It refers to the mcruns option in the RunVars CDMetaPOP input file. Right now it defaults to 1, which would be only one montecarlo run. |
gen |
Simulation run time (generation or year). Refers to runtime in the RunVars of CDMetaPOP input file. Currently defaults to 49. |
species |
If the simulation includes more species... The code for this needs to be adjusted |
Value
a dataframe with a column for each montecarlo run (MC) with the proportion of the population for each given age (in rows) and the last column with the average value across all montecarlo runs at any given age.
Examples
mypath <- system.file("extdata", "Example_dat", package = "cdmetapopR")
age_structure_proportions(path = paste0(mypath, "/"), runs = 1, gen = 9)
Plot Individual-Level Allele Frequencies
Description
Calculates allele frequencies from L#A# genotype columns in CDMetaPOP
ind##.csv or ind##_Sample.csv files.
Usage
allele_frequencies_ind(
path,
year = 0,
run = 0,
batch = 0,
mc = 0,
species = 0,
file_type = "ind",
patches = "all",
loci = NULL,
group_col = "PatchID",
jitter = TRUE
)
Arguments
path |
A dataframe, file path, vector of file paths, run directory, or top-level output directory containing individual files. |
year |
Integer. Year/generation to plot for one-year plots. Defaults to
|
run |
Integer. Run index used when |
batch |
Integer. Batch index used when |
mc |
Integer. Monte Carlo index used when |
species |
Integer. Species index used when |
file_type |
Character. Which individual file type to read. Use
|
patches |
Patch IDs to include. Use |
loci |
Optional vector of loci to include, such as |
group_col |
Column used for grouping frequencies. Defaults to
|
jitter |
Logical. If |
Value
A ggplot object with frequency data in plot$data.
Examples
ex_dir <- system.file("extdata", "Example_dat", package = "cdmetapopR")
allele_frequencies_ind(ex_dir, year = 9)
allele_frequencies_ind(ex_dir, year = 9, jitter = FALSE)
View a cdmetapopR input-file object as a plain data frame
Description
Returns an ordinary (independent) data.frame copy of x's underlying
table – e.g. for inspection with View(), or for any other base-R/
tidyverse workflow expecting a data frame. Editing the returned copy
never affects x itself; edit x through its column active bindings
(e.g. x$maturation <- ...) instead.
Usage
## S3 method for class 'ClassVars'
as.data.frame(x, ...)
Arguments
x |
A cdmetapopR input-file object: a |
... |
Currently unused; present for S3 consistency with
|
Value
A data.frame.
Examples
myclassvars <- ClassVars()
as.data.frame(myclassvars)
Convert CDMetaPOP data to GENEPOP or GENALEX format
Description
This function reads a CDMetaPOP CSV file, processes the genetic loci,
and converts the data into GENEPOP or GENALEX formats.
Usage
cdmetapop_to_gene(path, format = "genepop", output_dir = tempdir())
Arguments
path |
Character string; the file path to the |
format |
A character string indicating the desired output format: "genepop" or "genalex". Genepop is default. |
output_dir |
Character string; the directory where output files will be written. Defaults to tempdir(). |
Value
The function writes the GENEPOP or GENALEX formatted data to the specified output directory.
Examples
path <- system.file("extdata", "Example_dat",
"run0batch0mc0species0", "ind9.csv",
package = "cdmetapopR")
cdmetapop_to_gene(path = path, format = "genepop")
cdmetapop_to_gene(path = path, format = "genalex")
Create cost distance matrix for CDMetaPOP simulation
Description
Takes input coordinates and produces a symmetrical cost distance matrix with options for Euclidean distance, equal distance, or least cost paths based on a provided resistance surface
Usage
create_cdmat(
coords,
method = c("euclidean", "equal", "lcp"),
resistance = NULL
)
Arguments
coords |
A set of spatial coordinates in the form of a 2-column data frame or matrix |
method |
Method for creating the cost distance matrix, must be "euclidean", "equal", or "lcp" |
resistance |
Raster object representing resistance surface for generating cost distance matrix |
Details
Hello
Value
An NxN matrix of cost distances among patch locations
Examples
x <- c(1,2,3,4,5,6)
y <- c(1,2,3,4,5,6)
test <- data.frame(x=x, y=y)
create_cdmat(coords=test)
x <- runif(6, min=0, max=10)
y <- runif(6, min=0, max=10)
coords <- data.frame(x=x, y=y)
r <- terra::rast(nrows=10, ncols=10, xmin = 0, xmax = 10, ymin = 0, ymax = 10)
terra::values(r) <- 1
create_cdmat(coords=coords, method="lcp", resistance=r)
Plot Individual-Level Heterozygosity
Description
Calculates observed and expected heterozygosity from L#A# genotype columns
in CDMetaPOP ind##.csv files.
Usage
heterozygosity_ind(
path,
year = 0,
run = 0,
batch = 0,
mc = 0,
species = 0,
file_type = "ind",
patches = "all",
loci = NULL,
group_col = "PatchID",
jitter = TRUE
)
Arguments
path |
A dataframe, file path, vector of file paths, run directory, or top-level output directory containing individual files. |
year |
Integer. Year/generation to plot for one-year plots. Defaults to
|
run |
Integer. Run index used when |
batch |
Integer. Batch index used when |
mc |
Integer. Monte Carlo index used when |
species |
Integer. Species index used when |
file_type |
Character. Which individual file type to read. Use
|
patches |
Patch IDs to include. Use |
loci |
Optional vector of loci to include, such as |
group_col |
Column used for grouping frequencies. Defaults to
|
jitter |
Logical. If |
Value
A ggplot object with heterozygosity data in plot$data.
Examples
ex_dir <- system.file("extdata", "Example_dat", package = "cdmetapopR")
heterozygosity_ind(ex_dir, year = 9)
heterozygosity_ind(ex_dir, year = 9, jitter = FALSE)
Package import directives for NAMESPACE generation.
Description
Package import directives for NAMESPACE generation.
Launch a CDMetaPOP simulation from R
Description
Builds CDMetaPOP's input files from a RunVars() object (or uses an existing
on-disk run directory) and launches the Python simulation.
When runvars is a RunVars() object, its full set of input files (RunVars ->
PopVars -> PatchVars -> ClassVars, plus cost matrices and other referenced
files) is written to a fresh, timestamped run directory
(cdmetapop_run_<timestamp>/) created under base_dir, and CDMetaPOP is
pointed at it. When runvars is instead a path to a directory containing
a RunVars.csv, or directly to a RunVars csv file, that existing directory
is used as-is and no input files are written.
CDMetaPOP writes its output into a timestamped subfolder of the run directory.
Because CDMetaPOP runs can take a long
time, the simulation launches in the background by default (wait = FALSE)
so the R session is not blocked; set wait = TRUE to block until it
finishes. Either way, read results afterward by pointing the summary_*
functions (e.g. summary_pop()) at the returned run directory.
Usage
launch_cdmetapop(
runvars,
pythonFilepath = "python",
CDMetaPOPFilepath = "CDMetaPOP.py",
base_dir = getwd(),
output_prefix = "output_",
wait = FALSE
)
Arguments
runvars |
A |
pythonFilepath |
Location of the Python executable, or just |
CDMetaPOPFilepath |
Location of CDMetaPOP's |
base_dir |
Parent directory under which the fresh run directory is
created when |
output_prefix |
Name prefix for CDMetaPOP's output subfolder; CDMetaPOP
appends a unix timestamp to it. Defaults to |
wait |
If |
Value
The output run directory, to be used as an argument for output summary
functions, (e.g. summary_pop()) once the run has completed.
Examples
## Not run:
# Build inputs from a RunVars object and launch in the background:
myrun <- RunVars()
run_dir <- launch_cdmetapop(
myrun,
pythonFilepath = "C:/Users/User1/anaconda3/python.exe",
CDMetaPOPFilepath = "C:/Users/User1/CDMetaPOP/src/CDMetaPOP.py"
)
# ... once the run finishes, read results from the same directory:
summary_pop(run_dir, type = "N_initial")
# Or launch an existing on-disk run directory, blocking until it finishes:
launch_cdmetapop("C:/Users/User1/CDMetaPOP/example_files", wait = TRUE)
## End(Not run)
Build ClassVars File from Template
Description
This function loads a provided ClassVars template, allows the user to edit selected areas, and saves the modified version as a new file.
Usage
make_classvars(output_file = "my_new_classvars.csv")
Arguments
output_file |
The name of the output file. Defaults to 'my_new_classvars.csv'. |
Value
A Shiny app instance.
Build DiseaseVars File from Template
Description
This function loads a provided DiseaseVars template, allows the user to edit selected areas, and saves the modified version as a new file.
Usage
make_diseasevars(output_file = "my_new_diseasevars.csv")
Arguments
output_file |
The name of the output file. Defaults to 'my_new_diseasevars.csv'. |
Value
A Shiny app instance.
Build PatchVars File from Template
Description
This function loads a provided PatchVars template, allows the user to edit selected areas, and saves the modified version as a new file.
Usage
make_patchvars(output_file = "my_new_patchvars.csv")
Arguments
output_file |
The name of the output file. Defaults to 'my_new_patchvars.csv'. |
Value
A Shiny app instance.
Build PopVars File from Template
Description
This function loads a provided PopVars template, allows the user to edit selected areas, and saves the modified version as a new file.
Usage
make_popvars(output_file = "my_new_popvars.csv")
Arguments
output_file |
The name of the output file. Defaults to 'my_new_popvars.csv'. |
Value
A Shiny app instance.
Build RunVars File from Template
Description
This function loads a provided runVars template, allows the user to edit selected areas, and saves the modified version as a new file.
Usage
make_runvars(output_file = "my_new_runvars.csv")
Arguments
output_file |
The name of the output file. Defaults to 'my_new_runvars.csv'. |
Value
A Shiny app instance.
Plot Pairwise FST Between Individual Groups
Description
Calculates pairwise FST between groups, usually patches, from L#A#
genotype columns in CDMetaPOP ind##.csv files. FST is calculated per locus
and then averaged across loci for each pair.
Usage
pairwise_fst_ind(
path,
year = 0,
run = 0,
batch = 0,
mc = 0,
species = 0,
file_type = "ind",
patches = "all",
loci = NULL,
group_col = "PatchID"
)
Arguments
path |
A dataframe, file path, vector of file paths, run directory, or top-level output directory containing individual files. |
year |
Integer. Year/generation to plot for one-year plots. Defaults to
|
run |
Integer. Run index used when |
batch |
Integer. Batch index used when |
mc |
Integer. Monte Carlo index used when |
species |
Integer. Species index used when |
file_type |
Character. Which individual file type to read. Use
|
patches |
Patch IDs to include. Use |
loci |
Optional vector of loci to include, such as |
group_col |
Column used for grouping frequencies. Defaults to
|
Value
A ggplot heatmap with pairwise FST data in plot$data.
Examples
ex_dir <- system.file("extdata", "Example_dat", package = "cdmetapopR")
pairwise_fst_ind(ex_dir, year = 9)
Read an existing CDMetaPOP input file into an R6 object
Description
Read an existing CDMetaPOP input file into an R6 object
Usage
read_cdmetapop(filepath, type = "RunVars")
Arguments
filepath |
Path to an existing CDMetaPOP input csv. |
type |
Which input file type |
Value
An R6 object of the corresponding class (e.g. a RunVars()
object).
Examples
## Not run:
myrunvars <- read_cdmetapop("RunVars.csv", type = "RunVars")
mypopvars <- read_cdmetapop("popvars/PopVars.csv", type = "PopVars")
mypatchvars <- read_cdmetapop("patchvars/PatchVarsS1.csv", type = "PatchVars")
myclassvars <- read_cdmetapop("classvars/ClassVars_AS1.csv", type = "ClassVars")
mydiseasevars <- read_cdmetapop("otherfiles/disease/DiseaseVars_SIR.csv", type = "DiseaseVars")
## End(Not run)
Plot CDMetaPOP Class Summary Dynamics
Description
Summarizes and plots data from summary_classAllTime.csv files. Inputs can
be a data frame, one file path, multiple file paths, or a CDMetaPOP output
directory containing summary_classAllTime.csv files.
Usage
summary_class(
data,
type = "age_class",
batch_labels = NULL,
show_mc = TRUE,
show_ci = TRUE,
run = 0,
batch = 0,
mc = 0,
species = 0,
...
)
Arguments
data |
A dataframe, file path ( |
type |
String specifying the plot type: |
batch_labels |
Optional named character vector used to relabel faceted
source groups. Names should match folder names such as |
show_mc |
Logical. If |
show_ci |
Logical. If |
run |
Integer run index used when |
batch |
Integer batch index used when |
mc |
Integer Monte Carlo index used when |
species |
Integer species index used when |
... |
Additional arguments passed to specific plot types. Use |
Value
A ggplot object.
Examples
ex_dir <- system.file("extdata", "Example_dat", package = "cdmetapopR")
summary_class(ex_dir, type = "age_class", n = 10)
summary_class(ex_dir, type = "age_plus_one")
Return CDMetaPOP Output Data as Data Frames
Description
Reads CDMetaPOP population, class, disease-state, or individual output files and returns data frames for custom plotting or downstream summaries.
Usage
summary_dataframe(
data,
type = c("pop", "class", "disease", "ind"),
run = 0,
batch = 0,
mc = 0,
species = 0,
years = NULL,
file_type = "ind",
patches = "all",
state_names = NULL,
cumulative_states = NULL,
state_column = "States_SecondUpdate",
disease_format = c("long", "wide"),
summary_format = c("long", "wide")
)
Arguments
data |
A data frame, file path, vector of file paths, run directory, or top-level CDMetaPOP output directory. |
type |
Character. Which file type to read: |
run |
Integer run index used when |
batch |
Integer batch index used when |
mc |
Integer Monte Carlo index used when |
species |
Integer species index used when |
years |
Optional integer vector of years/generations to include for
|
file_type |
Character. Which individual file type to read for
|
patches |
Patch IDs to include for |
state_names |
Character vector used to name disease states for
|
cumulative_states |
Character vector of disease state names to
calculate as running totals for |
state_column |
Character. Disease-state column to parse for
|
disease_format |
Character. Use |
summary_format |
Character. Use |
Value
A data frame with source metadata columns. For type = "pop" and
type = "class", the default long format includes PatchID or ClassID
indexing values split from pipe-delimited metric columns. For
type = "disease", the default long format includes State and Count
columns.
Examples
ex_dir <- system.file("extdata", "Example_dat", package = "cdmetapopR")
pop_df <- summary_dataframe(ex_dir, type = "pop")
class_df <- summary_dataframe(ex_dir, type = "class")
disease_df <- summary_dataframe(ex_dir, type = "disease")
ind_df <- summary_dataframe(ex_dir, type = "ind", years = 9)
all_mc_pop_df <- summary_dataframe(ex_dir, type = "pop", mc = "all")
Summarize CDMetaPOP Disease States
Description
Scans CDMetaPOP output directories, pulls state totals from
summary_popAllTime_DiseaseStates.csv files, and returns a faceted ggplot
comparing disease states across batches.
Usage
summary_disease(
base_path,
state_names = NULL,
scenario_names = NULL,
cumulative_states = NULL,
state_column = "States_SecondUpdate"
)
Arguments
base_path |
Character. Path to a CDMetaPOP output directory containing
|
state_names |
Character vector. Optional labels for disease states. If
|
scenario_names |
Character vector. Optional labels for batches. The first value labels batch 0, the second labels batch 1, and so on. |
cumulative_states |
Character vector. Names of states to calculate as running totals within each Monte Carlo replicate. |
state_column |
Character. Disease-state column to summarize. Defaults
to |
Value
A ggplot object.
Examples
ex_dir <- system.file(
"extdata",
"Example_dat",
package = "cdmetapopR"
)
summary_disease(ex_dir)
summary_disease(
ex_dir,
state_names = c("Susceptible", "Infected", "Recovered"),
scenario_names = c("Batch 0", "Batch 1"),
cumulative_states = "Recovered"
)
Plot CDMetaPOP Individual File Summaries
Description
Plots simple summaries from CDMetaPOP ind##.csv or
ind##_Sample.csv files. Inputs can be a data frame, one individual file,
multiple individual files, a single run folder, or a top-level CDMetaPOP
output directory containing run folders.
Usage
summary_ind(
path,
type = "age",
year = 0,
years = NULL,
run = 0,
batch = 0,
mc = 0,
species = 0,
file_type = "ind",
patches = "all",
bins = 30
)
Arguments
path |
A dataframe, file path, vector of file paths, run directory, or top-level output directory containing individual files. |
type |
String specifying the plot type: |
year |
Integer. Year/generation to plot for one-year plots. Defaults to
|
years |
Integer vector. Years/generations to include for movement
plots. If |
run |
Integer. Run index used when |
batch |
Integer. Batch index used when |
mc |
Integer. Monte Carlo index used when |
species |
Integer. Species index used when |
file_type |
Character. Which individual file type to read. Use
|
patches |
Patch IDs to include. Use |
bins |
Integer. Number of bins for continuous histograms. Defaults to
|
Value
A ggplot object.
Examples
ex_dir <- system.file("extdata", "Example_dat", package = "cdmetapopR")
summary_ind(ex_dir, type = "age", year = 9)
summary_ind(ex_dir, type = "age_size", year = 9)
summary_ind(ex_dir, type = "movement", years = 0:9, batch = 1, mc = 1)
Map CDMetaPOP Patch Abundance
Description
Creates a faceted patch map from CDMetaPOP ind##.csv or
ind##_Sample.csv files. Points are drawn at patch coordinates and scaled
by the number of individuals in each patch.
Usage
summary_patch_map(
path,
type = "abundance",
years = 0,
run = 0,
batch = 0,
mc = 0,
species = 0,
file_type = "ind",
patches = "all",
states = NULL,
facet_by_state = FALSE,
locus = NULL,
allele = NULL,
metric = "Ho",
labels = FALSE,
log_scale = FALSE,
crs = NULL
)
Arguments
path |
A dataframe, file path, vector of file paths, run directory, or top-level output directory containing individual files. |
type |
Character. What to map: |
years |
Integer vector. Years/generations to map. Defaults to |
run |
Integer. Run index used when |
batch |
Integer. Batch index used when |
mc |
Integer. Monte Carlo index used when |
species |
Integer. Species index used when |
file_type |
Character. Which individual file type to read. Use
|
patches |
Patch IDs to include. Use |
states |
Optional vector of disease states to include. If |
facet_by_state |
Logical. If |
locus |
Locus to map for genetic summaries, such as |
allele |
Allele to map for |
metric |
Heterozygosity metric to map for |
labels |
Logical. If |
log_scale |
Logical. If |
crs |
Optional coordinate reference system label. For example, use
|
Value
A ggplot object with patch-level summary data in plot$data.
Examples
ex_dir <- system.file("extdata", "Example_dat", package = "cdmetapopR")
summary_patch_map(ex_dir, years = c(0, 5, 9), crs = 5070)
summary_patch_map(ex_dir, years = c(0, 5, 9), states = 1, crs = 5070)
summary_patch_map(ex_dir, years = c(0, 9), states = c(0, 1), facet_by_state = TRUE, crs = 5070)
summary_patch_map(ex_dir, type = "allele_frequency", years = 9, locus = "L0", allele = "A1")
summary_patch_map(ex_dir, type = "heterozygosity", years = 9, locus = "L0", metric = "Ho")
Plot CDMetaPOP Population Summary Dynamics
Description
Summarizes and plots data from summary_popAllTime.csv files. Inputs can be
a data frame, one file path, multiple file paths, or a CDMetaPOP output
directory containing summary_popAllTime.csv files.
Usage
summary_pop(
data,
type = "N_initial",
batch_labels = NULL,
show_mc = TRUE,
show_ci = TRUE,
run = 0,
batch = 0,
mc = 0,
species = 0,
...
)
Arguments
data |
A dataframe, file path ( |
type |
String specifying the plot type: |
batch_labels |
Optional named character vector used to relabel faceted
source groups. Names should match folder names such as |
show_mc |
Logical. If |
show_ci |
Logical. If |
run |
Integer run index used when |
batch |
Integer batch index used when |
mc |
Integer Monte Carlo index used when |
species |
Integer species index used when |
... |
Additional arguments passed to specific plot types. Use
|
Value
A ggplot object.
Examples
ex_dir <- system.file("extdata", "Example_dat", package = "cdmetapopR")
summary_pop(ex_dir, type = "N_initial")
summary_pop(ex_dir, type = "sex")
summary_pop(ex_dir, type = "mature", include_yys = TRUE)
summary_pop(ex_dir, type = "allelic_richness")
summary_pop(ex_dir, type = "het")
Write a cdmetapopR input-file object to a csv file
Description
Writes a single ClassVars(), PatchVars(), PopVars(), RunVars(), or
DiseaseVars() object to a csv file in CDMetaPOP's input format: the same
headers, column order, and unquoted values that launch_cdmetapop() writes.
Usage
write_cdmetapop(x, file, overwrite = FALSE)
Arguments
x |
A |
file |
File name or path of the csv to write. A bare file name (e.g.
|
overwrite |
If |
Details
This is a convenience for writing one object at a time. It is not needed to
run a simulation, since launch_cdmetapop() writes every input file
automatically. Only x itself is written:
References stored as file paths (e.g. a
class_varsvalue of"classvars/ClassVars_AS1.csv", or a cost-distance matrix path) are written exactly as entered. They are not checked, and the files they point to are not written or copied.A reference cell holding a live R object – a
PopVars(),PatchVars(),ClassVars(), orDiseaseVars()object, or a rawmatrix– has no file path to write, so that cell is written asNAand a warning lists the affected cells. To keep the reference, write that object or matrix to its own file first and assign its path instead.A
PatchVars()object's eight disease columns are written only if at least one of them is set, matching the 50-or-58 column file CDMetaPOP expects (seePatchVars()).
Value
file, invisibly.
Examples
myclassvars <- ClassVars()
out <- file.path(tempdir(), "myclassvars.csv")
write_cdmetapop(myclassvars, file = out)
# The written file can be read back in:
read_cdmetapop(out, type = "ClassVars")