DnaSequence

class DnaSequence(seq='', name=None, info=None, check=True, preserve_case=False, gaps_allowed=True, wildcards_allowed=True)

Holds the standard DNA sequence.

PROTEIN = None
add_annotation(klass, *args, **kw)
add_feature(type, name, spans)
annotate_from_gff(f, pre_parsed=False)

annotates a Sequence from a gff file where each entry has the same SeqID

annotate_matches_to(pattern, annot_type, name, allow_multiple=False)

Adds an annotation at sequence positions matching pattern.

Parameters:
  • pattern (string) – The search string for which annotations are made. IUPAC ambiguities are converted to regex on sequences with the appropriate MolType.

  • annot_type (string) – The type of the annotation (e.g. “domain”).

  • name (string) – The name of the annotation.

  • allow_multiple (boolean) – If True, allows multiple occurrences of the input pattern. Otherwise only the first match is used.

Return type:

Returns a list of Annotation instances.

annotations = ()
attach_annotations(annots)
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.

can_mismatch(other)

Returns True if any position in self could mismatch with other.

Truncates at length of shorter sequence. gaps are always counted as matches.

can_mispair(other)

Returns True if any position in self could mispair with other.

Pairing occurs in reverse order, i.e. last position of other with first position of self, etc.

Truncates at length of shorter sequence. gaps are always counted as possible mispairs, as are weak pairs like GU.

can_pair(other)

Returns True if self and other could pair.

Pairing occurs in reverse order, i.e. last position of other with first position of self, etc.

Truncates at length of shorter sequence. gaps are only allowed to pair with other gaps, and are counted as ‘weak’ (same category as GU and degenerate pairs).

NOTE: second must be able to be reverse

clear_annotations()
codon_alphabet(*args, **kwargs)

If CodonAlphabet is set as a property, it gets self as extra 1st arg.

complement()

Returns complement of self, using data from MolType.

Always tries to return same type as item: if item looks like a dict, will return list of keys.

copy()

returns a copy of self

copy_annotations(other)
count(item)

count() delegates to self._seq.

count_degenerate()

Counts the degenerate bases in the specified sequence.

count_gaps()

Counts the gaps in the specified sequence.

counts(motif_length=1, include_ambiguity=False, allow_gap=False, exclude_unobserved=False)

returns dict of counts of motifs

only non-overlapping motifs are counted.

Parameters:
  • motif_length – number of elements per character.

  • include_ambiguity – if True, motifs containing ambiguous characters from the seq moltype are included. No expansion of those is attempted.

  • allow_gaps – if True, motifs containing a gap character are included.

  • exclude_unobserved – if True, unobserved motif combinations are excluded.

degap()

Deletes all gap characters from sequence.

detach_annotations(annots)
diff(other)

Returns number of differences between self and other.

NOTE: truncates at the length of the shorter sequence. Case-sensitive.

disambiguate(method='strip')

Returns a non-degenerate sequence from a degenerate one.

method can be ‘strip’ (deletes any characters not in monomers or gaps) or ‘random’(assigns the possibilities at random, using equal frequencies).

distance(other, function=None)

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

other must be a sequence.

function should be a function that takes two items and returns a number. To turn a 2D matrix into a function, use cogent3.util.miscs.DistanceFromMatrix(matrix).

NOTE: Truncates at the length of the shorter sequence.

Note that 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.

first_degenerate()

Returns the index of first degenerate symbol in sequence, or None.

first_gap()

Returns the index of the first gap in the sequence, or None.

first_invalid()

Returns the index of first invalid symbol in sequence, or None.

first_non_strict()

Returns the index of first non-strict symbol in sequence, or None.

frac_diff(other)

Returns fraction of positions where self and other differ.

