diffgrammar 0.1.0__tar.gz

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 (69) hide show
  1. diffgrammar-0.1.0/LICENSE +57 -0
  2. diffgrammar-0.1.0/PKG-INFO +204 -0
  3. diffgrammar-0.1.0/README.md +158 -0
  4. diffgrammar-0.1.0/pyproject.toml +69 -0
  5. diffgrammar-0.1.0/setup.cfg +4 -0
  6. diffgrammar-0.1.0/src/diffgrammar/__init__.py +6 -0
  7. diffgrammar-0.1.0/src/diffgrammar/adapters/__init__.py +21 -0
  8. diffgrammar-0.1.0/src/diffgrammar/adapters/peak_npz.py +114 -0
  9. diffgrammar-0.1.0/src/diffgrammar/align.py +195 -0
  10. diffgrammar-0.1.0/src/diffgrammar/analysis.py +744 -0
  11. diffgrammar-0.1.0/src/diffgrammar/attribute.py +445 -0
  12. diffgrammar-0.1.0/src/diffgrammar/calibrate.py +279 -0
  13. diffgrammar-0.1.0/src/diffgrammar/cli.py +659 -0
  14. diffgrammar-0.1.0/src/diffgrammar/cluster.py +439 -0
  15. diffgrammar-0.1.0/src/diffgrammar/config.py +213 -0
  16. diffgrammar-0.1.0/src/diffgrammar/contrast.py +223 -0
  17. diffgrammar-0.1.0/src/diffgrammar/effects.py +317 -0
  18. diffgrammar-0.1.0/src/diffgrammar/export.py +185 -0
  19. diffgrammar-0.1.0/src/diffgrammar/expression.py +399 -0
  20. diffgrammar-0.1.0/src/diffgrammar/jaspar.py +185 -0
  21. diffgrammar-0.1.0/src/diffgrammar/marginalize/__init__.py +4 -0
  22. diffgrammar-0.1.0/src/diffgrammar/marginalize/backgrounds.py +107 -0
  23. diffgrammar-0.1.0/src/diffgrammar/marginalize/cooperativity.py +344 -0
  24. diffgrammar-0.1.0/src/diffgrammar/marginalize/design.py +209 -0
  25. diffgrammar-0.1.0/src/diffgrammar/marginalize/plots.py +546 -0
  26. diffgrammar-0.1.0/src/diffgrammar/marginalize/predictor.py +109 -0
  27. diffgrammar-0.1.0/src/diffgrammar/marginalize/readout.py +86 -0
  28. diffgrammar-0.1.0/src/diffgrammar/marginalize/run.py +223 -0
  29. diffgrammar-0.1.0/src/diffgrammar/marginalize/store.py +191 -0
  30. diffgrammar-0.1.0/src/diffgrammar/pair_regression.py +323 -0
  31. diffgrammar-0.1.0/src/diffgrammar/plotting.py +1186 -0
  32. diffgrammar-0.1.0/src/diffgrammar/scan.py +151 -0
  33. diffgrammar-0.1.0/src/diffgrammar/selection.py +174 -0
  34. diffgrammar-0.1.0/src/diffgrammar/seqlets.py +376 -0
  35. diffgrammar-0.1.0/src/diffgrammar/sequence.py +22 -0
  36. diffgrammar-0.1.0/src/diffgrammar/summaries.py +140 -0
  37. diffgrammar-0.1.0/src/diffgrammar/toy.py +129 -0
  38. diffgrammar-0.1.0/src/diffgrammar/view/__init__.py +0 -0
  39. diffgrammar-0.1.0/src/diffgrammar/view/app.py +1942 -0
  40. diffgrammar-0.1.0/src/diffgrammar/view/data.py +1950 -0
  41. diffgrammar-0.1.0/src/diffgrammar/view/figures.py +400 -0
  42. diffgrammar-0.1.0/src/diffgrammar/view/network/index.html +232 -0
  43. diffgrammar-0.1.0/src/diffgrammar/view/network.py +21 -0
  44. diffgrammar-0.1.0/src/diffgrammar/view/pages.py +257 -0
  45. diffgrammar-0.1.0/src/diffgrammar/view/tracks/index.html +459 -0
  46. diffgrammar-0.1.0/src/diffgrammar/view/tracks.py +153 -0
  47. diffgrammar-0.1.0/src/diffgrammar.egg-info/PKG-INFO +204 -0
  48. diffgrammar-0.1.0/src/diffgrammar.egg-info/SOURCES.txt +67 -0
  49. diffgrammar-0.1.0/src/diffgrammar.egg-info/dependency_links.txt +1 -0
  50. diffgrammar-0.1.0/src/diffgrammar.egg-info/entry_points.txt +2 -0
  51. diffgrammar-0.1.0/src/diffgrammar.egg-info/requires.txt +29 -0
  52. diffgrammar-0.1.0/src/diffgrammar.egg-info/top_level.txt +1 -0
  53. diffgrammar-0.1.0/tests/test_align.py +111 -0
  54. diffgrammar-0.1.0/tests/test_analysis.py +137 -0
  55. diffgrammar-0.1.0/tests/test_attribute.py +179 -0
  56. diffgrammar-0.1.0/tests/test_by_size.py +41 -0
  57. diffgrammar-0.1.0/tests/test_calibrate.py +179 -0
  58. diffgrammar-0.1.0/tests/test_colors.py +31 -0
  59. diffgrammar-0.1.0/tests/test_core.py +340 -0
  60. diffgrammar-0.1.0/tests/test_effects.py +198 -0
  61. diffgrammar-0.1.0/tests/test_expression.py +185 -0
  62. diffgrammar-0.1.0/tests/test_expression_contacts.py +76 -0
  63. diffgrammar-0.1.0/tests/test_gene_view.py +79 -0
  64. diffgrammar-0.1.0/tests/test_marginalize.py +191 -0
  65. diffgrammar-0.1.0/tests/test_pair_regression.py +83 -0
  66. diffgrammar-0.1.0/tests/test_pipeline.py +318 -0
  67. diffgrammar-0.1.0/tests/test_single.py +130 -0
  68. diffgrammar-0.1.0/tests/test_toy.py +61 -0
  69. diffgrammar-0.1.0/tests/test_view.py +1191 -0
