Skip to content

Sequence Analysis

Functions for extracting and analyzing DNA sequences, including reverse complement operations, k-mer counting, and position weight matrix scoring.

pymisha.gseq_extract

gseq_extract(intervals: DataFrame | str, pad: bool = False) -> list[str]

Extract DNA sequences for given intervals.

Returns an array of sequence strings for each interval from 'intervals'. If intervals contain an additional 'strand' column and its value is -1, the reverse-complementary sequence is returned.

By default (pad=False) each interval must lie within its chromosome: an interval that starts before 0 or ends past the end of the chromosome is an error.

With pad=True an interval may run past either end of its chromosome (start below 0, end above the chromosome length). The positions outside the chromosome come back as "N", so each sequence is end - start long, and an interval wholly outside its chromosome comes back as all "N". start must still be below end, and the chromosome must exist. For a row with strand -1 the padded sequence is reverse complemented as a whole, so the "N" run of the chromosome start comes last. The bases inside the chromosome are returned as stored, lowercase included. This gives fixed-width windows near chromosome ends, e.g. for sequence models (see the examples).

PARAMETER DESCRIPTION
intervals

Intervals for which DNA sequence is returned. Must have 'chrom', 'start', and 'end' columns. Optional 'strand' column (-1 for reverse complement).

TYPE: DataFrame

pad

If True, the part of an interval outside its chromosome is returned as "N". If False, an interval that runs past a chromosome end is an error.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
list of str

Array of character strings representing DNA sequence.

Examples:

>>> import pymisha as pm
>>> _ = pm.gdb_init_examples()
>>> intervs = pm.gintervals(["1", "2"], [10000, 10000], [10020, 10020])
>>> pm.gseq_extract(intervs)
[...]

Fixed-width windows centred on positions. The second window starts 30 bp before the start of chr1, so its first 30 bases are N.

