Site filtration#
A Filtration drops sites that violate downstream modelling assumptions. Filtrations can be applied on the fly by the Parser while it builds a spectrum, or run through the Filterer to write the retained sites to a file.
Filter the input using a list of filtrations. |
|
Base class for filtering sites based on certain criteria. |
|
Filter sites based on a samples mask, where |
|
Only keep SNPs. |
|
Only keep single site variants (discard indels and MNPs but keep monomorphic sites). |
|
Filter out poly-allelic sites. |
|
Filter out all sites. |
|
Do not filter out any sites. |
|
Filter out sites that are not in coding sequences. |
|
Filter out sites where the major allele of the specified outgroup samples differs from the major allele of the ingroup samples. |
|
Filter out sites for which at least |
|
Only retain A<->T and G<->C substitutions (which are unaffected by biased gene conversion, see [CITGB]). |
|
Filter out sites whose reference base is in a CpG dinucleotide context. |
|
Filter out sites that are not on the specified contigs. |
Filterer#
- class Filterer(source: str | os.PathLike | 'tskit.TreeSequence' | VariantReader | Iterable[Site] | None = None, output: str = None, gff: str | None = None, fasta: str | None = None, filtrations: List[Filtration] = [], info_ancestral: str = 'AA', max_sites: int = inf, seed: int | None = 0, cache: bool = True, aliases: Dict[str, List[str]] = {}, vcf: str | os.PathLike | 'tskit.TreeSequence' | VariantReader | Iterable[Site] | None = None)[source]#
Bases:
MultiHandlerFilter the input using a list of filtrations.
Example usage:
import sfsutils as su # only keep variants in coding sequences f = su.Filterer( source="http://ftp.1000genomes.ebi.ac.uk/vol1/ftp/data_collections/" "1000_genomes_project/release/20181203_biallelic_SNV/" "ALL.chr21.shapeit2_integrated_v1a.GRCh38.20181129.phased.vcf.gz", gff="http://ftp.ensembl.org/pub/release-109/gff3/homo_sapiens/" "Homo_sapiens.GRCh38.109.chromosome.21.gff3.gz", output='sapiens.chr21.coding.vcf.gz', filtrations=[su.CodingSequenceFiltration()], aliases=dict(chr21=['21']) ) f.filter()
Methods:
Create a new filter instance.
Count the number of sites in the source.
Download a file from a URL.
Download the file if it is a URL.
Get all aliases for the given contig alias including the primary alias.
Get the contig from the FASTA file.
Get the names of the contigs in the FASTA file.
Return the file extension of a URL.
Return a progress bar for the number of sites.
Return a truncated SHA1 hash of a string.
Check if the given path is a URL.
Load a FASTA file into a dictionary.
Open a VCF file for streaming.
Remove overlapping coding sequences.
If the given file is gzipped, unzip it and return the path to the unzipped file.
Whether the given variant is kept.
Filter the input.
- __init__(source: str | os.PathLike | 'tskit.TreeSequence' | VariantReader | Iterable[Site] | None = None, output: str = None, gff: str | None = None, fasta: str | None = None, filtrations: List[Filtration] = [], info_ancestral: str = 'AA', max_sites: int = inf, seed: int | None = 0, cache: bool = True, aliases: Dict[str, List[str]] = {}, vcf: str | os.PathLike | 'tskit.TreeSequence' | VariantReader | Iterable[Site] | None = None)[source]#
Create a new filter instance.
- Parameters:
source (str | os.PathLike | ‘tskit.TreeSequence’ | VariantReader | Iterable[Site] | None) – The variant source: a VCF file (gzipped or a URL), a VCF-Zarr store (a
.vczor.zarrdirectory), a tskit tree sequence (a.treesfile or an in-memorytskit.TreeSequence), or a pre-builtVariantReader/ iterable of sites. Read through the same streamed site interface as all handlers.output (
str) – The output file.gff (
str|None) – The GFF file, possibly gzipped or a URL. This argument is required for some filtrations.fasta (
str|None) – The FASTA reference file, possibly gzipped or a URL. This argument is required for filtrations that depend on the reference sequence (e.g. base context).filtrations (
List[Filtration]) – The filtrations.info_ancestral (
str) – The info field for the ancestral allele.max_sites (
int) – The maximum number of sites to process.seed (
int|None) – The seed for the random number generator. UseNonefor no seed.cache (
bool) – Whether to cache files downloaded from urls.aliases (
Dict[str,List[str]]) – Dictionary of aliases for the contigs in the input, e.g.{'chr1': ['1']}.vcf (str | os.PathLike | ‘tskit.TreeSequence’ | VariantReader | Iterable[Site] | None) – Deprecated alias for
source, kept for backward compatibility. Provide eithersourceorvcf, not both.
- Raises:
ValueError – If
max_sitesis not positive.
- filtrations: List[Filtration]#
The filtrations.
- property contig_lengths: Dict[str, int] | None#
The declared length (bp) of each contig of the source: the
##contigheaders of a VCF, thecontig_lengtharray of a VCF-Zarr store, or the length of the genome of a tree sequence. Only the contigs whose length is known are present, and a source declaring none givesNone. The span of the observed variants understates the region on a sparsely covered contig, so this is what a spectrum extrapolating monomorphic sites should be sized against.- Returns:
The per-contig lengths, or
Nonewhere the source declares none.
- classmethod download_file(url: str, cache: bool = True, desc: str = 'Downloading file')#
Download a file from a URL.
- get_contig(aliases, rewind: bool = True, notify: bool = True)#
Get the contig from the FASTA file. The contig is looked up in the header index and read by seeking to it, so the sites may visit the contigs in any order at the same cost.
Note that
pyfaidxwould be more efficient here, but there were problems when running it in parallel.- Parameters:
- Return type:
SeqRecord- Returns:
The contig.
- Raises:
LookupError – Where the FASTA carries none of the aliases.
- get_contig_names()#
Get the names of the contigs in the FASTA file.
- static get_filename(url: str)#
Return the file extension of a URL.
- Parameters:
url (
str) – The URL to get the file extension from.- Returns:
The file extension.
- get_pbar(desc: str = 'Processing sites', total: int | None = 0)#
Return a progress bar for the number of sites.
- load_fasta(file: str)#
Load a FASTA file into a dictionary.
- Parameters:
file (
str) – The path to The FASTA file path, possibly gzipped or a URL- Return type:
FastaIterator- Returns:
Iterator over the sequences.
- load_vcf()#
Open a VCF file for streaming.
- Return type:
cyvcf2.VCF
- Returns:
The VCF reader.
- static remove_overlaps(df: DataFrame)#
Remove overlapping coding sequences.
- Parameters:
df (
DataFrame) – The coding sequences.- Return type:
DataFrame- Returns:
The coding sequences without overlaps.
- static unzip_if_zipped(file: str)#
If the given file is gzipped, unzip it and return the path to the unzipped file. If the file is not gzipped, return the path to the original file.
- Parameters:
file (
str) – The path to the file.- Returns:
The path to the unzipped file, or the original file if it was not gzipped.
- vcf#
The variant source (a path or a tskit TreeSequence object)
- rng#
Random generator instance
- gff#
The GFF file path
- aliases#
The contig mappings
Filtration#
MaskedFiltration#
- class MaskedFiltration(use_parser: bool = True, include_samples: List[str] | None = None, exclude_samples: List[str] | None = None)[source]#
Bases:
Filtration,ABCFilter sites based on a samples mask, where
Noneselects every sample.Where the input carries no samples at all, as a sites-only VCF or store does, the verdict is taken from the declared alleles, with one warning on setup.
Methods:
Create a new filtration instance.
Filter site.
- __init__(use_parser: bool = True, include_samples: List[str] | None = None, exclude_samples: List[str] | None = None)[source]#
Create a new filtration instance.
SNPFiltration#
- class SNPFiltration(use_parser: bool = True, include_samples: List[str] | None = None, exclude_samples: List[str] | None = None)[source]#
Bases:
MaskedFiltrationOnly keep SNPs. Note that this entails discarding mono-morphic sites, monomorphism being judged from the alleles the included samples actually carry rather than from the
ALTfield.Methods:
Filter site.
Create a new filtration instance.
- filter_site(variant: Site)[source]#
Filter site.
- Parameters:
variant (
Site) – The variant to filter.- Return type:
- Returns:
Trueif the variant is an SNP that is polymorphic among the included samples,Falseotherwise. Poly-allelic SNPs are retained; usePolyAllelicFiltrationto drop those.
SNVFiltration#
PolyAllelicFiltration#
- class PolyAllelicFiltration(use_parser: bool = True, include_samples: List[str] | None = None, exclude_samples: List[str] | None = None)[source]#
Bases:
MaskedFiltrationFilter out poly-allelic sites.
Methods:
Filter site.
Create a new filtration instance.
- filter_site(variant: Site)[source]#
Filter site. A site is poly-allelic where three or more distinct alleles are called among the included samples, which are all of them unless
include_samples/exclude_samplesor a parser’s populations restrict them. An alternate allele that theALTfield declares but no included sample carries therefore does not make a site poly-allelic.
AllFiltration#
NoFiltration#
CodingSequenceFiltration#
- class CodingSequenceFiltration[source]#
Bases:
FiltrationFilter out sites that are not in coding sequences. This filter should find frequent use when parsing spectra for which only sites in coding sequences should be considered. By using it, the annotation and parsing of unnecessary sites can be avoided which increases the speed. Note that we assume here that within contigs, sites in the GFF file are sorted by position in ascending order.
For this filtration to work, we require a GFF file (passed to
ParserorFilterer).Methods:
Create a new filtration instance.
Filter site by whether it is in a coding sequence.
DeviantOutgroupFiltration#
- class DeviantOutgroupFiltration(outgroups: List[str], ingroups: List[str] = None, strict_mode: bool = True, retain_monomorphic: bool = True)[source]#
Bases:
FiltrationFilter out sites where the major allele of the specified outgroup samples differs from the major allele of the ingroup samples.
Methods:
Construct DeviantOutgroupFiltration.
Filter site.
- __init__(outgroups: List[str], ingroups: List[str] = None, strict_mode: bool = True, retain_monomorphic: bool = True)[source]#
Construct DeviantOutgroupFiltration.
- Parameters:
outgroups (
List[str]) – The name of the outgroup samples to consider.ingroups (
List[str]) – The name of the ingroup samples to consider, defaults to all samples but the outgroups.strict_mode (
bool) – Whether to filter out sites where no outgroup sample is present, defaults toTrue.retain_monomorphic (
bool) – Whether to retain monomorphic sites, defaults toTrue, which is faster.
ExistingOutgroupFiltration#
- class ExistingOutgroupFiltration(outgroups: List[str], n_missing: int = 1)[source]#
Bases:
FiltrationFilter out sites for which at least
n_missingof the specified outgroup samples have no called base.Methods:
Construct ExistingOutgroupFiltration.
Filter site.
BiasedGCConversionFiltration#
- class BiasedGCConversionFiltration[source]#
Bases:
FiltrationOnly retain A<->T and G<->C substitutions (which are unaffected by biased gene conversion, see [CITGB]).
Mono-allelic sites are always retained, and we assume sites are at most bi-allelic. Note that the number of mutational target sites is reduced by this filtration.
Methods:
Remove bi-allelic sites that are not A<->T or G<->C mutations.
Initialize filtration.
- __init__()#
Initialize filtration.
CpGFiltration#
- class CpGFiltration[source]#
Bases:
FiltrationFilter out sites whose reference base is in a CpG dinucleotide context. CpG sites are hypermutable (the cytosine is prone to deamination), so they are commonly excluded to avoid mutation-rate heterogeneity. A site is in CpG context iff:
the reference base is
Cand the next base on the same strand isG, orthe reference base is
Gand the previous base on the same strand isC.
Like
CodingSequenceFiltration, this filtration requires a FASTA reference (passed toParserorFilterer), which is used for the±1base lookup. Sites on a contig the FASTA carries no sequence for, and sites the FASTA sequence does not reach, cannot be typed and are kept, with one warning per contig.Methods:
Create a new filtration instance.
Filter site by whether its reference base is in a CpG context.