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/interpret/score.py
ADDED
|
@@ -0,0 +1,390 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Functions related to scoring the importance of individual DNA bases.
|
|
3
|
+
"""
|
|
4
|
+
import os
|
|
5
|
+
import warnings
|
|
6
|
+
from typing import Callable, List, Optional, Union
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
import pandas as pd
|
|
10
|
+
import torch
|
|
11
|
+
from captum.attr import InputXGradient, IntegratedGradients
|
|
12
|
+
from tangermeme.deep_lift_shap import deep_lift_shap
|
|
13
|
+
from torch import Tensor
|
|
14
|
+
|
|
15
|
+
from grelu.model.models import EnformerModel, EnformerPretrainedModel
|
|
16
|
+
from grelu.sequence.format import convert_input_type
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def ISM_predict(
|
|
20
|
+
seqs: Union[pd.DataFrame, np.ndarray, str],
|
|
21
|
+
model: Callable,
|
|
22
|
+
genome: Optional[str] = None,
|
|
23
|
+
prediction_transform: Optional[Callable] = None,
|
|
24
|
+
start_pos: int = 0,
|
|
25
|
+
end_pos: Optional[int] = None,
|
|
26
|
+
compare_func: Optional[Union[str, Callable]] = None,
|
|
27
|
+
devices: Union[str, List[int]] = "cpu",
|
|
28
|
+
num_workers: int = 1,
|
|
29
|
+
batch_size: int = 64,
|
|
30
|
+
return_df: bool = True,
|
|
31
|
+
) -> Union[np.array, pd.DataFrame]:
|
|
32
|
+
"""
|
|
33
|
+
Predicts the importance scores of each nucleotide position in a given DNA sequence
|
|
34
|
+
using the In Silico Mutagenesis (ISM) method.
|
|
35
|
+
|
|
36
|
+
Args:
|
|
37
|
+
seqs: Input DNA sequences as genomic intervals, strings, or integer-encoded form.
|
|
38
|
+
genome: Name of the genome to use if a genomic interval is supplied.
|
|
39
|
+
model: A pre-trained deep learning model
|
|
40
|
+
prediction_transform: A module to transform the model output
|
|
41
|
+
start_pos: Index of the position to start applying ISM
|
|
42
|
+
end_pos: Index of the position to stop applying ISM
|
|
43
|
+
compare_func: A function or name of a function to compare the predictions for mutated
|
|
44
|
+
and reference sequences. Allowed names are "divide", "subtract" and "log2FC".
|
|
45
|
+
If not provided, the raw predictions for both mutant and reference sequences will
|
|
46
|
+
be returned.
|
|
47
|
+
devices: Indices of the devices on which to run inference
|
|
48
|
+
num_workers: number of workers for inference
|
|
49
|
+
batch_size: batch size for model inference
|
|
50
|
+
return_df: If True, the ISM results will be returned as a dataframe. Otherwise, they
|
|
51
|
+
will be returned as a Numpy array.
|
|
52
|
+
|
|
53
|
+
Returns:
|
|
54
|
+
A numpy array of the predicted scores for each nucleotide position (if return_df = False)
|
|
55
|
+
or a pandas dataframe with A, C, G, and T as row labels and the bases at each position
|
|
56
|
+
of the sequence as column labels (if return_df = True).
|
|
57
|
+
"""
|
|
58
|
+
from grelu.data.dataset import ISMDataset
|
|
59
|
+
from grelu.sequence.format import BASE_TO_INDEX_HASH, STANDARD_BASES
|
|
60
|
+
from grelu.sequence.utils import get_unique_length
|
|
61
|
+
from grelu.utils import get_compare_func, make_list
|
|
62
|
+
|
|
63
|
+
# Get sequence as string
|
|
64
|
+
seqs = convert_input_type(seqs, "strings", genome=genome)
|
|
65
|
+
seqs = make_list(seqs)
|
|
66
|
+
|
|
67
|
+
# Get the last position to mutate
|
|
68
|
+
if end_pos is None:
|
|
69
|
+
end_pos = get_unique_length(seqs)
|
|
70
|
+
|
|
71
|
+
# Make dataset
|
|
72
|
+
ism = ISMDataset(
|
|
73
|
+
seqs=seqs,
|
|
74
|
+
positions=range(start_pos, end_pos),
|
|
75
|
+
drop_ref=False,
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
# Add transform to model
|
|
79
|
+
model.add_transform(prediction_transform)
|
|
80
|
+
|
|
81
|
+
# Get predictions for all mutated sequences
|
|
82
|
+
preds = model.predict_on_dataset(
|
|
83
|
+
ism,
|
|
84
|
+
devices=devices,
|
|
85
|
+
num_workers=num_workers,
|
|
86
|
+
batch_size=batch_size,
|
|
87
|
+
)
|
|
88
|
+
# B, L, 4, T, L
|
|
89
|
+
|
|
90
|
+
# Calculate log ratio w.r.t reference sequence
|
|
91
|
+
if compare_func is not None:
|
|
92
|
+
ref_bases = [BASE_TO_INDEX_HASH[seq[start_pos]] for seq in seqs]
|
|
93
|
+
ref_pred = preds[:, [0], [ref_bases], :] # B, 1, 1, T, L
|
|
94
|
+
preds = get_compare_func(compare_func, tensor=False)(preds, ref_pred)
|
|
95
|
+
|
|
96
|
+
# Convert into a dataframe
|
|
97
|
+
if return_df:
|
|
98
|
+
if (preds.shape[0] == 1) and (preds.shape[3:] == (1, 1)):
|
|
99
|
+
preds = preds.squeeze(axis=(0, 3, 4)) # L, 4
|
|
100
|
+
preds = pd.DataFrame(
|
|
101
|
+
preds.T, # 4, L
|
|
102
|
+
index=STANDARD_BASES,
|
|
103
|
+
columns=[b for b in seqs[0][start_pos:end_pos]],
|
|
104
|
+
)
|
|
105
|
+
else:
|
|
106
|
+
warnings.warn(
|
|
107
|
+
"Cannot return a dataframe as either multiple sequences are \
|
|
108
|
+
supplied or the model predictions are multi-dimensional. Returning Numpy array."
|
|
109
|
+
)
|
|
110
|
+
|
|
111
|
+
# Remove transform
|
|
112
|
+
model.reset_transform()
|
|
113
|
+
return preds
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def get_attributions(
|
|
117
|
+
model,
|
|
118
|
+
seqs: Union[pd.DataFrame, np.array, List[str]],
|
|
119
|
+
genome: Optional[str] = None,
|
|
120
|
+
prediction_transform: Optional[Callable] = None,
|
|
121
|
+
device: Union[str, int] = "cpu",
|
|
122
|
+
method: str = "deepshap",
|
|
123
|
+
hypothetical: bool = False,
|
|
124
|
+
n_shuffles: int = 20,
|
|
125
|
+
seed=None,
|
|
126
|
+
**kwargs,
|
|
127
|
+
) -> np.array:
|
|
128
|
+
"""
|
|
129
|
+
Get per-nucleotide importance scores for sequences using Captum.
|
|
130
|
+
|
|
131
|
+
Args:
|
|
132
|
+
model: A trained deep learning model
|
|
133
|
+
seqs: input DNA sequences as genomic intervals, strings, or integer-encoded form.
|
|
134
|
+
genome: Name of the genome to use if a genomic interval is supplied.
|
|
135
|
+
prediction_transform: A module to transform the model output
|
|
136
|
+
devices: Indices of the devices to use for inference
|
|
137
|
+
method: One of "deepshap", "saliency", "inputxgradient" or "integratedgradients"
|
|
138
|
+
hypothetical: whether to calculate hypothetical importance scores.
|
|
139
|
+
Set this to True to obtain input for tf-modisco, False otherwise
|
|
140
|
+
n_shuffles: Number of times to dinucleotide shuffle sequence
|
|
141
|
+
seed: Random seed
|
|
142
|
+
**kwargs: Additional arguments to pass to tangermeme.deep_lift_shap.deep_lift_shap
|
|
143
|
+
|
|
144
|
+
Returns:
|
|
145
|
+
Per-nucleotide importance scores as numpy array of shape (B, 4, L).
|
|
146
|
+
"""
|
|
147
|
+
# One-hot encode the input
|
|
148
|
+
seqs = convert_input_type(seqs, "one_hot", genome=genome, add_batch_axis=True)
|
|
149
|
+
|
|
150
|
+
# Add transform to model
|
|
151
|
+
model.add_transform(prediction_transform)
|
|
152
|
+
model = model.eval()
|
|
153
|
+
|
|
154
|
+
# Empty list for the output
|
|
155
|
+
attributions = []
|
|
156
|
+
|
|
157
|
+
# Check hypothetical
|
|
158
|
+
if hypothetical:
|
|
159
|
+
assert method == "deepshap", "hypothetical = True requires deepshap."
|
|
160
|
+
|
|
161
|
+
# Initialize the attributer
|
|
162
|
+
if method == "deepshap":
|
|
163
|
+
if isinstance(model.model, EnformerModel) or isinstance(
|
|
164
|
+
model.model, EnformerPretrainedModel
|
|
165
|
+
):
|
|
166
|
+
raise NotImplementedError(
|
|
167
|
+
"DeepShap currently cannot be applied to Enformer models."
|
|
168
|
+
)
|
|
169
|
+
else:
|
|
170
|
+
attributions = deep_lift_shap(
|
|
171
|
+
model,
|
|
172
|
+
X=seqs,
|
|
173
|
+
n_shuffles=n_shuffles,
|
|
174
|
+
hypothetical=hypothetical,
|
|
175
|
+
device=device,
|
|
176
|
+
random_state=seed,
|
|
177
|
+
**kwargs,
|
|
178
|
+
).numpy(force=True)
|
|
179
|
+
|
|
180
|
+
else:
|
|
181
|
+
if method == "integratedgradients":
|
|
182
|
+
attributer = IntegratedGradients(model.to(device))
|
|
183
|
+
elif method == "inputxgradient":
|
|
184
|
+
attributer = InputXGradient(model.to(device))
|
|
185
|
+
else:
|
|
186
|
+
raise NotImplementedError
|
|
187
|
+
|
|
188
|
+
# Calculate attributions for each sequence
|
|
189
|
+
with torch.no_grad():
|
|
190
|
+
for i in range(len(seqs)):
|
|
191
|
+
X_ = seqs[i : i + 1].to(device) # 1, 4, L
|
|
192
|
+
attr = attributer.attribute(X_)
|
|
193
|
+
attributions.append(attr.cpu().numpy())
|
|
194
|
+
|
|
195
|
+
attributions = np.vstack(attributions)
|
|
196
|
+
|
|
197
|
+
# Remove transform
|
|
198
|
+
model.reset_transform()
|
|
199
|
+
return attributions # N, 4, L
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def run_modisco(
|
|
203
|
+
model,
|
|
204
|
+
seqs: Union[pd.DataFrame, np.array, List[str]],
|
|
205
|
+
genome: Optional[str] = None,
|
|
206
|
+
prediction_transform: Optional[Callable] = None,
|
|
207
|
+
window: int = None,
|
|
208
|
+
meme_file: str = None,
|
|
209
|
+
out_dir: str = "outputs",
|
|
210
|
+
devices: Union[str, int] = "cpu",
|
|
211
|
+
num_workers: int = 1,
|
|
212
|
+
batch_size: int = 64,
|
|
213
|
+
n_shuffles: int = 10,
|
|
214
|
+
seed=None,
|
|
215
|
+
method: str = "deepshap",
|
|
216
|
+
**kwargs,
|
|
217
|
+
):
|
|
218
|
+
"""
|
|
219
|
+
Run TF-Modisco to get relevant motifs for a set of inputs, and optionally score the
|
|
220
|
+
motifs against a reference set of motifs using TOMTOM
|
|
221
|
+
|
|
222
|
+
Args:
|
|
223
|
+
model: A trained deep learning model
|
|
224
|
+
seqs: Input DNA sequences as genomic intervals, strings, or integer-encoded form.
|
|
225
|
+
genome: Name of the genome to use. Only used if genomic intervals are provided.
|
|
226
|
+
prediction_transform: A module to transform the model output
|
|
227
|
+
window: Sequence length over which to consider attributions
|
|
228
|
+
meme_file: Path to a MEME file containing reference motifs for TOMTOM.
|
|
229
|
+
out_dir: Output directory
|
|
230
|
+
devices: Indices of devices to use for model inference
|
|
231
|
+
num_workers: Number of workers to use for model inference
|
|
232
|
+
batch_size: Batch size to use for model inference
|
|
233
|
+
n_shuffles: Number of times to shuffle the background sequences for deepshap.
|
|
234
|
+
seed: Random seed
|
|
235
|
+
method: Either "deepshap" or "ism".
|
|
236
|
+
**kwargs: Additional arguments to pass to TF-Modisco.
|
|
237
|
+
|
|
238
|
+
Raises:
|
|
239
|
+
NotImplementedError: if the method is neither "deepshap" nor "ism"
|
|
240
|
+
"""
|
|
241
|
+
import modiscolite
|
|
242
|
+
|
|
243
|
+
from grelu.data.dataset import ISMDataset, SeqDataset
|
|
244
|
+
from grelu.resources import get_meme_file_path
|
|
245
|
+
from grelu.sequence.utils import get_unique_length
|
|
246
|
+
|
|
247
|
+
# Get start and end positions
|
|
248
|
+
if window is None:
|
|
249
|
+
start = 0
|
|
250
|
+
end = get_unique_length(seqs)
|
|
251
|
+
else:
|
|
252
|
+
center = get_unique_length(seqs) // 2
|
|
253
|
+
start = center - window // 2
|
|
254
|
+
end = start + window
|
|
255
|
+
|
|
256
|
+
# Get one-hot encoded sequence
|
|
257
|
+
one_hot = convert_input_type(seqs, "one_hot", genome=genome)
|
|
258
|
+
one_hot_arr = one_hot[:, :, start:end].numpy()
|
|
259
|
+
|
|
260
|
+
if method == "deepshap":
|
|
261
|
+
print("Getting attributions")
|
|
262
|
+
attrs = get_attributions(
|
|
263
|
+
model=model,
|
|
264
|
+
seqs=one_hot,
|
|
265
|
+
prediction_transform=prediction_transform,
|
|
266
|
+
device=devices,
|
|
267
|
+
n_shuffles=n_shuffles,
|
|
268
|
+
method=method,
|
|
269
|
+
hypothetical=True,
|
|
270
|
+
genome=genome,
|
|
271
|
+
seed=seed,
|
|
272
|
+
)
|
|
273
|
+
attrs = attrs[:, :, start:end]
|
|
274
|
+
|
|
275
|
+
elif method == "ism":
|
|
276
|
+
print("Performing ISM")
|
|
277
|
+
ref_ds = SeqDataset(seqs, genome=genome)
|
|
278
|
+
ism_ds = ISMDataset(
|
|
279
|
+
seqs, drop_ref=True, positions=range(start, end), genome=genome
|
|
280
|
+
)
|
|
281
|
+
|
|
282
|
+
# Add transform to model
|
|
283
|
+
model.add_transform(prediction_transform)
|
|
284
|
+
|
|
285
|
+
# Get predictions for reference sequences
|
|
286
|
+
ref_preds = model.predict_on_dataset(
|
|
287
|
+
ref_ds, devices=devices, num_workers=num_workers, batch_size=batch_size
|
|
288
|
+
) # B, 1, T, L
|
|
289
|
+
assert (ref_preds.shape[-1] == 1) and (ref_preds.shape[-2] == 1)
|
|
290
|
+
|
|
291
|
+
# Get predictions for all mutated sequences
|
|
292
|
+
ism_preds = model.predict_on_dataset(
|
|
293
|
+
ism_ds,
|
|
294
|
+
devices=devices,
|
|
295
|
+
num_workers=num_workers,
|
|
296
|
+
batch_size=batch_size,
|
|
297
|
+
) # B, l, 3, 1, 1
|
|
298
|
+
assert (ism_preds.shape[-1] == 1) and (ism_preds.shape[-2] == 1)
|
|
299
|
+
ism_preds = ism_preds.squeeze((-1, -2)) # B, l, 3
|
|
300
|
+
|
|
301
|
+
# Remove transform
|
|
302
|
+
model.reset_transform()
|
|
303
|
+
|
|
304
|
+
# Get the negative log ratio
|
|
305
|
+
attrs = -np.log2(np.divide(ism_preds, ref_preds)) # B, l, 3
|
|
306
|
+
|
|
307
|
+
# Mean over all possible mutations
|
|
308
|
+
attrs = np.expand_dims(attrs.mean(-1), 1) # B, 1, l
|
|
309
|
+
|
|
310
|
+
# Multiply by original sequence
|
|
311
|
+
attrs = np.multiply(attrs, one_hot_arr) # B, 4, l
|
|
312
|
+
|
|
313
|
+
else:
|
|
314
|
+
raise NotImplementedError
|
|
315
|
+
|
|
316
|
+
print("Running modisco")
|
|
317
|
+
one_hot_arr = one_hot_arr.transpose(0, 2, 1).astype("float32")
|
|
318
|
+
attrs = attrs.transpose(0, 2, 1).astype("float32")
|
|
319
|
+
pos_patterns, neg_patterns = modiscolite.tfmodisco.TFMoDISco(
|
|
320
|
+
hypothetical_contribs=attrs,
|
|
321
|
+
one_hot=one_hot_arr,
|
|
322
|
+
**kwargs,
|
|
323
|
+
)
|
|
324
|
+
|
|
325
|
+
print("Writing modisco output")
|
|
326
|
+
if not os.path.exists(out_dir):
|
|
327
|
+
os.makedirs(out_dir)
|
|
328
|
+
|
|
329
|
+
h5_file = os.path.join(out_dir, "modisco_report.h5")
|
|
330
|
+
modiscolite.io.save_hdf5(h5_file, pos_patterns, neg_patterns, window_size=20)
|
|
331
|
+
|
|
332
|
+
if meme_file is not None:
|
|
333
|
+
print("Making report")
|
|
334
|
+
meme_file = get_meme_file_path(meme_file)
|
|
335
|
+
modiscolite.report.report_motifs(
|
|
336
|
+
h5_file,
|
|
337
|
+
out_dir,
|
|
338
|
+
is_writing_tomtom_matrix=True,
|
|
339
|
+
top_n_matches=10,
|
|
340
|
+
meme_motif_db=meme_file,
|
|
341
|
+
img_path_suffix="./",
|
|
342
|
+
trim_threshold=0.2,
|
|
343
|
+
)
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
def get_attention_scores(
|
|
347
|
+
model,
|
|
348
|
+
seqs: Union[pd.DataFrame, str, np.ndarray, Tensor],
|
|
349
|
+
block_idx: Optional[int] = None,
|
|
350
|
+
genome: Optional[str] = None,
|
|
351
|
+
) -> np.ndarray:
|
|
352
|
+
"""
|
|
353
|
+
Get the attention scores from a model's transformer layers, for a given input sequence.
|
|
354
|
+
|
|
355
|
+
Args:
|
|
356
|
+
model: A trained deep learning model
|
|
357
|
+
seq: Input sequences as genoic intervals, strings or in index or one-hot encoded format.
|
|
358
|
+
block_idx: Index of the transformer layer to use, ranging from 0 to n_transformers-1.
|
|
359
|
+
If None, attention scores from all transformer layers will be returned.
|
|
360
|
+
genome: Name of the genome to use if genomic intervals are supplied.
|
|
361
|
+
|
|
362
|
+
Returns:
|
|
363
|
+
Numpy array of shape (Layers, Heads, L, L) if block_idx is None or (Heads, L, L) otherwise.
|
|
364
|
+
"""
|
|
365
|
+
# One-hot encode the input sequence
|
|
366
|
+
x = convert_input_type(seqs, "one_hot", genome=genome)
|
|
367
|
+
if x.ndim == 2:
|
|
368
|
+
x = x.unsqueeze(0)
|
|
369
|
+
|
|
370
|
+
# Pass input through convolutional layers
|
|
371
|
+
x = model.model.embedding.conv_tower(x)
|
|
372
|
+
if isinstance(x, tuple):
|
|
373
|
+
x = x[0]
|
|
374
|
+
x = x.swapaxes(1, 2)
|
|
375
|
+
|
|
376
|
+
if block_idx is None:
|
|
377
|
+
# All blocks
|
|
378
|
+
attn = []
|
|
379
|
+
for block in model.model.embedding.transformer_tower.blocks:
|
|
380
|
+
attn.append(block.mha.get_attn_scores(block.norm(x)))
|
|
381
|
+
x = block(x)
|
|
382
|
+
attn = torch.stack(attn, axis=1)
|
|
383
|
+
else:
|
|
384
|
+
# Single block
|
|
385
|
+
for block in model.model.embedding.transformer_tower.blocks[:block_idx]:
|
|
386
|
+
x = block(x)
|
|
387
|
+
block = model.model.embedding.transformer_tower.blocks[block_idx]
|
|
388
|
+
attn = block.mha.get_attn_scores(block.norm(x))
|
|
389
|
+
|
|
390
|
+
return attn.squeeze(0).detach().cpu().numpy()
|
grelu/io/__init__.py
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
"""
|
|
2
|
+
General functions for reading and writing data
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
from typing import Optional
|
|
7
|
+
|
|
8
|
+
import pandas as pd
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def read_tomtom(tomtom_dir: str, qthresh: float = 0.05) -> pd.DataFrame:
|
|
12
|
+
"""
|
|
13
|
+
Reads TOMTOM output files into a dataframe
|
|
14
|
+
|
|
15
|
+
Args:
|
|
16
|
+
tomtom_dir: Path to a directory containing TOMTOM output files
|
|
17
|
+
qthresh: q-value threshold. Only TOMTOM hits with q-value lower than this will be returned.
|
|
18
|
+
|
|
19
|
+
Returns:
|
|
20
|
+
A dataFrame containing TOMTOM matches with q-value lower than threshold.
|
|
21
|
+
"""
|
|
22
|
+
# Initialize an empty dataframe
|
|
23
|
+
tomtom_df = pd.DataFrame()
|
|
24
|
+
|
|
25
|
+
# Read each file from the TOMTOM output directory
|
|
26
|
+
for file in os.listdir(tomtom_dir):
|
|
27
|
+
if file.endswith("tomtom.tsv"):
|
|
28
|
+
df = pd.read_table(os.path.join(tomtom_dir, file))
|
|
29
|
+
df["Query_ID"] = file.replace(".tomtom.tsv", "")
|
|
30
|
+
tomtom_df = pd.concat([tomtom_df, df])
|
|
31
|
+
|
|
32
|
+
# Format dataframe
|
|
33
|
+
tomtom_df = tomtom_df.reset_index(drop=True).dropna()
|
|
34
|
+
|
|
35
|
+
# Filter by q-value
|
|
36
|
+
tomtom_df = tomtom_df[tomtom_df["q-value"] <= qthresh]
|
|
37
|
+
return tomtom_df
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def update_ckpt(ckpt_file: str, out_file: Optional[str] = None) -> None:
|
|
41
|
+
"""
|
|
42
|
+
Update legacy model checkpoint files saved with gReLU v0.4 or lower. Creates
|
|
43
|
+
a new checkpoint file which can be loaded using
|
|
44
|
+
grelu.lightning.LightningModel.load_from_checkpoint
|
|
45
|
+
|
|
46
|
+
Args:
|
|
47
|
+
ckpt_file: Path to a legacy checkpoint file saved with gReLU v0.4 or lower
|
|
48
|
+
out_file: Path to the output file
|
|
49
|
+
"""
|
|
50
|
+
from collections import OrderedDict
|
|
51
|
+
|
|
52
|
+
import torch
|
|
53
|
+
from pytorch_lightning.utilities.migration import migrate_checkpoint
|
|
54
|
+
|
|
55
|
+
# Load old checkpoint
|
|
56
|
+
ckpt = torch.load(ckpt_file, map_location="cpu")
|
|
57
|
+
|
|
58
|
+
# Update pytorch version
|
|
59
|
+
ckpt, _ = migrate_checkpoint(ckpt)
|
|
60
|
+
|
|
61
|
+
# Update hyperparameter names
|
|
62
|
+
if "depth" in ckpt["hyper_parameters"]["model_params"]:
|
|
63
|
+
ckpt["hyper_parameters"]["model_params"]["n_transformers"] = ckpt[
|
|
64
|
+
"hyper_parameters"
|
|
65
|
+
]["model_params"].pop("depth")
|
|
66
|
+
if "target_length" in ckpt["hyper_parameters"]["model_params"]:
|
|
67
|
+
del ckpt["hyper_parameters"]["model_params"]["target_length"]
|
|
68
|
+
|
|
69
|
+
# Make dictionary of old and new keys
|
|
70
|
+
keys_dict = {
|
|
71
|
+
"model.stem.0": "model.embedding.conv_tower.blocks.0.0",
|
|
72
|
+
"model.stem.1.fn.0": "model.embedding.conv_tower.blocks.0.1.norm.layer",
|
|
73
|
+
"model.stem.1.fn.2": "model.embedding.conv_tower.blocks.0.1.conv",
|
|
74
|
+
"model.stem.2": "model.embedding.conv_tower.blocks.0.1.pool.layer",
|
|
75
|
+
"model.final_pointwise.1.0": "model.embedding.pointwise_conv.norm.layer",
|
|
76
|
+
"model.final_pointwise.1.2": "model.embedding.pointwise_conv.conv",
|
|
77
|
+
"model.linear": "model.head.channel_transform.conv.layer",
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
for i in range(6):
|
|
81
|
+
keys_dict[
|
|
82
|
+
f"model.conv_tower.{i}.0.0"
|
|
83
|
+
] = f"model.embedding.conv_tower.blocks.{i+1}.0.norm.layer"
|
|
84
|
+
keys_dict[
|
|
85
|
+
f"model.conv_tower.{i}.0.2"
|
|
86
|
+
] = f"model.embedding.conv_tower.blocks.{i+1}.0.conv"
|
|
87
|
+
keys_dict[
|
|
88
|
+
f"model.conv_tower.{i}.1.fn.0"
|
|
89
|
+
] = f"model.embedding.conv_tower.blocks.{i+1}.1.norm.layer"
|
|
90
|
+
keys_dict[
|
|
91
|
+
f"model.conv_tower.{i}.1.fn.2"
|
|
92
|
+
] = f"model.embedding.conv_tower.blocks.{i+1}.1.conv"
|
|
93
|
+
keys_dict[
|
|
94
|
+
f"model.conv_tower.{i}.2"
|
|
95
|
+
] = f"model.embedding.conv_tower.blocks.{i+1}.1.pool.layer"
|
|
96
|
+
|
|
97
|
+
for i in range(ckpt["hyper_parameters"]["model_params"]["n_transformers"]):
|
|
98
|
+
keys_dict[
|
|
99
|
+
f"model.transformer.{i}.0.fn.0"
|
|
100
|
+
] = f"model.embedding.transformer_tower.blocks.{i}.norm.layer"
|
|
101
|
+
keys_dict[
|
|
102
|
+
f"model.transformer.{i}.0.fn.1"
|
|
103
|
+
] = f"model.embedding.transformer_tower.blocks.{i}.mha"
|
|
104
|
+
keys_dict[
|
|
105
|
+
f"model.transformer.{i}.1.fn.0"
|
|
106
|
+
] = f"model.embedding.transformer_tower.blocks.{i}.ffn.dense1.norm.layer"
|
|
107
|
+
keys_dict[
|
|
108
|
+
f"model.transformer.{i}.1.fn.1"
|
|
109
|
+
] = f"model.embedding.transformer_tower.blocks.{i}.ffn.dense1.linear"
|
|
110
|
+
keys_dict[
|
|
111
|
+
f"model.transformer.{i}.1.fn.4"
|
|
112
|
+
] = f"model.embedding.transformer_tower.blocks.{i}.ffn.dense2.linear"
|
|
113
|
+
|
|
114
|
+
# Make new state dict in which old names are replaced by new ones
|
|
115
|
+
new_state_dict = OrderedDict()
|
|
116
|
+
|
|
117
|
+
for k, v in ckpt["state_dict"].items():
|
|
118
|
+
# Update name of the parameter
|
|
119
|
+
for old, new in keys_dict.items():
|
|
120
|
+
k = k.replace(old, new)
|
|
121
|
+
|
|
122
|
+
# Save parameter value under the new name
|
|
123
|
+
if k == "model.head.channel_transform.conv.layer.weight":
|
|
124
|
+
new_state_dict[k] = v.unsqueeze(-1)
|
|
125
|
+
else:
|
|
126
|
+
new_state_dict[k] = v
|
|
127
|
+
|
|
128
|
+
# Replace old state dict with new one
|
|
129
|
+
ckpt["state_dict"] = new_state_dict
|
|
130
|
+
|
|
131
|
+
# Save checkpoint with new state dict
|
|
132
|
+
if out_file is None:
|
|
133
|
+
out_file = ckpt_file
|
|
134
|
+
|
|
135
|
+
print(f"Saving new checkpoint to {out_file}")
|
|
136
|
+
torch.save(ckpt, out_file)
|
grelu/io/bed.py
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Functions related to reading and writing BED and BED-like files
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
import pandas as pd
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def read_bed(
|
|
9
|
+
bed_file: str, has_header: bool = False, str_index: bool = True, **kwargs
|
|
10
|
+
) -> pd.DataFrame:
|
|
11
|
+
"""
|
|
12
|
+
Read a BED file into a pandas DataFrame of genomic intervals.
|
|
13
|
+
|
|
14
|
+
Args:
|
|
15
|
+
bed_file: The path to the BED file.
|
|
16
|
+
has_header: If True, the BED file is assumed to have a header. If False,
|
|
17
|
+
it is assumed to have no header.
|
|
18
|
+
str_index: If True, the index is converted into a string format. If False,
|
|
19
|
+
the index is unchanged.
|
|
20
|
+
**kwargs: Additional arguments to pass to pd.read_table
|
|
21
|
+
|
|
22
|
+
Returns:
|
|
23
|
+
A DataFrame of genomic intervals, with columns 'chrom', 'start',
|
|
24
|
+
and 'end', and a string index if `str_index` is True.
|
|
25
|
+
"""
|
|
26
|
+
# Check header
|
|
27
|
+
header = 0 if has_header else None
|
|
28
|
+
|
|
29
|
+
# Read BED file
|
|
30
|
+
intervals = pd.read_table(bed_file, header=header, **kwargs)
|
|
31
|
+
|
|
32
|
+
# Name required columns
|
|
33
|
+
intervals = intervals.rename(
|
|
34
|
+
columns={
|
|
35
|
+
intervals.columns[0]: "chrom",
|
|
36
|
+
intervals.columns[1]: "start",
|
|
37
|
+
intervals.columns[2]: "end",
|
|
38
|
+
}
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
# Convert start and end to int
|
|
42
|
+
intervals["start"] = intervals["start"].astype(int)
|
|
43
|
+
intervals["end"] = intervals["end"].astype(int)
|
|
44
|
+
|
|
45
|
+
# Convert index to str (useful for anndata)
|
|
46
|
+
if str_index:
|
|
47
|
+
intervals.index = intervals.index.astype(str)
|
|
48
|
+
|
|
49
|
+
return intervals
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def read_narrowpeak(
|
|
53
|
+
peak_file: str, skiprows: int = 0, str_index: bool = False, **kwargs
|
|
54
|
+
) -> pd.DataFrame:
|
|
55
|
+
"""
|
|
56
|
+
Read a narrowPeak file into a pandas DataFrame of genomic intervals.
|
|
57
|
+
|
|
58
|
+
Args:
|
|
59
|
+
peak_file: The path to the narrowpeak file.
|
|
60
|
+
skiprows: number of rows to skip at the beginning of the file.
|
|
61
|
+
str_index: If True, the index is converted into a string format. If False,
|
|
62
|
+
the index is unchanged.
|
|
63
|
+
**kwargs: Additional arguments to pass to pd.read_table.
|
|
64
|
+
|
|
65
|
+
Returns:
|
|
66
|
+
A DataFrame of genomic intervals, with a string index if `str_index` is True.
|
|
67
|
+
"""
|
|
68
|
+
|
|
69
|
+
# Read narrowpeak file
|
|
70
|
+
intervals = pd.read_table(peak_file, skiprows=skiprows, **kwargs)
|
|
71
|
+
|
|
72
|
+
# Name required columns
|
|
73
|
+
intervals = intervals.rename(
|
|
74
|
+
columns={
|
|
75
|
+
intervals.columns[0]: "chrom",
|
|
76
|
+
intervals.columns[1]: "start",
|
|
77
|
+
intervals.columns[2]: "end",
|
|
78
|
+
intervals.columns[3]: "name",
|
|
79
|
+
intervals.columns[4]: "score",
|
|
80
|
+
intervals.columns[5]: "strand",
|
|
81
|
+
intervals.columns[6]: "signal",
|
|
82
|
+
intervals.columns[7]: "pvalue",
|
|
83
|
+
intervals.columns[8]: "qvalue",
|
|
84
|
+
intervals.columns[9]: "summit",
|
|
85
|
+
}
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
# Convert genomic coordinates to int
|
|
89
|
+
intervals["start"] = intervals["start"].astype(int)
|
|
90
|
+
intervals["end"] = intervals["end"].astype(int)
|
|
91
|
+
intervals["summit"] = intervals["summit"].astype(int)
|
|
92
|
+
|
|
93
|
+
# Convert index to str (useful for anndata)
|
|
94
|
+
if str_index:
|
|
95
|
+
intervals.index = intervals.index.astype(str)
|
|
96
|
+
|
|
97
|
+
return intervals
|