Sequence Analysis¶
Functions for extracting and analyzing DNA sequences, including reverse complement operations, k-mer counting, and position weight matrix scoring.
pymisha.gseq_extract ¶
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:
|
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:
|
| 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
TYPE:
|
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
TYPE:
|
dtype
|
One of bool, uint8, int8, int16, int32, int64, float32, float64.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ndarray
|
Array of shape |
See Also
gseq_extract, gextract_windows
Examples:
pymisha.gseq_rev ¶
Reverse DNA sequence(s).
| PARAMETER | DESCRIPTION |
|---|---|
seq
|
DNA sequence(s) to reverse.
TYPE:
|
| 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 ¶
Return complement of DNA sequence(s).
| PARAMETER | DESCRIPTION |
|---|---|
seq
|
DNA sequence(s) to complement.
TYPE:
|
| 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 ¶
Return reverse complement of DNA sequence(s).
| PARAMETER | DESCRIPTION |
|---|---|
seq
|
DNA sequence(s) to reverse complement.
TYPE:
|
| 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:
|
kmer
|
K-mer pattern to search for (only A, C, G, T characters).
TYPE:
|
mode
|
"count" returns raw counts, "frac" returns the fraction of the allowed anchors that match.
TYPE:
|
strand
|
0 = both strands, summed, 1 = forward only, -1 = reverse complement only.
TYPE:
|
start_pos
|
1-based start of the ROI, per sequence (recycled); 1 by default.
TYPE:
|
end_pos
|
1-based end of the ROI (inclusive), per sequence (recycled); the sequence end by default.
TYPE:
|
extend
|
How many bases a match may run past
TYPE:
|
skip_gaps
|
If True, gap characters are removed before scanning; windows are k
consecutive non-gap bases, and
TYPE:
|
gap_chars
|
Characters to treat as gaps. Default: ["-", "."].
TYPE:
|
| 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:
Count CG dinucleotides on the forward strand (CG is its own reverse
complement, so strand=0 would count each site twice, with a warning):
Get fraction instead of count:
Count in a specific region:
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:
|
k
|
K-mer size (1-10).
TYPE:
|
mask
|
Intervals to exclude: a k-mer with any base in one is not counted.
TYPE:
|
| 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);
TYPE:
|
k
|
The k-mer length whose counts are kept, 1 to 32.
TYPE:
|
n
|
The number of shuffles of each sequence.
TYPE:
|
seed
|
An integer with
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str, list of str, or list of list of str
|
For a single string, a string ( |
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:
|
pssm
|
Position-specific scoring matrix. If ndarray, shape
TYPE:
|
mode
|
Scoring mode:
TYPE:
|
bidirect
|
If True, score both forward and reverse complement strands. Overrides strand.
TYPE:
|
strand
|
Used only when
TYPE:
|
score_thresh
|
Threshold for
TYPE:
|
start_pos
|
1-based inclusive start of the region of interest (ROI), per sequence (recycled); 1 by default.
TYPE:
|
end_pos
|
1-based inclusive end of the ROI, per sequence (recycled); the sequence end by default.
TYPE:
|
extend
|
How many bases a window may run past
TYPE:
|
spat_factor
|
Spatial weighting factors, one per spatial bin. When provided,
the score at each window position is shifted in log-space by
TYPE:
|
spat_bin
|
Number of consecutive positions that share the same spatial
weight. Position offset maps to bin
TYPE:
|
spat_min
|
1-based position, counted from
TYPE:
|
spat_max
|
1-based position, counted from
TYPE:
|
return_strand
|
For
TYPE:
|
skip_gaps
|
Skip gap characters when scanning.
TYPE:
|
gap_chars
|
Characters treated as gaps. Default
TYPE:
|
neutral_chars
|
Characters to score as unknown bases, by
TYPE:
|
neutral_chars_policy
|
How to score neutral characters:
TYPE:
|
prior
|
Pseudocount added to PSSM before normalization, between 0 and 1.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ndarray or DataFrame
|
With Otherwise, an array of scores (one per input sequence). For |
Examples:
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):
Find position of best match:
Count matches above a threshold:
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:
|
pssm
|
Position-specific scoring matrix, shape
TYPE:
|
score_thresh
|
Required. Windows scoring at or above it are hits.
TYPE:
|
bidirect
|
Scan both strands.
TYPE:
|
strand
|
With
TYPE:
|
start_pos
|
1-based inclusive region of interest per sequence (recycled), as in
:func:
TYPE:
|
end_pos
|
1-based inclusive region of interest per sequence (recycled), as in
:func:
TYPE:
|
extend
|
How many bases a window may run past
TYPE:
|
prior
|
Pseudocount added to the PSSM frequencies.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DataFrame
|
One row per hit with columns |
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:
|
model
|
The energy model, with keys:
Extra keys named
TYPE:
|
mode
|
TYPE:
|
bidirect
|
If True both strands are read. The two strands are combined at each
window by log-sum-exp for
TYPE:
|
strand
|
Used only when
TYPE:
|
score_thresh
|
Required for
TYPE:
|
extend
|
Accepted for signature parity with :func:
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ndarray
|
One value per input sequence. |
Examples:
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 ¶
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 (
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict[str, DataFrame]
|
Keys are motif identifiers, values are DataFrames. Each DataFrame
has |
| RAISES | DESCRIPTION |
|---|---|
FileNotFoundError
|
If file does not exist. |
ValueError
|
If the file is malformed or contains unsupported content. |
pymisha.gseq_read_jaspar ¶
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 (
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict[str, DataFrame]
|
Keys are motif identifiers, values are DataFrames with columns
|
| RAISES | DESCRIPTION |
|---|---|
FileNotFoundError
|
If file does not exist. |
ValueError
|
If the file is malformed. |
pymisha.gseq_read_homer ¶
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 (
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict[str, DataFrame]
|
Keys are derived from the consensus sequence. Each DataFrame has
|
| RAISES | DESCRIPTION |
|---|---|
FileNotFoundError
|
If file does not exist. |
ValueError
|
If the file is malformed. |
pymisha.gseq_write_meme ¶
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:
TYPE:
|
file
|
Path of the file to write.
TYPE:
|
background
|
Background letter frequencies: 4 values keyed
TYPE:
|
strands
|
TYPE:
|
See Also
gseq_read_meme, gseq_write_jaspar, gseq_write_homer
Examples:
pymisha.gseq_write_jaspar ¶
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:
TYPE:
|
file
|
Path of the file to write.
TYPE:
|
nsites
|
Number of sites to scale probabilities to counts: a positive number, or
one per motif.
TYPE:
|
format
|
TYPE:
|
round_counts
|
Round counts to whole numbers (the default), or write them with up to 6
decimals (
TYPE:
|
See Also
gseq_read_jaspar, gseq_write_meme, gseq_write_homer
pymisha.gseq_write_homer ¶
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:
TYPE:
|
file
|
Path of the file to write.
TYPE:
|
threshold
|
Log-odds detection threshold: a number, or one per motif.
TYPE:
|
threshold_frac
|
Fraction of a motif's highest log-odds score used as its threshold when
neither
TYPE:
|
See Also
gseq_read_homer, gseq_write_meme, gseq_write_jaspar