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/scan.py ADDED
@@ -0,0 +1,151 @@
1
+ """
2
+ Motifs found by scanning each region's sequence with matrices: the second way to say which motifs a region carries,
3
+ beside its seqlets. It lets co-occurrence be counted both ways (diffgrammar.view.data, source='scan'), and it reads
4
+ the motifs of regions that have no attributions (diffgrammar.pair_regression).
5
+
6
+ A motif key is scanned with the JASPAR matrices that best match its clusters (the families step's matrix_id;
7
+ key_matrices) or, at the cluster level, where clusters that share a best match must stay apart, with each cluster's own
8
+ sequence frequencies, from its members and a few bp around them, over its informative columns (cluster_matrices), by
9
+ FIMO (memesuite-lite, both strands, p < threshold), over the central `window` bp of each region's input: by default
10
+ the whole input, the same sequence the attributions cover. A key is present
11
+ in a region where any of its matrices hits. A matrix of n bp cannot reach a p below 4^-n, so one shorter than 7 bp
12
+ never passes the default threshold of 1e-4: scan leaves such matrices out (reachable), as memelite would otherwise
13
+ report their exact matches with p = 0.
14
+
15
+ from diffgrammar import scan
16
+ hits = scan.scan(onehot, {'MA0511.2': pwm}) # FIMO hits in sequences (N, 4, L)
17
+ """
18
+ from __future__ import annotations
19
+
20
+ from typing import Callable, Dict, Optional
21
+
22
+ import numpy as np
23
+ import pandas as pd
24
+
25
+ from .sequence import one_hot
26
+
27
+ #: [cooccurrence] settings of the scanning source
28
+ SCAN_DEFAULTS = {'scan_threshold': 1e-4, 'scan_window': None}
29
+ HIT_COLUMNS = ['seq', 'matrix', 'start', 'end', 'strand', 'score', 'p']
30
+
31
+
32
+ def key_matrices(an, labels: pd.DataFrame) -> Dict[str, Dict[str, np.ndarray]]:
33
+ """
34
+ key -> {matrix id: probability matrix (4, length)}: the best JASPAR match of each of the key's clusters (labels:
35
+ view.data.motif_labels, one row per cluster with its key). Clusters without a match, or whose match is not among
36
+ the run's JASPAR matrices, add nothing.
37
+ """
38
+ ids, _, pwms = an.jaspar
39
+ pwm = dict(zip(ids, pwms))
40
+ best = an.families.set_index('cluster')['matrix_id']
41
+ out: Dict[str, Dict[str, np.ndarray]] = {}
42
+ for c, k in zip(labels['cluster'], labels['key']):
43
+ mid = best.get(c)
44
+ if isinstance(mid, str) and mid in pwm:
45
+ out.setdefault(k, {})[mid] = np.asarray(pwm[mid], float).T
46
+ return out
47
+
48
+
49
+ def cluster_pwm(pfm: np.ndarray, min_bits: float = 0.5, min_cover: float = 0.5, prior: float = 0.05) -> Optional[np.ndarray]:
50
+ """
51
+ A cluster's own probability matrix (4, length) to scan with, from its sequence frequencies (Analysis.pfms: (L, 4)
52
+ over its consensus frame and some flank, divided by the number of members, so a column sums to the share of
53
+ members whose input reaches it): each column's frequencies among those members, with a uniform prior of weight
54
+ `prior`, from the first to the last column of at least min_bits of information that min_cover of the members
55
+ reach, so flanks without a preference drop out and a gap inside the motif stays. None when no column qualifies.
56
+ """
57
+ pfm = np.asarray(pfm, float)
58
+ cover = pfm.sum(1)
59
+ q = (pfm + prior / 4) / (cover[:, None] + prior)
60
+ bits = 2 + (q * np.log2(q)).sum(1)
61
+ ok = np.flatnonzero((bits >= min_bits) & (cover >= min_cover))
62
+ return q[ok[0]:ok[-1] + 1].T if len(ok) else None
63
+
64
+
65
+ def cluster_matrices(an, labels: pd.DataFrame, **kw) -> Dict[str, Dict[str, np.ndarray]]:
66
+ """
67
+ key -> {'cl<id>': probability matrix (4, length)}: each cluster's own matrix (cluster_pwm of Analysis.pfms), for
68
+ the cluster level, where clusters that share a best JASPAR match must stay apart. labels: view.data.motif_labels.
69
+ Clusters without a column of enough information add nothing.
70
+ """
71
+ out: Dict[str, Dict[str, np.ndarray]] = {}
72
+ pfms = an.pfms
73
+ for c, k in zip(labels['cluster'], labels['key']):
74
+ m = cluster_pwm(pfms[int(c)], **kw) if int(c) in pfms else None
75
+ if m is not None:
76
+ out.setdefault(k, {})[f'cl{int(c)}'] = m
77
+ return out
78
+
79
+
80
+ def reachable(matrices: Dict[str, np.ndarray], threshold: float) -> Dict[str, np.ndarray]:
81
+ """
82
+ The matrices (4, length) that can reach a p below threshold: under FIMO's uniform background no site of a matrix of
83
+ n bp has p below 4^-n. memelite reports p = 0 for a short matrix's best sites whatever its length, so scan leaves
84
+ the others out rather than take their exact matches as hits.
85
+ """
86
+ return {k: m for k, m in matrices.items() if 0.25 ** np.asarray(m).shape[1] <= threshold}
87
+
88
+
89
+ def scan(onehot: np.ndarray, matrices: Dict[str, np.ndarray], threshold: float = 1e-4) -> pd.DataFrame:
90
+ """
91
+ FIMO hits of every matrix that can reach p < threshold (reachable) in one-hot sequences (N, 4, L): seq (its index),
92
+ matrix, start, end, strand, score, p.
93
+ """
94
+ matrices = reachable(matrices, threshold)
95
+ if not len(onehot) or not matrices:
96
+ return pd.DataFrame(columns=HIT_COLUMNS)
97
+ from memelite import fimo
98
+ hits = [h for h in fimo(matrices, np.ascontiguousarray(onehot, dtype=np.float32), threshold=threshold) if len(h)]
99
+ if not hits:
100
+ return pd.DataFrame(columns=HIT_COLUMNS)
101
+ t = pd.concat(hits, ignore_index=True).rename(columns={'motif_name': 'matrix', 'sequence_name': 'seq', 'p-value': 'p'})
102
+ return t[HIT_COLUMNS].astype({'seq': int, 'start': int, 'end': int})
103
+
104
+
105
+ def central(coord: str, length: int, window: Optional[int] = None) -> slice:
106
+ """
107
+ The part of an input of `length` bp to scan: the central `window` bp, by default the whole input, so the scan
108
+ covers everything the attributions cover. Give the width of the region's coordinate interval to scan the called
109
+ region alone (250 for 'chr1:100-350') rather than the flanks the model also reads.
110
+ """
111
+ if window is None:
112
+ window = length
113
+ window = min(int(window), length)
114
+ lo = (length - window) // 2
115
+ return slice(lo, lo + window)
116
+
117
+
118
+ def region_hits(regions: pd.DataFrame, matrices: Dict[str, Dict[str, np.ndarray]], sequence: Callable[[str], str],
119
+ window: Optional[int] = None, threshold: float = 1e-4) -> pd.DataFrame:
120
+ """
121
+ Hits of every key's matrices in the central `window` bp (see central) of each region of `regions` (coord,
122
+ set_name): set_name, coord, key, matrix, start, end (input coordinates, as seqlets), strand, score, p. matrices:
123
+ key_matrices; sequence: coord -> the region's input sequence. A matrix shared by several keys counts for each.
124
+ """
125
+ by_matrix: Dict[str, list] = {}
126
+ for k, ms in matrices.items():
127
+ for mid in ms:
128
+ by_matrix.setdefault(mid, []).append(k)
129
+ pwms = {mid: next(ms[mid] for ms in matrices.values() if mid in ms) for mid in by_matrix}
130
+ rows = regions.drop_duplicates('coord').reset_index(drop=True)
131
+ cut, parts = [], {}
132
+ for coord in rows['coord']:
133
+ s = sequence(coord)
134
+ part = central(coord, len(s), window)
135
+ cut.append(part.start)
136
+ parts.setdefault(part.stop - part.start, []).append((len(cut) - 1, one_hot(s[part]).T))
137
+ out = []
138
+ for _, group in parts.items(): # FIMO wants one length per call
139
+ idx = np.array([i for i, _ in group])
140
+ hits = scan(np.stack([x for _, x in group]), pwms, threshold)
141
+ if len(hits):
142
+ hits['seq'] = idx[hits['seq'].to_numpy()]
143
+ out.append(hits)
144
+ cols = ['set_name', 'coord', 'key', 'matrix', 'start', 'end', 'strand', 'score', 'p']
145
+ if not out:
146
+ return pd.DataFrame(columns=cols)
147
+ h = pd.concat(out, ignore_index=True)
148
+ shift = np.asarray(cut)[h['seq'].to_numpy()]
149
+ h = h.assign(coord=rows['coord'].to_numpy()[h['seq']], set_name=rows['set_name'].to_numpy()[h['seq']],
150
+ start=h['start'] + shift, end=h['end'] + shift, key=h['matrix'].map(by_matrix)).explode('key')
151
+ return h[cols].sort_values(['coord', 'start', 'key'], kind='stable', ignore_index=True)
@@ -0,0 +1,174 @@
1
+ """
2
+ Which regions a run kept and why the others were left out, in one table every project can fill.
3
+
4
+ coord, set_name, contrast, stage the region, and the filter that removed it ('Included' when it was kept)
5
+ meas_a, meas_b, meas_diff measured signal of each condition and B - A, where known
6
+ pred_a, pred_b, pred_diff, log2fc the same predicted, and the fold change the selection used
7
+
8
+ Any other numeric column is kept too, so it can colour a figure. The table is read from <out_dir>/regions.parquet
9
+ (or .csv), which a project with its own selection writes and `diffgrammar export` copies; without one it is built from
10
+ the `candidates.csv` of the attribute step, the stages following from the settings recorded beside it. 'Included' always
11
+ means the region reached seqlet calling, so it is taken from thresholds.csv and the counts match the run. The filters
12
+ are listed in the order they apply, each region counted at the first it fails, as in `attribute.select_regions`.
13
+
14
+ A project that scores shuffled sequences can add <out_dir>/selection_null.parquet: contrast, condition, value and cut,
15
+ the predicted signal of each sequence and the cutoff of its model. Figures then draw peaks against that null.
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import json
20
+ import re
21
+ from pathlib import Path
22
+ from typing import List, Optional
23
+
24
+ import numpy as np
25
+ import pandas as pd
26
+
27
+ INCLUDED = 'Included'
28
+ OTHER = 'Other filters'
29
+ VALUES = ['meas_a', 'meas_b', 'meas_diff', 'pred_a', 'pred_b', 'pred_diff', 'log2fc']
30
+ OUTCOMES = ['Seqlet called', 'Above the cut, run too short', 'No position above the cut']
31
+
32
+
33
+ def candidate_files(cfg: dict) -> List[Path]:
34
+ """The candidates.csv of a run: beside the attributions, one per fold below them, or one level above them."""
35
+ roots = [Path(cfg['attribute']['out_dir'])] if cfg.get('attribute', {}).get('out_dir') else []
36
+ if cfg.get('attributions', {}).get('root'):
37
+ roots.append(Path(cfg['attributions']['root']))
38
+ for r in roots:
39
+ for found in ([r / 'candidates.csv'], sorted(r.glob('*/candidates.csv')), [r.parent / 'candidates.csv']):
40
+ found = [f for f in found if f.exists()]
41
+ if found:
42
+ return found
43
+ return []
44
+
45
+
46
+ def _settings(folder: Path) -> dict:
47
+ """The thresholds of a selection from the config.json beside its candidates; {} when it records none."""
48
+ f = folder / 'config.json'
49
+ if not f.exists():
50
+ return {}
51
+ d = json.loads(f.read_text())
52
+ s = d.get('selection') if isinstance(d.get('selection'), dict) else {}
53
+ pf = d.get('prediction_filters') if isinstance(d.get('prediction_filters'), dict) else {}
54
+ pick = lambda *keys: next((v for src in (s, d, pf) for k in keys if isinstance(v := src.get(k), (int, float))), None) # noqa: E731
55
+ frac = pick('min_pred_frac', 'pred_frac', 'min_frac')
56
+ if frac is None and isinstance(pf.get('magnitude'), str): # written out as a rule: '|pred| >= 0.4 * |meas|'
57
+ m = re.search(r'>=\s*([0-9.]+)\s*\*', pf['magnitude'])
58
+ frac = float(m.group(1)) if m else None
59
+ return {'lfc': pick('lfc', 'lfc_thresh'), 'fdr': pick('fdr', 'fdr_thresh'), 'min_signal': pick('min_signal'), 'min_pred_frac': frac}
60
+
61
+
62
+ def from_candidates(c: pd.DataFrame, contrast, settings: dict, kept: pd.DataFrame) -> pd.DataFrame:
63
+ """
64
+ The region table of one contrast from a candidates table. Column names follow the attribute step (meas_a, pred_a,
65
+ log2fc, q), or carry the condition labels instead of a / b. kept: thresholds.csv, what reached seqlet calling.
66
+ """
67
+ la, lb = contrast.label_a.lower(), contrast.label_b.lower()
68
+
69
+ def col(*names):
70
+ return next((pd.to_numeric(c[n], errors='coerce') for n in names if n in c), None)
71
+ out = pd.DataFrame({'coord': c['chrom'].astype(str) + ':' + c['start'].astype(str) + '-' + c['end'].astype(str),
72
+ 'set_name': c['class'].astype(str), 'contrast': contrast.name})
73
+ ma, mb = col('meas_a', f'meas_{la}'), col('meas_b', f'meas_{lb}')
74
+ pa, pb = col('pred_a', f'pred_{la}'), col('pred_b', f'pred_{lb}')
75
+ if ma is not None and mb is not None:
76
+ out['meas_a'], out['meas_b'], out['meas_diff'] = ma, mb, mb - ma
77
+ if pa is not None and pb is not None:
78
+ out['pred_a'], out['pred_b'], out['pred_diff'] = pa, pb, pb - pa
79
+ lfc = col('log2fc', f'log2fc_{lb}_over_{la}')
80
+ if lfc is None and f'log2fc_{la}_over_{lb}' in c:
81
+ lfc = -col(f'log2fc_{la}_over_{lb}')
82
+ if lfc is not None:
83
+ out['log2fc'] = lfc
84
+
85
+ filters = []
86
+ if settings.get('lfc') is not None and lfc is not None:
87
+ filters.append(('Below the fold-change cut', lfc.abs() < settings['lfc']))
88
+ q = col('q', 'qval')
89
+ if settings.get('fdr') is not None and q is not None and q.notna().any():
90
+ filters.append(('Not consistent across tracks', q > settings['fdr']))
91
+ signal = col('signal')
92
+ if signal is None:
93
+ signal = out[['meas_a', 'meas_b']].max(axis=1) if 'meas_a' in out else \
94
+ (out[['pred_a', 'pred_b']].max(axis=1) if 'pred_a' in out else None)
95
+ if settings.get('min_signal') is not None and signal is not None:
96
+ filters.append(('Below the signal floor', signal < settings['min_signal']))
97
+ if 'meas_diff' in out and 'pred_diff' in out:
98
+ filters.append(('Opposite direction', np.sign(out['pred_diff']) != np.sign(out['meas_diff'])))
99
+ if settings.get('min_pred_frac') is not None:
100
+ filters.append(('Insufficient magnitude', out['pred_diff'].abs() < settings['min_pred_frac'] * out['meas_diff'].abs()))
101
+ stage = pd.Series(np.select([m.to_numpy(bool) for _, m in filters], [n for n, _ in filters], OTHER) if filters else OTHER,
102
+ index=out.index, dtype=object)
103
+ keys = set(zip(kept['set_name'], kept['coord']))
104
+ stage[[k in keys for k in zip(out['set_name'], out['coord'])]] = INCLUDED
105
+ out['stage'] = stage
106
+ return out
107
+
108
+
109
+ def region_table(cfg: dict, thresholds: pd.DataFrame, contrast) -> Optional[pd.DataFrame]:
110
+ """The run's region table (see the module docstring), or None when it has none."""
111
+ out = Path(cfg['run']['out_dir'])
112
+ for f, read in ((out / 'regions.parquet', pd.read_parquet), (out / 'regions.csv', pd.read_csv)):
113
+ if f.exists():
114
+ return read(f)
115
+ files = candidate_files(cfg)
116
+ if not files:
117
+ return None
118
+ settings = _settings(files[0].parent)
119
+ frames = [from_candidates(pd.read_csv(f), contrast, settings, thresholds[thresholds['contrast'] == contrast.name])
120
+ for f in files]
121
+ return pd.concat(frames, ignore_index=True)
122
+
123
+
124
+ def stage_counts(table: pd.DataFrame) -> pd.DataFrame:
125
+ """contrast, set_name, stage, regions; the stages keep the order they first appear in, 'Included' last."""
126
+ t = table[table['stage'].notna()]
127
+ return t.groupby(['contrast', 'set_name', 'stage'], sort=False).size().rename('regions').reset_index()
128
+
129
+
130
+ def stage_order(counts: pd.DataFrame) -> List[str]:
131
+ """The stages in the order they apply, however rows happen to be sorted: known filters, then others, then 'Included'."""
132
+ known = ['Below the fold-change cut', 'Not consistent across tracks', 'Below the signal floor', 'Opposite direction',
133
+ 'Insufficient magnitude']
134
+ seen = list(dict.fromkeys(counts['stage']))
135
+ rest = [s for s in seen if s not in known and s not in (OTHER, INCLUDED)]
136
+ return [s for s in known if s in seen] + rest + [s for s in (OTHER, INCLUDED) if s in seen]
137
+
138
+
139
+ def null_table(cfg: dict) -> Optional[pd.DataFrame]:
140
+ """The predicted signal of shuffled sequences (see the module docstring), or None."""
141
+ f = Path(cfg['run']['out_dir']) / 'selection_null.parquet'
142
+ return pd.read_parquet(f) if f.exists() else None
143
+
144
+
145
+ def contrast_thresholds(thresholds: pd.DataFrame) -> pd.DataFrame:
146
+ """
147
+ thresholds.csv as one row per region and contrast: the 'diff' track's record when the run called several tracks
148
+ (contrast.TRACKS), whose budget and cut are the contrast's and whose seqlets are the differential ones; every row
149
+ otherwise (one track, or a run before tracks were stored). A run without a 'diff' track keeps its first track.
150
+ """
151
+ if 'track' not in thresholds or thresholds['track'].nunique() <= 1:
152
+ return thresholds
153
+ track = 'diff' if (thresholds['track'] == 'diff').any() else thresholds['track'].iloc[0]
154
+ return thresholds[thresholds['track'] == track].reset_index(drop=True)
155
+
156
+
157
+ def seqlet_outcomes(thresholds: pd.DataFrame) -> pd.Series:
158
+ """Per record of thresholds.csv: a seqlet was called, positions passed the cut but no run was long enough, or none did."""
159
+ return pd.Series(np.select([thresholds['n_seqlets'] > 0, thresholds['n_above_cut'] > 0], OUTCOMES[:2], OUTCOMES[2]),
160
+ index=thresholds.index)
161
+
162
+
163
+ def region_values(table: Optional[pd.DataFrame], contrast_name: str) -> pd.DataFrame:
164
+ """
165
+ One row per (set_name, coord), one column per value and contrast: 'meas_diff|ATAC'. A figure of one contrast can then
166
+ be coloured by the measurement of another. Every numeric column of the table is offered, not only the known ones.
167
+ """
168
+ if table is None or table.empty:
169
+ return pd.DataFrame(columns=['set_name', 'coord'])
170
+ cols = [c for c in table.columns if c not in ('coord', 'set_name', 'contrast', 'stage')
171
+ and pd.api.types.is_numeric_dtype(table[c])]
172
+ wide = table.drop_duplicates(['set_name', 'coord', 'contrast']).pivot(index=['set_name', 'coord'], columns='contrast', values=cols)
173
+ wide.columns = [f'{v}|{c}' for v, c in wide.columns]
174
+ return wide.dropna(axis=1, how='all').reset_index()