core.alignment.SequenceCollection

core.alignment.SequenceCollection(
    seqs_data,
    moltype,
    info=None,
    source=None,
    annotation_db=None,
    name_map=None,
    is_reversed=False,
)

A container of unaligned sequences.

Notes

Should be constructed using make_unaligned_seqs().

Attributes

Name Description
annotation_db the annotation database for the collection
modified collection is a modification of underlying storage
name_map returns mapping of seq names to parent seq names
names returns the names of the sequences in the collection
num_seqs the number of sequences in the collection
seqs iterable of sequences in the collection
storage the unaligned sequence storage instance of the collection

Methods

Name Description
add_feature add feature on named sequence
add_seqs Returns new collection with additional sequences.
apply_pssm scores sequences using the specified pssm
copy_annotations copy annotations into attached annotation db
count_ambiguous_per_seq Counts of ambiguous characters per sequence.
count_kmers return kmer counts for each sequence
counts counts of motifs
counts_per_seq counts of motifs per sequence
degap returns collection sequences without gaps or missing characters.
distance_matrix Estimated pairwise distance between sequences
dotplot make a dotplot between two sequences.
drop_duplicated_seqs returns self without duplicated sequences
duplicated_seqs returns the names of duplicated sequences
entropy_per_seq Returns the Shannon entropy per sequence.
from_rich_dict returns a new instance from a rich dict
get_ambiguous_positions Returns dict of seq:{position:char} for ambiguous chars.
get_features yields Feature instances
get_identical_sets returns sets of names for sequences that are identical
get_motif_probs Return a dictionary of motif probs, calculated as the averaged
get_seq Return a Sequence object for the specified seqname.
get_seq_names_if Returns list of names of seqs where f(seq) is True.
get_similar Returns new SequenceCollection containing sequences similar to target.
get_translation translate sequences from nucleic acid to protein
has_annotation_db returns True if self has annotation db
has_terminal_stop Returns True if any sequence has a terminal stop codon.
is_ragged rerturns True if sequences are of different lengths
iter_seqs Iterates over sequences in the collection, in order.
make_feature create a feature on named sequence, or on the collection itself
pad_seqs Returns copy in which sequences are padded with the gap character to same length.
probs_per_seq return frequency array of motifs per sequence
rc Returns the reverse complement of all sequences in the collection.
renamed_seqs Returns new collection with renamed sequences.
replace_annotation_db public interface to assigning the annotation_db
reverse_complement Returns the reverse complement of all sequences in the collection.
set_repr_policy specify policy for repr(self)
strand_symmetry returns dict of strand symmetry test results per seq
take_seqs Returns new collection containing only specified seqs.
take_seqs_if Returns new collection containing seqs where f(seq) is True.
to_dict Return a dictionary of sequences.
to_dna returns copy of self as a collection of DNA moltype seqs
to_fasta Return collection in Fasta format.
to_html returns html with embedded styles for sequence colouring
to_json returns json formatted string
to_moltype returns copy of self with changed moltype
to_rich_dict returns a json serialisable dict
to_rna returns copy of self as a collection of RNA moltype seqs
trim_stop_codons Removes any terminal stop codons from the sequences
write Write the sequences to a file, preserving order of sequences.

add_feature

core.alignment.SequenceCollection.add_feature(
    seqid=None,
    biotype,
    name,
    spans,
    parent_id=None,
    strand='+',
    **kwargs,
)

add feature on named sequence

Parameters

Name Type Description Default
seqid str | None seq name to associate with None
parent_id str | None name of the parent feature None
biotype str biological type required
name str feature name required
spans list[tuple[int, int]] plus strand coordinates required
strand str | int either ‘+’ or ‘-’ '+'

Returns

Name Type Description
Feature

add_seqs

core.alignment.SequenceCollection.add_seqs(seqs, **kwargs)

Returns new collection with additional sequences.

Parameters

Name Type Description Default
seqs dict[str, str | bytes | NumpyIntArrayType] sequences to add required

apply_pssm

core.alignment.SequenceCollection.apply_pssm(
    pssm=None,
    path=None,
    background=None,
    pseudocount=0,
    names=None,
    show_progress=False,
)

scores sequences using the specified pssm

Parameters