>>> import pandas as pd
>>> w = 100
>>> centers = [250000, 20]
>>> windows = pd.DataFrame({"chrom": "chr1", "start": [c - w // 2 for c in centers],
...                         "end": [c + w // 2 for c in centers]})
>>> seqs = pm.gseq_extract(windows, pad=True)
>>> [len(s) for s in seqs]
[100, 100]
>>> seqs[1][:30] == "N" * 30
True
See Also

gseq_rev, gseq_comp, gseq_revcomp, gseq_kmer

pymisha.gseq_onehot

gseq_onehot(x: DataFrame | str | list[str], pad: bool = False, dtype: Any = _numpy.uint8) -> _numpy.ndarray

One-hot encode genomic intervals or DNA strings.

Returns the one-hot encoding of intervals of equal width, read directly from the genome sequence files in C++ (no Python strings are made), or of strings of equal length.

The result has shape (N, 4, L), i.e. (batch, channels, length): x[n, c, p] is 1 when position p of sequence n is base c. The channels are A, C, G and T, in that order. Lowercase (soft-masked) bases are encoded like uppercase ones. Any other character (N, IUPAC ambiguity codes, gaps) and, with pad=True, every position outside the chromosome has all four channels 0. The array is C-contiguous, so torch.from_numpy takes it without a copy.

For intervals with a strand column, a row with strand -1 (or "-") is reverse complemented, as in :func:gseq_extract.

Element [n, c, p] equals element [n, c, p] of R misha's gseq.onehot (whose array has dimensions c(N, 4, L)).

The array takes N * 4 * L * dtype.itemsize bytes.

PARAMETER DESCRIPTION
x

Intervals of equal width (a DataFrame or the name of an intervals set), or a list of sequences of equal length. A bare string is taken as the name of an intervals set; pass [seq] for a single sequence.

TYPE: DataFrame, str or list of str

pad

For intervals: if True, an interval may run past either end of its chromosome and the positions outside it are all 0, as the "N" of gseq_extract(pad=True). If False, such an interval is an error.

TYPE: bool DEFAULT: False

dtype

One of bool, uint8, int8, int16, int32, int64, float32, float64.

TYPE: numpy dtype DEFAULT: uint8

RETURNS DESCRIPTION
ndarray

Array of shape (N, 4, L).

See Also

gseq_extract, gextract_windows

Examples:

>>> import pymisha as pm
>>> _ = pm.gdb_init_examples()
>>> x = pm.gseq_onehot(pm.gintervals(["1", "1"], [10000, 20000], [10010, 20010]))
>>> x.shape
(2, 4, 10)
>>> pm.gseq_onehot(["ACGTN"])[0]
array([[1, 0, 0, 0, 0],
       [0, 1, 0, 0, 0],
       [0, 0, 1, 0, 0],
       [0, 0, 0, 1, 0]], dtype=uint8)

pymisha.gseq_rev

gseq_rev(seq: str | list[str]) -> str | list[str]

Reverse DNA sequence(s).

PARAMETER DESCRIPTION
seq

DNA sequence(s) to reverse.

TYPE: str or list of str

RETURNS DESCRIPTION
str or list of str

Reversed sequence(s).

Examples:

>>> import pymisha as pm
>>> pm.gseq_rev("ACGT")
'TGCA'
>>> pm.gseq_rev(["ACGT", "TATA"])
['TGCA', 'ATAT']
See Also

gseq_comp, gseq_revcomp, gseq_extract

pymisha.gseq_comp

gseq_comp(seq: str | list[str]) -> str | list[str]

Return complement of DNA sequence(s).

PARAMETER DESCRIPTION
seq

DNA sequence(s) to complement.

TYPE: str or list of str

RETURNS DESCRIPTION
str or list of str

Complemented sequence(s).

Examples:

>>> import pymisha as pm
>>> pm.gseq_comp("ACGT")
'TGCA'
>>> pm.gseq_comp(["ACGT", "AAAA"])
['TGCA', 'TTTT']
See Also

gseq_rev, gseq_revcomp, gseq_extract

pymisha.gseq_revcomp

gseq_revcomp(seq: str | list[str]) -> str | list[str]

Return reverse complement of DNA sequence(s).

PARAMETER DESCRIPTION
seq

DNA sequence(s) to reverse complement.

TYPE: str or list of str

RETURNS DESCRIPTION
str or list of str

Reverse complemented sequence(s).

Examples:

>>> import pymisha as pm
>>> pm.gseq_revcomp("AACG")
'CGTT'
>>> pm.gseq_revcomp(["AACG", "AAAA"])
['CGTT', 'TTTT']
See Also

gseq_rev, gseq_comp, gseq_extract

pymisha.gseq_kmer

gseq_kmer(seqs: str | list[str], kmer: str, mode: str = 'count', strand: int = 0, start_pos: int | list[int] | None = None, end_pos: int | list[int] | None = None, extend: bool | int = False, skip_gaps: bool = True, gap_chars: list[str] | None = None) -> _numpy.ndarray

Count k-mer occurrences in DNA sequences.

Counts the k-mer as the kmer.count and kmer.frac virtual tracks do, with the region of interest (ROI) in the interval's place: a match on either strand is anchored at its first (leftmost) base, which must not lie before start_pos, and extend sets how many bases past end_pos it may run, never past the end of the sequence. With strand=0 the matches on the two strands are summed, so a palindromic k-mer (its own reverse complement) counts twice per site, and a warning is given; use strand=1 or -1 to count it once. mode="frac" divides by the number of allowed anchors, doubled with strand=0, so the fraction stays in [0, 1].

PARAMETER DESCRIPTION
seqs

DNA sequence(s) to search (case-insensitive).

TYPE: str or list of str

kmer

K-mer pattern to search for (only A, C, G, T characters).

TYPE: str

mode

"count" returns raw counts, "frac" returns the fraction of the allowed anchors that match.

TYPE: str DEFAULT: "count"

strand

0 = both strands, summed, 1 = forward only, -1 = reverse complement only.

TYPE: int DEFAULT: 0

start_pos

1-based start of the ROI, per sequence (recycled); 1 by default.

TYPE: int or list of int DEFAULT: None

end_pos

1-based end of the ROI (inclusive), per sequence (recycled); the sequence end by default.

TYPE: int or list of int DEFAULT: None

extend

How many bases a match may run past end_pos: False for none (only k-mers inside the ROI), True for len(kmer) - 1 (every anchor in the ROI), or a non-negative number of bases. It never moves the first anchor before start_pos; a number above len(kmer) - 1 also counts k-mers that start after end_pos (and frac counts their starts).

TYPE: bool or int DEFAULT: False

skip_gaps

If True, gap characters are removed before scanning; windows are k consecutive non-gap bases, and extend and the frac denominator count non-gap bases and windows.

TYPE: bool DEFAULT: True

gap_chars

Characters to treat as gaps. Default: ["-", "."].

TYPE: list of str DEFAULT: None

RETURNS DESCRIPTION
ndarray

Array of counts or fractions, one per input sequence: 0 for a sequence shorter than the k-mer or an empty ROI, NaN for a None sequence.

Examples:

>>> import pymisha as pm

Count CG dinucleotides on the forward strand (CG is its own reverse complement, so strand=0 would count each site twice, with a warning):

>>> pm.gseq_kmer(["CGCGCGCGCG", "ATATATATAT"], "CG", strand=1)
array([5., 0.])

Get fraction instead of count:

>>> pm.gseq_kmer(["CGCGCGCGCG"], "CG", mode="frac", strand=1)
array([0.555...])

Count in a specific region:

>>> pm.gseq_kmer("ATCGATCG", "AT", strand=1, start_pos=1, end_pos=4)
array([1.])
See Also

gseq_kmer_dist, gseq_pwm, gseq_extract

pymisha.gseq_kmer_dist

gseq_kmer_dist(intervals: DataFrame | str, k: int = 6, mask: DataFrame | None = None) -> _pandas.DataFrame

Compute k-mer distribution in genomic intervals.

Counts all k-mers of size k within the specified genomic intervals, optionally excluding masked regions.

PARAMETER DESCRIPTION
intervals

Genomic intervals to analyze. Overlapping intervals are unified first, so each position is counted once; a k-mer that crosses from an interval into an adjacent one is not counted.

TYPE: DataFrame

k

K-mer size (1-10).

TYPE: int DEFAULT: 6

mask

Intervals to exclude: a k-mer with any base in one is not counted.

TYPE: DataFrame DEFAULT: None

RETURNS DESCRIPTION
DataFrame

DataFrame with columns 'kmer' (str) and 'count' (int). Only k-mers with count > 0 are included.

Examples:

>>> import pymisha as pm
>>> _ = pm.gdb_init_examples()
>>> intervs = pm.gintervals(1, 0, 10000)
>>> result = pm.gseq_kmer_dist(intervs, k=2)
>>> list(result.columns)
['kmer', 'count']
See Also

gseq_kmer, gseq_pwm, gseq_extract

pymisha.gseq_shuffle

gseq_shuffle(seqs: str | Iterable[str | None] | DataFrame, k: int = 2, n: int = 1, seed: int | Generator | None = None) -> str | list[str | None] | list[list[str | None]]

Shuffle sequences keeping their k-mer counts.

Draws random sequences with exactly the same k-mer counts as the input sequences - the dinucleotide counts with the default k=2 - for use as a composition-matched background, e.g. in motif enrichment. Mirrors R misha's gseq.shuffle.

Each shuffle is drawn uniformly at random from all the sequences that keep the k-mer counts and the first k-1 bases, by the Eulerian-path construction of Altschul & Erickson (1985) and Kandel et al. (1996), as in uShuffle (Jiang et al. 2008): the (k-1)-mers are the vertices of a graph whose edges are the k-mers of the sequence, a uniformly random spanning tree of "last exits" is drawn with Wilson's algorithm, and the remaining edges out of each vertex are put in a random order. k=1 is a plain random permutation of the bases. Because the k-mers form a path through the (k-1)-mers, the last k-1 bases are kept too.

Only A, C, G and T (in either case) are shuffled. Any other character - N, an IUPAC code, a gap - stays at its position and splits the sequence into segments, each shuffled on its own; the k-mers that touch such a character are unchanged, so the k-mer counts of the whole sequence, N-containing k-mers included, are kept. Bases are compared ignoring case and every position keeps its case, so a soft-masked stretch stays lowercase at the same coordinates (with new bases in it). A segment of k bases or fewer has only one arrangement and is returned as is.

The random numbers come from a generator in the C++ core shared with R misha (xoshiro256**), so an integer seed gives the same sequences as gseq.shuffle(..., seed = ) in R, on every platform. Without a seed one is drawn from numpy's global generator (so numpy.random.seed reproduces the call); from a numpy.random.Generator one is drawn from it. Those two do not match R, whose generator differs. Each input sequence gets its own stream, derived from the seed and its position in seqs, so its shuffles do not depend on the sequences after it.

PARAMETER DESCRIPTION
seqs

DNA sequence(s); None/NaN gives None. A DataFrame of intervals is read with :func:gseq_extract (strand-aware).

TYPE: str, iterable of str, or DataFrame

k

The k-mer length whose counts are kept, 1 to 32.

TYPE: int DEFAULT: 2

n

The number of shuffles of each sequence.

TYPE: int DEFAULT: 1

seed

An integer with abs(seed) <= 2**53, a generator to draw one from, or None to draw one from numpy's global generator.

TYPE: int, numpy.random.Generator, or None DEFAULT: None

RETURNS DESCRIPTION
str, list of str, or list of list of str

For a single string, a string (n=1) or a list of n strings. For several sequences, a list with one string per sequence (n=1) or with one list of n strings per sequence (R returns a matrix with a row per sequence).

Examples:

>>> import pymisha as pm
>>> seq = "ACGTTGCAACGTAGCTAGCTTTACG"
>>> s = pm.gseq_shuffle(seq, seed=1)
>>> sorted(s[i:i + 2] for i in range(24)) == sorted(seq[i:i + 2] for i in range(24))
True
>>> len(pm.gseq_shuffle(["ACGTACGT", "ccgNNacgtTT"], k=3, n=4, seed=1)[1])
4
See Also

gseq_kmer, gseq_kmer_dist, gsynth_sample

pymisha.gseq_pwm

gseq_pwm(seqs: str | list[str], pssm: ndarray | DataFrame, mode: str = 'lse', bidirect: bool = True, strand: int = 1, score_thresh: float | None = None, start_pos: int | list[int] | None = None, end_pos: int | list[int] | None = None, extend: bool | int = False, spat_factor: ndarray | list[float] | None = None, spat_bin: int = 1, spat_min: float | None = None, spat_max: float | None = None, return_strand: bool = False, skip_gaps: bool = True, gap_chars: list[str] | None = None, neutral_chars: list[str] | None = None, neutral_chars_policy: str = 'average', prior: float = 0.01) -> _numpy.ndarray | _pandas.DataFrame

Score DNA sequences with a position weight matrix (PWM/PSSM).

Scans each input sequence with a sliding window of PSSM width and computes per-position log-probability scores, then aggregates them according to mode.

PARAMETER DESCRIPTION
seqs

DNA sequence(s) to score.

TYPE: str or list of str

pssm

Position-specific scoring matrix. If ndarray, shape (w, 4) with columns ordered [A, C, G, T]. If DataFrame, must contain columns A, C, G, T (extra columns are ignored).

TYPE: ndarray or DataFrame

mode

Scoring mode:

  • "lse": log-sum-exp of all per-position scores.
  • "max": maximum per-position score.
  • "pos": 1-based position of best match.
  • "count": number of positions with score >= score_thresh.
  • "scores": the score of every window (see Returns).

TYPE: str DEFAULT: ``"lse"``

bidirect

If True, score both forward and reverse complement strands. Overrides strand.

TYPE: bool DEFAULT: True

strand

Used only when bidirect=False, and required there: 1 for the forward strand, -1 for the reverse complement. 0 is refused, since exactly one strand is read and 0 cannot name it. Under bidirect=True both strands are read and this is ignored.

TYPE: int DEFAULT: 1

score_thresh

Threshold for "count" mode, where it is required: PWM scores are log-likelihoods, so no default suits every PSSM. Ignored otherwise.

TYPE: float DEFAULT: None

start_pos

1-based inclusive start of the region of interest (ROI), per sequence (recycled); 1 by default.

TYPE: int, list of int or None DEFAULT: None

end_pos

1-based inclusive end of the ROI, per sequence (recycled); the sequence end by default.

TYPE: int, list of int or None DEFAULT: None

extend

How many bases a window may run past end_pos: False for none (only windows inside the ROI), True for w - 1 (every anchor in the ROI), or a non-negative number of bases; never past the end of the sequence. As in the pwm virtual tracks, a window on either strand is anchored at its first base, which never lies before start_pos; a number above w - 1 also scores windows that start after end_pos. With skip_gaps, extend counts non-gap bases.

TYPE: bool or int DEFAULT: False

spat_factor

Spatial weighting factors, one per spatial bin. When provided, the score at each window position is shifted in log-space by log(spat_factor[bin]) where bin = offset // spat_bin and offset is the 0-based position of the window start relative to the ROI start. Values must be non-negative.

TYPE: array - like or None DEFAULT: None

spat_bin

Number of consecutive positions that share the same spatial weight. Position offset maps to bin offset // spat_bin.

TYPE: int DEFAULT: 1

spat_min

1-based position, counted from start_pos, where the scanning window starts (>= 1); spatial bins are counted from it.

TYPE: float or None DEFAULT: None

spat_max

1-based position, counted from start_pos, where the scanning window ends: only windows ending at or before it are scored (>= 1). A spat_min..spat_max window shorter than the PSSM is an error.

TYPE: float or None DEFAULT: None

return_strand

For mode="pos" with bidirectional scoring, return a DataFrame with pos and strand columns instead of a plain array.

TYPE: bool DEFAULT: False

skip_gaps

Skip gap characters when scanning.

TYPE: bool DEFAULT: True

gap_chars

Characters treated as gaps. Default ["-", "."].

TYPE: list of str or None DEFAULT: None

neutral_chars

Characters to score as unknown bases, by neutral_chars_policy, instead of leaving their windows out. Default: none, as in R misha 5.15, so a window holding N or any other non-ACGT base is not scored (an interval with no scorable window gives -inf, or NaN for mode="pos"). Pass ["N", "n", "*"] for the scores of earlier versions.

TYPE: list of str or None DEFAULT: None

neutral_chars_policy

How to score neutral characters:

  • "average": mean log-probability of the PSSM column.
  • "log_quarter": log(0.25).
  • "na": window is invalid (NaN).

TYPE: str DEFAULT: ``"average"``

prior

Pseudocount added to PSSM before normalization, between 0 and 1.

TYPE: float DEFAULT: 0.01

RETURNS DESCRIPTION
ndarray or DataFrame

With mode="scores", a list with one float32 array of len(seq) per sequence: element i (0-based) is the score of the window anchored at base i (its leftmost base, on either strand), as a pwm virtual track gives at iterator=1, bit for bit when called with extend=True. Elements where no window is anchored (before start_pos, past the last anchor end_pos and extend allow, or too close to the end of the sequence) are NaN; a window holding a base other than A, C, G or T scores -inf; a None sequence gives None. spat_factor, spat_min, spat_max, neutral_chars and, while skip_gaps is True, sequences holding a gap character are refused.

Otherwise, an array of scores (one per input sequence). For mode="pos" with return_strand=True, returns a DataFrame with columns pos and strand. A sequence whose windows are all unscorable (for example all N) gives 0 for "count", as pwm.count does. A sequence or ROI with no window at all (shorter than the motif, start_pos past end_pos, fewer non-gap bases than the motif), or a None sequence, gives NaN in every mode, "count" included, as the pwm virtual tracks give for an interval without an anchor.

Examples:

>>> import pymisha as pm
>>> import numpy as np

Create a simple PSSM (frequency matrix):

>>> pssm = np.array([
...     [0.7, 0.1, 0.1, 0.1],
...     [0.1, 0.7, 0.1, 0.1],
...     [0.1, 0.1, 0.7, 0.1],
...     [0.1, 0.1, 0.1, 0.7],
... ])

Score sequences using log-sum-exp (default mode):

>>> pm.gseq_pwm(["ACGTACGT", "GGGGGGGG"], pssm, mode="lse")
array([...])

Find position of best match:

>>> pm.gseq_pwm(["ACGTACGT"], pssm, mode="pos")
array([...])

Count matches above a threshold:

>>> pm.gseq_pwm(["ACGTACGT"], pssm, mode="count", score_thresh=-5.0)
array([...])
See Also

gseq_kmer, gseq_kmer_dist, gseq_extract

pymisha.gseq_pwm_hits

gseq_pwm_hits(seqs: str | list[str], pssm: ndarray | DataFrame, score_thresh: float | None = None, bidirect: bool = True, strand: int = 1, start_pos: int | list[int] | None = None, end_pos: int | list[int] | None = None, extend: bool | int = False, prior: float = 0.01) -> _pandas.DataFrame

Find PWM motif hits in DNA sequences.

Returns every window of each sequence whose PWM score reaches score_thresh, with its position, strand and score. Windows are scored as R misha's gseq.pwm(mode = "count") scores them with its default neutral_chars and no spatial weights - a natural-log likelihood including the prior, summed in double precision over the PSSM's single precision log-probabilities - and the same C++ code finds them in both packages, so gseq_pwm_hits here and gseq.pwm_hits in R return the same rows. A window holding N or any other non-ACGT character is not scored; gap characters are not skipped. Windows that cannot reach the threshold are skipped without being scored, which makes a strict threshold fast; the hits are the same as scoring every window.

Strand: with bidirect=True a window is one hit, whose score is the log-sum-exp of its forward and reverse-complement scores (the value thresholded, as in :func:gseq_pwm and pwm.count), and whose strand is the strand that scores higher on its own (1 on a tie). With bidirect=False only the strand named by strand is read and strand is that strand. start and end are positions on the input sequence whatever the strand.

PARAMETER DESCRIPTION
seqs

DNA sequence(s) to scan (case-insensitive).

TYPE: str or list of str

pssm

Position-specific scoring matrix, shape (w, 4) with columns [A, C, G, T], or a DataFrame with columns A, C, G, T.

TYPE: ndarray or DataFrame

score_thresh

Required. Windows scoring at or above it are hits.

TYPE: float DEFAULT: None

bidirect

Scan both strands.

TYPE: bool DEFAULT: True

strand

With bidirect=False: 1 for the forward strand, -1 for the reverse complement.

TYPE: int DEFAULT: 1

start_pos

1-based inclusive region of interest per sequence (recycled), as in :func:gseq_pwm; windows start inside it.

TYPE: int, list of int or None DEFAULT: None

end_pos

1-based inclusive region of interest per sequence (recycled), as in :func:gseq_pwm; windows start inside it.

TYPE: int, list of int or None DEFAULT: None

extend

How many bases a window may run past end_pos, as in :func:gseq_pwm.

TYPE: bool or int DEFAULT: False

prior

Pseudocount added to the PSSM frequencies.

TYPE: float DEFAULT: 0.01

RETURNS DESCRIPTION
DataFrame

One row per hit with columns seq_idx (1-based index into seqs), start and end (1-based, inclusive window positions), strand (1 or -1) and score, ordered by seq_idx and start. Empty when nothing passes.

Examples:

>>> import numpy as np
>>> import pymisha as pm
>>> pssm = np.array([[0.7, 0.1, 0.1, 0.1], [0.1, 0.7, 0.1, 0.1],
...                  [0.1, 0.1, 0.7, 0.1], [0.1, 0.1, 0.1, 0.7]])
>>> pm.gseq_pwm_hits(["TTACGTAAACGTTT", "GGGGGGGG"], pssm, score_thresh=-3)
See Also

gseq_pwm, gintervals_pwm_hits

pymisha.gseq_potts

gseq_potts(seqs: str | list[str], model: dict, mode: str = 'lse', bidirect: bool = True, strand: int = 0, score_thresh: float | None = None, extend: bool = False) -> _numpy.ndarray

Score DNA sequences under a Potts (pairwise energy) model.

The sequence-level entry point of the potts family, the way :func:gseq_pwm is the pwm family's. The score of one width-W window is intercept + sum_i e[i, x_i] + sum_k J_k[x_i, x_j], and a sequence longer than W is reduced over every window by mode.

The parameterisation is not unique: adding a constant to a position's four e entries, or a row or column shift to a J block, changes no score, so e is comparable across positions only in the zero-sum gauge, where each row of e sums to 0 and every J block has zero row and column sums.

A Potts carries energies, not probabilities, so there is no prior and no fallback for an ambiguous base: a window containing any non-ACGT base is not scored and is left out of the reduction. A sequence that has windows but none of them scorable returns nan, and 0 for mode="count": it counted, and found none. A sequence shorter than the model returns nan for every mode including "count" - there was no window to count.

PARAMETER DESCRIPTION
seqs

DNA sequence(s) to score (case-insensitive).

TYPE: str or list of str

model

The energy model, with keys:

  • e -- a (W, 4) numeric array or DataFrame with columns A, C, G, T: the per-position energies.
  • J -- a list of 4x4 arrays, or an (npair, 16) array: the coupling tables, one per row of pairs, indexed with the lower position on the rows.
  • pairs -- an (npair, 2) array of 1-based position pairs, lower position first.
  • intercept -- a single number.

Extra keys named width, pair_strength, attr or link are accepted and ignored, so a fitted model can be passed verbatim; width is cross-checked against the row count of e.

TYPE: dict

mode

"lse" for the log-sum-exp over windows, "max" for the best window, "pos" for the 1-based position of the best window (signed by strand when bidirect=True), "count" for the number of windows scoring at least score_thresh.

TYPE: str DEFAULT: ``"lse"``

bidirect

If True both strands are read. The two strands are combined at each window by log-sum-exp for "lse", "max" and "count", and by the maximum for "pos", which has to name a strand. :func:gseq_pwm splits the two the same way.

TYPE: bool DEFAULT: True

strand

Used only when bidirect=False, and required there: 1 for the forward strand, -1 for the reverse. The default 0 is accepted only under bidirect=True, where both strands are read and it is ignored.

TYPE: int DEFAULT: 0

score_thresh

Required for mode="count" and ignored otherwise. A Potts score is an energy whose usable range depends entirely on the model, so there is no default; read one off mode="max" over your own sequences.

TYPE: float DEFAULT: None

extend

Accepted for signature parity with :func:gseq_pwm and ignored - a bare sequence has no genome to extend into. True or False, as in R.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
ndarray

One value per input sequence.

Examples:

>>> import numpy as np
>>> import pymisha as pm

A W=2 model with a real coupling. On the per-position energies alone the model prefers "AC", but the pair term penalises A-then-C and rewards G-then-T, so "GT" wins instead:

>>> e = np.array([[1.0, 0, 0, 0], [0, 1.0, 0, 0]])
>>> J = [np.array([[0, -3.0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 3.0], [0, 0, 0, 0]])]
>>> model = {"e": e, "J": J, "pairs": np.array([[1, 2]]), "intercept": 0.0}
>>> pm.gseq_potts(["AC", "GT"], model, mode="max", bidirect=False, strand=1)
array([-1.,  3.])
See Also

gseq_pwm : the same reduction for a position weight matrix. gvtrack_create : the potts virtual track functions.

Motif Import and Export

Functions to read and write motifs in standard motif file formats (MEME, JASPAR, HOMER).

pymisha.gseq_read_meme

gseq_read_meme(file: str) -> dict[str, _pandas.DataFrame]

Read motifs from a MEME minimal motif format file.

Parses a MEME minimal motif format file and returns a dict of position probability matrices (PPM). Each DataFrame has columns A, C, G, T with one row per motif position. Metadata is stored in the DataFrame's .attrs dict.

PARAMETER DESCRIPTION
file

Path to a MEME format file (.meme, .txt).

TYPE: str

RETURNS DESCRIPTION
dict[str, DataFrame]

Keys are motif identifiers, values are DataFrames. Each DataFrame has .attrs with keys: name, alength, w, nsites, E, url, strand, background.

RAISES DESCRIPTION
FileNotFoundError

If file does not exist.

ValueError

If the file is malformed or contains unsupported content.

pymisha.gseq_read_jaspar

gseq_read_jaspar(file: str) -> dict[str, _pandas.DataFrame]

Read motifs from a JASPAR PFM format file.

Parses a JASPAR Position Frequency Matrix (PFM) file and returns a dict of position probability matrices (PPM). Supports both the standard JASPAR header format (>ID NAME followed by labeled A/C/G/T rows) and the simple 4-row PFM format. Counts are converted to probabilities.

PARAMETER DESCRIPTION
file

Path to a JASPAR format file (.jaspar, .pfm, .txt).

TYPE: str

RETURNS DESCRIPTION
dict[str, DataFrame]

Keys are motif identifiers, values are DataFrames with columns A, C, G, T. Each DataFrame has .attrs with keys: name, w, nsites, format.

RAISES DESCRIPTION
FileNotFoundError

If file does not exist.

ValueError

If the file is malformed.

pymisha.gseq_read_homer

gseq_read_homer(file: str) -> dict[str, _pandas.DataFrame]

Read motifs from a HOMER motif format file.

Parses a HOMER .motif format file and returns a dict of position probability matrices (PPM). Each DataFrame has columns A, C, G, T.

PARAMETER DESCRIPTION
file

Path to a HOMER motif file (.motif).

TYPE: str

RETURNS DESCRIPTION
dict[str, DataFrame]

Keys are derived from the consensus sequence. Each DataFrame has .attrs with keys: name, consensus, log_odds_threshold, log_p_value, w, source.

RAISES DESCRIPTION
FileNotFoundError

If file does not exist.

ValueError

If the file is malformed.

pymisha.gseq_write_meme

gseq_write_meme(motifs, file, background=None, strands=None) -> None

Write motifs to a MEME minimal motif format file.

Each motif is written as a MOTIF <id> [<name>] line, a letter-probability matrix: line with alength, w and, when the motif has them, nsites and E, the matrix rows and, when the motif has one, a URL line. The file header declares the DNA alphabet, the strands and the background letter frequencies.

Probabilities are written with 6 decimals, as MEME writes them, so a written motif reads back within 5e-7 of the original. nsites and E-values are written with 15 significant digits. The output is byte-identical to R misha's gseq.write_meme for the same input.

Rows that do not sum to 1 are re-normalized (with a warning), as :func:gseq_read_meme does. Whitespace in IDs is replaced by _; whitespace in names is collapsed to single spaces (other tools may keep only the first word of a name). Motifs with the same ID (in a list) are written as they are; :func:gseq_read_meme adds suffixes to tell them apart.

PARAMETER DESCRIPTION
motifs

A dict of motif matrices, such as returned by :func:gseq_read_meme, :func:gseq_read_jaspar or :func:gseq_read_homer, a list of them, or a single matrix. Each matrix has one row per position and columns A, C, G, T (a numpy array or a DataFrame with default integer columns is taken in that order; a DataFrame indexed by A, C, G, T is transposed). Dict keys are the motif IDs; motifs without one are called motif_<i>. Metadata is read from each DataFrame's .attrs. The attrs name, nsites, E, url, strand and background are written when present.

TYPE: (dict, list, DataFrame or ndarray)

file

Path of the file to write.

TYPE: str or path - like

background

Background letter frequencies: 4 values keyed A, C, G, T (or a sequence in that order), normalized to sum to 1. None (the default) uses the background attr the motifs share (as :func:gseq_read_meme returns it), and uniform frequencies otherwise.

TYPE: (dict, sequence or None) DEFAULT: None

strands

"+ -" (both strands) or "+". None (the default) uses the strand attr the motifs share, and "+ -" otherwise.

TYPE: str or None DEFAULT: None

See Also

gseq_read_meme, gseq_write_jaspar, gseq_write_homer

Examples:

>>> import pandas as pd
>>> import pymisha as pm
>>> m = pd.DataFrame([[0.7, 0.1, 0.1, 0.1], [0.1, 0.1, 0.7, 0.1]],
...                  columns=["A", "C", "G", "T"])
>>> pm.gseq_write_meme({"M1": m}, "motifs.meme")

pymisha.gseq_write_jaspar

gseq_write_jaspar(motifs, file, nsites=None, format='jaspar', round_counts=True) -> None

Write motifs to a JASPAR format file.

Writes motifs as count matrices in the JASPAR format that :func:gseq_read_jaspar reads: a >ID name header line and one A [ ... ] row of counts per base. format="simple" writes the four rows of counts only, without headers or labels.

JASPAR matrices hold counts, so each motif's probabilities are multiplied by its number of sites: the nsites argument, else the motif's nsites attr (as :func:gseq_read_jaspar and :func:gseq_read_meme return it), else 100. Every position then sums to that number. Counts are rounded to whole numbers (halves to even), as JASPAR files hold them and as tools such as the MEME Suite's jaspar2meme and universalmotif require, so probabilities read back within about 0.5 / nsites; the integer counts of a JASPAR file are written back unchanged. With an nsites of a few, whole positions can round to zero, which readers take as uniform. round_counts=False writes counts with up to 6 decimals and without trailing zeros instead, so that probabilities read back within 1.5e-6 / nsites of the original. The output is byte-identical to R misha's gseq.write_jaspar.

The header names a motif by its name attr, or by its ID when it has none (JASPAR headers always carry a name). Rows that do not sum to 1 are re-normalized (with a warning). Whitespace in IDs is replaced by _; whitespace in names is collapsed to single spaces (other tools may keep only the first word of a name). A simple-format file has no IDs: :func:gseq_read_jaspar names its motifs after the file.

PARAMETER DESCRIPTION
motifs

A dict of motif matrices, such as returned by :func:gseq_read_meme, :func:gseq_read_jaspar or :func:gseq_read_homer, a list of them, or a single matrix. Each matrix has one row per position and columns A, C, G, T (a numpy array or a DataFrame with default integer columns is taken in that order; a DataFrame indexed by A, C, G, T is transposed). Dict keys are the motif IDs; motifs without one are called motif_<i>. Metadata is read from each DataFrame's .attrs. The attrs name and nsites are used when present.

TYPE: (dict, list, DataFrame or ndarray)

file

Path of the file to write.

TYPE: str or path - like

nsites

Number of sites to scale probabilities to counts: a positive number, or one per motif. None (the default) uses each motif's nsites attr, and 100 for motifs without one.

TYPE: float, sequence of float, or None DEFAULT: None

format

"jaspar" (headers and labeled rows) or "simple" (four rows of counts per motif).

TYPE: ('jaspar', 'simple') DEFAULT: "jaspar"

round_counts

Round counts to whole numbers (the default), or write them with up to 6 decimals (False).

TYPE: bool DEFAULT: True

See Also

gseq_read_jaspar, gseq_write_meme, gseq_write_homer

pymisha.gseq_write_homer

gseq_write_homer(motifs, file, threshold=None, threshold_frac=0.6) -> None

Write motifs to a HOMER motif format file.

Writes motifs in the HOMER .motif format that :func:gseq_read_homer and HOMER read: a header line >consensus<TAB>name<TAB>log-odds threshold[<TAB>log p-value] and one tab-separated row of A, C, G, T probabilities per position.

The consensus is the motif's consensus attr (as :func:gseq_read_homer returns it) when it has one of the motif's width, and otherwise is computed by HOMER's rule: each position's IUPAC symbol covers every base whose probability is within 0.15 of the highest. The name is the motif's name attr, or its ID when it has none. :func:gseq_read_homer names motifs by their consensus, so IDs that are not used as names are not kept.

The log-odds threshold (natural log against a uniform background, as HOMER scores) is the threshold argument, else the motif's log_odds_threshold attr, else threshold_frac times the motif's highest possible score. The log p-value is written when the motif has a log_p_value attr.

Probabilities, thresholds and log p-values are written with 6 decimals, so a written motif reads back within 5e-7 of the original. Rows that do not sum to 1 are re-normalized (with a warning). Tabs and other whitespace in names are collapsed to single spaces. The output is byte-identical to R misha's gseq.write_homer.

PARAMETER DESCRIPTION
motifs

A dict of motif matrices, such as returned by :func:gseq_read_meme, :func:gseq_read_jaspar or :func:gseq_read_homer, a list of them, or a single matrix. Each matrix has one row per position and columns A, C, G, T (a numpy array or a DataFrame with default integer columns is taken in that order; a DataFrame indexed by A, C, G, T is transposed). Dict keys are the motif IDs; motifs without one are called motif_<i>. Metadata is read from each DataFrame's .attrs. The attrs name, consensus, log_odds_threshold and log_p_value are used when present.

TYPE: (dict, list, DataFrame or ndarray)

file

Path of the file to write.

TYPE: str or path - like

threshold

Log-odds detection threshold: a number, or one per motif. None (the default) uses each motif's log_odds_threshold attr, and threshold_frac of its highest score for motifs without one.

TYPE: float, sequence of float, or None DEFAULT: None

threshold_frac

Fraction of a motif's highest log-odds score used as its threshold when neither threshold nor the motif gives one.

TYPE: float DEFAULT: 0.6

See Also

gseq_read_homer, gseq_write_meme, gseq_write_jaspar