core.sequence.ProteinSequence

core.sequence.ProteinSequence(
    moltype,
    seq,
    *,
    name=None,
    info=None,
    annotation_offset=0,
    annotation_db=None,
)

Holds the standard Protein sequence.

Attributes

Name Description
annotation_db the annotation database for the collection
annotation_offset The offset between annotation coordinates and sequence coordinates.

Methods

Name Description
add_feature add a feature to annotation_db
annotate_matches_to Adds an annotation at sequence positions matching pattern.
can_match Returns True if every pos in self could match same pos in other.
copy returns a copy of self
copy_annotations copy annotations into attached annotation db
count count() delegates to self._seq.
count_ambiguous Returns the number of ambiguous characters in the sequence.
count_degenerate Counts the degenerate bases in the specified sequence.
count_gaps Counts the gaps in the specified sequence.
count_kmers return array of counts of all possible kmers of length k
count_variants Counts number of possible sequences matching the sequence, given
counts returns dict of counts of motifs
degap Deletes all gap characters from sequence.
diff Returns number of differences between self and other.
disambiguate Returns a non-degenerate sequence from a degenerate one.
distance Returns distance between self and other using function(i,j).
frac_diff Returns fraction of positions where self and other differ.
frac_diff_gaps Returns frac. of positions where self and other’s gap states differ.
frac_diff_non_gaps Returns fraction of non-gap positions where self differs from other.
frac_same Returns fraction of positions where self and other are the same.
frac_same_gaps Returns fraction of positions where self and other share gap states.
frac_same_non_gaps Returns fraction of non-gap positions where self matches other.
frac_similar Returns fraction of positions where self[i] is similar to other[i].
from_rich_dict create a Sequence object from a rich dict
gap_indices Returns array of the indices of all gaps in the sequence
gap_vector Returns vector of True or False according to which pos are gaps or missing.
get_drawable make a figure from sequence features
get_drawables returns a dict of drawables, keyed by type
get_features yields Feature instances
get_in_motif_size returns sequence as list of non-overlapping motifs
get_kmers return all overlapping k-mers
get_name Return the sequence name – should just use name instead.
get_type Return the sequence type as moltype label.
has_annotation_db returns True if self has annotation db
is_annotated returns True if sequence parent name has any annotations
is_degenerate Returns True if sequence contains degenerate characters.
is_gapped Returns True if sequence contains gaps.
is_strict Returns True if sequence contains only monomers.
is_valid Returns True if sequence contains no items absent from alphabet.
iter_kmers generates all overlapping k-mers.
make_feature return an Feature instance from feature data
matrix_distance Returns distance between self and other using a score matrix.
mw Returns the molecular weight of (one strand of) the sequence.
parent_coordinates returns seqid, start, stop, strand of this sequence on its parent
parse_out_gaps returns Map corresponding to gap locations and ungapped Sequence
replace_annotation_db public interface to assigning the annotation_db
resolved_ambiguities Returns a list of sets of strings.
sample Returns random sample of positions from self, e.g. to bootstrap.
shuffle returns a randomized copy of the Sequence object
sliding_windows Generator function that yield new sequence objects
strip_bad Removes any symbols not in the alphabet.
strip_bad_and_gaps Removes any symbols not in the alphabet, and any gaps. As the missing
strip_degenerate Removes degenerate bases by stripping them out of the sequence.
to_array returns the numpy array
to_fasta Return string of self in FASTA format, no trailing newline
to_html returns html with embedded styles for sequence colouring
to_json returns a json formatted string
to_moltype returns copy of self with moltype seq
to_phylip Return string of self in one line for PHYLIP, no newline.
to_rich_dict returns {‘name’: name, ‘seq’: sequence, ‘moltype’: moltype.label}
with_masked_annotations returns a sequence with annot_types regions replaced by mask_char
with_termini_unknown Returns copy of sequence with terminal gaps remapped as missing.
write Write the sequence to a file.

add_feature

