ewht 0.0.1__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.
- ewht/__init__.py +39 -0
- ewht/_columns.py +49 -0
- ewht/_genotype.py +151 -0
- ewht/_io.py +59 -0
- ewht/_ordering.py +31 -0
- ewht/_validate.py +26 -0
- ewht/basis.py +166 -0
- ewht/cs.py +283 -0
- ewht/data.py +281 -0
- ewht/ewht.py +328 -0
- ewht/example_data/cr6261.a2m +129416 -0
- ewht/example_data/cr6261_h1_mean.csv +2049 -0
- ewht/example_data/cr6261_ps.npy +0 -0
- ewht/examples.py +58 -0
- ewht/ps/__init__.py +3 -0
- ewht/ps/_constants.py +9 -0
- ewht/ps/_parse.py +61 -0
- ewht/ps/compute.py +61 -0
- ewht/ps/esm.py +96 -0
- ewht/ps/msa.py +104 -0
- ewht-0.0.1.dist-info/METADATA +218 -0
- ewht-0.0.1.dist-info/RECORD +25 -0
- ewht-0.0.1.dist-info/WHEEL +5 -0
- ewht-0.0.1.dist-info/licenses/LICENSE +21 -0
- ewht-0.0.1.dist-info/top_level.txt +1 -0
ewht/__init__.py
ADDED
|
@@ -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"
|
ewht/_columns.py
ADDED
|
@@ -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
|
+
)
|
ewht/_genotype.py
ADDED
|
@@ -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
|
ewht/_io.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Union
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
import pandas as pd
|
|
7
|
+
|
|
8
|
+
from ewht._columns import resolve_column, resolve_genotype_column
|
|
9
|
+
from ewht._genotype import infer_genotype_length, validate_genotype_series
|
|
10
|
+
|
|
11
|
+
SeqData = Union[pd.DataFrame, tuple[np.ndarray, np.ndarray]]
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def parse_seq_data(data: SeqData) -> tuple[np.ndarray, np.ndarray]:
|
|
15
|
+
"""
|
|
16
|
+
Parse binary genotypes and fitness values from a DataFrame or tuple.
|
|
17
|
+
|
|
18
|
+
Inputs:
|
|
19
|
+
- ``data``: pandas DataFrame with genotype + fitness columns, or
|
|
20
|
+
``(bin_seqs, y)`` with ``bin_seqs`` ``(N, L)`` int8 and ``y`` ``(N,)`` float.
|
|
21
|
+
|
|
22
|
+
Outputs:
|
|
23
|
+
- ``bin_seqs``: ``(N, L)`` int8 array.
|
|
24
|
+
- ``y``: ``(N,)`` float array (duplicate genotypes averaged).
|
|
25
|
+
"""
|
|
26
|
+
if isinstance(data, tuple):
|
|
27
|
+
if len(data) != 2:
|
|
28
|
+
raise ValueError("Tuple input must be (bin_seqs, y).")
|
|
29
|
+
bin_seqs, y = data
|
|
30
|
+
bin_seqs = np.asarray(bin_seqs, dtype=np.int8)
|
|
31
|
+
y = np.asarray(y, dtype=float)
|
|
32
|
+
if bin_seqs.ndim != 2:
|
|
33
|
+
raise ValueError("bin_seqs must be a 2D array of shape (N, L).")
|
|
34
|
+
if y.ndim != 1 or len(y) != len(bin_seqs):
|
|
35
|
+
raise ValueError("y must be a 1D array with one value per sequence.")
|
|
36
|
+
return bin_seqs, y
|
|
37
|
+
|
|
38
|
+
if isinstance(data, pd.DataFrame):
|
|
39
|
+
if data.empty:
|
|
40
|
+
raise ValueError("Input DataFrame is empty.")
|
|
41
|
+
|
|
42
|
+
genotype_col = resolve_genotype_column(data)
|
|
43
|
+
fitness_col = resolve_column(data, ["y", "fitness", "score"], purpose="fitness")
|
|
44
|
+
|
|
45
|
+
work = data[[genotype_col, fitness_col]].copy()
|
|
46
|
+
L = infer_genotype_length(work[genotype_col])
|
|
47
|
+
work[genotype_col] = validate_genotype_series(work[genotype_col], L=L)
|
|
48
|
+
work[fitness_col] = pd.to_numeric(work[fitness_col], errors="coerce")
|
|
49
|
+
if work[fitness_col].isna().any():
|
|
50
|
+
raise ValueError(f"Non-numeric values found in '{fitness_col}'.")
|
|
51
|
+
|
|
52
|
+
grouped = work.groupby(genotype_col, as_index=False)[fitness_col].mean()
|
|
53
|
+
bin_seqs = np.stack(
|
|
54
|
+
[np.fromiter(g, dtype=np.int8) for g in grouped[genotype_col].to_numpy()]
|
|
55
|
+
)
|
|
56
|
+
y = grouped[fitness_col].to_numpy(dtype=float)
|
|
57
|
+
return bin_seqs, y
|
|
58
|
+
|
|
59
|
+
raise TypeError("Expected a pandas DataFrame or (bin_seqs, y) tuple.")
|
ewht/_ordering.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from itertools import combinations
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def degree_index(L: int) -> np.ndarray:
|
|
9
|
+
"""Map degree-ordered coefficient index -> lexicographic genotype index."""
|
|
10
|
+
idx = [
|
|
11
|
+
sum(1 << i for i in combo)
|
|
12
|
+
for r in range(L + 1)
|
|
13
|
+
for combo in combinations(range(L), r)
|
|
14
|
+
]
|
|
15
|
+
return np.asarray(idx, dtype=np.int64)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def lex_index(L: int) -> np.ndarray:
|
|
19
|
+
"""Map lexicographic index -> degree-ordered index."""
|
|
20
|
+
deg = degree_index(L)
|
|
21
|
+
lex = np.empty_like(deg)
|
|
22
|
+
lex[deg] = np.arange(len(deg))
|
|
23
|
+
return lex
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def reorder_coeffs(coeffs: np.ndarray, L: int, *, degree_order: bool = False) -> np.ndarray:
|
|
27
|
+
"""Convert coefficients between lexicographic and degree orderings."""
|
|
28
|
+
coeffs = np.asarray(coeffs, dtype=float)
|
|
29
|
+
if degree_order:
|
|
30
|
+
return coeffs[degree_index(L)]
|
|
31
|
+
return coeffs[lex_index(L)]
|
ewht/_validate.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def validate_ps(ps: np.ndarray | None, L: int) -> np.ndarray:
|
|
7
|
+
if ps is None:
|
|
8
|
+
return np.full(L, 0.5, dtype=float)
|
|
9
|
+
p = np.asarray(ps, dtype=float)
|
|
10
|
+
if p.shape != (L,):
|
|
11
|
+
raise ValueError(f"ps must have shape ({L},).")
|
|
12
|
+
if np.any((p <= 0.0) | (p >= 1.0)):
|
|
13
|
+
raise ValueError("All ps entries must lie strictly between 0 and 1.")
|
|
14
|
+
return p
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def validate_transform_inputs(y: np.ndarray, ps: np.ndarray | None) -> tuple[np.ndarray, np.ndarray, int, int]:
|
|
18
|
+
a = np.asarray(y, dtype=float)
|
|
19
|
+
if a.ndim != 1:
|
|
20
|
+
raise ValueError("y must be a 1D array.")
|
|
21
|
+
N = len(a)
|
|
22
|
+
if N == 0 or (N & (N - 1)) != 0:
|
|
23
|
+
raise ValueError("Input length must be a power of 2.")
|
|
24
|
+
L = int(np.log2(N))
|
|
25
|
+
p = validate_ps(ps, L)
|
|
26
|
+
return a.copy(), p, N, L
|
ewht/basis.py
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
|
|
5
|
+
from ewht._ordering import degree_index, lex_index
|
|
6
|
+
from ewht._validate import validate_ps
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def get_basis(
|
|
10
|
+
bin_seqs: np.ndarray,
|
|
11
|
+
ps: np.ndarray | None = None,
|
|
12
|
+
*,
|
|
13
|
+
basis: str = "eWHT",
|
|
14
|
+
norm: str = "stable",
|
|
15
|
+
degree_order: bool = True,
|
|
16
|
+
) -> np.ndarray | tuple[np.ndarray, np.ndarray]:
|
|
17
|
+
"""
|
|
18
|
+
Build a Lasso design matrix from sampled binary genotypes.
|
|
19
|
+
|
|
20
|
+
Each row evaluates the synthesis (inverse-transform) basis at one genotype so
|
|
21
|
+
that ``y ≈ X @ coeffs`` uses the same coefficient convention as ``efwht``.
|
|
22
|
+
|
|
23
|
+
Inputs:
|
|
24
|
+
- ``bin_seqs``: ``(N, L)`` int8 array with ``0`` = wild-type and ``1`` = mutant.
|
|
25
|
+
- ``ps``: ``(L,)`` float array of mutation probabilities. Ignored for ``WHT``
|
|
26
|
+
(internally uses ``0.5``).
|
|
27
|
+
- ``basis``: ``{'eWHT', 'WHT'}``.
|
|
28
|
+
- ``norm``: ``{'stable', 'expectation', 'sqrt'}``. CS uses ``stable`` for eWHT.
|
|
29
|
+
- ``degree_order``: if ``True``, columns are grouped by interaction degree.
|
|
30
|
+
|
|
31
|
+
Outputs:
|
|
32
|
+
- ``X``: ``(N, 2^L)`` float design matrix.
|
|
33
|
+
- ``p_norms``: ``(L,)`` float array when ``norm='stable'`` and ``basis='eWHT'``;
|
|
34
|
+
otherwise omitted (return is just ``X``).
|
|
35
|
+
"""
|
|
36
|
+
basis = basis.upper()
|
|
37
|
+
if basis == "WHT":
|
|
38
|
+
bin_seqs = np.asarray(bin_seqs, dtype=np.int8)
|
|
39
|
+
L = bin_seqs.shape[1]
|
|
40
|
+
ps = validate_ps(None, L)
|
|
41
|
+
norm = "expectation" if norm == "stable" else norm
|
|
42
|
+
elif basis == "EWHT":
|
|
43
|
+
pass
|
|
44
|
+
else:
|
|
45
|
+
raise ValueError("basis must be 'eWHT' or 'WHT'.")
|
|
46
|
+
|
|
47
|
+
X, p_norms = _ewht_basis_matrix(bin_seqs, ps, norm=norm)
|
|
48
|
+
if not degree_order:
|
|
49
|
+
X = X[:, lex_index(bin_seqs.shape[1])]
|
|
50
|
+
if p_norms is None:
|
|
51
|
+
return X
|
|
52
|
+
return X, p_norms
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def ewht_basis(
|
|
56
|
+
bin_seqs: np.ndarray,
|
|
57
|
+
ps: np.ndarray,
|
|
58
|
+
*,
|
|
59
|
+
norm: str = "stable",
|
|
60
|
+
degree_order: bool = True,
|
|
61
|
+
) -> np.ndarray | tuple[np.ndarray, np.ndarray]:
|
|
62
|
+
"""Alias for get_basis(..., basis='eWHT')."""
|
|
63
|
+
return get_basis(bin_seqs, ps, basis="eWHT", norm=norm, degree_order=degree_order)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def wht_basis(
|
|
67
|
+
bin_seqs: np.ndarray,
|
|
68
|
+
*,
|
|
69
|
+
norm: str = "expectation",
|
|
70
|
+
degree_order: bool = True,
|
|
71
|
+
) -> np.ndarray:
|
|
72
|
+
"""Alias for get_basis(..., basis='WHT')."""
|
|
73
|
+
out = get_basis(bin_seqs, None, basis="WHT", norm=norm, degree_order=degree_order)
|
|
74
|
+
return out[0] if isinstance(out, tuple) else out
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def restore_expectation_coeffs(
|
|
78
|
+
coeffs_stable: np.ndarray,
|
|
79
|
+
p_norms: np.ndarray,
|
|
80
|
+
*,
|
|
81
|
+
degree_order: bool = True,
|
|
82
|
+
) -> np.ndarray:
|
|
83
|
+
"""
|
|
84
|
+
Convert stable-basis Lasso coefficients to expectation-basis coefficients.
|
|
85
|
+
|
|
86
|
+
Inputs:
|
|
87
|
+
- ``coeffs_stable``: ``(2^L,)`` float Lasso coefficients in degree order.
|
|
88
|
+
- ``p_norms``: ``(L,)`` float stable scaling factors from ``get_basis``.
|
|
89
|
+
- ``degree_order``: whether ``coeffs_stable`` is in degree order.
|
|
90
|
+
|
|
91
|
+
Outputs:
|
|
92
|
+
- ``(2^L,)`` float array of expectation-norm coefficients.
|
|
93
|
+
"""
|
|
94
|
+
from ewht._ordering import reorder_coeffs
|
|
95
|
+
from ewht.ewht import get_stable_scaling_factors
|
|
96
|
+
|
|
97
|
+
coeffs_stable = np.asarray(coeffs_stable, dtype=float)
|
|
98
|
+
p_norms = np.asarray(p_norms, dtype=float)
|
|
99
|
+
L = len(p_norms)
|
|
100
|
+
scaling_lex = get_stable_scaling_factors(p_norms)
|
|
101
|
+
if degree_order:
|
|
102
|
+
scaling = reorder_coeffs(scaling_lex, L, degree_order=True)
|
|
103
|
+
else:
|
|
104
|
+
scaling = scaling_lex
|
|
105
|
+
return coeffs_stable / scaling
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _genotype_indices(bin_seqs: np.ndarray) -> np.ndarray:
|
|
109
|
+
L = bin_seqs.shape[1]
|
|
110
|
+
powers = 1 << np.arange(L - 1, -1, -1, dtype=np.int64)
|
|
111
|
+
return bin_seqs.astype(np.int64) @ powers
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _p_bias_matrix(p: float, *, stable: bool = False) -> tuple[np.ndarray, float]:
|
|
115
|
+
q = 1.0 - p
|
|
116
|
+
c0, c1 = np.sqrt(p / q), -np.sqrt(q / p)
|
|
117
|
+
p_norm = 1.0
|
|
118
|
+
if stable:
|
|
119
|
+
p_norm = np.sqrt(c0**2 + c1**2)
|
|
120
|
+
c0 /= p_norm
|
|
121
|
+
c1 /= p_norm
|
|
122
|
+
return np.array([[1.0, 1.0], [c0, c1]], dtype=float), p_norm
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _synthesis_matrix(
|
|
126
|
+
ps: np.ndarray,
|
|
127
|
+
*,
|
|
128
|
+
norm: str = "expectation",
|
|
129
|
+
) -> tuple[np.ndarray, np.ndarray | None]:
|
|
130
|
+
"""Full (2^L x 2^L) synthesis matrix with lexicographic coefficient columns."""
|
|
131
|
+
is_stable = norm == "stable"
|
|
132
|
+
ps = np.asarray(ps, dtype=float)
|
|
133
|
+
n = len(ps)
|
|
134
|
+
p_norms = np.ones(n, dtype=np.float64)
|
|
135
|
+
|
|
136
|
+
H, pn = _p_bias_matrix(float(ps[0]), stable=is_stable)
|
|
137
|
+
p_norms[0] = pn
|
|
138
|
+
for i in range(1, n):
|
|
139
|
+
mat, pn = _p_bias_matrix(float(ps[i]), stable=is_stable)
|
|
140
|
+
p_norms[i] = pn
|
|
141
|
+
H = np.kron(H, mat)
|
|
142
|
+
|
|
143
|
+
S = H.T
|
|
144
|
+
if norm == "sqrt":
|
|
145
|
+
S = S / np.sqrt(1 << n)
|
|
146
|
+
return S, p_norms if is_stable else None
|
|
147
|
+
if norm in ("expectation", "stable"):
|
|
148
|
+
return S, p_norms if is_stable else None
|
|
149
|
+
raise ValueError(f"norm must be one of {{'expectation', 'sqrt', 'stable'}}, got {norm!r}.")
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _ewht_basis_matrix(
|
|
153
|
+
bin_seqs: np.ndarray,
|
|
154
|
+
ps: np.ndarray,
|
|
155
|
+
*,
|
|
156
|
+
norm: str = "stable",
|
|
157
|
+
) -> tuple[np.ndarray, np.ndarray | None]:
|
|
158
|
+
bin_seqs = np.asarray(bin_seqs, dtype=np.int8)
|
|
159
|
+
ps = np.asarray(ps, dtype=np.float64)
|
|
160
|
+
N, L = bin_seqs.shape
|
|
161
|
+
|
|
162
|
+
S, p_norms = _synthesis_matrix(ps, norm=norm)
|
|
163
|
+
row_idx = _genotype_indices(bin_seqs)
|
|
164
|
+
X = S[row_idx, :]
|
|
165
|
+
X = X[:, degree_index(L)]
|
|
166
|
+
return X, p_norms
|