SNP Data¶
Objects, readers, writers, and convenience functions for genotype data.
Genotype QC and Preprocessing¶
SNPObject includes genotype QC helpers used before association testing, admixture
mapping, PCA and ancestry analysis, relatedness estimation, population-genetic
summaries, and other workflows that depend on clean sample and variant alignment.
Methods that compute metrics return NumPy arrays by default and usually accept
as_dataframe=True for labeled reports. Filter methods return a filtered copy
unless inplace=True.
Variant and Sample Missingness¶
Call-rate filters are useful in most genotype-based workflows. Differential missingness is useful when missing calls differ by phenotype, cohort, array, sequencing center, ancestry group, or other user-defined groups.
variant_qc = snpobj.variant_call_rate(as_dataframe=True)
sample_qc = snpobj.sample_call_rate(as_dataframe=True)
snpobj = snpobj.filter_variants_by_call_rate(min_call_rate=0.98)
snpobj = snpobj.filter_samples_by_call_rate(min_call_rate=0.98)
# Group-specific missingness. `groups` can be labels aligned to samples, a
# mapping keyed by sample ID, a pandas Series/DataFrame, or a snputils
# phenotype/covariate object.
missingness = snpobj.differential_missingness(groups, as_dataframe=True)
snpobj = snpobj.filter_differential_missingness(groups, min_p=1e-5)
Allele Frequency and Hardy-Weinberg Filters¶
MAF and MAC filters are common before single-variant association testing and can also stabilize sample-level summaries such as PCA, admixture analysis or relatedness. HWE filters are most often used as variant QC in diploid biallelic data; for case-control studies, controls are usually preferred.
maf = snpobj.maf(as_dataframe=True)
mac = snpobj.mac(as_dataframe=True)
snpobj = snpobj.filter_maf(maf=0.01)
snpobj = snpobj.filter_mac(mac=20)
# In case-control association studies, HWE QC is usually run in controls.
hwe = snpobj.hwe_pvalue(samples=controls, as_dataframe=True)
snpobj = snpobj.filter_hwe(min_p=1e-6, samples=controls)
Duplicate Sample and Variant Identifiers¶
Duplicate sample IDs can break phenotype, covariate, ancestry, and IBD alignment. Duplicate variant IDs or coordinates can make variant-level results ambiguous across association tests, population-genetic summaries, and file conversion.
duplicate_samples = snpobj.duplicate_sample_ids(as_dataframe=True)
duplicate_ids = snpobj.duplicate_variant_ids(as_dataframe=True)
duplicate_coords = snpobj.duplicate_variant_coordinates(as_dataframe=True)
snpobj = snpobj.filter_duplicate_samples(keep="first")
snpobj = snpobj.filter_duplicate_variants(by="id", keep="first")
snpobj = snpobj.filter_duplicate_variants(
by="coordinates",
fields=("chrom", "pos", "ref", "alt"),
)
Genetic Sex Checking¶
- snputils.sex_check(snpobj, reported_sex=None, *, x_chromosomes=('X', 'chrX', '23'), assume_x=False, low_information_threshold=500)[source]¶
Infer genetic sex from chromosome-X zygosity distributions using Zigo.
The function consumes hard-call genotypes already represented by a
SNPObject; file parsing remains the responsibility of snputils readers. Chromosome-X variants are selected automatically fromvariants_chrom. The three model features are the normalized frequencies of genotype classes 0, 1, and 2 after Zigo’s allele-orientation normalization.- Parameters:
snpobj – SNP data with 2D dosage calls
(variants, samples)or 3D biallelic allele calls(variants, samples, 2).reported_sex – Optional sample-aligned sex values or mapping from sample ID to sex. Values
1/M/maleand2/F/femaleare recognized. If omitted,snpobj.sample_sexis used when available.x_chromosomes – Chromosome labels treated as X. Defaults to
X,chrX, and the PLINK numeric label23.assume_x – Treat every variant as chromosome X. Use only when chromosome metadata is unavailable and the object is known to contain X variants exclusively.
low_information_threshold – Callable genotype count below which a non-empty sample is marked
low_information. The prediction is retained. Set to 0 to disable this flag.
- Returns:
A sample-level DataFrame containing reported and inferred sex, comparison status, male/female probabilities, callable counts, normalized Zigo features, and a QC status.
- Raises:
TypeError – If
snpobjis not an SNPObject.ValueError – If hard calls or chromosome-X variants are unavailable.
Notes
This integrates the distilled model from Sex checking by zygosity distributions (Molina-Sedano et al., 2026), https://doi.org/10.64898/2026.03.15.711924. The model was not designed to diagnose sex-chromosome aneuploidies.
The function uses the internally bundled Zigo distilled polynomial model. See Analysis for output interpretation, limitations, and the Zigo paper citation.
Objects¶
- class snputils.SNPObject(genotypes=None, samples=None, variants_ref=None, variants_alt=None, variants_chrom=None, variants_cm=None, variants_filter_pass=None, variants_id=None, variants_pos=None, variants_qual=None, variants_info=None, calldata_lai=None, calldata_gp=None, ancestry_map=None, sample_fid=None, sample_sex=None, calldata_gt=None)[source]¶
Bases:
objectA class for Single Nucleotide Polymorphism (SNP) data, with optional support for SNP-level Local Ancestry Information (LAI).
- Parameters:
genotypes (array, optional) – An array containing genotype data for each sample. This array can be either 2D with shape (n_snps, n_samples) for per-sample dosages, or 3D with shape (n_snps, n_samples, 2) for phased diploid allele calls.
samples (array of shape (n_samples,), optional) – An array containing unique sample identifiers.
sample_fid (array of shape (n_samples,), optional) – PLINK-style family ID per sample (same order as
samples), for example population labels in column 1 of a.famfile. When present and not identical tosamples, f-statistics use these values as default group labels ifsample_labelsis omitted.sample_sex (array of shape (n_samples,), optional) – PLINK-style sex code per sample, aligned with
samples.variants_ref (array of shape (n_snps,), optional) – An array containing the reference allele for each SNP.
variants_alt (array of shape (n_snps,), optional) – An array containing the alternate allele for each SNP.
variants_chrom (array of shape (n_snps,), optional) – An array containing the chromosome for each SNP.
variants_cm (array of shape (n_snps,), optional) – An array containing the genetic-map position in centimorgans for each SNP.
variants_filter_pass (array of shape (n_snps,), optional) – An array indicating whether each SNP passed control checks.
variants_id (array of shape (n_snps,), optional) – An array containing unique identifiers (IDs) for each SNP.
variants_pos (array of shape (n_snps,), optional) – An array containing the chromosomal positions for each SNP.
variants_qual (array of shape (n_snps,), optional) – An array containing the Phred-scaled quality score for each SNP.
variants_info (array of shape (n_snps,), optional) – An array containing VCF/PVAR INFO column values for each SNP.
calldata_lai (array, optional) – An array containing the ancestry for each SNP. This array can be either 2D with shape (n_snps, n_samples*2), or 3D with shape (n_snps, n_samples, 2).
calldata_gp (array, optional) – Genotype probabilities for each SNP and sample, with shape (n_snps, n_samples, n_probabilities). For diploid biallelic BGEN data, unphased probabilities typically have three columns and phased probabilities typically have four columns. Mixed-width BGEN reads are padded with NaN columns to keep this as a single array.
ancestry_map (dict of str to str, optional) – A dictionary mapping ancestry codes to region names.
calldata_gt (array, optional) – Backward-compatible alias for genotypes.
- property genotypes¶
Retrieve genotypes.
- Returns:
array – An array containing genotype data for each sample. This array can be either 2D with shape
(n_snps, n_samples)for per-sample dosages, or 3D with shape(n_snps, n_samples, 2)for phased diploid allele calls.
- property calldata_gt¶
Retrieve genotypes via legacy alias.
- property samples¶
Retrieve samples.
- Returns:
array of shape (n_samples,) – An array containing unique sample identifiers.
- property sample_fid¶
PLINK Family ID (FID) per sample, aligned with
samples.
- property sample_sex¶
PLINK sex code per sample, aligned with
samples.
- property variants_ref¶
Retrieve variants_ref.
- Returns:
array of shape (n_snps,) – An array containing the reference allele for each SNP.
- property variants_alt¶
Retrieve variants_alt.
- Returns:
array of shape (n_snps,) – An array containing the alternate allele for each SNP.
- property variants_chrom¶
Retrieve variants_chrom.
- Returns:
array of shape (n_snps,) – An array containing the chromosome for each SNP.
- property variants_cm¶
Retrieve variants_cm.
- Returns:
array of shape (n_snps,) – An array containing the genetic-map position in centimorgans for each SNP.
- property variants_filter_pass¶
Retrieve variants_filter_pass.
- Returns:
array of shape (n_snps,) – An array indicating whether each SNP passed control checks.
- property variants_id¶
Retrieve variants_id.
- Returns:
array of shape (n_snps,) – An array containing unique identifiers (IDs) for each SNP.
- property variants_pos¶
Retrieve variants_pos.
- Returns:
array of shape (n_snps,) – An array containing the chromosomal positions for each SNP.
- property variants_qual¶
Retrieve variants_qual.
- Returns:
array of shape (n_snps,) – An array containing the Phred-scaled quality score for each SNP.
- property variants_info¶
Retrieve variants_info.
- Returns:
array of shape (n_snps,) – An array containing VCF/PVAR INFO column values for each SNP.
- property calldata_lai¶
Retrieve calldata_lai.
- Returns:
array – An array containing the ancestry for each SNP. This array can be either 2D with shape (n_snps, n_samples*2), or 3D with shape (n_snps, n_samples, 2).
- property calldata_gp¶
Retrieve calldata_gp.
- Returns:
array – Genotype probabilities with shape (n_snps, n_samples, n_probabilities).
- property ancestry_map¶
Retrieve ancestry_map.
- Returns:
dict of str to str – A dictionary mapping ancestry codes to region names.
- property n_samples¶
Retrieve n_samples.
- Returns:
int – The total number of samples.
- property n_snps¶
Retrieve n_snps.
- Returns:
int – The total number of SNPs.
- property n_chrom¶
Retrieve n_chrom.
- Returns:
int – The total number of unique chromosomes in variants_chrom.
- property n_ancestries¶
Retrieve n_ancestries.
- Returns:
int – The total number of unique ancestries.
- property shape¶
Retrieve the primary data shape.
- Returns:
tuple – The shape of genotypes when present, otherwise the shape of calldata_gp or calldata_lai. If only metadata is available, returns (n_snps, n_samples) with unknown dimensions represented as None.
- property unique_chrom¶
Retrieve unique_chrom.
- Returns:
array – The unique chromosome names in variants_chrom, preserving their order of appearance.
- property is_dosage¶
Report whether
genotypesstores per-sample dosages.- Returns:
bool – True when
genotypeshas shape(n_snps, n_samples)and False when it contains phased calls with shape(n_snps, n_samples, 2). None when genotypes are unavailable.
- copy()[source]¶
Create and return a copy of self.
- Returns:
SNPObject – A new instance of the current object.
- keys()[source]¶
Retrieve a list of public attribute names for self.
- Returns:
list of str – A list of attribute names, with internal name-mangling removed, for easier reference to public attributes in the instance.
- dosage(allele='ALT')[source]¶
Return expected allele dosages as a 2D
(n_snps, n_samples)array.If
calldata_gpis present, this converts BGEN-style genotype probabilities to expected alternate-allele dosage. For now this supports biallelic variants, which are the common GWAS case. If genotype calls are present instead, 3D biallelic calls are summed across the allele axis and 2D calls are returned as floating-point dosages. Multiallelic hard calls are rejected because a single dosage value cannot identify the counted ALT allele.- Parameters:
allele – Allele to dosage. Currently only
"ALT"or1is supported for BGEN probability data.- Returns:
A float32 dosage matrix.
- to_dosage(inplace=False)[source]¶
Store expected dosages in
genotypes.This is useful for dosage-based analyses, such as GWAS, after reading a BGEN file where probabilities are stored in
calldata_gp. The original probability array is preserved.- Parameters:
inplace – If True, modifies
selfand returns None. If False, returns a copy withgenotypesset to dosages.
- allele_freq(sample_labels=None, ancestry=None, laiobj=None, pseudohaploid=False, return_counts=False, as_dataframe=False)[source]¶
Compute per-SNP alternate allele frequencies from genotypes.
- Parameters:
sample_labels (sequence, optional) – Population label per sample. If None, computes cohort-level frequencies.
ancestry (str or int, optional) – If provided, compute ancestry-masked frequencies using SNP-level LAI.
laiobj (LocalAncestryObject, optional) – Optional LAI object used when self.calldata_lai is not set.
pseudohaploid (bool or int, default=False) – If True, detects pseudo-haploid samples (samples with no heterozygotes in the first 1000 SNPs) and treats them as haploid. If an integer n is provided, checks the first n SNPs. If False, treats all samples as diploid.
return_counts (bool, default=False) – If True, also return called-allele counts with the same shape as frequencies.
as_dataframe (bool, default=False) – If True, return pandas DataFrame output.
- Returns:
Frequencies as a NumPy array (or DataFrame if as_dataframe=True). If return_counts=True, returns (freq, counts).
- allele_counts(sample_labels=None, ancestry=None, laiobj=None, pseudohaploid=False, return_called=False, as_dataframe=False)[source]¶
Compute per-SNP alternate allele counts from observed calls.
This uses the same missing-data handling as
allele_freq(): missing calls do not contribute to either the alternate allele count or the called-allele denominator. For 2D dosage arrays, alternate allele counts may be fractional when dosages are fractional.- Parameters:
sample_labels (sequence, optional) – Population label per sample. If None, computes cohort-level counts.
ancestry (str or int, optional) – If provided, compute ancestry-masked counts using SNP-level LAI.
laiobj (LocalAncestryObject, optional) – Optional LAI object used when self.calldata_lai is not set.
pseudohaploid (bool or int, default=False) – If True, detects pseudo-haploid samples using the same rule as
allele_freq(). If an integer n is provided, checks the first n SNPs.return_called (bool, default=False) – If True, also return called-allele counts with the same shape as the alternate allele counts.
as_dataframe (bool, default=False) – If True, return pandas DataFrame output.
- Returns:
Alternate allele counts as a NumPy array (or DataFrame if
as_dataframe=True). Ifreturn_called=True, returns(alt_counts, called_alleles).
- maf(sample_labels=None, ancestry=None, laiobj=None, pseudohaploid=False, as_dataframe=False)[source]¶
Compute per-SNP minor allele frequency from observed calls.
Missing calls are excluded from the denominator. Variants with no called alleles return
NaN.
- mac(sample_labels=None, ancestry=None, laiobj=None, pseudohaploid=False, as_dataframe=False)[source]¶
Compute per-SNP minor allele count from observed calls.
Missing calls are excluded from the denominator. Variants with no called alleles return
NaN.
- variant_call_rate(as_dataframe=False)[source]¶
Compute the fraction of samples with non-missing genotype calls per variant.
Missing calls are represented as negative values or NaN. For 3D genotype arrays, a sample is counted as called only when all allele entries are non-missing.
- sample_call_rate(as_dataframe=False)[source]¶
Compute the fraction of variants with non-missing genotype calls per sample.
Missing calls are represented as negative values or NaN. For 3D genotype arrays, a genotype is counted as called only when all allele entries are non-missing.
- duplicate_sample_ids(keep='first', ignore_missing=True, as_dataframe=False)[source]¶
Identify duplicate sample IDs.
- Parameters:
keep ({"first", "last", False}, default="first") – Which duplicate entry to keep unmarked.
"first"marks all but the first entry in each duplicate group,"last"marks all but the last, and False marks all members of duplicate groups.ignore_missing (bool, default=True) – If True, empty strings and
"."are not considered duplicate IDs.as_dataframe (bool, default=False) – If True, return a report with sample indexes, IDs, duplicate flags, and duplicate group IDs.
- Returns:
Boolean duplicate mask over samples, or a pandas DataFrame if
as_dataframe=True.
- duplicate_variant_ids(keep='first', ignore_missing=True, as_dataframe=False)[source]¶
Identify duplicate variant IDs.
- Parameters:
keep ({"first", "last", False}, default="first") – Which duplicate entry to keep unmarked.
"first"marks all but the first entry in each duplicate group,"last"marks all but the last, and False marks all members of duplicate groups.ignore_missing (bool, default=True) – If True, empty strings and
"."are not considered duplicate IDs.as_dataframe (bool, default=False) – If True, return a report with variant indexes, IDs, duplicate flags, and duplicate group IDs.
- Returns:
Boolean duplicate mask over variants, or a pandas DataFrame if
as_dataframe=True.
- duplicate_variant_coordinates(fields=('chrom', 'pos', 'ref', 'alt'), keep='first', ignore_missing=True, as_dataframe=False)[source]¶
Identify duplicate variants by metadata coordinates.
By default, variants are compared by chromosome, position, reference allele, and alternate allele. Pass a narrower
fieldsvalue such as("chrom", "pos")to flag variants sharing only a genomic position.- Parameters:
fields (str or sequence of str, default=("chrom", "pos", "ref", "alt")) – Variant metadata fields used as the duplicate key. Supported values are
"chrom","pos","ref","alt", and"id".keep ({"first", "last", False}, default="first") – Which duplicate entry to keep unmarked.
"first"marks all but the first entry in each duplicate group,"last"marks all but the last, and False marks all members of duplicate groups.ignore_missing (bool, default=True) – If True, rows with missing key fields are not considered duplicates.
as_dataframe (bool, default=False) – If True, return a report with variant indexes, key fields, duplicate flags, and duplicate group IDs.
- Returns:
Boolean duplicate mask over variants, or a pandas DataFrame if
as_dataframe=True.
- differential_missingness(groups, samples=None, test='auto', min_expected=5.0, group_column=None, as_dataframe=False)[source]¶
Test whether genotype missingness differs across sample groups per variant.
Missingness is computed from genotype calls or BGEN genotype probabilities. For 3D genotype arrays, a sample is counted as called only when all allele entries are non-missing.
groupsmay be a sequence aligned to samples, a mapping keyed by sample ID, a pandas Series/DataFrame, or a snputils phenotype/covariate-style object withsamplesandvaluesattributes.- Parameters:
groups – Group labels, such as case/control status or genotyping batch.
samples (str or array_like, optional) – Optional sample IDs, sample indexes, or boolean mask selecting samples used for the test.
test (str, default="auto") – Statistical test.
"chi2"uses the chi-square test of independence for 2xK tables."fisher"uses Fisher’s exact test and requires exactly two groups."auto"uses chi-square except for two-group variants with any expected cell belowmin_expected, where it uses Fisher’s exact test.min_expected (float, default=5.0) – Expected cell-count cutoff used by
test="auto".group_column (str, optional) – Column name to use when
groupscontains multiple columns.as_dataframe (bool, default=False) – If True, return p-values, test names, statistics, and per-group missing/called counts as a pandas DataFrame.
- Returns:
NumPy array of p-values, or a DataFrame if
as_dataframe=True.
Compute sample relatedness.
method="grm"computes genotype-derived relatedness from diploid biallelic dosages. Genotypes are standardized per variant as(g - 2p) / sqrt(2p(1-p))and pairwise products are averaged over variants where both samples are called.method="ibd"summarizes already-called IBD segments from anIBDObjectas(IBD1 cM + 2 * IBD2 cM) / (2 * genome_length_cm).- Parameters:
method (str, default="grm") – Relatedness estimator. Supported values are
"grm"and"ibd".samples (str or array_like, optional) – Sample IDs, sample indexes, or boolean mask selecting samples. If None, all samples are used.
scale (str, default="relationship") –
"relationship"returns the relationship coefficient."kinship"returns half the relationship coefficient.min_variants (int, default=1) – Minimum number of pairwise non-missing informative variants required to report a finite GRM value.
block_size (int, default=10000) – Number of variants per block used while accumulating the GRM.
ibdobj (IBDObject, optional) – IBD segments used when
method="ibd".genome_length_cm (float, default=3400.0) – Diploid genome length denominator for IBD normalization.
min_segment_cm (float, optional) – Minimum IBD segment length to include.
segment_types (sequence of str, optional) – IBD segment types to include, such as
["IBD1", "IBD2"].as_dataframe (bool, default=False) – If True, return a pandas DataFrame with sample labels.
- Returns:
Square NumPy array of relatedness values, or a DataFrame if
as_dataframe=True.
Return sample pairs with estimated kinship at or above
threshold.The default threshold, 0.0884, is a commonly used second-degree kinship cutoff. For
method="grm", input variants should already be appropriate for relatedness QC (autosomal, reasonably common, and preferably LD-pruned). Formethod="ibd", pass anIBDObjectviaibdobj.
Greedily remove samples until no selected pair exceeds a kinship threshold.
At each step, the removed sample is chosen by: more flagged relationships, then lower sample call rate, then later sample index. Samples outside the optional
samplessubset are kept.
- imputation_r2(source='auto', info_keys=None, as_dataframe=False)[source]¶
Compute per-variant imputation quality R2/INFO values.
source="info"extracts scalar quality values fromvariants_infousing common keys such asINFO,R2,DR2, andIMP.source="gp"estimates an INFO-like value from genotype probabilities as1 - mean(posterior variance) / expected genotype variance.source="dosage"computes empirical dosage R2 asVar(DS) / expected genotype variance.source="auto"uses INFO values when available and fills missing values from genotype probabilities, then dosages.- Parameters:
source (str, default="auto") – One of
"auto","info","gp", or"dosage". Aliases such as"bgen"and"ds"are accepted.info_keys (str or sequence of str, optional) – INFO field keys to search, in priority order. Defaults to common imputation quality keys.
as_dataframe (bool, default=False) – If True, return a pandas DataFrame.
- Returns:
NumPy array of imputation quality values, or a DataFrame if
as_dataframe=True. Values unavailable from the selected source are returned as NaN.
- sample_heterozygosity(samples=None, as_dataframe=False)[source]¶
Compute observed heterozygosity per sample.
The value is the fraction of called diploid biallelic genotypes that are heterozygous. Missing calls are ignored. This QC statistic is typically most useful after restricting to autosomal, reasonably common, LD-pruned variants.
- Parameters:
- Returns:
NumPy array of per-sample heterozygosity, or a DataFrame if
as_dataframe=True.
- sample_inbreeding_coefficient(samples=None, as_dataframe=False)[source]¶
Compute per-sample inbreeding coefficients from observed and expected heterozygosity.
The coefficient is
1 - observed_hets / expected_hets, where expected heterozygosity is summed from cohort allele frequencies estimated across the selected samples. Missing calls are ignored per sample. This statistic is typically most useful after restricting to autosomal, reasonably common, LD-pruned variants.- Parameters:
- Returns:
NumPy array of per-sample inbreeding coefficients, or a DataFrame if
as_dataframe=True.
- flag_heterozygosity_outliers(n_sd=3, samples=None)[source]¶
Build a per-sample heterozygosity outlier report.
Samples are flagged when their observed heterozygosity is more than
n_sdstandard deviations from the mean among finite selected samples. This is best run on autosomal, reasonably common, LD-pruned variants.- Parameters:
- Returns:
pandas.DataFrame – Sample-level QC report with heterozygosity, inbreeding coefficient, z-score, and outlier flag.
- hwe_pvalue(samples=None, as_dataframe=False)[source]¶
Compute exact Hardy-Weinberg equilibrium p-values per variant.
HWE is computed from hard-called diploid biallelic genotypes only. Missing calls are ignored. The optional
samplesargument can be used to restrict the calculation to a control-only subset, using sample IDs, sample indexes, or a boolean sample mask.- Parameters:
- Returns:
NumPy array of HWE p-values, or a DataFrame if
as_dataframe=True. Variants with no called genotypes in the selected samples return NaN.
- ld_prune_mask(window_size=50, step_size=5, r2_threshold=0.2, samples=None, min_samples=3)[source]¶
Build a greedy LD-pruning mask using sliding windows and pairwise r-squared.
Variants are processed in their current order. Within each window, the earlier variant is kept and later variants with pairwise r-squared greater than
r2_thresholdare removed. Windows advance bystep_sizeand previously removed variants stay removed.- Parameters:
window_size (int, default=50) – Number of variants per sliding window. Must be at least 2.
step_size (int, default=5) – Number of variants to advance the window each step. Must be at least 1.
r2_threshold (float, default=0.2) – Pairwise LD r-squared threshold. Must be between 0 and 1.
samples (str or array_like, optional) – Sample IDs, sample indexes, or boolean mask selecting samples used to estimate LD. If None, all samples are used.
min_samples (int, default=3) – Minimum number of pairwise non-missing samples needed to compute r-squared.
- Returns:
np.ndarray – Boolean mask aligned to variants, where True indicates retained variants.
- filter_variants(chrom=None, pos=None, indexes=None, mask=None, include=True, inplace=False)[source]¶
Filter variants based on chromosome names, variant positions, indexes, or a boolean mask.
This method updates the genotypes, variants_ref, variants_alt, variants_chrom, variants_filter_pass, variants_id, variants_pos, variants_qual, and lai attributes to include or exclude the specified variants. The filtering criteria can be based on chromosome names, variant positions, or indexes. If multiple criteria are provided, their union is used for filtering. The order of the variants is preserved.
Negative indexes are supported and follow [NumPy’s indexing conventions](https://numpy.org/doc/stable/user/basics.indexing.html).
- Parameters:
chrom (str or array_like of str, optional) – Chromosome(s) to filter variants by. Can be a single chromosome as a string or a sequence of chromosomes. If both chrom and pos are provided, they must either have matching lengths (pairing each chromosome with a position) or chrom should be a single value that applies to all positions in pos. Default is None.
pos (int or array_like of int, optional) – Position(s) to filter variants by. Can be a single position as an integer or a sequence of positions. If chrom is also provided, pos should either match chrom in length or chrom should be a single value. Default is None.
indexes (int or array_like of int, optional) – Index(es) of the variants to include or exclude. Can be a single index or a sequence of indexes. Negative indexes are supported. Default is None.
mask (array_like of bool, optional) – Boolean mask aligned to the SNP axis. If provided with other criteria, the union of all selected variants is used before applying
include.include (bool, default=True) – If True, includes only the specified variants. If False, excludes the specified variants. Default is True.
inplace (bool, default=False) – If True, modifies self in place. If False, returns a new SNPObject with the variants filtered. Default is False.
- Returns:
Optional[SNPObject] – A new SNPObject with the specified variants filtered if inplace=False. If inplace=True, modifies self in place and returns None.
- filter_biallelic_variants(snv_only=True, inplace=False)[source]¶
Keep variants with exactly one alternate allele.
- Parameters:
- Returns:
Optional[SNPObject] – A filtered SNPObject if
inplace=False; otherwise modifiesselfand returns None.
- filter_complete_genotypes(inplace=False)[source]¶
Keep variants with no missing genotype calls across all samples.
Missing calls are represented as negative values in
genotypes.
- filter_variable_genotypes(inplace=False)[source]¶
Keep variants with at least two observed genotype values among called samples.
This filters on genotype variability, not allele polymorphism. For example, a site where every called sample is heterozygous has one observed genotype value and is therefore removed. Phase order is ignored when comparing phased allele calls.
- filter_variants_by_call_rate(min_call_rate=0.98, include=True, inplace=False)[source]¶
Filter variants by genotype call rate.
- Parameters:
min_call_rate (float, default=0.98) – Minimum fraction of samples with non-missing genotype calls. Must be between 0 and 1.
include (bool, default=True) – If True, keeps variants with call rate greater than or equal to
min_call_rate. If False, excludes those variants.inplace (bool, default=False) – If True, modifies
selfin place. If False, returns a filtered copy.
- Returns:
Optional[SNPObject] – A filtered SNPObject if
inplace=False; otherwise modifiesselfand returns None.
- filter_samples_by_call_rate(min_call_rate=0.98, include=True, inplace=False)[source]¶
Filter samples by genotype call rate.
- Parameters:
min_call_rate (float, default=0.98) – Minimum fraction of variants with non-missing genotype calls. Must be between 0 and 1.
include (bool, default=True) – If True, keeps samples with call rate greater than or equal to
min_call_rate. If False, excludes those samples.inplace (bool, default=False) – If True, modifies
selfin place. If False, returns a filtered copy.
- Returns:
Optional[SNPObject] – A filtered SNPObject if
inplace=False; otherwise modifiesselfand returns None.
- filter_duplicate_samples(keep='first', ignore_missing=True, inplace=False)[source]¶
Remove duplicate sample IDs.
- Parameters:
keep ({"first", "last", False}, default="first") – Which sample in each duplicate ID group to keep. False removes every sample belonging to a duplicate group.
ignore_missing (bool, default=True) – If True, empty strings and
"."are not considered duplicate sample IDs.inplace (bool, default=False) – If True, modifies
selfin place. If False, returns a filtered copy.
- Returns:
Optional[SNPObject] – A filtered SNPObject if
inplace=False; otherwise modifiesselfand returns None.
- filter_duplicate_variants(by='id', fields=('chrom', 'pos', 'ref', 'alt'), keep='first', ignore_missing=True, inplace=False)[source]¶
Remove duplicate variants by ID or coordinate key.
- Parameters:
by (str, default="id") – Duplicate key to use:
"id"or"coordinates".fields (str or sequence of str, default=("chrom", "pos", "ref", "alt")) – Coordinate fields used when
by="coordinates".keep ({"first", "last", False}, default="first") – Which variant in each duplicate group to keep. False removes every variant belonging to a duplicate group.
ignore_missing (bool, default=True) – If True, rows with missing key fields are not considered duplicates.
inplace (bool, default=False) – If True, modifies
selfin place. If False, returns a filtered copy.
- Returns:
Optional[SNPObject] – A filtered SNPObject if
inplace=False; otherwise modifiesselfand returns None.
- filter_differential_missingness(groups, min_p=1e-05, samples=None, test='auto', min_expected=5.0, group_column=None, include=True, inplace=False)[source]¶
Filter variants by differential missingness p-value.
- Parameters:
groups – Group labels passed to
differential_missingness().min_p (float, default=1e-5) – Minimum differential missingness p-value. Must be between 0 and 1. Variants below this threshold show evidence that missingness differs by group.
samples (str or array_like, optional) – Optional sample IDs, sample indexes, or boolean mask selecting samples used for the test.
test (str, default="auto") – Statistical test passed to
differential_missingness().min_expected (float, default=5.0) – Expected cell-count cutoff used by
test="auto".group_column (str, optional) – Column name to use when
groupscontains multiple columns.include (bool, default=True) – If True, keeps variants with p-value greater than or equal to
min_p. If False, excludes those variants.inplace (bool, default=False) – If True, modifies
selfin place. If False, returns a filtered copy.
- Returns:
Optional[SNPObject] – A filtered SNPObject if
inplace=False; otherwise modifiesselfand returns None.
- filter_imputation_quality(min_r2=0.8, source='auto', info_keys=None, include=True, inplace=False)[source]¶
Filter variants by imputation quality R2/INFO.
- Parameters:
min_r2 (float, default=0.8) – Minimum imputation quality value. Must be between 0 and 1.
source (str, default="auto") – Source used by
imputation_r2():"auto","info","gp", or"dosage".info_keys (str or sequence of str, optional) – INFO field keys to search when extracting values from
variants_info.include (bool, default=True) – If True, keeps variants with imputation quality greater than or equal to
min_r2. If False, excludes those variants.inplace (bool, default=False) – If True, modifies
selfin place. If False, returns a filtered copy.
- Returns:
Optional[SNPObject] – A filtered SNPObject if
inplace=False; otherwise modifiesselfand returns None.
- filter_hwe(min_p=1e-06, samples=None, include=True, inplace=False)[source]¶
Filter variants by exact Hardy-Weinberg equilibrium p-value.
- Parameters:
min_p (float, default=1e-6) – Minimum HWE p-value. Must be between 0 and 1.
samples (str or array_like, optional) – Sample IDs, sample indexes, or boolean mask selecting the samples used for the HWE test. This is intended for control-only HWE QC in case-control GWAS.
include (bool, default=True) – If True, keeps variants with HWE p-value greater than or equal to
min_p. If False, excludes those variants.inplace (bool, default=False) – If True, modifies
selfin place. If False, returns a filtered copy.
- Returns:
Optional[SNPObject] – A filtered SNPObject if
inplace=False; otherwise modifiesselfand returns None.
- filter_ld_pruned(window_size=50, step_size=5, r2_threshold=0.2, samples=None, min_samples=3, include=True, inplace=False)[source]¶
Filter variants using greedy sliding-window LD pruning.
- Parameters:
window_size (int, default=50) – Number of variants per sliding window. Must be at least 2.
step_size (int, default=5) – Number of variants to advance the window each step. Must be at least 1.
r2_threshold (float, default=0.2) – Pairwise LD r-squared threshold. Must be between 0 and 1.
samples (str or array_like, optional) – Sample IDs, sample indexes, or boolean mask selecting samples used to estimate LD. If None, all samples are used.
min_samples (int, default=3) – Minimum number of pairwise non-missing samples needed to compute r-squared.
include (bool, default=True) – If True, keeps retained variants. If False, excludes retained variants.
inplace (bool, default=False) – If True, modifies
selfin place. If False, returns a filtered copy.
- Returns:
Optional[SNPObject] – A filtered SNPObject if
inplace=False; otherwise modifiesselfand returns None.
- ld_prune(window_size=50, step_size=5, r2_threshold=0.2, samples=None, min_samples=3, inplace=False)[source]¶
Alias for
filter_ld_pruned().
- filter_maf(maf=0.01, include=True, inplace=False)[source]¶
Filter variants by minor allele frequency.
The frequency is computed from observed allele calls only; missing calls do not contribute to the denominator.
- Parameters:
maf (float, default=0.01) – Minor allele frequency threshold. Must be between 0 and 0.5.
include (bool, default=True) – If True, keeps variants with minor allele frequency greater than or equal to
maf. If False, excludes those variants.inplace (bool, default=False) – If True, modifies
selfin place. If False, returns a filtered copy.
- Returns:
Optional[SNPObject] – A filtered SNPObject if
inplace=False; otherwise modifiesselfand returns None.
- filter_mac(mac=20, include=True, inplace=False)[source]¶
Filter variants by minor allele count.
The count is computed from observed allele calls only; missing calls do not contribute to the denominator.
- Parameters:
mac (int or float, default=20) – Minor allele count threshold. Must be non-negative.
include (bool, default=True) – If True, keeps variants with minor allele count greater than or equal to
mac. If False, excludes those variants.inplace (bool, default=False) – If True, modifies
selfin place. If False, returns a filtered copy.
- Returns:
Optional[SNPObject] – A filtered SNPObject if
inplace=False; otherwise modifiesselfand returns None.
- filter_samples(samples=None, indexes=None, include=True, reorder=False, inplace=False)[source]¶
Filter samples based on specified names or indexes.
This method updates the samples and genotypes attributes to include or exclude the specified samples. The order of the samples is preserved. Set reorder=True to match the ordering of the provided samples and/or indexes lists when including.
If both samples and indexes are provided, any sample matching either a name in samples or an index in indexes will be included or excluded.
This method allows inclusion or exclusion of specific samples by their names or indexes. When both sample names and indexes are provided, the union of the specified samples is used. Negative indexes are supported and follow [NumPy’s indexing conventions](https://numpy.org/doc/stable/user/basics.indexing.html).
- Parameters:
samples (str or array_like of str, optional) – Name(s) of the samples to include or exclude. Can be a single sample name or a sequence of sample names. Default is None.
indexes (int or array_like of int, optional) – Index(es) of the samples to include or exclude. Can be a single index or a sequence of indexes. Negative indexes are supported. Default is None.
include (bool, default=True) – If True, includes only the specified samples. If False, excludes the specified samples. Default is True.
inplace (bool, default=False) – If True, modifies self in place. If False, returns a new SNPObject with the samples filtered. Default is False.
- Returns:
Optional[SNPObject] – A new SNPObject with the specified samples filtered if inplace=False. If inplace=True, modifies self in place and returns None.
- detect_chromosome_format()[source]¶
Detect the chromosome naming convention in variants_chrom based on the prefix of the first chromosome identifier in unique_chrom.
Recognized formats:
‘chr’: Format with ‘chr’ prefix, e.g., ‘chr1’, ‘chr2’, …, ‘chrX’, ‘chrY’, ‘chrM’.
‘chm’: Format with ‘chm’ prefix, e.g., ‘chm1’, ‘chm2’, …, ‘chmX’, ‘chmY’, ‘chmM’.
‘chrom’: Format with ‘chrom’ prefix, e.g., ‘chrom1’, ‘chrom2’, …, ‘chromX’, ‘chromY’, ‘chromM’.
‘plain’: Plain format without a prefix, e.g., ‘1’, ‘2’, …, ‘X’, ‘Y’, ‘M’.
If the format does not match any recognized pattern, ‘Unknown format’ is returned.
- Returns:
str – A string indicating the detected chromosome format (‘chr’, ‘chm’, ‘chrom’, or ‘plain’). If no recognized format is matched, returns ‘Unknown format’.
- convert_chromosome_format(from_format, to_format, inplace=False)[source]¶
Convert the chromosome format from one naming convention to another in variants_chrom.
Supported formats:
‘chr’: Format with ‘chr’ prefix, e.g., ‘chr1’, ‘chr2’, …, ‘chrX’, ‘chrY’, ‘chrM’.
‘chm’: Format with ‘chm’ prefix, e.g., ‘chm1’, ‘chm2’, …, ‘chmX’, ‘chmY’, ‘chmM’.
‘chrom’: Format with ‘chrom’ prefix, e.g., ‘chrom1’, ‘chrom2’, …, ‘chromX’, ‘chromY’, ‘chromM’.
‘plain’: Plain format without a prefix, e.g., ‘1’, ‘2’, …, ‘X’, ‘Y’, ‘M’.
- Parameters:
from_format (str) – The current chromosome format. Acceptable values are ‘chr’, ‘chm’, ‘chrom’, or ‘plain’.
to_format (str) – The target format for chromosome data conversion. Acceptable values match from_format options.
inplace (bool, default=False) – If True, modifies self in place. If False, returns a new SNPObject with the converted format. Default is False.
- Returns:
Optional[SNPObject] – A new SNPObject with the converted chromosome format if inplace=False. If inplace=True, modifies self in place and returns None.
- match_chromosome_format(snpobj, inplace=False)[source]¶
Convert the chromosome format in variants_chrom from self to match the format of a reference snpobj.
Recognized formats:
‘chr’: Format with ‘chr’ prefix, e.g., ‘chr1’, ‘chr2’, …, ‘chrX’, ‘chrY’, ‘chrM’.
‘chm’: Format with ‘chm’ prefix, e.g., ‘chm1’, ‘chm2’, …, ‘chmX’, ‘chmY’, ‘chmM’.
‘chrom’: Format with ‘chrom’ prefix, e.g., ‘chrom1’, ‘chrom2’, …, ‘chromX’, ‘chromY’, ‘chromM’.
‘plain’: Plain format without a prefix, e.g., ‘1’, ‘2’, …, ‘X’, ‘Y’, ‘M’.
- Parameters:
- Returns:
Optional[SNPObject] – A new SNPObject with matched chromosome format if inplace=False. If inplace=True, modifies self in place and returns None.
- rename_chrom(to_replace={'^([0-9]+)$': 'chr\\1', '^chr([0-9]+)$': '\\1'}, value=None, regex=True, inplace=False)[source]¶
Replace chromosome values in variants_chrom using patterns or exact matches.
This method allows flexible chromosome replacements, using regex or exact matches, useful for non-standard chromosome formats. For standard conversions (e.g., ‘chr1’ to ‘1’), consider convert_chromosome_format.
- Parameters:
to_replace (dict, str, or list of str) – Pattern(s) or exact value(s) to be replaced in chromosome names. Default behavior transforms <chrom_num> to chr<chrom_num> or vice versa. Non-matching values remain unchanged. - If str or list of str: Matches will be replaced with value. - If regex (bool), then any regex matches will be replaced with value. - If dict: Keys defines values to replace, with corresponding replacements as values.
value (str or list of str, optional) – Replacement value(s) if to_replace is a string or list. Ignored if to_replace is a dictionary.
regex (bool, default=True) – If True, interprets to_replace keys as regex patterns.
inplace (bool, default=False) – If True, modifies self in place. If False, returns a new SNPObject with the chromosomes renamed. Default is False.
- Returns:
Optional[SNPObject] – A new SNPObject with the renamed chromosome format if inplace=False. If inplace=True, modifies self in place and returns None.
- rename_missings(before=-1, after='.', inplace=False)[source]¶
Replace missing values in the genotypes attribute.
This method identifies missing values in ‘genotypes’ and replaces them with a specified value. By default, it replaces occurrences of -1 (often used to signify missing data) with ‘.’.
- Parameters:
before (int, float, or str, default=-1) – The current representation of missing values in genotypes. Common values might be -1, ‘.’, or NaN. Default is -1.
after (int, float, or str, default='.') – The value that will replace before. Default is ‘.’.
inplace (bool, default=False) – If True, modifies self in place. If False, returns a new SNPObject with the applied replacements. Default is False.
- Returns:
Optional[SNPObject] – A new SNPObject with the renamed missing values if inplace=False. If inplace=True, modifies self in place and returns None.
- get_common_variants_intersection(snpobj, index_by='pos')[source]¶
Identify common variants between self and the snpobj instance based on the specified index_by criterion, which may match based on chromosome and position (variants_chrom, variants_pos), ID (variants_id), or both.
This method returns the identifiers of common variants and their corresponding indices in both objects.
- Parameters:
snpobj (SNPObject) – The reference SNPObject to compare against.
index_by (str, default='pos') – Criteria for matching variants. Options: - ‘pos’: Matches by chromosome and position (variants_chrom, variants_pos), e.g., ‘chr1-12345’. - ‘id’: Matches by variant ID alone (variants_id), e.g., ‘rs123’. - ‘pos+id’: Matches by chromosome, position, and ID (variants_chrom, variants_pos, variants_id), e.g., ‘chr1-12345-rs123’. Default is ‘pos’.
- Returns:
Tuple containing –
list of str: A list of common variant identifiers (as strings).
array: An array of indices in self where common variants are located.
array: An array of indices in snpobj where common variants are located.
- get_common_markers_intersection(snpobj)[source]¶
Identify common markers between between self and the snpobj instance. Common markers are identified based on matching chromosome (variants_chrom), position (variants_pos), reference (variants_ref), and alternate (variants_alt) alleles.
This method returns the identifiers of common markers and their corresponding indices in both objects.
- Parameters:
snpobj (SNPObject) – The reference SNPObject to compare against.
- Returns:
Tuple containing –
list of str: A list of common variant identifiers (as strings).
array: An array of indices in self where common variants are located.
array: An array of indices in snpobj where common variants are located.
- subset_to_common_variants(snpobj, index_by='pos', common_variants_intersection=None, inplace=False)[source]¶
Subset self to include only the common variants with a reference snpobj based on the specified index_by criterion, which may match based on chromosome and position (variants_chrom, variants_pos), ID (variants_id), or both.
- Parameters:
snpobj (SNPObject) – The reference SNPObject to compare against.
index_by (str, default='pos') – Criteria for matching variants. Options: - ‘pos’: Matches by chromosome and position (variants_chrom, variants_pos), e.g., ‘chr1-12345’. - ‘id’: Matches by variant ID alone (variants_id), e.g., ‘rs123’. - ‘pos+id’: Matches by chromosome, position, and ID (variants_chrom, variants_pos, variants_id), e.g., ‘chr1-12345-rs123’. Default is ‘pos’.
common_variants_intersection (Tuple[np.ndarray, np.ndarray], optional) – Precomputed indices of common variants between self and snpobj. If None, intersection is computed within the function.
inplace (bool, default=False) – If True, modifies self in place. If False, returns a new SNPObject with the common variants subsetted. Default is False.
- Returns:
Optional[SNPObject] – A new SNPObject with the common variants subsetted if inplace=False. If inplace=True, modifies self in place and returns None.
- subset_to_common_markers(snpobj, common_markers_intersection=None, inplace=False)[source]¶
Subset self to include only the common markers with a reference snpobj. Common markers are identified based on matching chromosome (variants_chrom), position (variants_pos), reference (variants_ref), and alternate (variants_alt) alleles.
- Parameters:
snpobj (SNPObject) – The reference SNPObject to compare against.
common_markers_intersection (tuple of arrays, optional) – Precomputed indices of common markers between self and snpobj. If None, intersection is computed within the function.
inplace (bool, default=False) – If True, modifies self in place. If False, returns a new SNPObject with the common markers subsetted. Default is False.
- Returns:
Optional[SNPObject] – A new SNPObject with the common markers subsetted if inplace=False. If inplace=True, modifies self in place and returns None.
- merge(snpobj, force_samples=False, prefix='2', inplace=False)[source]¶
Merge self with snpobj along the sample axis.
This method expects both SNPObjects to contain the same set of SNPs in the same order, then combines their genotype (genotypes) and LAI (calldata_lai) arrays by concatenating the sample dimension. Samples from snpobj are appended to those in self.
- Parameters:
snpobj (SNPObject) – The SNPObject to merge samples with.
force_samples (bool, default=False) – If True, duplicate sample names are resolved by prepending the prefix to duplicate sample names in snpobj. Otherwise, merging fails when duplicate sample names are found. Default is False.
prefix (str, default='2') – A string prepended to duplicate sample names in snpobj when force_samples=True. Duplicates are renamed from <sample_name> to <prefix>:<sample_name>. For instance, if prefix=’2’ and there is a conflict with a sample called “sample_1”, it becomes “2:sample_1”.
inplace (bool, default=False) – If True, modifies self in place. If False, returns a new SNPObject with the merged samples. Default is False.
- Returns:
Optional[SNPObject] – A new SNPObject containing the merged sample data.
- concat(snpobj, inplace=False)[source]¶
Concatenate self with snpobj along the SNP axis.
This method expects both SNPObjects to contain the same set of samples in the same order, and that the chromosome(s) in snpobj follow (i.e. have higher numeric identifiers than) those in self.
- Parameters:
- Returns:
Optional[SNPObject] – A new SNPObject containing the concatenated SNP data.
- classmethod concat_variants(snpobjs)[source]¶
Concatenate multiple SNPObjects along the SNP axis.
All objects must have the same sample order and genotype representation.
- remove_strand_ambiguous_variants(inplace=False)[source]¶
A strand-ambiguous variant has reference (variants_ref) and alternate (variants_alt) alleles in the pairs A/T, T/A, C/G, or G/C, where both alleles are complementary and thus indistinguishable in terms of strand orientation.
- Parameters:
inplace (bool, default=False) – If True, modifies self in place. If False, returns a new SNPObject with the strand-ambiguous variants removed. Default is False.
- Returns:
Optional[SNPObject] – A new SNPObject with non-ambiguous variants only if inplace=False. If inplace=True, modifies self in place and returns None.
- correct_flipped_variants(snpobj, check_complement=True, index_by='pos', common_variants_intersection=None, log_stats=True, inplace=False)[source]¶
Correct flipped variants between between self and a reference snpobj, where reference (variants_ref) and alternate (variants_alt) alleles are swapped.
Flip Detection Based on check_complement:
- If check_complement=False, only direct allele swaps are considered:
Direct Swap: self.variants_ref == snpobj.variants_alt and self.variants_alt == snpobj.variants_ref.
If check_complement=True, a swap is accepted when either both original alleles or both complemented alleles match the swapped reference pair. Partial complements and strand-ambiguous orientations are not changed.
Note: Variants where self.variants_ref == self.variants_alt are ignored as they are ambiguous.
Correction Process: - Swaps variants_ref and variants_alt alleles in self to align with snpobj. - Flips called 2D diploid dosages as 2 - dosage and called 3D allele indexes as
1 - allele, while preserving missing values.
- Parameters:
snpobj (SNPObject) – The reference SNPObject to compare against.
check_complement (bool, default=True) – If True, also checks for complementary base pairs (A/T, T/A, C/G, and G/C) when identifying swapped variants. Default is True.
index_by (str, default='pos') – Criteria for matching variants. Options: - ‘pos’: Matches by chromosome and position (variants_chrom, variants_pos), e.g., ‘chr1-12345’. - ‘id’: Matches by variant ID alone (variants_id), e.g., ‘rs123’. - ‘pos+id’: Matches by chromosome, position, and ID (variants_chrom, variants_pos, variants_id), e.g., ‘chr1-12345-rs123’. Default is ‘pos’.
common_variants_intersection (tuple of arrays, optional) – Precomputed indices of common variants between self and snpobj. If None, intersection is computed within the function.
log_stats (bool, default=True) – If True, logs statistical information about matching and ambiguous alleles. Default is True.
inplace (bool, default=False) – If True, modifies self in place. If False, returns a new SNPObject with corrected flips. Default is False.
- Returns:
Optional[SNPObject] – A new SNPObject with corrected flips if inplace=False. If inplace=True, modifies self in place and returns None.
- remove_mismatching_variants(snpobj, index_by='pos', common_variants_intersection=None, inplace=False)[source]¶
Remove variants from self, where reference (variants_ref) and/or alternate (variants_alt) alleles do not match with a reference snpobj.
- Parameters:
snpobj (SNPObject) – The reference SNPObject to compare against.
index_by (str, default='pos') – Criteria for matching variants. Options: - ‘pos’: Matches by chromosome and position (variants_chrom, variants_pos), e.g., ‘chr1-12345’. - ‘id’: Matches by variant ID alone (variants_id), e.g., ‘rs123’. - ‘pos+id’: Matches by chromosome, position, and ID (variants_chrom, variants_pos, variants_id), e.g., ‘chr1-12345-rs123’. Default is ‘pos’.
common_variants_intersection (tuple of arrays, optional) – Precomputed indices of common variants between self and the reference snpobj. If None, the intersection is computed within the function.
inplace (bool, default=False) – If True, modifies self in place. If False, returns a new SNPObject without mismatching variants. Default is False.
- Returns:
Optional[SNPObject] – A new SNPObject without mismatching variants if inplace=False. If inplace=True, modifies self in place and returns None.
- shuffle_variants(inplace=False)[source]¶
Randomly shuffle the positions of variants in the SNPObject, ensuring that all associated data (e.g., genotypes and variant-specific attributes) remain aligned.
- Parameters:
inplace (bool, default=False) – If True, modifies self in place. If False, returns a new SNPObject with shuffled variants. Default is False.
- Returns:
Optional[SNPObject] – A new SNPObject without shuffled variant positions if inplace=False. If inplace=True, modifies self in place and returns None.
- set_empty_to_missing(inplace=False)[source]¶
Replace empty strings ‘’ with missing values ‘.’ in attributes of self.
- Parameters:
inplace (bool, default=False) – If True, modifies self in place. If False, returns a new SNPObject with empty strings ‘’ replaced by missing values ‘.’. Default is False.
- Returns:
Optional[SNPObject] – A new SNPObject with empty strings replaced if inplace=False. If inplace=True, modifies self in place and returns None.
- convert_to_window_level(window_size=None, physical_pos=None, chromosomes=None, window_sizes=None, laiobj=None)[source]¶
Aggregate the calldata_lai attribute into genomic windows within a snputils.ancestry.genobj.LocalAncestryObject.
Window definitions are resolved in this precedence order: fixed window size via
window_size; explicit boundaries viaphysical_pos(optionally withchromosomesandwindow_sizes); or reuse of existing window metadata fromlaiobj.- Parameters:
window_size (int, optional) – Number of SNPs in each window if defining fixed-size windows. If the total number of SNPs in a chromosome is not evenly divisible by the window size, the last window on that chromosome will include all remaining SNPs and therefore be larger than the specified size.
physical_pos (array of shape (n_windows, 2), optional) – A 2D array containing the start and end physical positions for each window.
chromosomes (array of shape (n_windows,), optional) – An array with chromosome numbers corresponding to each genomic window.
window_sizes (array of shape (n_windows,), optional) – An array specifying the number of SNPs in each genomic window.
laiobj (LocalAncestryObject, optional) – A reference LocalAncestryObject from which to copy existing window definitions.
- Returns:
LocalAncestryObject – A LocalAncestryObject containing window-level ancestry data.
- save(file)[source]¶
Save the data stored in self to a specified file.
The format of the saved file is determined by the file extension provided in the file argument.
Supported formats:
.bed: Binary PED (Plink) format.
.bgen: BGEN genotype probability format.
.pgen: Plink2 binary genotype format.
.vcf: Variant Call Format.
.bcf: Binary Call Format.
.pkl: Pickle format for saving self in serialized form.
- Parameters:
file (str or pathlib.Path) – Path to the file where the data will be saved. The extension of the file determines the save format. Supported extensions: .bed, .bgen, .pgen, .vcf, .bcf, .pkl.
- save_bed(file, rename_missing_values=True, before=-1, after='.', sample_phenotype=None)[source]¶
Save the data stored in self to a .bed file.
- Parameters:
file (str or pathlib.Path) – Path to the file where the data will be saved. It should end with .bed. If the provided path does not have this extension, it will be appended.
rename_missing_values (bool, optional) – If True, renames potential missing values in genotypes before writing.
before (int, float, or str, default=-1) – The current representation of missing values in genotypes.
after (int, float, or str, default='.') – The value that will replace before.
sample_phenotype (optional) – PLINK phenotype value per sample, or a scalar used for all samples.
- save_pgen(file)[source]¶
Save the data stored in self to a .pgen file.
- Parameters:
file (str or pathlib.Path) – Path to the file where the data will be saved. It should end with .pgen. If the provided path does not have this extension, it will be appended.
- save_bgen(file)[source]¶
Save the data stored in self to a .bgen file.
- Parameters:
file (str or pathlib.Path) – Path to the file where the data will be saved. It should end with .bgen. If the provided path does not have this extension, it will be appended.
- save_vcf(file)[source]¶
Save the data stored in self to a .vcf file.
- Parameters:
file (str or pathlib.Path) – Path to the file where the data will be saved. It should end with .vcf. If the provided path does not have this extension, it will be appended.
- save_bcf(file, phased=False)[source]¶
Save the data stored in self to a .bcf file.
- Parameters:
file (str or pathlib.Path) – Path to the file where the data will be saved. It should end with .bcf. If the provided path does not have this extension, it will be appended.
phased (bool, optional) – If True, genotype data is written in phased format. If False, genotype data is written in unphased format. Defaults to False.
- save_pickle(file)[source]¶
Save self in serialized form to a .pkl file.
- Parameters:
file (str or pathlib.Path) – Path to the file where the data will be saved. It should end with .pkl. If the provided path does not have this extension, it will be appended.
- class snputils.GRGObject(genotypes=None, filename=None, mutable=None)[source]¶
Bases:
objectA class for Single Nucleotide Polymorphism (SNP) data.
- Parameters:
genotypes (GRG | MutableGRG, optional) – A Genotype Representation Graph containing genotype data for each sample.
filename (str, optional) – File storing the GRG.
- property genotypes¶
Retrieve genotypes.
- Returns:
GRG | MutableGRG – An GRG containing genotype data for all samples.
- property filename¶
Retrieve filename.
- Returns:
- str
A string containing the file name.
- property shape¶
Retrieve the graph genotype shape as (n_mutations, n_haplotypes).
- to_snpobject(genotype_mode='phased', chrom='.', sample_prefix='sample')[source]¶
Convert the GRG to a dense SNPObject.
Notes
This materializes the full genotype matrix, so memory usage scales with num_mutations * num_samples.
For diploid GRGs and
genotype_mode="phased", output has shape (n_snps, n_samples, 2).For
genotype_mode="dosage", output has shape (n_snps, n_samples) with per-individual allele counts.
- copy()[source]¶
Create and return a copy of self.
- Returns:
GRGObject – A new instance of the current object.
Readers¶
- class snputils.SNPReader(filename, vcf_backend='default')[source]¶
Bases:
objectAutomatically detect the SNP file format from the file extension, and return its corresponding reader.
- Parameters:
filename – Filename of the file to read.
vcf_backend – Backend to use for reading the VCF file. Options are ‘default’ or ‘polars’. Default is ‘default’.
- Raises:
ValueError – If the filename does not have an extension or the extension is not supported.
- class snputils.BEDReader(filename)[source]¶
Bases:
SNPBaseReaderInitialize the SNPBaseReader.
- Parameters:
filename – The path to the file storing SNP data.
- read(fields=None, exclude_fields=None, sample_ids=None, sample_idxs=None, variant_ids=None, variant_idxs=None, genotype_mode='dosage', chromosome_ploidy=None, separator=None)[source]¶
Read a bed fileset (bed, bim, fam) into a SNPObject.
- Parameters:
fields (str, None, or list of str, optional) – Fields to extract data for that should be included in the returned SNPObject. Available fields are ‘GT’, ‘IID’, ‘REF’, ‘ALT’, ‘#CHROM’, ‘CM’, ‘ID’, ‘POS’. To extract all fields, set fields to None. Defaults to None.
exclude_fields (str, None, or list of str, optional) – Fields to exclude from the returned SNPObject. Available fields are ‘GT’, ‘IID’, ‘REF’, ‘ALT’, ‘#CHROM’, ‘CM’, ‘ID’, ‘POS’. To exclude no fields, set exclude_fields to None. Defaults to None.
sample_ids – List of sample IDs to read. If None and sample_idxs is None, all samples are read.
sample_idxs – List of sample indices to read. If None and sample_ids is None, all samples are read.
variant_ids – List of variant IDs to read. If None and variant_idxs is None, all variants are read.
variant_idxs – List of variant indices to read. If None and variant_ids is None, all variants are read.
genotype_mode –
"dosage"(default) returns genotype dosages in a singleint8array with values{0, 1, 2}."auto"is equivalent to"dosage". PLINK BED/BIM/FAM does not store phase, so"phased"is not supported.chromosome_ploidy – Optional hint for chromosome-specific dosage conversion. Use “autosomal” when all selected variants should be treated as ordinary diploid/autosomal; this skips non-diploid chromosome checks and can be faster. The default None/”auto” preserves existing behavior.
separator – Separator used in the pvar file. If None, the separator is automatically detected. If the automatic detection fails, please specify the separator manually.
- Returns:
*SNPObject* – A SNPObject instance.
- iter_read(fields=None, exclude_fields=None, sample_ids=None, sample_idxs=None, variant_ids=None, variant_idxs=None, genotype_mode='dosage', chromosome_ploidy=None, separator=None, chunk_size=10000)[source]¶
Stream the BED fileset in variant chunks.
This yields a sequence of SNPObject chunks along the SNP axis.
- chromosome_ploidy:
Optional hint for chromosome-specific dosage conversion. Use “autosomal” when all selected variants should be treated as ordinary diploid/autosomal; this skips non-diploid chromosome checks and can be faster. The default None/”auto” preserves existing behavior.
- class snputils.BCFReader(filename)[source]¶
Bases:
SNPBaseReaderInitialize the SNPBaseReader.
- Parameters:
filename – The path to the file storing SNP data.
- read(fields=None, exclude_fields=None, sample_ids=None, sample_idxs=None, variant_ids=None, variant_idxs=None, region=None, genotype_mode='auto', chromosome_ploidy=None)[source]¶
Read a BCF file into a SNPObject.
- Parameters:
fields – Fields to include. Supported fields are
GT,GP,IID,REF,ALT,#CHROM,ID,POS,QUAL,FILTER, andINFO. Use"*"to request the full set. If None, the default core fields are loaded.exclude_fields – Fields to exclude from the returned SNPObject.
sample_ids – Sample IDs to read. If None and sample_idxs is None, all samples are read.
sample_idxs – Sample indices to read. Negative indexes follow NumPy conventions.
variant_ids – Variant identifiers to read. Matches BCF
ID,chrom:pos, orchrom:pos:ref:alt.variant_idxs – Variant indices to read. Negative indexes follow NumPy conventions.
region – Optional genomic region, such as
"22"or"22:100000-200000".genotype_mode –
"dosage"returns biallelic ALT-copy counts (0,1, or2) and rejects multiallelic variants."phased"keeps phased allele columns separate and rejects unphased calls."auto"(default) preserves phased calls and falls back to dosage for unphased calls.chromosome_ploidy – Optional hint for chromosome-specific dosage conversion. Use “autosomal” when all selected variants should be treated as ordinary diploid/autosomal; this skips non-diploid chromosome checks and can be faster. The default None/”auto” preserves existing behavior.
- Returns:
SNPObject – Object containing selected genotype, sample, and variant fields.
GPis stored onSNPObject.calldata_gpwhen present.
- class snputils.BGENReader(filename)[source]¶
Bases:
SNPBaseReaderInitialize the SNPBaseReader.
- Parameters:
filename – The path to the file storing SNP data.
- read(fields=None, exclude_fields=None, sample_path=None, sample_ids=None, sample_idxs=None, variant_ids=None, variant_idxs=None)[source]¶
Read a BGEN file into a SNPObject.
- Parameters:
fields – Fields to include. Available fields are
GP,IID,REF,ALT,#CHROM,ID, andPOS.GTis intentionally unsupported because this reader preserves BGEN genotype probabilities instead of converting them to hard calls.exclude_fields – Fields to exclude from the returned SNPObject.
sample_path – Optional Oxford
.samplefile for BGEN files without embedded sample identifiers.sample_ids – Sample IDs to read. If None and sample_idxs is None, all samples are read.
sample_idxs – Sample indices to read. If None and sample_ids is None, all samples are read.
variant_ids – Variant IDs to read. Matches BGEN varid, rsid, or
chrom:pos.variant_idxs – Variant indices to read. If None and variant_ids is None, all variants are read.
- Returns:
SNPObject – A SNPObject with genotype probabilities in
calldata_gp. Mixed probability widths are padded with NaN columns.
- read_dosage(sample_path=None, sample_ids=None, sample_idxs=None, variant_ids=None, variant_idxs=None)[source]¶
Read biallelic BGEN alternate-allele dosages as a
float32array.The all-samples/all-variants case uses a native streaming decoder that avoids materializing genotype probabilities. Filtered reads fall back to the general probability reader and convert from
calldata_gp.
- class snputils.PGENReader(filename)[source]¶
Bases:
SNPBaseReaderInitialize the SNPBaseReader.
- Parameters:
filename – The path to the file storing SNP data.
- read(fields=None, exclude_fields=None, sample_ids=None, sample_idxs=None, variant_ids=None, variant_idxs=None, genotype_mode='auto', chromosome_ploidy=None, separator=None)[source]¶
Read a pgen fileset (pgen, psam, pvar) into a SNPObject.
- Parameters:
fields (str, None, or list of str, optional) – Fields to extract data for that should be included in the returned SNPObject. Available fields are ‘GT’, ‘IID’, ‘REF’, ‘ALT’, ‘#CHROM’, ‘CM’, ‘ID’, ‘POS’, ‘FILTER’, ‘QUAL’, ‘INFO’. To extract all fields, set fields to None. Defaults to None.
exclude_fields (str, None, or list of str, optional) – Fields to exclude from the returned SNPObject. Available fields are ‘GT’, ‘IID’, ‘REF’, ‘ALT’, ‘#CHROM’, ‘CM’, ‘ID’, ‘POS’, ‘FILTER’, ‘QUAL’, ‘INFO’. To exclude no fields, set exclude_fields to None. Defaults to None.
sample_ids – List of sample IDs to read. If None and sample_idxs is None, all samples are read.
sample_idxs – List of sample indices to read. If None and sample_ids is None, all samples are read.
variant_ids – List of variant IDs to read. If None and variant_idxs is None, all variants are read.
variant_idxs – List of variant indices to read. If None and variant_ids is None, all variants are read.
genotype_mode –
"dosage"returns one biallelic ALT-copy count per sample as anint8value in{0, 1, 2}and rejects multiallelic variants."phased"returns phased allele calls and requires PGEN hardcall phase information."auto"(default) preserves phased hardcalls when possible and falls back to dosage for unphased hardcalls.chromosome_ploidy – Optional hint for chromosome-specific dosage conversion. Use “autosomal” when all selected variants should be treated as ordinary diploid/autosomal; this skips non-diploid chromosome checks and can be faster. The default None/”auto” preserves existing behavior.
separator – Separator used in the pvar file. If None, the separator is automatically detected. If the automatic detection fails, please specify the separator manually.
- Returns:
*SNPObject* – A SNPObject instance.
- iter_read(fields=None, exclude_fields=None, sample_ids=None, sample_idxs=None, variant_ids=None, variant_idxs=None, genotype_mode='phased', chromosome_ploidy=None, separator=None, chunk_size=10000)[source]¶
Stream the PGEN fileset in variant chunks.
This yields a sequence of SNPObject chunks along the SNP axis.
- chromosome_ploidy:
Optional hint for chromosome-specific dosage conversion. Use “autosomal” when all selected variants should be treated as ordinary diploid/autosomal; this skips non-diploid chromosome checks and can be faster. The default None/”auto” preserves existing behavior.
- class snputils.VCFReader(filename)[source]¶
Bases:
SNPBaseReaderReads VCF files into an SNPObject with a NumPy parser optimized for GT columns.
.vcfand.vcf.gzfiles with GT-only sample fields use a block parser that avoids materializing genotype strings in a DataFrame. Simple diploid FORMAT layouts such asGT:DPandDP:GTuse a streaming byte parser. Other supported VCF layouts fall back to a pandas chunked parser. By default it reads the core variant fieldsCHROM,POS,ID,REF,ALT,QUAL, andFILTER; passfields="*"or include"INFO"when the INFO column is required.Supports reading sampleless (annotation-only) VCF files. In this case, the returned SNPObject will have an empty genotypes array with a variant axis (shape (n_snps, 0) or (n_snps, 0, 2)).
Initialize the SNPBaseReader.
- Parameters:
filename – The path to the file storing SNP data.
- read(fields=None, exclude_fields=None, region=None, samples=None, genotype_mode='auto', chromosome_ploidy=None, separator=None)[source]¶
Read a VCF file into an
SNPObject.By default, the reader loads the core VCF variant columns
CHROM,POS,ID,REF,ALT,QUAL, andFILTER, plus all sample genotype columns. Genotypes are read from theGTFORMAT field and returned as anint8array. By default (genotype_mode="auto"), phased genotypes are kept separate with shape(n_variants, n_samples, 2)and unphased GT calls fall back to dosages with shape(n_variants, n_samples). Withgenotype_mode="dosage", the two alleles are converted to dosage. Withgenotype_mode="phased", unphased/GT calls are rejected because their allele order is not meaningful.- Parameters:
fields – VCF fixed columns to include, such as
["CHROM", "POS", "ID"]. Use"*"to include all fixed VCF columns, includingINFOandFORMAT. IfNone, the default core fields are used.exclude_fields – Fixed VCF columns to exclude. This is mainly useful with
fields="*"; whenfieldsisNone, it excludes columns from the default core field set.region – Optional genomic region to read. Accepts chromosome-only values such as
"22"or inclusive 1-based intervals such as"22:100000-200000". Records are included when their POS is within the requested interval.samples – Optional sample subset. Provide sample IDs or zero-based sample indexes. If omitted, all samples are read; pass an empty sequence to read variant metadata without genotypes.
genotype_mode –
"dosage"returns biallelic ALT-copy counts (0,1, or2) and rejects multiallelic variants."phased"keeps phased allele columns separate and rejects unphased GT calls."auto"(default) preserves phased calls and falls back to dosage for unphased calls.chromosome_ploidy – Optional hint for chromosome-specific dosage conversion. Use “autosomal” when all selected variants should be treated as ordinary diploid/autosomal; this skips non-diploid chromosome checks and can be faster. The default None/”auto” preserves existing behavior.
separator – Optional column separator. If omitted, the separator is detected from the VCF header. Tab-delimited files use optimized byte parsers when possible; other separators use the pandas chunked parser.
- Returns:
SNPObject – Object containing selected genotype, sample, and variant fields.
- iter_read(fields=None, exclude_fields=None, region=None, samples=None, sample_ids=None, sample_idxs=None, variant_ids=None, variant_idxs=None, genotype_mode='phased', chromosome_ploidy=None, separator=None, chunk_size=10000)[source]¶
Stream a VCF in variant chunks.
- chromosome_ploidy:
Optional hint for chromosome-specific dosage conversion. Use “autosomal” when all selected variants should be treated as ordinary diploid/autosomal; this skips non-diploid chromosome checks and can be faster. The default None/”auto” preserves existing behavior.
- class snputils.snp.io.read.vcf.VCFReaderPolars(filename)[source]¶
Bases:
SNPBaseReaderReads a VCF file and processes it into a SNPObject.
Initialize the SNPBaseReader.
- Parameters:
filename – The path to the file storing SNP data.
- read(fields=None, exclude_fields=None, region=None, samples=None, genotype_mode='auto', chromosome_ploidy=None, separator=None)[source]¶
Read a vcf file into a SNPObject.
- Parameters:
fields – Fields to extract data for. This parameter specifies which data fields from the VCF file should be included in the result. Available options include ‘CHROM’/’#CHROM’, ‘POS’, ‘ID’, ‘REF’, ‘ALT’, ‘QUAL’, ‘FILTER’, ‘INFO’, and ‘FORMAT’. To extract all fields, provide just the string ‘*’ or the default None.
exclude_fields – Fields to exclude for use in combination with fields=’*’. Available options include ‘CHROM’/’#CHROM’, ‘POS’, ‘ID’, ‘REF’, ‘ALT’, ‘QUAL’, ‘FILTER’, ‘INFO’, and ‘FORMAT’.
region – Genomic region to extract variants for. If provided, it should be a tabix-style region string, specifying a chromosome name and optionally beginning and end coordinates (e.g., ‘2L:100000-200000’). TODO
samples – Selection of samples to extract calldata for. If provided, should be a list of strings giving sample identifiers. May also be a list of integers giving indices of selected samples. If an empty list is provided, no samples are extracted.
genotype_mode –
"dosage"returns biallelic ALT-copy counts (0,1, or2) and rejects multiallelic variants."phased"preserves phased allele calls and rejects unphased calls."auto"preserves phased calls and falls back to dosage for unphased calls.chromosome_ploidy – Optional hint for chromosome-specific dosage conversion. Use “autosomal” when all selected variants should be treated as ordinary diploid/autosomal; this skips non-diploid chromosome checks and can be faster. The default None/”auto” preserves existing behavior.
separator – Separator used in the pvar file. If None, the separator is automatically detected. If the automatic detection fails, please specify the separator manually.
- Returns:
snpobj –
- SNPObject containing the data from the VCF file. The format and content
of this object depend on the specified parameters and the content of the VCF file.
- iter_read(fields=None, exclude_fields=None, region=None, samples=None, sample_ids=None, sample_idxs=None, variant_ids=None, variant_idxs=None, genotype_mode='phased', chromosome_ploidy=None, separator=None, chunk_size=10000)[source]¶
Stream a VCF in variant chunks using the Polars backend.
- chromosome_ploidy:
Optional hint for chromosome-specific dosage conversion. Use “autosomal” when all selected variants should be treated as ordinary diploid/autosomal; this skips non-diploid chromosome checks and can be faster. The default None/”auto” preserves existing behavior.
Read Functions¶
- snputils.read_snp(filename, **kwargs)[source]¶
Automatically detect the file format and read it into a SNPObject.
- Parameters:
filename – Filename of the file to read.
**kwargs – Additional arguments passed to the reader method.
- Raises:
ValueError – If the filename does not have an extension or the extension is not supported.
- snputils.read_bed(filename, **kwargs)[source]¶
Read a BED fileset into a SNPObject.
- Parameters:
filename – Filename of the BED fileset to read.
**kwargs – Additional arguments passed to the reader method. See
snputils.snp.io.read.bed.BEDReaderfor possible parameters.
- snputils.read_bcf(filename, **kwargs)[source]¶
Read a BCF file into a SNPObject.
- Parameters:
filename – Filename of the BCF file to read.
**kwargs – Additional arguments passed to the reader method. See
snputils.snp.io.read.bcf.BCFReaderfor possible parameters.
- snputils.read_bgen(filename, **kwargs)[source]¶
Read a BGEN file into a SNPObject.
- Parameters:
filename – Filename of the BGEN file to read.
**kwargs – Additional arguments passed to the reader method. See
snputils.snp.io.read.bgen.BGENReaderfor possible parameters.
- snputils.read_pgen(filename, **kwargs)[source]¶
Read a PGEN fileset into a SNPObject.
- Parameters:
filename – Filename of the PGEN fileset to read.
**kwargs – Additional arguments passed to the reader method. See
snputils.snp.io.read.pgen.PGENReaderfor possible parameters.
- snputils.read_vcf(filename, backend='default', **kwargs)[source]¶
Read a VCF into a SNPObject.
- Parameters:
filename – Filename of the VCF fileset to read.
backend – Backend to use for reading the VCF file. Options are ‘default’ or ‘polars’.
**kwargs – Additional arguments passed to the reader method. See
snputils.snp.io.read.vcf.VCFReaderfor possible parameters.
Writers¶
- class snputils.BEDWriter(snpobj, filename)[source]¶
Bases:
objectWrites an object in bed/bim/fam formats in the specified output path.
- Parameters:
snpobj – The SNPObject to be written.
file – The output file path.
- write(rename_missing_values=True, before=-1, after='.', sample_phenotype=None)[source]¶
Writes the SNPObject to bed/bim/fam formats.
- Parameters:
rename_missing_values (bool, optional) – If True, renames potential missing values in snpobj.genotypes before writing. Defaults to True.
before (int, float, or str, default=-1) – The current representation of missing values in genotypes. Common values might be -1, ‘.’, or NaN. Default is -1.
after (int, float, or str, default='.') – The value that will replace before. Default is ‘.’.
sample_phenotype (optional) – PLINK phenotype value per sample, or a scalar used for all samples. Defaults to
-9for all samples.
- class snputils.BGENWriter(snpobj, filename)[source]¶
Bases:
objectWrite a SNPObject to BGEN format.
calldata_gpis written directly when present. If it is absent andgenotypesis present, hard calls are encoded as one-hot genotype probabilities so SNPObjects created from VCF/BED/PGEN can still be exported.Initialize the BGENWriter.
- Parameters:
snpobj – SNPObject containing genotype probabilities or hard-call genotypes.
filename – Output path. A
.bgensuffix is appended if missing.
- write(compression='zstd', layout=2, bit_depth=8, phased=None, metadata=None)[source]¶
Write the SNPObject to a BGEN file.
- Parameters:
compression – BGEN compression type. Supported by the backend:
None,"zlib", and"zstd".layout – BGEN layout version. The backend supports layouts 1 and 2.
bit_depth – Number of bits used to store each probability.
phased – Whether probabilities are phased. If None, inferred per variant from
calldata_gpwidth and NaN padding when possible.metadata – Optional free-form BGEN metadata string.
- class snputils.PGENWriter(snpobj, filename)[source]¶
Bases:
objectWrites a genotype object in PGEN format (.pgen, .psam, and .pvar files) in the specified output path.
Initializes the PGENWriter instance.
- Parameters:
- write(vzs=False, rename_missing_values=True, before=-1, after='.')[source]¶
Writes the SNPObject data to .pgen, .psam, and .pvar files.
- Parameters:
vzs (bool, optional) – If True, compresses the .pvar file using zstd and saves it as .pvar.zst. Defaults to False.
rename_missing_values (bool, optional) – If True, renames potential missing values in snpobj.genotypes before writing. Defaults to True.
before (int, float, or str, default=-1) – The current representation of missing values in genotypes. Common values might be -1, ‘.’, or NaN. Default is -1.
after (int, float, or str, default='.') – The value that will replace before. Default is ‘.’.
- class snputils.VCFWriter(snpobj, filename, n_jobs=-1, phased=False)[source]¶
Bases:
objectA writer class for exporting SNP data from a snputils.snp.genobj.SNPObject into an .vcf file. Supports sampleless VCF writes (annotation-only) when the input SNPObject has no samples.
- Parameters:
snpobj (SNPObject) – A SNPObject instance.
file (str or pathlib.Path) – Path to the file where the data will be saved. It should end with .vcf. If the provided path does not have this extension, the .vcf extension will be appended.
n_jobs – Number of jobs to run in parallel. - None: use 1 job unless within a joblib.parallel_backend context. - -1: use all available processors. - Any other integer: use the specified number of jobs.
phased – If True, genotype data is written in “first_allele|second_allele” format. If False, genotype data is written in “first_allele/second_allele” format.
- write(chrom_partition=False, rename_missing_values=True, before=-1, after='.', variants_info=None)[source]¶
Writes the SNP data to VCF file(s). If writing a sampleless VCF, the genotypes array must be an empty array with a variant axis.
- Parameters:
chrom_partition (bool, optional) – If True, individual VCF files are generated for each chromosome. If False, a single VCF file containing data for all chromosomes is created. Defaults to False.
rename_missing_values (bool, optional) – If True, renames potential missing values in snpobj.genotypes before writing. Defaults to True.
before (int, float, or str, default=-1) – The current representation of missing values in genotypes. Common values might be -1, ‘.’, or NaN. Default is -1.
after (int, float, or str, default='.') – The value that will replace before. Default is ‘.’.
variants_info (sequence of str, optional) – Per-variant INFO column values (e.g.
["END=2000", "END=3000"]). Length must match variant count. When provided, a ##INFO header line for END is written if any value containsEND=.
- class snputils.BCFWriter(snpobj, filename, n_jobs=-1, phased=False)[source]¶
Bases:
objectA writer class for exporting SNP data from a snputils.snp.genobj.SNPObject into a .bcf file.
- Parameters:
snpobj – A SNPObject instance.
filename – Path to the file where the data will be saved. It should end with .bcf. If the provided path does not have this extension, the .bcf extension will be appended.
n_jobs – Number of jobs to run in parallel. Unused, included for API consistency.
phased – If True, diploid GT values are written with phased separators.
- write(chrom_partition=False, rename_missing_values=True, before=-1, after='.', variants_info=None, compression_level=1)[source]¶
Writes the SNP data to BCF file(s).
- Parameters:
chrom_partition – If True, individual BCF files are generated for each chromosome. If False, a single BCF file containing data for all chromosomes is created.
rename_missing_values – If True, common missing representations in genotypes are encoded as native BCF missing GT values. The SNPObject is not mutated.
before – Current representation of missing values in genotypes.
after – Unused for BCF because the binary GT representation has a native missing value. Kept for API compatibility.
variants_info – Optional per-variant INFO column values. When omitted, snpobj.variants_info is used when present.
compression_level – BGZF compression level from 0 to 9. The default favors write speed while producing standard BGZF-compressed BCF.