core.sequence.ProteinSequence.add_feature(
    biotype,
    name,
    spans,
    parent_id=None,
    strand=None,
    on_alignment=False,
    seqid=None,
)

add a feature to annotation_db

Parameters

Name Type Description Default
biotype str biological type required
name str name of the feature required
spans list[tuple[int, int]] coordinates for this sequence required
parent_id str | None name of the feature parent None
strand str | None ‘+’ or ‘-’, defaults to ‘+’ None
on_alignment bool whether the feature spans are alignment coordinates False
seqid str | None ignored since the feature is added to this sequence None

Returns

Name Type Description
Feature instance

annotate_matches_to

core.sequence.ProteinSequence.annotate_matches_to(
    pattern,
    biotype,
    name,
    allow_multiple=False,
)

Adds an annotation at sequence positions matching pattern.

Parameters

Name Type Description Default
pattern str The search string for which annotations are made. IUPAC ambiguities are converted to regex on sequences with the appropriate MolType. required
biotype str The type of the annotation (e.g. “domain”). required
name str The name of the annotation. required
allow_multiple bool If True, allows multiple occurrences of the input pattern. Otherwise, only the first match is used. False

Returns

Name Type Description
Returns a list of Feature instances.

can_match

core.sequence.ProteinSequence.can_match(other)

Returns True if every pos in self could match same pos in other.

Truncates at length of shorter sequence. gaps are only allowed to match other gaps.

copy

core.sequence.ProteinSequence.copy(exclude_annotations=False, sliced=True)

returns a copy of self

Parameters

Name Type Description Default
sliced bool Slices underlying sequence with start/end of self coordinates. The offset is retained. True
exclude_annotations bool drops annotation_db when True False

copy_annotations

core.sequence.ProteinSequence.copy_annotations(seq_db)

copy annotations into attached annotation db

Parameters

Name Type Description Default
seq_db AnnotationDbABC compatible annotation db required

Notes

Only copies annotations for records with seqid equal to self.name

count

core.sequence.ProteinSequence.count(item)

count() delegates to self._seq.

count_ambiguous

core.sequence.ProteinSequence.count_ambiguous()

Returns the number of ambiguous characters in the sequence.

count_degenerate

core.sequence.ProteinSequence.count_degenerate()

Counts the degenerate bases in the specified sequence.

Notes

gap and missing characters are counted as degenerate.

count_gaps

core.sequence.ProteinSequence.count_gaps()

Counts the gaps in the specified sequence.

count_kmers

core.sequence.ProteinSequence.count_kmers(k=1, use_hook=None, **kwargs)

return array of counts of all possible kmers of length k

Parameters

Name Type Description Default
k int length of kmers to count 1
use_hook str | None name of a third-party package that implements the quick_tree hook. If not specified, defaults to the first available hook or the cogent3 quick_tree() app. To force default, set use_hook=“cogent3”. None
**kwargs additional arguments to pass to the hook app constructor {}

Notes

Only states in moltype.alphabet are allowed in a kmer (the canonical states). If using cogent3, to get the order of kmers as strings, use self.moltype.alphabet.get_kmer_alphabet(k). See the documentation for details of any third-party hooks.

count_variants

core.sequence.ProteinSequence.count_variants()

Counts number of possible sequences matching the sequence, given any ambiguous characters in the sequence.

Notes

Uses self.ambiguitues to decide how many possibilities there are at each position in the sequence and calculates the permutations.

counts

core.sequence.ProteinSequence.counts(
    motif_length=1,
    include_ambiguity=False,
    allow_gap=False,
    warn=False,
)

returns dict of counts of motifs

only non-overlapping motifs are counted.

Parameters

Name Type Description Default
motif_length int number of elements per character. 1
include_ambiguity bool if True, motifs containing ambiguous characters from the seq moltype are included. No expansion of those is attempted. False
allow_gaps if True, motifs containing a gap character are included. required
warn bool warns if motif_length > 1 and alignment trimmed to produce motif columns False

