References (genomics: sequences, motifs, proteins, RNA)#
Sequence basics#
- class DNA(sequence, codons_stop=['TAA', 'TGA', 'TAG'], codons_stop_rev=['TTA', 'TCA', 'CTA'], codons_start=['ATG'], codons_start_rev=['CAT'])[source]#
Simple DNA class
>>> from sequana.sequence import DNA >>> d = DNA("ACGTTTT") >>> d.reverse_complement()
Some long computations are done when setting the window size:
d.window = 100
The ORF detection has been validated agains a plasmodium 3D7 ORF file found on plasmodb.org across the 14 chromosomes.
Constructor
A sequence is just a string stored in the
sequenceattribute. It has properties related to the type of alphabet authorised.- Parameters:
sequence (str) -- May be a string of a Fasta File, in which case only the first sequence is used.
complement_in
complement_out
letters -- authorise letters. Used in
check()only.
Todo
use counter only once as a property
- property AT_skew#
- DEFAULT_TRACKS = ['GC_skew', 'GC_skew_cumul', 'AT_skew', 'AT_skew_cumul', 'RY_skew_cumul', 'MK_skew_cumul', 'H_bond_skew_cumul', 'GC_content', 'AT_content']#
Tracks plotted by
plot_tracks()andplot_all_skews()when no track is requested.
- property GC_skew#
- property ORF_pos#
- TRACKS = {'AT_content': TrackSpec(getter=<function DNA.<lambda>>, ylabel='AT', title='AT content', color='k', default_window=None, requires_window=True), 'AT_skew': TrackSpec(getter=<function DNA.<lambda>>, ylabel='(A - T) / (A + T)', title='AT skew', color='b', default_window=None, requires_window=True), 'AT_skew_cumul': TrackSpec(getter=<function DNA.<lambda>>, ylabel='(A - T) / (A + T)', title='AT skew (cumulative sum)', color='r', default_window=None, requires_window=True), 'GC_content': TrackSpec(getter=<function DNA.<lambda>>, ylabel='GC', title='GC content', color='k', default_window=None, requires_window=True), 'GC_skew': TrackSpec(getter=<function DNA.<lambda>>, ylabel='(G - C) / (G + C)', title='GC skew', color='b', default_window=None, requires_window=True), 'GC_skew_cumul': TrackSpec(getter=<function DNA.<lambda>>, ylabel='(G - C) / (G + C)', title='GC skew (cumulative sum)', color='r', default_window=None, requires_window=True), 'H_bond_skew_cumul': TrackSpec(getter=<function DNA.<lambda>>, ylabel='(A + T) - (G + C)', title='Cumulative H-bond skew (Weak H-bond - Strong H-bond)', color='g', default_window=None, requires_window=True), 'MK_skew_cumul': TrackSpec(getter=<function DNA.<lambda>>, ylabel='(A + C) - (G + T)', title='Cumulative MK skew (Amino - Keto)', color='g', default_window=None, requires_window=True), 'RY_skew_cumul': TrackSpec(getter=<function DNA.<lambda>>, ylabel='(A + G) - (C + T)', title='Cumulative RY skew (Purine - Pyrimidine)', color='g', default_window=None, requires_window=True), 'curvature': TrackSpec(getter=<function DNA.<lambda>>, ylabel='curvature (degrees)', title='Intrinsic curvature', color='m', default_window=11, requires_window=False), 'dinucleotide_count': TrackSpec(getter=<function DNA.<lambda>>, ylabel='count', title='Dinucleotide count (AA, CC, GG, TT)', color='k', default_window=100, requires_window=False), 'entropy': TrackSpec(getter=<function DNA.<lambda>>, ylabel='entropy (bits)', title='Shannon entropy', color='k', default_window=500, requires_window=False), 'flexibility': TrackSpec(getter=<function DNA.<lambda>>, ylabel='flexibility angle', title='DNA flexibility', color='k', default_window=100, requires_window=False), 'informational_entropy': TrackSpec(getter=<function DNA.<lambda>>, ylabel='entropy', title='Informational entropy (triplets)', color='k', default_window=500, requires_window=False), 'karlin_content': TrackSpec(getter=<function DNA.<lambda>>, ylabel='(A + G) - (C + T)', title='Karlin content (excess of purines over pyrimidines)', color='k', default_window=None, requires_window=True), 'karlin_signature_difference': TrackSpec(getter=<function DNA.<lambda>>, ylabel='difference', title='Karlin signature difference', color='k', default_window=500, requires_window=False), 'trinucleotide_count': TrackSpec(getter=<function DNA.<lambda>>, ylabel='count', title='Trinucleotide count (AAA, CCC, GGG, TTT)', color='k', default_window=100, requires_window=False), 'twist': TrackSpec(getter=<function DNA.<lambda>>, ylabel='twist (degrees)', title='Helix twist', color='m', default_window=None, requires_window=False)}#
Tracks known to
plot_tracks(), as a name toTrackSpecmapping. Add an entry to plot your own metric:DNA.TRACKS["my_metric"] = TrackSpec( getter=lambda dna, window: my_function(dna.sequence), ylabel="my metric", color="m")
Tracks with requires_window set need
windowto be set first.
- barplot_count_ORF_CDS_by_frame(alpha=0.5, bins=40, xlabel='Frame', ylabel='#', bar_width=0.35)[source]#
- classmethod get_available_tracks()[source]#
Return the sorted names of the tracks known to
plot_tracks()
- get_curvature(window=11, use_twist=True, bp_per_turn=10.5)[source]#
Return the local intrinsic (static) curvature of the helix axis.
Each base-pair step bends the axis by its Roll angle (taken from
sequana.metrics.dinucleotide_roll) in a direction that rotates with the accumulated twist. Bends repeated in phase with the helical repeat (about 10.5 bases, as in A-tracts) add up and give the classic intrinsically-curved DNA signature, while out-of-phase bends cancel out. The curvature of a step is the norm of the vector sum of the bends inside the window centred on that step. Seesequana.metrics.compute_curvature()for the model and references.- Parameters:
window (int) -- window length in steps; 11 is about one helical turn.
use_twist (bool) -- use the sequence-dependent twist from
get_twist()for the phasing. If False, a constant canonical twist of 360 / bp_per_turn is used.bp_per_turn (float) -- helical repeat used for the canonical twist.
- Returns:
array of length len(sequence) - 1 in degrees accumulated over the window. Steps closer than window//2 to either end are set to NaN. Steps with a letter outside ACGT contribute no bend.
from sequana.sequence import DNA curvature = DNA("data.fa").get_curvature(window=11)
- get_twist(bp_per_turn=10.5)[source]#
Return the helical twist angle (degrees) of each base-pair step.
The twist is the rotation between two consecutive base pairs. Canonical B-DNA is about 36 degrees per step but the actual value depends on the dinucleotide (about 32 to 37 degrees), which matters for supercoiling, nucleosome positioning and protein-DNA interactions. Values are the averages stored in
sequana.metrics.helix_twist.- Parameters:
bp_per_turn (float) -- helical repeat used for steps that contain a letter outside ACGT (e.g. N); those fall back to 360 / bp_per_turn.
- Returns:
array of length len(sequence) - 1. Entry i is the step between positions i and i+1.
from sequana.sequence import DNA twist = DNA("ACGTACGT").get_twist()
- plot_all_skews(figsize=(10, 12), fontsize=16, alpha=0.5)[source]#
Plot the skew and content tracks.
Alias to
plot_tracks()called withDEFAULT_TRACKS. Useplot_tracks()to choose the tracks to display.
- plot_tracks(tracks=None, window=None, figsize=None, fontsize=16, alpha=0.5)[source]#
Plot any combination of the metrics available in
TRACKS.One panel is created per track, all sharing the X axis (the position along the sequence).
- Parameters:
tracks (list) -- names of the tracks to plot (see
get_available_tracks()). A single name may be given as a string. Defaults toDEFAULT_TRACKS, that is the skew and content tracks.window (int) -- window used by all the tracks. Each track falls back on its own default (
TrackSpec.default_window) if not provided. Note that the curvature window is expressed in base-pair steps, not in bases. The skew tracks are precomputed, so passing a window here is equivalent to settingwindow.figsize (tuple) -- defaults to a height that grows with the number of tracks.
fontsize (float) -- size of the main title.
alpha (float) -- transparency of the curves.
- Returns:
the matplotlib figure.
from sequana.sequence import DNA dna = DNA("data.fa") dna.window = 1000 dna.plot_tracks() # default tracks dna.plot_tracks(["GC_skew", "curvature", "entropy"]) dna.plot_tracks(["GC_content", "entropy"], window=500)
- property threshold#
- property type_filter#
- property type_window#
- property window#
- class RNA(sequence)[source]#
Simple RNA class
>>> from sequana.sequence import RNA >>> d = RNA("ACGUUUU") >>> d.reverse_complement()
Constructor
A sequence is just a string stored in the
sequenceattribute. It has properties related to the type of alphabet authorised.- Parameters:
sequence (str) -- May be a string of a Fasta File, in which case only the first sequence is used.
complement_in
complement_out
letters -- authorise letters. Used in
check()only.
Todo
use counter only once as a property
- class Repeats(filename_fasta, merge=False, name=None)[source]#
Class for finding repeats in DNA or RNA linear sequences.
Computation is performed each time the
thresholdis set to a new value.from sequana import sequana_data, Repeats rr = Repeats(sequana_data("measles.fa")) rr.threshold = 4 rr.hist_length_repeats()
Note
Works with shustring package from Bioconda (April 2017)
Todo
use a specific sequence (first one by default). Others can be selected by name
Constructor
Input must be a fasta file with valid DNA or RNA characters
- Parameters:
filename_fasta (str) -- a Fasta file, only the first sequence is used !
threshold (int) -- Minimal length of repeat to output
name (str) -- if name is provided, scan the Fasta file and select the corresponding sequence. if you want to analyse all sequences, you need to use a loop by setting _header for each sequence with the sequence name found in sequence header.
Note
known problems. Header with a > character (e.g. in the comment) are left strip and only the comments is kept. Another issue is for multi-fasta where one sequence is ignored (last or first ?)
- property begin_end_repeat_position#
- property df_shustring#
Return dataframe with shortest unique substring length at each position shortest unique substrings are unique in the sequence and its complement Uses shustring tool
- property do_merge#
- property header#
- hist_length_repeats(bins=20, alpha=0.5, hold=False, fontsize=12, grid=True, title='Repeat length', xlabel='Repeat length', ylabel='#', logy=True)[source]#
Plots histogram of the repeat lengths
- property length#
- property list_len_repeats#
- property longest_shustring#
- property names#
- property threshold#
- class Sequence(sequence, complement_in=b'ACGT', complement_out=b'TGCA', letters='ACGT')[source]#
Abstract base classe for other specialised sequences such as DNA.
Sequenced is the base class for other classes such as
DNAandRNA.from sequana import Sequence s = Sequence("ACGT") s.stats() s.get_complement()
Note
You may use a Fasta file as input (see constructor)
Constructor
A sequence is just a string stored in the
sequenceattribute. It has properties related to the type of alphabet authorised.- Parameters:
Todo
use counter only once as a property
- complement()[source]#
Alias to
get_complement()
- get_occurences(pattern, overlap=False)[source]#
Return position of the input pattern in the sequence
>>> from sequana import Sequence >>> s = Sequence('ACGTTTTACGT') >>> s.get_occurences("ACGT") [0, 7]
- reverse()[source]#
Alias to
get_reverse()
- property sequence#
- class TrackSpec(getter: Callable, ylabel: str, title: str = '', color: str = 'b', default_window: int | None = None, requires_window: bool = False)[source]#
Description of a track that
DNA.plot_tracks()can display.- Parameters:
getter -- called as
getter(dna, window)and returns the values to plot (one value per position). window is the window requested by the user, ordefault_windowif none was requested.ylabel -- label of the Y axis.
title -- title of the panel. The track name is used if empty.
color -- matplotlib color.
default_window -- window used when the user does not provide one. Use None for tracks that do not depend on a window.
requires_window -- if True, the track reads values precomputed by
DNA._compute_skews()and therefore needsDNA.windowto be set beforehand.
Utilities to manipulate and find codons
- class Codon[source]#
Utilities to manipulate codons
The codon contains hard-coded set of start and stop codons (bacteria) for strand plus and minus. Adapt to your needs for other organisms. Based on the scan of Methanothermobacter thermautotrophicus bacteria.
from sequana import Codon c = Codon() c.start_codons['+']
- codons = {'start': {'+': frozenset({'ATG', 'GTG', 'TTG'}), '-': frozenset({'CAA', 'CAC', 'CAT'})}, 'stop': {'+': frozenset({'TAA', 'TAG', 'TGA'}), '-': frozenset({'CTA', 'TCA', 'TTA'})}}#
- find_start_codon_position(sequence, position, strand, max_shift=10000)[source]#
Return starting position and string of closest start codon to a given position
The starting position is on the 5-3 prime direction (see later)
The search starts at the given position, then +1 base, then -1 base, then +2, -2, +3, etc
Here, we start at position 2 (letter G), then shift by +1 and find the ATG string.
>>> from sequana import Codon >>> c = Codon() >>> c.find_start_codon_position("ATGATGATG", 2, "+") (3, 'ATG')
whereas starting at position 1, a shift or +1 (position 2 ) does not hit a start codon. Next, a shift of -1 (position 0) hits the ATG start codon.:
>>> c.find_start_codon_position("ATGATGATG", 1, "+") (3, 'ATG')
On strand -, the start codon goes from right to left. So, in the following example, the CAT start codon (reverse complement of ATG) is found at position 3. Developers must take into account a +3 shift if needed:
>>> c.find_start_codon_position("AAACAT", 3, "-") (3, 'CAT') >>> c.find_start_codon_position("AAACATCAT", 8, "-")
- find_stop_codon_position(sequence, position, strand, max_shift=10000)[source]#
Return position and string of closest stop codon to a given position
See
find_start_codon_position()for details.Only difference is that the search is based on stop codons rather than start codons.
>>> from sequana import Codon >>> c = Codon() >>> c.find_stop_codon_position("ATGACCCC", 2, "+") (1, 'TGA')
- compute_melting_temperature_salt_adjusted(sequence)[source]#
compute melting temperature with salt adjustement
This rule is a quick estimation for sequences greater than 14bp in length (Chester and Marshak 1993)
Tm(Celsius) = 69.3 + 0.41 x %GC - 650 / (sequence length)
This formula accounts for the stability conferred by GC content but does not account for secondary structures or mismatches.
- compute_melting_temperature_wallace_rule(sequence)[source]#
Compute mekting temperature Tm of a sequence using Wallace rule
This rule is a quick estimation for short oligonucleotides (20-25 base pairs), based on [Marmu and Doty 1962]:
Tm(Celsius) = 2 ({A} + {T}) + 4 ({G} + {C})
Where A and T bases contribute 2°C each and G and C bases contribute 4°C each.
This formula assumes standard conditions and is less accurate for longer sequences or those with unusual salt concentrations.
Pairwise sequence alignment (global and local, affine gap penalties).
Provides a Biopython Bio.Align.PairwiseAligner-equivalent: Needleman-Wunsch
global alignment and Smith-Waterman local alignment, with affine gap
penalties (separate gap-open / gap-extend costs) and pluggable scoring via
sequana.substitution_matrices or a simple match/mismatch score.
This is a pure-Python dynamic-programming implementation (numpy-backed score matrix). It is intended for short-to-medium sequences (single genes, primers, short reads, protein domains) -- not for chromosome/genome-scale alignment, which is O(n*m) in time and memory and should instead go through an external aligner (minimap2, bwa) already wrapped elsewhere in Sequana.
Example:
from sequana.pairwise import PairwiseAligner
aligner = PairwiseAligner(mode="global", match=1, mismatch=-1, open_gap=-2, extend_gap=-0.5)
result = aligner.align("GATTACA", "GCATGCU")
print(result.score)
print(result)
Protein alignment with a substitution matrix:
from sequana.pairwise import PairwiseAligner
aligner = PairwiseAligner(mode="local", matrix="BLOSUM62", open_gap=-10, extend_gap=-0.5)
result = aligner.align("MEEPQSDPSV", "MEEPQSDLSV")
print(result.identity)
- class PairwiseAligner(mode: str = 'global', match: float = 1.0, mismatch: float = -1.0, matrix: str | SubstitutionMatrix | None = None, open_gap: float = -10.0, extend_gap: float = -0.5)[source]#
Global (Needleman-Wunsch) or local (Smith-Waterman) pairwise alignment.
- Args:
- mode: "global" (Needleman-Wunsch, align full length of both
sequences) or "local" (Smith-Waterman, find the best-scoring local region).
- match: score for a matching pair when no substitution matrix is
given (simple match/mismatch scoring). Ignored if
matrixis set.- mismatch: score for a mismatching pair when no substitution matrix
is given. Ignored if
matrixis set.- matrix: name of a built-in substitution matrix (e.g. "BLOSUM62",
"PAM250", see
sequana.substitution_matrices.available_matrices()) or aSubstitutionMatrixinstance. Overridesmatch/mismatchwhen set.
open_gap: penalty for opening a gap (should be negative or zero). extend_gap: penalty for each additional gap position after the
first (should be negative or zero); this is what makes the gap penalty affine rather than linear.
Note on scale: this is an O(n*m) dynamic-programming aligner suitable for sequences up to a few thousand bases/residues (genes, amplicons, protein domains, primers). For chromosome/genome-scale alignment use an external mapper (minimap2, bwa) -- see
sequana.bamtools.Example:
from sequana.pairwise import PairwiseAligner aligner = PairwiseAligner(mode="global", match=1, mismatch=-1, open_gap=-2, extend_gap=-0.5) result = aligner.align("GATTACA", "GCATGCU") result.score -1.0
- align(seqA: str, seqB: str) PairwiseAlignmentResult[source]#
Align two sequences and return the best-scoring alignment.
- Args:
- seqA: first sequence (string; case-insensitive scoring, case
preserved in output)
seqB: second sequence
- Returns:
PairwiseAlignmentResult with the best-scoring alignment. When several optimal alignments exist, one arbitrary optimum is returned (matching typical Needleman-Wunsch/Smith-Waterman traceback behaviour).
- Raises:
SequanaException: if either sequence is empty.
- class PairwiseAlignmentResult(seqA: str, seqB: str, score: float, start_a: int = 0, end_a: int = 0, start_b: int = 0, end_b: int = 0)[source]#
Result of a pairwise alignment.
- Attributes:
seqA: first (aligned) sequence, with "-" for gaps seqB: second (aligned) sequence, with "-" for gaps score: alignment score under the aligner's scoring scheme start_a, end_a: 0-indexed span of the alignment in the original seqA
(whole sequence for global alignment; sub-region for local)
start_b, end_b: same, for seqB
- format(width: int = 60) str[source]#
Return a human-readable alignment block, wrapped at
widthcolumns.Example:
target: GATTACA |..|.|. query : GCATGCU
- align_global(seqA: str, seqB: str, match: float = 1.0, mismatch: float = -1.0, open_gap: float = -10.0, extend_gap: float = -0.5, matrix: str | SubstitutionMatrix | None = None) PairwiseAlignmentResult[source]#
Convenience function: global (Needleman-Wunsch) alignment of two sequences.
Example:
from sequana.pairwise import align_global result = align_global("GATTACA", "GCATGCU") print(result)
- align_local(seqA: str, seqB: str, match: float = 1.0, mismatch: float = -1.0, open_gap: float = -10.0, extend_gap: float = -0.5, matrix: str | SubstitutionMatrix | None = None) PairwiseAlignmentResult[source]#
Convenience function: local (Smith-Waterman) alignment of two sequences.
Example:
from sequana.pairwise import align_local result = align_local("AAAGATTACAAAA", "GGGGCATGCUGGGG") print(result)
Substitution matrices for sequence alignment scoring (BLOSUM/PAM).
Values match NCBI's canonical BLOSUM/PAM tables (cross-checked against
Biopython's Bio.Align.substitution_matrices).
Example:
from sequana.substitution_matrices import load_matrix
blosum62 = load_matrix("BLOSUM62")
blosum62.score("A", "R")
-1
- class SubstitutionMatrix(name: str, scores: Dict[Tuple[str, str], float])[source]#
A symmetric amino-acid (or nucleotide) substitution/scoring matrix.
Wraps a dict of pairwise substitution scores (e.g. BLOSUM62, PAM250) and exposes a simple
score(a, b)lookup used by pairwise aligners.- Args:
name: matrix name (e.g. "BLOSUM62") scores: dict mapping (char_a, char_b) -> score, symmetric lookups are
handled automatically (score("A","R") == score("R","A"))
Example:
from sequana.substitution_matrices import load_matrix m = load_matrix("BLOSUM62") m.score("A", "A") 4 m.score("W", "F") 1
- load_matrix(name: str) SubstitutionMatrix[source]#
Load a built-in substitution matrix by name.
- Args:
name: one of
available_matrices(), e.g. "BLOSUM62", "PAM250".- Returns:
SubstitutionMatrix instance.
- Raises:
ValueError: if
nameis not a known built-in matrix.
Example:
from sequana.substitution_matrices import load_matrix blosum62 = load_matrix("BLOSUM62")
- simple_dna_matrix(match: float = 1.0, mismatch: float = -1.0) SubstitutionMatrix[source]#
Build a trivial match/mismatch scoring matrix for nucleotides (ACGTN).
Useful default for DNA/RNA pairwise alignment where a full substitution matrix like BLOSUM (protein-oriented) doesn't apply.
Example:
from sequana.substitution_matrices import simple_dna_matrix m = simple_dna_matrix(match=2, mismatch=-1) m.score("A", "A") 2 m.score("A", "T") -1
Melting temperature of nucleic acid duplexes with the nearest-neighbour model.
Nearest-neighbour parameters are provided for DNA/DNA duplexes (four sets) and for RNA/DNA hybrids. The RNA/DNA set
is what is needed to predict the stability of a DNA probe bound to an RNA target (see
sequana.ribodesigner2). The calculation follows the standard two-state nearest-neighbour model with the
entropy salt correction of SantaLucia (1998). Perfectly matched duplexes are supported (no mismatch, no dangling end).
The results agree with Bio.SeqUtils.MeltingTemp.Tm_NN (Biopython) for the same parameters; this is checked in the
tests.
Table |
Reference |
|---|---|
DNA_NN1 |
Breslauer, K.J. et al. PNAS 83, 3746-3750 (1986) |
DNA_NN2 |
Sugimoto, N. et al. Nucleic Acids Res. 24, 4501-4505 (1996) |
DNA_NN3 |
Allawi, H.T. and SantaLucia, J. Biochemistry 36, 10581-10594 (1997) |
DNA_NN4 |
SantaLucia, J. and Hicks, D. Annu. Rev. Biophys. Biomol. Struct. 33, 415-440 (2004) |
R_DNA_NN1 |
Sugimoto, N. et al. Biochemistry 34, 11211-11216 (1995), RNA/DNA hybrids |
The salt correction is from SantaLucia, J. PNAS 95, 1460-1465 (1998).
- TABLES = {'DNA_NN1': {'AA/TT': (-9.1, -24.0), 'AT/TA': (-8.6, -23.9), 'CA/GT': (-5.8, -12.9), 'CG/GC': (-11.9, -27.8), 'CT/GA': (-7.8, -20.8), 'GA/CT': (-5.6, -13.5), 'GC/CG': (-11.1, -26.7), 'GG/CC': (-11.0, -26.6), 'GT/CA': (-6.5, -17.3), 'TA/AT': (-6.0, -16.9), 'init': (0, 0), 'init_5T/A': (0, 0), 'init_A/T': (0, 0), 'init_G/C': (0, 0), 'init_allA/T': (0, -20.1), 'init_oneG/C': (0, -16.8), 'sym': (0, -1.3)}, 'DNA_NN2': {'AA/TT': (-8.0, -21.9), 'AT/TA': (-5.6, -15.2), 'CA/GT': (-8.2, -21.0), 'CG/GC': (-11.8, -29.0), 'CT/GA': (-6.6, -16.4), 'GA/CT': (-8.8, -23.5), 'GC/CG': (-10.5, -26.4), 'GG/CC': (-10.9, -28.4), 'GT/CA': (-9.4, -25.5), 'TA/AT': (-6.6, -18.4), 'init': (0.6, -9.0), 'init_5T/A': (0, 0), 'init_A/T': (0, 0), 'init_G/C': (0, 0), 'init_allA/T': (0, 0), 'init_oneG/C': (0, 0), 'sym': (0, -1.4)}, 'DNA_NN3': {'AA/TT': (-7.9, -22.2), 'AT/TA': (-7.2, -20.4), 'CA/GT': (-8.5, -22.7), 'CG/GC': (-10.6, -27.2), 'CT/GA': (-7.8, -21.0), 'GA/CT': (-8.2, -22.2), 'GC/CG': (-9.8, -24.4), 'GG/CC': (-8.0, -19.9), 'GT/CA': (-8.4, -22.4), 'TA/AT': (-7.2, -21.3), 'init': (0, 0), 'init_5T/A': (0, 0), 'init_A/T': (2.3, 4.1), 'init_G/C': (0.1, -2.8), 'init_allA/T': (0, 0), 'init_oneG/C': (0, 0), 'sym': (0, -1.4)}, 'DNA_NN4': {'AA/TT': (-7.6, -21.3), 'AT/TA': (-7.2, -20.4), 'CA/GT': (-8.5, -22.7), 'CG/GC': (-10.6, -27.2), 'CT/GA': (-7.8, -21.0), 'GA/CT': (-8.2, -22.2), 'GC/CG': (-9.8, -24.4), 'GG/CC': (-8.0, -19.9), 'GT/CA': (-8.4, -22.4), 'TA/AT': (-7.2, -21.3), 'init': (0.2, -5.7), 'init_5T/A': (0, 0), 'init_A/T': (2.2, 6.9), 'init_G/C': (0, 0), 'init_allA/T': (0, 0), 'init_oneG/C': (0, 0), 'sym': (0, -1.4)}, 'R_DNA_NN1': {'AA/TT': (-7.8, -21.9), 'AC/TG': (-5.9, -12.3), 'AG/TC': (-9.1, -23.5), 'AT/TA': (-8.3, -23.9), 'CA/GT': (-9.0, -26.1), 'CC/GG': (-9.3, -23.2), 'CG/GC': (-16.3, -47.1), 'CT/GA': (-7.0, -19.7), 'GA/CT': (-5.5, -13.5), 'GC/CG': (-8.0, -17.1), 'GG/CC': (-12.8, -31.9), 'GT/CA': (-7.8, -21.6), 'TA/AT': (-7.8, -23.2), 'TC/AG': (-8.6, -22.9), 'TG/AC': (-10.4, -28.4), 'TT/AA': (-11.5, -36.4), 'init': (1.9, -3.9), 'init_5T/A': (0, 0), 'init_A/T': (0, 0), 'init_G/C': (0, 0), 'init_allA/T': (0, 0), 'init_oneG/C': (0, 0), 'sym': (0, 0)}}#
Parameter sets by name.
- tm_dna_dna(sequence, na_mm=50.0, strand_nm=250.0, table='DNA_NN4')[source]#
Melting temperature (Celsius) of a DNA oligonucleotide annealed to its perfect complement.
Both strands are assumed to be at the same concentration (for instance a primer and its template).
- Parameters:
sequence -- DNA sequence, 5' to 3'.
na_mm -- monovalent cation concentration in mM.
strand_nm -- concentration of each strand in nM.
table -- DNA/DNA parameter set,
"DNA_NN1"to"DNA_NN4"(default: SantaLucia and Hicks, 2004).
- Raises:
ValueError -- if the sequence contains other characters than A, C, G, T.
>>> from sequana.melting import tm_dna_dna >>> round(tm_dna_dna("CGTTGACGTAGCTAGCATCG"), 1) 56.3
- tm_nn(target, na_mm=50.0, probe_nm=250.0, target_nm=0.0, table='R_DNA_NN1', self_complementary=None)[source]#
Melting temperature (Celsius) of a perfectly matched duplex, nearest-neighbour model.
The duplex is made of
targetand its complement (the probe). For RNA/DNA hybrids the target is the RNA.- Parameters:
target -- sequence, 5' to 3', made of A, C, G and T (write U as T).
na_mm -- monovalent cation concentration in mM.
probe_nm -- concentration of the probe (higher concentrated strand) in nM.
target_nm -- concentration of the target (lower concentrated strand) in nM. 0 means a probe in large excess; the two strands are at equal concentration when
target_nm == probe_nm.table -- name of a parameter set of
TABLESor a dictionary with the same structure.self_complementary -- whether the sequence is self-complementary (palindromic). Detected from the sequence when None.
- Returns:
the melting temperature in Celsius.
- Raises:
ValueError -- if the sequence is shorter than 2 bases or contains other characters than A, C, G, T.
>>> from sequana.melting import tm_nn >>> round(tm_nn("GCGCGCGCGCGCGCGCGCGCGCGC", na_mm=100, probe_nm=1000), 1) 80.0 >>> round(tm_nn("CGTTGACGTAGCTAGCATCG", table="DNA_NN4", na_mm=50, probe_nm=250, target_nm=250), 1) 56.3
- tm_probe_rna_dna(probe, na_mm=100.0, probe_nm=1000.0)[source]#
Melting temperature (Celsius) of a DNA probe bound to its complementary RNA target.
Uses the RNA/DNA hybrid parameters of Sugimoto et al. (1995). The probe is assumed to be in large excess over the target.
- Parameters:
probe -- DNA probe sequence, 5' to 3'. The RNA target is its reverse complement.
na_mm -- monovalent cation concentration in mM.
probe_nm -- concentration of the probe in nM.
- Raises:
ValueError -- if the probe contains other characters than A, C, G, T.
>>> from sequana.melting import tm_probe_rna_dna >>> round(tm_probe_rna_dna("AGCCCTCATTCTTTACGAAGCCCAGCGTCAGCGG"), 1) 76.4
Regulatory / regulatory-adjacent#
- class ConsensusBuilder(df)[source]#
- all_consensus(threshold=0.25, relative=0.8, strong=0.6, majority=0.5, info_threshold=1.0, notation='iupac')[source]#
- get_consensus(mode='majority', threshold=0.25, relative=0.8, strong=0.6, majority=0.5, info_threshold=1.0, notation='iupac')[source]#
- Parameters:
- modestr
majority | threshold | relative | information | max_only
- thresholdfloat
used in threshold mode
- relativefloat
keep bases >= relative * max_frequency
- strongfloat
uppercase if max >= strong
- info_thresholdfloat
uppercase if information >= this value
- notationstr
how to encode ambiguous positions:
iupac(single ambiguity code, e.g.R) orexpanded(slash-joined bases, e.g.A/G)
- get_consensus_cavener(notation='iupac')[source]#
Consensus following the Cavener (1987) rule.
For each position:
if a single nucleotide exceeds 50% frequency and is more than twice as frequent as the next one, it is reported as a capital letter;
otherwise, if the two most frequent nucleotides have a combined frequency above 75%, a co-consensus is reported as the uppercase encoding of that pair;
otherwise the most frequent nucleotide is reported as a lowercase letter.
- Parameters:
notation -- how to encode the co-consensus pair:
iupac(single ambiguity code, e.g.R) orexpanded(slash-joined bases, e.g.A/G, as in the original Cavener notation).
>>> import pandas as pd >>> from sequana.kozak import ConsensusBuilder >>> df = pd.DataFrame({ ... "A": [0.90, 0.45, 0.30, 0.55, 0.10], ... "C": [0.04, 0.40, 0.30, 0.20, 0.10], ... "G": [0.03, 0.10, 0.30, 0.15, 0.70], ... "T": [0.03, 0.05, 0.10, 0.10, 0.10], ... }) >>> cb = ConsensusBuilder(df) >>> cb.get_consensus_cavener() 'AMaAG' >>> cb.get_consensus_cavener(notation="expanded") 'AA/CaAG'
Position 1 (A=0.90) is a capital because A exceeds 50% and is more than twice the next base. Position 2 (A=0.45, C=0.40) is a co-consensus (combined 0.85 > 75%). Position 3 (A=C=G=0.30) is lowercase. Position 5 (G=0.70) is a capital again.
Reference: Cavener DR (1987), Nucleic Acids Research 15(4):1353-1361.
- class KLAnalysis(df)[source]#
- class Kozak("fasta", "gff", feature="gene")[source]#
Filter only to keep ATG since others seems to ncRNA
raw Kozak sequence names and counts
a Kozak is e.g GGCRGG . first position is the less important
for the enumeration of kmers, get of the rid of the Ns
- odds ratio have 4 cases depending on the on enumeration:
use entire genome use chromosome by chromosome use of gene on genome use gene on chromosomes
Table of counts of Kozak sequences without dna ambiguities. - across the entire genome - by chromosomes
counts = k.get_all_kmer_counts() counts_chroms = k.get_all_kmer_counts_by_chromosome() counts_genes = k.get_all_kmer_counts_genes_only()
# proportions of kmer in genes: sum(list(counts_genes.values())) / length_genome
# counts in chroms should equal counts in genomes: Sgenes = sum([sum(list(counts_chroms[x].values())) for x in counts_chroms.keys()]) Sgenome = sum(list(counts.values()))
k = Kozak("ecoli_MG1655.fa", "ecoli_MG1655.gff", "gene", "ID") df = k.get_data() k.plot_logo(df.query("start_codon=='ATG'"))
- bootstrap(df, contexts, n_boot=500, ci=95, sample_size=200)[source]#
Perform bootstrapping to compute confidence intervals for KL divergence.
- property collapse_first_cds#
- property genetic_type#
- get_random_contexts(Nmax=None, quiet=True)[source]#
Return a background distribution of Kozak contexts.
- property include_start_codon#
- property keep_ATG_only#
- kl_vs_random_atg(motif_df, random_df)[source]#
Compute position-wise divergence using Kullback–Leibler (KL) divergence between Kozak contexts and random (non-annotated) ATG contexts.
This quantifies how specific the Kozak signal is compared to generic ATG neighborhoods.
Compute positional KL divergence between the observed Kozak motif and a background nucleotide distribution.
This method computes, for each position i:
D_KL(P_i || Q) = sum_i (P_i x log2(P_i / Q_i))
where P_i is the observed nucleotide frequency distribution at position i, and Q is a fixed background distribution.
- Parameters:
- motif_dfpandas.DataFrame
DataFrame with columns ['A', 'C', 'G', 'T'] containing nucleotide frequencies per position.
- random_dfpandas.DataFrame
Background distribution.
- Returns:
- numpy.ndarray
KL divergence (bits) for each motif position.
Notes
This quantity is mathematically related to Shannon entropy.
When Q is uniform, this is equivalent to classical sequence logo information content.
The result is deterministic for a given motif_df and random_df input pair
- property left_kozak#
- plot_kozak_chi2(motif=None, GC_mode=None, fontsize=10, noplot=False)[source]#
- for GC computation, 2 options:
genomic ATG background excluding annotated starts. Good for GC bias, codon bias, local sequence structure.
- genome wide base composition. simple and fast but inflates signal in GC biases genomes. does not control for ATG specific context. This is a simple a genome-wide background is estimated assuming strand symmetry:
G = C = GC / 2 A = T = AT / 2
- plot_logo_bits(df=None, ax=None, color_scheme='colorblind')[source]#
Plot sequence logo with letter heights scaled by information content (bits).
Unlike
plot_logo()which shows relative nucleotide frequencies with uniform column heights, this method scales each column by its information content (IC = 2 - Shannon entropy), so highly conserved positions appear tall (up to 2 bits) and variable positions appear short.- Parameters:
df -- output of
get_data(). If None,get_data()is called.ax -- matplotlib axes object. If None, the current axes is used.
color_scheme --
"colorblind"(default) or"classic".
- Returns:
the probability logo_data DataFrame (same as
plot_logo()).
- plot_logo_purine_pyrimidine(df=None, ax=None)[source]#
df is the output of
get_data()
- property right_kozak#
- set_context(left_kozak=6, right_kozak=6, keep_ATG_only=True, include_start_codon=False, background_method='context', collapse_first_cds=True)[source]#
Configure context windows and feature-row collapsing.
- Parameters:
left_kozak (int) -- number of nucleotides to keep upstream of the start codon.
right_kozak (int) -- number of nucleotides to keep downstream of the start codon.
keep_ATG_only (bool) -- if True, restrict downstream analyses to rows whose start codon is
ATG.include_start_codon (bool) -- include the start codon itself in the Kozak window when True.
background_method (str) -- one of
"context","shuffled", or"uniform".collapse_first_cds (bool) -- when True (default), collapse multi-exon CDS rows to one row per transcript (the 5'-most CDS, which is the only CDS row corresponding to a real start codon). See
_collapse_to_first_cds()for rationale. Set to False to recover the legacy behaviour where every CDS row is treated as a separate start (useful for benchmarking the bug fix).
- class KozakAddon(*args, **kwargs)[source]#
-
- property df#
- find_kmers(sequence, pattern='GCC[AG]CC')[source]#
>>> k.find_kmers("GCCACC") True >>> k.find_kmers("AAAAAA") False
- class KozakWeightScore(weight_matrix=None, left_flank=10, right_flank=10)[source]#
Compute Kozak Similarity Score using weight matrix approach.
Weight-matrix based scoring for translation initiation prediction. Implements the algorithm from https://journals.plos.org/plosone/article?id=10.1371/journal.pone.0256411
Flexible left/right flank parameters allow custom window sizes.
Example:
from sequana.kozak import KozakWeightScore kss = KozakWeightScore(left_flank=10, right_flank=10) score = kss.score("CGCCGCCACCATGGCGGCGGAGG")
Initialize weight-based scorer.
- Parameters:
- weight_matrixnp.ndarray, optional
Shape (n_positions, 5) where columns: A, T, G, C, N. Default: canonical ATG 23bp matrix.
- left_flankint, default 10
Bases upstream of codon.
- right_flankint, default 10
Bases downstream of codon.
- class Motif(motif)[source]#
- property entropy#
Compute Shannon entropy for each position in the motif.
Shannon Entropy H(p) = -sum(p * log_base(p)) for DNA (4-letter alphabet).
- Parameters:
base -- the base of the logarithm. Common values: 2 (bits, default), e (nats), 10 (bans).
- Returns:
numpy array of entropy values per position.
- property information_content#
Compute information content (bits) for each position in the motif.
Information Content (IC) = max_entropy - Shannon_entropy = 2 - H(p) for DNA (4-letter alphabet).
- Parameters:
base -- the base of the logarithm. Common values: 2 (bits, default), e (nats), 10 (bans).
- Returns:
numpy array of information content values per position.
- classify_kozak_strength(motif, left=6)[source]#
Classify a Kozak consensus motif as optimal, strong, adequate or weak.
The tiers follow Meijer and Thomas (2002), Biochem J, doi:10.1042/bj20011706. The two key nucleotides are a purine (
R= A/G) at the -3 position and aGat the +4 position (the base just after the ATG codon). U is treated as T. The 6 upstream positions (-6..-1) plus the +4 position are compared, the ATG codon being fixed:GCCRCC-AUG-G->"optimal"(full optimal context, both key nucleotides present);NNNRNN-AUG-G->"strong"(both key nucleotides present);NNNRNN-AUG-(A/C/U) orNNN(C/U)NN-AUG-G->"adequate"(only one of the two key nucleotides present; termed"moderate"in Hernandez et al. 2019, Cell);NNN(C/U)NN-AUG-(A/C/U) ->"weak"(both key nucleotides absent).
- Parameters:
motif (str) -- a Kozak motif. The ATG start codon is located automatically (first
ATGsubstring); if absent,leftis used as the number of upstream positions and the motif is assumed to be the 6 upstream bases immediately followed by the +4 base (no ATG codon).left (int) -- number of upstream positions when no ATG is found.
- Returns:
one of
"optimal","strong","adequate"or"weak".
>>> from sequana.kozak import classify_kozak_strength >>> classify_kozak_strength("GCCRCCATGG") 'optimal' >>> classify_kozak_strength("AAARAAATGG") 'strong' >>> classify_kozak_strength("AAACAAATGG") 'adequate' >>> classify_kozak_strength("AAACAAATGA") 'weak'
- kozak_weight_score(sequence, weight_matrix=None, left_flank=10, right_flank=10)[source]#
Quick-score function (convenience wrapper).
- Parameters:
- sequencestr
DNA sequence centered on codon.
- weight_matrixnp.ndarray, optional
Weight matrix. Uses default ATG if None.
- left_flankint, default 10
- right_flankint, default 10
- Returns:
- float
Normalized KSS [0, 1].
- class TelomerFilter(filename, pattern='AACCCT', threshold=0.8)[source]#
Filter reads based on telomeric repeat content.
- Parameters:
- save_non_telomeric_reads(output_filename='non_telomeric.fastq', progress=True)[source]#
Save non-telomeric reads to a file.
- class Telomere(reference_file=None, peak_height=20, peak_width=50)[source]#
Scan a FASTA file and identify the extent of telomeric regions.
Basic usage:
from sequana.telomere import Telomere telo = Telomere("ref.fa") df = telo.run(tag="myrun")
run()processes every contig, writes per-contig PNG plots and a CSV summary, and returns a DataFrame with one row per contig.Identifying the right k-mers
By default the scanner uses all six rotations of the canonical vertebrate telomere repeat
AACCCTplus additional 6-mers that improve signal-to-noise. To discover organism-specific k-mers:contig = telo.fasta.sequences[0] candidates = telo.find_representative_kmers(contig, kmers=6) telo.kmers = [k for k, _ in candidates]
Sliding-window counts
The two core signals used for peak detection:
XX = telo.get_sliding_kmer_count_five_to_three_prime(seq) YY = telo.get_sliding_kmer_count_three_to_five_prime(seq)
A telomere on a correctly oriented contig will appear as a peak at the left of
XX(LHS) and a peak at the right ofYY(RHS). Any peak at the opposite end indicates a reversed/mis-oriented contig.Plotting
Two plot styles are available through the plot_style argument of
run():'annotated'(default)Per-contig:
plot_contig()— single panel, both strand signals overlaid with colour-coded shaded telomere regions and a status badge. Reversed telomeres are highlighted in red.Summary:
plot_summary()— horizontal chromosome map with each contig drawn proportionally to its length, telomere blocks coloured by orientation, and per-row status badges.'legacy'Original two-subplot raw signals (per-contig) and two heatmaps (binary presence + length, summary).
Telomere categories
Each contig in the output DataFrame is assigned a
telomerecolumn:completeBoth LHS (forward) and RHS (reverse-complement) detected.
LHS_onlyOnly the left-hand telomere detected.
RHS_onlyOnly the right-hand telomere detected.
noneNo telomeric signal above threshold.
Reversed peaks (signal on the unexpected end) are flagged by
run()vialoggingwarnings and highlighted in red in the annotated plots.Initialize the Telomere scanner.
- Parameters:
reference_file -- path to a FASTA file.
peak_height -- minimum peak height for telomere peak detection.
peak_width -- minimum peak width for telomere peak detection.
- find_representative_kmers(seq, N=100000, pocc=0.005, n_sigma=5, kmers=6)[source]#
Identify over-represented k-mers in the first N bases of seq.
The probability of occurrence threshold pocc works well for ~100,000 bases. For shorter sequences the threshold may need to be adjusted.
Note
The fitted beta distribution used for plotting is estimated from a Leishmania genome and may not be appropriate for other organisms.
- get_sliding_kmer_count_five_to_three_prime(seq, W=100)[source]#
Return sliding kmer counts in the 5' → 3' direction.
- get_sliding_kmer_count_three_to_five_prime(seq, W=100)[source]#
Return sliding kmer counts in the 3' → 5' direction.
- plot_contig(XX, YY, chrom, total_length, midpoint, lhs1, rhs1, lhs1_extend, rhs1_extend, lhs2, rhs2, lhs2_extend, rhs2_extend)[source]#
Produce an annotated per-contig telomere figure.
Both sliding-kmer-count signals are shown overlaid in a single panel:
Blue line / shading: 5'→3' signal; telomere expected at the left (LHS). A signal at the right (RHS) indicates a reversed orientation and is highlighted in red.
Orange line / shading: 3'→5' signal; telomere expected at the right (RHS). A signal at the left (LHS) is reversed and shown in red.
A vertical grey bar marks the midpoint when the sequence was trimmed to Nmax. The title carries a status badge (COMPLETE / LHS only / RHS only / NONE).
- Parameters:
XX -- 5'→3' sliding kmer count array.
YY -- 3'→5' sliding kmer count array.
chrom -- contig/chromosome name.
total_length -- original full sequence length in bp.
midpoint -- index of the midpoint cut (0 means no trimming).
lhs1 -- LHS telomere boundary position from XX.
rhs1 -- RHS telomere boundary position from XX.
lhs1_extend -- LHS telomere length from XX.
rhs1_extend -- RHS telomere length from XX.
lhs2 -- LHS telomere boundary position from YY.
rhs2 -- RHS telomere boundary position from YY.
lhs2_extend -- LHS telomere length from YY.
rhs2_extend -- RHS telomere length from YY.
- plot_summary(df)[source]#
Produce an annotated genome-wide telomere summary figure.
Each contig is drawn as a horizontal bar scaled to its length (so longer chromosomes appear wider). Telomeric blocks are overlaid at the appropriate ends:
Blue: LHS telomere (5'→3', expected orientation)
Orange: RHS telomere (3'→5', expected orientation)
Red: Reversed telomere (unexpected end)
A coloured status badge on the right of each row indicates:
COMPLETE(green),LHS only(blue),RHS only(orange),NONE(grey), or⚠ REVERSED(red).Contigs are sorted by descending length so the largest chromosomes appear at the top.
- Parameters:
df -- DataFrame returned by
run().- Returns:
matplotlib Figure.
- run(tag, names=None, W=100, Nmax=100000, plot_style='annotated')[source]#
Run telomere detection across all (or selected) contigs.
- Parameters:
tag -- output filename prefix (
Nonesuppresses file output).names -- list of chromosome/contig names to process; defaults to all.
W -- sliding window half-width in bp.
Nmax -- maximum bp to examine at each end of the contig.
plot_style --
'annotated'(default) usesplot_contig()which overlays both strand signals with colour-coded telomeric regions and a status badge;'legacy'reproduces the original two-subplot raw output.
- circular_shifts(sequence)[source]#
Return all circular shifts of sequence as an ordered list.
For example,
circular_shifts("AACCCT")returns all 6 rotations of the string. Useful for kmer-based analyses where all phases of a repeat unit must be considered.
- CpG(sequence, window=200)[source]#
The Sequence Manipulation Suite: CpG Islands Results for 1200 residue sequence "sample sequence" starting "taacatactt". CpG islands search using window size of 200. Range, value 32 to 231, the y-value is 1.75 and the %GC content is 50.5 33 to 232, the y-value is 1.75 and the %GC content is 50.5
Gardiner-Garden M, Frommer M. J Mol Biol. 1987 Jul 20;196(2):261-82.
- find_restriction_sites(sequence, enzymes)[source]#
Find restriction sites in a DNA sequence.
- Args:
sequence (str): The DNA sequence. enzymes (dict): Dictionary of enzyme names and recognition sequences.
- Returns:
dict: A dictionary with enzyme names as keys and lists of start positions as values.
Non-B DNA / motif detection#
- class G4Hunter(fastafile, window=25, score=1)[source]#
This is an implementation of G4hunter that is 1-2 fold faster
Idea to speed up 50% is to use numba.
- class Cruciforms(fasta_file, min_stem_len=6, max_stem_len=115, min_spacer=0, max_spacer=100, short_spacer_max=4, min_stem_len_long=10)[source]#
Detect inverted repeats (cruciform-forming motifs).
An inverted repeat is two arms that are reverse-complements of each other, optionally separated by a spacer (loop):
5'- ARM ----- spacer ----- revcomp(ARM) -3'
This mirrors the Inverted_Repeat output of the non-B gfa / nBMST tool (
gfa_IR.gff). Differences from a naive adjacent-arm scan:a spacer (loop) between the two arms is allowed (
min_spacer..max_spacer); gfa default is 0..100,for every (gap, spacer) center the maximal stem is reported instead of one hit per stem length, avoiding nested-register duplicates,
hits fully contained in a longer hit are kept but flagged (
subset=1), matching gfa'ssubsetattribute. Setinclude_subsets=Falseto drop them.
gfa couples the loop and arm lengths: a short loop tolerates a short arm, a long loop requires a long arm. The two-tier default is reproduced here: spacer <=
short_spacer_max(4) needs stem >=min_stem_len(6), otherwise stem >=min_stem_len_long(10).Validated against gfa on a 30+ Mb Leishmania assembly: 57,702 non-subset inverted repeats vs gfa's 57,740 (0.07% difference), with 100% reciprocal positional overlap on a test slice. With the numba kernel the whole genome is processed in ~25 s.
- Parameters:
fasta_file -- input FASTA.
min_stem_len -- minimum arm length for short loops (gfa default 6).
max_stem_len -- maximum arm length (cap on stem extension).
min_spacer -- minimum loop length (gfa default 0).
max_spacer -- maximum loop length (gfa default 100).
short_spacer_max -- largest loop still allowed with
min_stem_len.min_stem_len_long -- minimum arm length once spacer > short_spacer_max.
Note
cost scales as
len(genome) * (max_spacer + 1). For a whole genome lowermax_spaceror run per-chromosome if too slow.- run(include_subsets=True, progress=True, processes=None)[source]#
Scan every sequence for inverted repeats.
Uses a numba-compiled kernel when numba is installed, otherwise a numpy-vectorised fallback. Sequences are independent, so the scan is spread over
processesworkers (None= all CPUs;1= serial).
Detect mirror repeats.
A mirror repeat is two arms that read the same forwards and backwards across a central axis (the right arm is the reverse of the left arm, NOT the reverse complement — that would be an inverted repeat / cruciform), optionally separated by a spacer:
5'- ARM ----- spacer ----- reverse(ARM) -3'
This reproduces the Mirror_Repeat output of the non-B gfa / nBMST tool
(gfa_MR.gff). The homopurine / homopyrimidine subset of mirror repeats forms
H-DNA (triplex); see sequana.hdna.HDNA.
gfa defaults (from print_usage.c): arm (repeat) >= 10, spacer 0..100.
Maximal arms are reported; hits fully contained in a longer hit are kept but
flagged (subset=1); include_subsets=False drops them.
Validated against gfa on a 30+ Mb Leishmania assembly: all 22254 gfa mirror repeats are recovered (100% positional overlap), density within ~2% (22704 vs 22254). The numba kernel processes the whole genome in a few seconds.
- class MirrorRepeats(fasta_file, min_repeat=10, max_repeat=200, min_spacer=0, max_spacer=100)[source]#
Detect mirror repeats like gfa
gfa_MR.gff.- Parameters:
fasta_file -- input FASTA.
min_repeat -- minimum arm length (gfa default 10).
max_repeat -- maximum arm length (cap on arm extension).
min_spacer -- minimum loop length (gfa default 0).
max_spacer -- maximum loop length (gfa default 100).
Detect intramolecular triplex (H-DNA) forming motifs.
H-DNA forms at mirror repeats whose strands are homopurine or
homopyrimidine. This reproduces the Triplex output of the non-B gfa / nBMST
tool (gfa_TPX.gff).
A motif is:
5'- ARM ----- spacer ----- mirror(ARM) -3'
where mirror(ARM) is the arm read backwards (same bases, not the
reverse complement, unlike a cruciform/inverted repeat), and the whole motif
(both arms + spacer) is 100% purine (A/G) or 100% pyrimidine (C/T).
gfa gfa_TPX.gff defaults, reverse-engineered from its output, are
reproduced here: arm (repeat) >= 10, spacer 0..8, and each arm is allowed up to
10% impurities (impure * 10 <= arm_length) judged on the arm only, not the
spacer. Every gfa Triplex is also a gfa Mirror_Repeat; the triplex set is the
homopurine / homopyrimidine subset of mirror repeats.
Validated against gfa on a 30+ Mb Leishmania assembly (gfa_TPX.gff): all
1746 gfa Triplex loci are recovered (100% positional overlap), with density
within ~6% (1859 vs 1746). The numba kernel processes the whole genome in ~4 s.
- class HDNA(fasta_file, min_repeat=10, max_repeat=100, min_spacer=0, max_spacer=8)[source]#
Detect H-DNA (intramolecular triplex) forming mirror repeats.
- Parameters:
fasta_file -- input FASTA.
min_repeat -- minimum arm length (gfa Triplex default 10).
max_repeat -- maximum arm length (cap on arm extension).
min_spacer -- minimum loop length (gfa default 0).
max_spacer -- maximum loop length (gfa default 8).
Hits fully contained in a longer hit are kept but flagged (
subset=1), matching gfa'ssubsetattribute;include_subsets=Falsedrops them.
Detect A-phased repeats (intrinsically bent DNA).
A-phased repeats are clusters of short A-tracts (runs of A/T) repeated in phase
with the ~10.5 bp helical period, which bends the double helix. This reproduces
the A_Phased_Repeat output of the non-B gfa / nBMST tool (gfa_APR.gff),
ported from its findAPR.c / getAtracts routines.
Algorithm (gfa defaults shown):
A-tracts — every maximal run of A/T whose length is in
[min_tract_len, max_tract_len]=[3, 9]. A run is a valid A-tract when, on the forward or reverse-complement strand, the longest A / AnTn pattern minus the longest pure-T run is>= min_tract_len. Each tract is summarised by the centre of its longest A-run.Phasing — consecutive tract centres separated by
[min_sep, max_sep](gfa uses 9.9..11.1, i.e. ~10 bp) are chained; a chain of at leastmin_tracts(3) tracts is reported as one A-phased repeat.
Validated against gfa on a 30+ Mb Leishmania assembly: identical count (889)
and 100% reciprocal positional overlap with gfa_APR.gff.
- class APhasedRepeats(fasta_file, min_tract_len=3, max_tract_len=9, min_tracts=3, min_sep=9.9, max_sep=11.1)[source]#
Detect A-phased repeats (bent DNA) like gfa
gfa_APR.gff.- Parameters:
fasta_file -- input FASTA.
min_tract_len -- minimum A-tract (A/T run) length (gfa default 3).
max_tract_len -- maximum A-tract length (gfa default 9).
min_tracts -- minimum number of phased tracts (gfa default 3).
min_sep -- minimum centre-to-centre tract separation (gfa 9.9).
max_sep -- maximum centre-to-centre tract separation (gfa 11.1).
Detect short tandem repeats (STR / microsatellites).
A short tandem repeat is a short unit (period 1..9 bp) repeated head-to-tail at
least min_reps times, spanning at least min_span bp (including a partial
trailing copy). This reproduces the Short_Tandem_Repeat output of the non-B
gfa / nBMST tool (gfa_STR.gff), ported faithfully from its findSTR.c.
gfa defaults (from gfa.c): period 1..9, min_reps 3, min_span 10. For each
start position the smallest period giving a qualifying repeat is taken, then the
scan jumps past it; a new STR is kept only if it ends beyond the previous one.
The type attribute is gfa's nonBstr structural code, a 4-bit value
8*isComplementary + 4*isSymmetric + 2*isAlternatingRY + 1*isEven describing
which non-B structure the unit can adopt.
Validated against gfa on a 30+ Mb Leishmania assembly: identical coordinates and identical length/num/remainder/type attributes (exact match).
- class ShortTandemRepeats(fasta_file, min_period=1, max_period=9, min_span=10, min_reps=3)[source]#
Detect short tandem repeats (microsatellites) like gfa
gfa_STR.gff.- Parameters:
fasta_file -- input FASTA.
min_period -- minimum repeat-unit length (gfa default 1).
max_period -- maximum repeat-unit length (gfa default 9).
min_span -- minimum total span in bp (gfa default 10).
min_reps -- minimum number of full copies (gfa default 3).
Detect Z-DNA forming motifs (alternating purine/pyrimidine runs).
Z-DNA is favoured by runs of alternating purine/pyrimidine dinucleotides,
specifically CG/GC (strong) and CA/TG/AC/GT (weak); TA/AT are
excluded. This reproduces the Z_DNA_Motif output of the non-B gfa / nBMST
tool (gfa_Z.gff), ported faithfully from its findZDNA.c.
Each valid dinucleotide contributes to a Kadane/Vasquez (KV) style score
(CG/GC = 25, the weak ones = 3). A run of at least min_z consecutive
alternating bases is reported with score = sum_of_dinucleotide_scores // 2.
A motif is flagged subset=1 when its score reaches min_kvscore (33).
gfa defaults (from gfa.c): min_z = 10, min_kvscore = 33 (the comment in
gfa's is_subset.c saying 35 is stale; gfa.c uses 33).
Validated against gfa on a 30+ Mb Leishmania assembly: identical coordinates,
length, score and subset for all 60076 motifs. The only field that differs is
composition because gfa counts bases over [start, end-1) (an off-by-one
that drops the last base); this module counts the full motif, so its A/C/G/T
counts are the correct ones and match the reported sequence.
- class ZDNA(fasta_file, min_z=10, min_kvscore=33)[source]#
Detect Z-DNA forming motifs like gfa
gfa_Z.gff.- Parameters:
fasta_file -- input FASTA.
min_z -- minimum run length in bp (gfa default 10).
min_kvscore -- KV score threshold for the
subsetflag (gfa default 33); a motif withscore >= min_kvscoregetssubset=1.
Detect G-quadruplex forming motifs.
A G-quadruplex (G4) forms where four or more runs of guanines (G-islands,
each at least min_rep bp) sit close together (separated by loops of at most
max_spacer bp). This reproduces the G_Quadruplex_Motif output of the
non-B gfa / nBMST tool (gfa_GQ.gff), ported faithfully from its
findGQ.c / getGislands.
Both strands are scanned: runs of G give plus-strand motifs, runs of C
give minus-strand motifs (the reported sequence is then the reverse complement,
i.e. G-rich). For each motif gfa reports:
islands: number of merged G-islands (conIls),runs: how many minimal (min_rep) runs fit across the islands (npos, must be >= 4),max: the largest run size for which at least 4 runs still fit.
gfa defaults (from gfa.c): min_rep = 3, max_spacer = 7.
Validated against gfa on a 30+ Mb Leishmania assembly: identical coordinates,
strand, islands/runs/max attributes. As for Z-DNA, the only field that differs
is composition because gfa's printer counts bases over [start, end-1)
(an off-by-one dropping the last base); this module counts the full motif, so
its A/C/G/T counts are correct and match the reported sequence.
- class GQuadruplex(fasta_file, min_rep=3, max_spacer=7)[source]#
Detect G-quadruplex forming motifs like gfa
gfa_GQ.gff.- Parameters:
fasta_file -- input FASTA.
min_rep -- minimum guanine run length / G-island size (gfa default 3).
max_spacer -- maximum loop length between islands (gfa default 7).
Detect direct (and slipped / tandem) repeats.
A direct repeat is two identical arms in the same orientation, optionally separated by a spacer:
5'- ARM ----- spacer ----- ARM -3'
When the spacer is zero the arm is extended into a big tandem repeat (BTR).
This reproduces the Direct_Repeat output of the non-B gfa / nBMST tool
(gfa_DR.gff), ported faithfully from its findDR.c.
gfa defaults (from gfa.c): min arm 10, max arm 300, spacer 0..10 (the usage
text saying spacer 100 is stale; gfa.c uses 10). The search is greedy: for
each start it tries the largest arm first and the smallest qualifying spacer,
records the first full match, and skips ahead so successive repeats must extend
beyond the previous one (the end escape variable in gfa).
A motif is flagged subset=1 (gfa's "slipped" set) when its spacer is 0.
Validated against the gfa binary compiled from source on a 30+ Mb Leishmania assembly: identical coordinates and attributes.
- class DirectRepeats(fasta_file, min_repeat=10, max_repeat=300, max_spacer=10)[source]#
Detect direct/slipped repeats like gfa
gfa_DR.gff.- Parameters:
fasta_file -- input FASTA.
min_repeat -- minimum arm length (gfa default 10).
max_repeat -- maximum arm length (gfa default 300).
max_spacer -- maximum spacer between arms (gfa default 10).
Find exact repeats in a genome using the shustring tool.
- class Repeats(filename_fasta, merge=False, name=None)[source]#
Class for finding repeats in DNA or RNA linear sequences.
Computation is performed each time the
thresholdis set to a new value.from sequana import sequana_data, Repeats rr = Repeats(sequana_data("measles.fa")) rr.threshold = 4 rr.hist_length_repeats()
Note
Works with shustring package from Bioconda (April 2017)
Todo
use a specific sequence (first one by default). Others can be selected by name
Constructor
Input must be a fasta file with valid DNA or RNA characters
- Parameters:
filename_fasta (str) -- a Fasta file, only the first sequence is used !
threshold (int) -- Minimal length of repeat to output
name (str) -- if name is provided, scan the Fasta file and select the corresponding sequence. if you want to analyse all sequences, you need to use a loop by setting _header for each sequence with the sequence name found in sequence header.
Note
known problems. Header with a > character (e.g. in the comment) are left strip and only the comments is kept. Another issue is for multi-fasta where one sequence is ignored (last or first ?)
- property begin_end_repeat_position#
- property df_shustring#
Return dataframe with shortest unique substring length at each position shortest unique substrings are unique in the sequence and its complement Uses shustring tool
- property do_merge#
- property header#
- hist_length_repeats(bins=20, alpha=0.5, hold=False, fontsize=12, grid=True, title='Repeat length', xlabel='Repeat length', ylabel='#', logy=True)[source]#
Plots histogram of the repeat lengths
- property length#
- property list_len_repeats#
- property longest_shustring#
- property names#
- property threshold#
Reverse-complement palindrome detection.
A DNA palindrome is a sequence equal to its own reverse complement (e.g.
GAATTC). Such palindromes always have an even length: the central base of
an odd-length window would have to be its own complement, which never happens
for A/C/G/T. Only even window sizes are therefore scanned.
i-motif (C-rich) secondary-structure detection.
An i-motif is the cytosine-rich counterpart of a G-quadruplex: four or more
runs of C (each at least min_tract bases) separated by short loops fold into
an intercalated structure. Detection is a single regular expression scan.
- class TRF(filename: str | Path, verbose: bool = False, frmt: str | None = None)[source]#
Tandem Repeat Finder utilities
The input data is the output of trf tool when using the -d option. This is not a CSV file. It contains comments in the middle of the file to indicate the name of the contig.
The output filename has the following filename convention:
test.fa.2.5.7.80.10.50.2000.dat
where the numbers indicate the 7 input parameters:
Match = matching weight
Mismatch = mismatching penalty
Delta = indel penalty
PM = match probability (whole number)
PI = indel probability (whole number)
Minscore = minimum alignment score to report
MaxPeriod = maximum period size to report
You may use
-hto suppress html output.Then, you can use this class to easly identify the pattern you want:
t = TRF("input.dat") query = "length>100 and period_size==3 and entropy>0 and C>20 and A>20 and G>20" t.df.query(query)
- hist_cnvs(bins=50, CNVmin=10, motif=None, color='r', log=True)[source]#
Plot histogram of CNV counts for a given motif list.
- class FindMotif("cl10/select1.sorted.bam") df=fm.find_motif("CAGCAG") df.query("hit>10")[source]#
local threshold should be window length divided by motif length divided by 2
- find_motif_bam(filename, motif, window=200, figure=False, savefig=False, local_threshold=None, global_threshold=None)[source]#
RNA structure & rRNA depletion#
Ribodesigner module
- class RiboDesigner(fasta, gff=None, output_directory='ribodesigner', seq_type='rRNA', max_n_probes=384, force=False, threads=4, identity_step=0.01, force_clustering=False, offtarget_fasta=None, **kwargs)[source]#
Design probes for ribosomes depletion.
From a complete genome assembly FASTA file and a GFF annotation file:
Extract genomic sequences corresponding to the selected
seq_type.For these selected sequences, design probes computing probe length and inter probe space according to the length of the ribosomale sequence.
Detect the highest cd-hit-est identity threshold where the number of probes is inferior or equal to
max_n_probes.Report the list of probes in BED and CSV files.
In the CSV, the oligo names are in column 1 and the oligo sequences in column 2.
- Parameters:
fasta -- The FASTA file with complete genome assembly to extract ribosome sequences from.
gff -- GFF annotation file of the genome assembly. If none provided, assuming the input FastA is already made of rRNA.
output_directory -- The path to the output directory defaults to ribodesigner.
seq_type -- string describing sequence annotation type (column 3 in GFF) to select rRNA from.
max_n_probes -- Max number of probes to design
force -- If the output_directory already exists, overwrite it.
threads -- Number of threads to use in cd-hit clustering.
identity_step (float) -- step to scan the sequence identity (between 0 and 1) defaults to 0.01.
force_clustering
offtarget_fasta -- FASTA file (e.g. the whole genome or transcriptome) used to search for probe off-target hits with blastn. Defaults to
fastawhen agffis provided (hits overlapping the selected rRNA features are then ignored). With no GFF, off-target search is only possible when a separateofftarget_fastais given.
- check_offtarget(min_identity=80, min_aligned=25, evalue=10)[source]#
Search probes with blastn against
offtarget_fastaand report hits outside the rRNA loci.Hits on both strands are considered: probes are designed on both strands, and the strand of the target is not known in advance, so this is conservative. Hits overlapping a selected rRNA feature are on-target and discarded.
Adds
n_offtarget(number of off-target hits) andbest_offtarget_identitytoself.probes_df, and writes all hits toofftarget_hits.csv.- Parameters:
min_identity -- minimum percent identity of a reported hit.
min_aligned -- minimum alignment length (bases) of a reported hit.
evalue -- blastn e-value cutoff (permissive by default because probes are short).
- clustering_needed(force=False)[source]#
Checks if a clustering is needed.
- Parameters:
force -- force clustering even if unecessary.
- compute_coverage()[source]#
Report how much of each rRNA sequence is covered by the probes.
Clustering merges similar probes (for instance the copies of a rRNA operon), so a probe removed at one position is still represented by a kept probe at another position. Two coverages are therefore reported for each sequence:
covered_designed_pct: positions spanned by at least one designed probe (before clustering), on both strands together (covered_plus_pct/covered_minus_pctfor each strand alone). This is the coverage of the final pool, since every removed probe is represented by a kept probe at leastmin_merged_identitypercent identical.covered_direct_pct: positions spanned by a probe kept at that position.
Gaps (stretches with no designed probe) are listed per sequence. Results go to
coverage.csvandjson["coverage"]. Probe coordinates are relative to the rRNA sequence as transcribed (seeget_rna_pos_from_gff()).
- compute_qc(gc_range=(0.3, 0.7), max_homopolymer=5, max_hairpin=8, max_selfdimer=10)[source]#
Add quality-control columns to
self.probes_df.Columns added:
length,gc,tm,max_homopolymer,hairpin_stem,selfdimer_stemandqc_flags(comma-separated list oflow_gc,high_gc,homopolymer,hairpin,selfdimer; empty when the probe passes).tmis the RNA:DNA nearest-neighbour Tm (see_tm_nn()). For a probe with ambiguous bases, for which the model is not defined, a salt-adjusted GC estimate is used instead (see_tm()); the number of such probes is stored injson["qc"]["n_tm_estimated"].hairpin_stemandselfdimer_stemare the longest self-complementary stretches (hairpins need a loop of at least 3 bases); they are sequence-only heuristics, not free-energy predictions.- Parameters:
gc_range -- (min, max) acceptable GC fraction.
max_homopolymer -- longest acceptable single-nucleotide run.
max_hairpin -- longest acceptable hairpin stem (bases).
max_selfdimer -- longest acceptable self-dimer stretch (bases).
- export_probes_report()[source]#
Write the full probes table (coordinates, QC, off-target, clustering status) to CSV.
- get_all_probes(method='greedy')[source]#
Run all probe design and concatenate results in a single DataFrame.
- get_rna_pos_from_gff()[source]#
Convert a GFF file into a pandas DataFrame filtered according to the self.seq_type.
- run(method='greedy', offtarget=False)[source]#
Run the whole design.
- Parameters:
method -- probe/step length scanning method (original, greedy, simple).
offtarget -- if True, search probes for off-target hits (requires blastn, see
check_offtarget()).
- TILING_METHODS = {'greedy': (<function _greedy_candidates>, True, True, 'generic'), 'original': (<function _original_candidates>, True, False, 'generic'), 'simple': (<function _simple_candidates>, False, True, 'simple')}#
Available methods. To add one, write a function yielding (probe_len, gap) pairs and register it here.
- class TilingMethod(candidates: Callable, exact_fit: bool, short_sequences: bool, probes_mode: str)[source]#
How the probe length and the gap between probes are chosen for a sequence.
Create new instance of TilingMethod(candidates, exact_fit, short_sequences, probes_mode)
- find_rrna_like_features(gff)[source]#
Select the rRNA features of a GFF table whose type is not (only)
rRNA.Use it when the annotation stores rRNA as
geneorncRNA_gene(with agene_biotype/biotypeof rRNA or a product/description such as "16S ribosomal RNA"), asmisc_RNA,ncRNAortranscript. Only RNA-like feature types are considered (see_RRNA_FEATURE_RANK), so that CDS or genes whose product mentions rRNA (e.g. rRNA methyltransferases) are not selected.When a gene and its transcript (or several annotations of the same region) are found, only the most specific one is kept, so that a rRNA is not counted twice.
- Parameters:
gff -- DataFrame with the 9 GFF columns (see
GFF_COLUMNS).- Returns:
the selected rows, sorted by position.
- find_tiling(seq_len, method='greedy')[source]#
Probe length and gap to tile a sequence of
seq_lenbases.For an exact fit, the first probe starts on the first base and the last one ends on the last base:
L = N * probe_len + (N - 1) * gapwithNan integer. The first pair of the method that fits is returned. Sequences below 50 bases get one 50 nt probe, and sequences below 100 bases get 40 nt probes spaced by 10 nt (one or two probes), whatever the method (exceptoriginal).- Parameters:
seq_len -- length of the sequence.
method -- one of
TILING_METHODS.
- Returns:
(probe_len, gap)
- Raises:
ValueError -- if the method is unknown or no pair fits.
>>> find_tiling(1542) (60, 18) >>> find_tiling(116, "greedy") (52, 12)
- is_rrna_attributes(text)[source]#
Tell whether GFF attributes describe a rRNA, from a biotype or from the product/description/name.
>>> is_rrna_attributes("ID=gene-rrn5S;gene=rrn5S;gene_biotype=rRNA") True >>> is_rrna_attributes("ID=rna-x;product=16S ribosomal RNA") True >>> is_rrna_attributes("ID=gene:b0051;biotype=protein_coding;description=16S rRNA dimethyltransferase") False
- parse_gff_attributes(text)[source]#
Return the attributes of a GFF3 (
key=value;...) or GTF (key "value";...) line as a dictionary.Keys are lower-cased and values are URL-decoded.
>>> parse_gff_attributes("ID=gene:rrsH;biotype=rRNA;description=16S%20ribosomal%20RNA")["description"] '16S ribosomal RNA'
Protein structures (3D)#
PDB (Protein Data Bank) file parsing and 3D structure handling.
- class Alignment(rmsd: float, rotation_matrix: ndarray, translation: ndarray, mobile_coords: ndarray)[source]#
Result of structure superposition.
- Attributes:
rmsd: RMSD after optimal alignment rotation_matrix: 3x3 rotation matrix applied translation: translation vector applied mobile_coords: aligned (rotated) coordinates of mobile structure
- class Atom(serial: int, name: str, residue_name: str, chain_id: str, residue_seq: int, x: float, y: float, z: float, occupancy: float = 1.0, bfactor: float = 0.0, element: str = '', charge: int = 0, insertion_code: str = '', is_hetatm: bool = False)[source]#
Single atom in 3D structure.
- Attributes:
serial: PDB atom serial number name: atom name (e.g., "CA", "CB") residue_name: parent residue name (e.g., "ALA") chain_id: parent chain identifier residue_seq: residue sequence number x, y, z: 3D coordinates occupancy: fractional occupancy bfactor: temperature factor (B-factor) element: element symbol (e.g., "C", "N", "O") charge: formal charge
- class Chain(chain_id: str, residues: List[Residue] = <factory>)[source]#
Single polypeptide chain.
- Attributes:
chain_id: chain identifier (A, B, etc.) residues: ordered list of residues
- align_to(other: Chain, atoms: str = 'CA') Alignment[source]#
Superpose this chain onto another using specified atoms.
- Args:
other: target chain to align to atoms: which atoms to use ("CA", "CB", "all", etc.)
- Returns:
Alignment object with RMSD and transformation
- bfactor_by_residue() Dict[int, float][source]#
Return mean B-factor per residue.
- Returns:
dict mapping residue seq number -> mean B-factor
- bfactor_stats() dict[source]#
Return B-factor statistics for chain.
- Returns:
dict with mean, min, max, std B-factors
- contact_map(distance: float = 5.0, atoms: str = 'CA') ndarray[source]#
Generate binary contact map (residue pairs within distance).
- Args:
distance: distance cutoff in Angstroms atoms: which atoms to use ("CA" or "CB")
- Returns:
NxN binary matrix where N=residue count
- find_neighbors(residue_seq: int, distance: float = 5.0) List[int][source]#
Find residues within distance (Angstroms) of specified residue.
Uses CA atoms for distance calculation.
- Args:
residue_seq: sequence number of query residue distance: distance cutoff in Angstroms
- Returns:
list of neighbor residue sequence numbers (sorted, excluding query)
- phi_psi_angles() Dict[int, Tuple[float | None, float | None]][source]#
Compute real backbone phi/psi dihedral angles per residue.
phi(i) = dihedral(C(i-1), N(i), CA(i), C(i)) psi(i) = dihedral(N(i), CA(i), C(i), N(i+1))
Both require the backbone N/CA/C atoms of the residue and its neighbour(s); phi is undefined for the first residue (no preceding C) and psi is undefined for the last residue (no following N).
- Returns:
dict mapping residue seq -> (phi, psi) in degrees, either value being None where undefined or backbone atoms are missing.
- secondary_structure_ramachandran() Dict[int, str][source]#
Classify residues into helix/sheet/coil from real backbone phi/psi angles.
Computes true phi/psi dihedral angles from the N/CA/C backbone atoms (see
phi_psi_angles()) and assigns each residue to a broad Ramachandran region:Alpha helix (right-handed): phi in [-100, -30], psi in [-77, 0]
Beta sheet / extended: phi in [-180, -45], psi in [45, 225] (mod 360)
Coil: everything else, termini, or missing backbone atoms
- Caveats (important -- read before trusting the output):
This is a geometric, single-residue phi/psi classifier. It is NOT equivalent to DSSP, which additionally uses backbone hydrogen bonding patterns and multi-residue context to assign secondary structure and is the field standard. Expect disagreement with DSSP especially at helix/sheet boundaries and for short or distorted secondary structure elements. Use this for a quick, dependency-free estimate; use a DSSP wrapper (e.g. via
mkdssp) for publication-grade secondary structure assignment.- Returns:
dict mapping residue seq -> 'H' (helix), 'E' (sheet), or 'C' (coil)
- class Model(model_id: int, chains: Dict[str, ~sequana.pdb.Chain]=<factory>)[source]#
Single model (NMR ensemble or cryo-EM map).
- Attributes:
model_id: model number (typically 1 for X-ray) chains: dict of chains indexed by chain_id
- class Residue(name: str, seq: int, chain_id: str, insertion_code: str = '', atoms: Dict[str, ~sequana.pdb.Atom]=<factory>)[source]#
Single amino acid or nucleotide residue.
- Attributes:
name: residue name (e.g., "ALA", "GUA") seq: sequence number in chain chain_id: parent chain identifier atoms: dict of atoms indexed by atom name
- class Structure(pdb_id: str, title: str = '', models: List[Model] = <factory>, header: Dict = <factory>)[source]#
Complete PDB structure.
- Attributes:
pdb_id: 4-letter PDB identifier title: structure title models: ordered list of models header: metadata (resolution, method, etc.)
- align_to(other: Structure, atoms: str = 'CA') Alignment[source]#
Superpose this structure onto another.
Uses first model and first chain. For multi-chain alignment, use Chain.align_to().
- Args:
other: target structure to align to atoms: which atoms to use ("CA", "CB", all", etc.)
- Returns:
Alignment object with RMSD and transformation
- parse_pdb(filename: str) Structure[source]#
Convenience function to parse PDB file.
- Args:
filename: path to PDB file
- Returns:
Structure object
- parse_pdb_pdb_id(pdb_id: str) Structure[source]#
Download PDB from RCSB and parse it.
Downloads from RCSB's public HTTP endpoint.
- Args:
pdb_id: RCSB PDB ID (e.g., "1CRN").
- Returns:
Structure object.
- Raises:
Exception: if download or parsing fails.
Example:
from sequana.pdb import parse_pdb_pdb_id structure = parse_pdb_pdb_id("1CRN") structure.stats()
- rmsd(coords1: ndarray, coords2: ndarray) float[source]#
Calculate RMSD between two coordinate sets (Nx3).
Assumes coordinates are pre-aligned. For optimal alignment, use superpose().
- Args:
coords1, coords2: Nx3 coordinate arrays
- Returns:
RMSD value in angstroms
- superpose(coords1: ndarray, coords2: ndarray) Tuple[ndarray, ndarray, float][source]#
Optimally align coords2 onto coords1 using least-squares fit.
Returns rotated coords2, rotation matrix, and RMSD.
- Args:
coords1, coords2: Nx3 coordinate arrays (moving onto fixed)
- Returns:
(rotated_coords2, rotation_matrix, rmsd_value)
mmCIF (macromolecular Crystallographic Information File) parsing.
Modern PDB depositions (large assemblies, many chains, cryo-EM structures)
are distributed in mmCIF rather than legacy fixed-column PDB format -- RCSB
stopped generating legacy PDB files for structures that don't fit its column
limits. This module parses the atom_site records (and a handful of
header scalars) of a real-world, RCSB-deposited mmCIF file into the same
Structure / Model /
Chain / Residue /
Atom object model used by sequana.pdb, so all of
that module's analysis methods (superposition, RMSD, contact maps, phi/psi
angles, ...) work unchanged on mmCIF-sourced structures.
Scope note: this implements the practically-relevant subset of the CIF/STAR
grammar that RCSB-deposited files actually use (single data block, loop_
tables, quoted strings, semicolon-delimited multi-line text fields) -- it is
not a general-purpose CIF dictionary/validation parser. If you need
schema validation, non-PDBx CIF dialects, or the full computed-structure
categories (secondary structure, connectivity, etc.), reach for
Bio.PDB.MMCIFParser instead.
Example:
from sequana.mmcif import parse_mmcif
structure = parse_mmcif("1CRN.cif")
chain = structure.model.get_chain("A")
print(chain.sequence())
- class MMCIFParser[source]#
Parse mmCIF format files (
atom_siterecords + basic header metadata).- parse(filename: str) Structure[source]#
Parse an mmCIF file (optionally gzip-compressed) and return a Structure.
- Args:
filename: path to an mmCIF file (
.cifor.cif.gz).- Returns:
Structure object, built from the same classes as
sequana.pdb.parse_pdb().
- parse_string(cif_text: str, source: str = '<string>') Structure[source]#
Parse mmCIF content from a string and return a Structure.
- Args:
cif_text: mmCIF file content. source: label recorded in
structure.header["source"].- Returns:
Structure object.
- Raises:
- BadFileFormat: if no
atom_siteloop is found (not a coordinate-bearing mmCIF file, or an unsupported CIF dialect).
- BadFileFormat: if no
- parse_mmcif(filename: str) Structure[source]#
Convenience function to parse an mmCIF file.
- Args:
filename: path to an mmCIF file (
.cifor.cif.gz).- Returns:
Structure object.
Example:
from sequana.mmcif import parse_mmcif structure = parse_mmcif("1CRN.cif") structure.stats()
- parse_mmcif_pdb_id(pdb_id: str) Structure[source]#
Download mmCIF from RCSB PDB and parse it.
Downloads from RCSB's public HTTP endpoint.
- Args:
pdb_id: RCSB PDB ID (e.g., "1CRN").
- Returns:
Structure object.
- Raises:
Exception: if download or parsing fails.
Example:
from sequana.mmcif import parse_mmcif_pdb_id structure = parse_mmcif_pdb_id("1CRN") structure.stats()
Phylogenetic and comparative analysis#
Phylogenetic tree parsing and manipulation.
- class Tree(root)[source]#
Phylogenetic tree from Newick format.
Parses and manipulates phylogenetic trees. Supports: - Standard Newick: (A:1.0,B:1.0)C:0.0; - Bootstrap: (A:1.0,B:1.0)95:0.0; - Named internal nodes: (A:1.0,B:1.0)AB:0.0;
- Examples:
>>> tree = Tree.from_newick("(A:1.0,B:1.0)root:0.0;") >>> tree.leaves() ['A', 'B'] >>> tree.distance("A", "B") 2.0
Initialize tree from root node, filename, or Newick string.
- Args:
root: TreeNode object, filename (str), or Newick format string (str)
- bifurcations() List[Tuple[List[str], List[str]]][source]#
Return all bifurcations as (left_leaves, right_leaves) tuples.
Useful for cladogram analysis.
- depth_at_leaf(leaf_name: str) float[source]#
Return distance from root to leaf.
- Args:
leaf_name: leaf sequence name
- Returns:
cumulative branch length from root to leaf
- distance(leaf1: str, leaf2: str) float[source]#
Euclidean distance between two leaves.
Sum of branch lengths along path between leaves.
- classmethod from_newick(newick_str: str) Tree[source]#
Parse Newick format string.
Format: (child1:branch1,child2:branch2)parent:branch;
- Args:
newick_str: Newick string (with or without trailing ;)
- Returns:
Tree object
- get_tree_balance() float[source]#
Return tree balance metric (0-1, 1=perfectly balanced).
Uses Colles-like index: ratio of actual vs max imbalance. Perfectly balanced binary tree = 1.0 Completely ladder-like tree = 0.0
- get_tree_imbalance() float[source]#
Return tree imbalance (1 - balance).
High imbalance = unbalanced tree (like a ladder).
- leaf_distances(leaf_name: str) Dict[str, float][source]#
Return distances from one leaf to all others.
- Args:
leaf_name: starting leaf name
- Returns:
dict mapping leaf names to distances
- plot_dendrogram(figsize: Tuple[int, int] = (12, 8))[source]#
Plot tree as dendrogram using matplotlib.
- Args:
figsize: figure size (width, height)
- prune(leaves_to_keep: Set[str]) Tree[source]#
Remove leaves not in set and return pruned tree.
Removes single-child internal nodes (collapses lineage).
- subtree(mrca_leaves: Set[str]) Tree[source]#
Extract subtree containing given leaves (MRCA + descendants).
- to_ascii(node: TreeNode | None = None, prefix: str = '', is_last: bool = True) str[source]#
Return ASCII tree representation (text-based).
Example:
root ├── A └── B ├── C └── D
- to_dict(node: TreeNode | None = None) dict[source]#
Convert tree to nested dict for JSON serialization.
- Returns:
nested dict with keys: name, bootstrap, branch_length, children
- class TreeNode(name: str | None = None, branch_length: float = 0.0, bootstrap: float | None = None, children: List[TreeNode] = <factory>, parent: TreeNode | None = None, metadata: Dict = <factory>)[source]#
Single node in phylogenetic tree.
- Attributes:
name: taxon name (leaf) or internal node label branch_length: distance to parent bootstrap: bootstrap/confidence value (0-100) metadata: arbitrary node annotations
Phylogenetic tree construction (UPGMA, neighbor-joining) and consensus trees.
Complements sequana.phylo (which parses/manipulates an already-built
Tree) with the missing piece: building a tree from a distance matrix,
and summarizing a set of bootstrap-replicate trees into a majority-rule
consensus tree. This is the Biopython Bio.Phylo.TreeConstruction /
Bio.Phylo.Consensus equivalent.
Example, UPGMA from a 4-taxon distance matrix:
from sequana.phylo_construction import upgma
names = ["A", "B", "C", "D"]
matrix = [
[0, 5, 9, 9],
[5, 0, 10, 10],
[9, 10, 0, 8],
[9, 10, 8, 0],
]
tree = upgma(matrix, names)
print(tree.to_newick())
Example, neighbor-joining and majority-rule consensus of bootstrap trees:
from sequana.phylo_construction import neighbor_joining, majority_consensus
tree = neighbor_joining(matrix, names)
consensus = majority_consensus([tree1, tree2, tree3], cutoff=0.5)
- majority_consensus(trees: List[Tree], cutoff: float = 0.5) Tree[source]#
Build a majority-rule consensus tree from a list of trees on the same taxa.
Typical use: summarizing bootstrap replicate trees into a single consensus topology, with each retained internal split annotated by the fraction of input trees that contain it (stored as
bootstrapon the corresponding internal node, 0-100 scale to match the existingTreeNode.bootstrapconvention used when parsing Newick bootstrap values).- Args:
- trees: list of
Treeobjects, all sharing the same set of leaf names.
- cutoff: minimum fraction of trees (0-1) a bipartition must appear in
to be included in the consensus (0.5 = strict majority rule).
- trees: list of
- Returns:
Tree: consensus tree. Included internal splits carry a
bootstrapvalue (percentage of input trees supporting that split); leaf branch lengths are not meaningful in the topology-only consensus and are left at 0.- Raises:
- SequanaException: if
treesis empty, or the trees don't share an identical set of leaf names.
- SequanaException: if
Example:
from sequana.phylo_construction import majority_consensus consensus = majority_consensus([tree1, tree2, tree3], cutoff=0.5) consensus.to_newick()
- neighbor_joining(matrix: Sequence[Sequence[float]] | Dict[Tuple[str, str], float], names: List[str]) Tree[source]#
Build an unrooted tree by neighbor-joining (Saitou & Nei, 1987).
Unlike UPGMA, neighbor-joining does not assume a constant rate of evolution and produces the correct topology under more relaxed conditions (additive distances), at the cost of typically returning an unrooted tree topology (returned here rooted arbitrarily at the last internal node, matching common convention).
- Args:
- matrix: NxN distance matrix (list of lists / 2D array-like, symmetric,
zero diagonal) or a dict mapping (name_a, name_b) -> distance.
names: taxon names, in the same order as the matrix rows/columns.
- Returns:
Tree: tree with branch lengths from the neighbor-joining algorithm.
- Raises:
- SequanaException: if fewer than 3 names are given (NJ needs at least
3 taxa to have a meaningful internal topology).
Example:
from sequana.phylo_construction import neighbor_joining names = ["A", "B", "C", "D"] matrix = [[0, 5, 9, 9], [5, 0, 10, 10], [9, 10, 0, 8], [9, 10, 8, 0]] tree = neighbor_joining(matrix, names) tree.leaves() ['A', 'B', 'C', 'D']
- upgma(matrix: Sequence[Sequence[float]] | Dict[Tuple[str, str], float], names: List[str]) Tree[source]#
Build a rooted tree by UPGMA (Unweighted Pair Group Method with Arithmetic mean) clustering of a pairwise distance matrix.
UPGMA assumes a constant molecular clock (equal evolutionary rate across lineages) -- it always produces an ultrametric tree (all leaves equidistant from the root). For divergent-rate data, prefer
neighbor_joining().- Args:
- matrix: NxN distance matrix (list of lists / 2D array-like, symmetric,
zero diagonal) or a dict mapping (name_a, name_b) -> distance.
names: taxon names, in the same order as the matrix rows/columns.
- Returns:
Tree: rooted tree with branch lengths set from cluster merge heights.
- Raises:
SequanaException: if fewer than 2 names are given.
Example:
from sequana.phylo_construction import upgma tree = upgma([[0, 2], [2, 0]], ["A", "B"]) tree.leaves() ['A', 'B']
Multiple sequence alignment parsing and manipulation.
- class Alignment(sequences: Dict[str, str]=<factory>, format: str = 'unknown', annotations: Dict[str, ~typing.Dict]=<factory>)[source]#
Multiple sequence alignment.
- Attributes:
sequences: dict mapping sequence name -> sequence string names: ordered list of sequence names format: source format (phylip, stockholm, nexus, fasta) annotations: dict of per-sequence metadata
- add_sequence(name: str, sequence: str, annotations: Dict | None = None) None[source]#
Add sequence to alignment.
- Args:
name: sequence identifier sequence: aligned sequence string annotations: optional metadata dict
- consensus(ignore_gaps: bool = True) str[source]#
Return consensus sequence (most common char per position).
- Args:
ignore_gaps: exclude gaps/Ns from consensus calculation
- Returns:
consensus sequence string
- get_column(pos: int) Dict[str, str][source]#
Get all characters at alignment position.
- Args:
pos: column position (0-indexed)
- Returns:
dict mapping sequence name -> character
- class GeneTrees(directory)[source]#
Compute mean distances and variances within each group.
- Large variance with moderate mean often indicates:
Ancient duplication + recent paralogs
Asymmetric evolution across species
- class OrthoFinder(directory)[source]#
o = OrthoFinder(".") g = GFF3("Ld1S.gff") annotations, chromosomes, positions = o.add_annotation_Ld1S(g) o.ortho_groups['annotation'] = annotations o.ortho_groups['chromosome'] = chromosomes o.ortho_groups['position'] = positions
- class OrthoFinderResults(directory)[source]#
Summaries of an OrthoFinder results directory (data only, no plotting).
The directory must contain
Orthogroups/and may containComparative_Genomics_Statistics/andSpecies_Tree/(as produced by OrthoFinder). Used by the sequana_orthofinder pipeline for its report.res = OrthoFinderResults("ResultsLight") res.pairwise_shared() res.intersections() res.category_counts()
- RELATIONS = ['one-to-one', 'one-to-many', 'many-to-one', 'many-to-many']#
- categories()[source]#
Classify each orthogroup as core, shell or specific.
core: present in all genomes; specific: present in a single genome; shell: anything in between (with a single genome everything is core).
- category_counts()[source]#
Per-genome count of orthogroups in each category (DataFrame genome x category).
- copy_number_distribution(max_copies=10)[source]#
Orthogroup count per gene copy number, per genome (columns), capped at
max_copies.
- duplications_per_node()[source]#
Gene duplications mapped to each species-tree node (None if unavailable).
- expanded_families(top=None, with_genes=False)[source]#
Orthogroups ranked by copy-number spread across genomes.
Only orthogroups present in all genomes are considered, so that the spread reflects expansion/contraction and not presence/absence.
- Parameters:
with_genes -- add the columns
Largest_in(genome with the most copies) andGenes(its gene IDs, comma-separated)
- intersections()[source]#
Number of orthogroups for each combination of genomes (UpSet data).
- Returns:
DataFrame with one boolean column per genome plus
count, sorted by decreasing count.
- ortholog_relations()[source]#
Orthology relations for each ordered genome pair (A -> B).
Columns: Genome1, Genome2, one-to-one, one-to-many, many-to-one, many-to-many, Total (number of orthologues, as counted by OrthoFinder).
Orthogroups shared by each pair of genomes.
Percentage is relative to orthogroups present in either genome. This is gene-content sharing, not gene-order (synteny) conservation.
- property species_tree_file#
OrthoFinder rooted species tree (None for fewer than 3 genomes).
- specific_orthogroups()[source]#
Orthogroups present in a single genome: Orthogroup, Genome, N_genes, Genes.
- property statistics_dir#
- gene_tree_discordance(gene_trees_dir, species, species_tree)[source]#
Normalised Robinson-Foulds distance between gene trees and the species tree.
Only single-copy orthogroups (exactly one gene per genome) can be compared directly; the others are skipped. At least 4 genomes are needed for the distance to be informative.
- Parameters:
gene_trees_dir -- OrthoFinder
Gene_Treesdirectoryspecies -- genome names; gene tree leaves are
<genome>_<gene id>species_tree -- Newick file of the species tree
- Returns:
Series indexed by orthogroup name (
OG0000000) with values in [0, 1]