Truncates at length of shorter sequence. Note that frac_same and frac_diff are both 0 if one sequence is empty.

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(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(other)

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

Truncates at length of shorter sequence. Note that frac_same and frac_diff are both 0 if one sequence is empty.

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(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(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.

gap_indices()

Returns list of indices of all gaps in the sequence, or [].

gap_maps()

Returns dicts mapping between gapped and ungapped positions.

gap_vector()

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

gapped_by_map(map, recode_gaps=False)
gapped_by_map_motif_iter(map)
gapped_by_map_segment_iter(map, allow_gaps=True, recode_gaps=False)
get_annotations_matching(annotation_type, name=None, extend_query=False)
Parameters:
  • annotation_type (string) – name of the annotation type. Wild-cards allowed.

  • name (string) – name of the instance. Wild-cards allowed.

  • extend_query (boolean) – queries sub-annotations if True

Return type:

list of AnnotatableFeatures

get_by_annotation(annotation_type, name=None, ignore_partial=False)

yields the sequence segments corresponding to the specified annotation_type and name one at a time.

Parameters:

ignore_partial – if True, annotations that extend beyond the current sequence are ignored.

get_drawable(width=600, vertical=False)

returns Drawable instance

get_drawables()

returns a dict of drawables, keyed by type

get_in_motif_size(motif_length=1, log_warnings=True)

returns sequence as list of non-overlapping motifs

Parameters:
  • motif_length – length of the motifs

  • log_warnings – whether to notify of an incomplete terminal motif

get_kmers(k: int) List[str]

return all overlapping k-mers

get_name()

Return the sequence name – should just use name instead.

get_orf_positions(gc=None, atg=False)
get_region_covering_all(annotations, feature_class=None, extend_query=False)
get_translation(gc=None, incomplete_ok=False)

translate to amino acid sequence

Parameters:
  • gc – name or ID of genetic code

  • incomplete_ok (bool) – codons that are mixes of nucleotide and gaps converted to ‘?’. raises a ValueError if False

Return type:

sequence of PROTEIN moltype

get_type()

Return the sequence type as moltype label.

gettype()

Return the sequence type.

has_terminal_stop(gc=None, allow_partial=False)

Return True if the sequence has a terminal stop codon.

Parameters:
  • gc – genetic code object

  • allow_partial – if True and the sequence length is not dividisble by 3, ignores the 3’ terminal incomplete codon

is_annotated()

returns True if sequence has any annotations

is_degenerate()

Returns True if sequence contains degenerate characters.

is_gap(char=None)

Returns True if char is a gap.

If char is not supplied, tests whether self is gaps only.

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(k: int) Generator[str, None, None]

generates all overlapping k-mers

line_wrap = None
matrix_distance(other, matrix)

Returns distance between self and other using a score matrix.

WARNING: 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.

moltype = MolType(('T', 'C', 'A', 'G'))
must_match(other)

Returns True if all positions in self must match positions in other.

must_pair(other)

Returns True if all positions in self must pair with other.

Pairing occurs in reverse order, i.e. last position of other with first position of self, etc.

mw(method='random', delta=None)

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

If the sequence is ambiguous, uses method (random or strip) to disambiguate the sequence.

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.

Note that 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.

parse_out_gaps()
possibilities()

Counts number of possible sequences matching the sequence.

Uses self.degenerates to decide how many possibilities there are at each position in the sequence.

protein = MolType(('A', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'Y'))
rc()

Converts a nucleic acid sequence to its reverse complement.

replace(oldchar, newchar)

return new instance with oldchar replaced by newchar

resolveambiguities()

Returns a list of tuples of strings.

resolved_ambiguities() List[Tuple[str]]

Returns a list of tuples of strings.

reverse_complement()

Converts a nucleic acid sequence to its reverse complement. Synonymn for rc.

shuffle()

returns a randomized copy of the Sequence object

sliding_windows(window, step, start=None, end=None)

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

Parameters:
  • window – The length of the returned sequence

  • step – The interval between the start of the returned sequence objects

  • start – first window start position

  • end – last window start position

strand_symmetry(motif_length=1)

returns G-test for strand symmetry

strip_bad()

Removes any symbols not in the alphabet.

strip_bad_and_gaps()

Removes any symbols not in the alphabet, and any gaps.

strip_degenerate()

Removes degenerate bases by stripping them out of the sequence.

to_dna()

Returns copy of self as DNA.

to_fasta(make_seqlabel=None, block_size=60)

Return string of self in FASTA format, no trailing newline

Parameters:

make_seqlabel – callback function that takes the seq object and returns a label str

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

returns html with embedded styles for sequence colouring

Parameters:
  • wrap – maximum number of printed bases, defaults to alignment length

  • limit – truncate alignment to this length

  • colors – {character moltype.

  • font_size – in points. Affects labels and sequence and line spacing (proportional to value)

  • font_family – string denoting font family

  • notebook (To display in jupyter) –

    >>> from IPython.core.display import HTML
    >>> HTML(aln.to_html())
    

to_json()

returns a json formatted string

to_moltype(moltype)

returns copy of self with moltype seq

Parameters:

moltype (str) – molecular type

to_rich_dict()

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

to_rna()

Returns copy of self as RNA.

translate(*args, **kwargs)

returns the result of call str.translate

Notes

This is a string method, nothing to do with translating into a protein sequence.

trim_stop_codon(gc=None, allow_partial=False)

Removes a terminal stop codon from the sequence

Parameters:
  • gc – genetic code object

  • allow_partial – if True and the sequence length is not divisible by 3, ignores the 3’ terminal incomplete codon

with_masked_annotations(annot_types, mask_char=None, shadow=False, extend_query=False)

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

Parameters:
  • annot_types – annotation type(s)

  • mask_char – must be a character valid for the seq MolType. The default value is the most ambiguous character, eg. ‘?’ for DNA

  • shadow – whether to mask the annotated regions, or everything but the annotated regions

  • extend_query (boolean) – queries sub-annotations if True

with_termini_unknown()

Returns copy of sequence with terminal gaps remapped as missing.