Name Type Description Default
pssm PSSM | None A profile.PSSM instance, if not provided, will be loaded from path None
path str | None path to either a jaspar or cisbp matrix (path must end have a suffix matching the format). None
background NumpyFloatArrayType | None background frequencies distribution None
pseudocount int adjustment for zero in matrix 0
names list[str] | str | None returns only scores for these sequences and in the name order None
show_progress bool | Progress | dict[str, Any] whether to display a progress bar False

Returns

Name Type Description
numpy array of log2 based scores at every position

copy_annotations

core.alignment.SequenceCollection.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 in self.names

count_ambiguous_per_seq

core.alignment.SequenceCollection.count_ambiguous_per_seq()

Counts of ambiguous characters per sequence.

count_kmers

core.alignment.SequenceCollection.count_kmers(k=1, use_hook=None, **kwargs)

return kmer counts for each sequence

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.

Returns

Name Type Description
numpy array of shape (num_seqs, num_kmers)
0th axis is in the order of self.names, 1st axis is in the order
of the kmer alphabet.

counts

core.alignment.SequenceCollection.counts(
    motif_length=1,
    include_ambiguity=False,
    allow_gap=False,
    exclude_unobserved=False,
)

counts of motifs

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_gap bool if True, motifs containing a gap character are included. False
exclude_unobserved bool if True, unobserved motif combinations are excluded. False

Notes

only non-overlapping motifs are counted

counts_per_seq

core.alignment.SequenceCollection.counts_per_seq(
    motif_length=1,
    include_ambiguity=False,
    allow_gap=False,
    exclude_unobserved=False,
    warn=False,
)

counts of motifs per sequence

Parameters

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

Notes

only non-overlapping motifs are counted

degap

core.alignment.SequenceCollection.degap(storage_backend=None, **kwargs)

returns collection sequences without gaps or missing characters.

Parameters

Name Type Description Default
storage_backend str | None name of the storage backend to use for the SeqsData object, defaults to cogent3 builtin. None
kwargs Any keyword arguments for the storage driver {}

Notes

The returned collection will not retain an annotation_db if present.

distance_matrix

core.alignment.SequenceCollection.distance_matrix(calc='pdist', **kwargs)

Estimated pairwise distance between sequences

Parameters

Name Type Description Default
calc str The distance calculation method to use, either “pdist” or “jc69”. - “pdist” is an approximation of the proportion sites different. - “jc69” is an approximation of the Jukes Cantor distance. 'pdist'

Returns

Name Type Description
DistanceMatrix Estimated pairwise distances between sequences in the collection

Notes

pdist approximates the proportion sites different from the Jaccard distance. Coefficients for the approximation were derived from a polynomial fit between Jaccard distance of kmers with k=10 and the proportion of sites different using mammalian 106 protein coding gene DNA sequence alignments.

jc69 approximates the Jukes Cantor distance using the approximated proportion sites different, i.e., a transformation of the above.

dotplot

core.alignment.SequenceCollection.dotplot(
    name1=None,
    name2=None,
    window=20,
    threshold=None,
    k=None,
    min_gap=0,
    width=500,
    title=None,
    rc=False,
    biotype=None,
    show_progress=False,
)

make a dotplot between two sequences.

Parameters

