Skip to content

popgen

The ipyrad2 popgen tool makes it easy to compute population-genetic summary statistics from an assembled RAD-seq dataset while addressing the impacts of missing data.

Currently supported metrics include: pi, dxy, fst, tajima_d, theta_w, heterozygosity, fis, and sfs. Most metrics can be computed either genome-wide or in sliding windows on reference-based assemblies.

When to Use

Use popgen when you want population-level summaries directly inside ipyrad2 rather than exporting to another package first.

This command is most useful when you want:

  • quick within-population diversity summaries
  • pairwise divergence or differentiation summaries between populations
  • a folded, genome-wide site-frequency spectrum
  • optional windowed summaries on sequence-backed assemblies

Prerequisites

  • An input HDF5 from ipyrad2 assemble
  • A population map (IMAP) file if you want multi-population summaries
  • An understanding of how much missing data remains in your assembled dataset

For hard-call summaries and the uniform likelihood prior, omitting --imap treats retained samples as one reporting population named all. Population and SFS likelihood priors require an explicit --imap. This differs from assemble --genotype-model sfs, where omitting --populations fits a separate singleton SFS for each sample.

Inputs and Backends

--stats all means:

  • On sequence-backed input: run pi, dxy, fst, tajima_d, theta_w, heterozygosity, fis, and sfs
  • On SNP-backed input: run fst, heterozygosity, fis, and sfs

Windowing is only available on sequence-backed HDF5. If you request genomic or locus windows on SNP-only HDF5, the command errors.

Population Grouping and Filtering

Population membership is controlled with --imap. Each retained sample must belong to exactly one population for the per-sample and per-population summary tables.

--minmap controls the per-population minimum number of called samples required for site-based summaries. This matters most for pairwise and within-population summaries when missingness differs across populations.

The main dataset filters are:

  • --min-sample-coverage: remove sites that do not meet the required sample coverage
  • --max-sample-missing: drop samples with too much missing data before the analysis
  • --min-minor-allele-frequency: remove low-frequency SNPs in SNP-backed runs
  • --exclude: remove named samples before population summaries are calculated
  • -R, --include-reference: include the assembly reference sequence if present
  • --subsample-unlinked: for SNP-backed runs, subsample one SNP per linkage block
  • --seed: control the random seed for unlinked SNP subsampling

Missing data are not imputed in popgen.

Current missing-data behavior is:

  • Sequence backend: N and gap - are treated as missing
  • SNP backend: missing genotype calls are excluded from allele-count summaries

As a general rule, stronger filtering is usually safer than imputation for these estimators. Most of these statistics are designed around observed allele counts, and imputation can distort rare alleles, heterozygosity, and population differences.

Command Patterns

Sequence-backed full panel for grouped samples:

ipyrad2 analysis popgen \
  -d assembly.hdf5 \
  -i populations.tsv \
  --stats all \
  -o POPGEN_OUT

SNP-backed heterozygosity, Fis, FST, and SFS with one unlinked SNP per locus:

ipyrad2 analysis popgen \
  -d snps.hdf5 \
  -i populations.tsv \
  --stats all \
  --subsample-unlinked \
  --seed 7 \
  -o POPGEN_OUT

Sequence-backed genomic windows:

ipyrad2 analysis popgen \
  -d assembly.hdf5 \
  -i populations.tsv \
  --stats pi,fst,fis \
  --window-size 50000 \
  --step-size 10000 \
  -o POPGEN_WINDOWS

Sequence-backed anonymous RAD-style locus windows:

ipyrad2 analysis popgen \
  -d assembly.hdf5 \
  -i populations.tsv \
  --stats pi,dxy,fst \
  --loci-per-window 50 \
  --locus-step 10 \
  -o POPGEN_LOCUS_WINDOWS

Outputs

popgen writes a manifest plus one or more TSV tables, depending on which statistics were requested.

Current outputs are:

  • <name>.manifest.txt
  • <name>.sample_stats.tsv
  • <name>.population_stats.tsv when population-level scalar statistics are requested
  • <name>.pairwise_stats.tsv when pairwise statistics are requested
  • <name>.sfs.tsv when sfs is requested
  • <name>.window_population_stats.tsv when windowed population summaries are requested
  • <name>.window_pairwise_stats.tsv when windowed pairwise summaries are requested

