RnaSequence#
- class RnaSequence(seq='', name=None, info=None, check=True, preserve_case=False, gaps_allowed=True, wildcards_allowed=True, annotation_offset=0)#
Holds the standard RNA sequence.
- Attributes:
- annotation_db
annotation_offset
The offset between annotation coordinates and sequence coordinates.
- codon_alphabet
- line_wrap
Methods
add_feature
(*, biotype, name, spans[, ...])add a feature to annotation_db
annotate_from_gff
(f[, offset])copies annotations from a gff file to self,
annotate_matches_to
(pattern, biotype, name)Adds an annotation at sequence positions matching pattern.
can_match
(other)Returns True if every pos in self could match same pos in other.
can_mismatch
(other)Returns True if any position in self could mismatch with other.
can_mispair
(other)Returns True if any position in self could mispair with other.
can_pair
(other)Returns True if self and other could pair.
Returns complement of self, using data from MolType.
copy
([exclude_annotations, sliced])returns a copy of self
copy_annotations
(seq_db)copy annotations into attached annotation db
count
(item)count() delegates to self._seq.
Counts the degenerate bases in the specified sequence.
Counts the gaps in the specified sequence.
counts
([motif_length, include_ambiguity, ...])returns dict of counts of motifs
degap
()Deletes all gap characters from sequence.
diff
(other)Returns number of differences between self and other.
disambiguate
([method])Returns a non-degenerate sequence from a degenerate one.
distance
(other[, function])Returns distance between self and other using function(i,j).
Returns the index of first degenerate symbol in sequence, or None.
Returns the index of the first gap in the sequence, or None.
Returns the index of first invalid symbol in sequence, or None.
Returns the index of first non-strict symbol in sequence, or None.
frac_diff
(other)Returns fraction of positions where self and other differ.
frac_diff_gaps
(other)Returns frac.
frac_diff_non_gaps
(other)Returns fraction of non-gap positions where self differs from other.
frac_same
(other)Returns fraction of positions where self and other are the same.
frac_same_gaps
(other)Returns fraction of positions where self and other share gap states.
frac_same_non_gaps
(other)Returns fraction of non-gap positions where self matches other.
frac_similar
(other, similar_pairs)Returns fraction of positions where self[i] is similar to other[i].
Returns list of indices of all gaps in the sequence, or [].
gap_maps
()Returns dicts mapping between gapped and ungapped positions.
Returns vector of True or False according to which pos are gaps.
get_drawable
(*[, biotype, width, vertical])make a figure from sequence features
get_drawables
(*[, biotype])returns a dict of drawables, keyed by type
get_features
(*[, biotype, name, start, ...])yields Feature instances
get_in_motif_size
([motif_length, warn])returns sequence as list of non-overlapping motifs
get_kmers
(k[, strict])return all overlapping k-mers
get_name
()Return the sequence name -- should just use name instead.
get_translation
([gc, incomplete_ok, ...])translate to amino acid sequence
get_type
()Return the sequence type as moltype label.
has_terminal_stop
([gc, strict])Return True if the sequence has a terminal stop codon.
returns True if sequence has any annotations
Returns True if sequence contains degenerate characters.
is_gap
([char])Returns True if char is a gap.
Returns True if sequence contains gaps.
Returns True if sequence contains only monomers.
is_valid
()Returns True if sequence contains no items absent from alphabet.
iter_kmers
(k[, strict])generates all overlapping k-mers.
make_feature
(feature, *args)return an Feature instance from feature data
matrix_distance
(other, matrix)Returns distance between self and other using a score matrix.
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.
mw
([method, delta])Returns the molecular weight of (one strand of) the sequence.
returns seqid, start, stop, strand of this sequence on its parent
returns Map corresponding to gap locations and ungapped Sequence
Counts number of possible sequences matching the sequence.
rc
()Converts a nucleic acid sequence to its reverse complement.
replace
(oldchar, newchar)return new instance with oldchar replaced by newchar
replace_annotation_db
(value[, check])public interface to assigning the annotation_db
Returns a list of tuples of strings.
Converts a nucleic acid sequence to its reverse complement.
shuffle
()returns a randomized copy of the Sequence object
sliding_windows
(window, step[, start, end])Generator function that yield new sequence objects of a given length at a given interval.
strand_symmetry
([motif_length])returns G-test for strand symmetry
Removes any symbols not in the alphabet.
Removes any symbols not in the alphabet, and any gaps.
Removes degenerate bases by stripping them out of the sequence.
to_dna
()Returns copy of self as DNA.
to_fasta
([make_seqlabel, block_size])Return string of self in FASTA format, no trailing newline
to_html
([wrap, limit, colors, font_size, ...])returns html with embedded styles for sequence colouring
to_json
()returns a json formatted string
to_moltype
(moltype)returns copy of self with moltype seq
to_rich_dict
([exclude_annotations])returns {'name': name, 'seq': sequence, 'moltype': moltype.label}
to_rna
()Returns copy of self as RNA.
trim_stop_codon
([gc, strict])Removes a terminal stop codon from the sequence
with_masked_annotations
(annot_types[, ...])returns a sequence with annot_types regions replaced by mask_char if shadow is False, otherwise all other regions are masked.
Returns copy of sequence with terminal gaps remapped as missing.
gapped_by_map
gapped_by_map_motif_iter
gapped_by_map_segment_iter
- add_feature(*, biotype: str, name: str, spans: list[tuple[int, int]], parent_id: str | None = None, strand: str | None = None, on_alignment: bool = False, seqid: str | None = None) Feature #
add a feature to annotation_db
- Parameters:
- biotype
biological type
- name
name of the feature
- spans
coordinates for this sequence
- parent_id
name of the feature parent
- strand
‘+’ or ‘-’, defaults to ‘+’
- on_alignment
whether the feature spans are alignment coordinates
- seqid
ignored since the feature is added to this sequence
- Returns:
- Feature instance
- annotate_from_gff(f: PathLike, offset=None)#
copies annotations from a gff file to self,
- Parameters:
- fpath to gff annotation file.
- offsetOptional, the offset between annotation coordinates and sequence coordinates.
- annotate_matches_to(pattern: str, biotype: str, name: str, allow_multiple: bool = False)#
Adds an annotation at sequence positions matching pattern.
- Parameters:
- pattern
The search string for which annotations are made. IUPAC ambiguities are converted to regex on sequences with the appropriate MolType.
- biotype
The type of the annotation (e.g. “domain”).
- name
The name of the annotation.
- allow_multiple
If True, allows multiple occurrences of the input pattern. Otherwise, only the first match is used.
- Returns:
- Returns a list of Feature instances.
- property annotation_db#
- property annotation_offset#
The offset between annotation coordinates and sequence coordinates.
The offset can be used to adjust annotation coordinates to match the position of the given Sequence within a larger genomic context. For example, if the Annotations are with respect to a chromosome, and the sequence represents a gene that is 100 bp from the start of a chromosome, the offset can be set to 100 to ensure that the gene’s annotations are aligned with the appropriate genomic positions.
- Returns:
int: The offset between annotation coordinates and sequence coordinates.
- 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
- codon_alphabet = None#
- 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(exclude_annotations: bool = False, sliced: bool = True)#
returns a copy of self
- Parameters:
- sliced
Slices underlying sequence with start/end of self coordinates. The offset is retained.
- exclude_annotations
drops annotation_db when True
- copy_annotations(seq_db: SupportsFeatures) None #
copy annotations into attached annotation db
- Parameters:
- seq_db
compatible annotation db
Notes
Only copies annotations for records with seqid equal to self.name
- 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, warn=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.
- warn
warns if motif_length > 1 and alignment trimmed to produce motif columns
- degap()#
Deletes all gap characters from sequence.
- 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(segment_map, allow_gaps=True, recode_gaps=False) str #
- get_drawable(*, biotype: str | Iterable[str] | None = None, width: int = 600, vertical: bool = False)#
make a figure from sequence features
- Parameters:
- biotype
passed to get_features(biotype). Can be a single biotype or series. Only features matching this will be included.
- width
width in pixels
- vertical
rotates the drawable
- Returns:
- a Drawable instance
Notes
If provided, the biotype is used for plot order.
- get_drawables(*, biotype: str | Iterable[str] | None = None) dict #
returns a dict of drawables, keyed by type
- Parameters:
- biotype
passed to get_features(biotype). Can be a single biotype or series. Only features matching this will be included.
- get_features(*, biotype: str | None = None, name: str | None = None, start: int | None = None, stop: int | None = None, allow_partial: bool = False)#
yields Feature instances
- Parameters:
- biotype
biotype of the feature
- name
name of the feature
- start, stop
start, stop positions to search between, relative to offset of this sequence. If not provided, entire span of sequence is used.
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(motif_length=1, warn=False)#
returns sequence as list of non-overlapping motifs
- Parameters:
- motif_length
length of the motifs
- warn
whether to notify of an incomplete terminal motif
- get_kmers(k: int, strict: bool = True) list[str] #
return all overlapping k-mers
- get_name()#
Return the sequence name – should just use name instead.
- get_translation(gc: Any = None, incomplete_ok: bool = False, include_stop: bool = False, trim_stop: bool = True)#
translate to amino acid sequence
- Parameters:
- gc
valid input to cogent3.get_code(), a genetic code object, number or name
- incomplete_ok
codons that are mixes of nucleotide and gaps converted to ‘?’. raises a ValueError if False
- include_stop
allows stop codons in translation
- trim_stop
trims a terminal stop codon if it exists
- Returns:
- sequence of PROTEIN moltype
- Raises:
- AlphabetError if include_stop is False and a stop codon occurs
- get_type()#
Return the sequence type as moltype label.
- has_terminal_stop(gc: Any = None, strict: bool = False) bool #
Return True if the sequence has a terminal stop codon.
- Parameters:
- gc
valid input to cogent3.get_code(), a genetic code object, number or name
- strict
If True, raises an exception if length not divisible by 3
- 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, strict: bool = True) Generator[str, None, None] #
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
- line_wrap = None#
- make_feature(feature: FeatureDataType, *args) Feature #
return an Feature instance from feature data
- Parameters:
- feature
dict of key data to make an Feature instance
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(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(('U', '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.
- parent_coordinates() tuple[str, int, int, int] #
returns seqid, start, stop, strand of this sequence on its parent
- Returns:
- seqid, start, end, strand of this sequence on the parent. strand is either
- -1 or 1.
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.
- parse_out_gaps()#
returns Map corresponding to gap locations and ungapped Sequence
- 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
- replace_annotation_db(value: SupportsFeatures, check: bool = True) None #
public interface to assigning the annotation_db
- Parameters:
- value
the annotation db instance
- check
whether to check value supports the feature interface
Notes
The check can be very expensive, so if you’re confident set it to False
- 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
- To display in jupyter notebook:
>>> 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:
- moltypestr
molecular type
- to_rich_dict(exclude_annotations=False)#
returns {‘name’: name, ‘seq’: sequence, ‘moltype’: moltype.label}
- to_rna()#
Returns copy of self as RNA.
- trim_stop_codon(gc: Any = None, strict: bool = False)#
Removes a terminal stop codon from the sequence
- Parameters:
- gc
valid input to cogent3.get_code(), a genetic code object, number or name
- strict
If True, raises an exception if length not divisible by 3
Notes
If sequence contains gap characters, the result preserves the sequence length by adding gap characters at the end.
- 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
- with_termini_unknown()#
Returns copy of sequence with terminal gaps remapped as missing.