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.
Files changed (47) hide show
  1. diffgrammar/__init__.py +6 -0
  2. diffgrammar/adapters/__init__.py +21 -0
  3. diffgrammar/adapters/peak_npz.py +114 -0
  4. diffgrammar/align.py +195 -0
  5. diffgrammar/analysis.py +744 -0
  6. diffgrammar/attribute.py +445 -0
  7. diffgrammar/calibrate.py +279 -0
  8. diffgrammar/cli.py +659 -0
  9. diffgrammar/cluster.py +439 -0
  10. diffgrammar/config.py +213 -0
  11. diffgrammar/contrast.py +223 -0
  12. diffgrammar/effects.py +317 -0
  13. diffgrammar/export.py +185 -0
  14. diffgrammar/expression.py +399 -0
  15. diffgrammar/jaspar.py +185 -0
  16. diffgrammar/marginalize/__init__.py +4 -0
  17. diffgrammar/marginalize/backgrounds.py +107 -0
  18. diffgrammar/marginalize/cooperativity.py +344 -0
  19. diffgrammar/marginalize/design.py +209 -0
  20. diffgrammar/marginalize/plots.py +546 -0
  21. diffgrammar/marginalize/predictor.py +109 -0
  22. diffgrammar/marginalize/readout.py +86 -0
  23. diffgrammar/marginalize/run.py +223 -0
  24. diffgrammar/marginalize/store.py +191 -0
  25. diffgrammar/pair_regression.py +323 -0
  26. diffgrammar/plotting.py +1186 -0
  27. diffgrammar/scan.py +151 -0
  28. diffgrammar/selection.py +174 -0
  29. diffgrammar/seqlets.py +376 -0
  30. diffgrammar/sequence.py +22 -0
  31. diffgrammar/summaries.py +140 -0
  32. diffgrammar/toy.py +129 -0
  33. diffgrammar/view/__init__.py +0 -0
  34. diffgrammar/view/app.py +1942 -0
  35. diffgrammar/view/data.py +1950 -0
  36. diffgrammar/view/figures.py +400 -0
  37. diffgrammar/view/network/index.html +232 -0
  38. diffgrammar/view/network.py +21 -0
  39. diffgrammar/view/pages.py +257 -0
  40. diffgrammar/view/tracks/index.html +459 -0
  41. diffgrammar/view/tracks.py +153 -0
  42. diffgrammar-0.1.0.dist-info/METADATA +204 -0
  43. diffgrammar-0.1.0.dist-info/RECORD +47 -0
  44. diffgrammar-0.1.0.dist-info/WHEEL +5 -0
  45. diffgrammar-0.1.0.dist-info/entry_points.txt +2 -0
  46. diffgrammar-0.1.0.dist-info/licenses/LICENSE +57 -0
  47. diffgrammar-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,546 @@