Name Type Description Default
name1 str | None names of sequences – if not provided, a random choice is made None
name2 str | None names of sequences – if not provided, a random choice is made None
window int segment size for comparison between sequences 20
threshold int | None windows where the sequences are identical >= threshold are a match None
k int | None size of k-mer to break sequences into. Larger values increase speed but reduce resolution. If not specified, and window == threshold, then k is set to window. Otherwise, it is computed as the maximum of {threshold // (window - threshold), 5}. None
min_gap int permitted gap for joining adjacent line segments, default is no gap joining 0
width int figure width. Figure height is computed based on the ratio of len(seq1) / len(seq2) 500
title str | None title for the plot None
rc bool include dotplot of reverse compliment also. Only applies to Nucleic acids moltypes False
biotype str | tuple[str] | None if selected sequences are annotated, display only these biotypes None

Returns

Name Type Description
a Drawable or AnnotatedDrawable

drop_duplicated_seqs

core.alignment.SequenceCollection.drop_duplicated_seqs()

returns self without duplicated sequences

Notes

Retains the first sequence of each duplicte group.

duplicated_seqs

core.alignment.SequenceCollection.duplicated_seqs()

returns the names of duplicated sequences

entropy_per_seq

core.alignment.SequenceCollection.entropy_per_seq(
    motif_length=1,
    include_ambiguity=False,
    allow_gap=False,
    exclude_unobserved=True,
    warn=False,
)

Returns the Shannon entropy per sequence.

Parameters

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

Notes

For motif_length > 1, it’s advisable to specify exclude_unobserved=True, this avoids unnecessary calculations.

from_rich_dict

core.alignment.SequenceCollection.from_rich_dict(data)

returns a new instance from a rich dict

get_ambiguous_positions

core.alignment.SequenceCollection.get_ambiguous_positions()

Returns dict of seq:{position:char} for ambiguous chars.

Used in likelihood calculations.

get_features

core.alignment.SequenceCollection.get_features(
    seqid=None,
    biotype=None,
    name=None,
    allow_partial=False,
    start=None,
    stop=None,
    limit=None,
    **kwargs,
)

yields Feature instances

Parameters

Name Type Description Default
seqid str | Iterator[str] | None limit search to features on this named sequence, defaults to search all None
biotype str | tuple[str, …] | list[str] | set[str] | None biotype of the feature, e.g. CDS, gene None
name str | None name of the feature None
start int | None start position of the feature (not inclusive) None
stop int | None stop position of the feature (inclusive) None
allow_partial bool allow features partially overlaping self False
limit int | None maximum total number of features to yield across all sequences. If None, all matching features are returned. Must be positive. None
kwargs Any additional keyword arguments to query the annotation db {}

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.
  • start is non-inclusive, so if allow_partial is False, only features strictly starting after start will be returned.

get_identical_sets

core.alignment.SequenceCollection.get_identical_sets(mask_degen=False)

returns sets of names for sequences that are identical

Parameters

Name Type Description Default
mask_degen bool if True, degenerate characters are ignored False

get_motif_probs

core.alignment.SequenceCollection.get_motif_probs(
    alphabet=None,
    include_ambiguity=False,
    exclude_unobserved=False,
    allow_gap=False,
    pseudocount=0,
)

Return a dictionary of motif probs, calculated as the averaged frequency across sequences.

Parameters

Name Type Description Default
alphabet c3_alphabet.CharAlphabet[Any] | None alphabet to use for motifs None
include_ambiguity bool if True resolved ambiguous codes are included in estimation of frequencies. False
exclude_unobserved bool if True, motifs that are not present in the alignment are excluded from the returned dictionary. False
allow_gap bool allow gap motif False
pseudocount int value to add to each count 0

Notes

only non-overlapping motifs are counted

get_seq

core.alignment.SequenceCollection.get_seq(seqname, copy_annotations=False)

Return a Sequence object for the specified seqname.

Parameters

Name Type Description Default
seqname str name of the sequence to return required
copy_annotations bool if True, only the annotations for the specified sequence are copied to the annotation database of the Sequence object which is decoupled from this collection. If False, the connection to this collections db is retained. False

get_seq_names_if

core.alignment.SequenceCollection.get_seq_names_if(f, negate=False)

Returns list of names of seqs where f(seq) is True.

Parameters

Name Type Description Default
f Callable[[TSequenceOrAligned], bool] function that takes a sequence object and returns True or False required
negate bool select all sequences EXCEPT those where f(seq) is True False

Notes

Sequence objects can be converted into strings or numpy arrays using str() and numpy.array() respectively.

get_similar

core.alignment.SequenceCollection.get_similar(
    target,
    min_similarity=0.0,
    max_similarity=1.0,
    metric=cast('Callable[[Any, Any], float]', c3_sequence.frac_same),
    transform=None,
)

Returns new SequenceCollection containing sequences similar to target.

Parameters

Name Type Description Default
target c3_sequence.Sequence | Aligned sequence object to compare to. Can be in the collection. required
min_similarity float minimum similarity that will be kept. Default 0.0. 0.0
max_similarity float maximum similarity that will be kept. Default 1.0. 1.0
metric Callable[[c3_sequence.Sequence | Aligned, c3_sequence.Sequence | Aligned], float] a similarity function to use. Must be f(first_seq, second_seq). The default metric is fraction similarity, ranging from 0.0 (0% identical) to 1.0 (100% identical). The Sequence class have lots of methods that can be passed in as unbound methods to act as the metric, e.g. frac_same_gaps. cast('Callable[[Any, Any], float]', c3_sequence.frac_same)
transform Callable[[c3_sequence.Sequence | Aligned], c3_sequence.Sequence | Aligned] | None transformation function to use on the sequences before the metric is calculated. If None, uses the whole sequences in each case. A frequent transformation is a function that returns a specified range of a sequence, e.g. eliminating the ends. Note that the transform applies to both the real sequence and the target sequence. None

Notes

both min_similarity and max_similarity are inclusive.

Warnings

if the transformation changes the type of the sequence (e.g. extracting a string from an RnaSequence object), distance metrics that depend on instance data of the original class may fail.

get_translation

core.alignment.SequenceCollection.get_translation(
    gc=1,
    incomplete_ok=False,
    include_stop=False,
    trim_stop=True,
    **kwargs,
)

translate sequences from nucleic acid to protein

Parameters

Name Type Description Default
gc GeneticCodeTypes genetic code, either the number or name (use cogent3.core.genetic_code.available_codes) 1
incomplete_ok bool codons that are mixes of nucleotide and gaps converted to ‘?’. raises a ValueError if False False
include_stop bool whether to allow a stops in the translated sequence False
trim_stop bool exclude terminal stop codons if they exist True
kwargs Any related to construction of the resulting object {}

Returns

Name Type Description
A new instance of self translated into protein

Notes

Translating will break the relationship to an annotation_db if present.

has_annotation_db

core.alignment.SequenceCollection.has_annotation_db()

returns True if self has annotation db

has_terminal_stop

core.alignment.SequenceCollection.has_terminal_stop(gc=1, strict=False)

Returns True if any sequence has a terminal stop codon.

Parameters

Name Type Description Default
gc GeneticCodeTypes valid input to cogent3.get_code(), a genetic code object, number or name 1
strict bool If True, raises an exception if a seq length not divisible by 3 False

is_ragged

core.alignment.SequenceCollection.is_ragged()

rerturns True if sequences are of different lengths

iter_seqs

core.alignment.SequenceCollection.iter_seqs(seq_order=None)

Iterates over sequences in the collection, in order.

Parameters

Name Type Description Default
seq_order Iterable[str | int] | None list of seqids giving the order in which seqs will be returned. Defaults to self.names None

make_feature

core.alignment.SequenceCollection.make_feature(feature, **kwargs)

create a feature on named sequence, or on the collection itself

Parameters

Name Type Description Default
feature FeatureDataType a dict with all the necessary data to construct a feature required

Returns

Name Type Description
Feature

Notes

To get a feature AND add it to annotation_db, use add_feature().

pad_seqs

core.alignment.SequenceCollection.pad_seqs(pad_length=None)

Returns copy in which sequences are padded with the gap character to same length.

Parameters

Name Type Description Default
pad_length int | None Length all sequences are to be padded to. Will pad to max sequence length if pad_length is None or less than max length. None

probs_per_seq

core.alignment.SequenceCollection.probs_per_seq(
    motif_length=1,
    include_ambiguity=False,
    allow_gap=False,
    exclude_unobserved=False,
    warn=False,
)

return frequency array of motifs per sequence

Parameters

Name Type Description Default
motif_length int number of characters per motif 1
include_ambiguity bool if True, include motifs containing ambiguous characters from the seq moltype are included. No expansion of those is attempted. False
allow_gap bool if True, include motifs containing a gap character False
exclude_unobserved bool if True, exclude motifs not present in the sequences in the resulting array False
warn bool warns if motif_length > 1 and collection trimmed to produce motif columns. False

rc

core.alignment.SequenceCollection.rc()

Returns the reverse complement of all sequences in the collection. A synonym for reverse_complement.

renamed_seqs

core.alignment.SequenceCollection.renamed_seqs(renamer)

Returns new collection with renamed sequences.

Parameters

Name Type Description Default
renamer Callable[[str], str] callable that takes a name string and returns a string required

Raises

Name Type Description
ValueError if renamer produces duplicate names.

Notes

The resulting object stores the mapping of new to old names in self.name_map.

replace_annotation_db

core.alignment.SequenceCollection.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

reverse_complement

core.alignment.SequenceCollection.reverse_complement()

Returns the reverse complement of all sequences in the collection. A synonym for rc.

set_repr_policy

core.alignment.SequenceCollection.set_repr_policy(
    num_seqs=None,
    num_pos=None,
    ref_name=None,
    wrap=None,
)

specify policy for repr(self)

Parameters

Name Type Description Default
num_seqs int | None number of sequences to include in represented display. None
num_pos int | None length of sequences to include in represented display. None
ref_name int | None name of sequence to be placed first, or “longest” (default). If latter, indicates longest sequence will be chosen. None
wrap int | None number of printed bases per row None

strand_symmetry

core.alignment.SequenceCollection.strand_symmetry(motif_length=1)

returns dict of strand symmetry test results per seq

take_seqs

core.alignment.SequenceCollection.take_seqs(
    names,
    negate=False,
    copy_annotations=False,
    **kwargs,
)

Returns new collection containing only specified seqs.

Parameters

Name Type Description Default
names str | PySeq[str] sequences to select (or exclude if negate=True) required
negate bool select all sequences EXCEPT names False
kwargs Any keyword arguments to be passed to the constructor of the new collection {}
copy_annotations bool if True, only annotations from selected seqs are copied to the annotation_db of the new collection False

take_seqs_if

core.alignment.SequenceCollection.take_seqs_if(f, negate=False)

Returns new collection containing seqs where f(seq) is True.

Parameters

Name Type Description Default
f Callable[[TSequenceOrAligned], bool] function that takes a sequence object and returns True or False required
negate bool select all sequences EXCEPT those where f(seq) is True False

Notes

Sequence objects can be converted into strings or numpy arrays using str() and numpy.array() respectively.

to_dict

core.alignment.SequenceCollection.to_dict(as_array=False)

Return a dictionary of sequences.

Parameters

Name Type Description Default
as_array bool if True, sequences are returned as numpy arrays, otherwise as strings False

to_dna

core.alignment.SequenceCollection.to_dna()

returns copy of self as a collection of DNA moltype seqs

to_fasta

core.alignment.SequenceCollection.to_fasta(block_size=60)

Return collection in Fasta format.

Parameters

Name Type Description Default
block_size int the sequence length to write to each line, by default 60 60

Returns

Name Type Description
The collection in Fasta format.

to_html

core.alignment.SequenceCollection.to_html(
    name_order=None,
    wrap=60,
    limit=None,
    colors=None,
    font_size=12,
    font_family='Lucida Console',
    **kwargs,
)

returns html with embedded styles for sequence colouring

Parameters

Name Type Description Default
name_order PySeq[str] | None order of names for display. None
wrap int number of columns per row 60
limit int | None truncate view of collection to this length None
colors Mapping[str, str] | None {character moltype. 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'

Examples

In a jupyter notebook, this code is used to provide the representation.

.. code-block:: python

seq_col  # is rendered by jupyter

You can directly use the result for display in a notebook as

.. code-block:: python

from IPython.core.display import HTML

HTML(seq_col.to_html())

to_json

core.alignment.SequenceCollection.to_json()

returns json formatted string

to_moltype

core.alignment.SequenceCollection.to_moltype(moltype)

returns copy of self with changed moltype

Parameters

Name Type Description Default
moltype MolTypes name of the new moltype, e.g, ‘dna’, ‘rna’. required

Notes

Cannot convert from nucleic acids to proteins. Use get_translation() for that.

to_rich_dict

core.alignment.SequenceCollection.to_rich_dict()

returns a json serialisable dict

Notes

Deserialisation the object produced by this method will not include the annotation_db if present.

to_rna

core.alignment.SequenceCollection.to_rna()

returns copy of self as a collection of RNA moltype seqs

trim_stop_codons

core.alignment.SequenceCollection.trim_stop_codons(gc=1, strict=False, **kwargs)

Removes any terminal stop codons from the sequences

Parameters

Name Type Description Default
gc GeneticCodeTypes valid input to cogent3.get_code(), a genetic code object, number or name, defaults to standard code 1
strict bool If True, raises an exception if a seq length not divisible by 3 False

write

core.alignment.SequenceCollection.write(filename, format_name=None, **kwargs)

Write the sequences to a file, preserving order of sequences.

Parameters

Name Type Description Default
filename str name of the sequence file required
format_name str | None format of the sequence file None

Notes

If format_name is None, will attempt to infer format from the filename suffix.