varlens.read_evidence package

Submodules

varlens.read_evidence.pileup module

class varlens.read_evidence.pileup.Pileup(locus, elements)[source]

Bases: object

A Pileup is a collection of PileupElement instances at a particular locus.

Attributes:
locusVarcode.Locus

The reference locus. Must be length 1, i.e. a single base.

elementsOrderedDict of PileupElement instances

This is logically and ordered set, which we implement as an OrderedDict with all values mapping to None.

append(element)[source]

Append a PileupElement to this Pileup. If an identical PileupElement is already part of this Pileup, do nothing.

filter(filters)[source]

Apply filters to the pileup elements, and return a new Pileup with the filtered elements removed.

Parameters:
filterslist of PileupElement -> bool callables

A PileupUp element is retained if all filters return True when called on it.

update(other)[source]

Add all pileup elements from other into self.

varlens.read_evidence.pileup_collection module

class varlens.read_evidence.pileup_collection.MatchingEvidence(ref, alt, other)

Bases: tuple

alt

Alias for field number 1

other

Alias for field number 2

ref

Alias for field number 0

class varlens.read_evidence.pileup_collection.PileupCollection(pileups=None, parent=None, normalized_contig_names=True)[source]

Bases: object

A collection of Pileup instances for some loci.

Attributes:
pileups (optional)dict of Locus -> Pileup

A map from 1-base Locus instances to the Pileup at that locus.

parent (optional)PileupCollection

For PileupCollection instances that are derived (e.g. by filtering) from another instance, this attribute tracks the parent instance.

normalized_contig_names (optional)bool

Allow normalized aliases when looking up loci. Derived collections inherit this setting from their parent.

allele_summary(locus, score=<function PileupCollection.<lambda>>)[source]

Convenience method to summarize the evidence for each of the alleles present at a locus. Applies a score function to the PileupCollection associated with each allele.

See also PileupCollection.group_by_allele.

Parameters:
locusLocus

The reference locus, encompassing 0 or more bases.

score (optional)PileupCollection -> object

Function to apply to summarize the evidence for each allele. Default: count number of reads.

Returns:
List of (allele, score) pairs.
at(*loci)[source]

Return a new PileupCollection instance including only pileups for the specified loci.

filter(drop_duplicates=False, drop_improper_mate_pairs=False, min_mapping_quality=None, min_base_quality=None, filters=None)[source]

Return a new PileupCollection that includes only pileup elements satisfying the specified criteria.

Parameters:
drop_duplicates (optional, default False)boolean

Remove alignments with the is_duplicate flag.

drop_improper_mate_pairs (optional, default False)boolean

Retain only alignments that have mapped mate pairs, where one alignment in the pair is on the forward strand and the other is on the reverse.

min_mapping_quality (optional)int

If specified, retain only alignments with mapping quality >= the specified threshold.

min_base_quality (optional)int

If specified, retain only pileup elements where the base quality for the bases aligning to the pileup’s locus are >= the specified threshold.

filters (optional)list of PileupElement -> bool functions

User-specified filter functions to apply. This will be called on each PileupElement, and should return True if the element should be retained.

Returns:
A new PileupCollection that includes the subset of the pileup elements
matching all the specified filters.
static from_bam(pysam_samfile, loci, normalized_contig_names=True)[source]

Create a PileupCollection for a set of loci from a BAM file.

Parameters:
pysam_samfilepysam.Samfile instance, or filename string

to a BAM file. The BAM file must be indexed.

locilist of Locus instances

Loci to collect pileups for.

normalized_contig_namesbool

If true, normalize contig names and map aliases to BAM references. If false, preserve the supplied Locus contig names exactly.

Returns:
PileupCollection instance containing pileups for the specified loci.
All alignments in the BAM file are included (e.g. duplicate reads,
secondary alignments, etc.). See PileupCollection.filter if these
need to be removed.
group_by_allele(locus)[source]

Split the PileupCollection by the alleles suggested by the reads at the specified locus.

If a read has an insertion immediately following the locus, then the insertion is included in the allele. For example, if locus is the 1-base range [5,6), one allele might be “AGA”, indicating that at locus 5 some read has an “A” followed by a 2-base insertion (“GA”). If a read has a deletion at the specified locus, the allele is the empty string.

The given locus may include any number of bases. If the locus includes multiple bases, then the alleles consist of all bases aligning to that range in any read. Note that only sequences actually sequenced in a particular read are included. For example, if one read has “ATT” at a locus and another read has “GCC”, then the alleles are “ATT” and “GCC”, but not “GTT”. That is, the bases in each allele are phased. For this reason, only reads that overlap the entire locus are included.

