Package {reems}


Title: Estimating Effective Migration Surfaces from Single Nucleotide Polymorphism Data
Version: 0.1.0
Description: Wrapper and plotting utilities for the spatial population genetics tool 'EEMS' (Estimated Effective Migration Surfaces) for SNP (Single Nucleotide Polymorphism) data, originally provided as a command-line tool written in 'C++' together with an accompanying 'R' package for plotting the output of the 'EEMS' tool itself (https://github.com/dipetkov/eems/). There are four main motivations for offering this to 'R' users as a package. Firstly, to remove the installation and configuration burden for the 'EEMS' command-line tool, which relies on manually installed 'Boost' and 'Eigen' system libraries and configuring their location; secondly, to streamline the workflow by having a singe environment (the 'R' system) for the entire analysis rather than a file-based command-line executable whose output files are then to be imported and analysed by a separate 'R' script; thirdly, to make the input formats compatible with other, 'R'-based spatial population genetics tools such as the 'ConStruct' package; and lastly, to allow for easily running several chains in parallel and combining them for plotting and further analysis. The package also adds more intuitive, streamlined tooling around creating more complex habitats. The method of estimating effective migration surfaces was first described by Petkova, D., Novembre, J. & Stephens, M. (2016) <doi:10.1038/ng.3464>.
License: GPL-2
Encoding: UTF-8
RoxygenNote: 7.3.3
LinkingTo: BH (≥ 1.76.0), Rcpp (≥ 0.12.0), RcppEigen (≥ 0.3.3.9.1)
Imports: Rcpp, methods, raster (≥ 2.4-15), sp (≥ 1.1-1), sf, stats (≥ 3.3.2), utils (≥ 3.3.2)
Suggests: future, future.apply, Matrix (≥ 1.2.7.1), RColorBrewer (≥ 1.1), deldir (≥ 0.1), dichromat, rworldmap (≥ 1.3), rworldxtra (≥ 1.01), knitr, rmarkdown, testthat (≥ 3.0.0)
Depends: R (≥ 4.1.0)
LazyData: true
VignetteBuilder: knitr
URL: https://codeberg.org/felix_weitkaemper/reems
BugReports: https://codeberg.org/felix_weitkaemper/reems/issues
Config/testthat/edition: 3
NeedsCompilation: yes
Packaged: 2026-05-02 10:18:33 UTC; weitkaemper
Author: Felix Weitkämper ORCID iD [aut, cre, cph], Desislava Petkova ORCID iD [cph] (Author of the 'EEMS' command-line utility and the 'EEMS' plotting 'R' scripts adapted for this wrapper package.)
Maintainer: Felix Weitkämper <felix.weitkaemper@german-uds.de>
Repository: CRAN
Date/Publication: 2026-05-05 18:20:02 UTC

Run an EEMS analysis from data in R format

Description

This function runs an EEMS analysis with given parameters in the input format for conStruct, which include R matrices for allele frequency data and coordinates. In addition to taking R objects as inputs, it also provides additional default values over the original EEMS command-line utility. Furthermore, it allows for running more than one chain, either in parallel or sequentially, and returns a vector of output directories as input to eems.plots().

Usage

eems(
  seed = unclass(Sys.time()),
  coords,
  freqs,
  outer = NULL,
  buffer = NULL,
  mcmcpath,
  demes = NULL,
  edges = NULL,
  prevpath = "",
  nChains = 1,
  parallel = FALSE,
  nWorkers = NULL,
  nDemes = NULL,
  diploid = TRUE,
  distance = "greatcircle",
  numMCMCIter = 2e+06,
  numBurnIter = 1e+06,
  numThinIter = 9999,
  mSeedsProposalS2 = 0.01,
  qSeedsProposalS2 = 0.1,
  mEffctProposalS2 = 0.1,
  qEffctProposalS2 = 0.001,
  mrateMuProposalS2 = 0.01,
  qVoronoiPr = 0.25,
  qrateShape = 0.001,
  mrateShape = 0.001,
  sigmaShape = 0.001,
  qrateScale = 1,
  mrateScale = 1,
  sigmaScale = 1,
  negBiProb = 0.67,
  negBiSize = 10
)

Arguments

seed

The random seed. Defaults to the current system time in seconds.

coords

The coordinate matrix, a two-column matrix with a line for every sample.

freqs

An allele frequency matrix in conStruct format, with a column for every site and a row for every sample. Choosing one main allele, it tabulates the average genotypes of the sample at that locus.

outer

Matrix of coordinates of the outer polygon. Defaults to a polygon larger than the convex hull of the supplied coordinates to mitigate EEMS boundary effects, which is created by outer.buffered().

buffer

The rough distance of the boundary from the convex hull. Defaults to 0.2 times the length of the hull. Unused if outer is specified.

mcmcpath

Full path to a filename prefix in an output directory with write permission.

demes

Matrix of coordinates of demes; optional, and usually unnecessary. Only in conjunction with edges.

edges

Matrix of custom input grid; optional, and usually unnecessary. Only in conjunction with demes.

prevpath

Full path to previous output directory, i.e., the mcmcpath in a previous EEMS run. Optional.

nChains

Number of chains to be run. Defaults to 1.

parallel

Logical values that indicates whether chains should be run in parallel. Defaults to FALSE.

nWorkers

If parallel is TRUE, then the number of workers used is the minimum of nChains and nWorkers. Defaults to the number of available cores.

nDemes

Number of demes, roughly. EEMS constructs a regular triangular grid with circa nDemes vertices. Defaults to 6 times the number of individuals, aiming for sufficient resolution.

diploid

Logical value that indicates whether the species is diploid (TRUE) or haploid (FALSE). Defaults to TRUE.

distance

Distance metric. Either euclidean or greatcirc, that is, great circle distance. Defaults to 'greatcirc', which is more accurate at larger scales.

numMCMCIter

Number of Markov Chain Monte Carlo iterations. Defaults to 2000000.

numBurnIter

Number of burn-in iterations to be discarded before sampling from posterior. Defaults to 1000000.

numThinIter

Number of thinning iterations to be discarded between sampling from posterior. Defaults to 9999.

mSeedsProposalS2

Variance of normal proposals to update the seeds of the migration tiles. Defaults to 0.01.

qSeedsProposalS2

Variance of normal proposals to update the seeds of the diversity tiles. Defaults to 0.1.

mEffctProposalS2

Variance of normal proposals to update the log10 rates of the migration tiles. Defaults to 0.1.

qEffctProposalS2

Variance of normal proposals to update the log10 rates of the diversity tiles. Defaults to 0.001.

mrateMuProposalS2

Variance of normal proposals to update the overall mean migration rate, on the log10 scale. Defaults to 0.01.

qVoronoiPr

With probability qVoronoiPr, update diversity Voronoi; with probability 1-qVoronoiPr, update migration Voronoi. Defaults to 0.25.

qrateShape

Shape hyperparameter for the diversity rates variance, qrateS2 ~ invgamma(qrateShape, qrateScale). Defaults to 0.001

mrateShape

Shape hyperparameter for the migration rates variance, mrateS2 ~ invgamma(mrateShape, mrateScale). Defaults to 0.001.

sigmaShape

Shape hyperparameter for the scaling factor sigma^2 ~ invgamma(sigmaShape, sigmaScale). Defaults to 0.001.

qrateScale

Scale hyperparameter for the diversity rates variance, qrateS2 ~ invgamma(qrateShape, qrateScale). Defaults to 1.0.

mrateScale

Scale hyperparameter for the migration rates variance, mrateS2 ~ invgamma(mrateShape, mrateScale). Defaults to 1.0.

sigmaScale

Scale hyperparameter for the scaling factor sigma^2 ~ invgamma(sigmaShape, sigmaScale). Defaults to 1.0.

negBiProb

Success probability for the number of Voronoi tiles ~ negbinom(negBiSize, negBiProb). Defaults to 0.67.

negBiSize

Size for the number of Voronoi tiles ~ negbinom(negBiSize, negBiProb). Defaults to 10.

Value

A vector of output directories which can be given as input to eems.plots().

References

Petkova, D., Novembre, J. & Stephens, M. Visualizing spatial population structure with estimated effective migration surfaces. Nat Genet 48, 94–100 (2016). https://doi.org/10.1038/ng.3464

See Also

eems.plots, eems.from.files

Examples

# The example puts the output in a temporary directory.
mcmcdir <- file.path(tempdir(), "eems_out")
dir.create(mcmcdir, showWarnings = FALSE)
mcmcpath <- file.path(mcmcdir,"example")

# Run an example EEMS analysis with a small number of iterations to ensure quick termination. 

eems(
  freqs = ex.freqs,
  coords = ex.coords,
  mcmcpath = mcmcpath,   
  numMCMCIter = 200,
  numBurnIter = 100,
  numThinIter = 99,
)
# Delete the output directory to tidy up. 
unlink(mcmcdir, recursive = TRUE, force = TRUE)

Run an EEMS analysis

Description

This function runs an EEMS analysis with given parameters, which include file paths for retrieving the input files (datapath.coord, datapath.diffs and datapath.outer) and writing the output files. It is an exact replicate of the original EEMS command-line function.

Usage

eems.from.files(
  seed = unclass(Sys.time()),
  datapath,
  mcmcpath,
  prevpath = "",
  gridpath = "",
  nDemes,
  nIndiv,
  nSites,
  diploid = TRUE,
  distance = "euclidean",
  numMCMCIter,
  numBurnIter,
  numThinIter,
  mSeedsProposalS2 = 0.01,
  qSeedsProposalS2 = 0.1,
  mEffctProposalS2 = 0.1,
  qEffctProposalS2 = 0.001,
  mrateMuProposalS2 = 0.01,
  qVoronoiPr = 0.25,
  qrateShape = 0.001,
  mrateShape = 0.001,
  sigmaShape = 0.001,
  qrateScale = 1,
  mrateScale = 1,
  sigmaScale = 1,
  negBiProb = 0.67,
  negBiSize = 10
)

Arguments

seed

The random seed. Defaults to the current system time in seconds.

datapath

Full path to a set of three files: datapath.coord, datapath.diffs and datapath.outer.

mcmcpath

Full path to a filename prefix in an output directory with write permission.

prevpath

Full path to previous output directory, i.e., the mcmcpath in a previous EEMS run. Optional.

gridpath

Full path to a set of two files: gridpath.demes and gridpath.edges. Optional.

nDemes

Number of demes, roughly. EEMS constructs a regular triangular grid with circa nDemes vertices.

nIndiv

Number of samples. Should match the size of the dissimilarity matrix in datapath.diffs.

nSites

Number of SNPs used to compute the observed dissimilarity matrix in datapath.diffs.

diploid

Logical value that indicates whether the species is diploid (TRUE) or haploid (FALSE). Defaults to TRUE.

distance

Distance metric. Either euclidean or greatcirc, that is, great circle distance. Defaults to 'euclidean'.

numMCMCIter

Number of Markov Chain Monte Carlo iterations.

numBurnIter

Number of burn-in iterations to be discarded before sampling from posterior.

numThinIter

Number of thinning iterations to be discarded between sampling from posterior.

mSeedsProposalS2

Variance of normal proposals to update the seeds of the migration tiles. Defaults to 0.01.

qSeedsProposalS2

Variance of normal proposals to update the seeds of the diversity tiles. Defaults to 0.1.

mEffctProposalS2

Variance of normal proposals to update the log10 rates of the migration tiles. Defaults to 0.1.

qEffctProposalS2

Variance of normal proposals to update the log10 rates of the diversity tiles. Defaults to 0.001.

mrateMuProposalS2

Variance of normal proposals to update the overall mean migration rate, on the log10 scale. Defaults to 0.01.

qVoronoiPr

With probability qVoronoiPr, update diversity Voronoi; with probability 1-qVoronoiPr, update migration Voronoi. Defaults to 0.25.

qrateShape

Shape hyperparameter for the diversity rates variance, qrateS2 ~ invgamma(qrateShape, qrateScale). Defaults to 0.001

mrateShape

Shape hyperparameter for the migration rates variance, mrateS2 ~ invgamma(mrateShape, mrateScale). Defaults to 0.001.

sigmaShape

Shape hyperparameter for the scaling factor sigma^2 ~ invgamma(sigmaShape, sigmaScale). Defaults to 0.001.

qrateScale

Scale hyperparameter for the diversity rates variance, qrateS2 ~ invgamma(qrateShape, qrateScale). Defaults to 1.0.

mrateScale

Scale hyperparameter for the migration rates variance, mrateS2 ~ invgamma(mrateShape, mrateScale). Defaults to 1.0.

sigmaScale

Scale hyperparameter for the scaling factor sigma^2 ~ invgamma(sigmaShape, sigmaScale). Defaults to 1.0.

negBiProb

Success probability for the number of Voronoi tiles ~ negbinom(negBiSize, negBiProb). Defaults to 0.67.

negBiSize

Size for the number of Voronoi tiles ~ negbinom(negBiSize, negBiProb). Defaults to 10.

Value

None

References

Petkova, D., Novembre, J. & Stephens, M. Visualizing spatial population structure with estimated effective migration surfaces. Nat Genet 48, 94–100 (2016). https://doi.org/10.1038/ng.3464

See Also

eems.plots, eems

Examples

# We use example input from Petkova et al. (2016), found in the '/extdata' directory
data_path <- system.file("extdata", package = "reems")
input <- file.path(data_path, "barrier-schemeX-nIndiv300-nSites3000")
# The example puts the output in a temporary directory.
mcmcdir <- file.path(tempdir(), "eems_out")
dir.create(mcmcdir, showWarnings = FALSE)


# Run an example EEMS analysis with a small number of iterations to ensure quick termination. 

eems.from.files(
  datapath = input,
  mcmcpath = mcmcdir,
  nDemes = 200,
  nIndiv = 300,
  nSites = 3000,
  diploid = FALSE,
  numMCMCIter = 200,
  numBurnIter = 100,
  numThinIter = 99,
)
# Delete the output directory to tidy up. 
unlink(mcmcdir, recursive = TRUE, force = TRUE)

A function to plot effective migration and diversity surfaces from EEMS output

Description

Given a vector of EEMS output directories, this function generates several figures to visualize EEMS results. It is a good idea to examine all these figures, which is why they are generated by default.

The mrates and qrates figures visualize (properties of) the effective migration and diversity rates across the habitat. The other figures can help to check that the MCMC sampler has converged (the trace plot pilogl) and that the EEMS model fits the data well (the scatter plots of genetic dissimilarities rdist).

Usage

eems.plots(
  mcmcpath,
  plotpath,
  longlat,
  plot.width = 10,
  plot.height = 10,
  out.png = NULL,
  res = 600,
  xpd = TRUE,
  add.grid = FALSE,
  col.grid = "gray80",
  lwd.grid = 1,
  add.demes = FALSE,
  col.demes = "black",
  pch.demes = 19,
  min.cex.demes = 1,
  max.cex.demes = 3,
  add.outline = FALSE,
  col.outline = "gray90",
  lwd.outline = 2,
  projection.in = NULL,
  projection.out = NULL,
  add.map = FALSE,
  col.map = "gray60",
  lwd.map = 2,
  eems.colors = NULL,
  prob.levels = c(0.9, 0.95),
  add.colbar = TRUE,
  m.colscale = NULL,
  q.colscale = NULL,
  remove.singletons = TRUE,
  add.abline = FALSE,
  add.r.squared = FALSE,
  add.title = TRUE,
  m.plot.xy = NULL,
  q.plot.xy = NULL,
  xy.coords = NULL
)

Arguments

mcmcpath

A vector of EEMS output directories, for the same dataset. Warning: There is minimal checking that the given directories are for the same dataset.

plotpath

The full path and the file name for the graphics to be generated.

longlat

A logical value indicating whether the coordinates are given as pairs (longitude, latitude) or (latitude, longitude).

plot.width

The width of the graphics region for the two rate contour plots, in inches. The default value is 10.

plot.height

The height of the graphics region, in inches. The default value is 10.

out.png

A logical value which, if set, forces output graphics to be generated as PNGs (if TRUE) or PDFs (if FALSE). If left unset, the format depends on the nature of the plot.

res

Resolution, in dots per inch; used only for PNG images. The default is 600.

xpd

A logical value indicating whether to clip plotting to the figure region (xpd = TRUE, which is the default) or clip plotting to the plot region (xpd = FALSE).

add.grid

A logical value indicating whether to add the population grid or not.

col.grid

The color of the population grid. Defaults to gray80.

lwd.grid

The line width of the population grid. Defaults to 1.

add.demes

A logical value indicating whether to add the observed demes or not.

col.demes

The color of the demes. Defaults to black.

pch.demes

The symbol, specified as an integer, or the character to be used for plotting the demes. Defaults to 19.

min.cex.demes

The minimum size of the deme symbol/character.

max.cex.demes

The maximum size of the deme symbol/character. Defaults to 1 and 3, respectively. If max.cex.demes > min.cex.demes, then demes with more samples also have bigger size: the deme with the fewest samples has size min.cex.demes and the deme with the most samples has size max.cex.demes.

add.outline

A logical value indicating whether to add the habitat outline or not.

col.outline

The color of the habitat outline. Defaults to white.

lwd.outline

The line width of the habitat outline. Defaults to 2.

projection.in

The input cartographic projection, specified as a PROJ.4 string.

projection.out

The output cartographic projection, specified as a PROJ.4 string.

add.map

A logical value indicating whether to add a high-resolution geographic map. Requires the rworldmap and rworldxtra packages. It also requires that projection.in is specified.

col.map

The color of the geographic map. Default is gray60.

lwd.map

The line width of the geographic map. Defaults to 2.

eems.colors

The EEMS color scheme as a vector of colors, ordered from low to high. Defaults to a DarkOrange to Blue divergent palette with six orange shades, white in the middle, six blue shades. Acknowledgement: The default color scheme is adapted from the dichromat package.

prob.levels

A vector of probabilities for plotting the posterior probability contours of P(m > 0 | diffs) and P(m < 0 | diffs). Defaults to c(0.9, 0.95).

add.colbar

A logical value indicating whether to add the color bar (the key that shows how colors map to rates) to the right of the plot. Defaults to TRUE.

m.colscale

A fixed range for log10-transformed migration rates. If the estimated rates fall outside the specified range, then the color scale is ignored. By default, no range is specified for either type of rates.

q.colscale

A fixed range for log10-transformed diversity rates.

remove.singletons

Remove demes with a single observation from the diagnostic scatter plots. Defaults to TRUE.

add.abline

Add the line y = x to the diagnostic scatter plots of observed vs fitted genetic dissimilarities.

add.r.squared

Add the R squared coefficient to the diagnostic scatter plots of observed vs fitted genetic dissimilarities.

add.title

A logical value indicating whether to add the main title in the contour plots. Defaults to TRUE.

m.plot.xy

Statements which add graphical elements (e.g. points) on top of the migration sufrace.

q.plot.xy

Statements which add graphical elements (e.g. points) on top of the diversity surface.

xy.coords

Additional coordinates at which to estimate the migration and diversity rates.

Details

The function eems.plots will work given the results from a single EEMS run (one directory in mcmcpath) but it is better to run EEMS several times, randomly initializing the MCMC chain each time. In other words, simulate several realizations of the Markov chain and let each realization start from a different state in the parameter space (by using a different random seed).

Detail about the within-deme and between-deme components of genetic dissimilarity: Let D(a,b) be the dissimilarity between one individual from deme a and another individual from deme b. Then the within-deme component for a and b is simply D(a,a) and D(b, b), respectively. The between-deme component is D(a,b) - [D(a,a) + D(b,b)] / 2 and it represents dissimilarity that is due to the spatial structure of the population and is not a consequence of the local diversity in the two demes.

Value

None

References

Light A and Bartlein PJ (2004). The End of the Rainbow? Color Schemes for Improved Data Graphics. EOS Transactions of the American Geophysical Union, 85(40), 385.

See Also

eems.voronoi.samples, eems.posterior.draws, eems.population.grid

Examples

# Use the provided example or supply the path to your own EEMS run.
extdata_path <- system.file("extdata", package = "reems")
eems_results <- file.path(extdata_path, "EEMS-example")
# Create a temporary output directory for the sake of the example
outdir <- file.path(tempdir(), "plot_out")
dir.create(outdir, showWarnings = FALSE) 
name_figures <- file.path(outdir, "EEMS-example")

# Produce the set of EEMS figures, with default values for all optional parameters.
eems.plots(
  mcmcpath = eems_results,
  plotpath = paste0(name_figures, "-default"),
  longlat = TRUE,
  out.png = FALSE
)

# Delete the temporary output directory to tidy up. 
unlink(outdir, recursive = TRUE, force = TRUE)

A function to plot the constructed population grid and optionally the initial sampling locations

Description

Given an EEMS output directory, this function generates one figure to visualize the EEMS population grid. All edges are shown in the same color to visualize the grid before estimating migration and diversity rates. This can be helpful if EEMS exits with the error message "The population grid is not connected".

Usage

eems.population.grid(
  mcmcpath,
  plotpath,
  longlat,
  plot.width = 10,
  plot.height = 10,
  out.png = FALSE,
  res = 600,
  add.grid = TRUE,
  col.grid = "gray80",
  lwd.grid = 1,
  add.demes = FALSE,
  col.demes = "black",
  pch.demes = 19,
  min.cex.demes = 1,
  max.cex.demes = 3,
  add.outline = TRUE,
  col.outline = "gray90",
  lwd.outline = 2,
  add.coord = FALSE,
  col.coord = "red",
  pch.coord = 3,
  datapath = NULL
)

Arguments

mcmcpath

A vector of EEMS output directories, for the same dataset. Warning: There is minimal checking that the given directories are for the same dataset.

plotpath

The full path and the file name for the graphics to be generated.

longlat

A logical value indicating whether the coordinates are given as pairs (longitude, latitude) or (latitude, longitude).

plot.width

The width of the graphics region for the two rate contour plots, in inches. The default value is 10.

plot.height

The height of the graphics region, in inches. The default value is 10.

out.png

A logical value which, if set, forces output graphics to be generated as PNGs (if TRUE) or PDFs (if FALSE). Defaults to FALSE.

res

Resolution, in dots per inch; used only for PNG images. The default is 600.

add.grid

A logical value indicating whether to add the population grid or not.

col.grid

The color of the population grid. Defaults to gray80.

lwd.grid

The line width of the population grid. Defaults to 1.

add.demes

A logical value indicating whether to add the observed demes or not.

col.demes

The color of the demes. Defaults to black.

pch.demes

The symbol, specified as an integer, or the character to be used for plotting the demes. Defaults to 19.

min.cex.demes

The minimum size of the deme symbol/character.

max.cex.demes

The maximum size of the deme symbol/character. Defaults to 1 and 3, respectively. If max.cex.demes > min.cex.demes, then demes with more samples also have bigger size: the deme with the fewest samples has size min.cex.demes and the deme with the most samples has size max.cex.demes.

add.outline

A logical value indicating whether to add the habitat outline or not.

col.outline

The color of the habitat outline. Defaults to white.

lwd.outline

The line width of the habitat outline. Defaults to 2.

add.coord

A logical value indicating whether to add the original sampling locations to the plot or not.

col.coord

The color of the sampling locations. Defaults to red.

pch.coord

The symbol, specified as an integer, or the character to be used for plotting the sampling locations. Defaults to 3.

datapath

The full path and the file name of the input dataset (the three files datapath.coord, datapath.diffs, datapath.outer). Must be specified if add_coord = TRUE.

Value

Passes on the return value of dev.off() indicating the graphics device.

See Also

eems.plots, eems.voronoi.samples, eems.posterior.draws

Examples

# Use the provided example or supply the path to your own EEMS run.
extdata_path <- system.file("extdata", package = "reems")
eems_results <- file.path(extdata_path, "EEMS-example")
# Create a temporary output directory for this example 
outdir <- file.path(tempdir(), "path_out")
dir.create(outdir, showWarnings = FALSE)
name_figures <- file.path(outdir, "EEMS-grid_connected")

eems.population.grid(eems_results,
  name_figures,
  longlat = TRUE,
  add.outline = TRUE,
  col.outline = "purple",
  lwd.outline = 3,
  add.grid = TRUE,
  col.grid = "green",
  lwd.grid = 2,
  out.png = FALSE
)

# It is more interesting to see an example where the grid is unconnected
# due to the unusual shape of the habitat.
eems_results <- file.path(extdata_path, "EEMS-popgrid")

name_figures <- file.path(outdir, "EEMS-grid_not_connected")

eems.population.grid(
  mcmcpath = eems_results,
  plotpath = name_figures,
  longlat = FALSE,
  add.outline = TRUE, col.outline = "purple", lwd.outline = 3,
  add.grid = TRUE, col.grid = "green", lwd.grid = 2
)
# Delete the output file to tidy up.
unlink(outdir, recursive = TRUE, force = TRUE)

Plotting smoothed Voronoi diagrams of effective migration and diversity rates

Description

Given a set of EEMS output directories, this function takes random draws from the posterior distribution of the migration and diversity rate parameters. Each draw is visualized as two smoothed Voronoi diagrams; the migration diagram is saved to a file ending in mvoronoiXX, the diversity diagram is saved to a file ending in qvoronoiXX where XX is a numeric id. Specify the number of times to draw from the posterior with the argument post.draws. If post.draws = 10, then eems.posterior.draws will generate plots with id XX = 1 to XX = 10. This function differs from eems.voronoi.samples() by plotting smoothed contour diagrams rather than raw Voronoi plots.

Usage

eems.posterior.draws(
  mcmcpath,
  plotpath,
  longlat,
  post.draws = 1,
  plot.width = 10,
  plot.height = 10,
  out.png = TRUE,
  res = 600,
  xpd = TRUE,
  add.grid = FALSE,
  col.grid = "gray80",
  lwd.grid = 1,
  add.demes = FALSE,
  col.demes = "black",
  pch.demes = 19,
  min.cex.demes = 1,
  max.cex.demes = 3,
  add.outline = FALSE,
  col.outline = "gray90",
  lwd.outline = 2,
  projection.in = NULL,
  projection.out = NULL,
  add.map = FALSE,
  col.map = "gray60",
  lwd.map = 2,
  eems.colors = NULL,
  add.colbar = FALSE,
  m.colscale = NULL,
  q.colscale = NULL,
  add.title = FALSE,
  m.plot.xy = NULL,
  q.plot.xy = NULL
)

Arguments

mcmcpath

A vector of EEMS output directories, for the same dataset. Warning: There is minimal checking that the given directories are for the same dataset.

plotpath

The full path and the file name for the graphics to be generated.

longlat

A logical value indicating whether the coordinates are given as pairs (longitude, latitude) or (latitude, longitude).

post.draws

Number of times to sample from the posterior. The default is 1.

plot.width

The width of the graphics region for the two rate contour plots, in inches. The default value is 10.

plot.height

The height of the graphics region, in inches. The default value is 10.

out.png

A logical value which, if set, forces output graphics to be generated as PNGs (if TRUE) or PDFs (if FALSE). Defaults to TRUE.

res

Resolution, in dots per inch; used only for PNG images. The default is 600.

xpd

A logical value indicating whether to clip plotting to the figure region (xpd = TRUE, which is the default) or clip plotting to the plot region (xpd = FALSE).

add.grid

A logical value indicating whether to add the population grid or not.

col.grid

The color of the population grid. Defaults to gray80.

lwd.grid

The line width of the population grid. Defaults to 1.

add.demes

A logical value indicating whether to add the observed demes or not.

col.demes

The color of the demes. Defaults to black.

pch.demes

The symbol, specified as an integer, or the character to be used for plotting the demes. Defaults to 19.

min.cex.demes

The minimum size of the deme symbol/character.

max.cex.demes

The maximum size of the deme symbol/character. Defaults to 1 and 3, respectively. If max.cex.demes > min.cex.demes, then demes with more samples also have bigger size: the deme with the fewest samples has size min.cex.demes and the deme with the most samples has size max.cex.demes.

add.outline

A logical value indicating whether to add the habitat outline or not.

col.outline

The color of the habitat outline. Defaults to white.

lwd.outline

The line width of the habitat outline. Defaults to 2.

projection.in

The input cartographic projection, specified as a PROJ.4 string.

projection.out

The output cartographic projection, specified as a PROJ.4 string.

add.map

A logical value indicating whether to add a high-resolution geographic map. Requires the rworldmap and rworldxtra packages. It also requires that projection.in is specified.

col.map

The color of the geographic map. Default is gray60.

lwd.map

The line width of the geographic map. Defaults to 2.

eems.colors

The EEMS color scheme as a vector of colors, ordered from low to high. Defaults to a DarkOrange to Blue divergent palette with six orange shades, white in the middle, six blue shades. Acknowledgement: The default color scheme is adapted from the dichromat package.

add.colbar

A logical value indicating whether to add the color bar (the key that shows how colors map to rates) to the right of the plot. Defaults to TRUE.

m.colscale

A fixed range for log10-transformed migration rates. If the estimated rates fall outside the specified range, then the color scale is ignored. By default, no range is specified for either type of rates.

q.colscale

A fixed range for log10-transformed diversity rates.

add.title

A logical value indicating whether to add the main title in the contour plots. Defaults to TRUE.

m.plot.xy

Statements which add graphical elements (e.g. points) on top of the migration sufrace.

q.plot.xy

Statements which add graphical elements (e.g. points) on top of the diversity surface.

Details

Note about the implementation: eems.voronoi.samples samples randomly from the posterior draws saved during the execution of EEMS, after burn-in and thinning.

Value

None

References

Light A and Bartlein PJ (2004). The End of the Rainbow? Color Schemes for Improved Data Graphics. EOS Transactions of the American Geophysical Union, 85(40), 385.

See Also

eems.voronoi.samples

Examples

# Use the provided example or supply the path to your own EEMS run.
extdata_path <- system.file("extdata", package = "reems")
eems_results <- file.path(extdata_path, "EEMS-example")
# Create a temporary output directory for this example 
outdir <- file.path(tempdir(), "path_out")
dir.create(outdir, showWarnings = FALSE)
name_figures <- file.path(outdir, "EEMS-example")

# Plot a series of Voronoi diagrams for the EEMS model parameters:
# the effective migration rates (m) and the effective diversity rates (q).
eems.posterior.draws(
  mcmcpath = eems_results,
  plotpath = paste0(name_figures, "-posterior-draws"),
  longlat = TRUE,
  post.draws = 2,
  out.png = FALSE
)
# Delete the output directory to tidy up. 
unlink(outdir, recursive = TRUE, force = TRUE)

A function to plot raw Voronoi diagrams of effective migration and diversity rates

Description

Given a set of EEMS output directories, this function takes random draws from the posterior distribution of the migration and diversity rate parameters. Each draw is visualized as two raw Voronoi diagrams; the migration diagram is saved to a file ending in mvoronoiXX, the diversity diagram is saved to a file ending in qvoronoiXX where XX is a numeric id. Specify the number of times to draw from the posterior with the argument post.draws. If post.draws = 10, then eems.voronoi.samples will generate plots with id XX = 1 to XX = 10. This function differs from eems.posterior.draws() by displaying raw, unsmoothed Voronoi diagrams.

Usage

eems.voronoi.samples(
  mcmcpath,
  plotpath,
  longlat,
  post.draws = 1,
  plot.width = 10,
  plot.height = 10,
  out.png = FALSE,
  res = 600,
  add.grid = FALSE,
  col.grid = "gray80",
  lwd.grid = 1,
  add.outline = TRUE,
  col.outline = "gray80",
  lwd.outline = 2,
  add.demes = FALSE,
  col.demes = "gray80",
  pch.demes = 19,
  cex.demes = 1,
  add.seeds = TRUE,
  col.seeds = "#8AE234",
  pch.seeds = 4,
  cex.seeds = 1,
  eems.colors = NULL,
  m.colscale = NULL,
  q.colscale = NULL,
  add.title = FALSE
)

Arguments

mcmcpath

A vector of EEMS output directories, for the same dataset. Warning: There is minimal checking that the given directories are for the same dataset.

plotpath

The full path and the file name for the graphics to be generated.

longlat

A logical value indicating whether the coordinates are given as pairs (longitude, latitude) or (latitude, longitude).

post.draws

Number of times to sample from the posterior. The default is 1.

plot.width

The width of the graphics region for the two rate contour plots, in inches. The default value is 10.

plot.height

The height of the graphics region, in inches. The default value is 10.

out.png

A logical value which, if set, forces output graphics to be generated as PNGs (if TRUE) or PDFs (if FALSE). Defaults to FALSE.

res

Resolution, in dots per inch; used only for PNG images. The default is 600.

add.grid

A logical value indicating whether to add the population grid or not.

col.grid

The color of the population grid. Defaults to gray80.

lwd.grid

The line width of the population grid. Defaults to 1.

add.outline

A logical value indicating whether to add the habitat outline or not.

col.outline

The color of the habitat outline. Defaults to white.

lwd.outline

The line width of the habitat outline. Defaults to 2.

add.demes

A logical value indicating whether to add the observed demes or not.

col.demes

The color of the demes. Defaults to black.

pch.demes

The symbol, specified as an integer, or the character to be used for plotting the demes. Defaults to 19.

cex.demes

The size of the symbol/character used for plotting observed demes. Defaults to 1.

add.seeds

A logical value indicating whether to add the Voronoi seeds or not.

col.seeds

The color of the Voronoi seeds. Defaults to green.

pch.seeds

The symbol, specified as an integer, or the character to be used for plotting the Voronoi seeds. Defaults to 4.

cex.seeds

The size of the symbol/character used for plotting the Voronoi seeds. Defaults to 1.

eems.colors

The EEMS color scheme as a vector of colors, ordered from low to high. Defaults to a DarkOrange to Blue divergent palette with six orange shades, white in the middle, six blue shades. Acknowledgement: The default color scheme is adapted from the dichromat package.

m.colscale

A fixed range for log10-transformed migration rates. If the estimated rates fall outside the specified range, then the color scale is ignored. By default, no range is specified for either type of rates.

q.colscale

A fixed range for log10-transformed diversity rates.

add.title

A logical value indicating whether to add the main title in the contour plots. Defaults to TRUE.

Details

Note about the implementation: eems.voronoi.samples samples randomly from the posterior draws saved during the execution of EEMS, after burn-in and thinning.

Value

None

References

Light A and Bartlein PJ (2004). The End of the Rainbow? Color Schemes for Improved Data Graphics. EOS Transactions of the American Geophysical Union, 85(40), 385.

See Also

eems.posterior.draws

Examples

# Use the provided example or supply the path to your own EEMS run.
extdata_path <- system.file("extdata", package = "reems")
eems_results <- file.path(extdata_path, "EEMS-example")
# Create a temporary output directory for this example 
outdir <- file.path(tempdir(), "path_out")
dir.create(outdir, showWarnings = FALSE)
name_figures <- file.path(outdir, "eemsplot_out")

# Plot a series of Voronoi diagrams for the EEMS model parameters:
# the effective migration rates (m) and the effective diversity rates (q).
eems.voronoi.samples(
  mcmcpath = eems_results,
  plotpath = paste0(name_figures, "-voronoi-diagrams"),
  longlat = TRUE,
  post.draws = 2,
  out.png = FALSE
)
# Delete the output directory to tidy up. 
unlink(outdir, recursive = TRUE, force = TRUE)

Example coordinate data from ConStruct

Description

Example coordinate data from ConStruct

Usage

ex.coords

Format

ex.coords

A matrix with 16 rows and 2 columns. The rows designate samples and the two columns store the X and Y coordinate respectively. .

Source

https://github.com/gbradburd/conStruct/tree/master/data


Example allele frequency data from ConStruct

Description

Example allele frequency data from ConStruct

Usage

ex.freqs

Format

ex.freqs

A matrix with 16 rows and 10000 columns. The rows designate samples and the columns loci.

Source

https://github.com/gbradburd/conStruct/tree/master/data


Create a habitat with holes

Description

grid.make() constructs a regular triangular grid with circa nDemes vertices. This function creates three files:

Usage

grid.make(outer, holes = NULL, plotpath = NULL, nDemes)

Arguments

outer

A two-column matrix of coordinates of boundary points (longitude, latitude).

holes

List of holes. Each hole is a two-column matrix of coordinates of boundary points (longitude, latitude). This is optional, and defaults to no holes.

plotpath

Output filename for the visualisation PNG file. Optional.

nDemes

Number of demes, roughly, in the grid without accounting for possible holes.

Value

A two-entry list of demes and edges, both two-column matrices.

Examples

# We use example input from Petkova et al. (2016), found in the '/extdata' directory
data_path <- system.file("extdata", package = "reems")
input <- file.path(data_path, "barrier-schemeX-nIndiv300-nSites3000")
# Load the population habitat
outer <- read.table(paste0(input, ".outer"))
# Each hole is a ring (simple closed polygon) and the holes don't overlap
hole1 <- data.frame(V1 = c(2., 5., 5., 2., 2.), V2 = c(2., 2., 5., 5., 2.))
hole2 <- data.frame(V1 = c(6.5, 10., 8., 6.5), V2 = c(2.5, 5., 5., 2.5))

# Create the new grid  with holes
grid.make(outer = outer, holes = list(hole1, hole2), nDemes = 300)

Create a buffered habitat around a set of points.

Description

Creates a polygon a certain distance from each of a set of points. It is used for creating a default habitat outline for eems().

Usage

outer.buffered(coords, d = NULL)

Arguments

coords

A two-column matrix of point coordinates (longitude, latitude).

d

Rough buffer distance. Not necessarily kept completely to keep the polygon simple. Defaults to 0.2 of the length of the hull of the coords.

Value

A two-column matrix of coordinates with the outer boundary points of the containing polygon.

Examples

#  Create a buffer around the example habitat
outer <- outer.buffered(ex.coords)

Estimating Effective Migration Surfaces (EEMS)

Description

Provides several functions to run EEMS analyses and to visualise the results of EEMS. For an exmplanation of and introduction to the EEMS method, see Petkova, D., Novembre, J. & Stephens, M. (2016) <doi:10.1038/ng.3464>.

eems is the main entrypoint, running EEMS analyses on single nucleotide polymorphism data allele frequeny available as R matrices.

eems.from.files runs an EEMS analysis from input data available as tabular files, and correesponds precisely to the original EEMS utility available at <https://github.com/dipetkov/eems>.

eems.plots takes the output of one or more EEMS runs and produces contour plots of the effective migration and diversity rates, as well as scatterplots of observed vs fitted genetic dissimilarities and trace plots to assess convergence.

eems.population.grid plots the population grid, with all edges in the same color, to visualize the grid before estimating migration and diversity rates.

eems.voronoi.samples and eems.posterior.draws both take random samples from the posterior distribution of the migration and diversity rates and plot them to visualize the posterior variance (in a slightly different way).