degap

core.sequence.ProteinSequence.degap()

Deletes all gap characters from sequence.

diff

core.sequence.ProteinSequence.diff(other)

Returns number of differences between self and other.

Notes

Truncates at the length of the shorter sequence.

disambiguate

core.sequence.ProteinSequence.disambiguate(method='strip')

Returns a non-degenerate sequence from a degenerate one.

Parameters

Name Type Description Default
seq the sequence to be disambiguated required
method str how to disambiguate the sequence, one of “strip”, “random” strip: deletes any characters not in monomers or gaps random: assigns the possibilities at random, using equal frequencies 'strip'

distance

core.sequence.ProteinSequence.distance(other, function=None)

Returns distance between self and other using function(i,j).

Parameters

Name Type Description Default
other Self a sequence to compare to self required
function Callable[[str, str], float] | None takes two seq residues and returns a number. To turn a 2D matrix into a function, use cogent3.util.miscs.DistanceFromMatrix(matrix). None

Notes

Truncates at the length of the shorter sequence.

The function acts on two elements of the sequences, not the two sequences themselves (i.e. the behavior will be the same for every position in the sequences, such as identity scoring or a function derived from a distance matrix as suggested above). One limitation of this approach is that the distance function cannot use properties of the sequences themselves: for example, it cannot use the lengths of the sequences to normalize the scores as percent similarities or percent differences.

If you want functions that act on the two sequences themselves, there is no particular advantage in making these functions methods of the first sequences by passing them in as parameters like the function in this method. It makes more sense to use them as standalone functions. The factory function cogent3.util.transform.for_seq is useful for converting per-element functions into per-sequence functions, since it takes as parameters a per-element scoring function, a score aggregation function, and a normalization function (which itself takes the two sequences as parameters), returning a single function that combines these functions and that acts on two complete sequences.

frac_diff

core.sequence.ProteinSequence.frac_diff(other)

Returns fraction of positions where self and other differ.

Notes

Truncates at length of shorter sequence. Will return 0 if one sequence is empty.

frac_diff_gaps

core.sequence.ProteinSequence.frac_diff_gaps(other)

Returns frac. of positions where self and other’s gap states differ.

In other words, if self and other are both all gaps, or both all non-gaps, or both have gaps in the same places, frac_diff_gaps will return 0.0. If self is all gaps and other has no gaps, frac_diff_gaps will return 1.0.

Returns 0 if one sequence is empty.

Uses self’s gap characters for both sequences.

frac_diff_non_gaps

core.sequence.ProteinSequence.frac_diff_non_gaps(other)

Returns fraction of non-gap positions where self differs from other.

Doesn’t count any position where self or other has a gap. Truncates at the length of the shorter sequence.

Returns 0 if one sequence is empty. Note that this means that frac_diff_non_gaps is not the same as 1 - frac_same_non_gaps, since both return 0 if one sequence is empty.

frac_same

core.sequence.ProteinSequence.frac_same(other)

Returns fraction of positions where self and other are the same.

Notes

Truncates at length of shorter sequence. Will return 0 if one sequence is empty.

frac_same_gaps

core.sequence.ProteinSequence.frac_same_gaps(other)

Returns fraction of positions where self and other share gap states.

In other words, if self and other are both all gaps, or both all non-gaps, or both have gaps in the same places, frac_same_gaps will return 1.0. If self is all gaps and other has no gaps, frac_same_gaps will return 0.0. Returns 0 if one sequence is empty.

Uses self’s gap characters for both sequences.

frac_same_non_gaps

core.sequence.ProteinSequence.frac_same_non_gaps(other)

Returns fraction of non-gap positions where self matches other.

Doesn’t count any position where self or other has a gap. Truncates at the length of the shorter sequence.

Returns 0 if one sequence is empty.

frac_similar

core.sequence.ProteinSequence.frac_similar(other, similar_pairs)

Returns fraction of positions where self[i] is similar to other[i].

