gReLU 1.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.
- gReLU-1.0.1.dist-info/LICENSE.txt +21 -0
- gReLU-1.0.1.dist-info/METADATA +106 -0
- gReLU-1.0.1.dist-info/RECORD +58 -0
- gReLU-1.0.1.dist-info/WHEEL +5 -0
- gReLU-1.0.1.dist-info/top_level.txt +1 -0
- grelu/__init__.py +16 -0
- grelu/data/__init__.py +0 -0
- grelu/data/augment.py +227 -0
- grelu/data/dataset.py +1013 -0
- grelu/data/preprocess.py +710 -0
- grelu/data/utils.py +63 -0
- grelu/design.py +287 -0
- grelu/interpret/__init__.py +0 -0
- grelu/interpret/motifs.py +319 -0
- grelu/interpret/score.py +390 -0
- grelu/io/__init__.py +136 -0
- grelu/io/bed.py +97 -0
- grelu/io/bigwig.py +98 -0
- grelu/io/fasta.py +48 -0
- grelu/io/genome.py +93 -0
- grelu/io/meme.py +115 -0
- grelu/lightning/__init__.py +1097 -0
- grelu/lightning/losses.py +77 -0
- grelu/lightning/metrics.py +146 -0
- grelu/model/__init__.py +0 -0
- grelu/model/blocks.py +761 -0
- grelu/model/heads.py +135 -0
- grelu/model/layers.py +399 -0
- grelu/model/models.py +692 -0
- grelu/model/position.py +80 -0
- grelu/model/trunks/__init__.py +338 -0
- grelu/model/trunks/borzoi.py +166 -0
- grelu/model/trunks/enformer.py +277 -0
- grelu/model/trunks/explainn.py +119 -0
- grelu/resources/__init__.py +138 -0
- grelu/resources/__pycache__/__init__.cpython-310.pyc +0 -0
- grelu/resources/blacklists/encode/hg19-blacklist.v2.bed +834 -0
- grelu/resources/blacklists/encode/hg38-blacklist.v2.bed +636 -0
- grelu/resources/blacklists/encode/mm10-blacklist.v2.bed +3435 -0
- grelu/resources/blacklists/mito_combined/hg19.full.blacklist.bed +902 -0
- grelu/resources/blacklists/mito_combined/hg19_mm10_c.full.blacklist.bed +1425 -0
- grelu/resources/blacklists/mito_combined/hg38.full.blacklist.bed +820 -0
- grelu/resources/blacklists/mito_combined/mm10.full.blacklist.bed +523 -0
- grelu/resources/blacklists/mito_combined/mm9.full.blacklist.bed +3415 -0
- grelu/resources/meme/JASPAR2022_CORE_non-redundant_pfms_meme.txt +32224 -0
- grelu/resources/meme/jvierstra_consensus_pwms.meme +10405 -0
- grelu/sequence/__init__.py +0 -0
- grelu/sequence/format.py +428 -0
- grelu/sequence/metrics.py +105 -0
- grelu/sequence/mutate.py +252 -0
- grelu/sequence/utils.py +452 -0
- grelu/transforms/__init__.py +0 -0
- grelu/transforms/label_transforms.py +50 -0
- grelu/transforms/prediction_transforms.py +248 -0
- grelu/transforms/seq_transforms.py +132 -0
- grelu/utils.py +153 -0
- grelu/variant.py +389 -0
- grelu/visualize.py +740 -0
grelu/data/utils.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Dataset-related utility functions.
|
|
3
|
+
"""
|
|
4
|
+
from typing import List, Union
|
|
5
|
+
|
|
6
|
+
import pandas as pd
|
|
7
|
+
from pandas.api.types import is_categorical_dtype, is_string_dtype
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _check_multiclass(df: pd.DataFrame) -> bool:
|
|
11
|
+
"""
|
|
12
|
+
Check whether a dataframe contains valid multiclass labels.
|
|
13
|
+
"""
|
|
14
|
+
return (df.shape[1] == 1) and (
|
|
15
|
+
(is_string_dtype(df.iloc[:, 0])) or (is_categorical_dtype(df.iloc[:, 0]))
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _create_task_data(task_names: List[str]) -> pd.DataFrame:
|
|
20
|
+
"""
|
|
21
|
+
Check that task names are valid and create an empty dataframe with
|
|
22
|
+
task names as the index.
|
|
23
|
+
|
|
24
|
+
Args:
|
|
25
|
+
task_names: List of names
|
|
26
|
+
|
|
27
|
+
Returns:
|
|
28
|
+
Checked names as strings
|
|
29
|
+
"""
|
|
30
|
+
assert len(set(task_names)) == len(task_names), "Task names are not unique"
|
|
31
|
+
return pd.DataFrame(index=task_names)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def get_chromosomes(chroms: Union[str, List[str]]) -> List[str]:
|
|
35
|
+
"""
|
|
36
|
+
Return a list of chromosomes given shortcut names.
|
|
37
|
+
|
|
38
|
+
Args:
|
|
39
|
+
chroms: The chromosome name(s) or shortcut name(s).
|
|
40
|
+
|
|
41
|
+
Returns:
|
|
42
|
+
A list of chromosome name(s).
|
|
43
|
+
|
|
44
|
+
Example:
|
|
45
|
+
>>> get_chromosomes("autosomes")
|
|
46
|
+
['chr1', 'chr2', 'chr3', 'chr4', 'chr5', 'chr6', 'chr7', 'chr8', 'chr9', 'chr10',
|
|
47
|
+
'chr11', 'chr12', 'chr13', 'chr14', 'chr15', 'chr16', 'chr17', 'chr18', 'chr19',
|
|
48
|
+
'chr20', 'chr21', 'chr22']
|
|
49
|
+
"""
|
|
50
|
+
# Define shortcuts for chromosome names
|
|
51
|
+
chrom_shortcuts = {
|
|
52
|
+
"autosomes": ["chr" + str(x) for x in range(1, 23)],
|
|
53
|
+
"autosomesX": ["chr" + str(x) for x in range(1, 23)] + ["chrX"],
|
|
54
|
+
"autosomesXY": ["chr" + str(x) for x in range(1, 23)] + ["chrX", "chrY"],
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
# Return the corresponding chromosome names if a shortcut name is given
|
|
58
|
+
if isinstance(chroms, str) and (chroms in chrom_shortcuts):
|
|
59
|
+
return chrom_shortcuts[chroms]
|
|
60
|
+
|
|
61
|
+
# Return the chromosome names if they are given directly
|
|
62
|
+
else:
|
|
63
|
+
return chroms
|
grelu/design.py
ADDED
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
from typing import Callable, List, Optional, Union
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
import pandas as pd
|
|
5
|
+
import torch
|
|
6
|
+
from torch import Tensor, nn
|
|
7
|
+
|
|
8
|
+
from grelu.lightning import LightningModel
|
|
9
|
+
from grelu.sequence.format import convert_input_type
|
|
10
|
+
from grelu.utils import make_list
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
# Directed Evolution
|
|
14
|
+
def evolve(
|
|
15
|
+
seqs: Union[List[str], pd.DataFrame],
|
|
16
|
+
model: LightningModel,
|
|
17
|
+
method: str = "ism",
|
|
18
|
+
patterns: Optional[List[str]] = None,
|
|
19
|
+
prediction_transform: Optional[nn.Module] = None,
|
|
20
|
+
seq_transform: Optional[nn.Module] = None,
|
|
21
|
+
max_iter: int = 10,
|
|
22
|
+
positions: List[int] = None,
|
|
23
|
+
devices: Union[str, int, List[int]] = "cpu",
|
|
24
|
+
num_workers: int = 1,
|
|
25
|
+
batch_size: int = 64,
|
|
26
|
+
genome: Optional[str] = None,
|
|
27
|
+
for_each: bool = True,
|
|
28
|
+
return_seqs: str = "all",
|
|
29
|
+
return_preds: bool = True,
|
|
30
|
+
verbose: bool = True,
|
|
31
|
+
) -> pd.DataFrame:
|
|
32
|
+
"""
|
|
33
|
+
Sequence design by greedy directed evolution
|
|
34
|
+
|
|
35
|
+
Args:
|
|
36
|
+
seqs: a set of DNA sequences as strings or genomic intervals
|
|
37
|
+
model: LightningModel object containing a trained deep learning model
|
|
38
|
+
method: Either "ism" or "pattern".
|
|
39
|
+
patterns: A list of subsequences to try inserting into the starting sequence.
|
|
40
|
+
prediction_transform: A module to transform the model output
|
|
41
|
+
seq_transform: A module to asign scores to sequences
|
|
42
|
+
max_iter: Number of iterations
|
|
43
|
+
positions: Positions to mutate. If None, all positions will be mutated
|
|
44
|
+
devices: Device(s) for inference
|
|
45
|
+
num_workers: Number of workers for inference
|
|
46
|
+
batch_size: Batch size for inference
|
|
47
|
+
genome: genome to use if intervals are provided as starting sequences
|
|
48
|
+
for_each: If multiple start sequences are provided, perform directed
|
|
49
|
+
evolution independently from each one
|
|
50
|
+
return_seqs: "all", "best" or "none".
|
|
51
|
+
return_preds: If True, return all the individual model predictions in addition to the
|
|
52
|
+
model prediction score.
|
|
53
|
+
verbose: Print status after each iteration
|
|
54
|
+
|
|
55
|
+
Returns:
|
|
56
|
+
A dataframe containing directed evolution results
|
|
57
|
+
"""
|
|
58
|
+
from grelu.data.dataset import ISMDataset, MotifScanDataset, SeqDataset
|
|
59
|
+
|
|
60
|
+
# Empty dataframe to save outputs
|
|
61
|
+
outputs = pd.DataFrame()
|
|
62
|
+
|
|
63
|
+
# Initialize score for best sequence so far
|
|
64
|
+
best_score = -np.Inf
|
|
65
|
+
|
|
66
|
+
# Add prediction transform
|
|
67
|
+
model.add_transform(prediction_transform)
|
|
68
|
+
|
|
69
|
+
# Give each starting sequence a unique ID
|
|
70
|
+
start_seq_idxs = range(len(seqs))
|
|
71
|
+
|
|
72
|
+
# Create starting sequence dataset
|
|
73
|
+
ds = SeqDataset(seqs, genome=genome)
|
|
74
|
+
|
|
75
|
+
# Iterate
|
|
76
|
+
for i in range(max_iter + 1):
|
|
77
|
+
if verbose:
|
|
78
|
+
print(f"Iteration {i}")
|
|
79
|
+
|
|
80
|
+
# Make dataframe containing current iteration output
|
|
81
|
+
curr_output = pd.DataFrame.from_dict(
|
|
82
|
+
{
|
|
83
|
+
"iter": i,
|
|
84
|
+
"start_seq": start_seq_idxs,
|
|
85
|
+
"best_in_iter": False,
|
|
86
|
+
}
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
# Get position and allele
|
|
90
|
+
if i > 0:
|
|
91
|
+
curr_output[["position", "allele"]] = pd.DataFrame(
|
|
92
|
+
[ds.__getitem__(j, return_compressed=True) for j in range(len(ds))],
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
# Add prediction score
|
|
96
|
+
curr_output["prediction_score"] = model.predict_on_dataset(
|
|
97
|
+
dataset=ds,
|
|
98
|
+
devices=devices,
|
|
99
|
+
num_workers=num_workers,
|
|
100
|
+
batch_size=batch_size,
|
|
101
|
+
).flatten()
|
|
102
|
+
|
|
103
|
+
# Add sequence score
|
|
104
|
+
curr_output["seq_score"] = (
|
|
105
|
+
0
|
|
106
|
+
if seq_transform is None
|
|
107
|
+
else seq_transform(
|
|
108
|
+
[convert_input_type(ds[j], "strings") for j in range(len(ds))]
|
|
109
|
+
)
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
# Combine scores
|
|
113
|
+
curr_output["total_score"] = (
|
|
114
|
+
curr_output["prediction_score"] + curr_output["seq_score"]
|
|
115
|
+
)
|
|
116
|
+
|
|
117
|
+
# Mark best sequence(s) from current iteration
|
|
118
|
+
curr_best_idxs = (
|
|
119
|
+
curr_output.groupby("start_seq").total_score.idxmax()
|
|
120
|
+
if for_each
|
|
121
|
+
else curr_output.total_score.idxmax()
|
|
122
|
+
)
|
|
123
|
+
curr_output.loc[curr_best_idxs, "best_in_iter"] = True
|
|
124
|
+
|
|
125
|
+
# Add full sequences
|
|
126
|
+
if return_seqs == "all":
|
|
127
|
+
curr_output["seq"] = convert_input_type(
|
|
128
|
+
torch.stack([ds[j] for j in range(len(ds))]), "strings"
|
|
129
|
+
)
|
|
130
|
+
elif return_seqs == "best":
|
|
131
|
+
curr_output.loc[curr_best_idxs, "seq"] = convert_input_type(
|
|
132
|
+
torch.stack([ds[j] for j in curr_best_idxs]), "strings"
|
|
133
|
+
)
|
|
134
|
+
|
|
135
|
+
# Concatenate outputs
|
|
136
|
+
outputs = pd.concat([outputs, curr_output])
|
|
137
|
+
|
|
138
|
+
# Select the best sequences(s) from current iteration
|
|
139
|
+
best = curr_output.loc[
|
|
140
|
+
curr_best_idxs,
|
|
141
|
+
["seq", "start_seq", "total_score"],
|
|
142
|
+
]
|
|
143
|
+
overall_best_score = best.total_score.max()
|
|
144
|
+
if verbose:
|
|
145
|
+
# Print the best losses at current iteration
|
|
146
|
+
print(f"Best value at iteration {i}: {overall_best_score:.3f}")
|
|
147
|
+
|
|
148
|
+
# Check if best sequence is better than the previous best sequence
|
|
149
|
+
if overall_best_score > best_score:
|
|
150
|
+
best_score = overall_best_score
|
|
151
|
+
else:
|
|
152
|
+
print(f"Score did not increase on iteration: {i}")
|
|
153
|
+
break
|
|
154
|
+
|
|
155
|
+
# Mutate sequences for next iteration
|
|
156
|
+
if i < max_iter:
|
|
157
|
+
if method == "ism":
|
|
158
|
+
ds = ISMDataset(make_list(best.seq), positions=positions, drop_ref=True)
|
|
159
|
+
elif method == "pattern":
|
|
160
|
+
ds = MotifScanDataset(
|
|
161
|
+
make_list(best.seq), motifs=patterns, positions=positions
|
|
162
|
+
)
|
|
163
|
+
else:
|
|
164
|
+
raise NotImplementedError
|
|
165
|
+
|
|
166
|
+
start_seq_idxs = make_list(
|
|
167
|
+
best.start_seq.repeat(ds.n_augmented * ds.n_alleles)
|
|
168
|
+
)
|
|
169
|
+
|
|
170
|
+
# Remove the transform
|
|
171
|
+
model.reset_transform()
|
|
172
|
+
|
|
173
|
+
outputs = outputs.reset_index(drop=True)
|
|
174
|
+
|
|
175
|
+
# Get model predictions
|
|
176
|
+
if return_preds:
|
|
177
|
+
ds = SeqDataset(outputs.seq.dropna().tolist())
|
|
178
|
+
preds = model.predict_on_dataset(
|
|
179
|
+
ds,
|
|
180
|
+
devices=devices,
|
|
181
|
+
num_workers=num_workers,
|
|
182
|
+
batch_size=batch_size,
|
|
183
|
+
) # B T L
|
|
184
|
+
|
|
185
|
+
# Reshape the predictions for selected tasks
|
|
186
|
+
if prediction_transform is not None:
|
|
187
|
+
preds = preds[:, prediction_transform.tasks, :]
|
|
188
|
+
if prediction_transform.length_aggfunc_numpy is None:
|
|
189
|
+
preds = preds.squeeze(-1)
|
|
190
|
+
else:
|
|
191
|
+
preds = prediction_transform.length_aggfunc_numpy(
|
|
192
|
+
preds, axis=-1
|
|
193
|
+
) # B, T
|
|
194
|
+
|
|
195
|
+
# Get task names
|
|
196
|
+
task_names = [
|
|
197
|
+
model.data_params["tasks"]["name"][t]
|
|
198
|
+
for t in prediction_transform.tasks
|
|
199
|
+
]
|
|
200
|
+
|
|
201
|
+
else:
|
|
202
|
+
preds = preds.squeeze()
|
|
203
|
+
assert preds.ndim == 1
|
|
204
|
+
task_names = model.data_params["tasks"]["name"]
|
|
205
|
+
|
|
206
|
+
# Add model predictions to output dataframe
|
|
207
|
+
outputs[task_names] = np.nan
|
|
208
|
+
outputs.loc[~outputs.seq.isna(), task_names] = preds
|
|
209
|
+
|
|
210
|
+
return outputs
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
# Ledidi
|
|
214
|
+
def ledidi(
|
|
215
|
+
seq: str,
|
|
216
|
+
model: Callable,
|
|
217
|
+
prediction_transform: Optional[nn.Module] = None,
|
|
218
|
+
max_iter: int = 20000,
|
|
219
|
+
positions: Optional[List[int]] = None,
|
|
220
|
+
devices: Union[str, int] = "cpu",
|
|
221
|
+
num_workers: int = 1,
|
|
222
|
+
**kwargs,
|
|
223
|
+
):
|
|
224
|
+
"""
|
|
225
|
+
Sequence design with Ledidi
|
|
226
|
+
|
|
227
|
+
Args:
|
|
228
|
+
seq: an initial DNA sequence as a string.
|
|
229
|
+
model: A trained LightningModel object
|
|
230
|
+
prediction_transform: A module to transform the model output
|
|
231
|
+
max_iter: Number of iterations
|
|
232
|
+
positions: Positions to mutate. If None, all positions will be mutated
|
|
233
|
+
targets: List of targets for each loss function
|
|
234
|
+
devices: Index of device to use for inference
|
|
235
|
+
num_workers: Number of workers for inference
|
|
236
|
+
**kwargs: Other arguments to pass on to Ledidi
|
|
237
|
+
|
|
238
|
+
Returns:
|
|
239
|
+
Output DNA sequence(s) as strings.
|
|
240
|
+
|
|
241
|
+
"""
|
|
242
|
+
from ledidi import Ledidi
|
|
243
|
+
|
|
244
|
+
# Add the prediction transform
|
|
245
|
+
model.add_transform(prediction_transform)
|
|
246
|
+
|
|
247
|
+
def loss_func(x, target):
|
|
248
|
+
return -Tensor(x).mean()
|
|
249
|
+
|
|
250
|
+
# Convert sequence into a one-hot encoded tensor
|
|
251
|
+
X = convert_input_type(seq, "one_hot")
|
|
252
|
+
X = X.unsqueeze(0).to(torch.device(devices))
|
|
253
|
+
|
|
254
|
+
# Create input mask
|
|
255
|
+
if positions is not None:
|
|
256
|
+
input_mask = Tensor([True] * X.shape[-1]).type(torch.bool)
|
|
257
|
+
input_mask[positions] = False
|
|
258
|
+
else:
|
|
259
|
+
input_mask = None
|
|
260
|
+
|
|
261
|
+
# Move model to device
|
|
262
|
+
orig_device = model.device
|
|
263
|
+
model = model.to(torch.device(devices))
|
|
264
|
+
|
|
265
|
+
# Initialize ledidi
|
|
266
|
+
designer = Ledidi(
|
|
267
|
+
model,
|
|
268
|
+
X[0].shape,
|
|
269
|
+
output_loss=loss_func,
|
|
270
|
+
max_iter=max_iter,
|
|
271
|
+
input_mask=input_mask,
|
|
272
|
+
target=None,
|
|
273
|
+
**kwargs,
|
|
274
|
+
)
|
|
275
|
+
designer = designer.to(torch.device(devices))
|
|
276
|
+
|
|
277
|
+
# Run ledidi
|
|
278
|
+
X_hat = designer.fit_transform(X, None).cpu()
|
|
279
|
+
|
|
280
|
+
# Transfer device
|
|
281
|
+
model = model.to(orig_device)
|
|
282
|
+
|
|
283
|
+
# Remove the transform
|
|
284
|
+
model.reset_transform()
|
|
285
|
+
|
|
286
|
+
# Return sequences as strings
|
|
287
|
+
return convert_input_type(X_hat, "strings")
|
|
File without changes
|
|
@@ -0,0 +1,319 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Functions related to manipulating sequence motifs and scanning DNA sequences with motifs.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from typing import Callable, Generator, List, Optional, Tuple, Union
|
|
6
|
+
|
|
7
|
+
import numpy as np
|
|
8
|
+
import pandas as pd
|
|
9
|
+
from pymemesuite.common import Motif
|
|
10
|
+
|
|
11
|
+
from grelu.utils import make_list
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def motifs_to_strings(
|
|
15
|
+
motifs: Union[Motif, List[Motif], str],
|
|
16
|
+
names: Optional[List[str]] = None,
|
|
17
|
+
sample: bool = False,
|
|
18
|
+
rng: Optional[Generator] = None,
|
|
19
|
+
) -> str:
|
|
20
|
+
"""
|
|
21
|
+
Extracts a matching DNA sequence from a motif
|
|
22
|
+
|
|
23
|
+
Args:
|
|
24
|
+
motifs: A pymemesuite.common.Motif object, a list of such objects,
|
|
25
|
+
or the path to a MEME file.
|
|
26
|
+
names: A list of motif names to read from the MEME file, in case a MEME
|
|
27
|
+
file is supplied in motifs. If None, all motifs in the file will be read.
|
|
28
|
+
sample: If True, a sequence will be sampled from the motif.
|
|
29
|
+
Otherwise, the best match sequence will be returned.
|
|
30
|
+
rng: np.random.RandomState object
|
|
31
|
+
|
|
32
|
+
Returns:
|
|
33
|
+
DNA sequence(s) as strings
|
|
34
|
+
"""
|
|
35
|
+
from grelu.io.meme import read_meme_file
|
|
36
|
+
from grelu.sequence.format import indices_to_strings
|
|
37
|
+
|
|
38
|
+
# Set random seed
|
|
39
|
+
rng = rng or np.random.RandomState(seed=None)
|
|
40
|
+
|
|
41
|
+
# Convert a single motif
|
|
42
|
+
if isinstance(motifs, Motif):
|
|
43
|
+
# Extract probabilities
|
|
44
|
+
probs = np.array(motifs.frequencies)
|
|
45
|
+
|
|
46
|
+
# Extract sequence as indices
|
|
47
|
+
if sample:
|
|
48
|
+
indices = np.array(
|
|
49
|
+
[rng.multinomial(1, p).argmax() for p in probs], dtype=np.int8
|
|
50
|
+
)
|
|
51
|
+
else:
|
|
52
|
+
indices = probs.argmax(1).astype(np.int8)
|
|
53
|
+
|
|
54
|
+
# Return strings
|
|
55
|
+
return indices_to_strings(indices)
|
|
56
|
+
|
|
57
|
+
# Convert multiple motifs
|
|
58
|
+
elif isinstance(motifs, List):
|
|
59
|
+
return [motifs_to_strings(motif, rng=rng, sample=sample) for motif in motifs]
|
|
60
|
+
else:
|
|
61
|
+
motifs, _ = read_meme_file(motifs, names=make_list(names))
|
|
62
|
+
return motifs_to_strings(motifs, rng=rng, sample=sample)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def trim_pwm(
|
|
66
|
+
pwm: np.array,
|
|
67
|
+
trim_threshold: float = 0.3,
|
|
68
|
+
padding: int = 0,
|
|
69
|
+
return_indices: bool = False,
|
|
70
|
+
) -> Union[Tuple[int], np.array]:
|
|
71
|
+
"""
|
|
72
|
+
Trims the edges of a PWM based on information content.
|
|
73
|
+
|
|
74
|
+
Args:
|
|
75
|
+
pwm: PWM array of shape (L, 4)
|
|
76
|
+
trim_threshold: Threshold ranging from 0 to 1 to trim edge positions
|
|
77
|
+
padding: Number of low-information positions on either end to allow
|
|
78
|
+
return_indices: If True, only the indices of the positions to keep
|
|
79
|
+
will be returned. If False, the trimmed motif will be returned.
|
|
80
|
+
|
|
81
|
+
Returns:
|
|
82
|
+
np.array containing the trimmed PWM (if return_indices = True) or a
|
|
83
|
+
tuple of ints for the start and end positions of the trimmed motif
|
|
84
|
+
(if return_indices = False).
|
|
85
|
+
"""
|
|
86
|
+
# Get per position score
|
|
87
|
+
score = np.sum(np.abs(pwm), axis=1)
|
|
88
|
+
|
|
89
|
+
# Calculate score threshold
|
|
90
|
+
trim_thresh = np.max(score) * trim_threshold
|
|
91
|
+
|
|
92
|
+
# Get indices that pass the threshold
|
|
93
|
+
pass_inds = np.where(score >= trim_thresh)[0]
|
|
94
|
+
|
|
95
|
+
# Get the start and end of the trimmed motif
|
|
96
|
+
start = max(np.min(pass_inds) - padding, 0)
|
|
97
|
+
end = min(np.max(pass_inds) + padding + 1, len(score) + 1)
|
|
98
|
+
|
|
99
|
+
if return_indices:
|
|
100
|
+
return start, end
|
|
101
|
+
else:
|
|
102
|
+
return pwm[start:end]
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def scan_sequences(
|
|
106
|
+
seqs: List[str],
|
|
107
|
+
motifs: Union[Motif, List[Motif], str],
|
|
108
|
+
names: Optional[List[str]] = None,
|
|
109
|
+
bg=None,
|
|
110
|
+
seq_ids: Optional[List[str]] = None,
|
|
111
|
+
pthresh: float = 1e-3,
|
|
112
|
+
rc: bool = True,
|
|
113
|
+
):
|
|
114
|
+
"""
|
|
115
|
+
Scan a DNA sequence using motifs
|
|
116
|
+
|
|
117
|
+
Args:
|
|
118
|
+
seqs: A list of DNA sequences as strings
|
|
119
|
+
motifs: A list of pymemesuite.common.Motif objects,
|
|
120
|
+
or the path to a MEME file.
|
|
121
|
+
names: A list of motif names to read from the MEME file.
|
|
122
|
+
If None, all motifs in the file will be read.
|
|
123
|
+
bg: A background distribution for motif p-value calculations.
|
|
124
|
+
Only needed if a list of Motif objects is supplied instead
|
|
125
|
+
of a MEME file.
|
|
126
|
+
seq_ids: Optional list of IDs for sequences
|
|
127
|
+
pthresh: p-value cutoff for binding sites
|
|
128
|
+
rc: If True, both the sequence and its reverse complement will be
|
|
129
|
+
scanned. If False, only the given sequence will be scanned.
|
|
130
|
+
|
|
131
|
+
Returns:
|
|
132
|
+
pd.DataFrame containing columns 'motif', 'sequence', 'start', 'end',
|
|
133
|
+
'strand', 'score' and 'pval'.
|
|
134
|
+
"""
|
|
135
|
+
from collections import defaultdict
|
|
136
|
+
|
|
137
|
+
from pymemesuite.common import Sequence
|
|
138
|
+
from pymemesuite.fimo import FIMO
|
|
139
|
+
|
|
140
|
+
from grelu.io.meme import read_meme_file
|
|
141
|
+
|
|
142
|
+
# Load motifs
|
|
143
|
+
if isinstance(motifs, str):
|
|
144
|
+
motifs, bg = read_meme_file(motifs, names=names)
|
|
145
|
+
|
|
146
|
+
# Format sequences
|
|
147
|
+
seqs = make_list(seqs)
|
|
148
|
+
if seq_ids is None:
|
|
149
|
+
seq_ids = [str(i) for i in range(len(seqs))]
|
|
150
|
+
sequences = [Sequence(seq, name=id.encode()) for id, seq in zip(seq_ids, seqs)]
|
|
151
|
+
|
|
152
|
+
# Setup FIMO
|
|
153
|
+
fimo = FIMO(both_strands=rc, threshold=pthresh)
|
|
154
|
+
|
|
155
|
+
# Empty dictionary for output
|
|
156
|
+
out = defaultdict(list)
|
|
157
|
+
|
|
158
|
+
# Scan
|
|
159
|
+
for motif in motifs:
|
|
160
|
+
match = fimo.score_motif(motif, sequences, bg).matched_elements
|
|
161
|
+
for m in match:
|
|
162
|
+
out["motif"].append(motif.name.decode())
|
|
163
|
+
out["sequence"].append(m.source.accession.decode())
|
|
164
|
+
out["start"].append(m.start)
|
|
165
|
+
out["end"].append(m.stop)
|
|
166
|
+
out["strand"].append(m.strand)
|
|
167
|
+
out["score"].append(m.score)
|
|
168
|
+
out["pval"].append(m.pvalue)
|
|
169
|
+
|
|
170
|
+
return pd.DataFrame(out)
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def marginalize_patterns(
|
|
174
|
+
model: Callable,
|
|
175
|
+
patterns: Union[str, List[str]],
|
|
176
|
+
seqs: Union[pd.DataFrame, List[str], np.ndarray],
|
|
177
|
+
genome: Optional[str] = None,
|
|
178
|
+
devices: Union[str, int, List[int]] = "cpu",
|
|
179
|
+
num_workers: int = 1,
|
|
180
|
+
batch_size: int = 64,
|
|
181
|
+
n_shuffles: int = 0,
|
|
182
|
+
seed: Optional[int] = None,
|
|
183
|
+
prediction_transform: Optional[Callable] = None,
|
|
184
|
+
rc: bool = False,
|
|
185
|
+
compare_func: Optional[Union[str, Callable]] = None,
|
|
186
|
+
) -> Union[np.ndarray, Tuple[np.ndarray, np.ndarray]]:
|
|
187
|
+
"""
|
|
188
|
+
Runs a marginalization experiment.
|
|
189
|
+
|
|
190
|
+
Given a model, a pattern (short sequence) to insert, and a set of background
|
|
191
|
+
sequences, get the predictions from the model before and after
|
|
192
|
+
inserting the patterns into the (optionally shuffled) background sequences.
|
|
193
|
+
|
|
194
|
+
Args:
|
|
195
|
+
model: trained model
|
|
196
|
+
patterns: a sequence or list of sequences to insert
|
|
197
|
+
seqs: background sequences
|
|
198
|
+
genome: Name of the genome to use if genomic intervals are supplied
|
|
199
|
+
device: Index of device on which to run inference
|
|
200
|
+
num_workers: Number of workers for inference
|
|
201
|
+
batch_size: Batch size for inference
|
|
202
|
+
seed: Random seed
|
|
203
|
+
prediction_transform: A module to transform the model output
|
|
204
|
+
rc: If True, augment by reverse complementation
|
|
205
|
+
compare_func: Function to compare the predictions with and without the pattern. Options
|
|
206
|
+
are "divide" or "subtract". If not provided, the predictions for
|
|
207
|
+
the shuffled sequences and each pattern will be returned.
|
|
208
|
+
|
|
209
|
+
Returns:
|
|
210
|
+
preds_before: The predictions from the background sequences
|
|
211
|
+
preds_after: The predictions after inserting the pattern into
|
|
212
|
+
the background sequences.
|
|
213
|
+
"""
|
|
214
|
+
# Create torch dataset
|
|
215
|
+
from grelu.data.dataset import PatternMarginalizeDataset
|
|
216
|
+
from grelu.utils import get_compare_func
|
|
217
|
+
|
|
218
|
+
# Set transform
|
|
219
|
+
model.add_transform(prediction_transform)
|
|
220
|
+
|
|
221
|
+
# Make marginalization dataset
|
|
222
|
+
ds = PatternMarginalizeDataset(
|
|
223
|
+
seqs=seqs,
|
|
224
|
+
patterns=patterns,
|
|
225
|
+
genome=genome,
|
|
226
|
+
rc=rc,
|
|
227
|
+
n_shuffles=n_shuffles,
|
|
228
|
+
)
|
|
229
|
+
|
|
230
|
+
# Get predictions on the sequences before motif insertion
|
|
231
|
+
preds = model.predict_on_dataset(
|
|
232
|
+
ds,
|
|
233
|
+
devices=devices,
|
|
234
|
+
num_workers=num_workers,
|
|
235
|
+
batch_size=batch_size,
|
|
236
|
+
augment_aggfunc=None,
|
|
237
|
+
) # Output shape: B, shuf x augment, motifs+1, 1, 1
|
|
238
|
+
preds = preds.squeeze(axis=(-1, -2)) # B, shufxaugment, motifs+1
|
|
239
|
+
|
|
240
|
+
# Drop transform
|
|
241
|
+
model.reset_transform()
|
|
242
|
+
|
|
243
|
+
# Extract the reference sequence predictions
|
|
244
|
+
before_preds, after_preds = preds[:, :, [0]], preds[:, :, 1:]
|
|
245
|
+
|
|
246
|
+
if compare_func is None:
|
|
247
|
+
return before_preds, after_preds
|
|
248
|
+
else:
|
|
249
|
+
return get_compare_func(compare_func)(after_preds, before_preds)
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def compare_motifs(
|
|
253
|
+
ref_seq: Union[str, pd.DataFrame],
|
|
254
|
+
motifs: Union[Motif, List[Motif], str],
|
|
255
|
+
alt_seq: Optional[str] = None,
|
|
256
|
+
alt_allele: Optional[str] = None,
|
|
257
|
+
pos: Optional[int] = None,
|
|
258
|
+
names: Optional[List[str]] = None,
|
|
259
|
+
bg=None,
|
|
260
|
+
pthresh: float = 1e-3,
|
|
261
|
+
rc: bool = True,
|
|
262
|
+
) -> pd.DataFrame:
|
|
263
|
+
"""
|
|
264
|
+
Scan sequences containing the reference and alternate alleles
|
|
265
|
+
to identify affected motifs.
|
|
266
|
+
|
|
267
|
+
Args:
|
|
268
|
+
ref_seq: The reference sequence as a string
|
|
269
|
+
motifs: A list of pymemesuite.common.Motif objects,
|
|
270
|
+
or the path to a MEME file.
|
|
271
|
+
alt_seq: The alternate sequence as a string
|
|
272
|
+
ref_allele: The alternate allele as a string. Only used if
|
|
273
|
+
alt_seq is not supplied.
|
|
274
|
+
alt_allele: The alternate allele as a string. Only needed if
|
|
275
|
+
alt_seq is not supplied.
|
|
276
|
+
pos: The position at which to substitute the alternate allele.
|
|
277
|
+
Only needed if alt_seq is not supplied.
|
|
278
|
+
names: A list of motif names to read from the MEME file.
|
|
279
|
+
If None, all motifs in the file will be read.
|
|
280
|
+
bg: A background distribution for motif p-value calculations.
|
|
281
|
+
Only needed if a list of Motif objects is supplied instead
|
|
282
|
+
of a MEME file.
|
|
283
|
+
pthresh: p-value cutoff for binding sites
|
|
284
|
+
rc: If True, both the sequence and its reverse complement will be
|
|
285
|
+
scanned. If False, only the given sequence will be scanned.
|
|
286
|
+
"""
|
|
287
|
+
from grelu.interpret.motifs import scan_sequences
|
|
288
|
+
from grelu.sequence.mutate import mutate
|
|
289
|
+
|
|
290
|
+
# Create alt sequence
|
|
291
|
+
if alt_seq is None:
|
|
292
|
+
assert alt_allele is not None, "Either alt_seq or alt_allele must be supplied."
|
|
293
|
+
alt_seq = mutate(seq=ref_seq, allele=alt_allele, pos=pos, input_type="strings")
|
|
294
|
+
|
|
295
|
+
# Scan sequences
|
|
296
|
+
scan = scan_sequences(
|
|
297
|
+
seqs=[ref_seq, alt_seq],
|
|
298
|
+
motifs=motifs,
|
|
299
|
+
names=names,
|
|
300
|
+
seq_ids=["ref", "alt"],
|
|
301
|
+
pthresh=pthresh,
|
|
302
|
+
rc=True, # Scan both strands
|
|
303
|
+
)
|
|
304
|
+
|
|
305
|
+
# Compare the results for alt and ref sequences
|
|
306
|
+
scan = (
|
|
307
|
+
scan.pivot_table(
|
|
308
|
+
index=["motif", "start", "end", "strand"],
|
|
309
|
+
columns=["sequence"],
|
|
310
|
+
values="score",
|
|
311
|
+
)
|
|
312
|
+
.fillna(0)
|
|
313
|
+
.reset_index()
|
|
314
|
+
)
|
|
315
|
+
|
|
316
|
+
# Compute fold change
|
|
317
|
+
scan["foldChange"] = scan.alt / scan.ref
|
|
318
|
+
scan = scan.sort_values("foldChange").reset_index(drop=True)
|
|
319
|
+
return scan
|