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
diffgrammar/jaspar.py ADDED
@@ -0,0 +1,185 @@
1
+ """
2
+ JASPAR matching and family resolution for motif clusters.
3
+
4
+ JASPAR families can be broad ("Factors with multiple dispersed zinc fingers" groups motifs with
5
+ unrelated binding preferences), so counting clusters per family can inflate a family without one
6
+ shared specificity. Each family's PWMs are therefore split into subfamilies by complete-linkage
7
+ clustering of their pairwise distances, with the same metric and cutoff as the seqlet clustering
8
+ (the correlation p-value of diffgrammar.align, p < 0.05). Subfamilies are numbered by size (.1 largest); a
9
+ family that does not split keeps its name. A motif cluster takes the family and subfamily of its
10
+ best-matching matrix, matched by matrix ID because TF names are not unique. Clusters are matched on
11
+ their hypothetical consensus, which like a centred PWM scores every base: a contribution consensus
12
+ (one base per position) drifts to near-duplicate matrices filed under other families, such as the
13
+ AP-1 site of BNC2 MA1928.2 or the ETS site of IKZF2 MA2326.1.
14
+
15
+ Annotations (family, class) come from the JASPAR REST API by matrix ID and are cached as JSON,
16
+ so a rerun only fetches what is missing. The PWM distance matrix is cached as an npz next to it.
17
+ Without a `meme` in the config, the JASPAR 2024 CORE vertebrates non-redundant matrices are used,
18
+ downloaded once into ~/.cache/diffgrammar/jaspar ($DIFFGRAMMAR_CACHE/jaspar when that is set) and shared by every
19
+ run.
20
+ """
21
+ from __future__ import annotations
22
+
23
+ import json
24
+ import time
25
+ from pathlib import Path
26
+ from typing import Dict, List, Optional, Sequence
27
+
28
+ import numpy as np
29
+ import pandas as pd
30
+
31
+ from .align import compare
32
+
33
+ API = 'https://jaspar.elixir.no/api/v1/matrix/{}/?format=json'
34
+ MEME_NAME = 'JASPAR2024_CORE_vertebrates_non-redundant_pfms_meme.txt'
35
+ MEME_URL = 'https://jaspar.elixir.no/download/data/2024/CORE/' + MEME_NAME
36
+
37
+
38
+ def default_meme() -> Path:
39
+ """The default JASPAR file, in the user's diffgrammar cache: $DIFFGRAMMAR_CACHE, else ~/.cache/diffgrammar."""
40
+ import os
41
+ root = Path(os.environ.get('DIFFGRAMMAR_CACHE') or Path.home() / '.cache' / 'diffgrammar').expanduser()
42
+ return root / 'jaspar' / MEME_NAME
43
+
44
+
45
+ def ensure_meme(path, log=print) -> Path:
46
+ """The MEME file at path, downloading the default JASPAR release there when that is what is missing."""
47
+ path = Path(path)
48
+ if not path.exists():
49
+ if path.name != MEME_NAME:
50
+ raise FileNotFoundError(path)
51
+ import requests
52
+ log(f'downloading {MEME_URL}')
53
+ r = requests.get(MEME_URL, timeout=60)
54
+ r.raise_for_status()
55
+ path.parent.mkdir(parents=True, exist_ok=True)
56
+ path.write_text(r.text)
57
+ return path
58
+
59
+
60
+ def load_meme(path: str):
61
+ """(ids, names, pwms) from a MEME file; pwms are (L, 4) float32 probabilities."""
62
+ ids, names, pwms, cur_name, cur_id, rows = [], [], [], None, None, []
63
+ skip = ('MEME', 'ALPHABET', 'strands', 'Background', 'URL', 'w =', 'nsites', '//')
64
+ with open(path) as fh:
65
+ for line in fh:
66
+ line = line.strip()
67
+ if line.startswith('MOTIF'):
68
+ if cur_name is not None and rows:
69
+ ids.append(cur_id); names.append(cur_name); pwms.append(np.array(rows, np.float32))
70
+ parts = line.split()
71
+ cur_name = parts[2] if len(parts) >= 3 else parts[1]
72
+ cur_id = parts[1]
73
+ rows = []
74
+ elif line.startswith('letter-probability matrix'):
75
+ continue
76
+ elif cur_name is not None and line and not line.startswith(skip):
77
+ try:
78
+ vals = [float(x) for x in line.split()]
79
+ except ValueError:
80
+ continue
81
+ if len(vals) == 4:
82
+ rows.append(vals)
83
+ if cur_name is not None and rows:
84
+ ids.append(cur_id); names.append(cur_name); pwms.append(np.array(rows, np.float32))
85
+ return ids, names, pwms
86
+
87
+
88
+ def match(consensus: Sequence[np.ndarray], cluster_ids: Sequence[int], ids: Sequence[str],
89
+ names: Sequence[str], pwms: Sequence[np.ndarray], device: str = 'cuda', top_n: int = 5,
90
+ min_overlap: int = 4, batchsize: int = 512) -> Dict[int, List[dict]]:
91
+ """cluster id -> [{'tf', 'id', 'pval'}, ...] best first, by the seqlet-clustering metric."""
92
+ dist, _, _ = compare(
93
+ list(consensus), list(pwms), metric='correlation_pvalue', min_overlap=min_overlap,
94
+ device=device, batchsize=batchsize, return_alignment=True)
95
+ out = {}
96
+ for i, cid in enumerate(cluster_ids):
97
+ top = np.argsort(dist[i])[:top_n]
98
+ out[int(cid)] = [{'tf': names[j], 'id': ids[j], 'pval': float(dist[i, j])} for j in top]
99
+ return out
100
+
101
+
102
+ def fetch_annotations(ids: Sequence[str], names: Sequence[str], cache: str | Path,
103
+ sleep: float = 0.05, log=print) -> pd.DataFrame:
104
+ """matrix_id, name, family, class for every matrix; fetches only IDs missing from the cache."""
105
+ import requests
106
+ cache = Path(cache)
107
+ store = json.loads(cache.read_text()) if cache.exists() else {}
108
+ missing = [i for i in ids if i not in store]
109
+ if missing:
110
+ log(f'fetching {len(missing)} JASPAR annotations ({len(store)} cached)')
111
+ for k, mid in enumerate(missing):
112
+ d = requests.get(API.format(mid), timeout=20).json()
113
+ store[mid] = {'name': d.get('name'), 'family': d.get('family', []), 'class': d.get('class', [])}
114
+ time.sleep(sleep)
115
+ if (k + 1) % 100 == 0:
116
+ cache.write_text(json.dumps(store, indent=1))
117
+ if missing:
118
+ cache.parent.mkdir(parents=True, exist_ok=True)
119
+ cache.write_text(json.dumps(store, indent=1))
120
+ return pd.DataFrame([{'matrix_id': mid, 'name': n,
121
+ 'family': '; '.join(store[mid]['family']) or 'Unknown',
122
+ 'class': '; '.join(store[mid]['class']) or 'Unknown'}
123
+ for mid, n in zip(ids, names)])
124
+
125
+
126
+ def pwm_distance(pwms: Sequence[np.ndarray], ids: Sequence[str], cache: Optional[str | Path] = None,
127
+ device: str = 'cuda', min_overlap: int = 4) -> np.ndarray:
128
+ """(n, n) symmetric-diagonal-zero correlation p-value distance between the PWMs, cached."""
129
+ if cache is not None and Path(cache).exists():
130
+ z = np.load(cache)
131
+ if list(z['ids']) == list(ids):
132
+ return z['distance']
133
+ d, _, _ = compare(
134
+ list(pwms), list(pwms), metric='correlation_pvalue', min_overlap=min_overlap,
135
+ device=device, batchsize=1024, return_alignment=True)
136
+ d = np.asarray(d, np.float64)
137
+ np.fill_diagonal(d, 0.0)
138
+ if cache is not None:
139
+ Path(cache).parent.mkdir(parents=True, exist_ok=True)
140
+ np.savez_compressed(cache, distance=d, ids=np.array(ids))
141
+ return d
142
+
143
+
144
+ def subfamilies(ann: pd.DataFrame, distance: np.ndarray, group_level: str = 'family',
145
+ linkage: str = 'complete', p_cutoff: float = 0.05) -> pd.DataFrame:
146
+ """Adds 'group' (first listed family or class) and 'subfamily' to the annotation table."""
147
+ from scipy.cluster.hierarchy import fcluster, linkage as hlinkage
148
+ from scipy.spatial.distance import squareform
149
+ ann = ann.copy()
150
+ ann['group'] = ann[group_level].str.split('; ').str[0]
151
+ sub_of = {}
152
+ for g, ix in ann.groupby('group').groups.items():
153
+ ix = np.asarray(ix)
154
+ if len(ix) == 1:
155
+ sub_of[ix[0]] = g
156
+ continue
157
+ lab = fcluster(hlinkage(squareform(distance[np.ix_(ix, ix)], checks=False), method=linkage),
158
+ t=p_cutoff, criterion='distance')
159
+ if len(set(lab)) == 1:
160
+ sub_of.update({i: g for i in ix})
161
+ continue
162
+ order = pd.Series(lab).value_counts().index.tolist()
163
+ for i, l in zip(ix, lab):
164
+ sub_of[i] = f'{g}.{order.index(l) + 1}'
165
+ ann['subfamily'] = ann.index.map(sub_of)
166
+ return ann
167
+
168
+
169
+ def cluster_families(hits: Dict[int, List[dict]], ann: pd.DataFrame) -> pd.DataFrame:
170
+ """Per cluster: best matrix, TF, match p-value, family group and subfamily."""
171
+ by_id = ann.set_index('matrix_id')
172
+ rows = [{'cluster': c, 'matrix_id': h[0]['id'], 'tf': h[0]['tf'], 'match_p': h[0]['pval'],
173
+ 'top_tfs': ', '.join(dict.fromkeys(x['tf'] for x in h))} for c, h in hits.items()]
174
+ df = pd.DataFrame(rows)
175
+ df['group'] = df['matrix_id'].map(by_id['group'])
176
+ df['subfamily'] = df['matrix_id'].map(by_id['subfamily'])
177
+ return df
178
+
179
+
180
+ def information_content(pwm: np.ndarray, background: float = 0.25) -> np.ndarray:
181
+ """(L, 4) probabilities as letter heights in bits: each probability times the information of its position."""
182
+ p = np.asarray(pwm, np.float64)
183
+ p = p / np.maximum(p.sum(1, keepdims=True), 1e-12)
184
+ bits = (p * np.log2(np.maximum(p, 1e-12) / background)).sum(1, keepdims=True)
185
+ return p * np.clip(bits, 0, None)
@@ -0,0 +1,4 @@
1
+ """In silico marginalization: insert motif pairs into fixed backgrounds and read the model's response."""
2
+ from .design import Design, Geometry, realise
3
+ from .store import Store
4
+ from .predictor import TorchEnsemble, load_predictor
@@ -0,0 +1,107 @@
1
+ """
2
+ Background sequences for marginalization, (n, 4, L) one-hot.
3
+
4
+ Three kinds, each recorded in sequence_metadata.csv with its origin:
5
+
6
+ dinuc_shuffled given regions (e.g. peaks of the sets under study), dinucleotide-shuffled once
7
+ genome_shuffled random genome windows that overlap no interval of the exclusion BED files and
8
+ contain no N, dinucleotide-shuffled once
9
+ random independent uniform bases
10
+
11
+ Shuffling keeps dinucleotide composition and destroys motifs, so an insertion's effect is
12
+ measured against a background that carries the region's composition but none of its grammar.
13
+ The exclusion intervals are merged in Python, so no bedtools is needed.
14
+ """
15
+ from __future__ import annotations
16
+
17
+ from pathlib import Path
18
+ from typing import Dict, Iterable, List, Optional, Sequence, Tuple
19
+
20
+ import numpy as np
21
+ import pandas as pd
22
+
23
+ from ..sequence import one_hot
24
+
25
+
26
+ def dinuc_shuffle(seq: str, rng: np.random.Generator) -> np.ndarray:
27
+ """Dinucleotide-preserving shuffle (tangermeme); N becomes a random base first. (4, L)."""
28
+ import torch
29
+ from tangermeme.ersatz import dinucleotide_shuffle
30
+ clean = ''.join(rng.choice(list('ACGT')) if c not in 'ACGT' else c for c in seq.upper())
31
+ x = torch.from_numpy(one_hot(clean).T.copy()).float().unsqueeze(0)
32
+ out = dinucleotide_shuffle(x, n=1, random_state=int(rng.integers(0, 2 ** 31)))
33
+ return out[0, 0].numpy()
34
+
35
+
36
+ def read_intervals(beds: Iterable[str | Path]) -> Dict[str, Tuple[np.ndarray, np.ndarray]]:
37
+ """Merged intervals per chromosome from BED files: chrom -> (starts, ends), sorted, disjoint."""
38
+ frames = [pd.read_csv(b, sep='\t', header=None, usecols=[0, 1, 2], names=['chrom', 'start', 'end'],
39
+ comment='#') for b in beds]
40
+ if not frames:
41
+ return {}
42
+ iv = pd.concat(frames).sort_values(['chrom', 'start'])
43
+ out = {}
44
+ for chrom, g in iv.groupby('chrom'):
45
+ s, e = g['start'].to_numpy(), g['end'].to_numpy()
46
+ ms, me = [s[0]], [e[0]]
47
+ for a, b in zip(s[1:], e[1:]):
48
+ if a <= me[-1]:
49
+ me[-1] = max(me[-1], b)
50
+ else:
51
+ ms.append(a); me.append(b)
52
+ out[chrom] = (np.array(ms), np.array(me))
53
+ return out
54
+
55
+
56
+ def _overlaps(excl, chrom, lo, hi) -> bool:
57
+ if chrom not in excl:
58
+ return False
59
+ s, e = excl[chrom]
60
+ i = np.searchsorted(s, hi, side='left') - 1
61
+ return i >= 0 and e[i] > lo
62
+
63
+
64
+ def make_backgrounds(genome: str, seq_len: int, regions: Optional[pd.DataFrame] = None,
65
+ n_genome: int = 100, n_random: int = 0, chroms: Optional[Sequence[str]] = None,
66
+ exclude_beds: Sequence[str] = (), seed: int = 42, max_attempts: int = 20000):
67
+ """
68
+ regions: chrom, center (and optionally 'source') for the dinuc_shuffled rows.
69
+ Returns (sequences (n, 4, L) float32, metadata DataFrame).
70
+ """
71
+ from pyfaidx import Fasta
72
+ fa = Fasta(genome)
73
+ half = seq_len // 2
74
+ seqs: List[np.ndarray] = []
75
+ meta: List[dict] = []
76
+ rng = np.random.default_rng(seed)
77
+ if regions is not None:
78
+ for _, r in regions.iterrows():
79
+ c = int(r['center'])
80
+ s = str(fa[r['chrom']][c - half:c + half])
81
+ if len(s) != seq_len:
82
+ continue
83
+ seqs.append(dinuc_shuffle(s, rng))
84
+ meta.append({'chrom': r['chrom'], 'center': c, 'source': r.get('source', 'regions'),
85
+ 'type': 'dinuc_shuffled'})
86
+ for i in range(n_random):
87
+ seqs.append(np.eye(4, dtype=np.float32)[rng.integers(0, 4, seq_len)].T)
88
+ meta.append({'chrom': 'random', 'center': i, 'source': 'random', 'type': 'random'})
89
+
90
+ rng_g = np.random.default_rng(seed + 99)
91
+ excl = read_intervals(exclude_beds)
92
+ chroms = list(chroms) if chroms else [c for c in fa.keys() if c.removeprefix('chr').isdigit()]
93
+ sizes = np.array([len(fa[c]) for c in chroms], np.float64)
94
+ n_done = attempts = 0
95
+ while n_done < n_genome and attempts < max_attempts:
96
+ attempts += 1
97
+ chrom = chroms[rng_g.choice(len(chroms), p=sizes / sizes.sum())]
98
+ c = int(rng_g.integers(half, len(fa[chrom]) - half))
99
+ if _overlaps(excl, chrom, c - half, c + half):
100
+ continue
101
+ s = str(fa[chrom][c - half:c + half])
102
+ if len(s) != seq_len or 'N' in s.upper():
103
+ continue
104
+ seqs.append(dinuc_shuffle(s, rng_g))
105
+ meta.append({'chrom': chrom, 'center': c, 'source': 'genome_random', 'type': 'genome_shuffled'})
106
+ n_done += 1
107
+ return np.stack(seqs).astype(np.float32), pd.DataFrame(meta)
@@ -0,0 +1,344 @@
1
+ """
2
+ Marginalization of a list of motif pairs, read as cooperativity in the two conditions.
3
+
4
+ `diffgrammar marginalize CONFIG` (or `run(cfg)`) inserts each pair of the `[marginalize]` list into fixed
5
+ backgrounds, together with each motif alone at the position it holds in the pair, predicts every input with the
6
+ model, and reads per condition (the mean over its tracks)
7
+
8
+ cooperativity = both motifs - anchor alone - partner alone + background
9
+
10
+ Scans ('scans' in the config)
11
+ line anchor then partner at every spacing of the grid, the pair centred (pair_spacing)
12
+ heatmap anchor left and partner right of the centre, the two offsets moved independently (pair_offset_matrix)
13
+
14
+ Settings, in [marginalize]
15
+ pairs [[anchor, partner], ...], names from `motifs`
16
+ motifs name -> IUPAC sequence; degenerate positions are filled identically in a pair and its singles
17
+ scans default ['line']
18
+ predictor, predictor_kwargs, genome, seq_len default: those of [attribute]
19
+ a, b, label_a, label_b the conditions as model tracks; default: those of [attribute]
20
+ prediction_space the model's output space: 'identity' (default), 'log2p1', 'log1p' or 'logit'
21
+ bins, real_space the readout: bins summed (default all) and whether to undo the output transform first
22
+ heatmap_sigma smoothing of the heatmaps in offset steps (default 1; 0 for none)
23
+ geometry window, spacings, offsets (default: Geometry.for_input)
24
+ backgrounds n_genome (100 dinucleotide-shuffled genome windows), regions (CSV of chrom, center to
25
+ shuffle as well), chroms, exclude_beds, seed
26
+ store default <out_dir>/marginalize/store
27
+
28
+ Writes, under <out_dir>/marginalize/
29
+ store/ predictions: one npz per experiment, the backgrounds, design.json, store.json
30
+ cooperativity_line.csv anchor, partner, spacing, condition and, as mean and SEM over backgrounds:
31
+ pair, anchor_alone, partner_alone, additive, baseline, cooperativity
32
+ cooperativity_heatmap.csv the same per anchor_offset and partner_offset
33
+ summary.csv per pair, scan and condition: the largest cooperativity (in magnitude), where, and
34
+ its SEM
35
+ lines_cooperativity one row per pair: cooperativity against spacing in A, B and B - A
36
+ lines_predictions one row per pair: both motifs, each alone, additive and baseline in A and B
37
+ heatmap_<A>, heatmap_<B> with the heatmap scan: anchors down, partners across, each panel the pair's
38
+ cooperativity over both offsets; the two conditions on one colour scale
39
+ heatmap_<B>_minus_<A> the same for B - A, on its own scale
40
+ Figures are written as pdf and png. B - A is taken within each background, so its SEM is paired. A store is
41
+ only ever appended to: rerunning computes the pairs it does not hold yet, and recomputes a file whose motif
42
+ sequence changed.
43
+ """
44
+ from __future__ import annotations
45
+
46
+ import re
47
+ import time
48
+ from pathlib import Path
49
+ from typing import Optional
50
+
51
+ import numpy as np
52
+ import pandas as pd
53
+
54
+ from ..contrast import Contrast
55
+ from .design import SCANS, Design, Geometry
56
+ from .readout import _mean_sem, by_condition
57
+ from .store import Store
58
+
59
+ #: the five quantities of the store readers and their names in the tables
60
+ QUANTITIES = {'pair': 'pair', 'first': 'anchor_alone', 'second': 'partner_alone', 'additive': 'additive',
61
+ 'baseline': 'baseline', 'cooperativity': 'cooperativity'}
62
+ BACKGROUND_DEFAULTS = {'n_genome': 100, 'n_random': 0, 'seed': 42}
63
+
64
+
65
+ # -- settings -----------------------------------------------------------------------------------------
66
+
67
+ def settings_of(cfg: dict) -> dict:
68
+ """The [marginalize] section with its defaults, taken from [attribute] where it has them."""
69
+ m = dict(cfg.get('marginalize', {}))
70
+ a = cfg.get('attribute', {})
71
+ for k in ('predictor', 'predictor_kwargs', 'genome', 'seq_len'):
72
+ if k not in m and k in a:
73
+ m[k] = a[k]
74
+ m.setdefault('predictor_kwargs', {})
75
+ m.setdefault('scans', ['line'])
76
+ m.setdefault('prediction_space', 'identity')
77
+ m.setdefault('real_space', False)
78
+ m.setdefault('store', str(Path(cfg['run']['out_dir']) / 'marginalize' / 'store'))
79
+ m['backgrounds'] = {**BACKGROUND_DEFAULTS, **m.get('backgrounds', {})}
80
+ m['backgrounds'].setdefault('genome', m.get('genome'))
81
+ return m
82
+
83
+
84
+ def conditions(cfg: dict, tracks=None) -> Contrast:
85
+ """The two conditions as model tracks: [marginalize] a / b, else those of [attribute], else the first contrast; B
86
+ alone for a single-track run."""
87
+ m, a = cfg.get('marginalize', {}), cfg.get('attribute', {})
88
+ for sec in (m, a, *cfg.get('contrasts', {}).values()):
89
+ if any(k in sec for k in ('a', 'a_prefixes', 'b', 'b_prefixes')):
90
+ return Contrast.from_config('', sec, tracks)
91
+ raise ValueError('[marginalize] needs the conditions: a and b (model tracks), or an [attribute] section')
92
+
93
+
94
+ def design_of(cfg: dict) -> Design:
95
+ """The design: the [marginalize] pairs and motifs, or a design file (`design`)."""
96
+ m = settings_of(cfg)
97
+ if m.get('design'):
98
+ return Design.load(m['design'])
99
+ if not m.get('pairs') or not m.get('motifs'):
100
+ raise ValueError('[marginalize] needs `pairs` and `motifs` (or a `design` file)')
101
+ if not m.get('seq_len'):
102
+ raise ValueError('[marginalize] needs `seq_len`, the model input length (or an [attribute] section)')
103
+ geo = Geometry.for_input(int(m['seq_len']), **m.get('geometry', {}))
104
+ return Design.from_pairs(m['pairs'], m['motifs'], geo, scans=m['scans'], seed=int(m.get('seed', 42)))
105
+
106
+
107
+ def _readout(m: dict) -> dict:
108
+ return dict(bins=slice(*m['bins']) if m.get('bins') else None, real_space=bool(m['real_space']))
109
+
110
+
111
+ # -- tables ---------------------------------------------------------------------------------------------
112
+
113
+ def _columns(terms: dict, tracks, cond: Contrast):
114
+ """
115
+ terms reduced to the condition columns A, B and B - A (paired within each background). The difference is its
116
+ own block of columns, so the figures give it its own scale. A single-track run has its one column.
117
+ """
118
+ each, cols = by_condition(terms, tracks, [cond])
119
+ if cond.single:
120
+ return each, [('Per condition', lab) for _, lab in cols]
121
+ diff, dcols = by_condition(terms, tracks, [cond], diff=True)
122
+ cols = [('Per condition', lab) for _, lab in cols] + [('Difference', lab) for _, lab in dcols]
123
+ return {k: np.concatenate([each[k], diff[k]], -1) for k in each}, cols
124
+
125
+
126
+ def pair_terms(store: Store, anchor: str, partner: str, cond: Contrast, scan: str = 'line', bins=None,
127
+ real_space: bool = False):
128
+ """(grid, the five quantities (*grid, n_bg, column), columns) of one pair; columns A, B, B - A."""
129
+ tracks = list(dict.fromkeys(list(cond.a) + list(cond.b)))
130
+ read = store.terms if scan == 'line' else store.matrix_terms
131
+ grid, tm = read(anchor, partner, tracks=tracks, bins=bins, real_space=real_space)
132
+ tm, cols = _columns(tm, tracks, cond)
133
+ return grid, tm, cols
134
+
135
+
136
+ def _long(grid_cols: dict, tm: dict, cols) -> pd.DataFrame:
137
+ """Mean and SEM over backgrounds of every quantity, one row per grid point and condition column."""
138
+ shape = tm['pair'].shape[:-2]
139
+ frames = []
140
+ for ci, (_, label) in enumerate(cols):
141
+ d = {**grid_cols, 'condition': label}
142
+ for key, name in QUANTITIES.items():
143
+ x = tm[key][..., ci].reshape(-1, tm[key].shape[-2])
144
+ m, s = _mean_sem(x)
145
+ d[name], d[f'{name}_sem'] = m, s
146
+ frames.append(pd.DataFrame(d))
147
+ out = pd.concat(frames, ignore_index=True)
148
+ assert len(out) == len(cols) * int(np.prod(shape))
149
+ return out.dropna(subset=['pair'])
150
+
151
+
152
+ def tables(store: Store, design: Design, cond: Contrast, bins=None, real_space: bool = False) -> dict:
153
+ """{'line': table, 'heatmap': table} for the scans the design holds; see the module docstring."""
154
+ out = {}
155
+ for scan, geom in SCANS.items():
156
+ frames = []
157
+ for a, p in design.pairs(geom):
158
+ grid, tm, cols = pair_terms(store, a, p, cond, scan, bins, real_space)
159
+ if scan == 'line':
160
+ g = {'spacing': grid}
161
+ else:
162
+ x, y = np.meshgrid(grid, grid, indexing='ij')
163
+ g = {'anchor_offset': x.ravel(), 'partner_offset': y.ravel()}
164
+ frames.append(_long(g, tm, cols).assign(anchor=a, partner=p))
165
+ if frames:
166
+ t = pd.concat(frames, ignore_index=True)
167
+ out[scan] = t[['anchor', 'partner'] + [c for c in t if c not in ('anchor', 'partner')]]
168
+ return out
169
+
170
+
171
+ def summary(tabs: dict) -> pd.DataFrame:
172
+ """Per pair, scan and condition: the largest cooperativity in magnitude, where it is, and its SEM."""
173
+ rows = []
174
+ for scan, t in tabs.items():
175
+ at = ['spacing'] if scan == 'line' else ['anchor_offset', 'partner_offset']
176
+ for (a, p, c), g in t.groupby(['anchor', 'partner', 'condition'], sort=False):
177
+ i = g['cooperativity'].abs().idxmax()
178
+ rows.append({'anchor': a, 'partner': p, 'scan': scan, 'condition': c,
179
+ 'peak_cooperativity': g.at[i, 'cooperativity'], 'peak_sem': g.at[i, 'cooperativity_sem'],
180
+ **{f'at_{k}': g.at[i, k] for k in at},
181
+ 'mean_cooperativity': g['cooperativity'].mean()})
182
+ return pd.DataFrame(rows)
183
+
184
+
185
+ # -- figures --------------------------------------------------------------------------------------------
186
+
187
+ def _stem(label: str) -> str:
188
+ return re.sub(r'[^A-Za-z0-9]+', '_', label).strip('_')
189
+
190
+
191
+ def figures(store: Store, design: Design, cond: Contrast, bins=None, real_space: bool = False,
192
+ colors: Optional[dict] = None, sigma: float = 1.0, vmax_pct: float = 98.0) -> dict:
193
+ """
194
+ name -> figure, for the scans the design holds; see the module docstring. The heatmaps are smoothed by a
195
+ Gaussian of `sigma` offset steps (0 for none) and share one colour scale between the two conditions, symmetric
196
+ at the `vmax_pct` percentile of |cooperativity|; the difference has its own.
197
+ """
198
+ from .. import plotting as P
199
+ from . import plots as M
200
+ colors = colors or {}
201
+ ca, cb = colors.get('a', P.DEFAULT_A), colors.get('b', P.DEFAULT_B)
202
+ figs = {}
203
+ construct = lambda a, p: [(a, design.anchors[a]), (p, design.partners[p])]
204
+ lines = [(a, p, *pair_terms(store, a, p, cond, 'line', bins, real_space)) for a, p in design.pairs('pair_spacing')]
205
+ if lines:
206
+ cols = lines[0][4]
207
+ rows = [(f'{a} + {p}', construct(a, p), x, tm) for a, p, x, tm, _ in lines]
208
+ figs['lines_cooperativity'] = M.plot_row_lines(
209
+ rows, cols, quantity='cooperativity', ylims=M.shared_ylims([r[3] for r in rows], ['cooperativity'], cols, sem=True),
210
+ title='Cooperativity against spacing')
211
+ nc = 1 if cond.single else 2 # the conditions' own columns, not their difference
212
+ two = [(lab, d, x, {k: v[..., :nc] for k, v in tm.items()}) for lab, d, x, tm in rows]
213
+ keys = ['pair', 'first', 'second', 'additive', 'baseline']
214
+ figs['lines_predictions'] = M.plot_row_lines(two, cols[:nc], quantity='absolute',
215
+ ylims=M.shared_ylims([r[3] for r in two], keys, cols[:nc]),
216
+ title='Predicted signal against spacing')
217
+ mats = [(a, p, *pair_terms(store, a, p, cond, 'heatmap', bins, real_space)) for a, p in design.pairs('pair_offset_matrix')]
218
+ if mats:
219
+ from scipy.ndimage import gaussian_filter
220
+ off, cols = mats[0][2], mats[0][4]
221
+ anchors = list(dict.fromkeys(a for a, *_ in mats))
222
+ partners = list(dict.fromkeys(p for _, p, *_ in mats))
223
+ grids = [{(a, p): gaussian_filter(np.nanmean(tm['cooperativity'][..., ci], axis=2), sigma) if sigma
224
+ else np.nanmean(tm['cooperativity'][..., ci], axis=2) for a, p, _, tm, _ in mats}
225
+ for ci in range(len(cols))]
226
+ scale = lambda gs: float(np.nanpercentile(np.abs(np.concatenate([g.ravel() for d in gs for g in d.values()])),
227
+ vmax_pct)) or 1.0
228
+ shared = scale(grids[:2])
229
+ space = '' if real_space or store.space == 'identity' else f' ({store.space})'
230
+ names = ([f'heatmap_{_stem(cond.label_b)}'] if cond.single else
231
+ [f'heatmap_{_stem(cond.label_a)}', f'heatmap_{_stem(cond.label_b)}',
232
+ f'heatmap_{_stem(cond.label_b)}_minus_{_stem(cond.label_a)}'])
233
+ for ci, ((_, label), name) in enumerate(zip(cols, names)):
234
+ diff = ci == 2
235
+ figs[name] = M.plot_pair_grid(grids[ci], anchors, partners, off, vmax=scale(grids[2:]) if diff else shared,
236
+ cmap=P.diverging_cmap(ca, cb) if diff else 'RdBu_r',
237
+ label=f'Cooperativity effect,\n{label}{space}',
238
+ row_labels={a: f'{a}\n{design.anchors[a]}' for a in anchors})
239
+ return figs
240
+
241
+
242
+ # -- the step -------------------------------------------------------------------------------------------
243
+
244
+ def init(store_path, design: Design, predictor, settings: dict, log=print) -> Store:
245
+ """A new store: backgrounds from the genome (and regions), predicted once."""
246
+ from .backgrounds import make_backgrounds
247
+ from .run import init_store
248
+ b = settings['backgrounds']
249
+ if not b.get('genome'):
250
+ raise ValueError('[marginalize] needs a genome for the backgrounds (or an [attribute] genome)')
251
+ regions = pd.read_csv(b['regions']) if b.get('regions') else None
252
+ seqs, meta = make_backgrounds(b['genome'], design.geometry.seq_len, regions=regions, n_genome=int(b['n_genome']),
253
+ n_random=int(b['n_random']), chroms=b.get('chroms'),
254
+ exclude_beds=b.get('exclude_beds', []), seed=int(b['seed']))
255
+ tmp = Path(store_path) / '_backgrounds_tmp'
256
+ tmp.mkdir(parents=True, exist_ok=True)
257
+ np.savez_compressed(tmp / 'sequences.npz', sequences=seqs)
258
+ meta.to_csv(tmp / 'sequence_metadata.csv', index=False)
259
+ store = init_store(store_path, design, predictor, tmp / 'sequences.npz', tmp / 'sequence_metadata.csv',
260
+ sorted(meta['type'].unique()), settings['prediction_space'])
261
+ import shutil
262
+ shutil.rmtree(tmp)
263
+ log(f'[marginalize] store initialised at {store.path}: {meta["type"].value_counts().to_dict()} backgrounds')
264
+ return store
265
+
266
+
267
+ def run(cfg: dict, predictor=None, plan_only: bool = False, log=print) -> dict:
268
+ """
269
+ The marginalize step: compute what the store lacks for the configured pairs, then write the tables and figures.
270
+ `predictor` (a TorchEnsemble-like object) replaces the config's predictor factory; it is only loaded when
271
+ something has to be computed.
272
+ """
273
+ import matplotlib.pyplot as plt
274
+ from .predictor import load_predictor
275
+ from . import run as R
276
+ m = settings_of(cfg)
277
+ design = design_of(cfg)
278
+ problems = design.check()
279
+ if problems:
280
+ raise ValueError('design problems:\n ' + '\n '.join(problems))
281
+ out = Path(cfg['run']['out_dir']) / 'marginalize'
282
+ out.mkdir(parents=True, exist_ok=True)
283
+
284
+ def model():
285
+ nonlocal predictor
286
+ if predictor is None:
287
+ if not m.get('predictor'):
288
+ raise ValueError('[marginalize] needs a predictor (or an [attribute] predictor)')
289
+ predictor = load_predictor(m['predictor'], **(m['predictor_kwargs'] or {}))
290
+ return predictor
291
+
292
+ store = Store(m['store'])
293
+ if not (store.path / 'store.json').exists():
294
+ if plan_only:
295
+ log(f'[marginalize] no store at {store.path} yet: `marginalize` creates it ({m["backgrounds"]["n_genome"]} '
296
+ f'genome backgrounds), then computes every experiment')
297
+ return {'n_todo': len(R.wanted(design))}
298
+ store = init(store.path, design, model(), m, log)
299
+ elif store.meta.get('design', {}).get('geometry') != design.geometry.to_dict():
300
+ raise ValueError(f'{store.path} was made for another geometry (seq_len, window, spacings or offsets); '
301
+ f'give the new run its own `store`')
302
+ design.save(store.path / 'design.json')
303
+ todo = R.plan(store, design)
304
+ n_bg, n_mem = len(store.meta['background_rows']), len(store.meta['members'])
305
+ cost = sum(R.passes(design, k, a, p, n_bg, n_mem) for k, a, p, *_ in todo)
306
+ log(f'[marginalize] {len(design.pairs("pair_spacing")) + len(design.pairs("pair_offset_matrix"))} pair scans, '
307
+ f'{len(todo)} experiments to compute ({cost / 1e6:.2f} M forward passes) over {n_bg} backgrounds')
308
+ if plan_only:
309
+ for k, a, p, *_, st in todo:
310
+ log(f' {k:16s} {a or "":20s} {p or "":20s} {st}')
311
+ return {'n_todo': len(todo), 'forward_passes': cost}
312
+ if todo:
313
+ pred = model()
314
+ seqs = np.load(store.path / 'backgrounds' / 'sequences.npz')['sequences']
315
+ bgs = np.ascontiguousarray(seqs[store.meta['background_rows']].astype(np.float32))
316
+ for i, (k, a, p, *_) in enumerate(todo, 1):
317
+ t0 = time.time()
318
+ R.write(store, k, a, p, R.compute(design, k, a, p, pred, bgs))
319
+ log(f'[marginalize] {i}/{len(todo)} {k} {a or ""} {p or ""} ({time.time() - t0:.0f} s)')
320
+
321
+ cond = conditions(cfg, store.meta.get('tracks'))
322
+ missing = [t for t in list(cond.a) + list(cond.b) if t not in store.meta.get('tracks', [])]
323
+ if missing:
324
+ raise ValueError(f'condition tracks not in the store: {missing}; it has {store.meta.get("tracks")}')
325
+ ro = _readout(m)
326
+ tabs = tables(store, design, cond, **ro)
327
+ for scan, t in tabs.items():
328
+ t.to_csv(out / f'cooperativity_{scan}.csv', index=False, float_format='%.6g')
329
+ summ = summary(tabs)
330
+ summ.to_csv(out / 'summary.csv', index=False, float_format='%.6g')
331
+ rep = cfg.get('report', {})
332
+ from .. import plotting as P
333
+ P.style()
334
+ figs = figures(store, design, cond, colors={k: rep[f'color_{k}'] for k in 'ab' if rep.get(f'color_{k}')},
335
+ sigma=float(m.get('heatmap_sigma', 1.0)), **ro)
336
+ for name, fig in figs.items():
337
+ for ext in ('pdf', 'png'):
338
+ fig.savefig(out / f'{name}.{ext}', bbox_inches='tight')
339
+ plt.close(fig)
340
+ log(f'[marginalize] tables and {len(figs)} figures written to {out}')
341
+ return {'n_computed': len(todo), 'pairs': [list(p) for p in design.pairs('pair_spacing')],
342
+ 'pairs_heatmap': [list(p) for p in design.pairs('pair_offset_matrix')], 'conditions':
343
+ {'a': {'label': cond.label_a, 'tracks': list(cond.a)}, 'b': {'label': cond.label_b, 'tracks': list(cond.b)}},
344
+ 'store': str(store.path), 'n_backgrounds': n_bg, **{k: str(v) for k, v in ro.items()}}