similar_pairs must be a dict such that d[(i,j)] exists if i and j are to be counted as similar. Use PairsFromGroups in cogent3.util.misc to construct such a dict from a list of lists of similar residues.

Truncates at the length of the shorter sequence.

Note: current implementation re-creates the distance function each time, so may be expensive compared to creating the distance function using for_seq separately.

Returns 0 if one sequence is empty.

from_rich_dict

core.sequence.ProteinSequence.from_rich_dict(data)

create a Sequence object from a rich dict

gap_indices

core.sequence.ProteinSequence.gap_indices()

Returns array of the indices of all gaps in the sequence

gap_vector

core.sequence.ProteinSequence.gap_vector()

Returns vector of True or False according to which pos are gaps or missing.

get_drawable

core.sequence.ProteinSequence.get_drawable(
    biotype=None,
    width=600,
    vertical=False,
)

make a figure from sequence features

Parameters

Name Type Description Default
biotype str | tuple[str, …] | list[str] | set[str] | None passed to get_features(biotype). Can be a single biotype or series. Only features matching this will be included. None
width float width in pixels 600
vertical bool rotates the drawable False

Returns

Name Type Description
a Drawable instance

Notes

If provided, the biotype is used for plot order.

get_drawables

core.sequence.ProteinSequence.get_drawables(biotype=None)

returns a dict of drawables, keyed by type

Parameters

Name Type Description Default
biotype str | tuple[str, …] | list[str] | set[str] | None passed to get_features(biotype). Can be a single biotype or series. Only features matching this will be included. None

get_features

core.sequence.ProteinSequence.get_features(
    biotype=None,
    name=None,
    start=None,
    stop=None,
    allow_partial=False,
    limit=None,
    **kwargs,
)

yields Feature instances

Parameters

Name Type Description Default
biotype str | tuple[str, …] | list[str] | set[str] | None biotype of the feature None
name str | None name of the feature None
start int | None start, stop positions to search between, relative to offset of this sequence. If not provided, entire span of sequence is used. None
stop int | None start, stop positions to search between, relative to offset of this sequence. If not provided, entire span of sequence is used. None
limit int | None maximum number of features to yield. If None, all matching features are returned. Must be positive. None
kwargs Any keyword arguments passed to annotation_db.get_features_matching() {}

Notes

When dealing with a nucleic acid moltype, the returned features will yield a sequence segment that is consistently oriented irrespective of strand of the current instance.

get_in_motif_size

core.sequence.ProteinSequence.get_in_motif_size(motif_length=1, warn=False)

returns sequence as list of non-overlapping motifs

Parameters

Name Type Description Default
motif_length int length of the motifs 1
warn bool whether to notify of an incomplete terminal motif False

get_kmers

core.sequence.ProteinSequence.get_kmers(k, strict=True)

return all overlapping k-mers

get_name

core.sequence.ProteinSequence.get_name()

Return the sequence name – should just use name instead.

get_type

core.sequence.ProteinSequence.get_type()

Return the sequence type as moltype label.

has_annotation_db

core.sequence.ProteinSequence.has_annotation_db()

returns True if self has annotation db

is_annotated

core.sequence.ProteinSequence.is_annotated(biotype=None)

returns True if sequence parent name has any annotations

Parameters

Name Type Description Default
biotype str | tuple[str] | None amend condition to return True only if the sequence is annotated with one of provided biotypes. None

is_degenerate

core.sequence.ProteinSequence.is_degenerate()

Returns True if sequence contains degenerate characters.

is_gapped

core.sequence.ProteinSequence.is_gapped()

Returns True if sequence contains gaps.

is_strict

core.sequence.ProteinSequence.is_strict()

Returns True if sequence contains only monomers.

is_valid

core.sequence.ProteinSequence.is_valid()

Returns True if sequence contains no items absent from alphabet.

iter_kmers

core.sequence.ProteinSequence.iter_kmers(k, strict=True)

generates all overlapping k-mers. When strict is True, the characters in the k-mer must be a subset of the canonical characters for the moltype