If the locus is an empty interval (e.g. [5,5) ), then the alleles consist only of inserted bases. In this example, only bases inserted between reference positions 4 and 5 (zero-based) would be included. An insertion after position 5 uses [6,6). In the previous example, the allele would be “GA”, indicating a 2-base insertion. Reads that have no insertion at that position (matches or deletions) would have the empty string as their allele.

Parameters:
locusLocus

The reference locus, encompassing 0 or more bases.

Returns:
A dict of string -> PileupCollection. The keys are nucleotide strings
giving the bases sequenced at the locus, and the values are
PileupCollection instances of the alignments that support that allele.
group_by_match(variant)[source]

Given a variant, split the PileupCollection based on whether it the data supports the reference allele, the alternate allele, or neither.

Parameters:
variantVariant

The variant. Must have fields ‘locus’, ‘ref’, and ‘alt’.

Returns:
A MatchingEvidence named tuple with fields (ref, alt, other),
each of which is a string -> PileupCollection dict mapping alleles
to the PileupCollection of evidence supporting them.
line = '        '
loci()[source]

Returns the loci included in this instance.

match = None
match_summary(variant, score=<function PileupCollection.<lambda>>)[source]

Convenience method to summarize the evidence for and against a variant using a user-specified score function.

See also PileupCollection.group_by_match.

Parameters:
variantVariant

The variant. Must have fields ‘locus’, ‘ref’, and ‘alt’.

score (optional)PileupCollection -> object

Function to apply to summarize the evidence for each allele. Default: count number of reads.

Returns:
List of (allele, score) pairs. This list will always have at least two
elements. The first pair in the list is the reference allele. The
second pair is the alternate. The subsequent items give the “third”
alleles (neither ref nor alt), if any.
merge(*others)[source]

Return a new PileupCollection that is the union of self and the other specified collections.

num_reads()[source]

Returns the number of reads in this PileupCollection.

pileup(locus)[source]

Given a 1-base locus, return the Pileup at that locus.

Raises a KeyError if this PileupCollection does not have a Pileup at the specified locus.

read_attribute(attribute)[source]

Query a read attribute across all reads in this PileupCollection.

Parameters:
attributestring

Attribute to query. See PileupCollection.read_attributes for possible attributes.

Returns:
pandas.Series instance giving values for the attribute in each read.
The order of reads is fixed, so multiple calls to this function will
return corresponding values.
read_attributes(attributes=None)[source]

Collect read attributes across reads in this PileupCollection into a pandas.DataFrame.

Valid attributes are the following properties of a pysam.AlignedSegment instance. See the pysam API documentation for their meanings.

  • cigarstring

  • flag

  • inferred_length

  • is_duplicate

  • is_paired

  • is_proper_pair

  • is_qcfail

  • is_read1

  • is_read2

  • is_reverse

  • is_secondary

  • is_unmapped

  • mapping_quality

  • mate_is_reverse

  • mate_is_unmapped

  • next_reference_id

  • next_reference_start

  • query_alignment_end

  • query_alignment_length

  • query_alignment_qualities

  • query_alignment_sequence

  • query_alignment_start

  • query_length

  • query_name

  • reference_end

  • reference_id

  • reference_length

  • reference_start

  • template_length

(Note: the above list is parsed into the _READ_ATTRIBUTE_NAMES class variable, so be careful when modifying it.)

Additionally, for alignment “tags” (arbitrary key values associated with an alignment), a column of the form “TAG_{tag name}” is included.

Finally, the column “pysam_alignment_record” gives the underlying pysam.AlignedSegment instances.

Parameters:
attributes (optional): list of strings

List of columns to include. If unspecified, all columns are included in the result.

Returns:
pandas.DataFrame of read attributes.
reads()[source]

The reads in this PileupCollection. All reads will have an alignment that overlaps at least one of the included loci.

Since SAM (and pysam) have no real notion of a “read”, the returned instances are actually pysam.AlignedSegment instances, (i.e. alignments). However, only one alignment will be returned by this method per read.

Returns:
List of pysam.AlignedSegment instances. If a particular read has more
than one alignment in this PileupCollection (e.g. one primary and one
secondary), then the alignment returned is the one with the highest
mapping quality.
varlens.read_evidence.pileup_collection.to_locus(variant_or_locus)[source]

