| Type: | Package |
| Title: | Computer Simulations of 'SNP' Data |
| Version: | 1.3.0 |
| Date: | 2026-11-18 |
| Revision: | Hardy Hedgehog |
| Description: | Allows to simulate SNP data using genlight objects. For example, it is straight forward to simulate a simple drift scenario with exchange of individuals between two populations or create a new genlight object based on allele frequencies of an existing genlight object. Also more complicated, fully fledged population viability analyses are possible. |
| Encoding: | UTF-8 |
| Depends: | R (≥ 4.1.0), dartR.base (≥ 1.3.0), dartR.data, ggplot2, dartR.popgen |
| Imports: | adegenet (≥ 2.0.0), bigsnpr, shiny, fields, utils, methods, stringi, data.table, Rcpp, shinyBS, shinyjs, shinythemes, shinyWidgets, hierfstat, foreach, ggrepel, dplyr, doParallel |
| Suggests: | bigstatsr, testthat (≥ 3.0.0), knitr, rmarkdown |
| VignetteBuilder: | knitr |
| License: | GPL (≥ 3) |
| RoxygenNote: | 7.3.3 |
| NeedsCompilation: | no |
| Packaged: | 2026-11-18 23:42:52 UTC; s425824 |
| Author: | Jose L. Mijangos [aut, cre], Bernd Gruber [aut], Arthur Georges [aut], Carlo Pacioni [aut], Diana Robledo-Ruiz [aut], Peter J. Unmack [ctb], Oliver Berry [ctb] |
| URL: | https://green-striped-gecko.github.io/dartR/, https://github.com/green-striped-gecko/dartR.sim |
| BugReports: | https://github.com/green-striped-gecko/dartR.sim/issues |
| Maintainer: | Jose L. Mijangos <luis.mijangos@gmail.com> |
| Repository: | CRAN |
| Date/Publication: | 2026-11-19 17:20:02 UTC |
Comparing simulations against theoretical expectations
Description
Comparing simulations against theoretical expectations
Usage
gl.diagnostics.sim(
x,
Ne = NULL,
iteration = 1,
pop_he = 1,
pops_fst = c(1, 2),
plot_theme = theme_dartR(),
plot.file = NULL,
plot.dir = NULL,
verbose = NULL
)
Arguments
x |
Output from function |
Ne |
Effective population size used for the theoretical expectations: one value, or one value per population [default NULL, the expected Ne stored by gl.sim.WF.run() in sim.vars$ne_expected]. |
iteration |
Iteration number to analyse [default 1]. |
pop_he |
Population (position in popNames) in which the rate of loss of heterozygosity is compared against theoretical expectations [default 1]. |
pops_fst |
Pair of populations (positions in popNames) in which FST is compared against theoretical expectations [default c(1,2)]. |
plot_theme |
User specified theme [default theme_dartR()]. |
plot.file |
Name for the RDS binary file to save (base name only, exclude extension) [default NULL]. |
plot.dir |
Directory in which to save files [default = working directory]. |
verbose |
Verbosity: 0, silent or fatal errors; 1, begin and end; 2, brief progress messages; 3, progress and results summary; 5, full report [default 2, unless specified using gl.set.verbosity]. |
Details
Two plots compare the simulations against theoretical expectations:
Heterozygosity. The expected He under drift in an isolated population (Crow & Kimura, 1970, p. 329) is
He(t) = He(t0) (1 - 1/(2Ne))^(t - t0),
where t0 is the first stored generation and He(t0) the observed He in population pop_he at t0. Five curves are drawn, for Ne, 1.25 Ne, ... 2 Ne, to show how sensitive the expectation is to Ne. Migration slows the loss of heterozygosity, so with dispersal the observed He is expected to fall more slowly than these curves.
FST. The expected FST between the populations in pops_fst is computed generation by generation with the identity-by-descent recursion of the island model simulated by
gl.sim.WF.run: in each generation, genes are exchanged between populations (a fraction m of each population are immigrants, m = number_transfers / N in generations with dispersal, coming equally from the other populations), then drift acts within populations (Ne). FST = (F0 - F1) / (1 - F1), where F0 and F1 are the probabilities of identity by descent of two genes within and between populations. The recursion starts at the first stored generation of phase 2 from the observed FST. At equilibrium, for n populations and small m, this is close to 1 / (1 + 4 Ne m n / (n - 1)) (Takahata, 1983, with m counting only immigrants from other populations). The expectation is available without dispersal (m = 0) and for dispersal_type "all_connected"; "line", "circle" and dispersal files are not island models and stop the function.
Observed FST is Nei's estimator (hierfstat::pairwise.neifst).
Value
Invisibly, a list with the plot (plot), a data frame of observed and expected He by generation and Ne (he), and a data frame of observed and expected FST by generation (fst). The plot is printed.
Author(s)
Author(s): Luis Mijangos. Custodian: Luis Mijangos – Post to https://groups.google.com/d/forum/dartr
References
Crow JF, Kimura M. An introduction to population genetics theory. Harper and Row, New York. 1970.
Takahata N. Gene identity and genetic differentiation of populations in the finite island model. Genetics. 1983;104(3):497-512.
See Also
Other simulation functions:
gl.report.nall(),
gl.sim.Neconst(),
gl.sim.WF.run(),
gl.sim.WF.table(),
gl.sim.create_dispersal(),
gl.sim.emigration(),
gl.sim.ind(),
gl.sim.ind.af(),
gl.sim.mutate(),
gl.sim.offspring()
Examples
ref_table <- gl.sim.WF.table(file_var=system.file('extdata',
'ref_variables.csv', package = 'dartR.sim'),interactive_vars = FALSE)
res_sim <- gl.sim.WF.run(file_var = system.file('extdata',
'sim_variables.csv', package ='dartR.sim'),ref_table=ref_table,
interactive_vars = FALSE,number_pops_phase2=2,population_size_phase2="10 10")
res <- gl.diagnostics.sim(x=res_sim, Ne=10)
head(res$fst)
Report allelic retention and simulate a rarefaction curve
Description
This function reports per-population allele counts and simulates a rarefaction-style curve showing the proportion of the dataset's total allelic diversity expected as progressively more individuals are sampled.
Usage
gl.report.nall(
x,
simlevels = seq(1, nInd(x), 5),
reps = 10,
plot.colors.pop = gl.colors("dis", verbose = 0),
ncores = 2,
plot.display = TRUE,
plot.theme = theme_dartR(),
plot.dir = NULL,
plot.file = NULL,
verbose = NULL
)
Arguments
x |
Name of the genlight/dartR object containing the SNP data. Loci with no calls in any one population are removed before the analysis; otherwise missing data are allowed, as allele frequencies are computed from the called genotypes [required]. |
simlevels |
A vector of whole numbers of at least 1 with the sample sizes (numbers of individuals) to simulate [default seq(1,nInd(x),5)]. |
reps |
Number of replicate simulated samples per sample size, a whole number of at least 1 [default 10]. |
plot.colors.pop |
A color palette for population plots or a list with as many colors as there are populations in the dataset [default gl.colors("dis")]. |
ncores |
Number of cores to be used for parallel processing, a whole number of at least 1. With 1, the simulations run in the current R session without starting a cluster [default 2]. |
plot.display |
Specify if plot is to be produced [default TRUE]. |
plot.theme |
A 'ggplot2' theme object for styling the plot [default theme_dartR()]. |
plot.dir |
Directory to save the plot RDS files [default as specified by the global working directory or tempdir()]. |
plot.file |
Filename (minus extension) for the RDS plot file [Required for plot save]. |
verbose |
Verbosity: 0, silent or fatal errors; 1, begin and end; 2, progress log; 3, progress and results summary; 5, full report [default 2, unless specified using gl.set.verbosity]. |
Details
The function estimates how sampling effort affects observed allelic diversity.
All individuals are pooled into a single group, and the allele frequencies of
the pool are computed. For each sample size in 'simlevels', 'reps' samples of
that many individuals are simulated from the pooled frequencies with
gl.sim.ind, i.e. under Hardy-Weinberg and linkage equilibrium.
The curve is therefore the expectation for a panmictic population with the
allele frequencies of the whole dataset, not a subsampling of the real
individuals: structure between populations is not part of it, and alleles
that are rare in the pool can be missed even at the full sample size, so the
curve need not reach 1.
The number of alleles counts 1 for a fixed locus and 2 for a polymorphic one. The maximum is the count in the pooled real data; all simulation outputs and per-population observations are divided by this maximum and expressed as a proportion of alleles retained.
For each target sample size, replicated samples are aggregated to yield the mean, minimum, and maximum proportions of alleles retained. A plot is produced showing (i) the mean rarefaction curve with an uncertainty ribbon (min–max across replicates) and (ii) points for each empirical population at its observed sample size and retained proportion.
How to use the output
- Assess genetic diversity and sampling sufficiency. The curve indicates how quickly allelic diversity accumulates with additional individuals, and where diminishing returns begin. - Interpret population points relative to the curve.
Above the curve: population retains more allelic diversity than expected for its sample size (e.g., unusually high diversity or more private/low-frequency alleles).
On/within the ribbon: diversity consistent with a sample of that size from a panmictic population with the pooled allele frequencies.
Below the curve: population retains fewer alleles than expected, suggesting reduced diversity (e.g., drift, bottleneck), uneven missingness, or data-quality issues.
Value
A list with three elements (the input object is not modified):
'sim': 'data.frame' with columns 'Npop' (sample size), 'mnall' (mean proportion retained), 'low' (minimum), and 'high' (maximum) across replicates.
'points': 'data.frame' with observed per-population values at their actual sample sizes (columns include 'popname', 'Npop', and scaled 'N.all').
'p1': a 'ggplot' object showing the rarefaction curve, uncertainty ribbon, and per-population points.
Author(s)
Author(s): Bernd Gruber. Custodian: Bernd Gruber – Post to https://groups.google.com/d/forum/dartr
See Also
Other simulation functions:
gl.diagnostics.sim(),
gl.sim.Neconst(),
gl.sim.WF.run(),
gl.sim.WF.table(),
gl.sim.create_dispersal(),
gl.sim.emigration(),
gl.sim.ind(),
gl.sim.ind.af(),
gl.sim.mutate(),
gl.sim.offspring()
Examples
dummy <- gl.report.nall(possums.gl[c(1:5,31:35),], simlevels=seq(1,10,3),
reps=5, ncores=2)
Simulates a population at mutation-drift equilibrium with constant Ne
Description
This function simulates SNP genotypes of a population of constant effective size at mutation-drift equilibrium, using Wright's beta distribution for allele frequencies.
Usage
gl.sim.Neconst(
ninds,
nlocs,
mutation_rate = 1e-08,
fbm = isTRUE(getOption("dartR_fbm")),
verbose = NULL
)
Arguments
ninds |
Number of individuals in the population, which is also its effective population size (Ne); a whole number of at least 2 [required]. |
nlocs |
Number of loci (SNPs) to simulate, a whole number of at least 1 [required]. |
mutation_rate |
Mutation rate per locus per generation, a number greater than 0 [default 1e-8]. |
fbm |
If TRUE, the genotypes of the returned object are held in a
file-backed matrix (@fbm, see |
verbose |
Verbosity: 0, silent or fatal errors; 1, begin and end; 2, brief progress messages; 3, progress and results summary; 5, full report [default 2, unless specified using gl.set.verbosity]. |
Details
At mutation-drift equilibrium under symmetric mutation between two alleles, the allele frequency p of a locus follows Wright's beta distribution, with density proportional to (p(1 - p))^(theta - 1), where theta = 4 * ninds * mutation_rate.
The population has 2 * ninds gene copies. For each locus, the number of copies k of one allele is drawn from 1 to 2 * ninds - 1 with probability proportional to (k/2N (1 - k/2N))^(theta - 1), i.e. conditioned on the locus being polymorphic, and the k copies are placed at random among the gene copies of the individuals. Every locus is therefore a SNP.
When theta is much smaller than 1 (e.g. mutation_rate = 1e-8 for any realistic ninds), the spectrum is the neutral site frequency spectrum, proportional to 1/k + 1/(2N - k), and does not depend on mutation_rate. mutation_rate changes the output only when theta approaches 1 or more, when intermediate frequencies become more common.
Individuals are named "1", "2", ..., loci "Loc1", "Loc2", ..., all individuals belong to population "pop1", and alleles are set to the placeholder "A/C".
Value
A genlight object representing the simulated population, file-backed (@fbm) if fbm = TRUE and gen-backed (@gen) otherwise.
Author(s)
Author(s): Bernd Gruber. Custodian: Bernd Gruber – Post to https://groups.google.com/d/forum/dartr
See Also
Other simulation functions:
gl.diagnostics.sim(),
gl.report.nall(),
gl.sim.WF.run(),
gl.sim.WF.table(),
gl.sim.create_dispersal(),
gl.sim.emigration(),
gl.sim.ind(),
gl.sim.ind.af(),
gl.sim.mutate(),
gl.sim.offspring()
Examples
# Simulate a population with 50 individuals and 4000 loci
gg <- gl.sim.Neconst(ninds = 50, nlocs = 4000, mutation_rate = 1e-8, verbose = 0)
dartR.popgen::gl.sfs(gg)
Runs Wright-Fisher simulations
Description
This function simulates populations made up of diploid organisms that reproduce in non-overlapping generations. Each individual has a pair of homologous chromosomes that contains interspersed selected and neutral loci. For the initial generation, the genotype for each individual's chromosomes is randomly drawn from distributions at linkage equilibrium and in Hardy-Weinberg equilibrium.
The simulations will take a little longer the first time you use the function gl.sim.WF.run() in an R session because C++ functions must be compiled.
Usage
gl.sim.WF.run(
file_var,
ref_table,
x = NULL,
file_dispersal = NULL,
number_iterations = 1,
every_gen = 10,
sample_percent = 50,
store_phase1 = FALSE,
store_founders = FALSE,
store_pedigree = FALSE,
interactive_vars = TRUE,
seed = NULL,
verbose = NULL,
...
)
Arguments
file_var |
Path of the variables file 'sim_variables.csv' (see details) [required if interactive_vars = FALSE]. |
ref_table |
Reference table created by the function
|
x |
Genlight object containing the SNP data to extract values for some simulation variables (see details) [default NULL]. |
file_dispersal |
Path of the file with the dispersal table created with
the function |
number_iterations |
Number of iterations of the simulations [default 1]. |
every_gen |
Generation interval at which simulations should be stored in a genlight object [default 10]. |
sample_percent |
Percentage of individuals, from the total population, to sample and save in the genlight object every generation. The number is rounded up to an even number, e.g. 50 percent of 50 individuals stores 26 [default 50]. |
store_phase1 |
Whether to store simulations of phase 1 in genlight objects [default FALSE]. |
store_founders |
Whether to store the founders of the first phase simulated, before they reproduce, as "generation_0" [default FALSE]. Their ind.metrics hold F_founder, the proportion of loci whose two copies are identical by descent (0 unless real_inbreeding = TRUE), and F_founder_map, the same proportion measured along the map. Founders have no parents (pat and mat are NA). |
store_pedigree |
Whether to return the pedigree of every individual of every generation, sampled or not, as the attribute "pedigree" of each iteration: a data frame with id (as in indNames of the stored genlights), pat, mat (NA for founders), generation (0 for founders), pop, F_founder (founders only, NA otherwise) and in_population (FALSE for offspring sampled by sample_families that did not join the population). Read it with attr(res[["iteration_1"]], "pedigree") [default FALSE]. |
interactive_vars |
Run a shiny app to input interactively the values of simulations variables [default TRUE]. |
seed |
Set the seed for the simulations. This calls set.seed(), so it also sets the random number stream of the R session for any code run afterwards [default NULL]. |
verbose |
Verbosity: 0, silent or fatal errors; 1, begin and end; 2, brief progress messages; 3, progress and results summary; 5, full report [default 2, unless specified using gl.set.verbosity]. |
... |
Any simulation variable of 'sim_variables.csv' and its value, e.g. gen_number_phase2 = 20 or local_adap = "1 2". The value replaces the one in the csv file or the Shiny app. Names that are not simulation variables stop the function with an error. |
Details
Values for the simulation variables can be entered in a Shiny app (interactive_vars = TRUE) or in the file 'sim_variables.csv', which can be found by typing in the R console: system.file('extdata', 'sim_variables.csv', package = 'dartR.sim').
The model, generation by generation:
Migration. Every transfer_each_gen generations, each connected pair of populations swaps number_transfers individuals in each direction (half males, half females; a single transfer alternates between sexes). With dispersal_type "line", "circle" or "all_connected", each pair of connected populations is processed once. A file from
gl.sim.create_dispersalis used row by row.Reproduction. N/2 monogamous pairs are formed at random, except that a proportion sib_mating of the pairs are full siblings (see Inbreeding below). The number of offspring per pair follows a negative binomial distribution with mean number_offspring and size variance_offspring: large values of variance_offspring give Poisson family sizes (Ne close to N), small values increase the variance of family size and lower Ne. Sex is assigned at random.
Recombination. For each gamete, the number of recombination events is Poisson with mean equal to the map length in Morgans rounded up; each event places a crossover between two loci with probability proportional to the recombination rate c of the reference table, so the mean number of crossovers per gamete equals the map length. There is no interference. recombination_males = FALSE switches recombination off in males.
Mutation. Each offspring receives, with probability mut_rate, one new allele at a locus drawn from the loci of type mutation_neu, mutation_del or mutation_adv that are not segregating. A locus returns to this pool when its new allele is lost.
Selection. Fitness is multiplicative across loci: 1 - s for the homozygote of the simulated allele, 1 - hs for heterozygotes and 1 otherwise; advantageous alleles have negative s. With the "relative" model, the next generation is sampled from the offspring without replacement with probability proportional to fitness; this weakens selection when the offspring pool is not much larger than N (a warning is printed at verbose >= 1 when it is less than 3 times N). With the "absolute" model, an offspring survives with probability min(1, fitness / genetic_load), so there is no selection among offspring whose fitness is at least genetic_load. local_adap lists the populations where advantageous alleles are under selection (s = 0 elsewhere). clinal_adap gives the first and last populations of a cline along which advantageous s is multiplied by 1, 1 - k, 1 - 2k, ... with k = clinal_strength / 100 (floored at 0); outside the cline s = 0.
Next generation. N/2 males and N/2 females are sampled from the offspring. If there are too few of either sex, the population is extinct: the iteration stops and the generations stored so far are returned.
With phase1 = TRUE, phase 2 starts from individuals sampled from the phase-1 populations, without replacement unless phase 2 is larger.
If a genlight object is used (real_pops, real_pop_size, real_loc, real_freq or real_inbreeding), the simulated allele is the alternative allele of the genlight (genotype 2). Loci without calls in a population take the frequency across all populations. real_pop_size sets the sizes of the first phase simulated, rounded up to even numbers.
Inbreeding. sib_mating_phase1 and sib_mating_phase2 set the proportion of pairs that are full siblings (brother and sister with the same father and mother), one value or one per population (space delimited and in quotes); NULL or 0 is random mating. At equilibrium the inbreeding coefficient is F = b / (4 - 3b) for a proportion b of sib matings. Sib matings need females with a brother among the parents, so when families are small (low number_offspring) fewer sib matings than asked for can take place and a warning is printed at verbose >= 1. With real_inbreeding = TRUE, F = 1 - Ho / He is estimated in each population of x (on the loci of chromosome_name when real_loc = TRUE; negative values are set to 0) and x must have as many populations as the first phase simulated. The founders are then made inbred: along the chromosome they alternate between stretches whose two copies are identical by descent (a fraction F of the map, mean length 25 cM, as in the offspring of full siblings) and stretches drawn independently. In a phase whose sib_mating is NULL, the proportion of sib matings is set to b = 4F / (1 + 3F), which keeps F in the following generations; a sib_mating value that is set is used instead. Founders are unrelated to each other, so the first generation (their offspring) has F close to 0; F returns close to the value in x from the second generation. To store only generations at equilibrium, use phase 1 as a burn-in (phase1 = TRUE, store_phase1 = FALSE). inbreeding_founders (one value or one per population, in the order of the populations) gives the founders' F directly and replaces the value estimated from x, with or without real_inbreeding; negative values are set to 0. It is useful because heterozygote dropout inflates F in the full locus set: estimate F on high call-rate loci and pass it here while x keeps all loci for the allele frequencies.
Differentiation. With real_freq = TRUE, each population's founders are drawn from its sample frequencies in x, which carry sampling noise and so inflate FST among founders. real_freq_shrink = "auto" shrinks them toward their mean, q' = mean + lambda (q - mean), with lambda chosen so the between-population variance of the frequencies equals that of x after removing the variance expected from sampling; an FST estimator that corrects for sample size (e.g. Hudson's) then gives about the same value for the founders as for x, whatever the population size. A number sets lambda directly; NULL (default) does not shrink. The lambda used is stored in sim.vars$freq_shrink_lambda. Drift after the founders raises FST again, faster in small populations.
Migration. With real_migration = TRUE, the number of individuals each pair of populations swaps per generation is set from x's FST (Hudson's, mean over pairs of populations). Each pair swaps number_transfers individuals in each direction, so with n populations and dispersal_type "all_connected" the island model gives an equilibrium FST = 1 / (1 + 4 n T) for T transfers per generation (Takahata, 1983) when Ne = N. FST depends on Ne m rather than N m, so T = (1 / FST - 1) / (4 n) x N / Ne (mean over populations of N / Ne, with Ne the expected Ne, see below) replaces number_transfers. T can be fractional: each pair moves floor(T) or floor(T) + 1 individuals, the latter with probability T - floor(T). It applies to the phases with dispersal, which must be "all_connected" (no dispersal file). T is stored in sim.vars$migrants_real.
Effective population size. Ne = 4N / (Vk + 2), with Vk the variance in
the number of offspring an individual leaves in the next generation.
With parents sampled without replacement Ne / N = k / (k + 1), and with
replace_parents = TRUE (parents mate a Poisson number of times, which
produces half siblings) Ne / N = k / (2k + 1), at most 1/2; k is
variance_offspring, one value or one per population. ne_phase1 and
ne_phase2 set a target Ne for each population, for example estimated
from x with gl.LDNe() (per population; with small samples its estimate
can be infinite and is then of no use), and variance_offspring is set to
reach it. Family-size variance can only lower Ne, so a target above N
(N/2 with replace_parents = TRUE) is capped there with a warning; raise
the population size instead. With real_pop_size = TRUE the populations
are as small as x's samples; to simulate larger populations while storing
samples of x's sizes, set population_size_phase2 and use
real_sample_size = TRUE, which replaces sample_percent. The expected Ne is
stored in sim.vars$ne_expected, which gl.diagnostics.sim
uses by default.
Family-structured samples. A sample made of a few families (clutches, litters) makes unrelated pairs look related, because allele frequencies come from few families. sample_families gives the sizes of the full-sib families in each stored sample (e.g. "9 15 9"; ";" between populations, one group for all populations). For each size a mating pair with that many offspring is chosen and that many of its offspring are sampled from the offspring pool, before the next generation is drawn (so, like hatchlings, they may not survive to reproduce); the rest of the sample is drawn at random from the population. sample_parents = TRUE also stores each family's two parents, from the previous generation; they count against the sample size. The sample size is x's with real_sample_size = TRUE (exactly, with or without families), otherwise set by sample_percent. Family sampling starts at generation 1, as the founders have no parents; number_offspring must be at least the largest family, otherwise large families are rare and a warning is printed. ind.metrics gains sample_role ("family", "parent" or "random") and family (the parents' ids).
Planted crosses. To recreate a mating design with shared parents (e.g. 4 litters from 2 sires x 2 dams), sample_crosses gives one "SxD" token per family of sample_families, where the same label is the same individual (e.g. "S1xD1 S1xD2 S2xD1 S2xD2"; ";" between populations); sample_design = "2x2" is shorthand for every cross of 2 sires and 2 dams. Sires and dams are drawn at random from the previous generation and each cross makes a family of exactly the given size, with the usual meiosis. The planted offspring are only sampled: they do not join the population, so drift and gene flow are unchanged. With sample_parents = TRUE each parent is sampled once. ind.metrics also gains sample_cross (the offspring's cross) and parent_label (the parent's label).
Value
A list with one element per iteration ("iteration_1", ...). Each is a list of genlight objects, one per stored generation, named by the generation they hold ("generation_1", ...). Each genlight has the reference table in @other$loc.metrics, sex and parents in
Author(s)
Author(s): Luis Mijangos. Custodian: Luis Mijangos – Post to https://groups.google.com/d/forum/dartr
See Also
Other simulation functions:
gl.diagnostics.sim(),
gl.report.nall(),
gl.sim.Neconst(),
gl.sim.WF.table(),
gl.sim.create_dispersal(),
gl.sim.emigration(),
gl.sim.ind(),
gl.sim.ind.af(),
gl.sim.mutate(),
gl.sim.offspring()
Examples
ref_table <- gl.sim.WF.table(file_var=system.file("extdata",
"ref_variables.csv", package = "dartR.sim"),interactive_vars = FALSE)
# Runs about 20 seconds
res_sim <- gl.sim.WF.run(file_var = system.file("extdata",
"sim_variables.csv", package ="dartR.sim"),ref_table=ref_table,
interactive_vars = FALSE)
Creates the reference table for running gl.sim.WF.run
Description
This function creates a reference table to be used as input for the function
gl.sim.WF.run. The created table has eight columns with the
following information for each locus to be simulated:
q - initial frequency.
h - dominance coefficient.
s - selection coefficient.
c - recombination rate.
loc_bp - chromosome location in base pairs.
loc_cM - chromosome location in centiMorgans.
chr_name - chromosome name.
type - SNP type.
The reference table can be further modified as required.
Usage
gl.sim.WF.table(
file_var,
x = NULL,
file_targets_sel = NULL,
file_r_map = NULL,
interactive_vars = TRUE,
seed = NULL,
verbose = NULL,
...
)
Arguments
file_var |
Path of the variables file 'ref_variables.csv' (see details) [required if interactive_vars = FALSE]. |
x |
Genlight object containing the SNP data to extract values for some simulation variables (see details) [default NULL]. |
file_targets_sel |
Path of the file with the targets for selection (see details) [default NULL]. |
file_r_map |
Path of the file with the recombination map (see details) [default NULL]. |
interactive_vars |
Run a shiny app to input interactively the values of simulation variables [default TRUE]. |
seed |
Set the seed for the simulations. This calls set.seed(), so it also sets the random number stream of the R session for any code run afterwards [default NULL]. |
verbose |
Verbosity: 0, silent or fatal errors; 1, begin and end; 2, brief progress messages; 3, progress and results summary; 5, full report [default 2, unless specified using gl.set.verbosity]. |
... |
Any simulation variable of 'ref_variables.csv' and its value, e.g. chunk_number = 20. The value replaces the one in the csv file or the Shiny app. Names that are not simulation variables stop the function with an error. |
Details
Values for the variables to create the reference table can be submitted into the function interactively through a Shiny app if interactive_vars = TRUE. Optionally, if interactive_vars = FALSE, values for variables can be submitted by using the csv file 'ref_variables.csv' which can be found by typing in the R console: system.file('extdata', 'ref_variables.csv', package = 'dartR.sim').
The values of the variables can be modified using the third column ("value") of this file.
If a genlight object is used as input (real_loc = TRUE or real_freq = TRUE), this function uses the slots x@position and x@chromosome. x@chromosome must contain the value of the variable chromosome_name.
The recombination map file needs the columns Chr (chromosome name), from and to (start and end of each interval in bp) and cM (centiMorgans in the interval). Intervals can have any size; intervals with cM = NA are treated as not recombining. The targets of selection file needs the columns chr_name, start and end (in bp) and targets (number of targets of selection in the region). Examples of both files can be found by typing in the R console:
system.file('extdata', 'fly_recom_map.csv', package = 'dartR.sim')
system.file('extdata', 'fly_targets_of_selection.csv', package = 'dartR.sim')
Values drawn from distributions or equations are capped: q at 0.5, deleterious s at 0.99 and advantageous s at -0.5. Each class is capped only when its own distribution setting is not "equal". The number of capped loci is reported when verbose >= 1.
To show further information of the variables in interactive mode, it might be necessary to call first: 'library(shinyBS)' for the information to be displayed.
Value
Returns a list with the reference table used as input for the function
gl.sim.WF.run and a table with the values variables used to
create the reference table.
Author(s)
Author(s): Luis Mijangos. Custodian: Luis Mijangos – Post to https://groups.google.com/d/forum/dartr
See Also
Other simulation functions:
gl.diagnostics.sim(),
gl.report.nall(),
gl.sim.Neconst(),
gl.sim.WF.run(),
gl.sim.create_dispersal(),
gl.sim.emigration(),
gl.sim.ind(),
gl.sim.ind.af(),
gl.sim.mutate(),
gl.sim.offspring()
Examples
ref_table <- gl.sim.WF.table(file_var=system.file("extdata",
"ref_variables.csv", package = "dartR.sim"),interactive_vars = FALSE)
# Runs about 20 seconds
res_sim <- gl.sim.WF.run(file_var = system.file("extdata",
"sim_variables.csv", package ="dartR.sim"),ref_table=ref_table,
interactive_vars = FALSE)
Creates a dispersal file as input for the function gl.sim.WF.run
Description
This function writes a csv file called "dispersal_table.csv" which contains
the dispersal variables for each pair of populations to be used as input for
the function gl.sim.WF.run.
The values of the variables can be modified using the columns "transfer_each_gen" and "number_transfers" of this file.
See documentation and tutorial for a complete description of the simulations. These documents can be accessed by typing in the R console: browseVignettes(package = "dartR.sim")
Usage
gl.sim.create_dispersal(
number_pops,
dispersal_type = "all_connected",
number_transfers = 1,
transfer_each_gen = 1,
outpath = tempdir(),
outfile = "dispersal_table.csv",
verbose = NULL
)
Arguments
number_pops |
Number of populations, a whole number of at least 2 [required]. |
dispersal_type |
One of: "all_connected", "circle" or "line" [default "all_connected"]. |
number_transfers |
Number of individuals swapped in each direction between the two populations of a row at each dispersal event, a whole number of at least 0. Each connected pair of populations is written once. This value can be modified by hand after the file has been created [default 1]. |
transfer_each_gen |
Interval of number of generations in which dispersal occur, a whole number of at least 1. This value can be modified by hand after the file has been created [default 1]. |
outpath |
Path where to save the output file. Use outpath=getwd() or outpath='.' when calling this function to direct output files to your working directory [default tempdir(), mandated by CRAN]. |
outfile |
File name of the output file [default 'dispersal_table.csv']. |
verbose |
Verbosity: 0, silent or fatal errors; 1, begin and end; 2, progress log; 3, progress and results summary; 5, full report [default 2, unless specified using gl.set.verbosity]. |
Details
With "all_connected", every pair of populations is connected; with "line", each population is connected to the next one (1-2, 2-3, ...); with "circle", the last population is also connected to the first one.
A number_transfers of 0 in a row switches dispersal off for that pair. If outpath does not exist, the file is written to tempdir() with a warning.
Value
Writes a csv file containing the dispersal variables for each pair
of populations to be used as input for the function
gl.sim.WF.run, and returns the same table invisibly as a
data.frame.
Author(s)
Author(s): Luis Mijangos. Custodian: Luis Mijangos – Post to https://groups.google.com/d/forum/dartr
See Also
Other simulation functions:
gl.diagnostics.sim(),
gl.report.nall(),
gl.sim.Neconst(),
gl.sim.WF.run(),
gl.sim.WF.table(),
gl.sim.emigration(),
gl.sim.ind(),
gl.sim.ind.af(),
gl.sim.mutate(),
gl.sim.offspring()
Examples
gl.sim.create_dispersal(number_pops=10)
Simulates emigration between populations
Description
A function that allows to exchange individuals of populations within a genlight object (=simulate emigration between populations).
Usage
gl.sim.emigration(
x,
perc.mig = NULL,
emi.m = NULL,
emi.table = NULL,
verbose = NULL
)
Arguments
x |
A genlight object, or a list of genlight objects with one element per population (NULL for an empty population) [required]. |
perc.mig |
Proportion of individuals that emigrate, between 0 and 1 (each individual emigrates with this probability) [default NULL]. |
emi.m |
Probabilistic emigration matrix (emigrate from = column, to = row), a square matrix with one row and one column per population [default NULL]. |
emi.table |
If provided, emi.m and perc.mig are ignored. Deterministic emigration as specified in the matrix (a square matrix of dimension of the number of populations). e.g. an entry in the 'emi.table[2,1]<- 5' means that five individuals emigrate from population 1 to population 2 (from=columns and to=row) [default NULL]. |
verbose |
Verbosity: 0, silent or fatal errors; 1, begin and end; 2, brief progress messages; 3, progress and results summary; 5, full report [default 2, unless specified using gl.set.verbosity]. |
Details
There are two ways to specify emigration. If an emi.table is provided (a square matrix of dimension of the populations that specifies the emigration from column x to row y), then emigration is deterministic in terms of numbers of individuals as specified in the table. If perc.mig and emi.m are provided, then emigration is probabilistic: each individual emigrates with probability perc.mig, and the population it moves to is drawn from the relative probabilities in the column of emi.m of its population (from = column, to = row). A column of zeros means that no individual leaves that population.
If the diagonal of emi.m is non zero, emigrants can be assigned to their own population, where they stay. So most often you want to set the diagonal of the emi.m matrix to zero. The diagonal of emi.table is ignored.
Emigrants are drawn at random from the individuals present in each population at the start of the call, and all move at the same time, so an individual moves at most once per call. The returned object is grouped by population; the population of each moved individual is updated in pop() and in other$ind.metrics$pop.
A population can lose all its individuals. In a returned genlight object it no longer appears in popNames(); in a returned list its element is NULL. A list with NULL elements is accepted as input, so repeated calls can use the same matrices.
Value
A list or a single [depends on the input] genlight object, where emigration between population has happened
Author(s)
Author(s): Bernd Gruber. Custodian: Bernd Gruber – Post to https://groups.google.com/d/forum/dartr
See Also
Other simulation functions:
gl.diagnostics.sim(),
gl.report.nall(),
gl.sim.Neconst(),
gl.sim.WF.run(),
gl.sim.WF.table(),
gl.sim.create_dispersal(),
gl.sim.ind(),
gl.sim.ind.af(),
gl.sim.mutate(),
gl.sim.offspring()
Examples
x <- possums.gl
#one individual moves from every population to
#every other population
emi.tab <- matrix(1, nrow=nPop(x), ncol=nPop(x))
diag(emi.tab)<- 0
np <- gl.sim.emigration(x, emi.table=emi.tab)
np
Simulates individuals based on allele frequencies
Description
This function simulates individuals based on the allele frequencies of a genlight object. The output is a genlight object with the same loci as the input genlight object.
Usage
gl.sim.ind(x, n = 50, popname = "pop1", verbose = NULL)
Arguments
x |
Genlight object containing the SNP data [required]. |
n |
Number of individuals that should be simulated [default 50]. |
popname |
A population name for the simulated individuals [default "pop1"]. |
verbose |
Verbosity: 0, silent or fatal errors; 1, begin and end; 2, brief progress messages; 3, progress and results summary; 5, full report [default 2, unless specified using gl.set.verbosity]. |
Details
For each locus, the frequency p of the alternative allele (genotype 2) is estimated from x, ignoring missing data. Each simulated genotype is the number of alternative alleles in two independent draws, so genotypes are in Hardy-Weinberg proportions and loci are in linkage equilibrium. Loci with no calls in x get missing genotypes (NA).
The simulated object keeps the locus names, alleles, positions, chromosomes and locus metrics of x; the metrics flags are reset, so recalculable metrics are recalculated when needed.
The simulated object has the same flavour as x: if the genotypes of x are
held in a file-backed matrix (@fbm, see dartR.base::gl.gen2fbm),
the simulated genotypes are written to a new file-backed matrix, otherwise
they are stored in @gen. In the file-backed matrix missing genotypes are
stored as the raw code 3, which is read back as NA.
The function can be used to simulate populations for sampling designs or for power analysis. The example below explores drift by simulating several generations, each from the allele frequencies of the previous one.
Value
A genlight object with n individuals, file-backed (@fbm) if x is file-backed and gen-backed (@gen) otherwise.
Author(s)
Author(s): Bernd Gruber. Custodian: Luis Mijangos – Post to https://groups.google.com/d/forum/dartr
See Also
Other simulation functions:
gl.diagnostics.sim(),
gl.report.nall(),
gl.sim.Neconst(),
gl.sim.WF.run(),
gl.sim.WF.table(),
gl.sim.create_dispersal(),
gl.sim.emigration(),
gl.sim.ind.af(),
gl.sim.mutate(),
gl.sim.offspring()
Examples
glsim <- gl.sim.ind(testset.gl, n=10, popname='sims')
glsim
###Simulate drift over 10 generation
# assuming a bottleneck of only 10 individuals
# [ignoring effect of mating and mutation]
# Simulate 20 individuals with no structure and 50 SNP loci
founder <- glSim(n.ind = 20, n.snp.nonstruc = 50, ploidy=2)
#number of fixed loci in the first generation
res <- sum(colMeans(as.matrix(founder), na.rm=TRUE) %%2 ==0)
simgl <- founder
#49 generations of only 10 individuals
for (i in 2:50) {
simgl <- gl.sim.ind(simgl, n=10, popname='sims', verbose = 0)
res[i]<- sum(colMeans(as.matrix(simgl), na.rm=TRUE) %%2 ==0)
}
plot(1:50, res, type='b', xlab='generation', ylab='# fixed loci')
Simulates diploid genotypes from per-population allele frequencies
Description
This function generates a diploid SNP dataset by sampling genotypes for a specified number of individuals per population from user-provided allele frequencies. The result is returned as a genlight object with population and individual metadata.
Usage
gl.sim.ind.af(
df,
pop.sizes,
fbm = isTRUE(getOption("dartR_fbm")),
verbose = NULL
)
Arguments
df |
A data.frame with three columns: (1) population name, (2) locus name, and (3) frequency of the alternate allele (numeric in [0, 1]) [required]. |
pop.sizes |
A vector of whole numbers of at least 1, with the number of individuals to simulate in each population. If unnamed, one element per population in the order in which the populations first appear in df; if named, the names must match the population names in df [required]. |
fbm |
If TRUE, the genotypes of the returned object are held in a
file-backed matrix (@fbm, see |
verbose |
Verbosity: 0, silent or fatal errors; 1, begin and end; 2, brief progress messages; 3, progress and results summary; 5, full report [default 2, unless specified using gl.set.verbosity]. |
Details
The input df must have three columns: population name, locus name, and the frequency of the alternate allele for that population-locus combination. The alternate allele is the allele counted in the genotypes of a genlight object, and its frequency is the column frequency returned by gl.allele.freq(x, by = "popxloc").
For each individual, the genotype at each locus is the number of copies of the alternate allele in two gametes drawn independently with the supplied frequency. The procedure assumes Hardy-Weinberg proportions and linkage equilibrium (loci are sampled independently and there is no within-population structure beyond the supplied allele frequencies).
Populations are matched to their frequencies and sizes by name, so the rows of df can be in any order. Every population must provide each locus exactly once.
Individual IDs have the form "0_<population name>_<i>". Sex alternates between individuals ("m", "f", "m", ...) and a placeholder phenotype is set to "control" for all individuals; both are stored in other$ind.metrics, together with id, pop, fid (population) and iid (individual ID). Locus alleles are set to the placeholder "G/C", and other$loc.metrics holds the locus names (AlleleID) with all metrics flags reset.
Value
A genlight object with sum(pop.sizes) individuals and one locus per locus in df, with diploid SNP genotypes (0, 1, 2 copies of the alternate allele), pop() set to population names, and the metadata described in Details. The object is file-backed (@fbm) if fbm = TRUE and gen-backed (@gen) otherwise.
Author(s)
Author(s): Luis Mijangos. Custodian: Luis Mijangos – Post to https://groups.google.com/d/forum/dartr
See Also
Other simulation functions:
gl.diagnostics.sim(),
gl.report.nall(),
gl.sim.Neconst(),
gl.sim.WF.run(),
gl.sim.WF.table(),
gl.sim.create_dispersal(),
gl.sim.emigration(),
gl.sim.ind(),
gl.sim.mutate(),
gl.sim.offspring()
Examples
t1 <- gl.filter.callrate(platypus.gl,threshold = 1, mono.rm = TRUE)
r1 <- gl.allele.freq(t1, by='popxloc' )
r2 <- r1[,c("popn",'locus',"frequency")]
res <- gl.sim.ind.af(df = r2, pop.sizes= c(50,50,50))
Simulates mutations within a genlight object
Description
This function is intended to be used within the simulation framework of dartR. It adds the ability to add a constant mutation rate across all loci. Only works for biallelic SNP data.
Usage
gl.sim.mutate(x, mut.rate = 1e-06, verbose = NULL)
Arguments
x |
Name of the genlight object containing the SNP data [required]. |
mut.rate |
Constant mutation rate per allele copy, a number between 0 and 1 [default 1e-6]. |
verbose |
Verbosity: 0, silent or fatal errors; 1, begin and end; 2, brief progress messages; 3, progress and results summary; 5, full report [default 2, unless specified using gl.set.verbosity]. |
Details
Each of the nInd * nLoc * 2 allele copies mutates with probability mut.rate, so the number of mutation events is drawn from a binomial distribution, and each event is placed at a random individual and locus. A mutation changes one allele: a homozygote (0 or 2) becomes a heterozygote (1), and a heterozygote becomes either homozygote with equal probability.
Events that fall on a missing genotype are dropped, so the realised rate is lower than mut.rate by the proportion of missing data. In principle 'double mutations' at the same locus of the same individual can occur, but should be rare.
If any genotype changes, the locus metrics flags are reset so that metrics are recalculated by the functions that use them.
Value
Returns a genlight object with the applied mutations
Author(s)
Author(s): Bernd Gruber. Custodian: Bernd Gruber – Post to https://groups.google.com/d/forum/dartr
See Also
Other simulation functions:
gl.diagnostics.sim(),
gl.report.nall(),
gl.sim.Neconst(),
gl.sim.WF.run(),
gl.sim.WF.table(),
gl.sim.create_dispersal(),
gl.sim.emigration(),
gl.sim.ind(),
gl.sim.ind.af(),
gl.sim.offspring()
Examples
b2 <- gl.sim.mutate(bandicoot.gl,mut.rate=1e-4 )
#check the mutations that have occurred
table(as.matrix(bandicoot.gl), as.matrix(b2))
Simulates offspring based on alleles provided by parents
Description
This function takes a population (or a single individual) of fathers and of mothers (provided as genlight objects) and simulates offspring by Mendelian inheritance. It can be used to simulate population dynamics and check their effect on allele frequencies and number of alleles, or to simulate the relatedness of siblings and compare it with the relatedness found in a population.
Usage
gl.sim.offspring(
fathers,
mothers,
noffpermother,
sexratio = 0.5,
popname = "offspring",
verbose = NULL
)
Arguments
fathers |
Genlight object of potential fathers [required]. |
mothers |
Genlight object of mothers [required]. |
noffpermother |
Number of offspring per mother [required]. |
sexratio |
The sex ratio of simulated offspring (females / (females + males); 1 equals 100 percent females) [default 0.5]. |
popname |
Population name of the returned genlight object [default "offspring"]. |
verbose |
Verbosity: 0, silent or fatal errors; 1, begin and end; 2, brief progress messages; 3, progress and results summary; 5, full report [default 2, unless specified using gl.set.verbosity]. |
Details
Each mother has exactly noffpermother offspring. The father of each offspring is drawn at random from fathers, so offspring of the same mother are full siblings only when a single father is given; otherwise most are half siblings.
Each parent passes on one of its two alleles at every locus with probability 1/2, independently across loci (no linkage). Missing genotypes in a parent give missing genotypes in its offspring.
fathers and mothers must be SNP data with the same loci in the same order. The offspring keep the locus metadata of the mothers (the metrics flags are reset), and @other$ind.metrics records each offspring's sex, mother and father (their individual names).
The offspring have the same flavour as the parents: if the genotypes of
fathers or mothers are held in a file-backed matrix (@fbm, see
dartR.base::gl.gen2fbm), the offspring genotypes are written to a
new file-backed matrix, otherwise they are stored in @gen. In the
file-backed matrix missing genotypes are stored as the raw code 3, which
is read back as NA.
Value
A genlight object with nInd(mothers) * noffpermother individuals, file-backed (@fbm) if fathers or mothers are file-backed and gen-backed (@gen) otherwise.
Author(s)
Author(s): Bernd Gruber. Custodian: Luis Mijangos – Post to https://groups.google.com/d/forum/dartr
See Also
Other simulation functions:
gl.diagnostics.sim(),
gl.report.nall(),
gl.sim.Neconst(),
gl.sim.WF.run(),
gl.sim.WF.table(),
gl.sim.create_dispersal(),
gl.sim.emigration(),
gl.sim.ind(),
gl.sim.ind.af(),
gl.sim.mutate()
Examples
#Simulate 10 potential fathers
gl.fathers <- glSim(10, 20, ploidy=2)
#Simulate 10 potential mothers
gl.mothers <- glSim(10, 20, ploidy=2)
res <- gl.sim.offspring(gl.fathers, gl.mothers, 2, sexratio=0.5)
Shiny app for the input of the reference table for the simulations
Description
Shiny app for the input of the reference table for the simulations
Usage
interactive_reference()
Author(s)
Custodian: Luis Mijangos – Post to https://groups.google.com/d/forum/dartr
Shiny app for the input of the simulations variables
Description
Shiny app for the input of the simulations variables
Usage
interactive_sim_run()
Author(s)
Custodian: Luis Mijangos – Post to https://groups.google.com/d/forum/dartr
Setting up the package
Description
Setting up dartR.sim
Usage
zzz
Format
An object of class NULL of length 0.