Package 'tidygenclust'

Title: Clustering for Population Genetics in R
Description: A tidy interface for population genetic clustering. This package provides a unified workflow to estimate, compare, summarize, and visualize genetic clustering analyses, supporting both single runs and collections of replicate analyses. It is designed to work natively with diploid and pseudohaploid data, and integrates seamlessly with the 'tidypopgen' ecosystem.
Authors: Eirlys Tysall [aut], Anahit Hovhannisyan [aut], Evie Carter [aut], Andrea Pozzi [aut], Cecilia Padilla-Iglesias [aut], Michela Leonardi [aut], Aramish Fatima [aut], Ondrej Pelanek [aut], Nile Stephenson [aut], Margherita Colucci [aut], Joan Saurina [aut], Andrea Manica [aut, cre] (ORCID: <https://orcid.org/0000-0003-1895-450X>), Seyoon Ko [cph] (Copyright holder of OpenADMIXTURE.jl, from which parts of the C++ code of gt_radmix() are ported (see inst/COPYRIGHTS)), Kenneth Lange [cph] (Copyright holder of OpenADMIXTURE.jl, from which parts of the C++ code of gt_radmix() are ported (see inst/COPYRIGHTS)), Ioannidis Lab [cph] (Copyright holder of ADAMIXTURE, from which the alternating least squares of gt_radmix() are adapted (see inst/COPYRIGHTS)), Jonas Meisner [cph] (Author of fastmixture, from which the python code of gt_fastmixture() is derived (see inst/COPYRIGHTS)), Xiran Liu [cph] (Author of clumppling, from which the code of gt_clumppling() is ported (see inst/COPYRIGHTS)), Thomas Aynaud [cph] (Copyright holder of python-louvain, from which the Louvain method of gt_clumppling() is ported (see inst/COPYRIGHTS)), Guy Allard [cph] (Copyright holder of markov_clustering, from which the Markov clustering of gt_clumppling() is ported (see inst/COPYRIGHTS)), Andrey Lopatin [cph] (Author of the implementation of the Hungarian algorithm of cp-algorithms (CC BY-SA 4.0), from which the assignment solver of gt_clumppling() is adapted (see inst/COPYRIGHTS)), Alboukadel Kassambara [cph] (Author of ggpubr, from which a helper of the plots of gt_clumppling() is copied (see inst/COPYRIGHTS))
Maintainer: Andrea Manica <[email protected]>
License: GPL (>= 3)
Version: 0.2.0
Built: 2026-12-02 10:16:29 UTC
Source: https://github.com/EvolEcolGroup/tidygenclust

Help Index


autoplot for clumppling objects

Description

An autoplot method to generate quick visualisations for gt_clumppling objects. Available types are:

  • 'modes': all aligned modes in structure plots over a multipartite graph, where better alignment between the modes is indicated by the darker color of the edges connecting their structure plots (the colour scale of the costs of optimal alignment is shown in an empty cell of the grid, if there is one), and the number of replicates in each mode is given in brackets.

  • 'modes_within_k': all the modes with k clusters, in a series of structure plots.

  • 'major_modes': the major modes of each K aligned in a series of structure plots.

  • 'all_modes': all aligned modes in a series of structure plots.

Usage

## S3 method for class 'gt_clumppling'
autoplot(
  object,
  type = c("modes", "modes_within_k", "major_modes", "all_modes"),
  group = NULL,
  k = NULL,
  ...
)

Arguments

object

a gt_clumppling object

type

the type of plot, one of 'modes', 'modes_within_k', 'major_modes' or 'all_modes'.

group

a vector of membership to a-priori groups (e.g. populations). Note that individuals from the same group need to be adjacent to each other

k

the k value to be plotted if 'type' is 'modes_within_k'

...

not used at the moment

Details

autoplot produces simple plots to quickly inspect an object. They are not customisable; we recommend that you use ggplot2 to produce publication ready plots.

If you would like to generate an annotated autoplot, ensure that all individuals from the same population are adjacent to one another in the Q-matrix or gt_admix object supplied to gt_clumppling. Autoplot 'group' argument requires that all individuals from the same group are adjacent.

Value

a plot

Examples

# the runs of ADMIXTURE for K = 2 to 5 of the Cape Verde example of
# clumppling, aligned into modes
capeverde <- readRDS(
  system.file("extdata", "capeverde_admix.rds", package = "tidygenclust")
)
clump_res <- gt_clumppling(capeverde, seed = 1)

# all the modes, linked by the costs of their alignment

autoplot(clump_res, type = "modes")


# the major mode of each K, labelled with the populations (whose
# individuals are adjacent in the Q matrices)
autoplot(clump_res, type = "major_modes", group = capeverde_pops)

# the modes with K = 3
autoplot(clump_res, type = "modes_within_k", k = 3)

Population membership for the Capeverde dataset

Description

Membership to populations for a dataset of 399 individuals, including 44 Cape Verdean. These are the populations of the Cape Verde example of clumppling (Liu, Kopelman and Rosenberg 2024), whose runs of ADMIXTURE are in extdata/capeverde_admix.rds.

Usage

capeverde_pops

Format

A vector of length 399

Source

The example data of clumppling (https://github.com/PopGenClustering/Clumppling), from the Cape Verde data of Verdu P, Jewett EM, Pemberton TJ, Rosenberg NA, Baptista M (2017) Parallel trajectories of genetic and linguistic admixture in a genetically admixed creole population. Current Biology, 27(16), 2529-2535.

Examples

table(capeverde_pops)

ADAMIXTURE algorithm for population genetics clustering

Description

This function runs ADAMIXTURE, a python package for biobank-scale genetic clustering with the model of ADMIXTURE. It combines a spectral initialisation (SVD and ALS) with accelerated block relaxation (BR-QN) to reach high likelihoods with fast convergence. If you use this function, make sure that you cite the paper by Saurina-i-Ricos, Mas Montserrat and Ioannidis (2026).

Usage

gt_adamixture(
  x,
  k,
  n_runs = 1,
  threads = 1,
  seed = 42,
  tol = 0.1,
  max_iter = 10000,
  no_freqs = TRUE,
  cv = NULL,
  verbose = TRUE
)

Arguments

x

either a tidypopgen::gen_tibble, or the name of the binary plink file (without the .bed extension)

k

the number of ancestral components (clusters), either a single value or a vector

n_runs

the number of repeats for each k value (1)

threads

the number of threads to use (1)

seed

the random seed (defaults to 42): a vector of length n_runs, with one seed per run (the same seeds are used for each value of k), or a single seed, used for the first run and incremented for the following ones

tol

the tolerance: the fit stops when the log-likelihood changes by less than tol between iterations (0.1)

max_iter

the maximum number of iterations (10000)

no_freqs

do not save P-matrix (TRUE)

cv

the number of cross-validation folds, greater than 1 (NULL, no cross-validation)

verbose

boolean; should the progress of ADAMIXTURE be printed (TRUE)?

Details

This function returns a gt_admix object that can be plotted with autoplot, and tidied with tidy methods from the tidypopgen package. Cross-validation is not performed by default (cv = NULL); if you want to include cross-validation you can set cv to the number of folds, a value greater than 1 (e.g. 5 for 5-fold cross-validation).

ADAMIXTURE is an optional tool, which is not needed by the rest of tidygenclust (see gt_radmix() for a native implementation of the ADMIXTURE model). It is installed by tgc_tools_install(), or it can be added to an existing ctidygenclust conda environment with tgc_adamixture_install() (only on Linux at the moment, see tgc_tools_install()). Its CPU version, used here, does not need PyTorch.

Value

an object of class gt_admix. See tidypopgen::gt_admixture() for details. As for gt_radmix(), the P matrices give the frequency of the alternate allele of each locus (for PLINK files, of the first allele in the bim file).

References

Saurina-i-Ricos, J., Mas Montserrat, D., & Ioannidis, A. G. (2026). ADAMIXTURE: adaptive first-order optimization for biobank-scale genetic clustering. Bioinformatics, 42(Supplement_1). doi: https://doi.org/10.1093/bioinformatics/btag236

Examples

# ADAMIXTURE is optional: this example only runs if it is installed (see
# tgc_tools_install(), only on Linux at the moment)
if (!is.na(tgc_tools_version()$adamixture)) {
  # the lizard Anolis punctatus, an example dataset of tidypopgen
  vcf_path <- system.file("extdata", "anolis",
    "punctatus_t70_s10_n46_filtered.recode.vcf.gz",
    package = "tidypopgen"
  )
  anole_gt <- tidypopgen::gen_tibble(vcf_path,
    quiet = TRUE, backingfile = tempfile("anolis_")
  )
  anole_ada <- gt_adamixture(anole_gt, k = 2:3, seed = 1, verbose = FALSE)
  anole_ada$Q[[2]]

  # choose K by cross-validation
  anole_ada_cv <- gt_adamixture(anole_gt, k = 2:4, seed = 1, cv = 5,
    verbose = FALSE
  )
  autoplot(anole_ada_cv, type = "cv")
}

Run clumppling

Description

This function aligns multiple runs of a clustering algorithm (e.g. ADMIXTURE or STRUCTURE) with the method of clumppling (Liu, Kopelman and Rosenberg 2024). gt_clumppling() is a native R and C++ port, with modifications to enhance performance, of the python package clumppling (version 2.0.10, by Xiran Liu; https://github.com/PopGenClustering/Clumppling), and gives the same results without the need for Python. The main modifications are that the alignment of each pair of runs, an integer linear program in clumppling, is solved exactly as an equivalent assignment problem (with an implementation of the Hungarian algorithm adapted from cp-algorithms), and that community detection uses ports of the implementations that clumppling uses through cdlib (python-louvain, in C++, and markov_clustering, in R) or the igraph package. The licences of the ported code are in the file COPYRIGHTS of the package (system.file("COPYRIGHTS", package = "tidygenclust")). If you use this function, make sure that you cite the paper on clumppling by Liu, Kopelman, and Rosenberg (2024).

Usage

gt_clumppling(
  x,
  use_rep = TRUE,
  merge = TRUE,
  cd_method = "louvain",
  use_best_pair = TRUE,
  seed = NULL,
  output_path = NULL,
  cd_res = 1,
  test_comm = FALSE,
  comm_min = 1e-06,
  comm_max = 0.01
)

Arguments

x

a gt_admix object with at least two Q matrices

use_rep

boolean, whether to use representative modes (alternative: average), defaults to TRUE

merge

boolean, whether to merge two clusters when aligning K+1 to K, defaults to TRUE

cd_method

the community detection method to use, one of 'louvain' (default), 'leiden', 'infomap', 'markov_clustering', 'label_propagation', 'walktrap', 'custom'. 'leiden', 'infomap', 'label_propagation' and 'walktrap' require the 'igraph' package; as in clumppling (which calls them through 'cdlib'), only 'louvain', 'infomap' and 'markov_clustering' use the similarity between replicates as edge weights, while 'leiden', 'label_propagation' and 'walktrap' only use the presence of edges (all pairs of replicates are connected, except for the most dissimilar pair). 'custom' reproduces the example custom method of clumppling (Markov clustering with a pruning threshold of 0.2); alternatively, cd_method can be a function that takes the adjacency matrix between replicates (similarities rescaled to [0, 1], with ones on the diagonal) and returns a vector of community labels.

use_best_pair

boolean, whether to use best pair as anchor for across-K alignment (alternative: major), defaults to TRUE

seed

(optional) an integer used to set the random seed, so that community detection (e.g. 'louvain') is reproducible. Defaults to NULL (no seed is set).

output_path

deprecated and ignored. Results are returned as R objects rather than written to files.

cd_res

the resolution of the 'louvain' community detection method, defaults to 1

test_comm

boolean, whether to test for community structure (with a Tracy-Widom test) before running community detection; if there is no structure, all replicates form a single mode. Defaults to FALSE.

comm_min, comm_max

cost thresholds for community detection: if all pairwise costs between replicates are below comm_min, they form a single mode; if they are all above comm_max, each replicate is a mode. Defaults to 1e-6 and 1e-2.

Details

The example data (capeverde_admix.rds and chicken_admix.rds in extdata) are the example datasets of clumppling: runs of ADMIXTURE on the Cape Verde data of Verdu et al. (2017), and runs of STRUCTURE on the chicken data of Rosenberg et al. (2001).

The algorithm has three steps:

  1. all pairs of replicates with the same K are aligned, finding the matching of clusters that minimises the squared distance between their memberships;

  2. replicates with the same K are grouped into modes by community detection on the network of alignment costs; each mode is summarised by a representative replicate (the one with the smallest cost to the others) or by the average of its replicates;

  3. modes are aligned across K (merging two clusters of the larger K when two values of K differ by one), and their clusters are reordered so that they are consistent across K.

The replicates are the Q matrices of a gt_admix object, as returned by the clustering functions of 'tidypopgen' (e.g. tidypopgen::gt_admixture()) and 'tidygenclust' (e.g. gt_radmix()); to align replicates stored as Q files, read them into a gt_admix object with tidypopgen::read_q_files(). Replicates with the same K are numbered in the order in which they appear in the gt_admix object. The rows of each Q matrix must sum to 1 (to within 1e-6), so memberships that were rounded (e.g. by STRUCTURE) should be rescaled first.

If you would like to generate an annotated autoplot from your gt_clumppling object, ensure that all individuals from the same population are adjacent to one another in the gt_admix object supplied to gt_clumppling (see tidypopgen::gt_admix_reorder_q()). Autoplot 'group' argument requires that all individuals from the same group are adjacent.

The only random step is community detection. For the default 'louvain' method, the C++ implementation follows python-louvain (used by clumppling), but random numbers are drawn from R's generator: the modes are the same as in python unless the community structure is ambiguous, but the same seed does not give the same random choices in R and python. If seed is given, the state of R's random number generator is restored on exit. When a mode includes replicates with identical Q matrices, the representative of the mode can also differ from the python implementation (it is then an identical replicate), as their costs only differ by rounding errors.

Value

a list of class gt_clumppling containing:

  • aligned_modes: a list of data.frames, each data.frame is a Q-matrix

  • cost_acrossK: a named list of costs for each pairwise K alignment

  • mode_replicates: a list of replicate indices for each mode

  • K_range: vector of K values analyzed

  • N: number of individuals

  • mode_stats: a data.frame with the size, cost and performance (average similarity among replicates) of each mode

References

X. Liu, N. M. Kopelman, N. A. Rosenberg (2024) Clumppling: cluster matching and permutation program with integer linear programming. Bioinformatics 40(1): btad751. doi: https://doi.org/10.1093/bioinformatics/btad751

N. A. Rosenberg, T. Burke, K. Elo, M. W. Feldman, P. J. Freidlin, M. A. M. Groenen, J. Hillel, A. Mäki-Tanila, M. Tixier-Boichard, A. Vignal, K. Wimmers, S. Weigend (2001) Empirical evaluation of genetic clustering methods using multilocus genotypes from 20 chicken breeds. Genetics 159(2): 699-713.

P. Verdu, E. M. Jewett, T. J. Pemberton, N. A. Rosenberg, M. Baptista (2017) Parallel trajectories of genetic and linguistic admixture in a genetically admixed creole population. Current Biology 27(16): 2529-2535.

Examples

capeverde <- readRDS(
  system.file("extdata", "capeverde_admix.rds", package = "tidygenclust")
)
clump_res <- gt_clumppling(capeverde, seed = 1)
clump_res$mode_stats

fastmixture algorithm for population genetics clustering

Description

This function implements the fastmixture algorithm for population genetics clustering by calling the python module. If you use this function, make sure that you cite the relevant paper by Santander, Refoyo-Martínez, and Meisner (2024).

Usage

gt_fastmixture(
  x,
  k,
  n_runs = 1,
  threads = 1,
  seed = 42,
  iter = 1000,
  tole = 1e-09,
  batches = 32,
  supervised = NULL,
  check = 5,
  power = 11,
  chunk = 8192,
  subsample = 0.7,
  min_subsample = 50000,
  max_subsample = 5e+05,
  als_iter = 1000,
  als_tole = 1e-04,
  no_freqs = TRUE,
  random_init = FALSE,
  safety = NULL,
  cv = NULL,
  cv_tole = 1e-07
)

Arguments

x

either a tidypopgen::gen_tibble, or the name of the binary plink file (without the .bed extension)

k

the number of ancestral components (clusters), either a single value or a vector

n_runs

the number of repeats for each k value

threads

the number of threads to use (1)

seed

the random seed (defaults to 42): a vector of length n_runs, with one seed per run (the same seeds are used for each value of k), or a single seed, used for the first run and incremented for the following ones

iter

the maximum number of iterations (1000)

tole

the tolerance in log-likelihood units between iterations (1e-9)

batches

the number of maximum mini-batches (32)

supervised

the name of the file with the supervised labels (NULL)

check

the number of iterations to check for convergence (5)

power

number of power iterations in randomised SVD (11)

chunk

the number of SNPs in chunk operations (8192)

subsample

Fraction of SNPs to subsample in SVD/ALS (0.7)

min_subsample

Minimum number of SNPs to subsample in SVD/ALS (50000)

max_subsample

Maximum number of SNPs to subsample in SVD/ALS (500000)

als_iter

the maximum number of iterations in the ALS algorithm (1000)

als_tole

the tolerance for the RMSE of P between iterations (1e-4)

no_freqs

do not save P-matrix (TRUE)

random_init

random initialisation of parameters (FALSE). By default, as in the fastmixture program, the parameters are initialised from a randomised SVD of the genotypes (followed by alternating least squares), which needs all the loci to be polymorphic; random starting values can take much longer to converge

safety

deprecated and ignored: fastmixture turns on its safety updates by itself when an update is unstable

cv

the number of cross-validation folds, greater than 1 (NULL, no cross-validation)

cv_tole

the tolerance for the cross-validation error in scaled log-likelihood units (1e-7)

Details

This function returns a gt_admix object that can be plotted with autoplot, and tidied with tidy methods from the tidypopgen package. Cross-validation is not performed by default (cv = NULL); if you want to include cross-validation you can set cv to the number of folds, a value greater than 1 (ADMIXTURE performs 5-fold cv as default).

fastmixture is an optional tool, which is not needed by the rest of tidygenclust (see gt_radmix() for a native implementation of the ADMIXTURE model). Install it with tgc_tools_install(tools = "fastmixture"), or add it to an existing ctidygenclust conda environment with tgc_fastmixture_install() (only on Linux at the moment, see tgc_tools_install()).

Value

an object of class gt_admix. See tidypopgen::gt_admixture() for details.

References

C. G. Santander, A. Refoyo Martinez, J. Meisner (2024) Faster model-based estimation of ancestry proportions. bioRxiv 2024.07.08.602454; doi: https://doi.org/10.1101/2024.07.08.602454

Examples

# fastmixture is optional: this example only runs if it is installed (see
# tgc_tools_install(), only on Linux at the moment)
if (!is.na(tgc_tools_version()$fastmixture)) {
  # the lizard Anolis punctatus, an example dataset of tidypopgen
  vcf_path <- system.file("extdata", "anolis",
    "punctatus_t70_s10_n46_filtered.recode.vcf.gz",
    package = "tidypopgen"
  )
  anole_gt <- tidypopgen::gen_tibble(vcf_path,
    quiet = TRUE, backingfile = tempfile("anolis_")
  )
  anole_fm <- gt_fastmixture(anole_gt, k = 2:3, seed = 1)
  anole_fm$Q[[2]]

  # choose K by cross-validation
  anole_fm_cv <- gt_fastmixture(anole_gt, k = 2:4, seed = 1, cv = 5)
  autoplot(anole_fm_cv, type = "cv")
}

Estimate ancestry proportions with the ADMIXTURE method

Description

This function estimates individual ancestry proportions (Q) and the allele frequencies of the ancestral populations (P) with the method of ADMIXTURE (Alexander et al. 2009), i.e. by maximum likelihood under the ADMIXTURE model. It uses the optimisation strategy of ADMIXTURE: a few EM iterations to prime a random start, then block-wise Newton updates of Q and P, each solved as a constrained quadratic program, accelerated by the quasi-Newton scheme of Zhou, Alexander and Lange (2011). It also offers the cross-validation of ADMIXTURE to choose K (Alexander and Lange 2011), a start from a truncated singular value decomposition (SVD) of the genotypes, supervised analyses with individuals of known ancestry, and support for pseudohaploid data. With genotype likelihoods (given by another package, see gt_radmix_data()), it fits the model of NGSadmix (Skotte et al. 2013), the ADMIXTURE model for low-depth sequencing data, with the same algorithm. If you use this function, please cite Alexander et al. (2009) for the method, and, if you use cross-validation, Alexander and Lange (2011); with genotype likelihoods, also cite Skotte et al. (2013).

Usage

gt_radmix(
  x,
  k,
  n_runs = 1,
  seed = NULL,
  max_iter = 1000,
  rtol = 1e-08,
  step_tol = NULL,
  n_em_iter = 5,
  n_qn = 3,
  gl_curvature = c("complete", "observed"),
  init = c("random", "svd"),
  svd_power = 3,
  init_q = NULL,
  init_p = NULL,
  fix_q = FALSE,
  fix_p = FALSE,
  supervised = NULL,
  use_imputed = FALSE,
  crossval = FALSE,
  n_folds = 5,
  cv_max_iter = max_iter,
  cv_rtol = max(rtol, 1e-07),
  n_cores = 1,
  verbose = FALSE
)

Arguments

x

a tidypopgen::gen_tibble, or genotype likelihoods from another package (see "Genotype likelihoods" in the details), possibly grouped

k

an integer vector giving the number(s) of ancestral populations

n_runs

the number of runs for each value of k (defaults to 1)

seed

the seed for the random number generator (defaults to NULL). Either a vector of length n_runs (the same seeds are used for each k) or of length n_runs * length(k). The global random number generator state is restored on exit.

max_iter

the maximum number of iterations (defaults to 1000)

rtol

the convergence threshold on the relative change in log-likelihood between iterations (defaults to 1e-8). A threshold of 1e-7 takes 10-20% less time, but can stop a few log-likelihood units short of convergence, with ancestry proportions up to about 0.05 away from the converged ones

step_tol

optional second convergence threshold: the largest change of any ancestry proportion or allele frequency in the first round of block updates of an iteration (e.g. 1e-4). If given, the fit stops only when both this change and the relative change in log-likelihood fall below their thresholds. Defaults to NULL, to stop on rtol alone. Not used by the refits of cross-validation.

n_em_iter

the number of EM iterations used to prime the estimates (defaults to 5, as in ADMIXTURE); not used with init = "svd"

n_qn

the number of secant pairs used by the quasi-Newton acceleration (defaults to 3, as in ADMIXTURE)

gl_curvature

the curvature used by the Newton steps for genotype likelihoods: "complete" (the default), that of the expected log-likelihood of the genotypes; or "observed", that of the log-likelihood itself (floored), usually faster on low-depth data (see "Genotype likelihoods" in the details). Not used with genotypes, for which the two are the same

init

how the starting values of each run are chosen: "random" (the default), random values followed by n_em_iter EM iterations, as in ADMIXTURE; or "svd", from a truncated SVD of the genotypes, which needs fewer iterations but is not suited to exploring the modes of the likelihood with several runs (see "Starting values from the SVD" in the details). "svd" cannot be combined with init_q or init_p.

svd_power

the number of power iterations of the randomised SVD of genotype likelihoods used by init = "svd" (defaults to 3; see "Starting values from the SVD" in the details). Not used with genotypes, whose truncated SVD is computed by tidypopgen::gt_pca_partialSVD()

init_q

optional matrix (individuals x k) of starting ancestry proportions; only allowed with a single value of k

init_p

optional matrix (loci x k) of starting allele frequencies (of the alternate allele, or of allele2 for genotype likelihoods, as in the P matrices returned by this function; those of tidypopgen::gt_admixture() give the frequency of the reference allele, so use 1 - P); only allowed with a single value of k. If it has row names (as the P matrices returned by this function), they are used to match its rows to the loci of x (it can then include other loci, which are ignored); otherwise its rows must be in the order of the loci of x

fix_q, fix_p

booleans; if TRUE, Q (respectively P) is kept at the value given in init_q (respectively init_p)

supervised

optional vector (character or factor) with one element per individual of x, for a supervised analysis (as ADMIXTURE's --supervised): the population of each reference individual, whose ancestry is then fixed, and NA for the individuals to estimate. k must be a single value, equal to the number of populations. See "Supervised analyses" in the details.

use_imputed

boolean; if TRUE, imputed genotypes are used as if they were observed; otherwise they are treated as missing (the default). Only for genotypes.

crossval

boolean; should the cross-validation error be computed (defaults to FALSE)? See the details (for genotype likelihoods, the error is the deviance of the held-out likelihoods).

n_folds

the number of folds used for cross-validation (defaults to 5, as in ADMIXTURE)

cv_max_iter, cv_rtol

the maximum number of iterations and the convergence threshold of the refit of each fold in cross-validation (default to max_iter, as for the full data, and to 1e-7, or rtol if it is larger). Smaller cv_max_iter or larger cv_rtol make cross-validation faster but bias its errors downwards (see "Cross-validation" in the details).

n_cores

the number of cores to use (defaults to 1); the results do not depend on it

verbose

boolean; should progress be printed (defaults to FALSE)? With verbose = TRUE, the log-likelihood is also computed (and logged) every 5 EM steps during the initial EM iterations; otherwise only their number is logged, as these values are not needed by the algorithm.

Details

Genotypes are read directly from the backing file of the gen_tibble (respecting any filtering of individuals and selection of loci), so no intermediate PLINK file is written; the same holds for genotype likelihoods, which the package that stores them gives to gt_radmix() through a method of gt_radmix_data(). Computation is in C++, multithreaded with OpenMP. The C++ code started as a port of the Julia package OpenADMIXTURE.jl (Ko et al. 2023), and has since been extensively rewritten; its solver of the quadratic programs, its projections, its quasi-Newton step and the structure of its fitting loop are still derived from OpenADMIXTURE.jl, and the alternating least squares of init = "svd" are adapted from ADAMIXTURE (see the file COPYRIGHTS of the package, system.file("COPYRIGHTS", package = "tidygenclust")).

Missing genotypes are ignored in the likelihood. Pseudohaploid individuals (see tidypopgen::gt_pseudohaploid()) contribute a single allele per locus. Only diploid and pseudohaploid gen_tibbles are supported.

P gives the frequency of the alternate allele (allele_alt in tidypopgen::show_loci()) in each ancestral population (for genotype likelihoods, of allele2, often the minor allele; see "Genotype likelihoods" below).

Supplying init_p together with fix_p = TRUE estimates the ancestry of new individuals given the allele frequencies of a reference panel (a "projection" analysis); the loci of x must then match the rows of init_p.

Algorithm

As in ADMIXTURE (Alexander et al. 2009; Alexander and Lange 2011), each run consists of:

  1. a random initialisation followed by a few EM iterations (n_em_iter; the EM algorithm of FRAPPE, Tang et al. 2005), or, with init = "svd", a start from the SVD of the genotypes (see below);

  2. block-wise Newton updates (block relaxation): all of Q given P (one individual at a time, on the simplex), then all of P given the new Q (one locus at a time, in the unit interval). Each Newton step is solved exactly as a small quadratic program, by an active-set method based on the sweep operator (Lange 2010);

  3. quasi-Newton acceleration (Zhou, Alexander and Lange 2011): each iteration applies two rounds of block updates, and the changes that they made in the last n_qn iterations (secant pairs) give a quasi-Newton step, which is accepted only when it improves the log-likelihood of the previous iteration (otherwise the iteration ends with the plain block updates).

Iterations stop when the relative change in log-likelihood falls below rtol (a decrease of the log-likelihood, which can happen after a rejected quasi-Newton point, never counts as convergence) and, if step_tol is given, when the first round of block updates of the iteration changes no ancestry proportion or allele frequency by more than step_tol. That change, reported in the log of each iteration as "step", shows how far the estimates still are from converged, in their own units. All estimates are kept within [1e-5, 1 - 1e-5], as in ADMIXTURE. The log of each run (element log of the result) reports the log-likelihood at each iteration, together with that of the quasi-Newton point ("QN") and that of the plain block updates ("basic"). The latter is only computed when the quasi-Newton point is rejected (otherwise it is reported as "not computed"), which saves a pass over the genotypes in most iterations.

A few numerical safeguards handle degenerate cases, without changing the results when the computations are well behaved: for example, a Newton step that is not finite (because a genotype is impossible under the current estimates) is discarded, and the individual or locus keeps its current value for that iteration.

Genotype likelihoods

With genotype likelihoods, the genotypes are not observed: each individual has the likelihoods of its data (its reads) given each of the three genotypes at a locus, with 0, 1 and 2 copies of allele2. tidygenclust does not store them: a package that does can provide a method of gt_radmix_data() for its class. The model is that of NGSadmix (Skotte et al. 2013): the genotypes follow the ADMIXTURE model, with P the frequency of allele2, and the log-likelihood is

∑ijlog⁡∑g=02P(Dij∣g)P(g∣xij),\sum_{ij} \log \sum_{g=0}^{2} P(D_{ij} | g) P(g | x_{ij}),

where xij=∑kqikpkjx_{ij} = \sum_k q_{ik} p_{kj}, P(g∣x)P(g | x) is binomial (Hardy-Weinberg proportions), and the likelihoods P(Dij∣g)P(D_{ij} | g) of each individual are normalised to sum to 1, as in the beagle files read by NGSadmix. Individuals without data at a locus do not contribute to it, whereas NGSadmix counts log⁡(1/3)\log(1/3) for each of them (they have three equal likelihoods): otherwise, the log-likelihoods of the two programs are the same.

The algorithm is the same as for genotypes: every step uses the expected numbers of copies of each allele given the likelihoods and the current estimates in place of the observed ones. EM steps are then those of NGSadmix, and the gradients of the block updates are exact; as the log-likelihood of genotype likelihoods is not concave in each block, the Newton steps use by default the curvature of the expected log-likelihood of the genotypes (that of the EM algorithm), which keeps every quadratic program convex. That curvature exceeds the curvature of the log-likelihood itself by the missing information (the uncertainty about the genotypes), so the steps are short where genotypes are uncertain. With gl_curvature = "observed", the Newton steps use the curvature of the log-likelihood instead, floored at a quarter of the complete one for each individual and locus (which keeps the programs convex). On simulated data at depths of 1-2 reads per site, with K from 3 to 10, this made fits about 1.5 times faster (fewer iterations, at the same cost each), and the fits reached maxima at least as good; as it changes the path of each fit, the maxima found by a given run can differ. The quasi-Newton steps are accepted on the log-likelihood above. Cross-validation (crossval) is available (see "Cross-validation"), and so are starts from the SVD (init = "svd"): the SVD is then that of the posterior dosages of the genotypes (their expected numbers of copies of allele2) under Hardy-Weinberg proportions with the allele frequencies estimated from the likelihoods (emMAF, Kim et al. 2011), as in the first step of PCAngsd (Meisner and Albrechtsen 2018), computed by a randomised SVD (Halko et al. 2011) whose products are passes over the likelihoods; individuals without data at a locus get the mean dosage. use_imputed is not available for genotype likelihoods. Unlike NGSadmix, which by default drops loci with a minor allele frequency below 0.05 (its option -minMaf), gt_radmix() uses all the loci of x: select them beforehand if needed.

Supervised analyses

As with ADMIXTURE's --supervised option, the ancestry of some individuals can be given rather than estimated: supervised gives the population of each of these reference individuals (and NA for the individuals to estimate), and each population is one of the k ancestral populations, so k must equal the number of populations in supervised. The ancestry proportions of each reference individual are fixed at 1 for its population and 0 for the others (moved inside the feasible set like every estimate, i.e. 1 - (k - 1) 1e-5 and 1e-5, as reported by ADMIXTURE); the allele frequencies of the ancestral populations (P) are estimated from all the individuals, and the ancestry of the other individuals is estimated given them. Each column of Q and P is one reference population: in the order of the levels of supervised if it is a factor, or of their first appearance otherwise (the order used by ADMIXTURE for the populations of its .pop file). The populations are listed in the element ref_pops of the result (the columns of Q keep the names .Q1, .Q2, ..., which tidypopgen's methods expect).

The fit is the same as in an unsupervised analysis (random start, EM priming, block updates and quasi-Newton steps), with the reference individuals fixed from the start; their ancestry proportions are never updated, and the passes over the genotypes skip the work that only serves them, so a supervised fit with many reference individuals is faster than an unsupervised one. Cross-validation (crossval = TRUE) is available, as in ADMIXTURE: the reference individuals stay fixed in the fit of each fold, and their genotypes belong to the folds and are predicted like the others (ADMIXTURE does not document this detail). init_q (whose rows for the reference individuals are ignored) and init_p can give starting values; fix_q, fix_p and init = "svd" cannot be combined with supervised. Supervised analyses are also available for genotype likelihoods.

When the reference individuals are many, starting P from the allele frequencies of the reference populations, as fastmixture does in its supervised mode, can save iterations: pass them as init_p (the frequency of the alternate allele, e.g. from tidypopgen::loci_alt_freq() on the individuals of each population, in the order of the columns), with n_em_iter = 0 (the individuals to estimate then start from random values). On the HGDP data (K = 5, 660 of 1043 individuals as references), this took 7 iterations instead of 11 and 5 EM steps, to the same log-likelihood; with fewer references (EUR_subset, 102 of 379), it made no difference.

Starting values from the SVD

With init = "svd", each run starts from the principal components of the genotypes rather than from random values, as in ADAMIXTURE (Saurina-i-Ricos et al. 2026) and fastmixture (Santander et al. 2024):

  1. a truncated SVD of the genotypes, computed by tidypopgen::gt_pca() (centred and scaled as by default there) with max(k) + 5 components, is computed once and shared by all the runs (monomorphic loci are left unscaled);

  2. for each run, alternating least squares (ALS) find Q and P whose product approximates the allele frequencies predicted by the first k + 5 components, starting from random allele frequencies. As in ADAMIXTURE, the least squares are bounded, the loci are weighted by the inverse of their binomial variance when solving for Q, and Q is extrapolated (momentum) when solving for P. The ALS only uses the SVD, not the genotypes, so it is fast;

  3. the best of 3 such solutions, by log-likelihood, starts the fit, without EM priming (n_em_iter is not used).

Missing genotypes need no imputation: as in gt_pca() (and PLINK 1.9), each pair of individuals is compared over the loci genotyped in both, and pseudohaploids enter the SVD as homozygous diploids. With more than 20,000 individuals, the SVD is a randomised SVD (gt_pca(method = "random")), which cannot use missing genotypes, so they must then be imputed first (e.g. with tidypopgen::gt_impute_simple()). Imputed genotypes, if any, are only used for the SVD, and the fit ignores them (unless use_imputed = TRUE). The SVD also needs more individuals and loci than max(k) + 5. With genotype likelihoods, the SVD is that of the posterior dosages (see "Genotype likelihoods"), and needs no imputation; its random test matrix is drawn after setting the first value of seed, and its number of power iterations is svd_power (3 by default, enough for the leading components, those of the structure; each further iteration makes the trailing components more accurate at the cost of two more passes over the likelihoods).

Fits from the SVD need fewer iterations (often less than half as many as from random starts in our tests), and usually reach a good fit (though, as from any start, not always the best one). They are therefore useful for a single good fit of a large dataset, where many random runs would be costly, or as a first exploration before a more extensive search with random starts. However, the starts of different runs vary little, and favour some solutions over others: to explore the modes of the likelihood with several runs (e.g. with gt_clumppling()), use random starts (the default), and do not mix runs started in the two ways, as the runs started from the SVD would over-represent the solutions that they favour.

Cross-validation

With crossval = TRUE, the cross-validation error of ADMIXTURE (Alexander and Lange 2011) is computed for each run, and can be used to choose k (lower is better; see autoplot(type = "cv")). The observed genotypes are split into n_folds folds of roughly equal size; for each fold, the model is refitted with the genotypes of that fold treated as missing, and each of them is predicted by its expected value μ=n∑kqikpkj\mu = n \sum_k q_{ik} p_{kj}, where nn is the number of allele copies of the individual. The error is the binomial deviance

d(g,μ)=glog⁡(g/μ)+(n−g)log⁡((n−g)/(n−μ))d(g, \mu) = g \log(g / \mu) + (n - g) \log((n - g) / (n - \mu))

averaged over all the masked genotypes of all folds. Where ADMIXTURE does not document the details, we made the following choices:

  • each fold is fitted starting from the estimates for the full data, with at most max_iter iterations and a convergence threshold of 1e-7 (or rtol, if larger) by default (see below for cv_max_iter and cv_rtol);

  • genotypes are assigned to folds by a hash of their position and of a seed drawn from the random number generator (reproducible with seed), so the folds differ from those of ADMIXTURE and the errors agree with ADMIXTURE's closely but not exactly;

  • pseudohaploid individuals use n=1n = 1.

With genotype likelihoods, the folds are drawn over the individuals and loci with data, in the same way, and the error of a masked individual and locus is the deviance of its likelihoods,

d=log⁡max⁡xf(x)−log⁡f(xij),d = \log \max_x f(x) - \log f(x_{ij}),

where f(x)=∑gP(Dij∣g)P(g∣x)f(x) = \sum_{g} P(D_{ij} | g) P(g | x) is the likelihood of its data given a frequency xx of allele2 (see "Genotype likelihoods"), maximised over xx in [0,1][0, 1], and xijx_{ij} is the prediction of the refitted model. For the likelihoods of a hard call, this is the binomial deviance above (with n=2n = 2); with uncertain genotypes, the errors are smaller, as the data say less about each genotype, so they can be compared across values of k but not with those of genotypes.

Cross-validation does not change the estimates of Q and P, but requires n_folds additional fits for each run (each usually converging in a few iterations).

The refits of the folds stop earlier than the fit to the full data (cv_rtol = 1e-7, against rtol = 1e-8), and can be shortened further with cv_max_iter (at most that many iterations per fold; ADAMIXTURE refits each fold with 5) or a larger cv_rtol. This saves time, but biases the errors downwards: each refit starts from the estimates for the full data, which have seen the masked genotypes, and a refit stopped early still predicts them too well, the more so at larger k. In our tests, the default halved the cost of cross-validation on EUR_subset (379 individuals, 54,051 loci, k = 1-6, 5 seeds), where refits run to rtol took 24 iterations on average, and lowered the errors by at most 1.5e-5 up to k = 4, and by 1.2e-4 and 2e-4 at k = 5 and 6, while the errors of successive values of k differed by 5e-4 to 3e-3. On the HGDP (1,043 individuals, 130,943 loci, k = 2-10, 3 seeds), where refits converge in about 7 iterations, it saved 11% of the passes and changed the errors by less than 1e-6. Shorter refits save more on EUR_subset (cv_rtol = 1e-6: 74%; cv_max_iter = 5: 80%) with larger biases (up to 6.7e-4 and 1e-3 at k = 6). None of these choices changed the value of k with the lowest error, for any seed. To refit each fold to convergence, set cv_rtol = rtol.

Reproducibility

The random starting values (and the folds of cross-validation) are drawn from R's random number generator, so runs are reproducible with seed (or set.seed()). The work is divided between threads in a way that depends only on the dimensions of the data, so the results are identical for any n_cores.

On x86-64 Linux, when the package is compiled with GCC 12 or later, the main computations are also compiled for processors with the AVX2 and FMA instructions (most processors made since 2015), and the faster version is chosen when the package is loaded. Results are reproducible on a given machine, but can differ in the last digits between machines with and without these instructions. Compiling the package with -DRADMIX_NO_MULTIVERSION (e.g. added to CXXFLAGS in ⁠~/.R/Makevars⁠) builds only the portable version, whose results are the same on every x86-64 machine.

Data larger than the memory

The genotypes (or likelihoods) are read from their memory-mapped backing file at every pass, and never copied into memory, so data larger than the memory can be analysed: the operating system reads the file again as needed. When the file read by a pass is larger than 0.8 times the memory available (on Linux, MemAvailable or the limit of the control group), the passes stream it: all the threads work on one chunk of loci at a time, a helper thread asks the operating system to read the next chunk meanwhile, and the passes that can take the chunks in any order alternate their direction, so that each starts with the data that the previous one left in memory. Genotypes that fit in memory, with 8,192 individuals or more, have the passes over the individuals in chunks of loci too (all the threads reading the same part of the file), which is faster. The results are identical. The option tidygenclust.radmix_stream forces streaming on (TRUE) or off (FALSE, which also turns off the chunks in memory), and tidygenclust.radmix_chunk_mb sets the size of the chunks (by default a sixteenth of the memory available, between 16 and 256 MB, when streaming, and 64 MB in memory). Each pass still reads the part of the file that is not in memory, so a fit runs at the speed of the disk once the data are much larger than the memory.

Comparison with ADMIXTURE

The model, the log-likelihood and the optimisation strategy are those of ADMIXTURE (Alexander et al. 2009; Alexander and Lange 2011), so both programs reach the same maximum likelihood estimates, up to local optima and the convergence criterion (ADMIXTURE stops when the log-likelihood increases by less than 1e-4 between iterations). The test suite checks this on the EUR_subset data of SnpArrays.jl. Note that:

  • ADMIXTURE reports the frequency of the second allele in the PLINK bim file, which for a gen_tibble is the reference allele, so its P matrices are 1 - P of those returned here;

  • cross-validation follows ADMIXTURE (see above), and the test suite checks that the errors agree with those of ADMIXTURE on EUR_subset;

  • ADMIXTURE treats the autosomal genotypes of every individual as diploid, whereas gt_radmix() counts a single allele per locus for pseudohaploid individuals (see above);

  • supervised analyses (supervised) follow ADMIXTURE's --supervised option: the same fixed ancestry of the reference individuals, the same order of the populations, and the same requirement that k equals their number; supervised gives the populations as a vector (with NA for the individuals to estimate) instead of a .pop file (with -). The test suite checks the estimates against those of ADMIXTURE on EUR_subset;

  • bootstrap standard errors, available in ADMIXTURE, are not implemented.

Value

an object of class gt_admix, a list with elements:

  • k the number of clusters of each run

  • Q a list of tidypopgen::q_matrix() objects with the ancestry proportions

  • P a list of matrices (loci x k) with the alternate allele frequencies (frequencies of allele2 for genotype likelihoods)

  • log a list with the log of each run

  • loglik the log-likelihood of each run

  • converged whether each run converged

  • cv the cross-validation error of each run (if crossval is TRUE)

  • id the id column of x

  • group the group column of x (if x is grouped)

  • ref_pops the reference population of each column of Q and P (only for a supervised analysis)

  • algorithm "radmix"

References

Alexander DH, Novembre J, Lange K (2009) Fast model-based estimation of ancestry in unrelated individuals. Genome Research, 19(9), 1655-1664.

Alexander DH, Lange K (2011) Enhancements to the ADMIXTURE algorithm for individual ancestry estimation. BMC Bioinformatics, 12, 246.

Zhou H, Alexander D, Lange K (2011) A quasi-Newton acceleration for high-dimensional optimization algorithms. Statistics and Computing, 21(2), 261-273.

Tang H, Peng J, Wang P, Risch NJ (2005) Estimation of individual admixture: analytical and study design considerations. Genetic Epidemiology, 28(4), 289-301.

Lange K (2010) Numerical Analysis for Statisticians, 2nd edition. Springer, New York.

Ko S, Chu BB, Peterson D, Okenwa C, Papp JC, Alexander DH, Sobel EM, Zhou H, Lange KL (2023) Unsupervised discovery of ancestry-informative markers and genetic admixture proportions in biobank-scale datasets. The American Journal of Human Genetics, 110(2), 314-325.

Saurina-i-Ricos J, Mas Montserrat D, Ioannidis AG (2026) ADAMIXTURE: adaptive first-order optimization for biobank-scale genetic clustering. Bioinformatics, 42(Supplement_1). doi: https://doi.org/10.1093/bioinformatics/btag236

Santander CG, Refoyo Martinez A, Meisner J (2024) Faster model-based estimation of ancestry proportions. Peer Community Journal, 4, e115. doi: https://doi.org/10.24072/pcjournal.503

Skotte L, Korneliussen TS, Albrechtsen A (2013) Estimating individual admixture proportions from next generation sequencing data. Genetics, 195(3), 693-702.

Kim SY, Lohmueller KE, Albrechtsen A, Li Y, Korneliussen T, Tian G, Grarup N, Jiang T, Andersen G, Witte D, Jorgensen T, Hansen T, Pedersen O, Wang J, Nielsen R (2011) Estimation of allele frequency and association mapping using next-generation sequencing data. BMC Bioinformatics, 12, 231.

Meisner J, Albrechtsen A (2018) Inferring population structure and admixture proportions in low-depth NGS data. Genetics, 210(2), 719-731.

Halko N, Martinsson PG, Tropp JA (2011) Finding structure with randomness: probabilistic algorithms for constructing approximate matrix decompositions. SIAM Review, 53(2), 217-288.

Examples

bed_file <-
  system.file("extdata", "pop_a.bed", package = "tidypopgen")
pop_a <- tidypopgen::gen_tibble(bed_file,
  backingfile = tempfile("pop_a"),
  quiet = TRUE
)
adm <- gt_radmix(pop_a, k = 2, seed = 1)
adm$Q[[1]]

# choose k by cross-validation
adm_cv <- gt_radmix(pop_a, k = 1:3, seed = 1, crossval = TRUE)
adm_cv$cv

# supervised analysis: the first two individuals are references of
# population "A" and the next two of population "B"; the ancestry of the
# others is estimated
pops <- rep(NA, nrow(pop_a))
pops[1:4] <- c("A", "A", "B", "B")
adm_sup <- gt_radmix(pop_a, k = 2, seed = 1, supervised = pops)
adm_sup$ref_pops
adm_sup$Q[[1]]

Subset a gt_clumppling object

Description

This function subsets gt_clumppling objects to a set of individuals or a set of values of K. This is intended to create plot insets, or to visualise a subset of individuals during data analysis. To understand the modes within a subset of individuals in your data, you should subset your gt_admix object and re-run gt_clumppling.

Usage

subset_gt_clumppling(x, k = NULL, indivs = NULL)

Arguments

x

a gt_clumppling object

k

a vector of values of K to subset to: consecutive values of K_range (e.g. c(17, 19) if K_range is 17, 19 and 21), in increasing order

indivs

a vector of individual indices to keep

Value

a gt_clumppling object subsetted to the individuals specified

Examples

# the runs of ADMIXTURE for K = 2 to 5 of the Cape Verde example of
# clumppling, aligned into modes
capeverde <- readRDS(
  system.file("extdata", "capeverde_admix.rds", package = "tidygenclust")
)
clump_res <- gt_clumppling(capeverde, seed = 1)

# the modes with K = 3 and 4
clump_k34 <- subset_gt_clumppling(clump_res, k = c(3, 4))
autoplot(clump_k34, type = "modes")

# the Cape Verdean individuals only, e.g. for an inset (their modes are
# still those of all the individuals, and autoplot() warns about it)
cape_verdeans <- which(capeverde_pops == "Cape Verdean")
clump_cv <- subset_gt_clumppling(clump_res, indivs = cape_verdeans)
clump_cv$N

Add ADAMIXTURE to the conda environment of tidygenclust

Description

ADAMIXTURE (used by gt_adamixture()) is an optional tool. This function adds it to an existing ctidygenclust environment (created with tgc_tools_install()), or installs another version, from PyPI. Its CPU version, used by gt_adamixture(), does not need PyTorch. Like the other optional tools, it is only available on Linux at the moment (see tgc_tools_install()).

Usage

tgc_adamixture_install(adamixture_version = "1.9.6")

Arguments

adamixture_version

a string with the version of ADAMIXTURE to install from PyPI. Default is the latest tested version.

Value

NULL (invisibly)

Examples

## Not run: 
# installs software in a conda environment (only on Linux at the moment)
tgc_adamixture_install()

## End(Not run)

Add ADMIXTURE to the conda environment of tidygenclust

Description

ADMIXTURE (used by tidypopgen::gt_admixture()) is an optional tool. This function adds it to an existing ctidygenclust environment (created with tgc_tools_install()). Like the other optional tools, it is only available on Linux at the moment (see tgc_tools_install()).

Usage

tgc_admixture_install(conda_yaml = "auto", ci_install = FALSE)

Arguments

conda_yaml

only used on OSX (not supported at the moment): the path of the yaml file used to create the cadmixture86 environment, "auto" (the default, the latest tested yaml) or NULL (the latest version of ADMIXTURE in bioconda). See tgc_tools_install().

ci_install

a boolean indicating if the installation is being run on continuous integration (CI) services. Default is FALSE. If TRUE, the function will look for the conda yaml file in the inst/env_snapshots folder of the package source directory, rather than in the installed package directory. This is useful when testing the package on CI services.

Value

NULL (invisibly)

Examples

## Not run: 
# installs software in a conda environment (only on Linux at the moment)
tgc_admixture_install()

## End(Not run)

Add fastmixture to the conda environment of tidygenclust

Description

fastmixture (used by gt_fastmixture()) is an optional tool. This function adds it to an existing ctidygenclust environment (created with tgc_tools_install()), or reinstalls it. Like the other optional tools, it is only available on Linux at the moment (see tgc_tools_install()).

Usage

tgc_fastmixture_install(
  fastmixture_hash = "1f03a8980be4872341e5faca9d6f2dfc7ccbfe35"
)

Arguments

fastmixture_hash

a string with the commit hash of the fastmixture version to install. Default is the latest tested version.

Value

NULL (invisibly)

Examples

## Not run: 
# installs software in a conda environment (only on Linux at the moment)
tgc_fastmixture_install()

## End(Not run)

Install optional tools for tidygenclust

Description

The core functionality of tidygenclust is native: gt_radmix() and gt_clumppling() need neither Python nor conda. A few additional features rely on external tools, which are optional and are only installed on request:

Usage

tgc_tools_install(
  tools = c("fastmixture", "admixture", "adamixture"),
  reset = FALSE,
  fastmixture_hash = "1f03a8980be4872341e5faca9d6f2dfc7ccbfe35",
  adamixture_version = "1.9.6",
  conda_yaml = "auto",
  ci_install = FALSE
)

Arguments

tools

a vector with the tools to install, any of "fastmixture", "admixture" and "adamixture". Defaults to all of them.

reset

a boolean used to reset the virtual environment. Only set to TRUE if you have a broken virtual environment that you want to reset.

fastmixture_hash

a string with the commit hash of the fastmixture version to install. Default is the latest tested version.

adamixture_version

a string with the version of ADAMIXTURE to install from PyPI. Default is the latest tested version.

conda_yaml

A vector of string with the path for the yaml files used for installation (one for ctidygenclust and, for osx only, one for admixture in x86 compatibility mode). The value of each string can either be "auto" (the default, select the latest available yaml that has been tested to work on a given operating system), NULL (let conda attempt to install the latest available packages from the internet), or a path to a specific conda yaml found in "inst/env_snapshots". For "auto" or NULL, it is also possible to provide a vector of length one, and the value will apply to all the conda environments (e.g. conda_yaml="auto" is equivalent to conda_yaml = c("auto", "auto") in osx); a single path is used for ctidygenclust (and "auto" for the environment of ADMIXTURE on osx). Tools that are not in tools are left out of the yaml files, as is fastmixture, which is always installed from github.

ci_install

a boolean indicating if the installation is being run on continuous integration (CI) services. Default is FALSE. If TRUE, the function will look for the conda yaml file in the inst/env_snapshots folder of the package source directory, rather than in the installed package directory. This is useful when testing the package on CI services.

Details

We use reticulate to install them in a conda environment, ctidygenclust.

The optional tools are only available on Linux at the moment. On Windows, they can be used through the Windows Subsystem for Linux (WSL). On macOS, the OpenMP library of the python tools conflicts with the one used by R packages such as bigstatsr, which crashes the R session.

tgc_tools_install() creates the conda environment with the chosen tools. If the environment already exists, it only adds the tools that are not installed yet (alternatively, use tgc_fastmixture_install(), tgc_admixture_install() and tgc_adamixture_install() to add a tool to an existing environment). tgc_tools_version() reports the tools that are installed.

For each tool, default to the latest version of these packages that has been tested to work with tidygenclust. It is possible to provide a more recent github commit for a specific tool, but this might lead to incompatibilities and errors.

The conda environment is created from a conda yaml file with the versions of all the packages that have been tested on each operating system (see conda_yaml); fastmixture is then installed from its github repository, and ADAMIXTURE from PyPI, with pip, run in the environment with reticulate::conda_run2(). If the installation fails with the tested yaml, you can try conda_yaml = NULL to let conda install the latest available packages.

Value

NULL (invisibly)

Examples

## Not run: 
# installs software in a conda environment (only on Linux at the moment):
# all the tools
tgc_tools_install()

# or, alternatively, only fastmixture (other tools already in the
# environment are kept)
tgc_tools_install(tools = "fastmixture")

## End(Not run)

Print version of the optional tools installed by tidygenclust

Description

This function returns the version of the optional tools installed by tgc_tools_install(): fastmixture, ADMIXTURE and ADAMIXTURE. Tools that are not installed have version NA.

Usage

tgc_tools_version()

Value

A list with the version of the optional tools installed by tidygenclust

Examples

tgc_tools_version()

Tidy a gt_clumppling object

Description

A tidy method to extract information from a gt_clumppling object, and return it as a tibble. It can extract:

  • 'modes': all the modes detected by gt_clumppling(). The modes have label 'KxMy', where 'x' and 'y' represent the K value and the mode rank.

  • 'major_modes': modes of rank 1 for each K.

  • 'Q_modes', 'q_modes': a list of q matrices, one per mode, each tidied into a tibble

  • 'Q_major_modes', 'q_major_modes': the same output as 'Q_modes' but subsetted to only the major modes.

Usage

## S3 method for class 'gt_clumppling'
tidy(
  x,
  matrix = c("modes", "major_modes", "Q_modes", "q_modes", "Q_major_modes",
    "q_major_modes"),
  ...
)

Arguments

x

the gt_clumppling object

matrix

a string defining the information to be extracted, one of: "modes", "major_modes", "Q_modes" (or "q_modes"), "Q_major_modes" (or "q_major_modes").

...

Additional arguments. Not used. Needed to match generic signature only.

Value

a tibble::tibble of the information of interest (for "Q_modes" and "Q_major_modes", a named list of tibbles, one per mode)

Examples

# the runs of ADMIXTURE for K = 2 to 5 of the Cape Verde example of
# clumppling, aligned into modes
capeverde <- readRDS(
  system.file("extdata", "capeverde_admix.rds", package = "tidygenclust")
)
clump_res <- gt_clumppling(capeverde, seed = 1)

# the modes, with their K, their rank within K and their label
tidy(clump_res, matrix = "modes")

# the ancestry proportions of the major modes, one tibble per mode
q_major <- tidy(clump_res, matrix = "Q_major_modes")
names(q_major)
q_major[["K3M1"]]