@@ -0,0 +1,57 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Eleni Mourouzidou
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
23
+ -------------------------------------------------------------------------------
24
+
25
+ src/diffgrammar/align.py rewrites the motif alignment and consensus functions of
26
+ drg_tools (https://github.com/sasselab/DRG), and the seqlet calling in
27
+ src/diffgrammar/seqlets.py follows its find_motifs. drg_tools is distributed
28
+ under the following license:
29
+
30
+ BSD 3-Clause License
31
+
32
+ Copyright (c) 2024, Alexander Sasse
33
+
34
+ Redistribution and use in source and binary forms, with or without
35
+ modification, are permitted provided that the following conditions are met:
36
+
37
+ 1. Redistributions of source code must retain the above copyright notice, this
38
+ list of conditions and the following disclaimer.
39
+
40
+ 2. Redistributions in binary form must reproduce the above copyright notice,
41
+ this list of conditions and the following disclaimer in the documentation
42
+ and/or other materials provided with the distribution.
43
+
44
+ 3. Neither the name of the copyright holder nor the names of its
45
+ contributors may be used to endorse or promote products derived from
46
+ this software without specific prior written permission.
47
+
48
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
49
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
50
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
51
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
52
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
53
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
54
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
55
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
56
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
57
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1,204 @@
1
+ Metadata-Version: 2.4
2
+ Name: diffgrammar
3
+ Version: 0.1.0
4
+ Summary: Differential motif grammar from sequence-to-function models: attributions of two conditions, contrast seqlets, clustering, JASPAR subfamilies and the cooperativity of motif pairs by in silico marginalization.
5
+ Author: Eleni Mourouzidou
6
+ License-Expression: MIT
7
+ Project-URL: Repository, https://github.com/sasselab/diffgrammar
8
+ Project-URL: Documentation, https://github.com/sasselab/diffgrammar/tree/main/docs
9
+ Project-URL: Changelog, https://github.com/sasselab/diffgrammar/blob/main/CHANGELOG.md
10
+ Keywords: genomics,deep learning,interpretability,motifs,attribution,sequence-to-function
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: Operating System :: POSIX :: Linux
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
19
+ Requires-Python: <3.13,>=3.10
20
+ Description-Content-Type: text/markdown
21
+ License-File: LICENSE
22
+ Requires-Dist: numpy<2,>=1.26
23
+ Requires-Dist: scipy>=1.11
24
+ Requires-Dist: pandas<3,>=2.2
25
+ Requires-Dist: scikit-learn>=1.5
26
+ Requires-Dist: matplotlib>=3.9
27
+ Requires-Dist: logomaker>=0.8
28
+ Requires-Dist: pyarrow<20,>=17
29
+ Requires-Dist: requests
30
+ Requires-Dist: pyfaidx>=0.8
31
+ Requires-Dist: torch>=2.4
32
+ Requires-Dist: tangermeme>=1.0
33
+ Requires-Dist: memelite>=0.5
34
+ Requires-Dist: tomli>=2; python_version < "3.11"
35
+ Provides-Extra: view
36
+ Requires-Dist: streamlit>=1.66; extra == "view"
37
+ Provides-Extra: notebooks
38
+ Requires-Dist: ipykernel; extra == "notebooks"
39
+ Requires-Dist: ipywidgets; extra == "notebooks"
40
+ Requires-Dist: nbconvert; extra == "notebooks"
41
+ Provides-Extra: test
42
+ Requires-Dist: pytest>=8; extra == "test"
43
+ Provides-Extra: grelu
44
+ Requires-Dist: grelu==1.0.10; extra == "grelu"
45
+ Dynamic: license-file
46
+
47
+ # diffgrammar
48
+
49
+ Differential motif grammar from sequence-to-function models. Give diffgrammar a trained model and two conditions (two
50
+ cell types, two genotypes, two groups of output tracks). It picks the regions the model separates between them,
51
+ attributes each condition, finds the motif instances that drive the difference, groups them into motifs and JASPAR
52
+ families, and, for motif pairs you name, measures how they combine in each condition by in silico marginalization.
53
+ A browser viewer shows the result. The same pipeline also analyses output tracks one at a time, without a
54
+ comparison (single-track runs).
55
+
56
+ ![The diffgrammar pipeline: inputs, the attribute and marginalize steps that run the model, and the seqlets, cluster, families and report steps that need only diffgrammar](https://raw.githubusercontent.com/sasselab/diffgrammar/main/docs/images/pipeline.png)
57
+
58
+ ## Install
59
+
60
+ ```bash
61
+ git clone https://github.com/sasselab/diffgrammar.git
62
+ cd diffgrammar
63
+ conda env create -f environment.yml
64
+ conda activate diffgrammar
65
+ python -m ipykernel install --user --name diffgrammar --display-name diffgrammar # for the tutorial notebooks
66
+ ```
67
+
68
+ This one environment runs the whole pipeline, the viewer, the tests and the tutorials, gReLU models included. It
69
+ installs the CUDA 12.8 build of torch; on a machine without a GPU, change `cu128` to `cpu` in `environment.yml`.
70
+
71
+ To install into an environment you already have: `pip install -e ".[view]"`, adding `grelu` for gReLU model-zoo
72
+ models and `notebooks` for the tutorials. diffgrammar pins `numpy<2`, `pandas<3` and `pyarrow<20`.
73
+
74
+ **A model with its own environment.** Only two steps run the model, `attribute` and `marginalize`; the rest need only
75
+ diffgrammar. When a model needs packages that conflict with diffgrammar's pins, add diffgrammar to the model's
76
+ environment without its dependencies (`pip install --no-deps -e /path/to/diffgrammar`), run the model steps there,
77
+ and the rest in the diffgrammar environment. The Decima tutorial works this way.
78
+
79
+ ## Quick start
80
+
81
+ A run is one TOML config. A minimal one:
82
+
83
+ ```toml
84
+ [run]
85
+ out_dir = "results"
86
+
87
+ [attribute]
88
+ predictor = "my_model.py:make_predictor" # a function returning the model, see "Your model" below
89
+ regions = "regions.csv" # chrom, start, end, and a measured value per model track if you have them
90
+ genome = "hg38.fa"
91
+ seq_len = 200 # the model's input length
92
+ a = ["K562"] # condition A: model output tracks
93
+ b = ["HepG2"] # condition B
94
+ label_a = "K562"
95
+ label_b = "HepG2"
96
+ transform = "sigmoid" # the model output back to signal: sigmoid, pow2m1, exp or identity
97
+ holdout_chroms = ["chr10", "chr11"]
98
+
99
+ [marginalize] # optional: motif pairs to test
100
+ pairs = [["HNF4A", "FOXA2"], ["GATA", "AP1"]]
101
+ motifs = { HNF4A = "RGTCCAAAGGTCA", FOXA2 = "GTAAACA", GATA = "TTATCW", AP1 = "RTGACTCA" }
102
+ ```
103
+
104
+ ```bash
105
+ diffgrammar pipeline config.toml # every step, in order
106
+ diffgrammar pipeline config.toml --max-regions 200 # a quick check on the first regions
107
+ diffgrammar view # the result in the browser
108
+ ```
109
+
110
+ Each step also runs alone, `diffgrammar <step> config.toml`:
111
+
112
+ | Step | What it does | Writes, under `out_dir` |
113
+ |---|---|---|
114
+ | `attribute` | chooses the regions the model separates and attributes both conditions (runs the model) | `attributions/` |
115
+ | `seqlets` | calls seqlets on each condition and on their difference, at a cut calibrated on the run | `seqlets/`, `thresholds.csv`, `seqlet_settings.json` |
116
+ | `cluster` | merges each site's seqlets across tracks and clusters them into motifs | `cluster_summary.csv`, `cluster_consensus/`, `merged_seqlets/` |
117
+ | `families` | names each motif by its best JASPAR matrix, family and subfamily | `jaspar_matches.json`, `families/` |
118
+ | `report` | motif tables and figures | `report/` |
119
+ | `marginalize` | inserts motif pairs into backgrounds and reads their cooperativity (runs the model) | `marginalize/` |
120
+ | `pair-regression` | fits every motif pair against a measured fold change | `pair_regression/` |
121
+
122
+ `marginalize run` computes only the pairs a store does not hold yet, so pairs can be added later. Every step appends
123
+ its settings, the diffgrammar version and git commit to `run.json`.
124
+
125
+ ## Your model
126
+
127
+ A model is a torch module that takes one-hot sequence `(N, 4, L)`, bases in the order A, C, G, T, and returns
128
+ `(N, tracks)` or `(N, tracks, bins)`. Wrap it with a name for each output track, in a function the config can name:
129
+
130
+ ```python
131
+ # my_model.py
132
+ from diffgrammar.marginalize import TorchEnsemble
133
+
134
+ def make_predictor():
135
+ model = ... # load your trained model
136
+ return TorchEnsemble([model], member_names=['model'], all_tracks=['GM12878', 'HepG2', 'K562'])
137
+ ```
138
+
139
+ Several models (cross-validation folds) go in as several members. Any gReLU model-zoo model loads with
140
+ `predictor = "diffgrammar.marginalize.predictor:grelu_zoo"` and `predictor_kwargs = { project = "..." }`. From Python,
141
+ pass the object instead: `Analysis('config.toml', predictor=pred)` (`docs/python.md`).
142
+
143
+ Attributions made elsewhere can be read too: name them in `[attributions]` and the conditions in `[contrasts]`
144
+ instead of `[attribute]` (`docs/config.md`).
145
+
146
+ **One track at a time.** To ask what the model uses for each output on its own, without comparing two conditions,
147
+ list the tracks in place of `a` and `b`. Each becomes its own run in `results/<track>`, and every command takes
148
+ `--track` to pick one:
149
+
150
+ ```toml
151
+ [attribute]
152
+ tracks = ["HepG2", "K562"]
153
+ min_signal = 0.5 # the track's measured signal, where the region table has it
154
+ min_pred = 0.5 # and its predicted signal
155
+ ```
156
+
157
+ A seqlet then raises or lowers its track. See "Single-track runs" in `docs/config.md`.
158
+
159
+ ## Tutorials
160
+
161
+ | Tutorial | What it shows | Needs |
162
+ |---|---|---|
163
+ | [`tutorials/toy`](https://github.com/sasselab/diffgrammar/blob/main/tutorials/toy/tutorial.ipynb) | every step on a toy model with a planted grammar, each output checked against the answer | a CPU, about a minute |
164
+ | [`tutorials/toy/single_tracks`](https://github.com/sasselab/diffgrammar/blob/main/tutorials/toy/single_tracks.ipynb) | the same toy as two single-track runs: what the model uses for each output on its own | a CPU, about a minute |
165
+ | [`tutorials/hepg2_vs_k562`](https://github.com/sasselab/diffgrammar/blob/main/tutorials/hepg2_vs_k562/README.md) | the same steps on a public gReLU model-zoo classifier, HepG2 against K562 accessibility | a GPU and the hg38 genome |
166
+ | [`tutorials/hepg2_vs_k562/single_tracks`](https://github.com/sasselab/diffgrammar/blob/main/tutorials/hepg2_vs_k562/single_tracks.ipynb) | HepG2 and K562 each on its own with the same model, next to the comparison: what each cell line uses, shared motifs such as CTCF included | a GPU and the hg38 genome |
167
+ | [`tutorials/decima`](https://github.com/sasselab/diffgrammar/blob/main/tutorials/decima/README.md) | a gene-expression model with 524 kb inputs (Decima), lung against heart macrophages, attributions made in the model's own environment | a GPU and a decima environment |
168
+
169
+ Start with the toy: it is the step-by-step guide, and its answers are known.
170
+
171
+ ## Viewer
172
+
173
+ ![The viewer's Families page: motif families with their regions per class, and the cluster figure of the selected family](https://raw.githubusercontent.com/sasselab/diffgrammar/main/docs/images/viewer_families.png)
174
+
175
+ `diffgrammar view`, in the folder of a run's config, opens the run in the browser: the motif families with their
176
+ logos and regions down to single bases, which motifs occur together and whether that differs between the
177
+ conditions, one motif's effect against another's per region, and the cooperativity of the marginalized pairs. It
178
+ needs no GPU and no model. `diffgrammar export` packs a run into a small folder that someone else opens the same
179
+ way. See `docs/viewer.md`.
180
+
181
+ ## Documentation
182
+
183
+ | | |
184
+ |---|---|
185
+ | [`docs/config.md`](https://github.com/sasselab/diffgrammar/blob/main/docs/config.md) | every config section and setting, with its default |
186
+ | [`docs/methods.md`](https://github.com/sasselab/diffgrammar/blob/main/docs/methods.md) | what each step computes, and the statistics of the viewer |
187
+ | [`docs/viewer.md`](https://github.com/sasselab/diffgrammar/blob/main/docs/viewer.md) | the viewer's pages and sharing a run |
188
+ | [`docs/python.md`](https://github.com/sasselab/diffgrammar/blob/main/docs/python.md) | `Analysis`, the model wrapper and the modules |
189
+
190
+ ## Tests
191
+
192
+ ```bash
193
+ pytest
194
+ ```
195
+
196
+ The tests run on synthetic data, without project files or a GPU: the attribution convention against captum, region
197
+ selection, seqlet calling and calibration, clustering, marginalization (a linear model is exactly additive, a planted
198
+ interaction is recovered in the right condition), the whole pipeline on a toy model, and every viewer page rendered
199
+ headless.
200
+
201
+ ## License
202
+
203
+ MIT, see `LICENSE`. The motif alignment (`diffgrammar.align`) reimplements functions of
204
+ [drg_tools](https://github.com/sasselab/DRG) by Alexander Sasse (BSD 3-clause), whose notice is included in `LICENSE`.
@@ -0,0 +1,158 @@
1
+ # diffgrammar
2
+
3
+ Differential motif grammar from sequence-to-function models. Give diffgrammar a trained model and two conditions (two
4
+ cell types, two genotypes, two groups of output tracks). It picks the regions the model separates between them,
5
+ attributes each condition, finds the motif instances that drive the difference, groups them into motifs and JASPAR
6
+ families, and, for motif pairs you name, measures how they combine in each condition by in silico marginalization.
7
+ A browser viewer shows the result. The same pipeline also analyses output tracks one at a time, without a
8
+ comparison (single-track runs).
9
+
10
+ ![The diffgrammar pipeline: inputs, the attribute and marginalize steps that run the model, and the seqlets, cluster, families and report steps that need only diffgrammar](https://raw.githubusercontent.com/sasselab/diffgrammar/main/docs/images/pipeline.png)
11
+
12
+ ## Install
13
+
14
+ ```bash
15
+ git clone https://github.com/sasselab/diffgrammar.git
16
+ cd diffgrammar
17
+ conda env create -f environment.yml
18
+ conda activate diffgrammar
19
+ python -m ipykernel install --user --name diffgrammar --display-name diffgrammar # for the tutorial notebooks
20
+ ```
21
+
22
+ This one environment runs the whole pipeline, the viewer, the tests and the tutorials, gReLU models included. It
23
+ installs the CUDA 12.8 build of torch; on a machine without a GPU, change `cu128` to `cpu` in `environment.yml`.
24
+
25
+ To install into an environment you already have: `pip install -e ".[view]"`, adding `grelu` for gReLU model-zoo
26
+ models and `notebooks` for the tutorials. diffgrammar pins `numpy<2`, `pandas<3` and `pyarrow<20`.
27
+
28
+ **A model with its own environment.** Only two steps run the model, `attribute` and `marginalize`; the rest need only
29
+ diffgrammar. When a model needs packages that conflict with diffgrammar's pins, add diffgrammar to the model's
30
+ environment without its dependencies (`pip install --no-deps -e /path/to/diffgrammar`), run the model steps there,
31
+ and the rest in the diffgrammar environment. The Decima tutorial works this way.
32
+
33
+ ## Quick start
34
+
35
+ A run is one TOML config. A minimal one:
36
+
37
+ ```toml
38
+ [run]
39
+ out_dir = "results"
40
+
41
+ [attribute]
42
+ predictor = "my_model.py:make_predictor" # a function returning the model, see "Your model" below
43
+ regions = "regions.csv" # chrom, start, end, and a measured value per model track if you have them
44
+ genome = "hg38.fa"
45
+ seq_len = 200 # the model's input length
46
+ a = ["K562"] # condition A: model output tracks
47
+ b = ["HepG2"] # condition B
48
+ label_a = "K562"
49
+ label_b = "HepG2"
50
+ transform = "sigmoid" # the model output back to signal: sigmoid, pow2m1, exp or identity
51
+ holdout_chroms = ["chr10", "chr11"]
52
+
53
+ [marginalize] # optional: motif pairs to test
54
+ pairs = [["HNF4A", "FOXA2"], ["GATA", "AP1"]]
55
+ motifs = { HNF4A = "RGTCCAAAGGTCA", FOXA2 = "GTAAACA", GATA = "TTATCW", AP1 = "RTGACTCA" }
56
+ ```
57
+
58
+ ```bash
59
+ diffgrammar pipeline config.toml # every step, in order
60
+ diffgrammar pipeline config.toml --max-regions 200 # a quick check on the first regions
61
+ diffgrammar view # the result in the browser
62
+ ```
63
+
64
+ Each step also runs alone, `diffgrammar <step> config.toml`:
65
+
66
+ | Step | What it does | Writes, under `out_dir` |
67
+ |---|---|---|
68
+ | `attribute` | chooses the regions the model separates and attributes both conditions (runs the model) | `attributions/` |
69
+ | `seqlets` | calls seqlets on each condition and on their difference, at a cut calibrated on the run | `seqlets/`, `thresholds.csv`, `seqlet_settings.json` |
70
+ | `cluster` | merges each site's seqlets across tracks and clusters them into motifs | `cluster_summary.csv`, `cluster_consensus/`, `merged_seqlets/` |
71
+ | `families` | names each motif by its best JASPAR matrix, family and subfamily | `jaspar_matches.json`, `families/` |
72
+ | `report` | motif tables and figures | `report/` |
73
+ | `marginalize` | inserts motif pairs into backgrounds and reads their cooperativity (runs the model) | `marginalize/` |
74
+ | `pair-regression` | fits every motif pair against a measured fold change | `pair_regression/` |
75
+
76
+ `marginalize run` computes only the pairs a store does not hold yet, so pairs can be added later. Every step appends
77
+ its settings, the diffgrammar version and git commit to `run.json`.
78
+
79
+ ## Your model
80
+
81
+ A model is a torch module that takes one-hot sequence `(N, 4, L)`, bases in the order A, C, G, T, and returns
82
+ `(N, tracks)` or `(N, tracks, bins)`. Wrap it with a name for each output track, in a function the config can name:
83
+
84
+ ```python
85
+ # my_model.py
86
+ from diffgrammar.marginalize import TorchEnsemble
87
+
88
+ def make_predictor():
89
+ model = ... # load your trained model
90
+ return TorchEnsemble([model], member_names=['model'], all_tracks=['GM12878', 'HepG2', 'K562'])
91
+ ```
92
+
93
+ Several models (cross-validation folds) go in as several members. Any gReLU model-zoo model loads with
94
+ `predictor = "diffgrammar.marginalize.predictor:grelu_zoo"` and `predictor_kwargs = { project = "..." }`. From Python,
95
+ pass the object instead: `Analysis('config.toml', predictor=pred)` (`docs/python.md`).
96
+
97
+ Attributions made elsewhere can be read too: name them in `[attributions]` and the conditions in `[contrasts]`
98
+ instead of `[attribute]` (`docs/config.md`).
99
+
100
+ **One track at a time.** To ask what the model uses for each output on its own, without comparing two conditions,
101
+ list the tracks in place of `a` and `b`. Each becomes its own run in `results/<track>`, and every command takes
102
+ `--track` to pick one:
103
+
104
+ ```toml
105
+ [attribute]
106
+ tracks = ["HepG2", "K562"]
107
+ min_signal = 0.5 # the track's measured signal, where the region table has it
108
+ min_pred = 0.5 # and its predicted signal
109
+ ```
110
+
111
+ A seqlet then raises or lowers its track. See "Single-track runs" in `docs/config.md`.
112
+
113
+ ## Tutorials
114
+
115
+ | Tutorial | What it shows | Needs |
116
+ |---|---|---|
117
+ | [`tutorials/toy`](https://github.com/sasselab/diffgrammar/blob/main/tutorials/toy/tutorial.ipynb) | every step on a toy model with a planted grammar, each output checked against the answer | a CPU, about a minute |
118
+ | [`tutorials/toy/single_tracks`](https://github.com/sasselab/diffgrammar/blob/main/tutorials/toy/single_tracks.ipynb) | the same toy as two single-track runs: what the model uses for each output on its own | a CPU, about a minute |
119
+ | [`tutorials/hepg2_vs_k562`](https://github.com/sasselab/diffgrammar/blob/main/tutorials/hepg2_vs_k562/README.md) | the same steps on a public gReLU model-zoo classifier, HepG2 against K562 accessibility | a GPU and the hg38 genome |
120
+ | [`tutorials/hepg2_vs_k562/single_tracks`](https://github.com/sasselab/diffgrammar/blob/main/tutorials/hepg2_vs_k562/single_tracks.ipynb) | HepG2 and K562 each on its own with the same model, next to the comparison: what each cell line uses, shared motifs such as CTCF included | a GPU and the hg38 genome |
121
+ | [`tutorials/decima`](https://github.com/sasselab/diffgrammar/blob/main/tutorials/decima/README.md) | a gene-expression model with 524 kb inputs (Decima), lung against heart macrophages, attributions made in the model's own environment | a GPU and a decima environment |
122
+
123
+ Start with the toy: it is the step-by-step guide, and its answers are known.
124
+
125
+ ## Viewer
126
+
127
+ ![The viewer's Families page: motif families with their regions per class, and the cluster figure of the selected family](https://raw.githubusercontent.com/sasselab/diffgrammar/main/docs/images/viewer_families.png)
128
+
129
+ `diffgrammar view`, in the folder of a run's config, opens the run in the browser: the motif families with their
130
+ logos and regions down to single bases, which motifs occur together and whether that differs between the
131
+ conditions, one motif's effect against another's per region, and the cooperativity of the marginalized pairs. It
132
+ needs no GPU and no model. `diffgrammar export` packs a run into a small folder that someone else opens the same
133
+ way. See `docs/viewer.md`.
134
+
135
+ ## Documentation
136
+
137
+ | | |
138
+ |---|---|
139
+ | [`docs/config.md`](https://github.com/sasselab/diffgrammar/blob/main/docs/config.md) | every config section and setting, with its default |
140
+ | [`docs/methods.md`](https://github.com/sasselab/diffgrammar/blob/main/docs/methods.md) | what each step computes, and the statistics of the viewer |
141
+ | [`docs/viewer.md`](https://github.com/sasselab/diffgrammar/blob/main/docs/viewer.md) | the viewer's pages and sharing a run |
142
+ | [`docs/python.md`](https://github.com/sasselab/diffgrammar/blob/main/docs/python.md) | `Analysis`, the model wrapper and the modules |
143
+
144
+ ## Tests
145
+
146
+ ```bash
147
+ pytest
148
+ ```
149
+
150
+ The tests run on synthetic data, without project files or a GPU: the attribution convention against captum, region
151
+ selection, seqlet calling and calibration, clustering, marginalization (a linear model is exactly additive, a planted
152
+ interaction is recovered in the right condition), the whole pipeline on a toy model, and every viewer page rendered
153
+ headless.
154
+
155
+ ## License
156
+
157
+ MIT, see `LICENSE`. The motif alignment (`diffgrammar.align`) reimplements functions of
158
+ [drg_tools](https://github.com/sasselab/DRG) by Alexander Sasse (BSD 3-clause), whose notice is included in `LICENSE`.
@@ -0,0 +1,69 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "diffgrammar"
7
+ version = "0.1.0"
8
+ description = "Differential motif grammar from sequence-to-function models: attributions of two conditions, contrast seqlets, clustering, JASPAR subfamilies and the cooperativity of motif pairs by in silico marginalization."
9
+ readme = "README.md"
10
+ requires-python = ">=3.10,<3.13" # numpy < 2 has no wheels for Python 3.13
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ keywords = ["genomics", "deep learning", "interpretability", "motifs", "attribution", "sequence-to-function"]
14
+ authors = [{ name = "Eleni Mourouzidou" }]
15
+ classifiers = [
16
+ "Development Status :: 3 - Alpha",
17
+ "Intended Audience :: Science/Research",
18
+ "Operating System :: POSIX :: Linux",
19
+ "Programming Language :: Python :: 3",
20
+ "Programming Language :: Python :: 3.10",
21
+ "Programming Language :: Python :: 3.11",
22
+ "Programming Language :: Python :: 3.12",
23
+ "Topic :: Scientific/Engineering :: Bio-Informatics",
24
+ ]
25
+ dependencies = [
26
+ "numpy>=1.26,<2",
27
+ "scipy>=1.11",
28
+ "pandas>=2.2,<3",
29
+ "scikit-learn>=1.5",
30
+ "matplotlib>=3.9",
31
+ "logomaker>=0.8",
32
+ "pyarrow>=17,<20",
33
+ "requests",
34
+ "pyfaidx>=0.8",
35
+ "torch>=2.4",
36
+ "tangermeme>=1.0",
37
+ "memelite>=0.5",
38
+ "tomli>=2; python_version < '3.11'",
39
+ ]
40
+
41
+ [project.urls]
42
+ Repository = "https://github.com/sasselab/diffgrammar"
43
+ Documentation = "https://github.com/sasselab/diffgrammar/tree/main/docs"
44
+ Changelog = "https://github.com/sasselab/diffgrammar/blob/main/CHANGELOG.md"
45
+
46
+ [project.optional-dependencies]
47
+ # diffgrammar view: a finished run in the browser
48
+ view = ["streamlit>=1.66"]
49
+ # the tutorial notebooks
50
+ notebooks = ["ipykernel", "ipywidgets", "nbconvert"]
51
+ test = ["pytest>=8"]
52
+ # gReLU model-zoo models (marginalize.predictor.grelu_zoo) and the HepG2 vs K562 tutorial; 1.0.10 runs with numpy < 2
53
+ grelu = ["grelu==1.0.10"]
54
+
55
+ [project.scripts]
56
+ diffgrammar = "diffgrammar.cli:main"
57
+
58
+ [tool.setuptools.package-data]
59
+ diffgrammar = ["view/network/*.html", "view/tracks/*.html"]
60
+
61
+ [tool.setuptools.packages.find]
62
+ where = ["src"]
63
+
64
+ [tool.pytest.ini_options]
65
+ testpaths = ["tests"]
66
+ markers = [
67
+ "golden: compares against stored outputs of an existing project; skipped when that data is absent",
68
+ "gpu: needs a CUDA device",
69
+ ]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,6 @@
1
+ """diffgrammar: differential motif grammar from sequence-to-function models."""
2
+ __version__ = '0.1.0'
3
+
4
+ from .contrast import Contrast, RegionAttributions, contrast_record, iter_records
5
+ from .seqlets import SeqletCollection, collect_seqlets, apply_polarity
6
+ from .analysis import Analysis, Example
@@ -0,0 +1,21 @@
1
+ """
2
+ Adapters read stored attributions and yield `RegionAttributions`.
3
+
4
+ Every adapter takes its settings from the `[attributions]` table of a run config and exposes
5
+ tracks : the track names it can deliver
6
+ regions() : an iterator of RegionAttributions
7
+ `diffgrammar attribute` writes the `peak_npz` layout; attributions computed elsewhere can be saved in it, or
8
+ read by a new adapter. Everything downstream is shared.
9
+ """
10
+ from .peak_npz import PeakNpzSource
11
+
12
+ ADAPTERS = {
13
+ 'peak_npz': PeakNpzSource, # one file per peak, (K, L, 4) over K tracks with metadata
14
+ }
15
+
16
+
17
+ def make_source(cfg: dict):
18
+ kind = cfg.get('adapter')
19
+ if kind not in ADAPTERS:
20
+ raise ValueError(f'unknown adapter {kind!r}; available: {sorted(ADAPTERS)}')
21
+ return ADAPTERS[kind](**{k: v for k, v in cfg.items() if k != 'adapter'})
@@ -0,0 +1,114 @@
1
+ """
2
+ One npz per peak holding every track at once (what `diffgrammar attribute` writes).
3
+
4
+ <root>/<fold dir>/peaks/<chrom>_<summit>.npz
5
+ hypothetical (K, L, 4) sequence (4, L) uint8 celltypes (K,) metadata (JSON string)
6
+
7
+ The region set of a peak is a metadata field (`set_field`, default 'class', e.g. HepG2_high /
8
+ K562_high). A `budgets` metadata field, contrast name -> signed dF(x) - dF(reference), carries stored
9
+ budgets for `[seqlets] budget = "stored"` (attributions made outside the attribute step). The region id is '<chrom>:<start>-<end>' of the peak when the metadata gives the
10
+ coordinates, else the peak id. Seqlet positions are always in input coordinates (0..L).
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import json
15
+ import re
16
+ from pathlib import Path
17
+ from typing import Iterator, List, Optional, Sequence
18
+
19
+ import numpy as np
20
+
21
+ from ..contrast import RegionAttributions
22
+
23
+
24
+ class PeakNpzSource:
25
+ def __init__(self, root: str, pattern: str = '*/peaks/*.npz', set_field: str = 'class',
26
+ sets: Optional[Sequence[str]] = None, tracks: Optional[Sequence[str]] = None,
27
+ info_fields: Sequence[str] = ('fold', 'peak_id'), max_regions: Optional[int] = None):
28
+ self.root = Path(root)
29
+ self.pattern = pattern
30
+ self.set_field = set_field
31
+ self.sets = set(sets) if sets else None
32
+ self._tracks = list(tracks) if tracks else None
33
+ self.info_fields = list(info_fields)
34
+ self.max_regions = max_regions
35
+
36
+ def files(self) -> List[Path]:
37
+ f = sorted(self.root.glob(self.pattern))
38
+ return f[:self.max_regions] if self.max_regions else f
39
+
40
+ @property
41
+ def tracks(self) -> List[str]:
42
+ if self._tracks is None:
43
+ self._tracks = [str(t) for t in np.load(self.files()[0])['celltypes']]
44
+ return self._tracks
45
+
46
+ def metadata(self, path) -> dict:
47
+ return json.loads(str(np.load(path, allow_pickle=True)['metadata']))
48
+
49
+ def region(self, path) -> Optional[RegionAttributions]:
50
+ """One peak file as RegionAttributions; None when its set is filtered out."""
51
+ d = np.load(path, allow_pickle=True)
52
+ meta = json.loads(str(d['metadata']))
53
+ set_name = str(meta.get(self.set_field, ''))
54
+ if self.sets is not None and set_name not in self.sets:
55
+ return None
56
+ names = [str(t) for t in d['celltypes']]
57
+ keep = self._tracks or names
58
+ hyp_all = d['hypothetical']
59
+ hyp = {t: hyp_all[i] for i, t in enumerate(names) if t in keep}
60
+ region = (f"{meta['chrom']}:{meta['start']}-{meta['end']}"
61
+ if {'chrom', 'start', 'end'} <= set(meta) else meta.get('peak_id', Path(path).stem))
62
+ return RegionAttributions(region=region, set_name=set_name,
63
+ onehot=np.asarray(d['sequence'], np.float32).T, hypothetical=hyp,
64
+ budgets={k: float(v) for k, v in meta.get('budgets', {}).items()},
65
+ info={k: meta[k] for k in self.info_fields if k in meta})
66
+
67
+ def _region_of(self, path) -> str:
68
+ m = self.metadata(path)
69
+ return f"{m['chrom']}:{m['start']}-{m['end']}" if {'chrom', 'start', 'end'} <= set(m) else m.get('peak_id', Path(path).stem)
70
+
71
+ def paths_for(self, coord: str) -> List[Path]:
72
+ """
73
+ Every file of the peak 'chrom:start-end', or of the peak id when the metadata gives no coordinates: a peak in
74
+ several region sets has one per set. Files named <chrom>_<summit> are found by name from an index built once, and
75
+ checked, since a neighbouring peak's summit can fall inside the window too; any other naming, and every peak id,
76
+ falls back to an index of every file's metadata, built once.
77
+ """
78
+ m = re.fullmatch(r'(.+):(\d+)-(\d+)', coord)
79
+ if m:
80
+ chrom, start, end = m[1], int(m[2]), int(m[3])
81
+ if not hasattr(self, '_name_index'):
82
+ index: dict = {}
83
+ for f in self.files():
84
+ c, _, tail = f.stem.rpartition('_')
85
+ if tail.isdigit():
86
+ index.setdefault(c, []).append((int(tail), f))
87
+ self._name_index = index
88
+ near = [(abs(summit - (start + end) // 2), str(f), f) for summit, f in self._name_index.get(chrom, []) if start <= summit <= end]
89
+ found = [f for _, _, f in sorted(near) if self._region_of(f) == coord]
90
+ if found:
91
+ return found
92
+ if not hasattr(self, '_coord_index'):
93
+ self._coord_index = {}
94
+ for f in self.files():
95
+ self._coord_index.setdefault(self._region_of(f), []).append(f)
96
+ return list(self._coord_index.get(coord, []))
97
+
98
+ def sequence(self, coord: str) -> str:
99
+ """The input sequence of a peak as a string, read without loading its attributions."""
100
+ from ..sequence import decode
101
+ return decode(np.load(self.path_for(coord))['sequence'])
102
+
103
+ def path_for(self, coord: str) -> Path:
104
+ """The file of the peak 'chrom:start-end' (the first, when it is in several region sets)."""
105
+ found = self.paths_for(coord)
106
+ if not found:
107
+ raise KeyError(coord)
108
+ return found[0]
109
+
110
+ def regions(self) -> Iterator[RegionAttributions]:
111
+ for path in self.files():
112
+ r = self.region(path)
113
+ if r is not None:
114
+ yield r