Return the half-open reference interval for a Variant or Locus.

Varcode substitutions and deletions use inclusive one-based coordinates. Its insertions have an empty reference allele and are anchored at the preceding one-based base; their interbase interval is [start, start).

varlens.read_evidence.pileup_element module

class varlens.read_evidence.pileup_element.PileupElement(locus, offset_start, offset_end, alignment)[source]

Bases: object

A PileupElement represents the segment of an alignment that aligns to a particular base in the reference.

Attributes:
locusVarcode.Locus

The reference locus. Must be length 1, i.e. a single base.

offset_startint

0-based start offset into the alignment sequence, inclusive

offset_endint

0-based end offset into the alignment sequence, exclusive

alignmentpysam.AlignedSegment

pysam alignment instance

alignment_keytuple

value computed from the alignment instance that uniquely specifies its properties. Used for comparisons since pysam.AlignedSegment instances do not support a useful notion of equality (they compare using object identity). See read_evidence.alignment_key for the implementation of this key.

property base_qualities

The phred-scaled base quality scores corresponding to self.bases, as a list.

property bases

The sequenced bases in the alignment that align to this locus in the genome, as a string.

Empty string in the case of a deletion. String of length > 1 if there is an insertion here.

fields()[source]

Fields that should be considered for our notion of object equality.

static from_pysam_alignment(locus, pileup_read)[source]

Factory function to create a new PileupElement from a pysam PileupRead.

Parameters:
locusvarcode.Locus

Reference locus for which to construct a PileupElement. Must include exactly one base.

pileup_readpysam.calignmentfile.PileupRead

pysam PileupRead instance. Its alignment must overlap the locus.

Returns:
PileupElement
property min_base_quality

The minimum of the base qualities. In the case of a deletion, in which case there are no bases in this PileupElement, the minimum is taken over the sequenced bases immediately before and after the deletion.

varlens.read_evidence.util module

varlens.read_evidence.util.alignment_key(pysam_alignment_record)[source]

Return the identifying attributes of a pysam.AlignedSegment instance. This is necessary since these objects do not support a useful notion of equality (they compare on identify by default).

varlens.read_evidence.util.read_key(pysam_alignment_record)[source]

Given a pysam.AlignedSegment instance, return the attributes identifying the read it comes from (not the alignment). There may be more than one alignment for a read, e.g. chimeric and secondary alignments.

Module contents

This subpackage provides functionality for collecting and filtering aligned sequencing reads from a BAM file, determining the alleles they suggest at a locus, and assesing the evidence for particular variants.

In this subpackage, the records stored in the BAM file are referred to as “alignments,” whereas the term “read” may be more familiar. We use the term “alignment” for consistency with the SAM specification, and since an individual read from the sequencer may generate any number of alignments in the case of chimeric alignments and secondary alignments.

class varlens.read_evidence.Pileup(locus, elements)[source]

Bases: object

A Pileup is a collection of PileupElement instances at a particular locus.

Attributes:
locusVarcode.Locus

The reference locus. Must be length 1, i.e. a single base.

elementsOrderedDict of PileupElement instances

This is logically and ordered set, which we implement as an OrderedDict with all values mapping to None.

append(element)[source]

Append a PileupElement to this Pileup. If an identical PileupElement is already part of this Pileup, do nothing.

filter(filters)[source]

Apply filters to the pileup elements, and return a new Pileup with the filtered elements removed.

Parameters:
filterslist of PileupElement -> bool callables

A PileupUp element is retained if all filters return True when called on it.

update(other)[source]

Add all pileup elements from other into self.

class varlens.read_evidence.PileupCollection(pileups=None, parent=None, normalized_contig_names=True)[source]

Bases: object

A collection of Pileup instances for some loci.

Attributes:
pileups (optional)dict of Locus -> Pileup

A map from 1-base Locus instances to the Pileup at that locus.

parent (optional)PileupCollection

For PileupCollection instances that are derived (e.g. by filtering) from another instance, this attribute tracks the parent instance.

normalized_contig_names (optional)bool

Allow normalized aliases when looking up loci. Derived collections inherit this setting from their parent.

allele_summary(locus, score=<function PileupCollection.<lambda>>)[source]

Convenience method to summarize the evidence for each of the alleles present at a locus. Applies a score function to the PileupCollection associated with each allele.

See also PileupCollection.group_by_allele.

Parameters:
locusLocus

The reference locus, encompassing 0 or more bases.