Two important current behaviors:

  • popgen does not write a separate stats.txt
  • popgen does not currently write sample_data_summary.tsv as a separate file

Instead, the manifest embeds a Sample Data Summary section showing:

  • sample
  • missing_fraction
  • post_imputation_missing_fraction
  • imputation_algorithm
  • imputed_genotype_fraction

For popgen, that embedded table documents that the data were not imputed.

sample_stats.tsv

This is the per-sample summary table. It records:

  • the population assignment for each retained sample
  • total sites examined for that sample
  • called and missing site counts
  • called and missing fractions
  • homozygous and heterozygous called-site counts
  • observed heterozygosity per sample

This table is often the first place to check for sample-level missingness problems before interpreting population summaries.

population_stats.tsv

This table contains within-population summaries. The exact columns depend on the requested statistics, but can include:

  • pi
  • theta_w
  • tajima_d
  • observed_heterozygosity
  • expected_heterozygosity
  • fis

It also includes the site counts actually used for each class of estimator, which matters because different statistics can retain different site sets under missing-data filters.

pairwise_stats.tsv

This table contains pairwise population comparisons. Depending on the backend and requested statistics it can include:

  • dxy
  • fst

Each row also reports sites_used, which is critical for interpretation when populations have uneven missing data.

sfs.tsv

This table reports a folded, genome-wide site-frequency spectrum by population using:

  • population
  • minor_allele_count
  • site_count

It is currently genome-wide only. Windowed SFS is not written in this phase.

Windowed Analyses

Windowing is currently supported only for sequence-backed HDF5.

There are two windowing modes:

  • Genomic windows: --window-size with optional --step-size
  • Consecutive-locus windows: --loci-per-window with optional --locus-step

Genomic windows use scaffold coordinates. Locus windows slide across consecutive phymap loci and are useful for RAD-style data where fixed genomic spans may be less informative.

Windowed runs still write the genome-wide outputs. The window tables are additional outputs, not replacements.

Current window metadata columns include:

  • window_id
  • window_mode
  • scaffold
  • start
  • end
  • first_locus
  • last_locus
  • nloci
  • sites_total

window_mode is either:

  • genomic
  • locus

Statistic Guide

pi

pi is within-population nucleotide diversity, or mean pairwise difference per site within a population.

In ipyrad2, pi is calculated from per-site allele counts using unbiased gene diversity and then averaged across retained sites with enough called chromosomes. For the sequence backend, ambiguous IUPAC heterozygote codes contribute split allele counts. For the SNP backend, pi is not currently reported.

Missing data can affect pi by changing which sites remain analyzable and by reducing the number of called chromosomes at retained sites. In practice, stronger filtering is usually preferable to imputation for pi, because imputation can flatten real allele-frequency variation.

dxy

dxy is the mean sequence divergence between two populations.

ipyrad2 calculates sitewise dxy as 1 - sum(p_i q_i), where p_i and q_i are allele frequencies in the two populations, and then averages across retained sites shared by both populations.

Missing data can matter a lot for dxy if one population loses more sites than the other, because the effective comparison set changes. Users should generally filter more strictly rather than impute when using dxy.

fst

fst is a pairwise measure of population differentiation. In this implementation it is Hudson-style FST, computed by summing the sitewise numerator and denominator and then taking the ratio of sums.

ipyrad2 uses the sitewise components:

  • numerator: dxy - (pi1 + pi2) / 2
  • denominator: dxy

and reports FST = sum(numerator) / sum(denominator) across retained sites.

Reference: Hudson, Slatkin, and Maddison 1992.

Missing data can strongly affect FST, especially when coverage differs across populations, because the retained site set may shift in ways that look like structure. Strong missing-data filtering is usually safer than imputation here.

theta_w

theta_w is Watterson's theta, a diversity estimator based on the number of segregating sites.

ipyrad2 calculates per-site Watterson's theta from the number of segregating sites divided by the harmonic-number constant a1, then normalizes by the number of sites used. In the current sequence backend, this estimator is computed from fully called sites within each population.

