diffgrammar 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- diffgrammar/__init__.py +6 -0
- diffgrammar/adapters/__init__.py +21 -0
- diffgrammar/adapters/peak_npz.py +114 -0
- diffgrammar/align.py +195 -0
- diffgrammar/analysis.py +744 -0
- diffgrammar/attribute.py +445 -0
- diffgrammar/calibrate.py +279 -0
- diffgrammar/cli.py +659 -0
- diffgrammar/cluster.py +439 -0
- diffgrammar/config.py +213 -0
- diffgrammar/contrast.py +223 -0
- diffgrammar/effects.py +317 -0
- diffgrammar/export.py +185 -0
- diffgrammar/expression.py +399 -0
- diffgrammar/jaspar.py +185 -0
- diffgrammar/marginalize/__init__.py +4 -0
- diffgrammar/marginalize/backgrounds.py +107 -0
- diffgrammar/marginalize/cooperativity.py +344 -0
- diffgrammar/marginalize/design.py +209 -0
- diffgrammar/marginalize/plots.py +546 -0
- diffgrammar/marginalize/predictor.py +109 -0
- diffgrammar/marginalize/readout.py +86 -0
- diffgrammar/marginalize/run.py +223 -0
- diffgrammar/marginalize/store.py +191 -0
- diffgrammar/pair_regression.py +323 -0
- diffgrammar/plotting.py +1186 -0
- diffgrammar/scan.py +151 -0
- diffgrammar/selection.py +174 -0
- diffgrammar/seqlets.py +376 -0
- diffgrammar/sequence.py +22 -0
- diffgrammar/summaries.py +140 -0
- diffgrammar/toy.py +129 -0
- diffgrammar/view/__init__.py +0 -0
- diffgrammar/view/app.py +1942 -0
- diffgrammar/view/data.py +1950 -0
- diffgrammar/view/figures.py +400 -0
- diffgrammar/view/network/index.html +232 -0
- diffgrammar/view/network.py +21 -0
- diffgrammar/view/pages.py +257 -0
- diffgrammar/view/tracks/index.html +459 -0
- diffgrammar/view/tracks.py +153 -0
- diffgrammar-0.1.0.dist-info/METADATA +204 -0
- diffgrammar-0.1.0.dist-info/RECORD +47 -0
- diffgrammar-0.1.0.dist-info/WHEEL +5 -0
- diffgrammar-0.1.0.dist-info/entry_points.txt +2 -0
- diffgrammar-0.1.0.dist-info/licenses/LICENSE +57 -0
- diffgrammar-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,323 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Which pairs of motifs move a measured differential more, or less, than the two motifs do apart, over every region of
|
|
3
|
+
a table of measured log2 fold changes and not only the regions the model was attributed on.
|
|
4
|
+
|
|
5
|
+
diffgrammar pair-regression config.toml # writes <out_dir>/pair_regression/<source>/
|
|
6
|
+
|
|
7
|
+
Why not co-occurrence between two classes of regions: the classes are chosen by the differential the motifs cause.
|
|
8
|
+
Two motifs that each nearly decide a class cannot show more of it together, as the class saturates; and within a
|
|
9
|
+
class, one of two motifs pushing the same way already explains the region, so the second looks less needed. A
|
|
10
|
+
regression of the measured fold change over every region, differential or not, has neither problem.
|
|
11
|
+
|
|
12
|
+
The model, for each pair (a, b) of motif families:
|
|
13
|
+
|
|
14
|
+
log2FC ~ every family's presence + log(1 + motif hits) + GC + [a and b both present]
|
|
15
|
+
|
|
16
|
+
so the pair term is what carrying both adds beyond the main effects of all families present in at least
|
|
17
|
+
`min_present` regions. It is fitted a second time with the pair split by spacing: both present with their nearest
|
|
18
|
+
sites at most `close` bp apart, or farther. Motifs come from scanning each region's central `window` bp
|
|
19
|
+
(diffgrammar.scan: the best JASPAR match of each cluster of a subfamily, FIMO p < `threshold`). Weighted by
|
|
20
|
+
1 / (SE^2 + tau^2), SE the fold change's standard error where the table has one and tau^2 the variance between
|
|
21
|
+
regions the standard errors do not cover (method of moments), so that a few very precise regions cannot carry the
|
|
22
|
+
fit. Standard errors are clustered by `block` bp of the genome, as neighbouring regions are not independent, with t on
|
|
23
|
+
(blocks - 1) degrees of freedom; BH over the pairs. The fold change is read as the contrast's B over A (`direction`),
|
|
24
|
+
so a negative pair term is towards A. Each pair is first tested against the main effects alone, so a pair that shares a
|
|
25
|
+
motif with a strong pair picks up a little of its effect; a second pass refits each pair with every pair that passed
|
|
26
|
+
the first (q <= `alpha`) in the base design, and a pair whose signal came from a stronger one drops out there. The
|
|
27
|
+
second pass can also take too much away where two families' matrices hit the same sites, as one pair then stands in
|
|
28
|
+
for the other; read both. A pair is skipped where one family's regions all carry the other, as the pair and that
|
|
29
|
+
family cannot be told apart there.
|
|
30
|
+
|
|
31
|
+
[pair_regression]
|
|
32
|
+
regions = "regions.parquet" # every region with a measured fold change
|
|
33
|
+
columns = { coord = "coord", log2fc = "log2fc", lfcse = "lfcSE" } # names in that table; lfcse optional
|
|
34
|
+
standard_errors = "deseq2.csv" # optional: a second table with the standard errors,
|
|
35
|
+
on = "OCR" # joined to the first on this column
|
|
36
|
+
exclude = { stage = ["Insufficient signal"] } # optional: rows to leave out, by column value
|
|
37
|
+
genome = "mm10.fa" # default: [attribute] or [marginalize] genome
|
|
38
|
+
# threshold = 1e-4, window = the median interval length, min_present = 50, min_both = 30, close = 16,
|
|
39
|
+
# block = 1000000, gc = "linear" ("deciles": GC deciles and CpG density, a stricter control of composition),
|
|
40
|
+
# direction = "b_over_a" (the table's fold change is the contrast's B over A; "a_over_b" turns it round)
|
|
41
|
+
|
|
42
|
+
Two sources of motifs (`sources`, both by default), each fitted on its own: 'scan', every region of the table with
|
|
43
|
+
its motifs found by scanning, which reads the sequence whether the model uses a site or not; and 'seqlets', the
|
|
44
|
+
run's own seqlets, which say which sites the model uses but exist only in the regions it was attributed on. Those
|
|
45
|
+
were chosen by the differential, so the seqlet fit sees a selected set of regions; set the two side by side.
|
|
46
|
+
|
|
47
|
+
Writes, per source under pair_regression/<source>/, pairs.csv (one row per pair: a, b, a_label, b_label, both, pair, se, p, q; the second pass pair_cond, se_cond,
|
|
48
|
+
p_cond, q_cond; close, close_se, close_p, n_close; far, far_se, far_p, n_far), families.csv (each family's main effect in the base model: key, label, regions, effect,
|
|
49
|
+
se, p) and settings.json (what the fit saw, and the settings under `settings`).
|
|
50
|
+
"""
|
|
51
|
+
from __future__ import annotations
|
|
52
|
+
|
|
53
|
+
import json
|
|
54
|
+
import re
|
|
55
|
+
import time
|
|
56
|
+
from typing import Dict, Optional, Tuple
|
|
57
|
+
|
|
58
|
+
import numpy as np
|
|
59
|
+
import pandas as pd
|
|
60
|
+
|
|
61
|
+
from . import config as C
|
|
62
|
+
from . import scan as SC
|
|
63
|
+
|
|
64
|
+
DEFAULTS = {'threshold': 1e-4, 'window': None, 'min_present': 50, 'min_both': 30, 'close': 16, 'block': 1_000_000,
|
|
65
|
+
'gc': 'linear', 'alpha': 0.05, 'direction': 'b_over_a', 'sources': ['scan', 'seqlets']}
|
|
66
|
+
#: where the motifs of a region come from: scanning its sequence (every region of the table), or the run's seqlets
|
|
67
|
+
#: (only the regions the model was attributed on, as only they have seqlets)
|
|
68
|
+
SOURCES = ('scan', 'seqlets')
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def settings(cfg: dict) -> dict:
|
|
72
|
+
"""[pair_regression] over DEFAULTS; the genome falls back to the one of [attribute] or [marginalize]."""
|
|
73
|
+
s = {**DEFAULTS, **(cfg.get('pair_regression') or {})}
|
|
74
|
+
if not s.get('regions'):
|
|
75
|
+
raise SystemExit('[pair_regression] needs `regions`: a table of every region with a measured log2 fold change')
|
|
76
|
+
s['genome'] = s.get('genome') or (cfg.get('attribute') or {}).get('genome') or (cfg.get('marginalize') or {}).get('genome')
|
|
77
|
+
if not s['genome']:
|
|
78
|
+
raise SystemExit('[pair_regression] needs `genome`, the FASTA the regions are read from')
|
|
79
|
+
return s
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def regions_table(s: dict) -> pd.DataFrame:
|
|
83
|
+
"""coord, log2fc and lfcse (NaN without standard errors) of every region the settings keep, one row per coord."""
|
|
84
|
+
from .expression import read_table
|
|
85
|
+
t = read_table(s['regions'])
|
|
86
|
+
if s.get('standard_errors'):
|
|
87
|
+
if not s.get('on'):
|
|
88
|
+
raise SystemExit('[pair_regression] standard_errors needs `on`, the column both tables share')
|
|
89
|
+
t = t.merge(read_table(s['standard_errors']), on=s['on'], how='inner', suffixes=('', '_se'))
|
|
90
|
+
for col, values in (s.get('exclude') or {}).items():
|
|
91
|
+
t = t[~t[col].isin(values if isinstance(values, list) else [values])]
|
|
92
|
+
cols = {'coord': 'coord', 'log2fc': 'log2fc', 'lfcse': None, **(s.get('columns') or {})}
|
|
93
|
+
out = pd.DataFrame({'coord': t[cols['coord']].astype(str).to_numpy(),
|
|
94
|
+
'log2fc': pd.to_numeric(t[cols['log2fc']], errors='coerce').to_numpy(),
|
|
95
|
+
'lfcse': pd.to_numeric(t[cols['lfcse']], errors='coerce').to_numpy() if cols['lfcse'] else np.nan})
|
|
96
|
+
keep = np.isfinite(out['log2fc']) & out['coord'].str.fullmatch(r'.+:\d+-\d+')
|
|
97
|
+
if cols['lfcse']:
|
|
98
|
+
keep &= np.isfinite(out['lfcse']) & (out['lfcse'] > 0)
|
|
99
|
+
return out[keep].drop_duplicates('coord').reset_index(drop=True)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def sequences(coords: pd.Series, genome: str, window: Optional[int] = None):
|
|
103
|
+
"""
|
|
104
|
+
The central `window` bp (default the median interval length) of each region as one-hot (n, 4, window), with N
|
|
105
|
+
past a chromosome end; GC and CpG share of each; chromosome and centre; and which regions the genome has.
|
|
106
|
+
"""
|
|
107
|
+
from pyfaidx import Fasta
|
|
108
|
+
xy = coords.str.extract(r'(.+):(\d+)-(\d+)')
|
|
109
|
+
start, end = xy[1].astype(int).to_numpy(), xy[2].astype(int).to_numpy()
|
|
110
|
+
w = int(window or np.median(end - start))
|
|
111
|
+
centre = (start + end) // 2
|
|
112
|
+
lo = centre - w // 2
|
|
113
|
+
fa = Fasta(genome)
|
|
114
|
+
have = xy[0].isin(set(fa.keys())).to_numpy()
|
|
115
|
+
lut = np.full(256, 4, np.uint8)
|
|
116
|
+
for i, ch in enumerate('ACGT'):
|
|
117
|
+
lut[ord(ch)] = lut[ord(ch.lower())] = i
|
|
118
|
+
codes = np.full((len(coords), w), 4, np.uint8)
|
|
119
|
+
for i in np.flatnonzero(have):
|
|
120
|
+
a, b = max(0, lo[i]), lo[i] + w
|
|
121
|
+
s = str(fa[xy[0].iat[i]][a:b])
|
|
122
|
+
codes[i, a - lo[i]:a - lo[i] + len(s)] = lut[np.frombuffer(s.encode(), np.uint8)]
|
|
123
|
+
onehot = np.zeros((len(coords), 4, w), np.float32)
|
|
124
|
+
n, pos = np.nonzero(codes < 4)
|
|
125
|
+
onehot[n, codes[n, pos], pos] = 1.0
|
|
126
|
+
gc = (onehot[:, 1] + onehot[:, 2]).mean(axis=1)
|
|
127
|
+
cpg = (onehot[:, 1, :-1] * onehot[:, 2, 1:]).sum(axis=1) / max(w - 1, 1)
|
|
128
|
+
return onehot, gc, cpg, xy[0].to_numpy(), centre, have
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
class WeightedFit:
|
|
132
|
+
"""
|
|
133
|
+
Weighted least squares of y on a base design X, weights 1 / (se2 + tau2), errors clustered by `blocks`; test()
|
|
134
|
+
adds columns to it by Frisch-Waugh-Lovell, so each pair costs one projection rather than a fit.
|
|
135
|
+
"""
|
|
136
|
+
|
|
137
|
+
def __init__(self, X: np.ndarray, y: np.ndarray, se2: np.ndarray, blocks: np.ndarray, sw: Optional[np.ndarray] = None):
|
|
138
|
+
if sw is None:
|
|
139
|
+
beta, *_ = np.linalg.lstsq(X, y, rcond=None)
|
|
140
|
+
self.tau2 = max(0.0, float(np.mean((y - X @ beta) ** 2) - np.mean(se2)))
|
|
141
|
+
sw = np.sqrt(1.0 / (se2 + self.tau2))
|
|
142
|
+
self.sw = sw
|
|
143
|
+
Xw = X * self.sw[:, None]
|
|
144
|
+
self.Q, self.R = np.linalg.qr(Xw)
|
|
145
|
+
yw = y * self.sw
|
|
146
|
+
self.beta = np.linalg.solve(self.R, self.Q.T @ yw)
|
|
147
|
+
self.ry = yw - self.Q @ (self.Q.T @ yw)
|
|
148
|
+
self.g = pd.factorize(blocks)[0]
|
|
149
|
+
self.G, self.n, self.p = int(self.g.max()) + 1, len(y), X.shape[1]
|
|
150
|
+
self.Xw = Xw
|
|
151
|
+
|
|
152
|
+
def _clustered(self, U: np.ndarray, e: np.ndarray, Ainv: np.ndarray, k: int):
|
|
153
|
+
S = np.stack([np.bincount(self.g, weights=U[:, j] * e, minlength=self.G) for j in range(U.shape[1])])
|
|
154
|
+
corr = self.G / (self.G - 1) * (self.n - 1) / (self.n - self.p - k)
|
|
155
|
+
return Ainv @ (S @ S.T) @ Ainv * corr
|
|
156
|
+
|
|
157
|
+
def base(self):
|
|
158
|
+
"""The base design's coefficients, clustered standard errors and p."""
|
|
159
|
+
from scipy.stats import t as tdist
|
|
160
|
+
Rinv = np.linalg.inv(self.R)
|
|
161
|
+
cov = self._clustered(self.Xw, self.ry, Rinv @ Rinv.T, 0)
|
|
162
|
+
se = np.sqrt(np.diag(cov))
|
|
163
|
+
return self.beta, se, 2 * tdist.sf(np.abs(self.beta / se), self.G - 1)
|
|
164
|
+
|
|
165
|
+
def test(self, Z: np.ndarray) -> Optional[Tuple[np.ndarray, np.ndarray, np.ndarray]]:
|
|
166
|
+
"""Coefficients, clustered standard errors and p of the columns of Z (n, k) added to the base design."""
|
|
167
|
+
from scipy.stats import t as tdist
|
|
168
|
+
Zw = Z * self.sw[:, None]
|
|
169
|
+
Rz = Zw - self.Q @ (self.Q.T @ Zw)
|
|
170
|
+
A = Rz.T @ Rz
|
|
171
|
+
if np.linalg.matrix_rank(A) < Z.shape[1] or np.diag(A).min() < 1e-9 * (Zw ** 2).sum(axis=0).max():
|
|
172
|
+
return None # a column the base design already holds, to rounding
|
|
173
|
+
Ainv = np.linalg.inv(A)
|
|
174
|
+
b = Ainv @ (Rz.T @ self.ry)
|
|
175
|
+
se = np.sqrt(np.diag(self._clustered(Rz, self.ry - Rz @ b, Ainv, Z.shape[1])))
|
|
176
|
+
return b, se, 2 * tdist.sf(np.abs(b / se), self.G - 1)
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def nearest_gaps(hits: pd.DataFrame, a: str, b: str) -> pd.Series:
|
|
180
|
+
"""For each region (seq) carrying keys a and b: the gap in bp between their nearest sites (0 where they overlap)."""
|
|
181
|
+
x, y = hits[hits['key'] == a], hits[hits['key'] == b]
|
|
182
|
+
m = x[['seq', 'start', 'end']].merge(y[['seq', 'start', 'end']], on='seq', suffixes=('_a', '_b'))
|
|
183
|
+
gap = np.maximum(0, np.maximum(m['start_a'], m['start_b']) - np.minimum(m['end_a'], m['end_b']))
|
|
184
|
+
return pd.Series(gap.to_numpy(), index=m['seq'].to_numpy()).groupby(level=0).min()
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def fit_pairs(y: np.ndarray, se2: np.ndarray, P: np.ndarray, keys: list, covariates: np.ndarray, blocks: np.ndarray,
|
|
188
|
+
hits: pd.DataFrame, close: int = 16, min_present: int = 50, min_both: int = 30, alpha: float = 0.05):
|
|
189
|
+
"""
|
|
190
|
+
The pair regression on prepared inputs: y the fold changes, se2 their squared standard errors (zeros for none),
|
|
191
|
+
P (regions, keys) the presence of each key, covariates (regions, c), blocks the cluster of each region, hits
|
|
192
|
+
(seq, key, start, end) the sites for the spacing split. Returns (pairs, families, info); see the module docstring.
|
|
193
|
+
"""
|
|
194
|
+
from .attribute import _bh
|
|
195
|
+
use = [i for i in range(len(keys)) if P[:, i].sum() >= min_present]
|
|
196
|
+
X = np.column_stack([np.ones(len(y)), P[:, use].astype(float), covariates])
|
|
197
|
+
fit = WeightedFit(X, y, se2, blocks)
|
|
198
|
+
beta, se, p = fit.base()
|
|
199
|
+
families = pd.DataFrame({'key': [keys[i] for i in use], 'regions': P[:, use].sum(axis=0),
|
|
200
|
+
'effect': beta[1:1 + len(use)], 'se': se[1:1 + len(use)], 'p': p[1:1 + len(use)]})
|
|
201
|
+
rows = []
|
|
202
|
+
for x, i in enumerate(use):
|
|
203
|
+
for j in use[x + 1:]:
|
|
204
|
+
both = P[:, i] & P[:, j]
|
|
205
|
+
if both.sum() < min_both or both.sum() in (P[:, i].sum(), P[:, j].sum()):
|
|
206
|
+
continue # too rare, or one family's regions all carry the other
|
|
207
|
+
r = fit.test(both[:, None].astype(float))
|
|
208
|
+
if r is None: # two keys with the same sites: a matrix they share
|
|
209
|
+
continue
|
|
210
|
+
row = {'a': keys[i], 'b': keys[j], 'both': int(both.sum()), 'pair': r[0][0], 'se': r[1][0], 'p': r[2][0]}
|
|
211
|
+
gaps = nearest_gaps(hits, keys[i], keys[j])
|
|
212
|
+
near = np.zeros(len(y), bool)
|
|
213
|
+
near[gaps.index[gaps.to_numpy() <= close]] = True
|
|
214
|
+
near &= both
|
|
215
|
+
far = both & ~near
|
|
216
|
+
row.update(n_close=int(near.sum()), n_far=int(far.sum()))
|
|
217
|
+
s = fit.test(np.column_stack([near, far]).astype(float)) if near.any() and far.any() else None
|
|
218
|
+
if s is not None:
|
|
219
|
+
row.update(close=s[0][0], close_se=s[1][0], close_p=s[2][0], far=s[0][1], far_se=s[1][1], far_p=s[2][1])
|
|
220
|
+
rows.append(row)
|
|
221
|
+
cols = ['a', 'b', 'both', 'pair', 'se', 'p', 'q', 'pair_cond', 'se_cond', 'p_cond', 'q_cond', 'close', 'close_se',
|
|
222
|
+
'close_p', 'n_close', 'far', 'far_se', 'far_p', 'n_far']
|
|
223
|
+
pairs = pd.DataFrame(rows).reindex(columns=[c for c in cols if c not in ('q', 'pair_cond', 'se_cond', 'p_cond', 'q_cond')])
|
|
224
|
+
pairs['q'] = _bh(pairs['p'].to_numpy()) if len(pairs) else []
|
|
225
|
+
# second pass: each pair with every first-pass pair at q <= alpha (but itself) in the base design
|
|
226
|
+
at = {k: i for i, k in enumerate(keys)}
|
|
227
|
+
both_of = lambda a, b: (P[:, at[a]] & P[:, at[b]]).astype(float) # noqa: E731
|
|
228
|
+
lead = {(r.a, r.b): both_of(r.a, r.b) for r in pairs[pairs['q'] <= alpha].itertuples()}
|
|
229
|
+
shared = WeightedFit(np.column_stack([X] + list(lead.values())), y, se2, blocks, sw=fit.sw) if lead else fit
|
|
230
|
+
cond = []
|
|
231
|
+
for r in pairs.itertuples():
|
|
232
|
+
f = shared
|
|
233
|
+
if (r.a, r.b) in lead:
|
|
234
|
+
others = [v for k, v in lead.items() if k != (r.a, r.b)]
|
|
235
|
+
f = WeightedFit(np.column_stack([X] + others), y, se2, blocks, sw=fit.sw) if others else fit
|
|
236
|
+
t = f.test(both_of(r.a, r.b)[:, None])
|
|
237
|
+
cond.append((t[0][0], t[1][0], t[2][0]) if t is not None else (np.nan, np.nan, np.nan))
|
|
238
|
+
pairs[['pair_cond', 'se_cond', 'p_cond']] = np.array(cond).reshape(-1, 3) if cond else np.empty((0, 3))
|
|
239
|
+
pairs['q_cond'] = _bh(pairs['p_cond'].to_numpy()) if len(pairs) else []
|
|
240
|
+
info = {'regions': int(len(y)), 'families_in_model': len(use), 'blocks': fit.G, 'tau2': fit.tau2,
|
|
241
|
+
'median_se2': float(np.median(se2)), 'pairs_tested': int(len(pairs)), 'first_pass_pairs': len(lead)}
|
|
242
|
+
return pairs[cols].sort_values('p', kind='stable', ignore_index=True), families, info
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def run(cfg: dict, log=print) -> dict:
|
|
246
|
+
"""
|
|
247
|
+
The pair regression of a run's config, once for each of [pair_regression] sources: writes
|
|
248
|
+
<out_dir>/pair_regression/<source>/. Returns what each fit saw, by source.
|
|
249
|
+
"""
|
|
250
|
+
from .analysis import Analysis
|
|
251
|
+
from .view.data import motif_labels, motif_sites
|
|
252
|
+
s = settings(cfg)
|
|
253
|
+
sources = [s['sources']] if isinstance(s['sources'], str) else list(s['sources'])
|
|
254
|
+
if not set(sources) <= set(SOURCES):
|
|
255
|
+
raise SystemExit(f'[pair_regression] sources are among {SOURCES}, not {sources}')
|
|
256
|
+
if s['direction'] not in ('b_over_a', 'a_over_b'):
|
|
257
|
+
raise SystemExit(f"[pair_regression] direction is b_over_a or a_over_b, not {s['direction']!r}")
|
|
258
|
+
t0 = time.time()
|
|
259
|
+
an = Analysis(cfg['_path'])
|
|
260
|
+
labels = motif_labels(an, 'subfamily')
|
|
261
|
+
names = labels.drop_duplicates('key').set_index('key')['label']
|
|
262
|
+
km = SC.key_matrices(an, labels)
|
|
263
|
+
reg = regions_table(s)
|
|
264
|
+
onehot, gc, cpg, chrom, centre, have = sequences(reg['coord'], s['genome'], s['window'])
|
|
265
|
+
keep = np.flatnonzero(have)
|
|
266
|
+
reg, onehot, gc, cpg, chrom, centre = reg.iloc[keep].reset_index(drop=True), onehot[keep], gc[keep], cpg[keep], chrom[keep], centre[keep]
|
|
267
|
+
log(f'[pair_regression] {len(reg):,} regions with a fold change read from the genome ({time.time() - t0:.0f}s)')
|
|
268
|
+
y = reg['log2fc'].to_numpy(float) * (1 if s['direction'] == 'b_over_a' else -1) # always B over A from here
|
|
269
|
+
se2 = reg['lfcse'].to_numpy(float) ** 2 if reg['lfcse'].notna().all() else np.zeros(len(reg))
|
|
270
|
+
blocks = (pd.Series(chrom).astype(str) + ':' + (centre // int(s['block'])).astype(str)).to_numpy()
|
|
271
|
+
short = [k for k, ms in km.items() if all(p.shape[1] < 7 for p in ms.values())]
|
|
272
|
+
infos = {}
|
|
273
|
+
for source in sources:
|
|
274
|
+
t1 = time.time()
|
|
275
|
+
if source == 'scan':
|
|
276
|
+
rows = np.arange(len(reg))
|
|
277
|
+
to_keys: Dict[str, list] = {}
|
|
278
|
+
for k, ms in km.items():
|
|
279
|
+
for mid in ms:
|
|
280
|
+
to_keys.setdefault(mid, []).append(k)
|
|
281
|
+
pwms = {mid: next(ms[mid] for ms in km.values() if mid in ms) for mid in to_keys}
|
|
282
|
+
hits = SC.scan(onehot, pwms, float(s['threshold']))
|
|
283
|
+
hits = hits.assign(key=hits['matrix'].map(to_keys)).explode('key')[['seq', 'key', 'start', 'end']]
|
|
284
|
+
keys = sorted(km)
|
|
285
|
+
else: # the run's seqlets, so only the attributed regions
|
|
286
|
+
thr = an.thresholds
|
|
287
|
+
thr = thr[(thr['contrast'] == an.contrast.name) & thr['set_name'].isin(an.sets)]
|
|
288
|
+
rows = np.flatnonzero(reg['coord'].isin(set(thr['coord'])).to_numpy())
|
|
289
|
+
at = {c: i for i, c in enumerate(reg['coord'].iloc[rows])}
|
|
290
|
+
m = motif_sites(an, 'subfamily', 'seqlets')
|
|
291
|
+
m = m[m['coord'].isin(at)]
|
|
292
|
+
hits = pd.DataFrame({'seq': m['coord'].map(at).to_numpy(int), 'key': m['key'].to_numpy(),
|
|
293
|
+
'start': m['start'].to_numpy(int), 'end': m['end'].to_numpy(int)})
|
|
294
|
+
keys = sorted(set(labels['key']))
|
|
295
|
+
P = np.zeros((len(rows), len(keys)), bool)
|
|
296
|
+
P[hits['seq'].to_numpy(int), hits['key'].map({k: i for i, k in enumerate(keys)}).to_numpy()] = True
|
|
297
|
+
n_hits = np.bincount(hits['seq'].to_numpy(int), minlength=len(rows)).astype(float)
|
|
298
|
+
g, c = gc[rows], cpg[rows]
|
|
299
|
+
if s['gc'] == 'deciles':
|
|
300
|
+
edges = np.quantile(g, np.linspace(0.1, 0.9, 9))
|
|
301
|
+
cov = np.column_stack([np.log1p(n_hits), g, c] + [(g > e).astype(float) for e in edges])
|
|
302
|
+
else:
|
|
303
|
+
cov = np.column_stack([np.log1p(n_hits), g])
|
|
304
|
+
log(f'[pair_regression] {source}: {len(rows):,} regions, {len(hits):,} motif sites in {len(keys)} families; '
|
|
305
|
+
'fitting every pair')
|
|
306
|
+
pairs, families, info = fit_pairs(y[rows], se2[rows], P, keys, cov, blocks[rows], hits, int(s['close']),
|
|
307
|
+
int(s['min_present']), int(s['min_both']), float(s['alpha']))
|
|
308
|
+
pairs.insert(2, 'a_label', pairs['a'].map(names))
|
|
309
|
+
pairs.insert(3, 'b_label', pairs['b'].map(names))
|
|
310
|
+
families.insert(1, 'label', families['key'].map(names))
|
|
311
|
+
out = C.out_dir(cfg) / 'pair_regression' / source
|
|
312
|
+
out.mkdir(parents=True, exist_ok=True)
|
|
313
|
+
pairs.to_csv(out / 'pairs.csv', index=False, float_format='%.6g')
|
|
314
|
+
families.sort_values('p').to_csv(out / 'families.csv', index=False, float_format='%.6g')
|
|
315
|
+
info.update(source=source, weighted=bool(se2.any()), seconds=round(time.time() - t1),
|
|
316
|
+
families_only_short_matrices=short if source == 'scan' else [],
|
|
317
|
+
settings={k: (v if isinstance(v, (int, float, str, type(None))) else str(v)) for k, v in s.items()})
|
|
318
|
+
(out / 'settings.json').write_text(json.dumps(info, indent=1, default=str))
|
|
319
|
+
a = float(s['alpha'])
|
|
320
|
+
log(f'[pair_regression] {source}: {len(pairs):,} pairs; {int((pairs["q"] <= a).sum())} at q <= {a:g}, '
|
|
321
|
+
f'{int((pairs["q_cond"] <= a).sum())} with the others in the model -> {out} ({info["seconds"]}s)')
|
|
322
|
+
infos[source] = info
|
|
323
|
+
return infos
|