score (optional)PileupCollection -> object

Function to apply to summarize the evidence for each allele. Default: count number of reads.

Returns:
List of (allele, score) pairs.
at(*loci)[source]

Return a new PileupCollection instance including only pileups for the specified loci.

filter(drop_duplicates=False, drop_improper_mate_pairs=False, min_mapping_quality=None, min_base_quality=None, filters=None)[source]

Return a new PileupCollection that includes only pileup elements satisfying the specified criteria.

Parameters:
drop_duplicates (optional, default False)boolean

Remove alignments with the is_duplicate flag.

drop_improper_mate_pairs (optional, default False)boolean

Retain only alignments that have mapped mate pairs, where one alignment in the pair is on the forward strand and the other is on the reverse.

min_mapping_quality (optional)int

If specified, retain only alignments with mapping quality >= the specified threshold.

min_base_quality (optional)int

If specified, retain only pileup elements where the base quality for the bases aligning to the pileup’s locus are >= the specified threshold.

filters (optional)list of PileupElement -> bool functions

User-specified filter functions to apply. This will be called on each PileupElement, and should return True if the element should be retained.

Returns:
A new PileupCollection that includes the subset of the pileup elements
matching all the specified filters.
static from_bam(pysam_samfile, loci, normalized_contig_names=True)[source]

Create a PileupCollection for a set of loci from a BAM file.

Parameters:
pysam_samfilepysam.Samfile instance, or filename string

to a BAM file. The BAM file must be indexed.

locilist of Locus instances

Loci to collect pileups for.

normalized_contig_namesbool

If true, normalize contig names and map aliases to BAM references. If false, preserve the supplied Locus contig names exactly.

Returns:
PileupCollection instance containing pileups for the specified loci.
All alignments in the BAM file are included (e.g. duplicate reads,
secondary alignments, etc.). See PileupCollection.filter if these
need to be removed.
group_by_allele(locus)[source]

Split the PileupCollection by the alleles suggested by the reads at the specified locus.

If a read has an insertion immediately following the locus, then the insertion is included in the allele. For example, if locus is the 1-base range [5,6), one allele might be “AGA”, indicating that at locus 5 some read has an “A” followed by a 2-base insertion (“GA”). If a read has a deletion at the specified locus, the allele is the empty string.

The given locus may include any number of bases. If the locus includes multiple bases, then the alleles consist of all bases aligning to that range in any read. Note that only sequences actually sequenced in a particular read are included. For example, if one read has “ATT” at a locus and another read has “GCC”, then the alleles are “ATT” and “GCC”, but not “GTT”. That is, the bases in each allele are phased. For this reason, only reads that overlap the entire locus are included.

If the locus is an empty interval (e.g. [5,5) ), then the alleles consist only of inserted bases. In this example, only bases inserted between reference positions 4 and 5 (zero-based) would be included. An insertion after position 5 uses [6,6). In the previous example, the allele would be “GA”, indicating a 2-base insertion. Reads that have no insertion at that position (matches or deletions) would have the empty string as their allele.

Parameters:
locusLocus

The reference locus, encompassing 0 or more bases.

Returns:
A dict of string -> PileupCollection. The keys are nucleotide strings
giving the bases sequenced at the locus, and the values are
PileupCollection instances of the alignments that support that allele.
group_by_match(variant)[source]

Given a variant, split the PileupCollection based on whether it the data supports the reference allele, the alternate allele, or neither.

Parameters:
variantVariant

The variant. Must have fields ‘locus’, ‘ref’, and ‘alt’.

Returns:
A MatchingEvidence named tuple with fields (ref, alt, other),
each of which is a string -> PileupCollection dict mapping alleles
to the PileupCollection of evidence supporting them.
line = '        '
loci()[source]

Returns the loci included in this instance.

match = None
match_summary(variant, score=<function PileupCollection.<lambda>>)[source]

Convenience method to summarize the evidence for and against a variant using a user-specified score function.

See also PileupCollection.group_by_match.

Parameters:
variantVariant

The variant. Must have fields ‘locus’, ‘ref’, and ‘alt’.

score (optional)PileupCollection -> object

Function to apply to summarize the evidence for each allele. Default: count number of reads.

Returns:
List of (allele, score) pairs. This list will always have at least two
elements. The first pair in the list is the reference allele. The
second pair is the alternate. The subsequent items give the “third”
alleles (neither ref nor alt), if any.
merge(*others)[source]

