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
diffgrammar/contrast.py
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Contrasts: turn per-track attributions of a region into the records seqlets are called on.
|
|
3
|
+
|
|
4
|
+
A contrast compares condition B with condition A, each a group of model output tracks (one
|
|
5
|
+
track per condition in a two-genotype model, several cell types per group in an atlas model).
|
|
6
|
+
Integrated gradients is linear in the output, so the attribution of a group mean is the mean
|
|
7
|
+
of the track attributions, and the contrast attribution is
|
|
8
|
+
|
|
9
|
+
hyp_B-A = mean_B(hyp) - mean_A(hyp) (L, 4) hypothetical
|
|
10
|
+
contrib = hyp_B-A . onehot (L,) sums to dF(x) - dF(reference)
|
|
11
|
+
|
|
12
|
+
Seqlets are called on up to three tracks of a region under a contrast (TRACKS): 'a', the mean A
|
|
13
|
+
attribution; 'b', the mean B attribution; and 'diff', their difference. A motif active in both
|
|
14
|
+
conditions and equal between them has a near-zero differential and is found on the condition
|
|
15
|
+
tracks only; a differential motif is found on 'diff'. One record per (region, contrast, track),
|
|
16
|
+
told apart by its `track`, and the cluster step merges the seqlets of one site across tracks.
|
|
17
|
+
|
|
18
|
+
The budget that sets the seqlet threshold is |dF(x) - dF(reference)| of the record's own track:
|
|
19
|
+
for 'diff' either the model's stored prediction (exact, when the adapter has one for the contrast)
|
|
20
|
+
or completeness, the sum of the contributions (equal up to the integration error of IG, typically
|
|
21
|
+
below a few percent); for a condition track always completeness, the sum of its own
|
|
22
|
+
contributions, since adapters store budgets per contrast only. A condition's budget is that
|
|
23
|
+
condition's whole predicted signal, the contrast's the difference between two of them, so with one
|
|
24
|
+
`pct` the absolute cut on a condition track is much higher than on 'diff'; thresholds.csv records
|
|
25
|
+
each record's cut and `diffgrammar seqlets` prints the per-track counts and median cut. A condition
|
|
26
|
+
track with almost no signal has a near-zero cut and yields noise, so contrast_records gates the
|
|
27
|
+
condition tracks on their budgets (diffgrammar.calibrate derives the floor from the run itself).
|
|
28
|
+
|
|
29
|
+
A contrast without A (`single`) is a single-track run: no comparison, the attributions of B alone. Each
|
|
30
|
+
region then gives one record, on 'b', whose contributions sum to F_b(x) - F_b(reference); a seqlet's sign
|
|
31
|
+
says whether the motif raises (+1) or lowers (-1) B's signal.
|
|
32
|
+
"""
|
|
33
|
+
from __future__ import annotations
|
|
34
|
+
|
|
35
|
+
from dataclasses import dataclass, field
|
|
36
|
+
from typing import Dict, Iterable, Iterator, List, Optional, Sequence
|
|
37
|
+
|
|
38
|
+
import numpy as np
|
|
39
|
+
|
|
40
|
+
from .seqlets import contributions_from_attributions
|
|
41
|
+
|
|
42
|
+
#: the tracks of a region under a contrast that seqlets can be called on, and the default order
|
|
43
|
+
TRACKS = ('a', 'b', 'diff')
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@dataclass
|
|
47
|
+
class Contrast:
|
|
48
|
+
"""B minus A over groups of track names. Labels are what figures call the two conditions."""
|
|
49
|
+
name: str
|
|
50
|
+
a: List[str]
|
|
51
|
+
b: List[str]
|
|
52
|
+
label_a: str = 'A'
|
|
53
|
+
label_b: str = 'B'
|
|
54
|
+
|
|
55
|
+
def __post_init__(self):
|
|
56
|
+
if set(self.a) & set(self.b):
|
|
57
|
+
raise ValueError(f'contrast {self.name}: tracks in both groups: {set(self.a) & set(self.b)}')
|
|
58
|
+
if not self.b:
|
|
59
|
+
raise ValueError(f'contrast {self.name}: condition B needs at least one track')
|
|
60
|
+
|
|
61
|
+
@property
|
|
62
|
+
def single(self) -> bool:
|
|
63
|
+
"""One condition and no comparison: a single-track run on B's attributions alone (no A tracks)."""
|
|
64
|
+
return not self.a
|
|
65
|
+
|
|
66
|
+
@classmethod
|
|
67
|
+
def from_config(cls, name: str, cfg: dict, tracks: Optional[Sequence[str]] = None) -> 'Contrast':
|
|
68
|
+
"""
|
|
69
|
+
cfg holds a / b as explicit track lists, or a_prefixes / b_prefixes resolved against
|
|
70
|
+
`tracks`, plus optional label_a / label_b. Without a and a_prefixes the contrast is single (B alone).
|
|
71
|
+
"""
|
|
72
|
+
def group(side):
|
|
73
|
+
if side in cfg:
|
|
74
|
+
return list(cfg[side])
|
|
75
|
+
pre = tuple(cfg.get(f'{side}_prefixes', ()))
|
|
76
|
+
if side == 'a' and not pre:
|
|
77
|
+
return []
|
|
78
|
+
if not pre or tracks is None:
|
|
79
|
+
raise ValueError(f'contrast {name}: give {side} or {side}_prefixes with known tracks')
|
|
80
|
+
return [t for t in tracks if t.startswith(pre)]
|
|
81
|
+
return cls(name, group('a'), group('b'), cfg.get('label_a', 'A'), cfg.get('label_b', 'B'))
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
@dataclass
|
|
85
|
+
class RegionAttributions:
|
|
86
|
+
"""
|
|
87
|
+
One region as an adapter delivers it.
|
|
88
|
+
|
|
89
|
+
region : unique id, conventionally 'chrom:start-end' of the model input window
|
|
90
|
+
set_name : the region set or class it belongs to
|
|
91
|
+
onehot : (L, 4) input sequence
|
|
92
|
+
hypothetical : track name -> (L, 4) hypothetical attributions (mean over bases subtracted)
|
|
93
|
+
budgets : contrast name -> signed dF(x) - dF(reference), when the adapter knows it
|
|
94
|
+
info : anything else worth carrying into the record (target bin, fold, ...)
|
|
95
|
+
"""
|
|
96
|
+
region: str
|
|
97
|
+
set_name: str
|
|
98
|
+
onehot: np.ndarray
|
|
99
|
+
hypothetical: Dict[str, np.ndarray]
|
|
100
|
+
budgets: Dict[str, float] = field(default_factory=dict)
|
|
101
|
+
info: dict = field(default_factory=dict)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def record_id(set_name: str, contrast: str, region: str, track: str = 'diff') -> str:
|
|
105
|
+
return f'{set_name}||{contrast}||{track}||{region}'
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def check_tracks(tracks: Sequence[str]) -> List[str]:
|
|
109
|
+
"""The track names as a list, in the order given; a ValueError names anything that is not one of TRACKS."""
|
|
110
|
+
tracks = [tracks] if isinstance(tracks, str) else list(tracks)
|
|
111
|
+
bad = [t for t in tracks if t not in TRACKS]
|
|
112
|
+
if bad or not tracks:
|
|
113
|
+
raise ValueError(f'tracks are any of {list(TRACKS)}, not {bad or tracks}')
|
|
114
|
+
return tracks
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def contrast_records(r: RegionAttributions, c: Contrast, budget: str = 'auto',
|
|
118
|
+
tracks: Sequence[str] = TRACKS, min_track_budget_frac: float = 0.0,
|
|
119
|
+
min_track_budget: float = 0.0, min_budget: float = 0.0) -> List[dict]:
|
|
120
|
+
"""
|
|
121
|
+
The seqlet-calling records of one region under one contrast, one per track of `tracks` ('a', 'b',
|
|
122
|
+
'diff'), in that order; [] when a track of the contrast is missing from the region.
|
|
123
|
+
|
|
124
|
+
budget: 'stored' uses r.budgets for 'diff' and skips the region when it has none for the contrast
|
|
125
|
+
(so a rerun covers exactly the regions of the run the budgets came from, on every track);
|
|
126
|
+
'completeness' the sum of each record's own contributions; 'auto' stored when available, else
|
|
127
|
+
completeness. A condition track has no stored budget, so its source is completeness whatever the
|
|
128
|
+
mode; `budget_source` says which was used, record by record.
|
|
129
|
+
|
|
130
|
+
Three gates on the condition budgets (|completeness| of each condition's own track), all off at 0
|
|
131
|
+
(see diffgrammar.calibrate for the values a run derives from its own budgets):
|
|
132
|
+
min_budget leaves the region out ([]) when its stronger condition budget is below it, the guard
|
|
133
|
+
for regions that arrive without a selection; min_track_budget drops the weaker condition record
|
|
134
|
+
when its budget is below it, and min_track_budget_frac when it is below that fraction of the
|
|
135
|
+
stronger one. pct is a share of each record's own budget, so on a track with almost no signal
|
|
136
|
+
the absolute cut is near zero and the seqlets are noise. The stronger condition track, the
|
|
137
|
+
region's own signal, and the 'diff' track are never dropped (whether the region has signal at
|
|
138
|
+
all is decided by the selection or min_budget).
|
|
139
|
+
|
|
140
|
+
Every record carries `attributions` (the (L, 4) hypothetical matrix of its track, the CWM source),
|
|
141
|
+
`contributions` (its (L,) per-position contribution), `onehot`, and `pred` (its budget), with
|
|
142
|
+
`signed_budget`, `budget_source`, `sum_contributions` and `condition_budgets` (the region's two
|
|
143
|
+
condition budgets, {'a': ..., 'b': ...}, whichever tracks are asked for). The 'diff' record also carries
|
|
144
|
+
`polarity`, the contributions of the mean of A and B, which the seqlet step uses to orient
|
|
145
|
+
differential seqlets (seqlets.call_seqlets) and to give each its mot_max_a / mot_max_b; a
|
|
146
|
+
condition record has neither, its sign being simply that of its own contribution.
|
|
147
|
+
"""
|
|
148
|
+
tracks = check_tracks(tracks)
|
|
149
|
+
if any(t not in r.hypothetical for t in c.a + c.b):
|
|
150
|
+
return []
|
|
151
|
+
if budget == 'stored' and c.name not in r.budgets:
|
|
152
|
+
return []
|
|
153
|
+
if budget not in ('stored', 'auto', 'completeness'):
|
|
154
|
+
raise ValueError(f'unknown budget mode {budget!r}')
|
|
155
|
+
if c.single:
|
|
156
|
+
return _single_record(r, c, budget, min_budget)
|
|
157
|
+
mean_a = np.mean([np.asarray(r.hypothetical[t], np.float64) for t in c.a], axis=0)
|
|
158
|
+
mean_b = np.mean([np.asarray(r.hypothetical[t], np.float64) for t in c.b], axis=0)
|
|
159
|
+
hyps = {'a': mean_a, 'b': mean_b, 'diff': mean_b - mean_a}
|
|
160
|
+
contribs = {t: contributions_from_attributions(hyps[t], r.onehot) for t in ('a', 'b')}
|
|
161
|
+
cond = {t: abs(float(contribs[t].sum())) for t in ('a', 'b')}
|
|
162
|
+
if max(cond.values()) < min_budget:
|
|
163
|
+
return []
|
|
164
|
+
strongest = max(cond.values())
|
|
165
|
+
floor = max(min_track_budget, min_track_budget_frac * strongest)
|
|
166
|
+
if floor > 0: # the gate decides the weaker condition track; the stronger one is the region's signal
|
|
167
|
+
tracks = [t for t in tracks if t == 'diff' or cond[t] == strongest or cond[t] >= floor]
|
|
168
|
+
out = []
|
|
169
|
+
for track in tracks:
|
|
170
|
+
hyp = hyps[track]
|
|
171
|
+
contrib = contribs[track] if track in contribs else contributions_from_attributions(hyp, r.onehot)
|
|
172
|
+
completeness = float(contrib.sum())
|
|
173
|
+
if track == 'diff' and budget != 'completeness' and c.name in r.budgets:
|
|
174
|
+
signed, source = float(r.budgets[c.name]), 'stored'
|
|
175
|
+
else:
|
|
176
|
+
signed, source = completeness, 'completeness'
|
|
177
|
+
rec = {
|
|
178
|
+
'record': record_id(r.set_name, c.name, r.region, track),
|
|
179
|
+
'set_name': r.set_name, 'contrast': c.name, 'track': track, 'coord': r.region,
|
|
180
|
+
'attributions': hyp, 'contributions': contrib, 'onehot': r.onehot,
|
|
181
|
+
'pred': abs(signed), 'baseline': 0.0,
|
|
182
|
+
'signed_budget': signed, 'budget_source': source, 'sum_contributions': completeness,
|
|
183
|
+
'condition_budgets': dict(cond),
|
|
184
|
+
**r.info,
|
|
185
|
+
}
|
|
186
|
+
if track == 'diff':
|
|
187
|
+
rec['polarity'] = contributions_from_attributions(0.5 * (mean_a + mean_b), r.onehot)
|
|
188
|
+
out.append(rec)
|
|
189
|
+
return out
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def _single_record(r: RegionAttributions, c: Contrast, budget: str, min_budget: float) -> List[dict]:
|
|
193
|
+
"""The one record of a region under a single contrast: B's own attribution, on track 'b', whatever was asked."""
|
|
194
|
+
mean_b = np.mean([np.asarray(r.hypothetical[t], np.float64) for t in c.b], axis=0)
|
|
195
|
+
contrib = contributions_from_attributions(mean_b, r.onehot)
|
|
196
|
+
completeness = float(contrib.sum())
|
|
197
|
+
if abs(completeness) < min_budget:
|
|
198
|
+
return []
|
|
199
|
+
if budget != 'completeness' and c.name in r.budgets:
|
|
200
|
+
signed, source = float(r.budgets[c.name]), 'stored'
|
|
201
|
+
else:
|
|
202
|
+
signed, source = completeness, 'completeness'
|
|
203
|
+
return [{'record': record_id(r.set_name, c.name, r.region, 'b'), 'set_name': r.set_name, 'contrast': c.name,
|
|
204
|
+
'track': 'b', 'coord': r.region, 'attributions': mean_b, 'contributions': contrib, 'onehot': r.onehot,
|
|
205
|
+
'pred': abs(signed), 'baseline': 0.0, 'signed_budget': signed, 'budget_source': source,
|
|
206
|
+
'sum_contributions': completeness, 'condition_budgets': {'b': abs(completeness)}, **r.info}]
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def contrast_record(r: RegionAttributions, c: Contrast, budget: str = 'auto', track: str = 'diff') -> Optional[dict]:
|
|
210
|
+
"""The record of one region under one contrast on one track (see contrast_records), or None when a track is missing.
|
|
211
|
+
A single contrast has one record, on 'b', whichever track is asked for."""
|
|
212
|
+
recs = contrast_records(r, c, budget, [track])
|
|
213
|
+
return recs[0] if recs else None
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def iter_records(regions: Iterable[RegionAttributions], contrasts: Sequence[Contrast],
|
|
217
|
+
budget: str = 'auto', tracks: Sequence[str] = TRACKS, min_track_budget_frac: float = 0.0,
|
|
218
|
+
min_track_budget: float = 0.0, min_budget: float = 0.0) -> Iterator[dict]:
|
|
219
|
+
"""Every record of every region: per region, per contrast, per track of `tracks` (contrast_records, with its gates)."""
|
|
220
|
+
tracks = check_tracks(tracks)
|
|
221
|
+
for r in regions:
|
|
222
|
+
for c in contrasts:
|
|
223
|
+
yield from contrast_records(r, c, budget, tracks, min_track_budget_frac, min_track_budget, min_budget)
|
diffgrammar/effects.py
ADDED
|
@@ -0,0 +1,317 @@
|
|
|
1
|
+
"""
|
|
2
|
+
One motif's effect against another's, region by region: does the model read them the same way in the same region?
|
|
3
|
+
|
|
4
|
+
y = Motif('HNF4', tfs=['HNF4A', 'HNF4G'])
|
|
5
|
+
x = Motif('FOXA', patterns={'strong': 'GTAAACA', 'weak': 'GTAAATA|GTAAGCA'})
|
|
6
|
+
pair_effects(an, x, y, sets=['K562_high', 'HepG2_high'])
|
|
7
|
+
|
|
8
|
+
Each row is one region of a set with one site of each motif. A motif is either a set of clusters, named by id, subfamily,
|
|
9
|
+
family or best JASPAR match, whose sites are its seqlets; or sequence patterns (IUPAC, alternatives with |), whose sites
|
|
10
|
+
are every match in the input. Patterns also see sites too weak to be called as seqlets, at the price of reading the
|
|
11
|
+
attributions of those regions. By default each region takes the strongest site of each motif at any distance;
|
|
12
|
+
`max_dist` takes instead the pair within that many bp, not overlapping, with the largest |x| + |y|.
|
|
13
|
+
|
|
14
|
+
An effect is the signed contribution at the site's strongest position (mot_max), of the difference (value='diff') or of one
|
|
15
|
+
condition ('a', 'b'). The difference is taken by size, as `seqlets.apply_polarity` orients a seqlet: at a site that
|
|
16
|
+
represses (the mean of A and B sums below zero over it) its sign is flipped, so for seqlets and patterns alike a positive
|
|
17
|
+
effect means |effect| stronger in B and a site repressing in both, more in A, reads negative.
|
|
18
|
+
|
|
19
|
+
Rows name what can colour them: x_variant and y_variant (the cluster, or the pattern's name), set_name, dist, and with
|
|
20
|
+
`add_region_values` the budget of the region (always known) and the measurements of `selection.region_table`.
|
|
21
|
+
"""
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import re
|
|
25
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
26
|
+
from dataclasses import dataclass, field
|
|
27
|
+
from typing import Dict, List, Optional, Sequence
|
|
28
|
+
|
|
29
|
+
import numpy as np
|
|
30
|
+
import pandas as pd
|
|
31
|
+
|
|
32
|
+
from . import selection as SEL
|
|
33
|
+
from .contrast import contrast_record
|
|
34
|
+
from .seqlets import by_size
|
|
35
|
+
|
|
36
|
+
IUPAC = {'A': 'A', 'C': 'C', 'G': 'G', 'T': 'T', 'R': '[AG]', 'Y': '[CT]', 'S': '[CG]', 'W': '[AT]', 'K': '[GT]',
|
|
37
|
+
'M': '[AC]', 'B': '[CGT]', 'D': '[AGT]', 'H': '[ACT]', 'V': '[ACG]', 'N': '[ACGT]'}
|
|
38
|
+
VALUE_COLUMN = {'diff': 'mot_max', 'a': 'mot_max_a', 'b': 'mot_max_b'}
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def pattern_regex(pattern: str) -> 're.Pattern':
|
|
42
|
+
"""An IUPAC pattern, alternatives with |, as a regular expression."""
|
|
43
|
+
return re.compile('|'.join(''.join(IUPAC.get(b, b) for b in alt.strip().upper()) for alt in pattern.split('|')))
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@dataclass
|
|
47
|
+
class Motif:
|
|
48
|
+
"""What one axis reads: clusters by any of their names, or sequence patterns. `colors` maps variant -> colour."""
|
|
49
|
+
label: str
|
|
50
|
+
clusters: Sequence[int] = ()
|
|
51
|
+
subfamilies: Sequence[str] = ()
|
|
52
|
+
families: Sequence[str] = ()
|
|
53
|
+
tfs: Sequence[str] = ()
|
|
54
|
+
patterns: Dict[str, str] = field(default_factory=dict)
|
|
55
|
+
colors: Dict[str, str] = field(default_factory=dict)
|
|
56
|
+
|
|
57
|
+
@classmethod
|
|
58
|
+
def from_config(cls, d: dict) -> 'Motif':
|
|
59
|
+
keys = cls.__dataclass_fields__
|
|
60
|
+
return cls(**{k: v for k, v in d.items() if k in keys})
|
|
61
|
+
|
|
62
|
+
def cluster_ids(self, an) -> List[int]:
|
|
63
|
+
"""The clusters this motif names; a TF is matched on each cluster's best JASPAR match, whatever its case."""
|
|
64
|
+
ids = {int(c) for c in self.clusters}
|
|
65
|
+
fam = an.families
|
|
66
|
+
if self.subfamilies:
|
|
67
|
+
ids |= set(fam.loc[fam['subfamily'].isin(self.subfamilies), 'cluster'].astype(int))
|
|
68
|
+
if self.families:
|
|
69
|
+
ids |= set(fam.loc[fam['group'].isin(self.families), 'cluster'].astype(int))
|
|
70
|
+
if self.tfs:
|
|
71
|
+
want = {t.upper() for t in self.tfs}
|
|
72
|
+
ids |= {c for c, h in an.hits.items() if h and h[0]['tf'].upper() in want}
|
|
73
|
+
return sorted(ids)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def core_sequence(logo: np.ndarray, frac: float = 0.3) -> str:
|
|
77
|
+
"""A contribution logo in letters: the strongest base per position, the flanks below frac of the peak trimmed."""
|
|
78
|
+
m = np.abs(np.asarray(logo, float))
|
|
79
|
+
h = m.max(1)
|
|
80
|
+
keep = np.flatnonzero(h >= frac * (h.max() or 1.0))
|
|
81
|
+
if not len(keep):
|
|
82
|
+
return ''
|
|
83
|
+
return ''.join('ACGT'[i] if h[k] >= frac * h.max() else 'n'
|
|
84
|
+
for k, i in zip(range(keep[0], keep[-1] + 1), m[keep[0]:keep[-1] + 1].argmax(1)))
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _variant_names(an) -> Dict[int, str]:
|
|
88
|
+
"""cluster -> 'cl60 NFIX TTGGC': clusters of one family often share a best match, so the core tells them apart."""
|
|
89
|
+
hits, logos, out = an.hits, an.logos, {}
|
|
90
|
+
for c in an.clusters['cluster'].astype(int):
|
|
91
|
+
tf = hits[int(c)][0]['tf'] if hits.get(int(c)) else ''
|
|
92
|
+
core = core_sequence(logos[int(c)]) if int(c) in logos else ''
|
|
93
|
+
out[int(c)] = ' '.join(x for x in (f'cl{c}', tf, core) if x)
|
|
94
|
+
return out
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _seqlet_sites(an, motif: Motif, meta: pd.DataFrame, column: str) -> Dict[tuple, list]:
|
|
98
|
+
"""(set_name, coord) -> sites (effect, start, end, variant, sequence) from the seqlets of the motif's clusters."""
|
|
99
|
+
names = _variant_names(an)
|
|
100
|
+
sub = meta[meta['cluster'].isin(motif.cluster_ids(an))]
|
|
101
|
+
sub = sub[sub[column].notna()] # a site equal in both conditions has no differential effect
|
|
102
|
+
sites: Dict[tuple, list] = {}
|
|
103
|
+
seqs = sub['seq'] if 'seq' in sub else [''] * len(sub)
|
|
104
|
+
for s, c, e, st, en, cl, q in zip(sub['set_name'], sub['coord'], sub[column], sub['start'], sub['end'], sub['cluster'], seqs):
|
|
105
|
+
sites.setdefault((s, c), []).append((float(e), int(st), int(en), names.get(int(cl), f'cl{cl}'), q))
|
|
106
|
+
return sites
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _read_track(an, key: tuple, value: str):
|
|
110
|
+
"""
|
|
111
|
+
(contributions of the difference or of one condition, sequence as a string, the mean of A and B) of a region of a
|
|
112
|
+
set; None if absent.
|
|
113
|
+
"""
|
|
114
|
+
from .sequence import decode
|
|
115
|
+
src, (set_name, coord) = an.source, key
|
|
116
|
+
paths = src.paths_for(coord) if hasattr(src, 'paths_for') else []
|
|
117
|
+
regions = (src.region(p) for p in paths) if paths else (r for r in src.regions() if r.region == coord)
|
|
118
|
+
for r in regions:
|
|
119
|
+
if r is None or r.set_name != set_name or r.region != coord:
|
|
120
|
+
continue
|
|
121
|
+
rec = contrast_record(r, an.contrast, an.cfg['seqlets']['budget'])
|
|
122
|
+
if rec is None:
|
|
123
|
+
continue
|
|
124
|
+
c, mid = rec['contributions'], rec.get('polarity')
|
|
125
|
+
if mid is None: # a single-track run: the track's own contributions
|
|
126
|
+
return np.asarray(c), decode(rec['onehot']), None
|
|
127
|
+
track = {'diff': c, 'a': mid - c / 2, 'b': mid + c / 2}[value]
|
|
128
|
+
return np.asarray(track), decode(rec['onehot']), np.asarray(mid)
|
|
129
|
+
return None
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _pattern_sites(an, motif: Motif, keys: Sequence[tuple], value: str, workers: int = 8):
|
|
133
|
+
"""Every match of the motif's patterns in the regions `keys`, in pattern order; also the keys without attributions."""
|
|
134
|
+
res = {name: pattern_regex(p) for name, p in motif.patterns.items()}
|
|
135
|
+
|
|
136
|
+
def one(key):
|
|
137
|
+
got = _read_track(an, key, value)
|
|
138
|
+
if got is None:
|
|
139
|
+
return key, None
|
|
140
|
+
track, seq, mid = got
|
|
141
|
+
out = []
|
|
142
|
+
for name, rx in res.items():
|
|
143
|
+
for m in rx.finditer(seq):
|
|
144
|
+
span = track[m.start():m.end()]
|
|
145
|
+
if len(span):
|
|
146
|
+
e = float(span[int(np.argmax(np.abs(span)))])
|
|
147
|
+
if value == 'diff' and mid is not None: # by size, as a seqlet's mot_max
|
|
148
|
+
e = float(by_size(e, mid[m.start():m.end()].sum()))
|
|
149
|
+
out.append((e, m.start(), m.end(), name, m.group()))
|
|
150
|
+
return key, out
|
|
151
|
+
sites, missing = {}, []
|
|
152
|
+
with ThreadPoolExecutor(workers) as pool:
|
|
153
|
+
for key, got in pool.map(one, keys):
|
|
154
|
+
if got is None:
|
|
155
|
+
missing.append(key)
|
|
156
|
+
else:
|
|
157
|
+
sites[key] = got
|
|
158
|
+
return sites, missing
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _best_pair(xs: list, ys: list, max_dist: Optional[float]):
|
|
162
|
+
if max_dist is None:
|
|
163
|
+
y = max(ys, key=lambda s: abs(s[0]))
|
|
164
|
+
rest = [s for s in xs if (s[1], s[2]) != (y[1], y[2])] # one seqlet cannot be both sites
|
|
165
|
+
return (max(rest, key=lambda s: abs(s[0])), y) if rest else None
|
|
166
|
+
best, score = None, -1.0
|
|
167
|
+
for x in xs:
|
|
168
|
+
for y in ys:
|
|
169
|
+
if abs((x[1] + x[2]) - (y[1] + y[2])) / 2 <= max_dist and (x[2] <= y[1] or x[1] >= y[2]):
|
|
170
|
+
if abs(x[0]) + abs(y[0]) > score:
|
|
171
|
+
best, score = (x, y), abs(x[0]) + abs(y[0])
|
|
172
|
+
return best
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def pair_effects(an, x: Motif, y: Motif, sets: Optional[Sequence[str]] = None, max_dist: Optional[float] = None,
|
|
176
|
+
value: str = 'diff') -> pd.DataFrame:
|
|
177
|
+
"""
|
|
178
|
+
One row per region of `sets` with a site of both motifs: set_name, coord, x, y (the effects), x_variant, y_variant,
|
|
179
|
+
x_seq, y_seq, x_start, x_end, y_start, y_end and dist (between site centres). attrs['missing'] counts the regions
|
|
180
|
+
a pattern could not read because their attributions are not there (an export keeps only a sample).
|
|
181
|
+
"""
|
|
182
|
+
if value not in VALUE_COLUMN:
|
|
183
|
+
raise ValueError(f"value must be one of {list(VALUE_COLUMN)}, got {value!r}")
|
|
184
|
+
meta = an.seqlets.meta
|
|
185
|
+
meta = meta[(meta['contrast'] == an.contrast.name) & meta['set_name'].isin(list(sets) if sets else an.sets)]
|
|
186
|
+
column = VALUE_COLUMN[value]
|
|
187
|
+
if column not in meta:
|
|
188
|
+
raise ValueError(f'these seqlets have no {column}; rerun `seqlets`')
|
|
189
|
+
seqlet_sites = {m.label: _seqlet_sites(an, m, meta, column) for m in (x, y) if not m.patterns}
|
|
190
|
+
if x.patterns and y.patterns:
|
|
191
|
+
keys = sorted(set(zip(meta['set_name'], meta['coord'])))
|
|
192
|
+
elif x.patterns or y.patterns:
|
|
193
|
+
keys = sorted(seqlet_sites[y.label if x.patterns else x.label])
|
|
194
|
+
else:
|
|
195
|
+
keys = sorted(set(seqlet_sites[x.label]) & set(seqlet_sites[y.label]))
|
|
196
|
+
missing = []
|
|
197
|
+
|
|
198
|
+
def sites_of(m: Motif) -> dict:
|
|
199
|
+
if not m.patterns:
|
|
200
|
+
return seqlet_sites[m.label]
|
|
201
|
+
got, miss = _pattern_sites(an, m, keys, value)
|
|
202
|
+
missing.extend(miss)
|
|
203
|
+
return got
|
|
204
|
+
sx, sy = sites_of(x), sites_of(y)
|
|
205
|
+
rows = []
|
|
206
|
+
for key in keys:
|
|
207
|
+
xs, ys = sx.get(key), sy.get(key)
|
|
208
|
+
if not xs or not ys:
|
|
209
|
+
continue
|
|
210
|
+
pair = _best_pair(xs, ys, max_dist)
|
|
211
|
+
if pair is None:
|
|
212
|
+
continue
|
|
213
|
+
a, b = pair
|
|
214
|
+
rows.append({'set_name': key[0], 'coord': key[1], 'x': a[0], 'y': b[0], 'x_variant': a[3], 'y_variant': b[3],
|
|
215
|
+
'x_seq': a[4], 'y_seq': b[4], 'x_start': a[1], 'x_end': a[2], 'y_start': b[1], 'y_end': b[2],
|
|
216
|
+
'dist': abs((a[1] + a[2]) - (b[1] + b[2])) / 2})
|
|
217
|
+
out = pd.DataFrame(rows, columns=['set_name', 'coord', 'x', 'y', 'x_variant', 'y_variant', 'x_seq', 'y_seq', 'x_start',
|
|
218
|
+
'x_end', 'y_start', 'y_end', 'dist'])
|
|
219
|
+
out.attrs['missing'] = len(set(missing))
|
|
220
|
+
return out
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def add_region_values(table: pd.DataFrame, an) -> pd.DataFrame:
|
|
224
|
+
"""The table with what a region can be coloured by: x + y, its budget, and the values of `selection.region_values`."""
|
|
225
|
+
thr = an.thresholds
|
|
226
|
+
thr = thr[thr['contrast'] == an.contrast.name].drop_duplicates(['set_name', 'coord'])
|
|
227
|
+
out = table.assign(sum=table['x'] + table['y']).merge(
|
|
228
|
+
thr[['set_name', 'coord', 'signed_budget']].rename(columns={'signed_budget': 'budget'}), on=['set_name', 'coord'], how='left')
|
|
229
|
+
from . import expression as X
|
|
230
|
+
out = out.merge(X.region_lfc(an), on='coord', how='left')
|
|
231
|
+
return out.merge(SEL.region_values(an.region_table, an.contrast.name), on=['set_name', 'coord'], how='left')
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def value_label(an, column: str) -> str:
|
|
235
|
+
"""A colour column in words: 'meas_diff|Assay1' -> 'Measured B − A, Assay1'; units from [report] value_units."""
|
|
236
|
+
la, lb = an.label_a, an.label_b
|
|
237
|
+
base, _, contrast = column.partition('|')
|
|
238
|
+
names = {'meas_a': f'Measured {la}', 'meas_b': f'Measured {lb}', 'meas_diff': f'Measured {lb} − {la}',
|
|
239
|
+
'pred_a': f'Predicted {la}', 'pred_b': f'Predicted {lb}', 'pred_diff': f'Predicted {lb} − {la}',
|
|
240
|
+
'log2fc': f'log2 fold change, {lb} / {la}',
|
|
241
|
+
'budget': f'Predicted {lb} (seqlet budget)' if an.single else f'Predicted {lb} − {la} (seqlet budget)',
|
|
242
|
+
'sum': 'Sum of both effects', 'dist': 'Distance between the sites (bp)', 'set_name': 'Region set',
|
|
243
|
+
'gene_lfc': f'log2FC of the assigned genes ({lb} / {la})'}
|
|
244
|
+
text = names.get(base, base)
|
|
245
|
+
if contrast and len(an.cfg.get('contrasts', {})) > 1:
|
|
246
|
+
text += f', {contrast}'
|
|
247
|
+
unit = an.cfg.get('report', {}).get('value_units', {}).get(base)
|
|
248
|
+
return f'{text} ({unit})' if unit else text
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def color_options(an, table: pd.DataFrame, x: Motif, y: Motif) -> Dict[str, str]:
|
|
252
|
+
"""column -> label of everything `table` (after add_region_values) can be coloured by, categories first."""
|
|
253
|
+
out = {'x_variant': f'{x.label} variant', 'y_variant': f'{y.label} variant', 'set_name': 'Region set'}
|
|
254
|
+
for c in table.columns:
|
|
255
|
+
if c in ('sum', 'dist', 'budget', 'gene_lfc') or '|' in c:
|
|
256
|
+
if table[c].notna().any():
|
|
257
|
+
out[c] = value_label(an, c)
|
|
258
|
+
return out
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def scatter_args(an, table: pd.DataFrame, x: Motif, y: Motif, color_by: Sequence[str], sets=None, value: str = 'diff') -> tuple:
|
|
262
|
+
"""The arguments of plotting.plot_effect_scatter: table, panels, rows (column, label, colours), axis labels, line."""
|
|
263
|
+
la, lb = an.label_a, an.label_b
|
|
264
|
+
what = {'diff': lb if an.single else f'{lb} − {la}', 'a': la, 'b': lb}[value]
|
|
265
|
+
fixed = {'x_variant': x.colors, 'y_variant': y.colors, 'set_name': an.set_colors}
|
|
266
|
+
labels = {'x_variant': f'{x.label} variant', 'y_variant': f'{y.label} variant'}
|
|
267
|
+
rows = [(c, labels.get(c) or value_label(an, c), fixed.get(c) or {}) for c in color_by if c in table]
|
|
268
|
+
panels = [s for s in (sets or an.sets) if s in set(table['set_name'])]
|
|
269
|
+
return (table, panels, rows, f'{x.label} effect ({what})', f'{y.label} effect ({what})', an.set_labels,
|
|
270
|
+
'sum' if value == 'diff' else 'equal')
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def configured_pairs(cfg: dict) -> Dict[str, dict]:
|
|
274
|
+
"""name -> entry of [[report.effect_pairs]]: label x and y, optional contrast, sets, max_dist, value, color_by."""
|
|
275
|
+
return {p['name']: p for p in cfg.get('report', {}).get('effect_pairs', [])}
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def _safe(name: str) -> str:
|
|
279
|
+
return re.sub(r'[^A-Za-z0-9._-]+', '_', name)
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def pair_table_path(an, name: str):
|
|
283
|
+
return an.out / 'report' / f'effects_{_safe(name)}.csv'
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def stored_pair(an, name: str) -> tuple:
|
|
287
|
+
"""(table, x, y, sets, value) of a configured pair: the report step's table when it wrote one, else computed and kept."""
|
|
288
|
+
p = configured_pairs(an.cfg)[name]
|
|
289
|
+
x, y = Motif.from_config(p['x']), Motif.from_config(p['y'])
|
|
290
|
+
|
|
291
|
+
def load():
|
|
292
|
+
f = pair_table_path(an, name)
|
|
293
|
+
if f.exists():
|
|
294
|
+
return pd.read_csv(f)
|
|
295
|
+
return an.pair_effects(x, y, p.get('sets'), p.get('max_dist'), p.get('value', 'diff'))
|
|
296
|
+
return an._get(f'effects/{name}', load), x, y, p.get('sets'), p.get('value', 'diff')
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
def write_pairs(an_for, out_dir, log=print) -> None:
|
|
300
|
+
"""
|
|
301
|
+
The report step's part: for each configured pair its table (report/effects_<name>.csv) and figure, one row per entry
|
|
302
|
+
of color_by. an_for(contrast) gives the Analysis of a contrast; a pair without `contrast` uses the first.
|
|
303
|
+
"""
|
|
304
|
+
from . import plotting as P
|
|
305
|
+
import matplotlib.pyplot as plt
|
|
306
|
+
pairs = configured_pairs(an_for(None).cfg)
|
|
307
|
+
for name, p in pairs.items():
|
|
308
|
+
an = an_for(p.get('contrast'))
|
|
309
|
+
x, y = Motif.from_config(p['x']), Motif.from_config(p['y'])
|
|
310
|
+
t = an.pair_effects(x, y, p.get('sets'), p.get('max_dist'), p.get('value', 'diff'))
|
|
311
|
+
t.to_csv(pair_table_path(an, name), index=False, float_format='%.6g')
|
|
312
|
+
color_by = [c for c in p.get('color_by', ['x_variant']) if c in t]
|
|
313
|
+
fig = P.plot_effect_scatter(*scatter_args(an, t, x, y, color_by, p.get('sets'), p.get('value', 'diff')))
|
|
314
|
+
for ext in ('pdf', 'png'):
|
|
315
|
+
fig.savefig(pair_table_path(an, name).with_suffix(f'.{ext}'), bbox_inches='tight')
|
|
316
|
+
plt.close(fig)
|
|
317
|
+
log(f'[report] effects {name}: {len(t)} regions')
|