Reference: Watterson 1975.

Missing data strongly affects theta_w because segregating-site counts are very sensitive to incomplete site retention. Users should generally filter more strictly and avoid imputation for this statistic.

tajima_d

Tajima's D compares two diversity summaries: diversity from pairwise differences and diversity from the number of segregating sites.

ipyrad2 calculates Tajima's D from total pairwise diversity, the number of segregating sites, and sample size using the standard Tajima formula. As with theta_w, the current implementation uses fully called sites within each population for this estimator.

Reference: Tajima 1989.

Missing data strongly affects Tajima's D because both the segregating-site count and the usable-site set change. Strong filtering is usually preferable to imputation.

heterozygosity

heterozygosity reports two related summaries:

  • observed heterozygosity (Ho)
  • expected heterozygosity (He)

Observed heterozygosity is the fraction of called genotypes that are heterozygous. Expected heterozygosity is calculated from allele counts as unbiased gene diversity.

This statistic is available on both sequence-backed and SNP-backed data. On sequence-backed data, heterozygous IUPAC ambiguity codes are treated as heterozygous calls.

Missing data has a moderate effect because both Ho and He depend on the called genotype set. In most cases, filtering is preferred to imputation because imputation can inflate or suppress heterozygote counts.

fis

fis is the within-population inbreeding coefficient.

ipyrad2 calculates it as:

Fis = 1 - Ho / He

where Ho is observed heterozygosity and He is expected heterozygosity. This same formula is also written to the manifest when fis is requested.

Because fis is a ratio of heterozygosity summaries, it can be sensitive to missing data and especially unstable when expected heterozygosity is very low. Strong filtering is generally better than imputation.

sfs

sfs is a folded, genome-wide site-frequency spectrum. In the current implementation it is reported as counts of biallelic sites by minor-allele-count bin within each population.

This means the output is not an unfolded ancestral-state spectrum. It is a folded spectrum based on minor allele count, and only genome-wide SFS is currently written.

Missing data matters a great deal for the SFS, especially in the rare-allele bins, because missing calls change which sites remain biallelic and how minor-allele counts are tallied. Users should usually apply fairly strong missing-data filtering and avoid imputation for SFS calculations.

References

  • Watterson, G. A. 1975. On the number of segregating sites in genetical models without recombination.
  • Tajima, F. 1989. Statistical method for testing the neutral mutation hypothesis by DNA polymorphism.
  • Hudson, R. R., Slatkin, M., and Maddison, W. P. 1992. Estimation of levels of gene flow from DNA sequence data.

Example Outputs

Example manifest

# paste real example manifest text here

Example sample_stats.tsv

# paste real sample_stats.tsv text here

Example population_stats.tsv

# paste real population_stats.tsv text here

Example pairwise_stats.tsv

# paste real pairwise_stats.tsv text here

Example sfs.tsv

# paste real sfs.tsv text here

Example window_population_stats.tsv

# paste real window_population_stats.tsv text here

Example window_pairwise_stats.tsv

# paste real window_pairwise_stats.tsv text here

Native genotype-likelihood mode (HDF5 v3/v4)

Use --genotype-mode likelihoods to summarize native SNP likelihoods from an assembly made with --evidence snps or --evidence loci. The default lean assembly (--evidence none) has no likelihood arrays; likelihood mode reports an error with the required assembly options. Standard popgen behavior remains calls and works with all three evidence settings.

ipyrad2 popgen -d assembly.hdf5 -o POPGEN_EVIDENCE \
  --genotype-mode likelihoods --stats heterozygosity \
  --evidence-prior population --imap populations.tsv

The default likelihood scope, --evidence-scope snps, supports biallelic SNP-catalogue heterozygosity and gene diversity. --stats all selects that supported subset. SNP-scope summaries are conditional on the retained SNP catalogue. For per-callable-base heterozygosity and diversity, select --evidence-scope loci --stats pi,heterozygosity as described below. Neither likelihood scope currently supports FST, inbreeding statistics, windows, or MAF filtering. Fitted SFS weights are diagnostic outputs of the SFS prior, separate from the hard-call --stats sfs statistic.