make_feature

core.sequence.ProteinSequence.make_feature(feature, *args)

return an Feature instance from feature data

Parameters

Name Type Description Default
feature FeatureDataType dict of key data to make an Feature instance required

Notes

Unlike add_feature(), this method does not add the feature to the database. We assume that spans represent the coordinates for this instance!

matrix_distance

core.sequence.ProteinSequence.matrix_distance(other, matrix)

Returns distance between self and other using a score matrix.

Warnings

The matrix must explicitly contain scores for the case where a position is the same in self and other (e.g. for a distance matrix, an identity between U and U might have a score of 0). The reason the scores for the ‘diagonals’ need to be passed explicitly is that for some kinds of distance matrices, e.g. log-odds matrices, the ‘diagonal’ scores differ from each other. If these elements are missing, this function will raise a KeyError at the first position that the two sequences are identical.

mw

core.sequence.ProteinSequence.mw(method='random', delta=None)

Returns the molecular weight of (one strand of) the sequence.

Parameters

Name Type Description Default
method str If the sequence is ambiguous, uses method (random or strip) to disambiguate the sequence. 'random'
delta float | None If delta is passed in, adds delta per strand. Default is None, which uses the alphabet default. Typically, this adds 18 Da for terminal water. However, note that the default nucleic acid weight assumes 5’ monophosphate and 3’ OH: pass in delta=18.0 if you want 5’ OH as well. None

Notes

this method only calculates the MW of the coding strand. If you want the MW of the reverse strand, add self.rc().mw(). DO NOT just multiply the MW by 2: the results may not be accurate due to strand bias, e.g. in mitochondrial genomes.

parent_coordinates

core.sequence.ProteinSequence.parent_coordinates(apply_offset=False, **kwargs)

returns seqid, start, stop, strand of this sequence on its parent

Parameters

Name Type Description Default
apply_offset bool if True, adds annotation offset from parent False

Notes

seqid is the identifier of the parent. Returned coordinates are with respect to the plus strand, irrespective of whether the sequence has been reversed complemented or not.

Returns

Name Type Description
seqid, start, end, strand of this sequence on the parent. strand is either
-1 or 1.0

parse_out_gaps

core.sequence.ProteinSequence.parse_out_gaps()

returns Map corresponding to gap locations and ungapped Sequence

replace_annotation_db

core.sequence.ProteinSequence.replace_annotation_db(value, check=True)

public interface to assigning the annotation_db

Parameters

Name Type Description Default
value AnnotationDbABC | list[AnnotationDbABC] | None the annotation db instance required
check bool whether to check value supports the feature interface True

Notes

The check can be very expensive, so if you’re confident set it to False

resolved_ambiguities

core.sequence.ProteinSequence.resolved_ambiguities()

Returns a list of sets of strings.

sample

core.sequence.ProteinSequence.sample(
    n=None,
    with_replacement=False,
    motif_length=1,
    randint=numpy.random.randint,
    permutation=numpy.random.permutation,
)

Returns random sample of positions from self, e.g. to bootstrap.

Parameters

Name Type Description Default
n int | None number of positions to sample. If None, all positions are sampled. None
with_replacement bool if True, samples with replacement. False
motif_length int number of positions to sample as a single motif. Starting point of each sampled motif is modulo motif_length in the original sequence. 1
randint Callable[[int, int | None, int | None], NumpyIntArrayType] random number generator, default is numpy.randint numpy.random.randint
permutation Callable[[int], NumpyIntArrayType] function to generate a random permutation of positions, default is numpy.permutation numpy.random.permutation

Notes

By default (resampling all positions without replacement), generates a permutation of the positions of the alignment.

shuffle

core.sequence.ProteinSequence.shuffle()

returns a randomized copy of the Sequence object

sliding_windows

core.sequence.ProteinSequence.sliding_windows(
    window,
    step,
    start=None,
    end=None,
)

