ewht 0.0.1__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.
- ewht-0.0.1/LICENSE +21 -0
- ewht-0.0.1/PKG-INFO +218 -0
- ewht-0.0.1/README.md +182 -0
- ewht-0.0.1/ewht/__init__.py +39 -0
- ewht-0.0.1/ewht/_columns.py +49 -0
- ewht-0.0.1/ewht/_genotype.py +151 -0
- ewht-0.0.1/ewht/_io.py +59 -0
- ewht-0.0.1/ewht/_ordering.py +31 -0
- ewht-0.0.1/ewht/_validate.py +26 -0
- ewht-0.0.1/ewht/basis.py +166 -0
- ewht-0.0.1/ewht/cs.py +283 -0
- ewht-0.0.1/ewht/data.py +281 -0
- ewht-0.0.1/ewht/ewht.py +328 -0
- ewht-0.0.1/ewht/example_data/cr6261.a2m +129416 -0
- ewht-0.0.1/ewht/example_data/cr6261_h1_mean.csv +2049 -0
- ewht-0.0.1/ewht/example_data/cr6261_ps.npy +0 -0
- ewht-0.0.1/ewht/examples.py +58 -0
- ewht-0.0.1/ewht/ps/__init__.py +3 -0
- ewht-0.0.1/ewht/ps/_constants.py +9 -0
- ewht-0.0.1/ewht/ps/_parse.py +61 -0
- ewht-0.0.1/ewht/ps/compute.py +61 -0
- ewht-0.0.1/ewht/ps/esm.py +96 -0
- ewht-0.0.1/ewht/ps/msa.py +104 -0
- ewht-0.0.1/ewht.egg-info/PKG-INFO +218 -0
- ewht-0.0.1/ewht.egg-info/SOURCES.txt +28 -0
- ewht-0.0.1/ewht.egg-info/dependency_links.txt +1 -0
- ewht-0.0.1/ewht.egg-info/requires.txt +16 -0
- ewht-0.0.1/ewht.egg-info/top_level.txt +1 -0
- ewht-0.0.1/pyproject.toml +59 -0
- ewht-0.0.1/setup.cfg +4 -0
ewht-0.0.1/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 the eWHT team
|
|
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.
|
ewht-0.0.1/PKG-INFO
ADDED
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: ewht
|
|
3
|
+
Version: 0.0.1
|
|
4
|
+
Summary: Evolutionary Walsh-Hadamard transform and compressed sensing for protein fitness landscapes
|
|
5
|
+
Author: Amir Group
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/amirgroup-codes/ewht
|
|
8
|
+
Project-URL: Repository, https://github.com/amirgroup-codes/ewht
|
|
9
|
+
Project-URL: Documentation, https://github.com/amirgroup-codes/ewht#readme
|
|
10
|
+
Keywords: walsh-hadamard,fitness-landscape,deep-mutational-scanning,compressed-sensing,protein-engineering
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Intended Audience :: Science/Research
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
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.9
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
License-File: LICENSE
|
|
22
|
+
Requires-Dist: numpy
|
|
23
|
+
Requires-Dist: pandas
|
|
24
|
+
Requires-Dist: scipy
|
|
25
|
+
Requires-Dist: scikit-learn
|
|
26
|
+
Provides-Extra: torch
|
|
27
|
+
Requires-Dist: torch; extra == "torch"
|
|
28
|
+
Provides-Extra: esm
|
|
29
|
+
Requires-Dist: torch; extra == "esm"
|
|
30
|
+
Requires-Dist: transformers; extra == "esm"
|
|
31
|
+
Provides-Extra: dev
|
|
32
|
+
Requires-Dist: pytest; extra == "dev"
|
|
33
|
+
Requires-Dist: build; extra == "dev"
|
|
34
|
+
Requires-Dist: twine; extra == "dev"
|
|
35
|
+
Dynamic: license-file
|
|
36
|
+
|
|
37
|
+
# eWHT: Evolutionary Walsh-Hadamard Transform for Fitness Landscapes
|
|
38
|
+
|
|
39
|
+
[](https://badge.fury.io/py/ewht)
|
|
40
|
+
[](https://opensource.org/licenses/MIT)
|
|
41
|
+
[](https://pypi.org/project/ewht/)
|
|
42
|
+
[](https://pypi.org/project/ewht/)
|
|
43
|
+
[](https://github.com/psf/black)
|
|
44
|
+
[](https://github.com/amirgroup-codes/ewht/commits/main)
|
|
45
|
+
|
|
46
|
+
`ewht` is a Python package for analyzing combinatorial fitness landscapes using the **evolutionary Walsh-Hadamard transform (eWHT)**. It provides:
|
|
47
|
+
|
|
48
|
+
- Fast **O(N log N)** forward and inverse eWHT transforms
|
|
49
|
+
- **Evolutionary mutation probabilities** `ps` from MSAs or ESM2-650M
|
|
50
|
+
- **Data preprocessing** helpers (genotype encoding, evolutionary subsampling)
|
|
51
|
+
- **Compressed sensing** with LASSO on eWHT/WHT bases
|
|
52
|
+
|
|
53
|
+
## Installation
|
|
54
|
+
|
|
55
|
+
`ewht` supports Python 3.9 and above. Install from PyPI:
|
|
56
|
+
|
|
57
|
+
```sh
|
|
58
|
+
pip install ewht
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
Optional extras:
|
|
62
|
+
|
|
63
|
+
```sh
|
|
64
|
+
pip install ewht[esm] # ESM2-650M ps estimation (requires torch + transformers)
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
## Quickstart
|
|
68
|
+
|
|
69
|
+
The package contains an example CR6261-H1 dataset from the paper. Load it, estimate `ps` from MSA, compute the eWHT, and run compressed sensing. The full script can be found in `example_ewht.py`:
|
|
70
|
+
|
|
71
|
+
```python
|
|
72
|
+
import ewht
|
|
73
|
+
|
|
74
|
+
# Load data and preprocess
|
|
75
|
+
raw = ewht.load_example()
|
|
76
|
+
print(raw.head())
|
|
77
|
+
mutant mutated_sequence fitness estimated_fitness
|
|
78
|
+
0 WT QVQLVESGAEVKKPGSSVKVSCKASGGTFSSYAISWVRQAPGQGPE... 7.0 0
|
|
79
|
+
1 L104V QVQLVESGAEVKKPGSSVKVSCKASGGTFSSYAISWVRQAPGQGPE... 7.0 0
|
|
80
|
+
2 A79V QVQLVESGAEVKKPGSSVKVSCKASGGTFSSYAISWVRQAPGQGPE... 7.0 0
|
|
81
|
+
3 A79V;L104V QVQLVESGAEVKKPGSSVKVSCKASGGTFSSYAISWVRQAPGQGPE... 7.0 0
|
|
82
|
+
4 S77G QVQLVESGAEVKKPGSSVKVSCKASGGTFSSYAISWVRQAPGQGPE... 7.0 0
|
|
83
|
+
POSITIONS = [28, 30, 58, 59, 62, 74, 75, 76, 77, 79, 104]
|
|
84
|
+
MUTANTS = ["P", "R", "T", "K", "P", "D", "F", "A", "G", "V", "V"]
|
|
85
|
+
WT = (
|
|
86
|
+
"QVQLVESGAEVKKPGSSVKVSCKASGGTFSSYAISWVRQAPGQGPEWMGGIIPIFGTANYAQKFQGRVTITADKSTSTAYMELSSLRSEDTAMYYCAKHMGYQLRETMDVWGQGTTVTVSS"
|
|
87
|
+
)
|
|
88
|
+
L = len(POSITIONS)
|
|
89
|
+
print(df.head())
|
|
90
|
+
print(f"{df['genotype'].nunique()} unique genotypes, L={L}")
|
|
91
|
+
mutant mutated_sequence fitness estimated_fitness genotype
|
|
92
|
+
0 WT QVQLVESGAEVKKPGSSVKVSCKASGGTFSSYAISWVRQAPGQGPE... 7.0 0 00000000000
|
|
93
|
+
1 L104V QVQLVESGAEVKKPGSSVKVSCKASGGTFSSYAISWVRQAPGQGPE... 7.0 0 00000000001
|
|
94
|
+
2 A79V QVQLVESGAEVKKPGSSVKVSCKASGGTFSSYAISWVRQAPGQGPE... 7.0 0 00000000010
|
|
95
|
+
3 A79V;L104V QVQLVESGAEVKKPGSSVKVSCKASGGTFSSYAISWVRQAPGQGPE... 7.0 0 00000000011
|
|
96
|
+
4 S77G QVQLVESGAEVKKPGSSVKVSCKASGGTFSSYAISWVRQAPGQGPE... 7.0 0 00000000100
|
|
97
|
+
2048 unique genotypes, L=11
|
|
98
|
+
|
|
99
|
+
with example_msa() as msa_path:
|
|
100
|
+
# Compute ps from MSA
|
|
101
|
+
ps = get_ps(WT_SEQUENCE, POSITIONS, MUTANTS, msa=msa_path)
|
|
102
|
+
plot_ps(ps, OUTPUT_DIR / "ps_from_msa.png")
|
|
103
|
+
|
|
104
|
+
# Compute eWHT
|
|
105
|
+
coeffs, center = efwht_from_dataframe(df, ps, basis="eWHT")
|
|
106
|
+
plot_ewht_spectrum(coeffs, L, OUTPUT_DIR / "ewht_spectrum.png", max_order=MAX_ORDER)
|
|
107
|
+
|
|
108
|
+
# Sample evolutionary sequences for compressed sensing
|
|
109
|
+
train, test = sample_evolutionary_sequences(
|
|
110
|
+
df,
|
|
111
|
+
ps,
|
|
112
|
+
msa=msa_path,
|
|
113
|
+
positions=POSITIONS,
|
|
114
|
+
wt_sequence=WT_SEQUENCE,
|
|
115
|
+
mutants=MUTANTS,
|
|
116
|
+
fraction=0.75,
|
|
117
|
+
train_n=TRAIN_N,
|
|
118
|
+
random_state=0,
|
|
119
|
+
)
|
|
120
|
+
print(f"train={len(train)}, test={len(test)}")
|
|
121
|
+
train=100, test=162
|
|
122
|
+
|
|
123
|
+
# Run compressed sensing experiment
|
|
124
|
+
result = run_cs_experiment(train, test, ps, basis="eWHT", center_by_ps=True, random_state=0)
|
|
125
|
+
print(f"best lambda: {result.best_lambda}")
|
|
126
|
+
print(f"train R²: {result.train_metrics['r2']:.4f}")
|
|
127
|
+
print(f"test R²: {result.test_metrics['r2']:.4f}")
|
|
128
|
+
best lambda: 0.005
|
|
129
|
+
train R²: 0.9662
|
|
130
|
+
test R²: 0.8282
|
|
131
|
+
|
|
132
|
+
print(f"Figures in {OUTPUT_DIR.resolve()}/")
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
Run the full example:
|
|
136
|
+
```sh
|
|
137
|
+
python example_ewht.py
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
### Evolutionary mutation probabilities
|
|
141
|
+
|
|
142
|
+
`get_ps` estimates per-site mutation probabilities from an MSA or, if no MSA is given, from ESM2-650M:
|
|
143
|
+
|
|
144
|
+
<p align="center">
|
|
145
|
+
<img width="700px" src="assets/ps_from_msa.png" alt="Per-site mutation probabilities from MSA">
|
|
146
|
+
</p>
|
|
147
|
+
|
|
148
|
+
### eWHT spectrum
|
|
149
|
+
|
|
150
|
+
The forward transform decomposes the centered landscape into Walsh coefficients grouped by interaction order:
|
|
151
|
+
|
|
152
|
+
<p align="center">
|
|
153
|
+
<img width="700px" src="assets/ewht_spectrum.png" alt="eWHT coefficient spectrum orders 1-5">
|
|
154
|
+
</p>
|
|
155
|
+
|
|
156
|
+
## Core API
|
|
157
|
+
|
|
158
|
+
| Function | Description |
|
|
159
|
+
|----------|-------------|
|
|
160
|
+
| `efwht_from_dataframe(df, ps)` | Forward eWHT from a preprocessed DataFrame |
|
|
161
|
+
| `efwht(y, ps)` | Forward eWHT on a length-`2^L` landscape vector |
|
|
162
|
+
| `iefwht(coeffs, ps)` | Inverse eWHT (exact round-trip with matching `norm`) |
|
|
163
|
+
| `get_ps(sequence, positions, mutants, msa=...)` | Per-site mutation probabilities |
|
|
164
|
+
| `genotypes_from_dataframe(df, positions, wt_sequence, mutants)` | Build binary genotype column from sequences |
|
|
165
|
+
| `sample_evolutionary_sequences(df, ps, ...)` | Evolutionary subsampling with optional MSA mask |
|
|
166
|
+
| `run_cs_experiment(train, test, ps)` | Lasso compressed sensing with CV on train |
|
|
167
|
+
|
|
168
|
+
## Genotype encodings
|
|
169
|
+
|
|
170
|
+
`ewht` accepts genotypes as:
|
|
171
|
+
|
|
172
|
+
- Binary strings: `"00101"` (`0` = WT, `1` = mutant)
|
|
173
|
+
- Pseudoboolean strings: `"1-1-11"` (`1` = WT, `-1` = mutant)
|
|
174
|
+
|
|
175
|
+
For custom mappings, add a `genotype` column directly instead of using `genotypes_from_dataframe`.
|
|
176
|
+
|
|
177
|
+
## Optional dependencies
|
|
178
|
+
|
|
179
|
+
| Extra | Packages | Use case |
|
|
180
|
+
|-------|----------|----------|
|
|
181
|
+
| (default) | numpy, pandas, scipy, scikit-learn | transforms, MSA-based ps, CS |
|
|
182
|
+
| `ewht[esm]` | torch, transformers | ps from ESM2-650M when no MSA is available |
|
|
183
|
+
|
|
184
|
+
## Publishing to PyPI
|
|
185
|
+
|
|
186
|
+
From a clean checkout of the repository:
|
|
187
|
+
|
|
188
|
+
```sh
|
|
189
|
+
# Install build tools
|
|
190
|
+
pip install build twine
|
|
191
|
+
|
|
192
|
+
# Build sdist + wheel (includes bundled example_data/)
|
|
193
|
+
python -m build
|
|
194
|
+
|
|
195
|
+
# Upload to TestPyPI first (recommended)
|
|
196
|
+
twine upload --repository testpypi dist/*
|
|
197
|
+
|
|
198
|
+
# Verify install
|
|
199
|
+
pip install --index-url https://test.pypi.org/simple/ ewht
|
|
200
|
+
|
|
201
|
+
# Upload to PyPI
|
|
202
|
+
twine upload dist/*
|
|
203
|
+
```
|
|
204
|
+
|
|
205
|
+
Before the first upload:
|
|
206
|
+
|
|
207
|
+
1. Create accounts on [PyPI](https://pypi.org/account/register/) and [TestPyPI](https://test.pypi.org/account/register/).
|
|
208
|
+
2. Configure an API token: `~/.pypirc` or `TWINE_USERNAME=__token__` / `TWINE_PASSWORD=pypi-...`.
|
|
209
|
+
3. Ensure the package name `ewht` is available on PyPI (or change `name` in `pyproject.toml`).
|
|
210
|
+
4. Bump `version` in `pyproject.toml` and `ewht/__init__.py` for each release.
|
|
211
|
+
|
|
212
|
+
## Development
|
|
213
|
+
|
|
214
|
+
```sh
|
|
215
|
+
pip install -e ".[esm]"
|
|
216
|
+
pytest tests/ -v -m "not slow"
|
|
217
|
+
python example_ewht.py
|
|
218
|
+
```
|
ewht-0.0.1/README.md
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
# eWHT: Evolutionary Walsh-Hadamard Transform for Fitness Landscapes
|
|
2
|
+
|
|
3
|
+
[](https://badge.fury.io/py/ewht)
|
|
4
|
+
[](https://opensource.org/licenses/MIT)
|
|
5
|
+
[](https://pypi.org/project/ewht/)
|
|
6
|
+
[](https://pypi.org/project/ewht/)
|
|
7
|
+
[](https://github.com/psf/black)
|
|
8
|
+
[](https://github.com/amirgroup-codes/ewht/commits/main)
|
|
9
|
+
|
|
10
|
+
`ewht` is a Python package for analyzing combinatorial fitness landscapes using the **evolutionary Walsh-Hadamard transform (eWHT)**. It provides:
|
|
11
|
+
|
|
12
|
+
- Fast **O(N log N)** forward and inverse eWHT transforms
|
|
13
|
+
- **Evolutionary mutation probabilities** `ps` from MSAs or ESM2-650M
|
|
14
|
+
- **Data preprocessing** helpers (genotype encoding, evolutionary subsampling)
|
|
15
|
+
- **Compressed sensing** with LASSO on eWHT/WHT bases
|
|
16
|
+
|
|
17
|
+
## Installation
|
|
18
|
+
|
|
19
|
+
`ewht` supports Python 3.9 and above. Install from PyPI:
|
|
20
|
+
|
|
21
|
+
```sh
|
|
22
|
+
pip install ewht
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
Optional extras:
|
|
26
|
+
|
|
27
|
+
```sh
|
|
28
|
+
pip install ewht[esm] # ESM2-650M ps estimation (requires torch + transformers)
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
## Quickstart
|
|
32
|
+
|
|
33
|
+
The package contains an example CR6261-H1 dataset from the paper. Load it, estimate `ps` from MSA, compute the eWHT, and run compressed sensing. The full script can be found in `example_ewht.py`:
|
|
34
|
+
|
|
35
|
+
```python
|
|
36
|
+
import ewht
|
|
37
|
+
|
|
38
|
+
# Load data and preprocess
|
|
39
|
+
raw = ewht.load_example()
|
|
40
|
+
print(raw.head())
|
|
41
|
+
mutant mutated_sequence fitness estimated_fitness
|
|
42
|
+
0 WT QVQLVESGAEVKKPGSSVKVSCKASGGTFSSYAISWVRQAPGQGPE... 7.0 0
|
|
43
|
+
1 L104V QVQLVESGAEVKKPGSSVKVSCKASGGTFSSYAISWVRQAPGQGPE... 7.0 0
|
|
44
|
+
2 A79V QVQLVESGAEVKKPGSSVKVSCKASGGTFSSYAISWVRQAPGQGPE... 7.0 0
|
|
45
|
+
3 A79V;L104V QVQLVESGAEVKKPGSSVKVSCKASGGTFSSYAISWVRQAPGQGPE... 7.0 0
|
|
46
|
+
4 S77G QVQLVESGAEVKKPGSSVKVSCKASGGTFSSYAISWVRQAPGQGPE... 7.0 0
|
|
47
|
+
POSITIONS = [28, 30, 58, 59, 62, 74, 75, 76, 77, 79, 104]
|
|
48
|
+
MUTANTS = ["P", "R", "T", "K", "P", "D", "F", "A", "G", "V", "V"]
|
|
49
|
+
WT = (
|
|
50
|
+
"QVQLVESGAEVKKPGSSVKVSCKASGGTFSSYAISWVRQAPGQGPEWMGGIIPIFGTANYAQKFQGRVTITADKSTSTAYMELSSLRSEDTAMYYCAKHMGYQLRETMDVWGQGTTVTVSS"
|
|
51
|
+
)
|
|
52
|
+
L = len(POSITIONS)
|
|
53
|
+
print(df.head())
|
|
54
|
+
print(f"{df['genotype'].nunique()} unique genotypes, L={L}")
|
|
55
|
+
mutant mutated_sequence fitness estimated_fitness genotype
|
|
56
|
+
0 WT QVQLVESGAEVKKPGSSVKVSCKASGGTFSSYAISWVRQAPGQGPE... 7.0 0 00000000000
|
|
57
|
+
1 L104V QVQLVESGAEVKKPGSSVKVSCKASGGTFSSYAISWVRQAPGQGPE... 7.0 0 00000000001
|
|
58
|
+
2 A79V QVQLVESGAEVKKPGSSVKVSCKASGGTFSSYAISWVRQAPGQGPE... 7.0 0 00000000010
|
|
59
|
+
3 A79V;L104V QVQLVESGAEVKKPGSSVKVSCKASGGTFSSYAISWVRQAPGQGPE... 7.0 0 00000000011
|
|
60
|
+
4 S77G QVQLVESGAEVKKPGSSVKVSCKASGGTFSSYAISWVRQAPGQGPE... 7.0 0 00000000100
|
|
61
|
+
2048 unique genotypes, L=11
|
|
62
|
+
|
|
63
|
+
with example_msa() as msa_path:
|
|
64
|
+
# Compute ps from MSA
|
|
65
|
+
ps = get_ps(WT_SEQUENCE, POSITIONS, MUTANTS, msa=msa_path)
|
|
66
|
+
plot_ps(ps, OUTPUT_DIR / "ps_from_msa.png")
|
|
67
|
+
|
|
68
|
+
# Compute eWHT
|
|
69
|
+
coeffs, center = efwht_from_dataframe(df, ps, basis="eWHT")
|
|
70
|
+
plot_ewht_spectrum(coeffs, L, OUTPUT_DIR / "ewht_spectrum.png", max_order=MAX_ORDER)
|
|
71
|
+
|
|
72
|
+
# Sample evolutionary sequences for compressed sensing
|
|
73
|
+
train, test = sample_evolutionary_sequences(
|
|
74
|
+
df,
|
|
75
|
+
ps,
|
|
76
|
+
msa=msa_path,
|
|
77
|
+
positions=POSITIONS,
|
|
78
|
+
wt_sequence=WT_SEQUENCE,
|
|
79
|
+
mutants=MUTANTS,
|
|
80
|
+
fraction=0.75,
|
|
81
|
+
train_n=TRAIN_N,
|
|
82
|
+
random_state=0,
|
|
83
|
+
)
|
|
84
|
+
print(f"train={len(train)}, test={len(test)}")
|
|
85
|
+
train=100, test=162
|
|
86
|
+
|
|
87
|
+
# Run compressed sensing experiment
|
|
88
|
+
result = run_cs_experiment(train, test, ps, basis="eWHT", center_by_ps=True, random_state=0)
|
|
89
|
+
print(f"best lambda: {result.best_lambda}")
|
|
90
|
+
print(f"train R²: {result.train_metrics['r2']:.4f}")
|
|
91
|
+
print(f"test R²: {result.test_metrics['r2']:.4f}")
|
|
92
|
+
best lambda: 0.005
|
|
93
|
+
train R²: 0.9662
|
|
94
|
+
test R²: 0.8282
|
|
95
|
+
|
|
96
|
+
print(f"Figures in {OUTPUT_DIR.resolve()}/")
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
Run the full example:
|
|
100
|
+
```sh
|
|
101
|
+
python example_ewht.py
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
### Evolutionary mutation probabilities
|
|
105
|
+
|
|
106
|
+
`get_ps` estimates per-site mutation probabilities from an MSA or, if no MSA is given, from ESM2-650M:
|
|
107
|
+
|
|
108
|
+
<p align="center">
|
|
109
|
+
<img width="700px" src="assets/ps_from_msa.png" alt="Per-site mutation probabilities from MSA">
|
|
110
|
+
</p>
|
|
111
|
+
|
|
112
|
+
### eWHT spectrum
|
|
113
|
+
|
|
114
|
+
The forward transform decomposes the centered landscape into Walsh coefficients grouped by interaction order:
|
|
115
|
+
|
|
116
|
+
<p align="center">
|
|
117
|
+
<img width="700px" src="assets/ewht_spectrum.png" alt="eWHT coefficient spectrum orders 1-5">
|
|
118
|
+
</p>
|
|
119
|
+
|
|
120
|
+
## Core API
|
|
121
|
+
|
|
122
|
+
| Function | Description |
|
|
123
|
+
|----------|-------------|
|
|
124
|
+
| `efwht_from_dataframe(df, ps)` | Forward eWHT from a preprocessed DataFrame |
|
|
125
|
+
| `efwht(y, ps)` | Forward eWHT on a length-`2^L` landscape vector |
|
|
126
|
+
| `iefwht(coeffs, ps)` | Inverse eWHT (exact round-trip with matching `norm`) |
|
|
127
|
+
| `get_ps(sequence, positions, mutants, msa=...)` | Per-site mutation probabilities |
|
|
128
|
+
| `genotypes_from_dataframe(df, positions, wt_sequence, mutants)` | Build binary genotype column from sequences |
|
|
129
|
+
| `sample_evolutionary_sequences(df, ps, ...)` | Evolutionary subsampling with optional MSA mask |
|
|
130
|
+
| `run_cs_experiment(train, test, ps)` | Lasso compressed sensing with CV on train |
|
|
131
|
+
|
|
132
|
+
## Genotype encodings
|
|
133
|
+
|
|
134
|
+
`ewht` accepts genotypes as:
|
|
135
|
+
|
|
136
|
+
- Binary strings: `"00101"` (`0` = WT, `1` = mutant)
|
|
137
|
+
- Pseudoboolean strings: `"1-1-11"` (`1` = WT, `-1` = mutant)
|
|
138
|
+
|
|
139
|
+
For custom mappings, add a `genotype` column directly instead of using `genotypes_from_dataframe`.
|
|
140
|
+
|
|
141
|
+
## Optional dependencies
|
|
142
|
+
|
|
143
|
+
| Extra | Packages | Use case |
|
|
144
|
+
|-------|----------|----------|
|
|
145
|
+
| (default) | numpy, pandas, scipy, scikit-learn | transforms, MSA-based ps, CS |
|
|
146
|
+
| `ewht[esm]` | torch, transformers | ps from ESM2-650M when no MSA is available |
|
|
147
|
+
|
|
148
|
+
## Publishing to PyPI
|
|
149
|
+
|
|
150
|
+
From a clean checkout of the repository:
|
|
151
|
+
|
|
152
|
+
```sh
|
|
153
|
+
# Install build tools
|
|
154
|
+
pip install build twine
|
|
155
|
+
|
|
156
|
+
# Build sdist + wheel (includes bundled example_data/)
|
|
157
|
+
python -m build
|
|
158
|
+
|
|
159
|
+
# Upload to TestPyPI first (recommended)
|
|
160
|
+
twine upload --repository testpypi dist/*
|
|
161
|
+
|
|
162
|
+
# Verify install
|
|
163
|
+
pip install --index-url https://test.pypi.org/simple/ ewht
|
|
164
|
+
|
|
165
|
+
# Upload to PyPI
|
|
166
|
+
twine upload dist/*
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
Before the first upload:
|
|
170
|
+
|
|
171
|
+
1. Create accounts on [PyPI](https://pypi.org/account/register/) and [TestPyPI](https://test.pypi.org/account/register/).
|
|
172
|
+
2. Configure an API token: `~/.pypirc` or `TWINE_USERNAME=__token__` / `TWINE_PASSWORD=pypi-...`.
|
|
173
|
+
3. Ensure the package name `ewht` is available on PyPI (or change `name` in `pyproject.toml`).
|
|
174
|
+
4. Bump `version` in `pyproject.toml` and `ewht/__init__.py` for each release.
|
|
175
|
+
|
|
176
|
+
## Development
|
|
177
|
+
|
|
178
|
+
```sh
|
|
179
|
+
pip install -e ".[esm]"
|
|
180
|
+
pytest tests/ -v -m "not slow"
|
|
181
|
+
python example_ewht.py
|
|
182
|
+
```
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""
|
|
2
|
+
ewht: evolutionary Walsh-Hadamard transform for protein fitness landscapes.
|
|
3
|
+
|
|
4
|
+
This package provides fast eWHT / WHT transforms, evolutionary probability estimation,
|
|
5
|
+
data preprocessing helpers, and Lasso-based compressed sensing for combinatorial
|
|
6
|
+
deep mutational scanning experiments.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from ewht.basis import ewht_basis, get_basis, restore_expectation_coeffs, wht_basis
|
|
10
|
+
from ewht.cs import CSResult, center_targets, run_cs_experiment, select_lambda_cv
|
|
11
|
+
from ewht.data import genotypes_from_dataframe, sample_evolutionary_sequences, subtract_mean
|
|
12
|
+
from ewht.examples import example_msa, example_ps_reference, load_example
|
|
13
|
+
from ewht.ewht import efwht, efwht_from_dataframe, get_stable_scaling_factors, iefwht, stable_to_expectation_coeffs
|
|
14
|
+
from ewht.ps import get_ps
|
|
15
|
+
|
|
16
|
+
__all__ = [
|
|
17
|
+
"efwht",
|
|
18
|
+
"efwht_from_dataframe",
|
|
19
|
+
"iefwht",
|
|
20
|
+
"get_stable_scaling_factors",
|
|
21
|
+
"stable_to_expectation_coeffs",
|
|
22
|
+
"get_basis",
|
|
23
|
+
"ewht_basis",
|
|
24
|
+
"wht_basis",
|
|
25
|
+
"restore_expectation_coeffs",
|
|
26
|
+
"run_cs_experiment",
|
|
27
|
+
"select_lambda_cv",
|
|
28
|
+
"center_targets",
|
|
29
|
+
"CSResult",
|
|
30
|
+
"get_ps",
|
|
31
|
+
"genotypes_from_dataframe",
|
|
32
|
+
"sample_evolutionary_sequences",
|
|
33
|
+
"subtract_mean",
|
|
34
|
+
"load_example",
|
|
35
|
+
"example_msa",
|
|
36
|
+
"example_ps_reference",
|
|
37
|
+
]
|
|
38
|
+
|
|
39
|
+
__version__ = "0.0.1"
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import pandas as pd
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def resolve_genotype_column(df: pd.DataFrame) -> str:
|
|
7
|
+
"""Resolve a binary genotype column for CS input."""
|
|
8
|
+
lower_exact = {col.lower(): col for col in df.columns}
|
|
9
|
+
if "genotype" in lower_exact:
|
|
10
|
+
return lower_exact["genotype"]
|
|
11
|
+
for col in df.columns:
|
|
12
|
+
lower = col.lower()
|
|
13
|
+
if "genotype" in lower:
|
|
14
|
+
return col
|
|
15
|
+
for col in df.columns:
|
|
16
|
+
lower = col.lower()
|
|
17
|
+
if "sequence" in lower and "mutated" not in lower:
|
|
18
|
+
return col
|
|
19
|
+
raise KeyError(
|
|
20
|
+
"Could not find genotype column. Expected a column named 'genotype' "
|
|
21
|
+
f"or containing 'genotype'/'sequence'. Available: {list(df.columns)}"
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _column_matches(candidate: str, col_lower: str) -> bool:
|
|
26
|
+
"""Match exact names or underscore-delimited tokens (not arbitrary substrings)."""
|
|
27
|
+
if col_lower == candidate:
|
|
28
|
+
return True
|
|
29
|
+
return (
|
|
30
|
+
col_lower.startswith(f"{candidate}_")
|
|
31
|
+
or col_lower.endswith(f"_{candidate}")
|
|
32
|
+
or f"_{candidate}_" in f"_{col_lower}_"
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def resolve_column(df: pd.DataFrame, candidates: list[str], *, purpose: str) -> str:
|
|
37
|
+
"""Resolve a column by case-insensitive token match with priority order."""
|
|
38
|
+
if df.empty:
|
|
39
|
+
raise ValueError(f"Cannot resolve {purpose} column on an empty DataFrame.")
|
|
40
|
+
lower_map = {col.lower(): col for col in df.columns}
|
|
41
|
+
for candidate in candidates:
|
|
42
|
+
cand = candidate.lower()
|
|
43
|
+
for col_lower, col in lower_map.items():
|
|
44
|
+
if _column_matches(cand, col_lower):
|
|
45
|
+
return col
|
|
46
|
+
raise KeyError(
|
|
47
|
+
f"Could not find {purpose} column. Tried candidates {candidates}; "
|
|
48
|
+
f"available columns: {list(df.columns)}"
|
|
49
|
+
)
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
import warnings
|
|
5
|
+
|
|
6
|
+
import numpy as np
|
|
7
|
+
import pandas as pd
|
|
8
|
+
|
|
9
|
+
from ewht.ps._constants import CANONICAL_AAS, X_MUTANT_AAS
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def parse_genotype_tokens(raw: object) -> list[int]:
|
|
13
|
+
"""Parse genotype tokens in {0,1} or {1,-1} encoding."""
|
|
14
|
+
text = str(raw).strip()
|
|
15
|
+
if not text:
|
|
16
|
+
raise ValueError("Empty genotype string.")
|
|
17
|
+
|
|
18
|
+
if re.fullmatch(r"[01]+", text):
|
|
19
|
+
return [int(ch) for ch in text]
|
|
20
|
+
|
|
21
|
+
tokens: list[int] = []
|
|
22
|
+
i = 0
|
|
23
|
+
while i < len(text):
|
|
24
|
+
if text[i].isspace() or text[i] in ",|/":
|
|
25
|
+
i += 1
|
|
26
|
+
continue
|
|
27
|
+
if text.startswith("-1", i):
|
|
28
|
+
tokens.append(-1)
|
|
29
|
+
i += 2
|
|
30
|
+
continue
|
|
31
|
+
if text[i] == "1":
|
|
32
|
+
tokens.append(1)
|
|
33
|
+
i += 1
|
|
34
|
+
continue
|
|
35
|
+
if text[i] == "0":
|
|
36
|
+
tokens.append(0)
|
|
37
|
+
i += 1
|
|
38
|
+
continue
|
|
39
|
+
raise ValueError(f"Invalid genotype token in {raw!r} at position {i}.")
|
|
40
|
+
|
|
41
|
+
if not tokens:
|
|
42
|
+
raise ValueError(f"Could not parse genotype from {raw!r}.")
|
|
43
|
+
return tokens
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def tokens_to_binary_string(tokens: list[int]) -> str:
|
|
47
|
+
"""Convert parsed tokens to an internal 0/1 genotype string."""
|
|
48
|
+
if any(t not in (0, 1) for t in tokens):
|
|
49
|
+
if any(t not in (1, -1) for t in tokens):
|
|
50
|
+
raise ValueError(f"Genotype tokens must use 0/1 or 1/-1 encoding, got {tokens}.")
|
|
51
|
+
return "".join("0" if t == 1 else "1" for t in tokens)
|
|
52
|
+
return "".join(str(t) for t in tokens)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def normalize_genotype_string(raw: object, L: int | None = None) -> str:
|
|
56
|
+
if isinstance(raw, (int, np.integer)):
|
|
57
|
+
if L is None:
|
|
58
|
+
raise ValueError("Genotype provided as integer requires length L.")
|
|
59
|
+
return str(int(raw)).zfill(L)
|
|
60
|
+
|
|
61
|
+
bits = tokens_to_binary_string(parse_genotype_tokens(raw))
|
|
62
|
+
if L is not None and len(bits) != L:
|
|
63
|
+
raise ValueError(f"Invalid genotype '{raw}': expected length {L}, got {len(bits)}.")
|
|
64
|
+
return bits
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def infer_genotype_length(series: pd.Series) -> int:
|
|
68
|
+
"""Infer landscape length L from a genotype column."""
|
|
69
|
+
if pd.api.types.is_numeric_dtype(series):
|
|
70
|
+
return max(len(str(int(v))) for v in series)
|
|
71
|
+
max_len = 0
|
|
72
|
+
for raw in series:
|
|
73
|
+
bits = normalize_genotype_string(raw)
|
|
74
|
+
max_len = max(max_len, len(bits))
|
|
75
|
+
return max_len
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def genotype_index(genotype: str) -> int:
|
|
79
|
+
"""Map a binary genotype string to lexicographic landscape index."""
|
|
80
|
+
return int(genotype, 2)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def index_to_genotype(index: int, L: int) -> str:
|
|
84
|
+
return format(index, f"0{L}b")
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def validate_genotype_series(series: pd.Series, L: int | None = None) -> pd.Series:
|
|
88
|
+
"""Normalize and validate a genotype column."""
|
|
89
|
+
if pd.api.types.is_numeric_dtype(series):
|
|
90
|
+
series = series.map(lambda v: str(int(v)).zfill(L))
|
|
91
|
+
else:
|
|
92
|
+
series = series.astype(str).str.strip()
|
|
93
|
+
series = series.map(lambda g: g.zfill(L) if set(g) <= {"0", "1"} and len(g) < L else g)
|
|
94
|
+
normalized = series.map(lambda g: normalize_genotype_string(g, L=L))
|
|
95
|
+
lengths = normalized.map(len).unique()
|
|
96
|
+
if len(lengths) != 1:
|
|
97
|
+
raise ValueError(f"All genotypes must have the same length; observed lengths {sorted(lengths)}.")
|
|
98
|
+
if L is not None and lengths[0] != L:
|
|
99
|
+
raise ValueError(f"Expected genotype length {L}, got {lengths[0]}.")
|
|
100
|
+
if not all(set(g).issubset({"0", "1"}) for g in normalized):
|
|
101
|
+
raise ValueError("Genotype column must contain only 0/1 after normalization.")
|
|
102
|
+
return normalized
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def mutant_matches(residue: str, mut_aa: str) -> bool:
|
|
106
|
+
residue = residue.upper()
|
|
107
|
+
mut_aa = mut_aa.upper()
|
|
108
|
+
if mut_aa == "X":
|
|
109
|
+
return residue in X_MUTANT_AAS
|
|
110
|
+
return residue == mut_aa
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def encode_genotype_from_sequence(
|
|
114
|
+
sequence: str,
|
|
115
|
+
positions: list[int | str],
|
|
116
|
+
mutant_list: list[str | None],
|
|
117
|
+
wt_sequence: str,
|
|
118
|
+
*,
|
|
119
|
+
mutant_label: str | None = None,
|
|
120
|
+
) -> str:
|
|
121
|
+
bits: list[str] = []
|
|
122
|
+
for pos, mut_aa in zip(positions, mutant_list):
|
|
123
|
+
if pos == "NC":
|
|
124
|
+
has_nc = bool(mutant_label and re.search(r"(^|;)NC($|;)", mutant_label))
|
|
125
|
+
bits.append("1" if has_nc else "0")
|
|
126
|
+
continue
|
|
127
|
+
pos_i = int(pos)
|
|
128
|
+
residue = sequence[pos_i - 1].upper()
|
|
129
|
+
wt_aa = wt_sequence[pos_i - 1].upper()
|
|
130
|
+
if mut_aa is None:
|
|
131
|
+
raise ValueError(
|
|
132
|
+
f"mutants must be specified for position {pos_i}; "
|
|
133
|
+
"use an explicit genotype column if mapping is custom."
|
|
134
|
+
)
|
|
135
|
+
if residue == wt_aa:
|
|
136
|
+
bits.append("0")
|
|
137
|
+
elif mutant_matches(residue, mut_aa):
|
|
138
|
+
bits.append("1")
|
|
139
|
+
else:
|
|
140
|
+
raise ValueError(
|
|
141
|
+
f"Residue '{residue}' at position {pos_i} is neither wild-type '{wt_aa}' "
|
|
142
|
+
f"nor mutant '{mut_aa}'."
|
|
143
|
+
)
|
|
144
|
+
return "".join(bits)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def build_landscape_weights(ps: np.ndarray) -> np.ndarray:
|
|
148
|
+
weights = np.array([1.0], dtype=np.float64)
|
|
149
|
+
for p in ps:
|
|
150
|
+
weights = np.kron(weights, np.array([1.0 - p, p], dtype=np.float64))
|
|
151
|
+
return weights
|