Three priors are available:

  • uniform (default): equal prior probability for the three genotypes of each individual, independently. No population information changes the posterior.
  • population: Hardy–Weinberg genotype probabilities conditional on an unknown allele frequency, integrated under a Beta(1,1) prior using all usable individual likelihoods in the specified group. This requires an explicit --imap. Group membership is a biological assumption; species labels alone do not establish an appropriate randomly mating population. No dropout correction is applied.
  • sfs: a folded finite-sample allele-count prior fitted across loci within each explicit --imap group, using whole-locus cross-fitting. See the SFS fitting details below.

Each row must represent a distinct individual. Supply --individual-map with sample<TAB>individual entries to check known duplicates. Replicate assays of one individual must be combined before analysis; this mode rejects duplicate individuals instead of counting them twice. Without this file, sample rows are assumed to represent distinct individuals.

Zero-read, hard-masked, unmatched, and incomplete-likelihood cells remain missing. Valid likelihoods can contribute even when a discrete genotype is missing. Coverage, depth, population minimum coverage, and sample missingness filters use usable likelihoods, rather than hard calls. --subsample-unlinked selects one retained SNP per locus. The synthetic reference cannot participate. No database, genotype, or alignment is modified. Posterior probabilities are calculated internally for these summaries; this mode does not export a per-sample, per-site GP matrix or posterior genotype calls. Use snpex -O bcf to export the underlying native PL likelihoods.

The sample table reports summed posterior heterozygote probabilities, their mean over usable SNP cells, mean expected alternative-allele dosage, and the numbers of canonical calls and heterozygotes on those same cells. The population table reports per-site mean heterozygosity, mean alternative-allele frequency, its model-based variance, and sampled-chromosome SNP gene diversity:

E[2 K (M-K) / (M (M-1)) | reads], where M = 2 × usable individuals.

This integrates the joint allele-count moments, including the dependence induced by a shared population frequency. It is not calculated by treating expected dosages as observed allele counts. The reported frequency variance is model uncertainty at a site, not a confidence interval across loci. The manifest records priors, filters, missingness rules and the SNP-catalogue scope. A higher posterior heterozygosity estimate does not by itself demonstrate improved accuracy; comparisons require known truth or clearly identified observational comparators and matched retention.

Likelihood diversity per callable locus base

Use all-locus evidence explicitly; the default likelihood scope remains the retained SNP catalogue:

ipyrad2 popgen -d assembly.hdf5 -n loci -o output-loci \
  --genotype-mode likelihoods --evidence-scope loci \
  --stats pi,heterozygosity --evidence-prior population -i populations.tsv \
  --min-genotype-depth 1

This requires assemble --evidence loci (format 4.0). It reads rad_evidence, including invariant positions; it does not use SNP ascertainment or hard calls to choose bases. posterior_pi is the mean posterior probability of a nucleotide difference between two distinct sampled chromosomes, per callable retained locus base. At each base it integrates 2 K (M-K) / [M(M-1)], where M=2n chromosomes come from the usable individuals at that base. Population-prior covariance is included. With only one usable diploid, this equals that individual's posterior heterozygosity. This is a posterior mean under the model, not a claim of an unbiased population estimator or whole-genome diversity.

The initial all-locus implementation uses a biallelic model. At native reference/<*> pileup records, the alternative is one latent unseen allele; its nucleotide identity is not fabricated. At records containing two observed ACGT nucleotides, the model conditions on that pair and uses its three native PL entries, excluding any third-allele symbolic states from the model. It does not recover a full four-nucleotide likelihood vector from a symbolic allele. Bases with more than two observed nucleotides, indels/unsupported tokens, multiple native records, non-ACGT reference, or no alternative likelihood are excluded and counted in the manifest. Native values remain unchanged.