Generator function that yield new sequence objects of a given length at a given interval.

Parameters

Name Type Description Default
window int The length of the returned sequence required
step int The interval between the start of the returned sequence objects required
start int | None first window start position None
end int | None last window start position None

strip_bad

core.sequence.ProteinSequence.strip_bad()

Removes any symbols not in the alphabet.

strip_bad_and_gaps

core.sequence.ProteinSequence.strip_bad_and_gaps()

Removes any symbols not in the alphabet, and any gaps. As the missing character could be a gap, this method will remove it as well.

strip_degenerate

core.sequence.ProteinSequence.strip_degenerate()

Removes degenerate bases by stripping them out of the sequence.

to_array

core.sequence.ProteinSequence.to_array(apply_transforms=True)

returns the numpy array

Parameters

Name Type Description Default
apply_transforms bool if True, applies any reverse complement operation True

Notes

Use this method with apply_transforms=False if you are creating data for storage in a SeqData instance.

to_fasta

core.sequence.ProteinSequence.to_fasta(make_seqlabel=None, block_size=60)

Return string of self in FASTA format, no trailing newline

Parameters

Name Type Description Default
make_seqlabel Callable[[Sequence], str] | None callback function that takes the seq object and returns a label str None

to_html

core.sequence.ProteinSequence.to_html(
    wrap=60,
    limit=None,
    colors=None,
    font_size=12,
    font_family='Lucida Console',
)

returns html with embedded styles for sequence colouring

Parameters

Name Type Description Default
wrap int maximum number of printed bases, defaults to alignment length 60
limit int | None truncate alignment to this length None
colors Mapping[str, str] | None dict of {char: color} to use for coloring None
font_size int in points. Affects labels and sequence and line spacing (proportional to value) 12
font_family str string denoting font family 'Lucida Console'
To >>> from IPython.core.display import HTML >>> HTML(aln.to_html()) required

to_json

core.sequence.ProteinSequence.to_json()

returns a json formatted string

to_moltype

core.sequence.ProteinSequence.to_moltype(moltype)

returns copy of self with moltype seq

Parameters

Name Type Description Default
moltype c3_moltype.MolTypeLiteral | c3_moltype.MolType[Any] molecular type required

Notes

This method cannot convert between nucleic acids and proteins. Use get_translation() for that.

When applied to a sequence in a SequenceCollection, the resulting sequence will no longer be part of the collection.

to_phylip

core.sequence.ProteinSequence.to_phylip(name_len=28, label_len=30)

Return string of self in one line for PHYLIP, no newline.

Default: max name length is 28, label length is 30.

to_rich_dict

core.sequence.ProteinSequence.to_rich_dict(exclude_annotations=True)

returns {‘name’: name, ‘seq’: sequence, ‘moltype’: moltype.label}

Notes

Deserialisation of the sequence object will not include the annotation_db even if exclude_annotations=False.

with_masked_annotations

core.sequence.ProteinSequence.with_masked_annotations(
    biotypes,
    mask_char=None,
    shadow=False,
)

returns a sequence with annot_types regions replaced by mask_char if shadow is False, otherwise all other regions are masked.

Parameters

Name Type Description Default
annot_types annotation type(s) required
mask_char str | None must be a character valid for the seq MolType. The default value is the most ambiguous character, eg. ‘?’ for DNA None
shadow bool whether to mask the annotated regions, or everything but the annotated regions False

with_termini_unknown

core.sequence.ProteinSequence.with_termini_unknown()

Returns copy of sequence with terminal gaps remapped as missing.

write

core.sequence.ProteinSequence.write(filename, format_name=None, **kwargs)

Write the sequence to a file.

Parameters

Name Type Description Default
filename str name of the sequence file required
format_name str | None format of the sequence file (e.g., ‘fasta’, ‘json’) None
**kwargs Any additional arguments passed to the format writer {}

Notes

If format_name is None, will attempt to infer format from the filename suffix. Uses the sequence format writer plugin system to support multiple output formats.