1
+ """
2
+ Figures of the marginalization store: lines, heatmaps and offset matrices of the five quantities every
3
+ reader returns, for a set of rows (partners, constructs, pairs) against one anchor.
4
+
5
+ pair both motifs inserted
6
+ first the anchor alone, at the position it has in the pair
7
+ second the partner alone, at the position it has in the pair
8
+ additive first + second - baseline, the expectation if the motifs act independently
9
+ cooperativity pair - additive; 0 is additive, above 0 super-additive
10
+
11
+ Arrays are (grid..., n_background, column): the store readers' track axis reduced to condition columns
12
+ (`readout.by_condition`: A and B of each contrast, or B - A), so a figure reads the same in every project.
13
+ `columns` is the list of (contrast, label) by_condition returns; panels of one contrast share a y scale.
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import re
18
+ import warnings
19
+ from typing import Dict, List, Optional, Sequence, Tuple
20
+
21
+ import numpy as np
22
+
23
+ PAIR_C, FIRST_C, SECOND_C, COOP_C = '#222222', '#8c564b', '#6a3d9a', '#2166ac'
24
+ PART_COLORS = ['#555555', '#1F6FB2', '#6A3D9A', '#9E1B32', '#2D6A4F', '#D35400']
25
+ QUANT = [('pair', 'Both motifs'), ('first', 'Anchor alone'), ('second', 'Partner alone'),
26
+ ('additive', 'Additive expectation'), ('cooperativity', 'Cooperativity')]
27
+ ABS_LINES = [('pair', 'Both motifs', PAIR_C, '-', 0.6), ('additive', 'Additive expectation', PAIR_C, '--', 0.55),
28
+ ('first', 'Anchor alone', FIRST_C, '-', 0.5), ('second', 'Partner alone', None, '-', 0.5),
29
+ ('baseline', 'Baseline', '#9a9a9a', ':', 0.5)]
30
+
31
+
32
+ def _mean_sem(v):
33
+ """Mean and SEM over backgrounds (the last axis) of a (..., n_bg) array; NaN where a grid point never fits."""
34
+ n = np.isfinite(v).sum(-1).clip(1)
35
+ with np.errstate(invalid='ignore', divide='ignore'), warnings.catch_warnings():
36
+ warnings.simplefilter('ignore', RuntimeWarning)
37
+ return np.nanmean(v, axis=-1), np.nanstd(v, axis=-1) / np.sqrt(n)
38
+
39
+
40
+ def _blocks(columns) -> Dict[str, List[int]]:
41
+ out: Dict[str, List[int]] = {}
42
+ for i, (block, _) in enumerate(columns):
43
+ out.setdefault(block, []).append(i)
44
+ return out
45
+
46
+
47
+ def _is_diff(label: str) -> bool:
48
+ return ' − ' in label
49
+
50
+
51
+ def shared_ylims(terms: Sequence[dict], keys: Sequence[str], columns, sem: bool = False, pad: float = 0.04):
52
+ """
53
+ y limits per contrast over every terms dict: the mean over backgrounds of each quantity in `keys` in
54
+ every column of that contrast, widened by the SEM when sem=True. Pass them to the row figures so
55
+ several figures share one scale.
56
+ """
57
+ out = {}
58
+ for block, idx in _blocks(columns).items():
59
+ ext = []
60
+ for tm in terms:
61
+ for k in keys:
62
+ for i in idx:
63
+ m, s = _mean_sem(np.asarray(tm[k])[..., i])
64
+ s = s if sem else 0
65
+ ext += [np.nanmin(m - s), np.nanmax(m + s)]
66
+ lo, hi = min(ext), max(ext)
67
+ out[block] = (lo - pad * (hi - lo), hi + pad * (hi - lo))
68
+ return out
69
+
70
+
71
+ # -- drawings of what was inserted ---------------------------------------------------------------
72
+ def plot_sequence_logo(ax, seq: str, max_len: Optional[int] = None) -> None:
73
+ """An inserted sequence as a logo, degenerate positions marked, padded to max_len so rows share a scale."""
74
+ from ..plotting import plot_cwm
75
+ from ..sequence import one_hot
76
+ plot_cwm(one_hot(seq), ax)
77
+ for j, b in enumerate(seq):
78
+ if b not in 'ACGT':
79
+ ax.text(j, 0.02, b, ha='center', va='bottom', fontsize=7.5, fontweight='bold', color='#9a9a9a')
80
+ pad = ((max_len or len(seq)) - len(seq)) / 2
81
+ ax.set_xlim(-0.5 - pad, len(seq) - 0.5 + pad)
82
+
83
+
84
+ def plot_construct(ax, parts: Sequence[Tuple[str, str]], gap_w: float = 14.0, span: Optional[tuple] = None,
85
+ colors: Optional[Dict[str, str]] = None, fixed: Sequence[str] = (), box_h: float = 0.42,
86
+ fs: float = 4.5, gap_labels: Optional[Sequence[str]] = None) -> float:
87
+ """
88
+ The inserted motifs on a DNA line, left to right: each a box per run of defined bases with its name
89
+ above, N runs as labelled spacers, and a double arrow for each gap that the experiment varies, labelled
90
+ d by default or by `gap_labels` (X and Y when the two gaps of a 2D scan move independently). A part named
91
+ in `fixed` (a triplet's center) gets a dotted line through it. Returns the drawn length, so several rows
92
+ can share one `span`.
93
+ """
94
+ from matplotlib.colors import to_rgba
95
+ from matplotlib.patches import Rectangle
96
+ ax.set_axis_off()
97
+ x = 0.0
98
+ for k, (name, seq) in enumerate(parts):
99
+ col = (colors or {}).get(name, PART_COLORS[k % len(PART_COLORS)])
100
+ for m in re.finditer('[^N]+', seq):
101
+ ax.add_patch(Rectangle((x + m.start(), -box_h / 2), m.end() - m.start(), box_h,
102
+ facecolor=to_rgba(col, 0.25), edgecolor=col, linewidth=0.5, zorder=2))
103
+ for m in re.finditer('N+', seq):
104
+ ax.text(x + (m.start() + m.end()) / 2, -box_h / 2 - 0.16, f'{m.end() - m.start()} bp', ha='center',
105
+ va='top', fontsize=fs * 0.9, color='#8a8a8a')
106
+ ax.text(x + len(seq) / 2, box_h / 2 + 0.2, name, ha='center', va='bottom', fontsize=fs, color=col)
107
+ if name in fixed:
108
+ ax.plot([x + len(seq) / 2] * 2, [-box_h * 1.6, box_h * 1.6], color='#aaaaaa', linewidth=0.5,
109
+ linestyle=(0, (1.5, 1.5)), zorder=1)
110
+ x += len(seq)
111
+ if k < len(parts) - 1:
112
+ ax.annotate('', (x, -1.0), (x + gap_w, -1.0), annotation_clip=False,
113
+ arrowprops=dict(arrowstyle='<->', color='#333333', linewidth=0.6, shrinkA=0, shrinkB=0,
114
+ mutation_scale=4))
115
+ ax.text(x + gap_w / 2, -1.18, (gap_labels or ['d'] * len(parts))[k], ha='center', va='top', fontsize=fs,
116
+ color='#333333')
117
+ x += gap_w
118
+ pad = max(1.0, 0.06 * x)
119
+ x0, x1 = span if span is not None else (-pad, x + pad)
120
+ ax.plot([x0, x1], [0, 0], color='#444444', linewidth=0.7, zorder=1)
121
+ ax.set_xlim(x0, x1)
122
+ ax.set_ylim(-2.0, 1.5)
123
+ return x
124
+
125
+
126
+ def _draw(ax, drawing, max_len, span, colors, fixed, independent=False):
127
+ if drawing is None:
128
+ return
129
+ if isinstance(drawing, str):
130
+ plot_sequence_logo(ax.inset_axes([0, 0.15, 1, 0.70]), drawing, max_len)
131
+ else:
132
+ labels = (['X + Y'] if len(drawing) == 2 else ['X', 'Y']) if independent else None
133
+ plot_construct(ax.inset_axes([0, 0.14, 1, 0.70]), drawing, span=span, colors=colors, fixed=fixed,
134
+ gap_labels=labels)
135
+
136
+
137
+ def _construct_len(drawing, gap_w=14.0):
138
+ return sum(len(s) for _, s in drawing) + gap_w * (len(drawing) - 1)
139
+
140
+
141
+ def _part_colors(builds, given=None):
142
+ """One colour per motif name across every drawn construct, so a motif keeps its colour from row to row."""
143
+ names = dict.fromkeys(n for b in builds for n, _ in b)
144
+ return {**{n: PART_COLORS[k % len(PART_COLORS)] for k, n in enumerate(names)}, **(given or {})}
145
+
146
+
147
+ # -- one figure per anchor: rows of partners or constructs ---------------------------------------
148
+ def plot_terms_lines(rows, x, columns, title: str = '', first_label: str = 'Anchor alone',
149
+ second_label: str = 'Partner alone', pair_label: str = 'Both motifs',
150
+ xlabel: str = 'Spacing (bp)', ylims=None, colors: Optional[Dict[str, str]] = None,
151
+ row_height: float = 0.85, width: float = 7.2):
152
+ """
153
+ One row per (label, terms). For each column in `columns` ([(label, column index)]): the predicted signal
154
+ (both motifs, each alone, additive expectation), then the cooperativity with its SEM over backgrounds,
155
+ so panels on one scale sit side by side. `ylims` is ((low, high) predicted, (low, high) cooperativity),
156
+ shared by every panel of its kind; by default the limits of this figure. `colors` maps a row label to the
157
+ colour of its cooperativity line.
158
+ """
159
+ import matplotlib.pyplot as plt
160
+ n, nt = len(rows), len(columns)
161
+ height = row_height * n + 0.9
162
+ fig = plt.figure(figsize=(width, height))
163
+ gs = fig.add_gridspec(n, 2 * nt + 1, width_ratios=[1] * nt + [0.28] + [1] * nt, top=1 - 0.45 / height,
164
+ bottom=0.6 / height, left=0.12, right=0.99, hspace=0.25, wspace=0.12)
165
+ cols = list(range(nt)) + list(range(nt + 1, 2 * nt + 1))
166
+ axes = np.empty((n, 2 * nt), dtype=object)
167
+ for ri in range(n):
168
+ for ci, gc in enumerate(cols):
169
+ axes[ri, ci] = fig.add_subplot(gs[ri, gc], sharex=axes[0, 0] if (ri, ci) != (0, 0) else None)
170
+ if ylims is None:
171
+ pred, coop = [], []
172
+ for _, tm in rows:
173
+ for _, ti in columns:
174
+ pred += [_mean_sem(tm[k][..., ti])[0] for k in ('pair', 'first', 'second', 'additive')]
175
+ m, s = _mean_sem(tm['cooperativity'][..., ti])
176
+ coop += [m - s, m + s]
177
+ ylims = []
178
+ for vals in (pred, coop):
179
+ lo, hi = np.nanmin([np.nanmin(v) for v in vals]), np.nanmax([np.nanmax(v) for v in vals])
180
+ ylims.append((lo - 0.04 * (hi - lo), hi + 0.04 * (hi - lo)))
181
+ for ri, (label, tm) in enumerate(rows):
182
+ for ci, (tlab, ti) in enumerate(columns):
183
+ ax = axes[ri, ci]
184
+ ax.plot(x, _mean_sem(tm['pair'][..., ti])[0], color=PAIR_C, linewidth=0.6, label=pair_label)
185
+ ax.plot(x, _mean_sem(tm['additive'][..., ti])[0], color=PAIR_C, linewidth=0.55, linestyle='--',
186
+ label='Additive expectation')
187
+ ax.plot(x, _mean_sem(tm['first'][..., ti])[0], color=FIRST_C, linewidth=0.5, label=first_label)
188
+ ax.plot(x, _mean_sem(tm['second'][..., ti])[0], color=SECOND_C, linewidth=0.5, label=second_label)
189
+ ax.set_ylim(*ylims[0])
190
+ ax = axes[ri, nt + ci]
191
+ col = (colors or {}).get(label, COOP_C)
192
+ m, s = _mean_sem(tm['cooperativity'][..., ti])
193
+ ax.fill_between(x, m - s, m + s, color=col, alpha=0.25, linewidth=0)
194
+ ax.plot(x, m, color=col, linewidth=0.6)
195
+ ax.axhline(0, color='black', linewidth=0.4, linestyle=':')
196
+ ax.set_ylim(*ylims[1])
197
+ if ri == 0:
198
+ axes[0, ci].set_title(f'{tlab}: predicted', fontsize=6.5)
199
+ axes[0, nt + ci].set_title(f'{tlab}: cooperativity', fontsize=6.5)
200
+ axes[ri, 0].set_ylabel(label, fontsize=5.5, rotation=0, ha='right', va='center')
201
+ for ri in range(n):
202
+ for ci in range(2 * nt):
203
+ if ci % nt:
204
+ axes[ri, ci].tick_params(labelleft=False)
205
+ for ax in axes.ravel():
206
+ ax.tick_params(labelsize=5, length=1.5, pad=1)
207
+ for ri in range(n - 1):
208
+ for ax in axes[ri]:
209
+ ax.tick_params(labelbottom=False)
210
+ for ci in range(axes.shape[1]):
211
+ axes[-1, ci].set_xlabel(xlabel, fontsize=6)
212
+ h, l = axes[0, 0].get_legend_handles_labels()
213
+ fig.legend(h, l, loc='lower center', ncol=4, frameon=False, fontsize=5.5, bbox_to_anchor=(0.5, 0.0))
214
+ if title:
215
+ fig.suptitle(title, fontsize=7.5, y=1 - 0.12 / height)
216
+ return fig
217
+
218
+
219
+ def plot_terms_heatmap(rows, x, column: int, title: str = '', labels_q: Optional[dict] = None,
220
+ xlabel: str = 'Spacing (bp)', row_height: float = 0.17, width: float = 7.2):
221
+ """
222
+ The five quantities as heatmaps, rows down and spacing across, for one column. The four absolute
223
+ quantities share one colour scale and the cooperativity has its own, centred on 0.
224
+ """
225
+ import matplotlib.pyplot as plt
226
+ labels = [r[0] for r in rows]
227
+ qnames = dict(QUANT, **(labels_q or {}))
228
+ grids = {k: np.array([_mean_sem(tm[k][..., column])[0] for _, tm in rows]) for k, _ in QUANT}
229
+ absolute = np.concatenate([grids[k][np.isfinite(grids[k])] for k in ('pair', 'first', 'second', 'additive')])
230
+ lo, hi = np.percentile(absolute, [1, 99])
231
+ cmax = np.nanpercentile(np.abs(grids['cooperativity']), 99)
232
+ fig, axes = plt.subplots(1, len(QUANT), figsize=(width, row_height * len(rows) + 1.3), sharey=True,
233
+ constrained_layout=True)
234
+ ext = [x[0], x[-1], len(rows), 0]
235
+ ims = {}
236
+ for ax, (k, lab) in zip(axes, QUANT):
237
+ coop = k == 'cooperativity'
238
+ ims[k] = ax.imshow(grids[k], aspect='auto', extent=ext, interpolation='nearest',
239
+ cmap='RdBu_r' if coop else 'viridis', vmin=-cmax if coop else lo, vmax=cmax if coop else hi)
240
+ ax.set_title(qnames[k], fontsize=6)
241
+ ax.set_xlabel(xlabel, fontsize=5.5)
242
+ ax.tick_params(labelsize=5, length=1.5, pad=1)
243
+ axes[0].set_yticks(np.arange(len(rows)) + 0.5)
244
+ axes[0].set_yticklabels(labels, fontsize=5)
245
+ cb = fig.colorbar(ims['pair'], ax=list(axes[:4]), location='bottom', shrink=0.5, pad=0.03, aspect=30)
246
+ cb.ax.tick_params(labelsize=4.5)
247
+ cb.set_label('Predicted signal', fontsize=5)
248
+ cb2 = fig.colorbar(ims['cooperativity'], ax=axes[4], location='bottom', pad=0.03, aspect=12)
249
+ cb2.ax.tick_params(labelsize=4.5)
250
+ cb2.set_label('Cooperativity', fontsize=5)
251
+ if title:
252
+ fig.suptitle(title, fontsize=7.5)
253
+ return fig
254
+
255
+
256
+ def plot_terms_matrix(rows, offsets, column: int, title: str = '', labels_q: Optional[dict] = None,
257
+ xlabel: str = 'Partner offset (bp)', ylabel: str = 'Anchor offset (bp)', width: float = 7.2,
258
+ cell: float = 1.15):
259
+ """
260
+ 2D offset scans: one row per (label, terms), the five quantities across, each a heatmap of the anchor
261
+ offset (y) against the partner offset (x), mean over backgrounds, unsmoothed, for one column. The four
262
+ absolute quantities share one colour scale and the cooperativity has its own, centred on 0.
263
+ """
264
+ import matplotlib.pyplot as plt
265
+ qnames = dict(QUANT, **(labels_q or {}))
266
+ grids = {k: [_mean_sem(tm[k][..., column])[0] for _, tm in rows] for k, _ in QUANT}
267
+ absolute = np.concatenate([g.ravel() for k in ('pair', 'first', 'second', 'additive') for g in grids[k]])
268
+ lo, hi = np.nanpercentile(absolute, [1, 99])
269
+ cmax = np.nanpercentile(np.abs(np.concatenate([g.ravel() for g in grids['cooperativity']])), 99)
270
+ fig, axes = plt.subplots(len(rows), len(QUANT), figsize=(width, cell * len(rows) + 1.2), squeeze=False,
271
+ constrained_layout=True)
272
+ step = offsets[1] - offsets[0]
273
+ ext = [offsets[0] - step / 2, offsets[-1] + step / 2, offsets[0] - step / 2, offsets[-1] + step / 2]
274
+ ticks = [int(offsets[0]), int(offsets[len(offsets) // 2]), int(offsets[-1])]
275
+ ims = {}
276
+ for ri, (label, _) in enumerate(rows):
277
+ for ci, (k, _) in enumerate(QUANT):
278
+ ax = axes[ri, ci]
279
+ coop = k == 'cooperativity'
280
+ ims[k] = ax.imshow(grids[k][ri], origin='lower', extent=ext, interpolation='nearest',
281
+ cmap='RdBu_r' if coop else 'viridis', vmin=-cmax if coop else lo,
282
+ vmax=cmax if coop else hi)
283
+ ax.set_xticks(ticks if ri == len(rows) - 1 else [])
284
+ ax.set_yticks(ticks if ci == 0 else [])
285
+ ax.tick_params(labelsize=5, length=1.5, pad=1)
286
+ if ri == 0:
287
+ ax.set_title(qnames[k], fontsize=6)
288
+ axes[ri, 0].set_ylabel(label, fontsize=5.5)
289
+ for ci in range(len(QUANT)):
290
+ axes[-1, ci].set_xlabel(xlabel, fontsize=5.5)
291
+ fig.supylabel(ylabel, fontsize=6)
292
+ cb = fig.colorbar(ims['pair'], ax=list(axes[-1, :4]), location='bottom', shrink=0.5, aspect=30)
293
+ cb.ax.tick_params(labelsize=4.5)
294
+ cb.set_label('Predicted signal', fontsize=5)
295
+ cb2 = fig.colorbar(ims['cooperativity'], ax=axes[-1, 4], location='bottom', aspect=12)
296
+ cb2.ax.tick_params(labelsize=4.5)
297
+ cb2.set_label('Cooperativity', fontsize=5)
298
+ if title:
299
+ fig.suptitle(title, fontsize=7.5)
300
+ return fig
301
+
302
+
303
+ # -- rows with a drawing, condition columns grouped by contrast -----------------------------------
304
+ def _auto_width(columns, per: float = 0.95) -> float:
305
+ """Figure width for the row figures: room for the label and drawing, then `per` inch per column."""
306
+ return 3.6 + per * len(columns) + 0.2 * len(_blocks(columns))
307
+
308
+
309
+ def _row_frame(n_rows, columns, width, row_h, head_h, title, header, extra_rows=0, draw=True, per=0.95, draw_w=2.9,
310
+ label_w=0.92, block_gap=0.3):
311
+ """
312
+ The shared skeleton of the row figures: a label column, a drawing column, then each contrast's columns
313
+ behind a narrow gap that leaves room for their y labels. Returns the figure, the grid, its height and
314
+ the grid column of each data column.
315
+ """
316
+ import matplotlib.gridspec as gridspec
317
+ import matplotlib.pyplot as plt
318
+ blocks = _blocks(columns)
319
+ width = width or _auto_width(columns, per)
320
+ ratios, pcols = [label_w, draw_w if draw else 0.05, 0.05], []
321
+ for idx in blocks.values():
322
+ ratios.append(block_gap)
323
+ pcols += list(range(len(ratios), len(ratios) + len(idx)))
324
+ ratios += [1] * len(idx)
325
+ head_ratio = 0.9
326
+ if header is None: # the top row only carries the block titles
327
+ head_h, head_ratio = head_h - 0.45, 0.45
328
+ height = n_rows * row_h + head_h
329
+ fig = plt.figure(figsize=(width, height))
330
+ gs = gridspec.GridSpec(n_rows + 1 + 2 * extra_rows, len(ratios), width_ratios=ratios,
331
+ height_ratios=[head_ratio] + [1] * n_rows + [0.32, 0.10] * extra_rows,
332
+ hspace=0.24 if not extra_rows else 0.12, wspace=0.09, left=0.015, right=0.99,
333
+ top=1 - 0.5 / height, bottom=0.62 / height)
334
+ ax_h = fig.add_subplot(gs[0, 1] if draw else gs[0, 0:2])
335
+ ax_h.set_axis_off()
336
+ if header is not None:
337
+ seq, note = header
338
+ plot_sequence_logo(ax_h.inset_axes([0.33, 0.45, 0.34, 0.55]), seq)
339
+ ax_h.text(0.5, 0.33, note, transform=ax_h.transAxes, ha='center', va='top', fontsize=6)
340
+ if len(blocks) > 1 or next(iter(blocks)):
341
+ k = 0
342
+ for block, idx in blocks.items():
343
+ ax_b = fig.add_subplot(gs[0, pcols[k]:pcols[k + len(idx) - 1] + 1])
344
+ ax_b.set_axis_off()
345
+ ax_b.text(0.5, 0.12, block, transform=ax_b.transAxes, ha='center', va='bottom', fontsize=8)
346
+ k += len(idx)
347
+ if title:
348
+ fig.suptitle(title, fontsize=7.5, y=0.998)
349
+ return fig, gs, height, pcols, width
350
+
351
+
352
+ def plot_row_lines(rows, columns, quantity: str = 'cooperativity', title: str = '', header: Optional[tuple] = None,
353
+ ylims: Optional[dict] = None, colors: Optional[Dict[str, str]] = None,
354
+ part_colors: Optional[Dict[str, str]] = None, fixed: Sequence[str] = (),
355
+ xlabel: str = 'Motif spacing (bp)', width: Optional[float] = None, row_h: float = 0.86,
356
+ draw_w: float = 2.9, label_w: float = 0.92, block_gap: float = 0.3):
357
+ """
358
+ One row per (label, drawing, x, terms): the label, a drawing of what was inserted (a sequence string draws
359
+ its logo, a list of (name, sequence) parts draws the construct, None draws nothing), then one panel per
360
+ column. quantity='cooperativity' draws the cooperativity and its SEM over backgrounds in the row colour;
361
+ quantity='absolute' draws both motifs, the additive expectation, each motif alone and the baseline.
362
+ Panels of one contrast share `ylims[contrast]` (see shared_ylims). `header` = (anchor sequence, note)
363
+ draws the anchor's logo above the drawings. `draw_w`, `label_w` and `block_gap` are the widths of the
364
+ drawing column, the row-label column and the gap in front of each contrast, relative to 1 per data
365
+ column: lower them to spend the figure on the panels instead. The gap holds the y tick labels.
366
+ """
367
+ from matplotlib.lines import Line2D
368
+ if quantity not in ('absolute', 'cooperativity'):
369
+ raise ValueError(f"quantity must be 'absolute' or 'cooperativity', got {quantity!r}")
370
+ draw = any(r[1] is not None for r in rows)
371
+ fig, gs, height, pcols, width = _row_frame(len(rows), columns, width, row_h, 1.2, title, header, draw=draw,
372
+ draw_w=draw_w, label_w=label_w, block_gap=block_gap)
373
+ logos = [r[1] for r in rows if isinstance(r[1], str)]
374
+ max_len = max((len(s) for s in logos), default=None)
375
+ builds = [r[1] for r in rows if isinstance(r[1], list)]
376
+ span = (-1.5, max(_construct_len(b) for b in builds) + 1.5) if builds else None
377
+ part_colors = _part_colors(builds, part_colors)
378
+ first_col = {b: idx[0] for b, idx in _blocks(columns).items()}
379
+ ax_ref, x_ref = {}, None
380
+ for ri, (label, drawing, x, tm) in enumerate(rows):
381
+ ax_t = fig.add_subplot(gs[ri + 1, 0])
382
+ ax_t.set_axis_off()
383
+ ax_t.text(1.0, 0.5, label, transform=ax_t.transAxes, ha='right', va='center', fontsize=5.4, linespacing=1.3)
384
+ ax_c = fig.add_subplot(gs[ri + 1, 1])
385
+ ax_c.set_axis_off()
386
+ _draw(ax_c, drawing, max_len, span, part_colors, fixed)
387
+ row_c = (colors or {}).get(label, SECOND_C if quantity == 'absolute' else COOP_C)
388
+ for ci, (block, clab) in enumerate(columns):
389
+ ax = fig.add_subplot(gs[ri + 1, pcols[ci]], sharex=x_ref, sharey=ax_ref.get(block))
390
+ x_ref = x_ref or ax
391
+ ax_ref.setdefault(block, ax)
392
+ if quantity == 'absolute':
393
+ for key, lab, col, ls, lw in ABS_LINES:
394
+ ax.plot(x, _mean_sem(tm[key][..., ci])[0], color=col or row_c, linestyle=ls, linewidth=lw, label=lab)
395
+ else:
396
+ m, s = _mean_sem(tm['cooperativity'][..., ci])
397
+ ax.fill_between(x, m - s, m + s, color=row_c, alpha=0.25, linewidth=0)
398
+ ax.plot(x, m, color=row_c, linewidth=0.6)
399
+ if quantity == 'cooperativity' or _is_diff(clab):
400
+ ax.axhline(0, color='black', linewidth=0.4, linestyle=':')
401
+ ax.tick_params(labelsize=5, length=1.5, pad=1)
402
+ if ri == 0:
403
+ ax.set_title(clab, fontsize=6.5, pad=2)
404
+ if ci != first_col[block]: # same scale as the first panel of its contrast
405
+ ax.tick_params(labelleft=False)
406
+ if ri < len(rows) - 1:
407
+ ax.tick_params(labelbottom=False)
408
+ for block, ax in ax_ref.items():
409
+ if ylims and block in ylims:
410
+ ax.set_ylim(*ylims[block])
411
+ fig.supxlabel(xlabel, fontsize=6.5, y=0.3 / height)
412
+ fig.text(0.008, 0.5, 'Predicted signal' if quantity == 'absolute' else 'Cooperativity effect', rotation=90,
413
+ ha='center', va='center', fontsize=7)
414
+ if quantity == 'absolute':
415
+ handles = [Line2D([], [], color=col or SECOND_C, linestyle=ls, linewidth=lw, label=lab)
416
+ for _, lab, col, ls, lw in ABS_LINES]
417
+ fig.legend(handles=handles, loc='lower center', ncol=5, frameon=False, fontsize=6, bbox_to_anchor=(0.5, -0.004))
418
+ return fig
419
+
420
+
421
+ def plot_row_matrices(rows, offsets, columns, title: str = '', header: Optional[tuple] = None,
422
+ vmax: Optional[dict] = None, sigma: float = 1.0, diff_cmap=None, vmax_pct: float = 98.0,
423
+ label_peak: bool = True,
424
+ part_colors: Optional[Dict[str, str]] = None, fixed: Sequence[str] = (),
425
+ xlabel: str = 'Anchor offset (bp)', ylabel: str = 'Partner offset (bp)',
426
+ width: Optional[float] = None, row_h: float = 0.95):
427
+ """
428
+ One row per (label, drawing, grid), grid (X, Y, column) the cooperativity averaged over backgrounds, as a
429
+ 2D map of the anchor offset (x) against the partner offset (y) per column, Gaussian smoothed (sigma in
430
+ grid steps, 0 for none). One colour scale per contrast, symmetric at the vmax_pct percentile of |value|
431
+ (lower it to see weak structure, raise it to 100 so a sharp peak does not saturate); a difference column
432
+ uses `diff_cmap`. Smoothing spreads a single-offset peak, such as a composite element at gap 0, into
433
+ offsets where it does not exist, so use sigma=0 for those. label_peak writes each map's largest value
434
+ (in magnitude) in its corner, so a peak that saturates the scale is still read off the figure.
435
+ """
436
+ from matplotlib.ticker import MaxNLocator
437
+ from scipy.ndimage import gaussian_filter
438
+ draw = any(r[1] is not None for r in rows)
439
+ fig, gs, height, pcols, width = _row_frame(len(rows), columns, width, row_h, 1.8, title, header, extra_rows=1, draw=draw,
440
+ per=1.4, draw_w=1.8)
441
+ logos = [r[1] for r in rows if isinstance(r[1], str)]
442
+ max_len = max((len(s) for s in logos), default=None)
443
+ builds = [r[1] for r in rows if isinstance(r[1], list)]
444
+ span = (-1.5, max(_construct_len(b) for b in builds) + 1.5) if builds else None
445
+ part_colors = _part_colors(builds, part_colors)
446
+ sm = {ri: gaussian_filter(np.asarray(r[2], np.float64), (sigma, sigma, 0)) if sigma else np.asarray(r[2])
447
+ for ri, r in enumerate(rows)}
448
+ blocks = _blocks(columns)
449
+ vmax = vmax or {b: np.nanpercentile(np.abs(np.concatenate([sm[ri][..., i].ravel() for ri in sm for i in idx])), vmax_pct)
450
+ for b, idx in blocks.items()}
451
+ step = offsets[1] - offsets[0]
452
+ ext = [offsets[0] - step / 2, offsets[-1] + step / 2] * 2
453
+ ticks = [int(offsets[0]), int(offsets[len(offsets) // 2]), int(offsets[-1])]
454
+ ims, ax_first = {}, None
455
+ for ri, (label, drawing, _) in enumerate(rows):
456
+ ax_t = fig.add_subplot(gs[ri + 1, 0])
457
+ ax_t.set_axis_off()
458
+ ax_t.text(1.0, 0.5, label, transform=ax_t.transAxes, ha='right', va='center', fontsize=5.4, linespacing=1.3)
459
+ ax_c = fig.add_subplot(gs[ri + 1, 1])
460
+ ax_c.set_axis_off()
461
+ _draw(ax_c, drawing, max_len, span, part_colors, fixed, independent=True)
462
+ for ci, (block, clab) in enumerate(columns):
463
+ ax = fig.add_subplot(gs[ri + 1, pcols[ci]])
464
+ ax_first = ax_first or ax
465
+ v = vmax[block]
466
+ im = ax.imshow(sm[ri][..., ci].T, origin='lower', extent=ext, vmin=-v, vmax=v, interpolation='nearest',
467
+ cmap=(diff_cmap or 'PuOr_r') if _is_diff(clab) else 'RdBu_r')
468
+ ims.setdefault(block, im)
469
+ if label_peak:
470
+ g = sm[ri][..., ci]
471
+ pk = g.flat[np.nanargmax(np.abs(g))]
472
+ ax.text(0.97, 0.95, f'{pk:+.2g}', transform=ax.transAxes, ha='right', va='top', fontsize=5,
473
+ color='#333333')
474
+ ax.set_xticks([])
475
+ ax.set_yticks([])
476
+ if ri == 0:
477
+ ax.set_title(clab, fontsize=6.5, pad=2)
478
+ if ri == len(rows) - 1 and ci == 0:
479
+ ax.set_xticks(ticks)
480
+ ax.set_yticks(ticks)
481
+ ax.tick_params(labelsize=4.5, length=1.5, pad=1)
482
+ k = 0
483
+ for block, idx in blocks.items():
484
+ cell = fig.add_subplot(gs[-1, pcols[k]:pcols[k + len(idx) - 1] + 1])
485
+ cell.set_axis_off()
486
+ cb = fig.colorbar(ims[block], cax=cell.inset_axes([0.08, 0, 0.84, 1]), orientation='horizontal')
487
+ cb.ax.xaxis.set_major_locator(MaxNLocator(nbins=3 if len(idx) == 1 else 5, symmetric=True))
488
+ cb.ax.tick_params(labelsize=4.5, length=1.5, pad=1)
489
+ cb.set_label('Cooperativity effect' + (f', {block}' if block else ''), fontsize=5.5, labelpad=1)
490
+ cb.outline.set_linewidth(0.4)
491
+ k += len(idx)
492
+ fig.supxlabel(xlabel, fontsize=6.5, y=0.2 / height)
493
+ fig.text(ax_first.get_position().x0 - 0.2 / width, 0.5, ylabel, rotation=90, ha='center', va='center', fontsize=6.5)
494
+ return fig
495
+
496
+
497
+ # -- every 2D scan of a design in one matrix of panels ---------------------------------------------
498
+ def plot_pair_grid(grids: Dict[Tuple[str, str], np.ndarray], anchors: Sequence[str], partners: Sequence[str], offsets,
499
+ vmax: float, cmap='RdBu_r', label: str = 'Cooperativity effect',
500
+ row_labels: Optional[Dict[str, str]] = None, cell: float = 1.0):
501
+ """
502
+ The 2D scans of a design as one matrix of panels, anchors down and partners across:
503
+ each panel is a pair's grid (anchor offset, partner offset), drawn with the anchor's offset up and the
504
+ partner's across. Pairs the design does not hold stay empty. One symmetric colour scale (+- vmax) and one colour
505
+ bar for the whole figure; pass the same vmax to the figures that should be compared.
506
+ """
507
+ import matplotlib.pyplot as plt
508
+ na, npart = len(anchors), len(partners)
509
+ cell = min(cell, 7.2 / max(npart, 1))
510
+ fig, axes = plt.subplots(na, npart, figsize=(npart * cell + 1.3, na * cell + 0.9), squeeze=False,
511
+ gridspec_kw=dict(hspace=0.12, wspace=0.08))
512
+ step = offsets[1] - offsets[0] if len(offsets) > 1 else 1
513
+ ext = [offsets[0] - step / 2, offsets[-1] + step / 2] * 2
514
+ im = None
515
+ for ai, a in enumerate(anchors):
516
+ for pi, p in enumerate(partners):
517
+ ax = axes[ai, pi]
518
+ ax.set_xticks([])
519
+ ax.set_yticks([])
520
+ ax.spines[['left', 'bottom']].set_visible(False)
521
+ if (a, p) in grids:
522
+ im = ax.imshow(grids[(a, p)], origin='lower', extent=ext, cmap=cmap, vmin=-vmax, vmax=vmax,
523
+ interpolation='nearest')
524
+ else:
525
+ ax.set_facecolor('none')
526
+ if ai == 0:
527
+ ax.set_title(p, fontsize=6, rotation=40, ha='left', va='bottom', loc='left')
528
+ if pi == 0:
529
+ ax.set_ylabel((row_labels or {}).get(a, a), fontsize=6, rotation=0, ha='right', va='center')
530
+ filled = [(ai, pi) for ai, a in enumerate(anchors) for pi, p in enumerate(partners) if (a, p) in grids]
531
+ ax0 = axes[max(filled, key=lambda t: (t[0], -t[1])) if filled else (na - 1, 0)] # the lowest drawn panel
532
+ ticks = [int(offsets[0]), int(offsets[len(offsets) // 2]), int(offsets[-1])]
533
+ ax0.set_xticks(ticks)
534
+ ax0.set_yticks(ticks)
535
+ ax0.tick_params(labelsize=5, length=1.5, pad=1)
536
+ ax0.set_xlabel('Partner offset (bp)', fontsize=6)
537
+ from ..plotting import _text_width
538
+ names = [(row_labels or {}).get(a, a) for a in anchors]
539
+ left = axes[0, 0].get_position().x0 - (max(_text_width(n.split('\n'), 6) for n in names) + 0.15) / fig.get_figwidth()
540
+ mid = (axes[-1, 0].get_position().y0 + axes[0, 0].get_position().y1) / 2
541
+ fig.text(left, mid, 'Anchor offset (bp)', rotation=90, ha='right', va='center', fontsize=6)
542
+ if im is not None:
543
+ cb = fig.colorbar(im, ax=axes, fraction=min(0.05, max(0.012, 0.12 / npart)), pad=0.02)
544
+ cb.set_label(label, fontsize=6)
545
+ cb.ax.tick_params(labelsize=5)
546
+ return fig
@@ -0,0 +1,109 @@
1
+ """
2
+ The model as the marginalization runner sees it: one-hot inputs in, per-bin tracks out.
3
+
4
+ predict(x) (N, 4, L) float32 -> (n_members, N, n_tracks, n_bins) in the model's output space
5
+
6
+ A model with one value per track, (N, n_tracks), gets a bin axis of length 1.
7
+
8
+ `members` are independent models whose predictions are kept separately and averaged at read
9
+ time: held-out fold models, or replicates. Projects provide a factory function that builds the
10
+ predictor, named in the run config as 'path/to/file.py:function' or 'package.module:function', so
11
+ the package never imports a project's model code. From Python, the predictor object itself can be
12
+ passed instead.
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import importlib.util
17
+ from pathlib import Path
18
+ from typing import Callable, List, Optional, Sequence
19
+
20
+ import numpy as np
21
+
22
+
23
+ class TorchEnsemble:
24
+ """Wraps torch modules that map (N, 4, L) to (N, all_tracks, n_bins)."""
25
+
26
+ def __init__(self, models: Sequence, member_names: Sequence[str], all_tracks: Sequence[str],
27
+ tracks: Optional[Sequence[str]] = None, batch_size: int = 256, device: Optional[str] = None,
28
+ transform: Optional[Callable] = None):
29
+ import torch
30
+ self.torch = torch
31
+ self.device = device or ('cuda' if torch.cuda.is_available() else 'cpu')
32
+ self.models = [m.to(self.device).eval() for m in models]
33
+ self.members = list(member_names)
34
+ self.tracks = list(tracks or all_tracks)
35
+ self.idx = [list(all_tracks).index(t) for t in self.tracks]
36
+ self.batch_size = batch_size
37
+ self.transform = transform # applied to the raw model output, e.g. to select heads
38
+
39
+ def predict(self, x: np.ndarray) -> np.ndarray:
40
+ out = None
41
+ for b0 in range(0, len(x), self.batch_size):
42
+ xg = self.torch.from_numpy(np.ascontiguousarray(x[b0:b0 + self.batch_size], np.float32)).to(self.device)
43
+ with self.torch.no_grad():
44
+ for k, m in enumerate(self.models):
45
+ y = m(xg)
46
+ if self.transform is not None:
47
+ y = self.transform(y)
48
+ y = y.float().cpu().numpy()[:, self.idx]
49
+ if y.ndim == 2:
50
+ y = y[..., None]
51
+ if out is None:
52
+ out = np.zeros((len(self.models), len(x)) + y.shape[1:], np.float32)
53
+ out[k, b0:b0 + len(y)] = y
54
+ return out
55
+
56
+
57
+ def load_predictor(spec: str, **kwargs):
58
+ """
59
+ The project's predictor factory called with kwargs: 'path/to/file.py:function', or 'package.module:function'
60
+ for a factory in an installed package.
61
+ """
62
+ path, func = spec.rsplit(':', 1)
63
+ if not path.endswith('.py'):
64
+ return getattr(importlib.import_module(path), func)(**kwargs)
65
+ mod_spec = importlib.util.spec_from_file_location(Path(path).stem, path)
66
+ mod = importlib.util.module_from_spec(mod_spec)
67
+ mod_spec.loader.exec_module(mod)
68
+ return getattr(mod, func)(**kwargs)
69
+
70
+
71
+ def grelu_zoo(project: str, model_name: str = 'model', tracks: Optional[Sequence[str]] = None, batch_size: int = 512,
72
+ device: Optional[str] = None, cache_dir: Optional[str] = None) -> TorchEnsemble:
73
+ """
74
+ A trained model of the gReLU model zoo as a predictor, its tracks named by its tasks. Needs grelu, imported here
75
+ only, so diffgrammar itself does not depend on it. In a config:
76
+
77
+ predictor = "diffgrammar.marginalize.predictor:grelu_zoo"
78
+ predictor_kwargs = { project = "binary_atac_cell_lines" }
79
+
80
+ The checkpoint is downloaded once into cache_dir (default $DIFFGRAMMAR_ZOO_CACHE or ~/.cache/diffgrammar/grelu-zoo)
81
+ and loaded with gReLU's own LightningModel.load_from_checkpoint. Checkpoints written by older gReLU versions keep
82
+ data_params inside hyper_parameters and have no performance entry, which that loader requires since gReLU 1.0
83
+ (KeyError 'data_params'); torch >= 2.6 also refuses some of their pickled fields under weights_only. Those are
84
+ built from their stored hyper_parameters and given their trained weights instead: the same model, unchanged.
85
+ """
86
+ import os
87
+ import pickle
88
+
89
+ import torch
90
+ import grelu.lightning as gl
91
+ import grelu.resources as r
92
+
93
+ device = device or ('cuda' if torch.cuda.is_available() else 'cpu')
94
+ root = Path(cache_dir or os.environ.get('DIFFGRAMMAR_ZOO_CACHE') or Path.home() / '.cache/diffgrammar/grelu-zoo') / project
95
+ root.mkdir(parents=True, exist_ok=True)
96
+ ckpt = Path(r.get_artifact(model_name, project=project).download(root=str(root))) / 'model.ckpt'
97
+ try:
98
+ lm = gl.LightningModel.load_from_checkpoint(ckpt, map_location='cpu')
99
+ except (KeyError, pickle.UnpicklingError):
100
+ ck = torch.load(ckpt, map_location='cpu', weights_only=False)
101
+ hp = ck['hyper_parameters']
102
+ lm = gl.LightningModel(model_params=dict(hp['model_params']), train_params=dict(hp.get('train_params', {})))
103
+ lm.load_state_dict(ck['state_dict'])
104
+ lm.data_params = ck.get('data_params') or hp.get('data_params') or {}
105
+ tasks = (lm.data_params or {}).get('tasks') or {}
106
+ names = tasks.get('name') if isinstance(tasks, dict) else None
107
+ all_tracks = list(names) if names is not None else [f'task{i}' for i in range(lm.model_params['n_tasks'])]
108
+ return TorchEnsemble([lm.model.eval()], member_names=[f'{project}/{model_name}'], all_tracks=all_tracks,
109
+ tracks=tracks, batch_size=batch_size, device=device)