A callable sample-base cell requires positive native DP (and any requested minimum depth), complete native PL, PASS status and no original hard mask. No record, zero reads, missing likelihoods or masked cells never become certain homozygous reference calls. Excluded bases contribute neither a numerator nor a denominator. Global -m and any explicit -g population minima apply before aggregation; each population then requires at least one usable individual. The population TSV exposes callable_bases, callable_sample_cells, counts of reference/unseen and observed-pair bases, and the summed pairwise-difference numerator. Sample tables report posterior heterozygosity over each individual's usable bases. Different groups can have different callable domains; comparisons need matched domains or explicit acknowledgment of that difference.

All three priors are available: independent uniform genotype probabilities, HWE conditional on a shared frequency integrated against Beta(1,1), or the cross-fitted finite-sample SFS prior within explicit populations. These priors can produce substantially different results at low depth; all-sites storage does not itself calibrate a prior or correct RAD allele dropout. No posterior is imputed for a missing individual. Repeated assays of the same individual must not be treated as separate individuals.

MAF filtering, variant QUAL filtering, one-SNP-per-locus subsampling and windows are unsupported for this mode. Sample missingness is measured against all retained ACGT bases before global/population coverage filtering. The final locus-selection and mapping/capture ascertainment remain; this is per callable base in the retained loci, not per base of the entire genome. snpex -O bcf continues to export SNP PL and does not export per-site GP.

Native symbolic-allele semantics follow the VCF specification. The bcftools pileup native allele/PL construction selects an unseen nucleotide as its symbolic alternative; this motivates the explicit conditional biallelic interpretation rather than assigning the symbol a known nucleotide or assuming reference certainty.

Opt-in fitted SFS prior

Documentation draft for review. See the mixed-depth paper example for commands, validated genotype-recovery results, and the distinction between the public SFS options and research observation calibration.

--evidence-prior sfs estimates a folded finite-sample site-frequency spectrum from native genotype likelihoods within each explicit --imap group. It changes only downstream posterior summaries; assembly calls, native PL, and input HDF5 files remain unchanged. No ancestral allele is required. This is an ANGSD-style sample allele-count likelihood model, not an ANGSD compatibility claim or a demographic inference tool.

ipyrad2 popgen -d oak.hdf5 -o output-sfs -n oak \
  --genotype-mode likelihoods --evidence-scope loci \
  --evidence-prior sfs --stats pi,heterozygosity -i populations.tsv \
  --min-genotype-depth 1 --sfs-fit-loci 1024 --sfs-folds 5 -c 4

For SNP scope, request --stats heterozygosity. Its fitted spectrum is conditional on the retained SNP catalogue and must not be interpreted as an all-base SFS. Locus scope includes eligible invariant bases, subject to the same conditional biallelic model and missingness/mask rules described above. This does not remove ascertainment or allele-model limitations.

For N diploid individuals the likelihood for count k is the coefficient of z^k in the product of (L0 + 2 L1 z + L2 z²), divided by choose(2N,k). The folded bins combine counts k and 2N−k with equal orientation weights; the middle bin is counted once. EM fits the N+1 folded weights with a symmetric Dirichlet prior of alpha=1.5 (0.5 pseudocount per bin). This weak regularization keeps unseen count categories from receiving exactly zero prior probability; it can matter in small or weakly informative panels.

By default, up to 1,024 whole fitting loci in total are selected evenly within five folds. Folds are sorted retained-locus rank modulo five. Every evaluation locus uses a spectrum fitted outside its entire fold. This guards against fitting and evaluating the same locus; it is not individual holdout. Group members' likelihoods enter a site's joint posterior once. Linked sites still contribute composite likelihood terms; no independence-based confidence interval is implied.

Missing individuals contribute a constant likelihood during fitting. During summarization, the count prior is projected hypergeometrically onto the usable individuals at that site. Missing cells receive no posterior and are never zero-filled. Joint chromosome-count variance is retained in diversity estimates.

The additional *.sfs.tsv table records every group/fold/bin weight, fitting-site counts, convergence status and iterations. The manifest records fitting loci, fold rules and assumptions. Flat likelihood rows supply no SFS information and are omitted from fitting. An entirely uninformative training fold or failure to converge raises an error; there is no silent replacement with a generic prior. --sfs-max-iter controls the iteration ceiling (default 10,000); convergence requires maximum absolute weight change <=1e-7. The current implementation supports up to 128 distinct individuals per group and limits stored fitting kernels to 256 MiB; reduce --sfs-fit-loci if necessary. Up to four group/fold fits run concurrently, bounded by -c, with one BLAS thread each.