Return a new PileupCollection that is the union of self and the other specified collections.

num_reads()[source]

Returns the number of reads in this PileupCollection.

pileup(locus)[source]

Given a 1-base locus, return the Pileup at that locus.

Raises a KeyError if this PileupCollection does not have a Pileup at the specified locus.

read_attribute(attribute)[source]

Query a read attribute across all reads in this PileupCollection.

Parameters:
attributestring

Attribute to query. See PileupCollection.read_attributes for possible attributes.

Returns:
pandas.Series instance giving values for the attribute in each read.
The order of reads is fixed, so multiple calls to this function will
return corresponding values.
read_attributes(attributes=None)[source]

Collect read attributes across reads in this PileupCollection into a pandas.DataFrame.

Valid attributes are the following properties of a pysam.AlignedSegment instance. See the pysam API documentation for their meanings.

  • cigarstring

  • flag

  • inferred_length

  • is_duplicate

  • is_paired

  • is_proper_pair

  • is_qcfail

  • is_read1

  • is_read2

  • is_reverse

  • is_secondary

  • is_unmapped

  • mapping_quality

  • mate_is_reverse

  • mate_is_unmapped

  • next_reference_id

  • next_reference_start

  • query_alignment_end

  • query_alignment_length

  • query_alignment_qualities

  • query_alignment_sequence

  • query_alignment_start

  • query_length

  • query_name

  • reference_end

  • reference_id

  • reference_length

  • reference_start

  • template_length

(Note: the above list is parsed into the _READ_ATTRIBUTE_NAMES class variable, so be careful when modifying it.)

Additionally, for alignment “tags” (arbitrary key values associated with an alignment), a column of the form “TAG_{tag name}” is included.

Finally, the column “pysam_alignment_record” gives the underlying pysam.AlignedSegment instances.

Parameters:
attributes (optional): list of strings

List of columns to include. If unspecified, all columns are included in the result.

Returns:
pandas.DataFrame of read attributes.
reads()[source]

The reads in this PileupCollection. All reads will have an alignment that overlaps at least one of the included loci.

Since SAM (and pysam) have no real notion of a “read”, the returned instances are actually pysam.AlignedSegment instances, (i.e. alignments). However, only one alignment will be returned by this method per read.

Returns:
List of pysam.AlignedSegment instances. If a particular read has more
than one alignment in this PileupCollection (e.g. one primary and one
secondary), then the alignment returned is the one with the highest
mapping quality.
class varlens.read_evidence.PileupElement(locus, offset_start, offset_end, alignment)[source]

Bases: object

A PileupElement represents the segment of an alignment that aligns to a particular base in the reference.

Attributes:
locusVarcode.Locus

The reference locus. Must be length 1, i.e. a single base.

offset_startint

0-based start offset into the alignment sequence, inclusive

offset_endint

0-based end offset into the alignment sequence, exclusive

alignmentpysam.AlignedSegment

pysam alignment instance

alignment_keytuple

value computed from the alignment instance that uniquely specifies its properties. Used for comparisons since pysam.AlignedSegment instances do not support a useful notion of equality (they compare using object identity). See read_evidence.alignment_key for the implementation of this key.

property base_qualities

The phred-scaled base quality scores corresponding to self.bases, as a list.

property bases

The sequenced bases in the alignment that align to this locus in the genome, as a string.

Empty string in the case of a deletion. String of length > 1 if there is an insertion here.

fields()[source]

Fields that should be considered for our notion of object equality.

static from_pysam_alignment(locus, pileup_read)[source]

Factory function to create a new PileupElement from a pysam PileupRead.

Parameters:
locusvarcode.Locus

Reference locus for which to construct a PileupElement. Must include exactly one base.

pileup_readpysam.calignmentfile.PileupRead

pysam PileupRead instance. Its alignment must overlap the locus.

Returns:
PileupElement
property min_base_quality

The minimum of the base qualities. In the case of a deletion, in which case there are no bases in this PileupElement, the minimum is taken over the sequenced bases immediately before and after the deletion.

varlens.read_evidence.alignment_key(pysam_alignment_record)[source]

Return the identifying attributes of a pysam.AlignedSegment instance. This is necessary since these objects do not support a useful notion of equality (they compare on identify by default).

varlens.read_evidence.read_key(pysam_alignment_record)[source]

Given a pysam.AlignedSegment instance, return the attributes identifying the read it comes from (not the alignment). There may be more than one alignment for a read, e.g. chimeric and secondary alignments.