DeRIP Class
DeRIP
DeRIP(alignment_input, max_snp_noise: float = 0.5, min_rip_like: float = 0.1, reaminate: bool = False, fill_index: Optional[int] = None, fill_max_gc: bool = False, max_gaps: float = 0.7)
A class to detect and correct RIP (Repeat-Induced Point) mutations in DNA alignments.
This class encapsulates the functionality to analyze DNA sequence alignments for RIP-like mutations, correct them, and generate deRIPed consensus sequences.
| PARAMETER | DESCRIPTION |
|---|---|
alignment_input
|
Path to the alignment file in FASTA format or a pre-loaded MultipleSeqAlignment object.
TYPE:
|
max_snp_noise
|
Maximum proportion of conflicting SNPs permitted before excluding column from RIP/deamination assessment (default: 0.5).
TYPE:
|
min_rip_like
|
Minimum proportion of deamination events in RIP context required for column to be deRIP'd in final sequence (default: 0.1).
TYPE:
|
reaminate
|
Whether to correct all deamination events independent of RIP context (default: False).
TYPE:
|
fill_index
|
Index of row to use for filling uncorrected positions (default: None).
TYPE:
|
fill_max_gc
|
Whether to use sequence with highest GC content for filling if no row index is specified (default: False).
TYPE:
|
max_gaps
|
Maximum proportion of gaps in a column before considering it a gap in consensus (default: 0.7).
TYPE:
|
| ATTRIBUTE | DESCRIPTION |
|---|---|
alignment |
The loaded DNA sequence alignment.
TYPE:
|
masked_alignment |
The alignment with RIP-corrected positions masked with IUPAC codes.
TYPE:
|
consensus |
The deRIPed consensus sequence.
TYPE:
|
gapped_consensus |
The deRIPed consensus sequence with gaps.
TYPE:
|
rip_counts |
Dictionary tracking RIP mutation counts for each sequence.
TYPE:
|
corrected_positions |
Dictionary of corrected positions {col_idx: {row_idx: {observed_base, corrected_base}}}.
TYPE:
|
colored_consensus |
Consensus sequence with corrected positions highlighted in green.
TYPE:
|
colored_alignment |
Alignment with corrected positions highlighted in green.
TYPE:
|
colored_masked_alignment |
Masked alignment with RIP positions highlighted in color.
TYPE:
|
markupdict |
Dictionary of markup codes for masked positions.
TYPE:
|
Initialize DeRIP with an alignment file or MultipleSeqAlignment object and parameters.
| PARAMETER | DESCRIPTION |
|---|---|
alignment_input
|
Path to the alignment file in FASTA format or a pre-loaded MultipleSeqAlignment object. If a MultipleSeqAlignment is provided, it must contain at least 2 sequences.
TYPE:
|
max_snp_noise
|
Maximum proportion of conflicting SNPs permitted before excluding column from RIP/deamination assessment (default: 0.5).
TYPE:
|
min_rip_like
|
Minimum proportion of deamination events in RIP context required for column to be deRIP'd in final sequence (default: 0.1).
TYPE:
|
reaminate
|
Whether to correct all deamination events independent of RIP context (default: False).
TYPE:
|
fill_index
|
Index of row to use for filling uncorrected positions (default: None).
TYPE:
|
fill_max_gc
|
Whether to use sequence with highest GC content for filling if no row index is specified (default: False).
TYPE:
|
max_gaps
|
Maximum proportion of gaps in a column before considering it a gap in consensus (default: 0.7).
TYPE:
|
calculate_rip
Calculate RIP locations and corrections in the alignment.
This method performs RIP detection and correction, fills in the consensus sequence, and populates the class attributes.
| PARAMETER | DESCRIPTION |
|---|---|
label
|
ID for the generated deRIPed sequence (default: "deRIPseq").
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
None
|
Updates class attributes with results. |
calculate_cri
Calculate the Composite RIP Index (CRI) for a DNA sequence.
| PARAMETER | DESCRIPTION |
|---|---|
sequence
|
The DNA sequence to analyze.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple
|
(cri, pi, si) - Composite RIP Index, Product Index, and Substrate Index. |
calculate_cri_for_all
Calculate the Composite RIP Index (CRI) for each sequence in the alignment and assign CRI values as annotations to each sequence record.
| RETURNS | DESCRIPTION |
|---|---|
MultipleSeqAlignment
|
The alignment with CRI metadata added to each record. |
Notes
This method calculates: - Product Index (PI) = TpA / ApT - Substrate Index (SI) = (CpA + TpG) / (ApC + GpT) - Composite RIP Index (CRI) = PI - SI
High CRI values indicate strong RIP activity.
calculate_dinucleotide_frequency
Calculate the frequency of specific dinucleotides in a sequence.
| PARAMETER | DESCRIPTION |
|---|---|
sequence
|
The DNA sequence to analyze.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
A dictionary with dinucleotide counts. |
calculate_rsi
Calculate the RIP Strandedness Imbalance (RSI) for every sequence.
RSI is p_fwd - p_rev, the difference between the proportion of
forward-strand substrate (CpA) and reverse-strand substrate (TpG) that
RIP has converted to TpA. It lies in [-1, 1]: positive means RIP
acted mainly on the forward strand, negative mainly on the reverse.
Because a single round of meiotic RIP acts on one strand of a duplex,
a strongly imbalanced sequence is the signature of one round of RIP,
while a balanced one has either escaped RIP or been RIP'd repeatedly on
both strands. p_fwd and p_rev separate those two cases.
| PARAMETER | DESCRIPTION |
|---|---|
ambiguous
|
How to attribute TpA dinucleotides that could have arisen from RIP
on either strand (default:
TYPE:
|
substrate_scope
|
Which unmutated substrate dinucleotides enter the denominators
(default:
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
RSIResult
|
Per-sequence RSI, its components, ambiguity counts and significance. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If :meth: |
See Also
derip2.stats.strand_bias.compute_rsi : The underlying calculation.
Examples:
rip_summary
Return a summary of RIP mutations found in each sequence as str.
| RETURNS | DESCRIPTION |
|---|---|
str
|
Summary of RIP mutations by sequence. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If calculate_rip has not been called first. |
summarize_cri
Generate a formatted table summarizing CRI values for all sequences.
| RETURNS | DESCRIPTION |
|---|---|
str
|
A formatted string containing the CRI summary table. |
summarize_stats
Build a per-sequence table of every RIP statistic deRIP2 computes.
Combines the RIP event counts from the alignment scan, the classical composite RIP index (CRI) and its components, GC content, and the strandedness imbalance (RSI) with its components and significance.
| PARAMETER | DESCRIPTION |
|---|---|
ambiguous
|
Ambiguity policy for RSI (default:
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DataFrame
|
One row per sequence, in alignment order. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If :meth: |
stats_summary
Format :meth:summarize_stats as a table for terminal output.
| PARAMETER | DESCRIPTION |
|---|---|
ambiguous
|
Ambiguity policy (default:
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
The stats table, ready to print. |
calculate_spectra
calculate_spectra(partition_by: str = 'none', ancestor=None, samples=None, context: str = 'trinucleotide')
Compute the SBS-96 and SBS-192 trinucleotide mutation spectra.
Every alignment cell whose base differs from the ancestral reference at that column is counted as one substitution event, with its trinucleotide context read from the ancestor using nearest non-gap bases. Events are folded to the pyrimidine strand for the SBS-96 matrix and kept strand-resolved for the SBS-192 matrix.
This is the tree-free baseline spectrum: the ancestor is deRIP2's reconstructed consensus (or a user-supplied sequence), so recurrence is reported only as a multi-hit-column proxy. Correct independent-event counting requires the phylogenetic path.
| PARAMETER | DESCRIPTION |
|---|---|
partition_by
|
How to split the spectra into samples.
TYPE:
|
ancestor
|
Ancestral reference sequence, one base per alignment column. Defaults
to deRIP2's gapped consensus (:attr:
TYPE:
|
samples
|
An explicit per-row sample label (length equal to the number of
sequences), e.g. species or group names. Overrides
TYPE:
|
context
|
Which sequence context to classify substitutions by (default:
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
SpectraResult
|
The assembled spectra, per-event detail and homoplasy proxy. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If :meth: |
See Also
derip2.stats.mutation_spectra.compute_spectra : The underlying calculation.
write_spectra_matrix
Write a SigProfiler-compliant SBS matrix, computing spectra if needed.
| PARAMETER | DESCRIPTION |
|---|---|
output_file
|
Destination path for the tab-separated matrix file.
TYPE:
|
kind
|
Which spectrum matrix to write (default:
TYPE:
|
**kwargs
|
Passed to :meth:
DEFAULT:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
The path written. |
plot_spectra
Draw an SBS mutation-spectrum figure, computing spectra if needed.
| PARAMETER | DESCRIPTION |
|---|---|
output_file
|
Path to write the figure to. Use
TYPE:
|
kind
|
Which figure to draw: the SBS-96 spectrum (default), the SBS-192 strand-resolved spectrum, the pyrimidine-folded downstream-triplet spectrum, the strand-asymmetry panel, or the homoplasy (recurrence) plot.
TYPE:
|
**kwargs
|
Forwarded to the underlying plotting function (e.g.
DEFAULT:
|
| RETURNS | DESCRIPTION |
|---|---|
Figure
|
The figure. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
calculate_flank_spectra
Compute the flanking-context spectra of RIP-like sites.
Classifies every RIP-like dinucleotide by the flank_length bases
upstream and downstream (a 2 + 2 * flank_length bp motif; a 4 bp motif
for the default 1 bp flank). Surviving substrate sites (CpA/TpG
anywhere in each sequence) and RIP product sites (TpA in RIP-informative
columns) are counted separately, one sample column per input sequence,
folded onto CA/TA-equivalent channels. The result is cached on
:attr:flank_spectra_result and recomputed if a different flank_length
is requested.
| PARAMETER | DESCRIPTION |
|---|---|
flank_length
|
Number of flanking bases resolved on each side of the centre
dinucleotide (default 1), giving
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
FlankSpectraResult
|
The four |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If :meth: |
See Also
derip2.stats.flank_spectra.compute_flank_spectra : The calculation.
write_flank_spectra_matrix
Write the flank-context spectra as a tidy TSV, computing them if needed.
| PARAMETER | DESCRIPTION |
|---|---|
output_file
|
Destination path for the tab-separated matrix file.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
The path written. |
write_flank_spectra_comparisons
Write the per-sequence flank-context comparison stats, computing if needed.
| PARAMETER | DESCRIPTION |
|---|---|
output_file
|
Destination path for the tab-separated comparison file.
TYPE:
|
min_sites
|
Minimum site count on both sides for the chi-squared reliability flag (default: 20).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
The path written. |
plot_flank_spectra
Draw the pooled flank-context bihistograms, computing spectra if needed.
| PARAMETER | DESCRIPTION |
|---|---|
output_file
|
Path to write the figure to. Use
TYPE:
|
percentage
|
When
TYPE:
|
**kwargs
|
Forwarded to
:func:
DEFAULT:
|
| RETURNS | DESCRIPTION |
|---|---|
Figure
|
The figure. |
plot_flank_conversion_heatmap
plot_flank_conversion_heatmap(output_file: Optional[str] = None, *, flank_length: int = 1, **kwargs)
Draw the pooled flank-context RIP-conversion heatmap, computing if needed.
Each cell of the 4 ** flank_length x 4 ** flank_length grid shows
the percentage of a RIP target CpA converted to TpA (the product share) as
a joint function of the upstream (rows) and downstream (columns) flank
bases.
| PARAMETER | DESCRIPTION |
|---|---|
output_file
|
Path to write the figure to (
TYPE:
|
flank_length
|
Flank width; recomputes the spectra if it differs from the cached result (default 1).
TYPE:
|
**kwargs
|
Forwarded to
:func:
DEFAULT:
|
| RETURNS | DESCRIPTION |
|---|---|
Figure
|
The heatmap figure. |
calculate_max_rip
Build a maximally RIP-mutated variant of the deRIP'd consensus.
The counterfactual complement of :meth:calculate_rip: instead of
restoring the bases RIP removed, it mutates every RIP target the
corrected sequence still carries. Results are cached per variant on
:attr:max_rip_results.
| PARAMETER | DESCRIPTION |
|---|---|
variant
|
Which sites to convert (default
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
MaxRIPResult
|
The mutated sequence and the positions that were changed. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If :meth: |
See Also
derip2.maxrip.compute_max_rip : The calculation.
get_max_rip_string
Return a maximum-RIP sequence as a string, computing it if needed.
| PARAMETER | DESCRIPTION |
|---|---|
variant
|
Which sites to convert (default
TYPE:
|
gapped
|
Return the column-aligned sequence rather than the ungapped one
(default
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
The maximally RIP-mutated sequence. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If :meth: |
get_max_rip_positions
Return the positions converted by a maximum-RIP variant.
| PARAMETER | DESCRIPTION |
|---|---|
variant
|
Which sites to convert (default
TYPE:
|
gapped
|
Return alignment column indices rather than offsets into the
ungapped sequence (default
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list of int
|
Ascending zero-based positions of the converted sites. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If :meth: |
write_max_rip
write_max_rip(output_file: str, variants=None, seq_id: str = 'maxRIPseq', gapped: bool = False) -> str
Write maximum-RIP sequences to a FASTA file, computing them if needed.
| PARAMETER | DESCRIPTION |
|---|---|
output_file
|
Destination path.
TYPE:
|
variants
|
Which variants to write, in order; defaults to every variant in
:data:
TYPE:
|
seq_id
|
Base record id; each record is suffixed with its variant name
(default
TYPE:
|
gapped
|
Write column-aligned sequences rather than ungapped ones
(default
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If :meth: |
write_alignment
write_alignment(output_file: str, append_consensus: bool = True, mask_rip: bool = True, consensus_id: str = 'deRIPseq', format: str = 'fasta') -> None
Write alignment to file with options to append consensus and mask RIP positions.
| PARAMETER | DESCRIPTION |
|---|---|
output_file
|
Path to the output alignment file.
TYPE:
|
append_consensus
|
Whether to append the consensus sequence to the alignment (default: True).
TYPE:
|
mask_rip
|
Whether to mask RIP positions in the output alignment (default: True).
TYPE:
|
consensus_id
|
ID for the consensus sequence if appended (default: "deRIPseq").
TYPE:
|
format
|
Format for the output alignment file (default: "fasta").
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
None
|
Writes alignment to file. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If calculate_rip has not been called first. |
write_consensus
Write the deRIPed consensus sequence to a FASTA file.
| PARAMETER | DESCRIPTION |
|---|---|
output_file
|
Path to the output FASTA file.
TYPE:
|
consensus_id
|
ID for the consensus sequence (default: "deRIPseq").
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
None
|
Writes consensus sequence to file. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If calculate_rip has not been called first. |
write_stats
Write the per-sequence statistics table to a TSV file.
| PARAMETER | DESCRIPTION |
|---|---|
output_file
|
Destination path.
TYPE:
|
ambiguous
|
Ambiguity policy (default:
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
The path written. |
write_html_report
write_html_report(output_file: str, title: Optional[str] = None, ambiguous: str = 'split', **kwargs) -> str
Write a self-contained HTML report of the strand-bias analysis.
The report embeds three strand-bias figures (RIP-like mutations, non-RIP deamination, and all deamination) as inline SVG, alongside the per-sequence statistics table. It has no external assets, so it can be emailed or archived as a single file.
| PARAMETER | DESCRIPTION |
|---|---|
output_file
|
Destination path for the HTML file.
TYPE:
|
title
|
Report heading.
TYPE:
|
ambiguous
|
Ambiguity policy for RSI (default:
TYPE:
|
**kwargs
|
Forwarded to each figure, e.g.
DEFAULT:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
The path written. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If :meth: |
write_per_sequence_report
write_per_sequence_report(output_file: str, title: Optional[str] = None, ambiguous: str = 'split', max_seqs: Optional[int] = None, **kwargs) -> str
Write a single-file, interactive per-sequence HTML report.
The report renders one panel per input sequence — the alignment row with RIP sites highlighted, a fixed-height per-sequence strand-bias strip, a per-sequence SBS-96 spectrum against the reconstructed ancestor, and that sequence's summary statistics — and lets the reader step between sequences with the arrow keys. Every figure is inline SVG, so the file is self-contained.
| PARAMETER | DESCRIPTION |
|---|---|
output_file
|
Destination path for the HTML file.
TYPE:
|
title
|
Report heading.
TYPE:
|
ambiguous
|
Ambiguity policy for the per-sequence RSI statistics
(default:
TYPE:
|
max_seqs
|
Cap the number of sequence panels, keeping the first
TYPE:
|
**kwargs
|
Forwarded to :func:
DEFAULT:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
The path written. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If :meth: |
plot_alignment
plot_alignment(output_file: Optional[str] = None, dpi: int = 300, title: Optional[str] = None, width: int = 20, height: int = 15, palette: str = 'derip2', column_ranges: Optional[List[Tuple[int, int, str, str]]] = None, show_chars: bool = False, draw_boxes: bool = False, show_rip: str = 'both', highlight_corrected: bool = True, flag_corrected: bool = False, **kwargs) -> str
Generate a visualization of the alignment with RIP mutations highlighted.
This method creates a PNG image showing the aligned sequences with color-coded highlighting of RIP mutations and corrections. It displays the consensus sequence below the alignment with asterisks marking corrected positions.
| PARAMETER | DESCRIPTION |
|---|---|
output_file
|
Path to save the output image file.
TYPE:
|
dpi
|
Resolution of the output image in dots per inch (default: 300).
TYPE:
|
title
|
Title to display on the image (default: None).
TYPE:
|
width
|
Width of the output image in inches (default: 20).
TYPE:
|
height
|
Height of the output image in inches (default: 15).
TYPE:
|
palette
|
Color palette to use: 'colorblind', 'bright', 'tetrimmer', 'basegrey', or 'derip2' (default: 'basegrey').
TYPE:
|
column_ranges
|
List of column ranges to mark, each as (start_col, end_col, color, label) (default: None).
TYPE:
|
show_chars
|
Whether to display sequence characters inside the colored cells (default: False).
TYPE:
|
draw_boxes
|
Whether to draw black borders around highlighted bases (default: False).
TYPE:
|
show_rip
|
Which RIP markup categories to include: 'substrate', 'product', or 'both' (default: 'both').
TYPE:
|
highlight_corrected
|
If True, only corrected positions in the consensus will be colored, all others will be gray (default: True).
TYPE:
|
flag_corrected
|
If True, corrected positions in the alignment will be marked with asterisks (default: False).
TYPE:
|
**kwargs
|
Additional keyword arguments to pass to drawMiniAlignment function.
DEFAULT:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
Path to the output image file. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If calculate_rip has not been called first. |
Notes
The visualization uses different colors to distinguish RIP-related mutations: - Red: RIP products (typically T from C→T mutations) - Blue: RIP substrates (unmutated nucleotides in RIP context) - Yellow: Non-RIP deaminations (only if reaminate=True) - Target bases are displayed in black text, while surrounding context is in grey text
plot_strand_bias
Draw a diverging stacked-bar chart of per-column RIP strand bias.
Bars are drawn above the axis where the deamination is observed on the forward strand and below it where it is observed on the reverse strand.
| PARAMETER | DESCRIPTION |
|---|---|
output_file
|
Path to write the figure to. Use
TYPE:
|
mode
|
Which deamination events to display (default:
TYPE:
|
**kwargs
|
Additional options forwarded to
:func:
DEFAULT:
|
| RETURNS | DESCRIPTION |
|---|---|
Figure
|
The figure. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If :meth: |
get_cri_values
Return a list of CRI values for all sequences in the alignment.
If a sequence doesn't have a CRI value yet, calculate it first.
| RETURNS | DESCRIPTION |
|---|---|
list of dict
|
List of dictionaries containing CRI, PI, SI values and sequence ID, in the same order as sequences appear in the alignment. |
get_rsi_values
Return per-sequence RSI values, calculating them if needed.
| PARAMETER | DESCRIPTION |
|---|---|
**kwargs
|
Passed to :meth:
DEFAULT:
|
| RETURNS | DESCRIPTION |
|---|---|
list of dict
|
One record per sequence, in alignment order. |
get_gc_content
Calculate and return the GC content for all sequences in the alignment.
| RETURNS | DESCRIPTION |
|---|---|
list of dict
|
List of dictionaries containing sequence ID and GC content, in the same order as sequences appear in the alignment. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If no alignment is loaded. |
get_consensus_string
Get the deRIPed consensus sequence as a string.
| RETURNS | DESCRIPTION |
|---|---|
str
|
The deRIPed consensus sequence. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If calculate_rip has not been called first. |
sort_by_cri
Sort the alignment by CRI score.
| PARAMETER | DESCRIPTION |
|---|---|
descending
|
If True, sort in descending order (highest CRI first). Default: True.
TYPE:
|
inplace
|
If True, replace the current alignment with the sorted alignment. If False, return a new alignment without modifying the original (default: False).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
MultipleSeqAlignment
|
A new alignment with sequences sorted by CRI score. |
sort_by_rsi
Sort the alignment by RIP strandedness imbalance.
| PARAMETER | DESCRIPTION |
|---|---|
descending
|
If True (default), sequences with the most forward-strand RIP come first and those with the most reverse-strand RIP last.
TYPE:
|
inplace
|
If True, replace the current alignment and discard all computed results, which must then be recalculated (default: False).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
MultipleSeqAlignment
|
The sorted alignment. |
Notes
Sequences whose RSI is undefined (NaN, because one strand carries no substrate and no product) sort to the end regardless of direction. They carry no evidence, so placing them at either extreme would misrepresent them.
filter_by_cri
Filter the alignment to remove sequences with CRI values below a threshold.
| PARAMETER | DESCRIPTION |
|---|---|
min_cri
|
Minimum CRI value to keep a sequence in the alignment (default: 0.0).
TYPE:
|
inplace
|
If True, replace the current alignment with the filtered alignment. If False, return a new alignment without modifying the original (default: False).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
MultipleSeqAlignment
|
A new alignment containing only sequences with CRI values >= min_cri. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If no alignment is loaded or if filtering would remove all sequences. |
Warning
|
If fewer than 2 sequences remain after filtering. |
Notes
CRI values will be calculated for sequences that don't already have them. If inplace=True, this will modify the original alignment in the DeRIP object.
filter_by_gc
Filter the alignment to remove sequences with GC content below a threshold.
| PARAMETER | DESCRIPTION |
|---|---|
min_gc
|
Minimum GC content to keep a sequence in the alignment (default: 0.0). Value should be between 0.0 and 1.0.
TYPE:
|
inplace
|
If True, replace the current alignment with the filtered alignment. If False, return a new alignment without modifying the original (default: False).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
MultipleSeqAlignment
|
A new alignment containing only sequences with GC content >= min_gc. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If no alignment is loaded or if filtering would remove all sequences. |
Warning
|
If fewer than 2 sequences remain after filtering. |
Notes
GC content will be calculated for sequences that don't already have it. If inplace=True, this will modify the original alignment in the DeRIP object.
keep_low_cri
Retain only the n sequences with the lowest CRI values.
| PARAMETER | DESCRIPTION |
|---|---|
n
|
Number of sequences with lowest CRI values to keep (default: 2).
TYPE:
|
inplace
|
If True, replace the current alignment with the filtered alignment. If False, return a new alignment without modifying the original (default: False).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
MultipleSeqAlignment
|
A new alignment containing only the n sequences with lowest CRI values. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If no alignment is loaded. |
Notes
CRI values will be calculated for sequences that don't already have them. If inplace=True, this will modify the original alignment in the DeRIP object. If n is greater than the number of sequences, no filtering occurs. If n is less than 2, no filtering occurs to ensure DeRIP has enough sequences to work with.
keep_high_gc
Retain only the n sequences with the highest GC content.
| PARAMETER | DESCRIPTION |
|---|---|
n
|
Number of sequences with highest GC content to keep (default: 2).
TYPE:
|
inplace
|
If True, replace the current alignment with the filtered alignment. If False, return a new alignment without modifying the original (default: False).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
MultipleSeqAlignment
|
A new alignment containing only the n sequences with highest GC content. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If no alignment is loaded. |
Notes
GC content will be calculated for sequences that don't already have it. If inplace=True, this will modify the original alignment in the DeRIP object. If n is greater than the number of sequences, no filtering occurs. If n is less than 2, no filtering occurs to ensure DeRIP has enough sequences to work with.
Strand bias statistics
strand_bias
RIP Strandedness Imbalance (RSI): a per-sequence measure of which strand RIP acted on.
Notes
Background
RIP deaminates the C of a CpA dinucleotide. Read on the forward strand, a reverse-strand CpA appears as TpG, so RIP acting on either strand converts a forward-strand dinucleotide to TpA::
forward substrate CA --RIP--> TA
reverse substrate TG --RIP--> TA
A single round of meiotic RIP acts on one strand of a given duplex, so progeny sequences carry a strand-biased signature: either their CpA sites converted, or their TpG sites converted, rarely both. RSI quantifies that asymmetry.
Definition
For each sequence::
p_fwd = fwd_products / (fwd_products + fwd_substrates)
p_rev = rev_products / (rev_products + rev_substrates)
RSI = p_fwd - p_rev
RSI lies in [-1, 1]. Positive values indicate RIP predominantly on the
forward strand, negative values the reverse strand. Both 0 (no RIP) and
0 (both strands fully converted) are neutral, so RSI must be read alongside
its components p_fwd and p_rev, which distinguish the two cases.
Because the proportions are normalised independently per strand, unequal abundances of CpA and TpG substrate motifs do not bias the score.
Substrates versus products
Unmutated substrates (CA, TG) are directly observed in a sequence. Products
(TA) must be inferred: a TA is only attributable to RIP when the alignment
column shows an aligned, unmutated substrate in some other sequence. The two
are therefore counted with different scopes, controlled by substrate_scope.
Counting substrates only inside RIP-classified columns would give a sequence
with no RIP at all p_fwd = 0 / 0, when the correct answer is 0.
Ambiguity
A physical TA dinucleotide spans two columns: the T at column i and the A
at column j. It is evidence of forward RIP if column i is a forward RIP
column (some sequence retains an aligned CA), and evidence of reverse RIP if
column j is a reverse RIP column (some sequence retains an aligned TG). When
both hold the strand of origin is unrecoverable from the alignment alone. The
ambiguous policy decides how such events are attributed; n_ambiguous is
always reported so the choice can be audited.
Substrates are never ambiguous: a CA's second base is A (not G) and a TG's first base is T (not C), so neither can be read as the other strand's substrate.
RSIResult
dataclass
RSIResult(rsi: ndarray, p_fwd: ndarray, p_rev: ndarray, fwd_prod: ndarray, fwd_sub: ndarray, rev_prod: ndarray, rev_sub: ndarray, n_ambiguous: ndarray, z: ndarray, pvalue: ndarray, ambiguous: str, substrate_scope: str)
Per-sequence RIP strandedness imbalance and its components.
All arrays have shape (n_rows,) and are indexed by alignment row.
| ATTRIBUTE | DESCRIPTION |
|---|---|
rsi |
TYPE:
|
p_fwd, p_rev |
Proportion of available forward (reverse) substrate sites converted to product. NaN when that strand has neither substrate nor product.
TYPE:
|
fwd_prod, rev_prod |
Attributed product counts. Fractional under the
TYPE:
|
fwd_sub, rev_sub |
Counts of unmutated substrate dinucleotides.
TYPE:
|
n_ambiguous |
Number of TA dinucleotides attributable to either strand.
TYPE:
|
z |
Two-proportion z statistic for
TYPE:
|
pvalue |
Two-sided p-value for the null that RIP struck both strands equally.
TYPE:
|
ambiguous |
The attribution policy used.
TYPE:
|
substrate_scope |
The substrate counting scope used.
TYPE:
|
pooled
Pool counts across all sequences and recompute the imbalance.
Summing the raw counts before taking the ratios weights each sequence by how many informative sites it carries, unlike the mean of the per-row RSI values, which weights every sequence equally regardless of evidence.
| RETURNS | DESCRIPTION |
|---|---|
dict
|
|
compute_rsi
compute_rsi(cls: ColumnClassification, ambiguous: str = 'split', substrate_scope: str = 'all') -> RSIResult
Compute the RIP Strandedness Imbalance for every sequence in an alignment.
| PARAMETER | DESCRIPTION |
|---|---|
cls
|
Classification produced by :func:
TYPE:
|
ambiguous
|
How to attribute TA dinucleotides that could have arisen from RIP on
either strand (default:
TYPE:
|
substrate_scope
|
Which unmutated substrate dinucleotides enter the denominators
(default:
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
RSIResult
|
Per-sequence RSI, components, ambiguity counts and significance. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
Notes
Products are always counted only within RIP columns (fwd_col /
rev_col), because a TA can only be attributed to RIP when an aligned
sequence retains the unmutated substrate.
A denominator of zero yields NaN rather than 0: a strand with neither substrate nor product carries no evidence, and reporting 0 would disguise "no data" as "perfectly one-sided".
Examples:
RIP column classification
aln_ops
Alignment operations for deRIP2.
This module provides functions for manipulating and analyzing DNA sequence alignments, with a focus on detecting and correcting RIP (Repeat-Induced Point mutation) mutations. It includes utilities for loading alignments, tracking RIP-like mutations, building consensus sequences, and outputting corrected sequences in various formats.
ColumnClassification
dataclass
ColumnClassification(arr: ndarray, next_idx: ndarray, prev_idx: ndarray, ca: ndarray, ta: ndarray, tg: ndarray, ta2: ndarray, ct_ok: ndarray, ga_ok: ndarray, fwd_block: ndarray, rev_block: ndarray, fwd_col: ndarray, rev_col: ndarray, modC: ndarray, modG: ndarray, base_counts: ndarray, reaminate: bool)
Per-cell and per-column classification of RIP context across an alignment.
This is the single source of truth for "which cells are RIP substrate,
product, or non-RIP deamination, and on which strand". Both the consensus
correction (:func:apply_classification) and the strand-bias statistics
consume it, so the two can never disagree.
RIP deaminates the C of a CpA dinucleotide. Read on the forward strand a reverse-strand CpA appears as TpG, so RIP on either strand yields a forward strand TpA::
Target strand: ++ --
Wild type: 5' CA--TG 3'
RIP mutated: 5' TA--TA 3'
Dinucleotides are defined per row over the nearest non-gap neighbour, so
a C-A spanning a gap column is still a CpA substrate.
| ATTRIBUTE | DESCRIPTION |
|---|---|
arr |
TYPE:
|
next_idx, prev_idx |
TYPE:
|
ca, ta, tg, ta2 |
TYPE:
|
ct_ok, ga_ok |
TYPE:
|
fwd_block, rev_block |
TYPE:
|
fwd_col, rev_col |
TYPE:
|
modC, modG |
TYPE:
|
base_counts |
TYPE:
|
reaminate |
Whether non-RIP-context deaminations are also corrected.
TYPE:
|
Notes
fwd_col requires at least one surviving CA somewhere in the column.
A column in which every row has been converted to TA therefore cannot
be recognised as a RIP column: with no ancestral C left in any sequence,
the alignment carries no evidence that the column was ever CpA. RIP is only
visible where at least one sibling sequence escaped it.
nA
property
Per-column count of A bases.
| RETURNS | DESCRIPTION |
|---|---|
ndarray
|
|
nC
property
Per-column count of C bases.
| RETURNS | DESCRIPTION |
|---|---|
ndarray
|
|
nG
property
Per-column count of G bases.
| RETURNS | DESCRIPTION |
|---|---|
ndarray
|
|
nT
property
Per-column count of T bases.
| RETURNS | DESCRIPTION |
|---|---|
ndarray
|
|
n_gap
property
Per-column count of gap characters.
| RETURNS | DESCRIPTION |
|---|---|
ndarray
|
|
base_count
property
Per-column count of unambiguous ACGT bases.
| RETURNS | DESCRIPTION |
|---|---|
ndarray
|
|
sub_fwd
property
Forward RIP substrate cells: C in CpA context, in assessable columns.
| RETURNS | DESCRIPTION |
|---|---|
ndarray
|
|
sub_rev
property
Reverse RIP substrate cells: G in TpG context, in assessable columns.
| RETURNS | DESCRIPTION |
|---|---|
ndarray
|
|
prod_fwd
property
Forward RIP product cells: T in TpA context, in forward RIP columns.
| RETURNS | DESCRIPTION |
|---|---|
ndarray
|
|
prod_rev
property
Reverse RIP product cells: A in TpA context, in reverse RIP columns.
| RETURNS | DESCRIPTION |
|---|---|
ndarray
|
|
nonrip_fwd
property
T cells in a forward candidate column that are not RIP products.
| RETURNS | DESCRIPTION |
|---|---|
ndarray
|
|
nonrip_rev
property
A cells in a reverse candidate column that are not RIP products.
| RETURNS | DESCRIPTION |
|---|---|
ndarray
|
|
mask_Y
property
Mask of cells overwritten with the IUPAC code Y (C/T) in the masked alignment.
| RETURNS | DESCRIPTION |
|---|---|
ndarray
|
|
mask_R
property
Mask of cells overwritten with the IUPAC code R (A/G) in the masked alignment.
| RETURNS | DESCRIPTION |
|---|---|
ndarray
|
|
add_fwd
property
Per-row count of forward-strand RIP events.
| RETURNS | DESCRIPTION |
|---|---|
ndarray
|
|
add_rev
property
Per-row count of reverse-strand RIP events.
| RETURNS | DESCRIPTION |
|---|---|
ndarray
|
|
add_nonrip
property
Per-row count of non-RIP deamination events.
| RETURNS | DESCRIPTION |
|---|---|
ndarray
|
|
classify_columns
classify_columns(arr: ndarray, next_idx: ndarray, prev_idx: ndarray, max_snp_noise: float = 0.5, min_rip_like: float = 0.1, reaminate: bool = False, block_size: Optional[int] = None, progress: bool = True) -> ColumnClassification
Classify every cell and column of an alignment by RIP context.
This is a vectorised reformulation of the per-column scan that
:func:correctRIP used to perform, and reproduces its decisions exactly.
Forward-strand RIP (C→T in CpA context) and reverse-strand RIP (G→A in TpG
context) are detected independently.
A column is assessed on the forward strand when its C+T bases make up at
least max_snp_noise of the non-gap bases, and is a correction
candidate only when C/T is the strict majority over G/A. Because every
non-gap base falls in exactly one of the C/T and G/A pairs, the two
proportions sum to one, so the strict inequality makes forward and reverse
correction mutually exclusive. A column can never be corrected on both
strands, and the Y/R masks can never collide.
| PARAMETER | DESCRIPTION |
|---|---|
arr
|
TYPE:
|
next_idx
|
Non-gap neighbour indices from :func:
TYPE:
|
prev_idx
|
Non-gap neighbour indices from :func:
TYPE:
|
max_snp_noise
|
Minimum proportion of a column's non-gap bases that must be C/T (or G/A) for that strand to be assessed (default: 0.5).
TYPE:
|
min_rip_like
|
Minimum proportion of a column's C/T (or G/A) bases that must sit in RIP dinucleotide context before the column is corrected (default: 0.1).
TYPE:
|
reaminate
|
If True, correct C→T and G→A transitions outside RIP context too (default: False).
TYPE:
|
block_size
|
Number of columns processed per block. Blocking bounds peak memory and is bit-identical to processing the whole array at once, because every reduction is within a single column and neighbour gathers index the full array. Defaults to a width chosen from a 64 MiB budget.
TYPE:
|
progress
|
Show a progress bar when more than one block is processed (default: True).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ColumnClassification
|
Cell masks, column flags, and per-column base counts. |
Notes
Cell classification (substrate / product / non-RIP) and the per-row tallies
depend only on max_snp_noise; min_rip_like and reaminate affect
only whether a column's consensus base is corrected and masked.
classify_alignment
classify_alignment(align: MultipleSeqAlignment, max_snp_noise: float = 0.5, min_rip_like: float = 0.1, reaminate: bool = False, block_size: Optional[int] = None, progress: bool = True) -> ColumnClassification
Convenience wrapper: decode an alignment and classify its RIP context.
| PARAMETER | DESCRIPTION |
|---|---|
align
|
The alignment to classify.
TYPE:
|
max_snp_noise
|
See :func:
TYPE:
|
min_rip_like
|
See :func:
TYPE:
|
reaminate
|
See :func:
TYPE:
|
block_size
|
See :func:
TYPE:
|
progress
|
See :func:
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ColumnClassification
|
Classification of the alignment. |
apply_classification
apply_classification(align: MultipleSeqAlignment, tracker: Dict[int, NamedTuple], RIPcounts: Dict[int, NamedTuple], cls: ColumnClassification) -> Tuple[Dict[int, NamedTuple], Dict[int, NamedTuple], AlignIO.MultipleSeqAlignment, List[int], Dict[str, List[RIPPosition]]]
Apply a column classification to the consensus tracker, counters and mask.
| PARAMETER | DESCRIPTION |
|---|---|
align
|
The alignment the classification was computed from; supplies record metadata for the rebuilt masked alignment.
TYPE:
|
tracker
|
Consensus tracker keyed by column index. Not mutated.
TYPE:
|
RIPcounts
|
Per-sequence RIP counters keyed by row index. Not mutated.
TYPE:
|
cls
|
Classification produced by :func:
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tuple
|
|
Strand bias plotting
strandbias
Diverging stacked-bar figures of per-column RIP strand bias.
Each alignment column that carries RIP signal becomes one bar. The bar is drawn above the axis when the deamination is observed on the forward strand (C→T in CpA context) and below when it is observed on the reverse strand (G→A, seen on the forward strand as the loss of a TpG).
A bar therefore sits at the column where the deaminated base itself lies. A forward event is scored at the C's column; the reverse event of the same duplex is scored at the G's column, one position to the right. Bars for a single physical TpA dinucleotide can consequently appear in adjacent columns on opposite sides of the axis — this is the strand ambiguity, made visible.
Within a bar the RIP product segment is drawn against the zero line and the unmutated substrate stacks outward. Every product segment therefore shares a common baseline, so the extent of RIP can be compared across columns at a glance.
plot_strand_bias
plot_strand_bias(cls, outfile=None, mode='rip', scale='column', stack='signal', xaxis='none', color_by='base', columns='all', column_range=None, consensus_seq=None, title=None, width=None, height=4.2, dpi=300, max_columns=None, emphasis=True, ax=None)
Draw a diverging stacked-bar chart of per-column RIP strand bias.
| PARAMETER | DESCRIPTION |
|---|---|
cls
|
Classification produced by :func:
TYPE:
|
outfile
|
Path to write the figure to; format inferred from the extension. Use
TYPE:
|
mode
|
Which deamination events to display (default:
TYPE:
|
scale
|
Bar height normalisation (default:
TYPE:
|
stack
|
Which bases the bar is made of (default:
TYPE:
|
xaxis
|
Decoration drawn in the gutter around the zero line: nothing, a sequence
logo, or the deRIP'd consensus base (default:
TYPE:
|
color_by
|
Colour segments by nucleotide identity or by the role the base plays
(default:
TYPE:
|
columns
|
Which positions are lettered when
TYPE:
|
column_range
|
TYPE:
|
consensus_seq
|
Gapped deRIP'd consensus, required when
TYPE:
|
title
|
Figure title. Defaults to a description of the mode.
TYPE:
|
width
|
Figure width in inches. Defaults to a width scaled to the column count, with no upper bound short of the matplotlib canvas limit.
TYPE:
|
height
|
Figure height in inches (default: 4.2).
TYPE:
|
dpi
|
Raster resolution (default: 300).
TYPE:
|
max_columns
|
Refuse to draw more than this many bars. Unset by default: long alignments are drawn in full, on the assumption that the output is vector and can be zoomed.
TYPE:
|
emphasis
|
Wash the columns in which the current mode observed a transition, and fade the bars and letters of the columns that merely provide context (default: True).
TYPE:
|
ax
|
Draw into an existing axes instead of creating a figure.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Figure
|
The figure containing the chart. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If an option is unrecognised, if |
Notes
Bars above the axis are forward-strand columns; bars below are reverse-strand columns. Columns where neither strand holds a majority carry no correction and are marked with a hatched band rather than dropped silently.
Examples:
report
Self-contained HTML report of a deRIP2 strand-bias analysis.
Figures are embedded as inline SVG rather than linked or base64-encoded raster images: the report stays a single file, the figures remain vector (so they can be zoomed or lifted straight into a manuscript), and no external asset is ever fetched.
write_html_report
Write a single-file HTML report of the strand-bias analysis.
| PARAMETER | DESCRIPTION |
|---|---|
derip
|
A DeRIP object on which
TYPE:
|
output_file
|
Destination path.
TYPE:
|
title
|
Report heading. Defaults to
TYPE:
|
ambiguous
|
Ambiguity policy used for RSI (default:
TYPE:
|
**kwargs
|
Forwarded to each figure, e.g.
DEFAULT:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
The path written. |
Notes
Panels that cannot be drawn — for instance because a max_columns limit
was passed and exceeded — are reported inline as a note rather than aborting
the report.
Per-sequence reporting
persequence
Single-sequence figures for the per-sequence HTML report.
These render one alignment row at a time, in the same visual system as the
alignment-wide strand-bias chart (:mod:derip2.plotting.strandbias): the same
colourblind-validated palette, typography and light publication surface, so the
per-sequence report reads as one document with the rest of the package.
Two figures are provided:
- :func:
per_sequence_strand_bias— a fixed-height binary bar strip showing, for one sequence, which RIP-like columns carry a forward-strand event (above the axis) or a reverse-strand event (below), coloured by whether the base is the RIP product or the surviving substrate. - :func:
sequence_row_strip— the subject and deRIP'd reference rows drawn base-by-base, with RIP-like columns shaded as in the alignment-wide plot. - :func:
rip_completion_bar/ :func:gc_content_bar— small horizontal stacked-bar summaries.
All return the matplotlib figure so the report can embed it as inline SVG.
per_sequence_strand_bias
per_sequence_strand_bias(cls, row_index: int, *, seq_id: Optional[str] = None, title: Optional[str] = None, height: float = 2.2, width: Optional[float] = None, dpi: int = 300, outfile: Optional[str] = None, ax=None)
Draw a fixed-height binary strand-bias strip for a single sequence.
Every RIP-like column that this sequence participates in becomes one bar of unit height. A forward-strand event is drawn above the axis, a reverse-strand event below it, and the bar is coloured by the role the sequence's base plays: the RIP product (the deaminated base) or the surviving substrate.
Because a cell holds one base, each column contributes at most one bar: a forward product (T of TpA), a forward substrate (C of CpA), a reverse product (A of TpA) or a reverse substrate (G of TpG). The four are mutually exclusive per cell, so the strip is unambiguous.
| PARAMETER | DESCRIPTION |
|---|---|
cls
|
Classification of the whole alignment; only row
TYPE:
|
row_index
|
Index of the sequence (alignment row) to plot.
TYPE:
|
seq_id
|
Sequence identifier, used in the default title.
TYPE:
|
title
|
Figure title. Defaults to a description naming
TYPE:
|
height
|
Figure height in inches (default: 2.2).
TYPE:
|
width
|
Figure width in inches. Defaults to a width scaled to the number of
columns (:func:
TYPE:
|
dpi
|
Raster resolution when
TYPE:
|
outfile
|
Path to write the figure to. When
TYPE:
|
ax
|
Existing axes to draw on. When given, no new figure is created and
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Figure
|
The figure the strip was drawn on. |
sequence_row_strip
sequence_row_strip(cls, row_index: int, *, seq_id: Optional[str] = None, consensus_seq: Optional[str] = None, cds_tracks=None, title: Optional[str] = None, height: float = 1.0, width: Optional[float] = None, dpi: int = 300, outfile: Optional[str] = None)
Draw the subject and deRIP'd reference rows as base-coloured strips.
Both aligned sequences are drawn base-by-base, coloured by nucleotide
identity with the shared palette (A green, C blue, G violet, T red; gaps
white). The subject is drawn on top and the reconstructed deRIP'd reference
below it, separated by a narrow gap. Triangle markers above the subject flag
its role at each column, and columns the whole-alignment strand-bias analysis
marks as RIP-like — those carrying a RIP product on either strand anywhere in
the alignment — are shaded with the same hueless wash used by
:func:derip2.plotting.strandbias.plot_strand_bias.
| PARAMETER | DESCRIPTION |
|---|---|
cls
|
Classification of the whole alignment; row
TYPE:
|
row_index
|
Index of the subject sequence (alignment row) to draw.
TYPE:
|
seq_id
|
Subject sequence identifier, used to label its row.
TYPE:
|
consensus_seq
|
The deRIP'd reference (one base per column), drawn as the second row.
TYPE:
|
cds_tracks
|
Gene-annotation tracks to draw in a sub-plot below the alignment rows,
each
TYPE:
|
title
|
Figure title. Untitled by default (the report supplies a heading).
TYPE:
|
height
|
Figure height in inches (default: 1.0).
TYPE:
|
width
|
Figure width in inches. Defaults to a width scaled to the number of columns; pass an explicit value to match the strand-bias strip so the two line up column-for-column in a scrolling container.
TYPE:
|
dpi
|
Raster resolution when
TYPE:
|
outfile
|
Path to write the figure to. When
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Figure
|
The figure the strip was drawn on. |
rip_completion_bar
rip_completion_bar(stats, *, title: Optional[str] = None, width: float = 6.6, height: float = 1.7, dpi: int = 300, outfile: Optional[str] = None)
Draw horizontal stacked bars of the fraction of RIP-like sites that are RIP'd.
For each strand, the available RIP-like sites are the surviving substrate dinucleotides plus the RIP products (converted sites). The bar shows what fraction of that substrate has been converted — the RIP product segment — against the intact substrate, so a nearly full blue bar is a heavily RIP'd strand and a nearly empty one has escaped RIP.
Three bars are drawn: forward, reverse and the two combined.
| PARAMETER | DESCRIPTION |
|---|---|
stats
|
A per-sequence statistics row exposing
TYPE:
|
title
|
Figure title.
TYPE:
|
width
|
Figure size in inches. Fixed by default so the bars line up across the per-sequence report's pages.
TYPE:
|
height
|
Figure size in inches. Fixed by default so the bars line up across the per-sequence report's pages.
TYPE:
|
dpi
|
Raster resolution when
TYPE:
|
outfile
|
Path to write the figure to. When
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Figure
|
The figure the bars were drawn on. |
gc_content_bar
gc_content_bar(stats, *, title: Optional[str] = None, width: float = 6.6, height: float = 1.0, dpi: int = 300, outfile: Optional[str] = None)
Draw a horizontal stacked bar of this sequence's GC content.
The bar is split into the G+C fraction (filled) and the A+T remainder, with the percentage labelled. RIP lowers GC by converting C to T, so a low bar is consistent with heavy RIP.
| PARAMETER | DESCRIPTION |
|---|---|
stats
|
A per-sequence statistics row exposing
TYPE:
|
title
|
Figure title.
TYPE:
|
width
|
Figure size in inches. Fixed by default so the bar lines up across pages.
TYPE:
|
height
|
Figure size in inches. Fixed by default so the bar lines up across pages.
TYPE:
|
dpi
|
Raster resolution when
TYPE:
|
outfile
|
Path to write the figure to. When
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Figure
|
The figure the bar was drawn on. |
resolve_cmap
Coerce a user-supplied colormap specification to a matplotlib colormap.
Lets callers restyle the conversion heatmap without importing matplotlib:
a name selects any registered colormap (append _r to reverse it), a list
of colours builds a custom ramp, and a colormap object is taken as given. In
every case the "no data" colour is set to :data:NO_DATA_COLOR, so empty
cells stay consistent with the rest of the report whatever palette is in
use.
| PARAMETER | DESCRIPTION |
|---|---|
cmap
|
One of:
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Colormap
|
The resolved colormap, with its "bad" (no-data) colour set. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
TypeError
|
If |
Examples:
text_color_on
Pick black or white text for maximum contrast against a background colour.
Uses the WCAG relative luminance (a linearised, weighted sum of the channels) rather than the gamma-encoded approximation, so the choice matches what the contrast standard would score.
| PARAMETER | DESCRIPTION |
|---|---|
rgb
|
Background colour as
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
|
persequence_report
Self-contained, interactive per-sequence HTML report.
Where :mod:derip2.report gives one alignment-wide view of strand bias, this
module gives one panel per input sequence: the alignment row with its RIP
sites highlighted, a fixed-height per-sequence strand-bias strip, a per-sequence
SBS-96 mutation spectrum measured against the reconstructed ancestor, and that
sequence's summary statistics. The panels are stacked in a single HTML file and
shown one at a time; the reader steps between sequences with the arrow keys or
the prev/next buttons.
As with :mod:derip2.report, every figure is embedded as inline SVG so the
report is a single self-contained file with no external assets. Each figure is
given a unique ID prefix (s{row}{kind}-) because matplotlib reuses element
IDs across figures and a browser resolves href="#id" to the first match in
the document — without unique prefixes, later figures would borrow the first
figure's glyphs.
write_per_sequence_report
write_per_sequence_report(derip, output_file, *, title=None, ambiguous='split', max_seqs=None, gff=None, genetic_code=1, spectra_ref_index=None, flank_length=1)
Write a single-file, arrow-key-navigable per-sequence HTML report.
| PARAMETER | DESCRIPTION |
|---|---|
derip
|
A DeRIP object on which
TYPE:
|
output_file
|
Destination path.
TYPE:
|
title
|
Report heading. Defaults to
TYPE:
|
ambiguous
|
Ambiguity policy used for the per-sequence RSI statistics
(default:
TYPE:
|
max_seqs
|
Cap the number of sequence panels. When the alignment has more sequences
than this, the first
TYPE:
|
gff
|
Path to a GFF3 gene model. When given, each annotated sequence's panel gains a gene-effect table and the deRIP-restored protein.
TYPE:
|
genetic_code
|
NCBI translation table for the effect prediction (default: 1).
TYPE:
|
spectra_ref_index
|
Alignment row index of a sequence to use as the reference for the mutation spectra (per-sequence and the pooled overview), instead of the default deRIP-corrected consensus. Supports negative indexing. The reference sequence's own panel then shows an empty (self-comparison) spectrum.
TYPE:
|
flank_length
|
Number of flanking bases each side of a RIP-like dinucleotide for the flank-context spectra and conversion heatmap (default 1 → 4×4 grid; 2 → 16×16).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
The path written. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
Notes
Rendering hundreds of sequences produces hundreds of inline-SVG figures and
a correspondingly large file; max_seqs is the recommended mitigation for
large alignments.
Gene annotation and RIP effect prediction
annotation
GFF3 gene annotation and RIP effect prediction over a gapped alignment.
deRIP2 reconstructs an un-RIP'd ancestral sequence for a family of aligned repeats. When a gene model is supplied for one or more of those sequences, this module answers a follow-on question: what did RIP do to the protein? It
- parses a GFF3 file into per-sequence genes (:func:
parse_gff3), - maps each gene's ungapped coordinates onto gapped alignment columns
(:func:
ungapped_to_column_map), so a feature lines up with the alignment, and - translates each sequence's CDS and compares it to the reconstructed ancestor,
reporting premature stops, non-synonymous changes, frameshifts and broken
splice sites (:func:
predict_gene_effects, :func:translate_cds).
GFF3 coordinates are 1-based and inclusive, in the ungapped sequence's own frame; the alignment is gapped. The coordinate map is the bridge between the two.
No new dependency is introduced: GFF3 is parsed with the standard library and
translation uses Biopython's :meth:Bio.Seq.Seq.translate, already a project
dependency. The genetic code defaults to the NCBI standard table (1) and is
configurable for organisms that use an alternate code.
Gene
dataclass
A gene grouped to its coding exons, in transcription order via strand.
| ATTRIBUTE | DESCRIPTION |
|---|---|
gene_id |
Identifier for the gene / transcript the CDS features belong to.
TYPE:
|
seqid |
Sequence identifier, matched against alignment record IDs.
TYPE:
|
strand |
TYPE:
|
cds |
CDS features, sorted by
TYPE:
|
Feature
dataclass
Feature(seqid: str, ftype: str, start: int, end: int, strand: str, phase: Optional[int], attributes: Dict[str, str], feature_id: Optional[str], parent: Optional[str])
One GFF3 feature line, coordinates 1-based inclusive on the forward strand.
| ATTRIBUTE | DESCRIPTION |
|---|---|
seqid |
Sequence identifier; matched against alignment record IDs.
TYPE:
|
ftype |
Feature type (
TYPE:
|
start, end |
1-based inclusive bounds in the ungapped sequence's own coordinates.
TYPE:
|
strand |
TYPE:
|
phase |
CDS phase (0, 1 or 2) where given, else
TYPE:
|
attributes |
Parsed column-9 key/value attributes.
TYPE:
|
feature_id |
The
TYPE:
|
parent |
The
TYPE:
|
EffectRecord
dataclass
EffectRecord(seq_id: str, gene_id: str, kind: str, aa_pos: Optional[int] = None, ref_aa: Optional[str] = None, alt_aa: Optional[str] = None, gapped_col: Optional[int] = None, nt_ref: Optional[str] = None, nt_alt: Optional[str] = None)
One predicted effect of RIP on a sequence's coding sequence.
| ATTRIBUTE | DESCRIPTION |
|---|---|
seq_id |
The sequence the effect was found in.
TYPE:
|
gene_id |
The gene / transcript affected.
TYPE:
|
kind |
One of
TYPE:
|
aa_pos |
1-based amino-acid position of the change (
TYPE:
|
ref_aa, alt_aa |
Ancestral and observed amino acid (or splice dinucleotide) at the site.
TYPE:
|
gapped_col |
Alignment column of the affected codon's middle base (or the splice site), for cross-referencing the figures.
TYPE:
|
nt_ref, nt_alt |
Ancestral and observed nucleotide context, where meaningful.
TYPE:
|
parse_gff3
Parse a GFF3 file into genes grouped by sequence identifier.
CDS features are grouped by their Parent (falling back to the mRNA/gene
ID or a synthesised key) and sorted into forward-strand order. Only the
gene hierarchy is retained; other feature types are ignored.
| PARAMETER | DESCRIPTION |
|---|---|
path
|
Path to the GFF3 file.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict of str to list of Gene
|
Mapping of sequence identifier to its genes, in first-seen order. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If a coordinate field is not an integer or start > end. |
Notes
A gene whose CDS features disagree on strand is dropped with a warning: a single transcript cannot be transcribed from both strands.
ungapped_to_column_map
Map a sequence's ungapped positions to their gapped alignment columns.
| PARAMETER | DESCRIPTION |
|---|---|
row_bytes
|
A single alignment row as an
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ndarray
|
Int array where element |
predict_gene_effects
predict_gene_effects(gene: Gene, target_row: ndarray, ref_row: ndarray, ungapped_to_col: ndarray, *, seq_id: str = '', genetic_code: int = 1, include_synonymous: bool = False) -> List[EffectRecord]
Predict the coding effects of RIP on one sequence, versus the ancestor.
The gene's CDS is assembled in transcription order for both the observed
sequence (target_row) and the reconstructed ancestor (ref_row),
translated, and compared codon by codon. Length differences that are not a
multiple of three are reported as frameshifts; canonical splice boundaries
broken in the target are reported as splice-site effects.
| PARAMETER | DESCRIPTION |
|---|---|
gene
|
The gene to evaluate.
TYPE:
|
target_row
|
The observed and ancestral alignment rows (
TYPE:
|
ref_row
|
The observed and ancestral alignment rows (
TYPE:
|
ungapped_to_col
|
The observed sequence's ungapped-to-column map, used to place the CDS.
TYPE:
|
seq_id
|
Identifier stamped onto each returned record.
TYPE:
|
genetic_code
|
NCBI translation table (default: 1).
TYPE:
|
include_synonymous
|
Also emit
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list of EffectRecord
|
Effects in codon order, splice-site effects appended. |
translate_cds
translate_cds(gene: Gene, row_bytes: ndarray, ungapped_to_col: ndarray, genetic_code: int = 1) -> str
Translate one sequence's CDS for a gene, rendering stops as '*'.
| PARAMETER | DESCRIPTION |
|---|---|
gene
|
The gene to translate.
TYPE:
|
row_bytes
|
The sequence's alignment row (
TYPE:
|
ungapped_to_col
|
The sequence's ungapped-to-column map.
TYPE:
|
genetic_code
|
NCBI translation table (default: 1, the standard code).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
The amino-acid sequence, |
compute_effects_for_alignment
compute_effects_for_alignment(derip, genes_by_seqid: Dict[str, List[Gene]], genetic_code: int = 1) -> Dict[str, List[EffectRecord]]
Predict RIP effects for every annotated sequence in a DeRIP alignment.
Each gene is evaluated against the reconstructed ancestor (deRIP2's gapped consensus). Genes whose sequence identifier is not in the alignment are skipped.
| PARAMETER | DESCRIPTION |
|---|---|
derip
|
A DeRIP object on which
TYPE:
|
genes_by_seqid
|
Parsed genes keyed by sequence identifier.
TYPE:
|
genetic_code
|
NCBI translation table (default: 1).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict of str to list of EffectRecord
|
Effects keyed by sequence identifier (only sequences with a gene and at least one effect appear). |
deripd_translations
deripd_translations(derip, genes_by_seqid: Dict[str, List[Gene]], genetic_code: int = 1) -> Dict[str, str]
Translate each gene's CDS on the reconstructed deRIP'd sequence.
Columns are taken from the gene's owning sequence, but the bases are read from the deRIP'd consensus, so the returned protein is what the restored (un-RIP'd) coding sequence encodes.
| PARAMETER | DESCRIPTION |
|---|---|
derip
|
A DeRIP object on which
TYPE:
|
genes_by_seqid
|
Parsed genes keyed by sequence identifier.
TYPE:
|
genetic_code
|
NCBI translation table (default: 1).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict of str to str
|
Gene identifier to amino-acid string ( |
write_snp_effects
write_snp_effects(output_file: str, effects_by_seq: Dict[str, List[EffectRecord]], deripd_aa: Dict[str, str]) -> str
Write a tab-separated summary of RIP coding effects.
| PARAMETER | DESCRIPTION |
|---|---|
output_file
|
Destination path.
TYPE:
|
effects_by_seq
|
Per-sequence effects (:func:
TYPE:
|
deripd_aa
|
Per-gene deRIP'd translations (:func:
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
The path written. |
build_annotation_spans
build_annotation_spans(genes_by_seqid: Dict[str, List[Gene]], row_lookup: Dict[str, ndarray], colors: Optional[Dict[str, str]] = None) -> List[Tuple[int, int, str, str, int]]
Project gene CDS exons onto alignment columns as stacked track spans.
Each gene occupies its own track row; its CDS exons are drawn as separate
coloured spans (gaps split an exon into contiguous column runs). The result
is ready to pass to
:func:derip2.plotting.minialign.drawMiniAlignment as annotation_track.
| PARAMETER | DESCRIPTION |
|---|---|
genes_by_seqid
|
Parsed genes keyed by sequence identifier.
TYPE:
|
row_lookup
|
Maps each sequence identifier to its alignment row (
TYPE:
|
colors
|
Feature-type colour map; defaults to :data:
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list of tuple
|
|
load_annotation_colors
Load a two-column type<TAB>hex annotation-colour override file.
| PARAMETER | DESCRIPTION |
|---|---|
path
|
Path to a whitespace/tab-separated file of
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict of str to str
|
Feature type to colour, merged over :data: |
Mutation spectra statistics
mutation_spectra
Trinucleotide-context substitution spectra (SBS-96 / SBS-192) from an alignment.
This module computes single-base-substitution spectra by comparing every aligned sequence to an inferred ancestral reference (deRIP2's reconstructed consensus) and reading each substitution's trinucleotide context from that ancestor. It is the tree-free baseline method: every difference between a tip and the single reference is counted as one event, with its 5'/3' context taken from the nearest non-gap ancestral bases.
Because there is no phylogeny, recurrence can only be reported as a multi-hit
column proxy: how many sequences independently carry each derived state at a
site. True independent-event counting requires ancestral reconstruction on a tree
and is provided by the phylogenetic path in :mod:derip2.spectra (later
milestone). The API here is deliberately event-stream shaped so that path can
reuse the same channel assembly.
See Also
derip2.spectra.channels : SBS-96/192 channel ordering and pyrimidine folding. derip2.stats.strand_bias : The RSI statistic, the sibling per-alignment measure.
SpectraResult
dataclass
SpectraResult(sbs96: ndarray, sbs192: Optional[ndarray], sample_names: List[str], event_rows: ndarray, event_cols: ndarray, event_ref: ndarray, event_alt: ndarray, event_five: Optional[ndarray], event_three: Optional[ndarray], event_sample: ndarray, homoplasy_counts: ndarray, ancestor_ref: ndarray, n_indel_or_ambiguous: int, n_unassignable_context: int, method: str = 'baseline', context: str = 'trinucleotide', event_parent_names: Optional[List[str]] = None, event_child_names: Optional[List[str]] = None, event_down1: Optional[ndarray] = None, event_down2: Optional[ndarray] = None)
Trinucleotide-context substitution spectra for an alignment.
| ATTRIBUTE | DESCRIPTION |
|---|---|
sbs96 |
TYPE:
|
sbs192 |
TYPE:
|
sample_names |
Column labels for the matrices, one per sample.
TYPE:
|
event_rows, event_cols |
TYPE:
|
event_ref, event_alt |
TYPE:
|
event_five, event_three |
TYPE:
|
event_down1, event_down2 |
TYPE:
|
event_sample |
TYPE:
|
homoplasy_counts |
TYPE:
|
ancestor_ref |
TYPE:
|
n_indel_or_ambiguous |
Number of tip/ancestor differences skipped because one side was a gap or a non-ACGT base (not a callable substitution).
TYPE:
|
n_unassignable_context |
Number of substitutions dropped because a full trinucleotide context could not be resolved (terminal columns).
TYPE:
|
method |
TYPE:
|
context |
TYPE:
|
event_parent_names, event_child_names |
For the phylogenetic path, the parent and child node names of every
event's edge (
TYPE:
|
sbs96_channels
property
Canonical SBS-96 channel labels, aligned to :attr:sbs96 rows.
| RETURNS | DESCRIPTION |
|---|---|
list of str
|
The 96 channel labels in row order. |
sbs192_channels
property
Canonical SBS-192 channel labels, aligned to :attr:sbs192 rows.
| RETURNS | DESCRIPTION |
|---|---|
list of str
|
The 192 channel labels in row order. |
downstream_channels
property
Canonical downstream-triplet channel labels, aligned to :attr:sbs96 rows.
Only meaningful when :attr:context is 'downstream' (the sbs96
array then holds the downstream counts).
| RETURNS | DESCRIPTION |
|---|---|
list of str
|
The 96 downstream channel labels in row order. |
event_records
Return every counted substitution as a list of dictionaries.
| RETURNS | DESCRIPTION |
|---|---|
list of dict
|
One dictionary per event, in discovery order, with keys |
homoplasy_table
Return substitutions that recurred in >= min_hits independent lineages.
Recurrence is counted over the actual per-event reference and derived bases (the parent base for the phylogenetic path, the ancestor for the baseline), so a column hit by two distinct substitutions is reported as two separate entries and the reference base is always the base the event mutated from.
| PARAMETER | DESCRIPTION |
|---|---|
min_hits
|
Minimum number of independent lineages carrying the same
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list of dict
|
One dictionary per recurrent |
as_dict
Return a JSON-serialisable summary of the spectra.
Used for golden regression tests. Event-level detail is omitted; the matrices, sample names, homoplasy hits and skip counts fully pin the result.
| RETURNS | DESCRIPTION |
|---|---|
dict
|
Nested dictionary of the SBS-96/192 matrices (as nested lists), the sample names, the >= 2 homoplasy table and the two skip counts. |
compute_spectra
compute_spectra(column_classes, ancestor_seq: str, *, samples: Optional[Sequence[str]] = None, context: str = 'trinucleotide') -> SpectraResult
Compute trinucleotide or downstream-triplet spectra against an ancestor.
Every alignment cell whose base differs from the ancestral base at that
column, where both are unambiguous (ACGT), is counted as one substitution
event. The context is read from the ancestor using the nearest non-gap bases:
context='trinucleotide'(default): the 5'/3' flanks, matching the Alexandrov reference-context convention. Events are folded to the pyrimidine strand for SBS-96 and kept strand-resolved for SBS-192.context='downstream': the two bases downstream of the mutated base on the pyrimidine strand (CHG-aware), producing a single pyrimidine-folded 96-channel matrix.sbs192isNonein this mode.
| PARAMETER | DESCRIPTION |
|---|---|
column_classes
|
The cached per-cell classification; only its
TYPE:
|
ancestor_seq
|
The gapped ancestral/consensus sequence, one base per alignment column
(deRIP2's
TYPE:
|
samples
|
Per-row sample label to split the matrices by (length
TYPE:
|
context
|
Which sequence context to classify substitutions by (default:
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
SpectraResult
|
The assembled spectra, per-event detail, homoplasy proxy and skip counts. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
assemble_matrices
assemble_matrices(five_c: ndarray, ref_c: ndarray, alt_c: ndarray, three_c: ndarray, sample_c: ndarray, n_samples: int, weights: Optional[ndarray] = None) -> Tuple[np.ndarray, np.ndarray]
Accumulate an event stream into SBS-96 and SBS-192 count matrices.
This is the single assembly core shared by the tree-free baseline and the
phylogenetic branch-traversal path. Each event is a tuple of base codes
(five, ref, alt, three) plus the sample it belongs to; the
precomputed :data:IDX96_TABLE / :data:IDX192_TABLE map it to its two
channel rows.
| PARAMETER | DESCRIPTION |
|---|---|
five_c
|
TYPE:
|
ref_c
|
TYPE:
|
alt_c
|
TYPE:
|
three_c
|
TYPE:
|
sample_c
|
TYPE:
|
n_samples
|
Number of sample columns in the output matrices.
TYPE:
|
weights
|
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple of numpy.ndarray
|
|
assemble_downstream
assemble_downstream(down1_c: ndarray, ref_c: ndarray, alt_c: ndarray, down2_c: ndarray, sample_c: ndarray, n_samples: int, weights: Optional[ndarray] = None) -> np.ndarray
Accumulate an event stream into a downstream-triplet count matrix.
Uses the same gather-and-scatter core as :func:assemble_matrices but with the
downstream channel-index table :data:IDX_DS_TABLE. The two context codes are
the pyrimidine-strand downstream bases resolved by
:func:derip2.spectra.channels.downstream_context.
| PARAMETER | DESCRIPTION |
|---|---|
down1_c
|
TYPE:
|
ref_c
|
TYPE:
|
alt_c
|
TYPE:
|
down2_c
|
TYPE:
|
sample_c
|
TYPE:
|
n_samples
|
Number of sample columns in the output matrix.
TYPE:
|
weights
|
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ndarray
|
The |
Mutation spectra plotting
spectra
Native matplotlib figures for SBS-96 / SBS-192 mutation spectra.
These reproduce the familiar SigProfiler spectrum layouts — the six-block SBS-96
bar plot, the twelve-block strand-resolved SBS-192 plot, a strand-asymmetry panel
and a homoplasy (recurrence) plot — without depending on SigProfilerPlotting. The
palette, typography and light publication surface are shared with the strand-bias
figures (:mod:derip2.plotting.strandbias) so the whole package renders as one
visual system.
All public functions accept a :class:derip2.stats.mutation_spectra.SpectraResult
and, optionally, an output path. They return the matplotlib figure so callers can
compose or further style it.
plot_sbs96
plot_sbs96(result, outfile: Optional[str] = None, *, title: Optional[str] = None, percentage: bool = False, dpi: int = 300, sample: Optional[int] = None, width: float = 11.0, bare: bool = False)
Draw the canonical six-block SBS-96 spectrum, one panel per sample.
| PARAMETER | DESCRIPTION |
|---|---|
result
|
The computed spectra.
TYPE:
|
outfile
|
Output path; when
TYPE:
|
title
|
Figure title.
TYPE:
|
percentage
|
Plot each sample as a percentage of its total (default: counts).
TYPE:
|
dpi
|
Raster resolution (default: 300).
TYPE:
|
sample
|
Draw only this single sample (by column index into
:attr:
TYPE:
|
width
|
Figure width in inches (default: 11.0). Wider than a page so the 96 trinucleotide ticks so they do not overlap.
TYPE:
|
bare
|
Omit the per-sample title and the context caption/suptitle (default: False). Use when an embedding caller supplies its own heading, to avoid a redundant sample label overlapping the title.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Figure
|
The rendered figure. |
| RAISES | DESCRIPTION |
|---|---|
IndexError
|
If |
plot_sbs192
plot_sbs192(result, outfile: Optional[str] = None, *, title: Optional[str] = None, percentage: bool = False, dpi: int = 300)
Draw the strand-resolved twelve-block SBS-192 spectrum, one panel per sample.
| PARAMETER | DESCRIPTION |
|---|---|
result
|
The computed spectra.
TYPE:
|
outfile
|
Output path; when
TYPE:
|
title
|
Figure title.
TYPE:
|
percentage
|
Plot each sample as a percentage of its total (default: counts).
TYPE:
|
dpi
|
Raster resolution (default: 300).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Figure
|
The rendered figure. |
plot_downstream
plot_downstream(result, outfile: Optional[str] = None, *, title: Optional[str] = None, percentage: bool = False, dpi: int = 300, sample: Optional[int] = None, width: float = 11.0, bare: bool = False)
Draw the pyrimidine-folded downstream-triplet spectrum, one panel per sample.
The six substitution blocks mirror the SBS-96 layout, but each bar is
classified by the mutated base plus its two downstream bases (motif
ref d1 d2, first base bold). The downstream counts are read from
result.sbs96 (which holds the 96-channel matrix for the downstream context).
| PARAMETER | DESCRIPTION |
|---|---|
result
|
The computed spectra (
TYPE:
|
outfile
|
Output path; when
TYPE:
|
title
|
Figure title.
TYPE:
|
percentage
|
Plot each sample as a percentage of its total (default: counts).
TYPE:
|
dpi
|
Raster resolution (default: 300).
TYPE:
|
sample
|
Draw only this single sample (by column index into
:attr:
TYPE:
|
width
|
Figure width in inches (default: 11.0). Wider than a page so the 96 downstream ticks so they do not overlap.
TYPE:
|
bare
|
Omit the per-sample title and the context caption/suptitle (default: False), for embedding under an external heading.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Figure
|
The rendered figure. |
| RAISES | DESCRIPTION |
|---|---|
IndexError
|
If |
strand_asymmetry
Summarise coding- versus template-strand counts per pyrimidine class.
For each of the six pyrimidine substitution classes, the coding-strand count is the sum of its SBS-192 channels and the template-strand count is the sum of its reverse-complement purine partner's channels. A binomial test against an even 50/50 split gives a screening p-value for strand bias.
| PARAMETER | DESCRIPTION |
|---|---|
result
|
The computed spectra.
TYPE:
|
sample
|
Sample column to summarise (default: 0).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list of dict
|
One dict per pyrimidine class with keys |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the result has no SBS-192 matrix (the downstream context). |
plot_strand_asymmetry
plot_strand_asymmetry(result, outfile: Optional[str] = None, *, sample: int = 0, min_count: int = 10, title: Optional[str] = None, dpi: int = 300)
Plot coding- versus template-strand counts for each pyrimidine class.
| PARAMETER | DESCRIPTION |
|---|---|
result
|
The computed spectra.
TYPE:
|
outfile
|
Output path; when
TYPE:
|
sample
|
Sample column to plot (default: 0).
TYPE:
|
min_count
|
A class is only tested (and starred) when both strands carry at least this many events (default: 10). A strand with near-zero counts gives an unstable binomial test, so such classes are drawn but not flagged.
TYPE:
|
title
|
Figure title.
TYPE:
|
dpi
|
Raster resolution (default: 300).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Figure
|
The rendered figure. |
plot_homoplasy
plot_homoplasy(result, outfile: Optional[str] = None, *, min_hits: int = 2, title: Optional[str] = None, dpi: int = 300)
Plot alignment columns hit by the same substitution in >= min_hits rows.
Each qualifying (column, derived base) is a stem whose height is the number of independent sequences carrying it, coloured by its pyrimidine-folded substitution class. This is the baseline recurrence proxy.
| PARAMETER | DESCRIPTION |
|---|---|
result
|
The computed spectra.
TYPE:
|
outfile
|
Output path; when
TYPE:
|
min_hits
|
Minimum independent hits for a site to be drawn (default: 2).
TYPE:
|
title
|
Figure title.
TYPE:
|
dpi
|
Raster resolution (default: 300).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Figure
|
The rendered figure. |
Spectra comparison
spectra_compare
Statistical comparison of mutation spectra.
Two spectra (e.g. two species, two clades, or two precalculated SBS matrices) can be compared in two complementary ways:
- Cosine similarity — a scale-free effect size in
[0, 1]. 1.0 means the two channel profiles have identical shape; lower values mean they differ. It ignores the total number of events, so it answers "do these look alike?". - Chi-squared test of homogeneity — a significance test of whether the channel counts could have come from one shared distribution. It answers "is the difference more than sampling noise?", and its per-channel standardised residuals show which channels drive any difference.
The two are used together: with very large spectra almost any difference is "significant", so read the p-value alongside the cosine similarity (how different) and the residuals (different where).
The chi-squared p-value is computed here from the regularised incomplete gamma function, so this module needs no SciPy — consistent with the rest of deRIP2's hand-rolled statistics.
cosine_similarity
Cosine similarity between two spectra vectors.
| PARAMETER | DESCRIPTION |
|---|---|
a
|
Channel count (or proportion) vectors of equal length.
TYPE:
|
b
|
Channel count (or proportion) vectors of equal length.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
float
|
Cosine similarity in |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the two vectors have different lengths. |
chi2_homogeneity
Chi-squared test of homogeneity across the columns of a count matrix.
The null hypothesis is that every column (sample/group) draws its channel counts from the same underlying distribution. Channels that are empty across all samples are dropped and the degrees of freedom reduced accordingly.
| PARAMETER | DESCRIPTION |
|---|---|
matrix
|
TYPE:
|
sample_names
|
Column labels, used only for the returned summary.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the matrix has fewer than two columns or contains negative counts. |
compare_spectra
compare_spectra(a: Sequence[float], b: Sequence[float], channels: Optional[Sequence[str]] = None, *, top: int = 8) -> Dict
Compare two spectra: cosine similarity plus a chi-squared homogeneity test.
| PARAMETER | DESCRIPTION |
|---|---|
a
|
Channel count vectors of equal length (e.g. two group columns, or one column from each of two precalculated matrices in the same context).
TYPE:
|
b
|
Channel count vectors of equal length (e.g. two group columns, or one column from each of two precalculated matrices in the same context).
TYPE:
|
channels
|
Channel labels, used to report the most differentiating channels.
TYPE:
|
top
|
How many top differentiating channels to return (default: 8).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the vectors differ in length, or |
compare_matrix_files
compare_matrix_files(path_a: str, path_b: str, *, sample_a: int = 0, sample_b: int = 0, top: int = 8) -> Dict
Compare two spectra matrix files, guarding that they share a context.
Each file is read with :func:derip2.spectra.matrix_io.read_sbs_matrix; the
two channel-label lists must match exactly (same membership and order), which
guarantees the matrices describe the same sequence context. One sample column
from each file is then compared with :func:compare_spectra.
| PARAMETER | DESCRIPTION |
|---|---|
path_a
|
Paths to two
TYPE:
|
path_b
|
Paths to two
TYPE:
|
sample_a
|
Which sample column of each file to compare (default:
TYPE:
|
sample_b
|
Which sample column of each file to compare (default:
TYPE:
|
top
|
How many top differentiating channels to return (default:
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
The :func: |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the two files use different channel sets (contexts), or if a requested sample column is out of range. |
pairwise_compare
pairwise_compare(matrix: ndarray, sample_names: Sequence[str], *, correction: str = 'bonferroni') -> List[Dict]
Compare every pair of sample columns with a chi-squared homogeneity test.
| PARAMETER | DESCRIPTION |
|---|---|
matrix
|
TYPE:
|
sample_names
|
Column labels, one per sample.
TYPE:
|
correction
|
Multiple-testing correction applied to the pairwise p-values (default:
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list of dict
|
One dict per pair with |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
Flank-context spectra statistics
flank_spectra
Flanking-context spectra of RIP-like sites from an alignment.
This module answers a specific biological question: among the RIP substrate
dinucleotides (CpA, or TpG when the CpA is on the reverse strand) that
survive in otherwise RIP-affected sequences, is there a local sequence context
that protects them from deamination? To probe it we classify every RIP-like
dinucleotide by the single base one position upstream and one downstream — a 4 bp
motif [up][center][down] — and compare the flank-context distribution of
surviving substrate sites against that of realised product (TpA) sites.
Two site states are counted per sequence, using the boolean cell masks of a
:class:derip2.aln_ops.ColumnClassification (the single source of truth for RIP
context, gap-aware over nearest non-gap neighbours):
- Substrate —
cls.ca(Cfollowed byA) andcls.tg(Gpreceded byT), counted anywhere in the sequence, not only in RIP-informative columns. This deliberately uses the raw dinucleotide masks, not thect_ok/ga_ok-gatedsub_fwd/sub_revused by the strand-bias statistic, because the question is about every surviving substrate. - Product —
cls.prod_fwd(ta & fwd_col) andcls.prod_rev(ta2 & rev_col): aTpAsitting in a column that also shows a surviving substrate, so the product is attributable to RIP.
Each state yields a (16, n_rows) count matrix (one column per alignment row),
folded so every reverse-strand motif is reverse-complemented onto the
CA/TA-equivalent channel (see :mod:derip2.spectra.flank_channels).
See Also
derip2.spectra.flank_channels : The 16-channel labelling and fold lookup. derip2.stats.spectra_compare : The cosine / chi-squared comparison reused here. derip2.stats.mutation_spectra : The sibling trinucleotide SBS-96/192 spectra.
FlankSpectraResult
dataclass
FlankSpectraResult(sub_fwd: ndarray, sub_rev: ndarray, prod_fwd: ndarray, prod_rev: ndarray, sample_names: List[str], n_skipped_flank: Dict[str, int], flank_length: int = 1, channels_substrate: List[str] = (lambda: list(FLANK16_LABELS_CA))(), channels_product: List[str] = (lambda: list(FLANK16_LABELS_TA))())
Per-sequence flanking-context spectra of RIP-like sites.
Four count matrices, each (n_channels, n_rows) with one column per
alignment row (the row is the sample index) and n_channels ==
4 ** (2 * flank_length) (16 for the default 1 bp flank). Every motif is folded
so its centre is CA (substrate) or TA (product) and its channel is
indexed by the resolved flanks (see :mod:derip2.spectra.flank_channels).
| ATTRIBUTE | DESCRIPTION |
|---|---|
sub_fwd, sub_rev |
TYPE:
|
prod_fwd, prod_rev |
TYPE:
|
sample_names |
Column labels, one per alignment row.
TYPE:
|
n_skipped_flank |
Per-state count of sites dropped because an up or down flank could not be
resolved to an
TYPE:
|
flank_length |
Number of flanking bases resolved on each side of the centre (default 1).
TYPE:
|
channels_substrate, channels_product |
The motif labels for the substrate (
TYPE:
|
substrate_combined
Combined-strand substrate spectrum.
| RETURNS | DESCRIPTION |
|---|---|
ndarray
|
|
product_combined
Combined-strand product spectrum.
| RETURNS | DESCRIPTION |
|---|---|
ndarray
|
|
matrix
Return one (16, n_rows) count matrix by state and strand.
| PARAMETER | DESCRIPTION |
|---|---|
state
|
Which site state to return.
TYPE:
|
strand
|
Which strand's counts (
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ndarray
|
The |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
pooled
Pool every sequence into a single alignment-wide spectrum per matrix.
| RETURNS | DESCRIPTION |
|---|---|
dict of str to numpy.ndarray
|
Keys :data: |
compute_flank_spectra
compute_flank_spectra(column_classes, sample_names: Optional[List[str]] = None, flank_length: int = 1) -> FlankSpectraResult
Compute per-sequence flanking-context spectra of RIP-like sites.
Substrate sites (cls.ca / cls.tg) are counted anywhere in each
sequence; product sites (cls.prod_fwd / cls.prod_rev) only in
RIP-informative columns. Gating is strictly per cell: a site contributes a
flank only when its own core dinucleotide satisfies one of those masks, so a
"noise" cell in a RIP-like column — a base that is neither the surviving
substrate nor the realised product (e.g. a G or an unrelated SNP) — is
False in every mask and never contributes a flank.
Each site's flank_length upstream and downstream bases are resolved over the
nearest non-gap neighbours and folded onto the CA/TA-equivalent channel,
giving 4 ** (2 * flank_length) channels (16 for the default 1 bp flank). The
computation is fully vectorised over the whole alignment; the alignment row is
the sample index, so no per-row Python loop is needed.
| PARAMETER | DESCRIPTION |
|---|---|
column_classes
|
The RIP classification, providing
TYPE:
|
sample_names
|
Per-row labels (length
TYPE:
|
flank_length
|
Number of flanking bases resolved on each side of the centre dinucleotide (default 1). Must be >= 1.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
FlankSpectraResult
|
The four |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
compare_flank_spectra
compare_flank_spectra(result: FlankSpectraResult, row_index: int, *, min_sites: int = 20, top: int = 6) -> Dict[str, Dict]
Run the five per-sequence flank-context comparisons for one alignment row.
Substrate (CA-centred) channel k and product (TA-centred) channel
k share the same (up, down) flank context, so the two spectra are
compared position-by-position as a like-for-like flank-context test (labelled
by the centre-agnostic up.down pair). The chi-squared p-value is only
trustworthy when both spectra carry enough sites; a chi2_reliable flag
records whether both totals reach min_sites so callers can lead with the
scale-free cosine effect size.
| PARAMETER | DESCRIPTION |
|---|---|
result
|
The computed spectra.
TYPE:
|
row_index
|
Which alignment row (sample column) to compare.
TYPE:
|
min_sites
|
Minimum site count on both sides for the chi-squared test to be flagged reliable (default: 20).
TYPE:
|
top
|
Number of most-differentiating flank channels to report per comparison (default: 6).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict of str to dict
|
Keyed by :data: |
compare_flank_spectra_pooled
compare_flank_spectra_pooled(result: FlankSpectraResult, *, min_sites: int = 20, top: int = 6) -> Dict[str, Dict]
Run the five flank-context comparisons on the alignment-wide pooled spectra.
Same five comparisons as :func:compare_flank_spectra, but on the counts
summed across every sequence (:meth:FlankSpectraResult.pooled), for the
report's overview page.
| PARAMETER | DESCRIPTION |
|---|---|
result
|
The computed spectra.
TYPE:
|
min_sites
|
Minimum site count on both sides for the reliability flag (default: 20).
TYPE:
|
top
|
Number of most-differentiating flank channels to report (default: 6).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict of str to dict
|
Keyed by :data: |
differential_channels
differential_channels(substrate: ndarray, product: ndarray, *, min_sites: int = 20, alpha: float = 0.05) -> np.ndarray
Flag flank channels differentially enriched between substrate and product.
For each of the 16 channels this computes the adjusted standardised
residual of the (16, 2) substrate/product contingency table
(Agresti/Haberman): under the null of a shared flank distribution these are
approximately standard normal, so a channel with |residual| beyond the
two-sided alpha critical value is enriched (or depleted) in one state
relative to the other. No multiple-testing correction is applied, consistent
with the effect-size-first stance of the rest of this module; the flags are
meant as visual guides on the spectra, read alongside the omnibus chi-squared.
The whole comparison is gated on reliability: if either state has fewer than
min_sites total sites, no channel is flagged (all False).
| PARAMETER | DESCRIPTION |
|---|---|
substrate
|
TYPE:
|
product
|
TYPE:
|
min_sites
|
Minimum total sites required in both states for any flag (default: 20).
TYPE:
|
alpha
|
Two-sided significance level for the per-channel test (default: 0.05).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ndarray
|
|
write_flank_matrix
Write the flank-context spectra as a tidy (long-form) TSV.
One row per sample x state x strand x channel, so the file is trivial to
pivot or filter downstream. Combined-strand rows are the sum of the forward
and reverse counts.
| PARAMETER | DESCRIPTION |
|---|---|
result
|
The computed spectra.
TYPE:
|
path
|
Destination path.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
The path written. |
write_flank_comparisons
Write the per-sequence flank-context comparison statistics as a TSV.
One row per sample x comparison (:data:COMPARISON_KEYS), carrying the
cosine effect size, Cramér's V, the chi-squared statistic/p-value, the two
site totals, the reliability flag and the most-differentiating channels.
| PARAMETER | DESCRIPTION |
|---|---|
result
|
The computed spectra.
TYPE:
|
path
|
Destination path.
TYPE:
|
min_sites
|
Minimum site count on both sides for
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
The path written. |
Flank-context spectra plotting
flank_spectra
Native matplotlib figures for flanking-context spectra of RIP-like sites.
Each figure is three bihistograms — one per strand view (combined, forward,
reverse) — comparing the two site states back to back: surviving substrate
counts extend to the left and realised RIP product counts to the
right of a shared centre line, one row per [up][centre][down] flank
channel. Because a substrate CpA motif and its product TpA share the same
flanks, every row is labelled by the CA-state motif (e.g. GCAG labels the
substrate GCAG and the equivalent product GTAG). Channels whose enrichment
differs significantly between the two states are marked.
The palette, typography and light publication surface are shared with the rest of
the package: the substrate/product bar colours come from
:mod:derip2.plotting.persequence (blue substrate, orange product, matching the
per-sequence strand-bias strip), and the axis styling and save helpers are reused
from :mod:derip2.plotting.spectra.
plot_flank_bihistograms
plot_flank_bihistograms(result, sample: int, outfile: Optional[str] = None, *, strands=_STRANDS, title: Optional[str] = None, percentage: bool = False, width: float = 11.0, panel_height: float = 5.2, min_sites: int = 20, alpha: float = 0.05, dpi: int = 300, bare: bool = False)
Draw the flank-context bihistograms for one sequence.
One bihistogram per strand view (combined, forward, reverse): substrate
counts extend left, product counts right, one row per CA-state flank channel.
Channels differentially enriched between the two states (adjusted
standardised residual beyond the alpha critical value, when both states
have at least min_sites sites) are highlighted and marked.
| PARAMETER | DESCRIPTION |
|---|---|
result
|
The computed spectra.
TYPE:
|
sample
|
Column index into
TYPE:
|
outfile
|
Output path; when
TYPE:
|
strands
|
Which strand views to draw, one panel each (default: combined, forward,
reverse). Pass e.g.
TYPE:
|
title
|
Figure heading (omitted when
TYPE:
|
percentage
|
Plot each state as a percentage of its own total (default: counts).
TYPE:
|
width
|
Figure width in inches (default: 11.0).
TYPE:
|
panel_height
|
Figure height in inches (default: 5.2), tall enough for 16 rows.
TYPE:
|
min_sites
|
Minimum sites per state for a channel to be eligible for a significance mark (default: 20).
TYPE:
|
alpha
|
Per-channel two-sided significance level (default: 0.05).
TYPE:
|
dpi
|
Raster resolution (default: 300).
TYPE:
|
bare
|
Omit the caption/suptitle for embedding under an external heading (default: False).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Figure
|
The rendered figure. |
| RAISES | DESCRIPTION |
|---|---|
IndexError
|
If |
plot_flank_bihistograms_pooled
plot_flank_bihistograms_pooled(result, outfile: Optional[str] = None, *, strands=_STRANDS, title: Optional[str] = None, percentage: bool = False, width: float = 11.0, panel_height: float = 5.2, min_sites: int = 20, alpha: float = 0.05, dpi: int = 300, bare: bool = False)
Draw the flank-context bihistograms pooled across every sequence.
Same layout as :func:plot_flank_bihistograms, but on the alignment-wide
row-summed counts (:meth:FlankSpectraResult.pooled), for the report's
overview page.
| PARAMETER | DESCRIPTION |
|---|---|
result
|
The computed spectra.
TYPE:
|
outfile
|
Output path; when
TYPE:
|
strands
|
Which strand views to draw, one panel each (default: combined, forward,
reverse). The report overview passes
TYPE:
|
title
|
Figure heading (omitted when
TYPE:
|
percentage
|
Plot each state as a percentage of its own total (default: counts).
TYPE:
|
width
|
Figure width in inches (default: 11.0).
TYPE:
|
panel_height
|
Figure height in inches (default: 5.2).
TYPE:
|
min_sites
|
Minimum sites per state for a channel to be eligible for a significance mark (default: 20).
TYPE:
|
alpha
|
Per-channel two-sided significance level (default: 0.05).
TYPE:
|
dpi
|
Raster resolution (default: 300).
TYPE:
|
bare
|
Omit the caption/suptitle for embedding (default: False).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Figure
|
The rendered figure. |
plot_flank_conversion_heatmap
plot_flank_conversion_heatmap(result, sample: Optional[int] = None, outfile: Optional[str] = None, *, flank_sort: str = 'proximal', cmap=None, title: Optional[str] = None, dpi: int = 300, bare: bool = False)
Draw a heatmap of RIP conversion as a function of the up/down flank bases.
For a RIP target CpA (the fixed centre dinucleotide) each cell shows the
product share — 100 * product / (substrate + product) — i.e. the
percentage of that flank motif converted from the substrate (CpA) to the
product (TpA) state, as a joint function of the flank_length bases
immediately 5' (rows) and 3' (columns) of the target. The grid is
4 ** flank_length on a side (4x4 for a 1 bp flank, 16x16 for 2 bp). Cell
counts are annotated only for the 4x4 grid; wider grids rely on colour and the
dinucleotide axis labels alone.
Colour defaults to viridis: dark purple where the motif has kept its
substrate, through teal and green, to bright yellow where it has been fully
converted. This encodes magnitude only — unlike the bihistograms, hue here
does not name the substrate or product state. Cells for motifs seen zero
times are left white, so a blank reads as a hole in the grid rather than a
low conversion rate. Pass cmap to use a different palette.
| PARAMETER | DESCRIPTION |
|---|---|
result
|
The computed spectra (any flank width).
TYPE:
|
sample
|
Alignment row to draw;
TYPE:
|
outfile
|
Output path; when
TYPE:
|
flank_sort
|
How the upstream (row) flank motifs are ordered (default
TYPE:
|
cmap
|
Palette for the 0-100 % scale. Accepts a registered matplotlib colormap
name (append The default
TYPE:
|
title
|
Figure heading (omitted when
TYPE:
|
dpi
|
Raster resolution (default: 300).
TYPE:
|
bare
|
Omit the default title for embedding under an external heading.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Figure
|
The rendered heatmap. |
| RAISES | DESCRIPTION |
|---|---|
IndexError
|
If |
ValueError
|
If |
Maximum RIP sequences
maxrip
Maximum-RIP counterfactuals of the deRIP'd consensus.
Where :mod:derip2.aln_ops runs RIP backwards — restoring the ancestral C and G
that RIP deaminated — this module runs it forwards to exhaustion. Given the deRIP'd
consensus it produces the sequence that would result if every RIP target it still
carries had been mutated, answering "how far could this locus have gone?" rather
than "where did it start?".
Three variants are offered, differing only in which sites count as targets:
'all'
Every RIP substrate site present in the consensus: a C whose 3' neighbour
is A becomes T, and a G whose 5' neighbour is T becomes A.
This is the pure counterfactual and ignores the alignment entirely.
'observed'
The same rule, but restricted to alignment columns where RIP demonstrably
occurred in at least one input sequence. Conservative: it will not invent
mutation at a site the family gives no evidence for.
'all_plus_nonrip'
'all', plus the columns where the alignment shows deamination outside
RIP dinucleotide context. Models a locus subject to both RIP and
context-independent cytosine deamination.
Context comes from the consensus; evidence comes from the alignment. The
deRIP'd consensus is a chimera — conserved columns, then RIP corrections, then a
fill from a chosen reference row — so a restored C can end up beside a filled
A and form a CpA that exists in no single input sequence. Since these
variants are claims about the reconstructed ancestor, the dinucleotide context is
read off the consensus itself; the per-column masks of
:class:derip2.aln_ops.ColumnClassification are consulted only to decide which
columns carry evidence (the 'observed' and 'all_plus_nonrip' filters).
Gap handling matches the alignment scan exactly, by reusing
:func:derip2.aln_ops._nongap_neighbors: a C-A spanning a gap column is a
substrate site, just as it is when the alignment is classified.
MaxRIPResult
dataclass
MaxRIPResult(variant: str, gapped_seq: str, seq: str, converted_cols: ndarray, converted_positions: ndarray, strand: ndarray, n_forward: int, n_reverse: int)
A maximally RIP-mutated variant of the deRIP'd consensus.
| ATTRIBUTE | DESCRIPTION |
|---|---|
variant |
Which rule produced this sequence; one of :data:
TYPE:
|
gapped_seq |
The mutated consensus with gap columns preserved, so it stays aligned column-for-column with the input alignment.
TYPE:
|
seq |
TYPE:
|
converted_cols |
Ascending alignment column indices that were mutated (
TYPE:
|
converted_positions |
The same sites as zero-based offsets into
TYPE:
|
strand |
TYPE:
|
n_forward |
Number of forward-strand conversions.
TYPE:
|
n_reverse |
Number of reverse-strand conversions.
TYPE:
|
n_converted
property
Total number of converted sites.
| RETURNS | DESCRIPTION |
|---|---|
int
|
|
as_record
Wrap the sequence as a :class:~Bio.SeqRecord.SeqRecord for writing.
| PARAMETER | DESCRIPTION |
|---|---|
seq_id
|
Record id and name (default
TYPE:
|
gapped
|
Emit the column-aligned sequence rather than the ungapped one
(default
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
SeqRecord
|
The sequence, with the variant named in its description. |
compute_max_rip
compute_max_rip(gapped_consensus: Union[str, SeqRecord, Seq], cls: ColumnClassification, *, variant: str = 'all') -> MaxRIPResult
Build a maximally RIP-mutated variant of a deRIP'd consensus.
Substrate context is read from gapped_consensus itself; cls supplies
only the per-column evidence used by the 'observed' and
'all_plus_nonrip' variants. See the module docstring for why.
Conversion runs to a fixed point, so the result is stable: re-running this function on its own output converts nothing.
For 'all' and 'observed' a single pass already is that fixed point,
because a context-derived conversion cannot create a new target. A forward
C would need its 3' neighbour to become A, which only a reverse
G-to-A does, and that requires the base before the G to be T
— but here it is the C itself; the reverse case is symmetric.
'all_plus_nonrip' genuinely does cascade, because its extra sites are
context-free: a C converted to T immediately 5' of a G creates a
TpG that was not a substrate beforehand. A maximally mutated sequence
should carry that downstream conversion too, so the passes repeat until
nothing changes. Each pass strictly reduces the number of C and G, so
the loop always terminates.
| PARAMETER | DESCRIPTION |
|---|---|
gapped_consensus
|
The column-aligned deRIP'd consensus, the same length as the alignment.
TYPE:
|
cls
|
The alignment's cached column classification.
TYPE:
|
variant
|
Which rule to apply (default
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
MaxRIPResult
|
The mutated sequence and the sites that were changed. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
write_max_rip_fasta
write_max_rip_fasta(results, output_file: str, seq_id: str = 'maxRIPseq', gapped: bool = False) -> str
Write one or more maximum-RIP sequences to a multi-FASTA file.
| PARAMETER | DESCRIPTION |
|---|---|
results
|
The sequences to write, in the order they should appear.
TYPE:
|
output_file
|
Destination path.
TYPE:
|
seq_id
|
Base record id; each record is suffixed with its variant name so the
records stay uniquely identifiable (default
TYPE:
|
gapped
|
Write the column-aligned sequences rather than the ungapped ones
(default
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
|
max_rip_multifasta
Render maximum-RIP sequences as a plain multi-FASTA string.
Used by the HTML report's download link, which embeds the text directly rather than writing a file.
| PARAMETER | DESCRIPTION |
|---|---|
results
|
The sequences to render.
TYPE:
|
seq_id
|
Base record id; suffixed with each variant name (default
TYPE:
|
width
|
Line-wrap width (default: 60).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
A FASTA document; empty when |
Phylogenetic spectra (ancestral state reconstruction)
tree_asr
Phylogeny and ancestral-state reconstruction for the mutation-spectrum pipeline.
This module wraps IQ-TREE to infer a maximum-likelihood tree and marginal ancestral sequences, then roots the tree and orients every edge parent -> child so that substitutions can be polarised. It is the only place in deRIP2 that shells out to an external binary; all subprocess handling is isolated here.
The workflow is:
- :func:
run_iqtreerunsiqtree --ancestralon a written alignment, producing<prefix>.treefile(Newick, named internal nodes) and<prefix>.state(per-internal-node marginal posteriors). - :func:
parse_statereads the.statefile into per-node ancestral sequences and per-site probabilities. - :func:
build_reconstructionloads the tree with ete4, roots it, orients edges away from the root, and assembles a :class:TreeReconstructiongiving every node a sequence (tips from the alignment, internal nodes from the.state).
IQ-TREE must be on PATH as iqtree3, iqtree2 or iqtree; ete4 must be
installed (the optional spectra dependency group).
TreeReconstruction
dataclass
TreeReconstruction(edges: List[Tuple[str, str]], node_seq: Dict[str, ndarray], node_prob: Dict[str, ndarray], root_name: str, tip_names: List[str], n_cols: int, manifest: dict = dict())
A rooted, ancestrally-reconstructed tree ready for branch traversal.
| ATTRIBUTE | DESCRIPTION |
|---|---|
edges |
Directed
TYPE:
|
node_seq |
Every node name (tips and internal) mapped to its
TYPE:
|
node_prob |
Every node name mapped to its
TYPE:
|
root_name |
Name of the node chosen as the root.
TYPE:
|
tip_names |
Names of the leaf nodes (alignment sequences).
TYPE:
|
n_cols |
Alignment width.
TYPE:
|
manifest |
Provenance: rooting method, outgroup, IQ-TREE version, node counts, etc.
TYPE:
|
build_reconstruction
build_reconstruction(treefile: str, state_path: str, alignment, *, rooting: str = 'midpoint', outgroup=None, manifest_extra: Optional[dict] = None) -> TreeReconstruction
Assemble a rooted, oriented, ancestrally-reconstructed tree.
| PARAMETER | DESCRIPTION |
|---|---|
treefile
|
Path to the IQ-TREE
TYPE:
|
state_path
|
Path to the IQ-TREE
TYPE:
|
alignment
|
The alignment IQ-TREE was run on; supplies tip sequences.
TYPE:
|
rooting
|
How to root the tree (default
TYPE:
|
outgroup
|
Outgroup tip name(s), required when
TYPE:
|
manifest_extra
|
Extra key/values to record in the reconstruction manifest.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
TreeReconstruction
|
The rooted tree with a sequence for every node. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If a tree node has no reconstructed or observed sequence, or the
alignment width does not match the |
reconstruct
reconstruct(alignment, work_prefix: str, *, model: str = 'MFP', threads: str = 'AUTO', rooting: str = 'midpoint', outgroup=None, tree: Optional[str] = None, binary: Optional[str] = None) -> TreeReconstruction
Run IQ-TREE on an alignment and build a rooted reconstruction in one call.
| PARAMETER | DESCRIPTION |
|---|---|
alignment
|
The alignment to analyse.
TYPE:
|
work_prefix
|
Prefix for the written alignment and all IQ-TREE outputs.
TYPE:
|
model
|
Substitution model for
TYPE:
|
threads
|
Value for IQ-TREE
TYPE:
|
rooting
|
Rooting strategy (default
TYPE:
|
outgroup
|
Outgroup tip name(s) when
TYPE:
|
tree
|
Path to a fixed user tree; passed to IQ-TREE via
TYPE:
|
binary
|
Explicit IQ-TREE executable.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
TreeReconstruction
|
The rooted, oriented, ancestrally-reconstructed tree. |
assign_clades
Assign every non-root node to the clade of its root-child ancestor.
Each subtree hanging directly off the root is one clade, named by its
root-child node. This yields the samples_by_child mapping used to
partition the spectra by lineage.
| PARAMETER | DESCRIPTION |
|---|---|
reconstruction
|
The rooted reconstruction.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict of str to str
|
Maps each non-root node name to its clade label. |
assign_groups
assign_groups(reconstruction: TreeReconstruction, group_by_tip: Dict[str, str], *, mixed_label: str = 'mixed', ungrouped_label: str = 'ungrouped') -> Dict[str, str]
Attribute each branch to a group when its whole descendant clade shares one.
Groups are defined on the tips (e.g. species labels). A branch parent ->
child is attributed to a group only when every tip descending from
child belongs to that group; branches whose descendants span more than
one group (the ancestral trunk) are labelled mixed_label. This gives the
samples_by_child mapping needed to report per-group spectra from the
phylogenetic path.
| PARAMETER | DESCRIPTION |
|---|---|
reconstruction
|
The rooted reconstruction.
TYPE:
|
group_by_tip
|
Maps each tip node name (as it appears in the tree) to a group label.
TYPE:
|
mixed_label
|
Label for branches whose descendants span several groups (default
TYPE:
|
ungrouped_label
|
Label used for tips absent from
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict of str to str
|
Maps each non-root node name to its group label. |
run_iqtree
run_iqtree(alignment_path: str, prefix: str, *, model: str = 'MFP', threads: str = 'AUTO', fixed_tree: Optional[str] = None, binary: Optional[str] = None, extra_args: Optional[List[str]] = None) -> Dict[str, str]
Run IQ-TREE with marginal ancestral state reconstruction.
| PARAMETER | DESCRIPTION |
|---|---|
alignment_path
|
Path to the input alignment (FASTA).
TYPE:
|
prefix
|
Output prefix; IQ-TREE writes
TYPE:
|
model
|
Substitution model passed to
TYPE:
|
threads
|
Value for
TYPE:
|
fixed_tree
|
Path to a user tree. When given it is passed via
TYPE:
|
binary
|
Explicit IQ-TREE executable; otherwise auto-detected.
TYPE:
|
extra_args
|
Additional command-line arguments appended verbatim.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
Paths of the key outputs: |
| RAISES | DESCRIPTION |
|---|---|
FileNotFoundError
|
If IQ-TREE is not found, or an expected output file is missing. |
RuntimeError
|
If IQ-TREE exits with a non-zero status. |
find_iqtree
Locate an IQ-TREE executable on PATH.
| PARAMETER | DESCRIPTION |
|---|---|
binary
|
An explicit executable name or path to use. When
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
The resolved path to the executable. |
| RAISES | DESCRIPTION |
|---|---|
FileNotFoundError
|
If no IQ-TREE executable can be found. |
call_mutations
Branch-by-branch substitution calling for the phylogenetic mutation spectrum.
Given a rooted, ancestrally-reconstructed tree (:class:TreeReconstruction), this
walks every directed parent -> child edge and logs each column where the two
sequences differ as one independent substitution event. The trinucleotide context
is read from the parent sequence at that branch — the sequence state at the
moment the mutation occurred — using the nearest non-gap bases.
Counting events per edge, rather than per tip against one reference, is what makes recurrent (homoplasic) deamination visible: the same C>T arising independently on three branches is three events here, and the homoplasy table records that a column was hit on multiple independent branches.
The assembled event stream is fed to the same channel-assembly core
(:func:derip2.stats.mutation_spectra.assemble_matrices) as the tree-free
baseline, so the two methods produce directly comparable SBS-96 / SBS-192
matrices.
compute_spectra_from_tree
compute_spectra_from_tree(reconstruction, *, samples_by_child: Optional[Dict[str, str]] = None, min_prob: float = 0.0, context: str = 'trinucleotide') -> SpectraResult
Call substitutions along every branch and assemble the mutation spectra.
| PARAMETER | DESCRIPTION |
|---|---|
reconstruction
|
A rooted, oriented, ancestrally-reconstructed tree.
TYPE:
|
samples_by_child
|
Maps a child node name to a sample label, so events can be partitioned by
clade. Children absent from the map fall into a
TYPE:
|
min_prob
|
Drop events whose combined parent/child state posterior probability is
below this threshold (default
TYPE:
|
context
|
Which sequence context to classify substitutions by (default:
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
SpectraResult
|
The phylogenetic spectra, per-event detail (with parent/child names) and the true (per-branch) homoplasy counts. |
Spectra channels and matrix IO
channels
SBS-96 and SBS-192 channel bookkeeping for trinucleotide mutation spectra.
The single-base-substitution (SBS) classification counts each substitution in the context of its immediately flanking 5' and 3' bases.
SBS-96 collapses every event onto the pyrimidine strand: the six pyrimidine
substitution types (C>A, C>G, C>T, T>A, T>C, T>G) times the sixteen 5'/3'
flank combinations. A purine-reference event is folded to its pyrimidine
complement by reverse-complementing the whole trinucleotide, which swaps and
complements the two flanks (the load-bearing correctness detail).
SBS-192 is strand-resolved: it keeps the reference base as observed on a
defined reference strand (here the coding sense strand), so all twelve
substitution types times sixteen flanks = 192 channels are retained. This
exposes strand asymmetries (e.g. APOBEC/AID or transcription-coupled biases) that
the collapsed SBS-96 hides. This is the plain purine+pyrimidine channel form
described in the design (labels such as A[G>T]A), not the transcriptional
T:/U: prefixed form some SigProfiler versions emit for 192.
Channel label form is the SigProfiler convention 5[REF>ALT]3 (e.g.
A[C>A]A). SBS96_CHANNELS and SBS192_CHANNELS give the canonical row
order used by the matrix files and plots.
sbs96_channel
Return the SBS-96 (pyrimidine-collapsed) channel label for an event.
| PARAMETER | DESCRIPTION |
|---|---|
five
|
The 5' flanking base on the reference strand.
TYPE:
|
ref
|
The reference (ancestral) base.
TYPE:
|
alt
|
The derived base.
TYPE:
|
three
|
The 3' flanking base on the reference strand.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
The folded channel label, e.g. |
sbs192_channel
Return the strand-resolved SBS-192 channel label for an event.
No pyrimidine folding is applied: the reference base is kept as observed on the coding reference strand, so all twelve substitution types are retained.
| PARAMETER | DESCRIPTION |
|---|---|
five
|
The 5' flanking base on the reference strand.
TYPE:
|
ref
|
The reference (ancestral) base.
TYPE:
|
alt
|
The derived base.
TYPE:
|
three
|
The 3' flanking base on the reference strand.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
The unfolded channel label, e.g. |
downstream_channel
Return the downstream-triplet channel label for a pyrimidine-folded event.
This is a pure label builder: ref/alt are expected to already be on
the pyrimidine strand (ref in C/T) and d1/d2 to already be
the pyrimidine-strand downstream bases, exactly as :func:downstream_context
resolves them. Folding of a purine-reference event is the caller's
responsibility (mirroring how :func:sbs96_channel is composed via
:func:fold_to_pyrimidine), because the two downstream bases are selected from
different physical neighbours depending on the reference strand.
| PARAMETER | DESCRIPTION |
|---|---|
ref
|
The pyrimidine reference base (
TYPE:
|
alt
|
The derived base on the pyrimidine strand.
TYPE:
|
d1
|
The first downstream base on the pyrimidine strand.
TYPE:
|
d2
|
The second downstream base on the pyrimidine strand.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
The channel label, e.g. |
trinucleotide_context
trinucleotide_context(seq: ndarray, col: int, next_idx: ndarray, prev_idx: ndarray) -> Optional[Tuple[str, str]]
Resolve the 5' and 3' flanking bases of a column using nearest non-gap bases.
The flanks are read from seq at the nearest non-gap (and non-ambiguous)
neighbour columns, whose indices are supplied precomputed in next_idx and
prev_idx. When either neighbour is absent (a terminal column, indicated
by -1) the event cannot be assigned a full trinucleotide context and
None is returned.
| PARAMETER | DESCRIPTION |
|---|---|
seq
|
1-D byte array (dtype
TYPE:
|
col
|
The column whose flanks are wanted.
TYPE:
|
next_idx
|
1-D int array; the column index of the nearest non-gap base to the right
of each column, or
TYPE:
|
prev_idx
|
1-D int array; the column index of the nearest non-gap base to the left
of each column, or
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple of str or None
|
|
downstream_context
downstream_context(seq: ndarray, col: int, next_idx: ndarray, prev_idx: ndarray) -> Optional[Tuple[str, str]]
Resolve the two pyrimidine-strand downstream bases of a column.
The reference base at col sets the strand on which "downstream" is read so
that the result is invariant to the orientation of the input alignment:
- Pyrimidine reference (C/T): the two downstream bases are read directly
from the nearest non-gap neighbours to the right (
next_idxchained once to reach the second base). - Purine reference (A/G): the equivalent pyrimidine event lives on the
opposite strand, whose two downstream bases are the reverse-complement of the
two upstream bases here. So the two nearest non-gap neighbours to the
left (
prev_idxchained once) are complemented and returned.
Non-ACGT positions must already be normalised to gaps in seq so the
neighbour indices skip over them (as for :func:trinucleotide_context). When
either required second neighbour is absent (a terminal column, or -- for a
purine reference -- a column too close to the 5' end) the event has no full
downstream context and None is returned. This 5'/3' asymmetry is inherent
to reading a fixed two-base window on the pyrimidine strand.
| PARAMETER | DESCRIPTION |
|---|---|
seq
|
1-D byte array (dtype
TYPE:
|
col
|
The column of the mutated (reference) base.
TYPE:
|
next_idx
|
1-D int array; the column index of the nearest non-gap base to the right
of each column, or
TYPE:
|
prev_idx
|
1-D int array; the column index of the nearest non-gap base to the left of
each column, or
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple of str or None
|
|
fold_to_pyrimidine
Fold a substitution onto the pyrimidine strand for SBS-96.
If the reference base is already a pyrimidine (C or T) the event is
returned unchanged. If it is a purine, the whole trinucleotide is
reverse-complemented: the reference and derived bases are complemented, and
the two flanks are complemented and swapped (the old 3' becomes the new
5'). For example G>A in context T_C (5'=T, 3'=C) folds to C>T in
context G_A.
| PARAMETER | DESCRIPTION |
|---|---|
five
|
The 5' flanking base on the reference strand.
TYPE:
|
ref
|
The reference (ancestral) base.
TYPE:
|
alt
|
The derived base.
TYPE:
|
three
|
The 3' flanking base on the reference strand.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple of str
|
|
revcomp_base
Return the Watson-Crick complement of a single uppercase DNA base.
| PARAMETER | DESCRIPTION |
|---|---|
base
|
A single character, one of
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
The complementary base. |
| RAISES | DESCRIPTION |
|---|---|
KeyError
|
If |
flank_channels
Channel bookkeeping for flanking-context spectra of RIP-like sites.
Where the SBS-96 model (see :mod:derip2.spectra.channels) classifies a
substitution by its 5'/3' trinucleotide context, this model classifies a
dinucleotide site by the single base one position upstream and one position
downstream — a 4 bp motif [up][center][down] with a fixed two-base centre.
Only the two flanks vary, giving 4 x 4 = 16 channels per site state.
Two site states are counted (each with a fixed centre after orientation folding):
- Substrate — the surviving RIP substrate dinucleotide,
CpAread on the pyrimidine (forward) strand. Centre'CA'. A reverse-strand substrate reads asTpGon the forward strand and is reverse-complemented back toCA. - Product — the RIP product dinucleotide
TpAin a RIP-informative column. Centre'TA'(TpAis its own reverse complement's centre).
Orientation folding reverse-complements a reverse-strand motif so every count
lands on the CA/TA-equivalent channel. Reverse-complementing a 4 bp motif
[up][X][Y][down] gives [comp(down)][comp(Y)][comp(X)][comp(up)]: the two
flanks swap sides and complement (the same load-bearing detail as SBS-96's
pyrimidine fold). The centre CA <-> TG maps to CA and TA <-> TA,
so both states keep a fixed centre after folding.
Channel order matches the SBS-96 flank convention: the upstream base varies in the
outer loop and the downstream base in the inner loop, so the 16 flanks are laid
out AA, AC, AG, AT, CA, ..., TT for a given centre (e.g. ACAA, ACAC, ACAG,
ACAT, CCAA, ..., TCAT for centre CA).
flank_channel_labels
Enumerate the [up][center][down] motif labels for a site state.
The upstream flank (width bases, written 5'->3') varies in the outer loop
and the downstream flank in the inner loop, so the returned order matches the
mixed-radix channel index of :func:flank_channel_index. For width == 1
this reproduces the 16-channel up*4 + down ordering exactly (e.g.
['ACAA', 'ACAC', ..., 'TCAT'] for center='CA').
| PARAMETER | DESCRIPTION |
|---|---|
center
|
The fixed two-base centre,
TYPE:
|
width
|
Number of flanking bases on each side (default 1).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list of str
|
The |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
flank_pair_labels
Enumerate the centre-agnostic up.down flank-pair labels.
These label the flank context alone (no centre dinucleotide), for comparing a
substrate (CA-centred) spectrum against a product (TA-centred) one
position-by-position without implying a shared centre motif.
| PARAMETER | DESCRIPTION |
|---|---|
width
|
Number of flanking bases on each side (default 1).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list of str
|
The |
matrix_io
Read and write SigProfiler-compliant SBS mutation matrices.
A matrix file is tab-separated. The first column is headed MutationType and
holds the channel labels in canonical order (A[C>A]A and so on); every
remaining column is one sample's counts. This is exactly the format
sigProfilerPlotting.plotSBS and SigProfilerAssignment expect, so the
files drop straight into those tools when they are installed, while deRIP2 itself
keeps no dependency on them.
write_sbs_matrix
Write a spectra result to a SigProfiler-compliant SBS matrix file.
| PARAMETER | DESCRIPTION |
|---|---|
result
|
The computed spectra to serialise.
TYPE:
|
path
|
Output file path.
TYPE:
|
kind
|
Which matrix to write (default:
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
The path written, for convenience. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If |
read_sbs_matrix
Read a SigProfiler-compliant SBS matrix file.
| PARAMETER | DESCRIPTION |
|---|---|
path
|
Path to a tab-separated matrix file with a
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple
|
|
write_matrix_metadata
Write a JSON sidecar describing how a matrix file was produced.
The SBS matrix files are kept as clean MutationType tab-separated tables so
third-party tools (e.g. SigProfilerPlotting / SigProfilerAssignment) can read
them directly -- those tools reject in-file comment lines, so the provenance
(which sequence context and calling method produced the matrix) is written to a
companion JSON file instead of into the matrix itself.
| PARAMETER | DESCRIPTION |
|---|---|
result
|
The computed spectra the matrix was written from.
TYPE:
|
path
|
Output path for the JSON sidecar.
TYPE:
|
kind
|
The matrix kind the sidecar documents (default:
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
The path written, for convenience. |
Alignment QC for spectra
qc
Alignment quality control for the phylogenetic mutation-spectrum pipeline.
Alignment artefacts become phantom substitutions, so before any tree is built the alignment is profiled: per-column gap and ambiguity fractions are computed and columns too gappy to give reliable flanking context are flagged. The report is advisory — nothing is removed — but the flags let downstream steps and the reader judge how much of the spectrum rests on well-supported columns.
ColumnProfile
dataclass
ColumnProfile(n_rows: int, n_cols: int, gap_fraction: ndarray, ambiguous_fraction: ndarray, context_unreliable: ndarray, gap_threshold: float)
Per-column gap and ambiguity profile of an alignment.
| ATTRIBUTE | DESCRIPTION |
|---|---|
n_rows |
Number of sequences.
TYPE:
|
n_cols |
Number of alignment columns.
TYPE:
|
gap_fraction |
TYPE:
|
ambiguous_fraction |
TYPE:
|
context_unreliable |
TYPE:
|
gap_threshold |
The gap fraction above which a column is flagged.
TYPE:
|
profile_alignment
Compute the per-column gap and ambiguity profile of an alignment.
| PARAMETER | DESCRIPTION |
|---|---|
alignment
|
The alignment to profile.
TYPE:
|
gap_threshold
|
Fraction of gaps above which a column is flagged context-unreliable (default: 0.5).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ColumnProfile
|
The computed profile. |
write_column_profile
Write the per-column gap/ambiguity profile to a TSV file.
| PARAMETER | DESCRIPTION |
|---|---|
profile
|
The profile to write.
TYPE:
|
path
|
Destination path.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
The path written. |
write_qc_report
Write a short human-readable QC summary.
| PARAMETER | DESCRIPTION |
|---|---|
alignment
|
The alignment that was profiled.
TYPE:
|
profile
|
The computed profile.
TYPE:
|
path
|
Destination path.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
The path written. |