Two or three diploid samples can provide useful information across many loci (three or four folded count bins, respectively). Their spectra have coarse resolution and can be weakly identified at very low depth. More loci cannot replace missing read information, and more samples do not fix inappropriate population grouping. Compare fold stability, fitting-panel sensitivity, generic priors, and held-out/downsampled high-depth controls before interpreting improved accuracy. Per-site posterior variance does not include uncertainty in the fitted spectrum. Taxon labels alone do not establish a panmictic population.

popgen fits its prior from the retained evidence and requested analysis filters; it does not reuse the weights in NAME.sfs.json from assembly. The assembly caller selects up to --sfs-fit-loci training loci separately for each group and held-out fold, while popgen uses the total fitting-locus budget described above. Matching the numerical option values therefore does not guarantee identical fitting panels or posterior weights between commands.

For diversity estimation, thresholded SFS calls still discard uncertain cells. Use --genotype-mode likelihoods --evidence-scope loci to integrate posterior uncertainty across callable locus bases, and inspect each reported denominator. Compare hard calls, uniform likelihoods, and SFS on matched domains when making method comparisons; their default usable-cell sets can differ. Neither SFS option fits the paper's separate library-specific observation correction.

Five all-site likelihood statistics

With --genotype-mode likelihoods --evidence-scope loci, --stats all computes heterozygosity,pi,theta_w,sfs,fis using the selected uniform, population, or SFS prior. Existing hard-call defaults and SNP-likelihood scope are unchanged. Explicit requests containing tajima_d, dxy, fst, or fit fail before fitting or publishing results. all reports these omissions in both the log and statistic_capabilities manifest entry; it never switches to hard calls. Tajima's D needs a separately validated posterior variance/sample-size policy; between-population statistics need resolved allele identities, which symbolic unseen alternatives do not provide. These are implementation/model limitations, not a general prohibition on likelihood estimators.

ipyrad2 popgen -d assembly.hdf5 -n diversity -o output-diversity \
  --genotype-mode likelihoods --evidence-scope loci --evidence-prior sfs \
  --imap populations.tsv --min-genotype-depth 1 --stats all

The existing H and pi calculations are unchanged. Additional output includes:

  • posterior_theta_w: mean of P(0<K<M | reads) / a_(M-1) across eligible physical bases, where M is twice the number of observed individuals and a_(M-1) = sum(1/i, i=1..M-1). This is a sitewise variable-sample-size estimator, not a fixed-size projected spectrum. Callable invariant bases contribute zero; sites without evidence do not contribute. Its value is conditional on the observed sample set and retained locus domain.
  • chromosome_counts.tsv: callable-base counts, expected segregating-site totals, theta numerators and estimates for each observed chromosome count. Compare strata when missingness differs among methods or assays.
  • posterior_sfs.tsv: posterior expected folded site counts by population, observed chromosome count and minor-allele count. Bin zero includes both monomorphic states. Counts sum to eligible bases within each stratum; do not pool different chromosome counts into one spectrum without projection. This evaluation spectrum is distinct from sfs.tsv, which continues to contain fitted, cross-fitted prior weights when the SFS prior is used.
  • posterior_fis: 1 - mean(Ho)/mean(He) on identical bases with at least two observed individuals. Ho is the mean individual heterozygote probability; He follows the existing finite-sample-corrected gene-diversity convention. Components and the denominator are reported. Negative values are retained; zero He or no eligible bases produces NA. This is a ratio of posterior summaries, not a posterior expectation of the ratio or an inbreeding model fitted to the reads.

All population quantities integrate the joint allele-count posterior. Under shared priors, multiplying marginal GP values would lose covariance and can misestimate segregation and diversity. Missing individuals remain missing. The fitted prior is not itself the evaluated SFS, and prior-fit uncertainty is not included in these point estimates. No external GP format, imputation, windowed likelihood analysis, or allele-dropout correction is introduced.