gReLU 1.0.3.post1.dev0__py3-none-any.whl → 1.0.4.post1.dev0__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.3.post1.dev0.dist-info → gReLU-1.0.4.post1.dev0.dist-info}/METADATA +19 -17
- {gReLU-1.0.3.post1.dev0.dist-info → gReLU-1.0.4.post1.dev0.dist-info}/RECORD +11 -18
- {gReLU-1.0.3.post1.dev0.dist-info → gReLU-1.0.4.post1.dev0.dist-info}/WHEEL +1 -1
- grelu/interpret/modisco.py +269 -0
- grelu/interpret/motifs.py +161 -19
- grelu/interpret/score.py +9 -149
- grelu/io/motifs.py +46 -3
- grelu/resources/__init__.py +5 -3
- grelu/resources/meme/jaspar_2024_consensus.meme +2412 -0
- grelu/io/meme.py +0 -116
- grelu/resources/.ipynb_checkpoints/__init__-checkpoint.py +0 -253
- grelu/resources/blacklists/encode/.ipynb_checkpoints/hg38-blacklist.v2-checkpoint.bed +0 -636
- grelu/resources/meme/.ipynb_checkpoints/H12CORE_meme_format-checkpoint.meme +0 -27626
- grelu/resources/meme/.ipynb_checkpoints/Untitled-checkpoint.ipynb +0 -6
- grelu/resources/meme/.ipynb_checkpoints/jvierstra_consensus_pwms-checkpoint.meme +0 -10405
- grelu/resources/meme/JASPAR2022_CORE_non-redundant_pfms_meme.txt +0 -32224
- grelu/resources/meme/Untitled.ipynb +0 -247
- grelu/resources/meme/jvierstra_consensus_pwms.meme +0 -10405
- {gReLU-1.0.3.post1.dev0.dist-info → gReLU-1.0.4.post1.dev0.dist-info}/LICENSE.txt +0 -0
- {gReLU-1.0.3.post1.dev0.dist-info → gReLU-1.0.4.post1.dev0.dist-info}/top_level.txt +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
Metadata-Version: 2.
|
|
1
|
+
Metadata-Version: 2.2
|
|
2
2
|
Name: gReLU
|
|
3
|
-
Version: 1.0.
|
|
3
|
+
Version: 1.0.4.post1.dev0
|
|
4
4
|
Summary: gReLU is a python library to train, interpret, and apply deep learning models to DNA sequences
|
|
5
5
|
Home-page: https://code.roche.com/gred-rb-ai-ml-regulatory-genomics/grelu
|
|
6
6
|
Author: lal.avantika,eraslan.gokcen
|
|
@@ -16,32 +16,34 @@ Description-Content-Type: text/markdown; charset=UTF-8
|
|
|
16
16
|
License-File: LICENSE.txt
|
|
17
17
|
Requires-Dist: importlib-metadata
|
|
18
18
|
Requires-Dist: importlib-resources
|
|
19
|
-
Requires-Dist: wandb
|
|
19
|
+
Requires-Dist: wandb>=0.14
|
|
20
20
|
Requires-Dist: numpy
|
|
21
21
|
Requires-Dist: pandas
|
|
22
22
|
Requires-Dist: seaborn
|
|
23
23
|
Requires-Dist: matplotlib
|
|
24
|
-
Requires-Dist: plotnine
|
|
25
|
-
Requires-Dist: anndata
|
|
24
|
+
Requires-Dist: plotnine>=0.8
|
|
25
|
+
Requires-Dist: anndata>=0.8
|
|
26
26
|
Requires-Dist: scikit-learn
|
|
27
|
-
Requires-Dist: torch
|
|
28
|
-
Requires-Dist: pytorch-lightning
|
|
29
|
-
Requires-Dist: torchmetrics
|
|
30
|
-
Requires-Dist: modisco-lite
|
|
27
|
+
Requires-Dist: torch>=2.0
|
|
28
|
+
Requires-Dist: pytorch-lightning>=2.0
|
|
29
|
+
Requires-Dist: torchmetrics>=1.1
|
|
30
|
+
Requires-Dist: modisco-lite>=2.2.1
|
|
31
31
|
Requires-Dist: biopython
|
|
32
32
|
Requires-Dist: enformer-pytorch
|
|
33
33
|
Requires-Dist: genomepy
|
|
34
|
-
Requires-Dist: bioframe
|
|
35
|
-
Requires-Dist: captum
|
|
36
|
-
Requires-Dist: logomaker
|
|
34
|
+
Requires-Dist: bioframe>=0.4
|
|
35
|
+
Requires-Dist: captum==0.5.0
|
|
36
|
+
Requires-Dist: logomaker>=0.8
|
|
37
37
|
Requires-Dist: pyBigWig
|
|
38
38
|
Requires-Dist: ledidi
|
|
39
|
-
Requires-Dist: tangermeme
|
|
40
|
-
Requires-Dist: pygenomeviz
|
|
39
|
+
Requires-Dist: tangermeme>=0.4.0
|
|
40
|
+
Requires-Dist: pygenomeviz<=0.4.4
|
|
41
|
+
Requires-Dist: statsmodels>=0.11.1
|
|
42
|
+
Requires-Dist: pyjaspar>=3.0
|
|
41
43
|
Provides-Extra: testing
|
|
42
|
-
Requires-Dist: setuptools
|
|
43
|
-
Requires-Dist: pytest
|
|
44
|
-
Requires-Dist: pytest-cov
|
|
44
|
+
Requires-Dist: setuptools; extra == "testing"
|
|
45
|
+
Requires-Dist: pytest; extra == "testing"
|
|
46
|
+
Requires-Dist: pytest-cov; extra == "testing"
|
|
45
47
|
|
|
46
48
|
# gReLU
|
|
47
49
|
|
|
@@ -9,15 +9,15 @@ grelu/data/dataset.py,sha256=AxULwsqENzRRGa49uAD_UJBw55YOgeQxdT5EiWtkixM,35167
|
|
|
9
9
|
grelu/data/preprocess.py,sha256=PJMIQsJvSpuwwcYFjhXSNpPvKnN77tZDp5SMR-7KzQM,23101
|
|
10
10
|
grelu/data/utils.py,sha256=To1BmKJ4aSnubZ0HTgq3Oc9zWRLR9HQkxctsvPybWkY,1906
|
|
11
11
|
grelu/interpret/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
12
|
-
grelu/interpret/
|
|
13
|
-
grelu/interpret/
|
|
12
|
+
grelu/interpret/modisco.py,sha256=Hq_IpgCrrghjuNeQFfVeMDjSmh8p-0WWbdfCI36n6CM,9142
|
|
13
|
+
grelu/interpret/motifs.py,sha256=2iQM9PVZJrI50kz7dl41HuCMkpsMVKHcWvVUOBG36Go,17106
|
|
14
|
+
grelu/interpret/score.py,sha256=ugweO4VNBjjL0JCRrvYxy5qvBQ7rNsf5Krv_wsGbU_M,9301
|
|
14
15
|
grelu/io/__init__.py,sha256=mo1XFA1uo_r4-uliJNIFAxPLmGTNIxB2TXWxHwJwQlo,4941
|
|
15
16
|
grelu/io/bed.py,sha256=_C-aTHNiaRYJo5QCbvXrchXa6-fgL_3CZ3p-0ngDSKU,3056
|
|
16
17
|
grelu/io/bigwig.py,sha256=HYChK3qalKCK-bl_902JppyQoPTM9ep0G_5x8Wph_DE,3065
|
|
17
18
|
grelu/io/fasta.py,sha256=YjsfSTARG6e8ta3G0rppG4rzLRLMDe5EZx-9zJd2QU8,1354
|
|
18
19
|
grelu/io/genome.py,sha256=cVNaB1dgj_Jw2JLnWiOEjyjE54C0pF6AJqFhj7uI2TM,2737
|
|
19
|
-
grelu/io/
|
|
20
|
-
grelu/io/motifs.py,sha256=zWbN2KXQw7Z3jkV3lbhR98rktmWjT8OqdWTpr7Wsu_c,3992
|
|
20
|
+
grelu/io/motifs.py,sha256=t5Ikzoa0bUMMYrG36IhObYzPRLMPc-VeUeiM147SKvo,5543
|
|
21
21
|
grelu/lightning/__init__.py,sha256=B_Wfx3cKD4Hf4Xuh6lf81asTk6sCaLoqZLCis2BvVTE,39095
|
|
22
22
|
grelu/lightning/losses.py,sha256=dzceUrqu2o_kmUWG8LHq67TmxtVLjTsnoeidw_7ybOY,2622
|
|
23
23
|
grelu/lightning/metrics.py,sha256=tYhU1vNn7Xq4-emqeMd2_shNfTxXIv0k2dj89gTV-kM,5534
|
|
@@ -37,24 +37,17 @@ grelu/model/trunks/__init__.py,sha256=3Q6VR8LftZYx2rAcyYAsMMwnYZAvB-nllF-8Oj2oV6
|
|
|
37
37
|
grelu/model/trunks/borzoi.py,sha256=m212crmFEt59GkbgxpsD8zCd9hYMW2rUlguoL_Ai7Zo,7158
|
|
38
38
|
grelu/model/trunks/enformer.py,sha256=AWwE-MpjWhNinMNb-Lng-1E6ZdRjpr3KSlKWBh5u7vg,9135
|
|
39
39
|
grelu/model/trunks/explainn.py,sha256=vgVrn0DZcKpzqSOxUYN_qmq7qiCeErYm5Ubuqi28MAY,3843
|
|
40
|
-
grelu/resources/__init__.py,sha256=
|
|
41
|
-
grelu/resources/.ipynb_checkpoints/__init__-checkpoint.py,sha256=D4w17vJPLd3TbbCdr4ox7BFmjh-tBkwoF4hAwl-dK90,7717
|
|
40
|
+
grelu/resources/__init__.py,sha256=iKQ5z5VJVLBpwNSg-LIR8IMwi7fqkNDwpf9gf7M4aJ0,7901
|
|
42
41
|
grelu/resources/blacklists/encode/hg19-blacklist.v2.bed,sha256=H2FLnBw5oO-KehaJHf9BcarN-Pxig1tlRlWdR2Wift8,34914
|
|
43
42
|
grelu/resources/blacklists/encode/hg38-blacklist.v2.bed,sha256=McaTQt9Du8Gd2O8ohmEagVDLU-kPNB3hTTDnQsklFzc,26898
|
|
44
43
|
grelu/resources/blacklists/encode/mm10-blacklist.v2.bed,sha256=lji760vo2Z3fVvG3BwD2qTNs5_VNhwMr0mJGXs87-sc,144278
|
|
45
|
-
grelu/resources/blacklists/encode/.ipynb_checkpoints/hg38-blacklist.v2-checkpoint.bed,sha256=McaTQt9Du8Gd2O8ohmEagVDLU-kPNB3hTTDnQsklFzc,26898
|
|
46
44
|
grelu/resources/blacklists/mito_combined/hg19.full.blacklist.bed,sha256=e4zmtfBQyapVfhqv7NyNzm5QjjK67ciC6xaBAjlKKTs,21537
|
|
47
45
|
grelu/resources/blacklists/mito_combined/hg19_mm10_c.full.blacklist.bed,sha256=CeEf4IaFJs5nPFMVacVPtH07HpFYB9OIJgHuYSoltQ4,36721
|
|
48
46
|
grelu/resources/blacklists/mito_combined/hg38.full.blacklist.bed,sha256=YEIzJjIlWiMG5h9LnEbWORyxDwepUS33nQaDBf5DHTw,19642
|
|
49
47
|
grelu/resources/blacklists/mito_combined/mm10.full.blacklist.bed,sha256=h5ddCbAQPpLR2xcaaNvYbAfKniRct7G5OGAgmR1ePnA,12334
|
|
50
48
|
grelu/resources/blacklists/mito_combined/mm9.full.blacklist.bed,sha256=ufHX4cLr4dO19HxxBu1Ld_tPxcUQ9yBDI_TbXijzymg,81053
|
|
51
49
|
grelu/resources/meme/H12CORE_meme_format.meme,sha256=PZxH3DlrO6TieM39KdUmwesvutSJW14tw0X1NfmMXxI,1619601
|
|
52
|
-
grelu/resources/meme/
|
|
53
|
-
grelu/resources/meme/Untitled.ipynb,sha256=qW7YN25nvNrdS0TF2SZWvvQdewnGxcmhp3-t7GHBLm0,7613
|
|
54
|
-
grelu/resources/meme/jvierstra_consensus_pwms.meme,sha256=wBoEEvfFfGGUWGoQjX71rHlyW_aKWhXbbSj1p_fuB_0,410215
|
|
55
|
-
grelu/resources/meme/.ipynb_checkpoints/H12CORE_meme_format-checkpoint.meme,sha256=PZxH3DlrO6TieM39KdUmwesvutSJW14tw0X1NfmMXxI,1619601
|
|
56
|
-
grelu/resources/meme/.ipynb_checkpoints/Untitled-checkpoint.ipynb,sha256=SmK2imM9ecU6b9iJPo6kLc8rmoo-kHsbmGFmHwTyFRc,72
|
|
57
|
-
grelu/resources/meme/.ipynb_checkpoints/jvierstra_consensus_pwms-checkpoint.meme,sha256=wBoEEvfFfGGUWGoQjX71rHlyW_aKWhXbbSj1p_fuB_0,410215
|
|
50
|
+
grelu/resources/meme/jaspar_2024_consensus.meme,sha256=_llYP3BmsjryEtbySg6kfLZsCxox4BbSWDJDRUpcKWo,97978
|
|
58
51
|
grelu/sequence/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
59
52
|
grelu/sequence/format.py,sha256=otaLzNTYdkGNQX7IyMR-ZJId8P94f8WwoD74CToUTzA,14028
|
|
60
53
|
grelu/sequence/metrics.py,sha256=wR6GWA045v_HlEgmBdSa6Q2z0Im0MwGSzTbOcYEZiuw,3563
|
|
@@ -64,8 +57,8 @@ grelu/transforms/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,
|
|
|
64
57
|
grelu/transforms/label_transforms.py,sha256=eqRW2bj0gDyq19w539f0zvM1zu3inXKppiWJpP-pGQo,1594
|
|
65
58
|
grelu/transforms/prediction_transforms.py,sha256=PvnQBHeCoWBT8StTXXHaPW7wBPAgIrR0Qg8gPpwG_4Q,9465
|
|
66
59
|
grelu/transforms/seq_transforms.py,sha256=AjWXJEN_1yt1ZVc67YLT3oBUXTUL8EZPzk7SjS1TpfI,3842
|
|
67
|
-
gReLU-1.0.
|
|
68
|
-
gReLU-1.0.
|
|
69
|
-
gReLU-1.0.
|
|
70
|
-
gReLU-1.0.
|
|
71
|
-
gReLU-1.0.
|
|
60
|
+
gReLU-1.0.4.post1.dev0.dist-info/LICENSE.txt,sha256=s3XG-K-P6kWmWKQRBWP2wEGncZSc-PLYZ39-pno7abQ,1082
|
|
61
|
+
gReLU-1.0.4.post1.dev0.dist-info/METADATA,sha256=gRhy8ON4gY1kPbnKBUv3rQ1zGYqgkNOUeqtOeHWN9mI,4203
|
|
62
|
+
gReLU-1.0.4.post1.dev0.dist-info/WHEEL,sha256=In9FTNxeP60KnTkGw7wk6mJPYd_dQSjEZmXdBdMCI-8,91
|
|
63
|
+
gReLU-1.0.4.post1.dev0.dist-info/top_level.txt,sha256=9US1FHRDdiDL1cOAWVbMYkbdHRI6Q1kRLEhX3ur15Dk,6
|
|
64
|
+
gReLU-1.0.4.post1.dev0.dist-info/RECORD,,
|
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
import os
|
|
2
|
+
from typing import Callable, List, Optional, Union
|
|
3
|
+
|
|
4
|
+
import numpy as np
|
|
5
|
+
import pandas as pd
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def _add_tomtom_to_modisco_report(
|
|
9
|
+
modisco_dir: str,
|
|
10
|
+
tomtom_results: pd.DataFrame,
|
|
11
|
+
meme_file: str,
|
|
12
|
+
top_n_matches: int,
|
|
13
|
+
) -> None:
|
|
14
|
+
"""
|
|
15
|
+
Modified from https://github.com/jmschrei/tfmodisco-lite/blob/3c6e38f/modiscolite/report.py#L245
|
|
16
|
+
"""
|
|
17
|
+
from modiscolite.report import make_logo, path_to_image_html, read_meme
|
|
18
|
+
|
|
19
|
+
from grelu.resources import get_meme_file_path
|
|
20
|
+
|
|
21
|
+
# Paths to outputs
|
|
22
|
+
html_file = os.path.join(modisco_dir, "motifs.html")
|
|
23
|
+
meme_logo_dir = os.path.join(modisco_dir, "trimmed_meme_logos")
|
|
24
|
+
if not os.path.exists(meme_logo_dir):
|
|
25
|
+
os.makedirs(meme_logo_dir)
|
|
26
|
+
|
|
27
|
+
# Loading html report
|
|
28
|
+
report = pd.read_html(html_file)[0]
|
|
29
|
+
cols = report.columns.tolist()
|
|
30
|
+
report["query"] = report.apply(
|
|
31
|
+
lambda row: row.pattern[:3] + "_" + row.pattern.split(".")[-1], axis=1
|
|
32
|
+
)
|
|
33
|
+
report["modisco_cwm_fwd"] = report.pattern.apply(
|
|
34
|
+
lambda x: os.path.join("trimmed_logos", f"{x}.cwm.fwd.png")
|
|
35
|
+
)
|
|
36
|
+
report["modisco_cwm_rev"] = report.pattern.apply(
|
|
37
|
+
lambda x: os.path.join("trimmed_logos", f"{x}.cwm.rev.png")
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
# Compiling top TOMTOM matches
|
|
41
|
+
tomtom_dict = dict()
|
|
42
|
+
for i in range(top_n_matches):
|
|
43
|
+
tomtom_dict[f"match{i}"] = []
|
|
44
|
+
tomtom_dict[f"qval{i}"] = []
|
|
45
|
+
|
|
46
|
+
for row in report.itertuples():
|
|
47
|
+
query_tomtom = tomtom_results.loc[
|
|
48
|
+
tomtom_results.Query_ID == row.query, ["Target_ID", "q-value"]
|
|
49
|
+
].sort_values("q-value")[:top_n_matches]
|
|
50
|
+
|
|
51
|
+
i = -1
|
|
52
|
+
for i, row in enumerate(query_tomtom.itertuples()):
|
|
53
|
+
tomtom_dict[f"match{i}"].append(row[1])
|
|
54
|
+
tomtom_dict[f"qval{i}"].append(row[2])
|
|
55
|
+
|
|
56
|
+
for j in range(i + 1, top_n_matches):
|
|
57
|
+
tomtom_dict[f"match{j}"].append(None)
|
|
58
|
+
tomtom_dict[f"qval{j}"].append(None)
|
|
59
|
+
|
|
60
|
+
report = pd.concat([report, pd.DataFrame(tomtom_dict)], axis=1)
|
|
61
|
+
|
|
62
|
+
# Reading reference motifs from the meme file
|
|
63
|
+
meme_file = get_meme_file_path(meme_file)
|
|
64
|
+
motifs = read_meme(meme_file)
|
|
65
|
+
|
|
66
|
+
# Generating logos for the reference motifs
|
|
67
|
+
for i in range(top_n_matches):
|
|
68
|
+
name = f"match{i}"
|
|
69
|
+
logos = []
|
|
70
|
+
for _, row in report.iterrows():
|
|
71
|
+
if name in report.columns:
|
|
72
|
+
if pd.isnull(row[name]):
|
|
73
|
+
logos.append("NA")
|
|
74
|
+
else:
|
|
75
|
+
make_logo(
|
|
76
|
+
row[name],
|
|
77
|
+
meme_logo_dir,
|
|
78
|
+
motifs,
|
|
79
|
+
)
|
|
80
|
+
logos.append(os.path.join("trimmed_meme_logos", f"{row[name]}.png"))
|
|
81
|
+
else:
|
|
82
|
+
break
|
|
83
|
+
report[f"{name}_logo"] = logos
|
|
84
|
+
cols.extend([name, f"qval{i}", f"{name}_logo"])
|
|
85
|
+
|
|
86
|
+
# Saving html file
|
|
87
|
+
with open(html_file, "w") as f:
|
|
88
|
+
report[cols].to_html(
|
|
89
|
+
f,
|
|
90
|
+
escape=False,
|
|
91
|
+
formatters=dict(
|
|
92
|
+
modisco_cwm_fwd=path_to_image_html,
|
|
93
|
+
modisco_cwm_rev=path_to_image_html,
|
|
94
|
+
match0_logo=path_to_image_html,
|
|
95
|
+
match1_logo=path_to_image_html,
|
|
96
|
+
match2_logo=path_to_image_html,
|
|
97
|
+
),
|
|
98
|
+
index=False,
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def run_modisco(
|
|
103
|
+
model,
|
|
104
|
+
seqs: Union[pd.DataFrame, np.array, List[str]],
|
|
105
|
+
genome: Optional[str] = None,
|
|
106
|
+
prediction_transform: Optional[Callable] = None,
|
|
107
|
+
window: int = None,
|
|
108
|
+
meme_file: str = None,
|
|
109
|
+
out_dir: str = "outputs",
|
|
110
|
+
devices: Union[str, int] = "cpu",
|
|
111
|
+
num_workers: int = 1,
|
|
112
|
+
batch_size: int = 64,
|
|
113
|
+
n_shuffles: int = 10,
|
|
114
|
+
seed=None,
|
|
115
|
+
method: str = "deepshap",
|
|
116
|
+
**kwargs,
|
|
117
|
+
) -> None:
|
|
118
|
+
"""
|
|
119
|
+
Run TF-Modisco to get relevant motifs for a set of inputs, and optionally score the
|
|
120
|
+
motifs against a reference set of motifs using TOMTOM
|
|
121
|
+
|
|
122
|
+
Args:
|
|
123
|
+
model: A trained deep learning model
|
|
124
|
+
seqs: Input DNA sequences as genomic intervals, strings, or integer-encoded form.
|
|
125
|
+
genome: Name of the genome to use. Only used if genomic intervals are provided.
|
|
126
|
+
prediction_transform: A module to transform the model output
|
|
127
|
+
window: Sequence length over which to consider attributions
|
|
128
|
+
meme_file: Path to a MEME file containing reference motifs for TOMTOM.
|
|
129
|
+
out_dir: Output directory
|
|
130
|
+
devices: Indices of devices to use for model inference
|
|
131
|
+
num_workers: Number of workers to use for model inference
|
|
132
|
+
batch_size: Batch size to use for model inference
|
|
133
|
+
n_shuffles: Number of times to shuffle the background sequences for deepshap.
|
|
134
|
+
seed: Random seed
|
|
135
|
+
method: Either "deepshap", "saliency" or "ism".
|
|
136
|
+
**kwargs: Additional arguments to pass to TF-Modisco.
|
|
137
|
+
|
|
138
|
+
Raises:
|
|
139
|
+
NotImplementedError: if the method is neither "deepshap" nor "ism"
|
|
140
|
+
"""
|
|
141
|
+
from modiscolite.io import save_hdf5
|
|
142
|
+
from modiscolite.report import create_modisco_logos, report_motifs
|
|
143
|
+
from modiscolite.tfmodisco import TFMoDISco
|
|
144
|
+
|
|
145
|
+
from grelu.data.dataset import ISMDataset, SeqDataset
|
|
146
|
+
from grelu.interpret.motifs import run_tomtom
|
|
147
|
+
from grelu.interpret.score import get_attributions
|
|
148
|
+
from grelu.io.motifs import read_modisco_report
|
|
149
|
+
from grelu.sequence.format import convert_input_type
|
|
150
|
+
from grelu.sequence.utils import get_unique_length
|
|
151
|
+
|
|
152
|
+
# Get start and end positions
|
|
153
|
+
if window is None:
|
|
154
|
+
start = 0
|
|
155
|
+
end = get_unique_length(seqs)
|
|
156
|
+
else:
|
|
157
|
+
center = get_unique_length(seqs) // 2
|
|
158
|
+
start = center - window // 2
|
|
159
|
+
end = start + window
|
|
160
|
+
|
|
161
|
+
# Get one-hot encoded sequence
|
|
162
|
+
one_hot = convert_input_type(seqs, "one_hot", genome=genome)
|
|
163
|
+
one_hot_arr = one_hot[:, :, start:end].numpy()
|
|
164
|
+
|
|
165
|
+
if method in ["deepshap", "saliency"]:
|
|
166
|
+
print("Getting attributions")
|
|
167
|
+
attrs = get_attributions(
|
|
168
|
+
model=model,
|
|
169
|
+
seqs=one_hot,
|
|
170
|
+
prediction_transform=prediction_transform,
|
|
171
|
+
device=devices,
|
|
172
|
+
n_shuffles=n_shuffles,
|
|
173
|
+
method=method,
|
|
174
|
+
hypothetical=True,
|
|
175
|
+
genome=genome,
|
|
176
|
+
seed=seed,
|
|
177
|
+
)
|
|
178
|
+
attrs = attrs[:, :, start:end]
|
|
179
|
+
|
|
180
|
+
elif method == "ism":
|
|
181
|
+
print("Performing ISM")
|
|
182
|
+
ref_ds = SeqDataset(seqs, genome=genome)
|
|
183
|
+
ism_ds = ISMDataset(
|
|
184
|
+
seqs, drop_ref=True, positions=range(start, end), genome=genome
|
|
185
|
+
)
|
|
186
|
+
|
|
187
|
+
# Add transform to model
|
|
188
|
+
model.add_transform(prediction_transform)
|
|
189
|
+
|
|
190
|
+
# Get predictions for reference sequences
|
|
191
|
+
ref_preds = model.predict_on_dataset(
|
|
192
|
+
ref_ds, devices=devices, num_workers=num_workers, batch_size=batch_size
|
|
193
|
+
) # B, 1, T, L
|
|
194
|
+
assert (ref_preds.shape[-1] == 1) and (ref_preds.shape[-2] == 1)
|
|
195
|
+
|
|
196
|
+
# Get predictions for all mutated sequences
|
|
197
|
+
ism_preds = model.predict_on_dataset(
|
|
198
|
+
ism_ds,
|
|
199
|
+
devices=devices,
|
|
200
|
+
num_workers=num_workers,
|
|
201
|
+
batch_size=batch_size,
|
|
202
|
+
) # B, l, 3, 1, 1
|
|
203
|
+
assert (ism_preds.shape[-1] == 1) and (ism_preds.shape[-2] == 1)
|
|
204
|
+
ism_preds = ism_preds.squeeze((-1, -2)) # B, l, 3
|
|
205
|
+
|
|
206
|
+
# Remove transform
|
|
207
|
+
model.reset_transform()
|
|
208
|
+
|
|
209
|
+
# Get the negative log ratio
|
|
210
|
+
attrs = -np.log2(np.divide(ism_preds, ref_preds)) # B, l, 3
|
|
211
|
+
|
|
212
|
+
# Mean over all possible mutations
|
|
213
|
+
attrs = np.expand_dims(attrs.mean(-1), 1) # B, 1, l
|
|
214
|
+
|
|
215
|
+
# Multiply by original sequence
|
|
216
|
+
attrs = np.multiply(attrs, one_hot_arr) # B, 4, l
|
|
217
|
+
|
|
218
|
+
else:
|
|
219
|
+
raise NotImplementedError
|
|
220
|
+
|
|
221
|
+
print("Running modisco")
|
|
222
|
+
one_hot_arr = one_hot_arr.transpose(0, 2, 1).astype("float32")
|
|
223
|
+
attrs = attrs.transpose(0, 2, 1).astype("float32")
|
|
224
|
+
pos_patterns, neg_patterns = TFMoDISco(
|
|
225
|
+
hypothetical_contribs=attrs,
|
|
226
|
+
one_hot=one_hot_arr,
|
|
227
|
+
**kwargs,
|
|
228
|
+
)
|
|
229
|
+
|
|
230
|
+
print("Writing modisco output")
|
|
231
|
+
if not os.path.exists(out_dir):
|
|
232
|
+
os.makedirs(out_dir)
|
|
233
|
+
|
|
234
|
+
h5_file = os.path.join(out_dir, "modisco_report.h5")
|
|
235
|
+
save_hdf5(h5_file, pos_patterns, neg_patterns, window_size=20)
|
|
236
|
+
|
|
237
|
+
print("Creating sequence logos")
|
|
238
|
+
modisco_logo_dir = os.path.join(out_dir, "trimmed_logos")
|
|
239
|
+
if not os.path.isdir(modisco_logo_dir):
|
|
240
|
+
os.mkdir(modisco_logo_dir)
|
|
241
|
+
create_modisco_logos(
|
|
242
|
+
h5_file,
|
|
243
|
+
modisco_logo_dir,
|
|
244
|
+
trim_threshold=0.2,
|
|
245
|
+
pattern_groups=["pos_patterns", "neg_patterns"],
|
|
246
|
+
)
|
|
247
|
+
|
|
248
|
+
print("Creating html report")
|
|
249
|
+
report_motifs(
|
|
250
|
+
modisco_h5py=h5_file,
|
|
251
|
+
output_dir=out_dir,
|
|
252
|
+
img_path_suffix=out_dir,
|
|
253
|
+
meme_motif_db=None,
|
|
254
|
+
is_writing_tomtom_matrix=False,
|
|
255
|
+
)
|
|
256
|
+
|
|
257
|
+
if meme_file is not None:
|
|
258
|
+
print("Running TOMTOM")
|
|
259
|
+
tomtom_file = os.path.join(out_dir, "tomtom.csv")
|
|
260
|
+
motifs = read_modisco_report(h5_file, trim_threshold=0.3)
|
|
261
|
+
if len(motifs) > 0:
|
|
262
|
+
tomtom_results = run_tomtom(motifs, meme_file)
|
|
263
|
+
tomtom_results.to_csv(tomtom_file)
|
|
264
|
+
_add_tomtom_to_modisco_report(
|
|
265
|
+
modisco_dir=out_dir,
|
|
266
|
+
tomtom_results=tomtom_results,
|
|
267
|
+
meme_file=meme_file,
|
|
268
|
+
top_n_matches=10,
|
|
269
|
+
)
|
grelu/interpret/motifs.py
CHANGED
|
@@ -58,7 +58,7 @@ def motifs_to_strings(
|
|
|
58
58
|
return indices_to_strings(indices)
|
|
59
59
|
|
|
60
60
|
# Convert multiple motifs
|
|
61
|
-
elif isinstance(motifs,
|
|
61
|
+
elif isinstance(motifs, dict):
|
|
62
62
|
return [
|
|
63
63
|
motifs_to_strings(motif, rng=rng, sample=sample)
|
|
64
64
|
for motif in motifs.values()
|
|
@@ -114,8 +114,9 @@ def scan_sequences(
|
|
|
114
114
|
seq_ids: Optional[List[str]] = None,
|
|
115
115
|
pthresh: float = 1e-3,
|
|
116
116
|
rc: bool = True,
|
|
117
|
-
bin_size=0.1,
|
|
118
|
-
eps=0.0001,
|
|
117
|
+
bin_size: float = 0.1,
|
|
118
|
+
eps: float = 0.0001,
|
|
119
|
+
attrs: Optional[np.ndarray] = None,
|
|
119
120
|
):
|
|
120
121
|
"""
|
|
121
122
|
Scan a DNA sequence using motifs. Based on
|
|
@@ -136,6 +137,9 @@ def scan_sequences(
|
|
|
136
137
|
available to support it. Default is 0.1.
|
|
137
138
|
eps: A small pseudocount to add to the motif PPMs before taking the log.
|
|
138
139
|
Default is 0.0001.
|
|
140
|
+
attrs: An optional numpy array of shape (B, 4, L) containing attributions
|
|
141
|
+
for the input sequences. If provided, the results will include site
|
|
142
|
+
attribution and motif attribution scores for each FIMO hit.
|
|
139
143
|
|
|
140
144
|
Returns:
|
|
141
145
|
pd.DataFrame containing columns 'motif', 'sequence', 'start', 'end',
|
|
@@ -153,14 +157,12 @@ def scan_sequences(
|
|
|
153
157
|
if isinstance(motifs, str):
|
|
154
158
|
motifs = read_meme_file(motifs)
|
|
155
159
|
|
|
156
|
-
motifs = {k: Tensor(v) for k, v in motifs.items()}
|
|
157
|
-
|
|
158
160
|
# Scan each sequence in seqs
|
|
159
|
-
|
|
160
|
-
for seq, seq_id in zip(seqs, seq_ids):
|
|
161
|
+
sites = pd.DataFrame()
|
|
162
|
+
for i, (seq, seq_id) in enumerate(zip(seqs, seq_ids)):
|
|
161
163
|
one_hot = strings_to_one_hot(seq, add_batch_axis=True)
|
|
162
|
-
|
|
163
|
-
motifs,
|
|
164
|
+
curr_sites = fimo(
|
|
165
|
+
motifs={k: Tensor(v) for k, v in motifs.items()},
|
|
164
166
|
sequences=one_hot,
|
|
165
167
|
alphabet=["A", "C", "G", "T"],
|
|
166
168
|
bin_size=bin_size,
|
|
@@ -169,16 +171,18 @@ def scan_sequences(
|
|
|
169
171
|
reverse_complement=rc,
|
|
170
172
|
dim=1,
|
|
171
173
|
)
|
|
172
|
-
if len(
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
174
|
+
if len(curr_sites) == 1:
|
|
175
|
+
curr_sites = curr_sites[0]
|
|
176
|
+
curr_sites["seq_idx"] = i
|
|
177
|
+
curr_sites["sequence"] = seq_id
|
|
178
|
+
curr_sites["matched_seq"] = curr_sites.apply(
|
|
176
179
|
lambda row: seq[row.start : row.end], axis=1
|
|
177
180
|
)
|
|
178
|
-
|
|
181
|
+
curr_sites = curr_sites[
|
|
179
182
|
[
|
|
180
183
|
"motif_name",
|
|
181
184
|
"sequence",
|
|
185
|
+
"seq_idx",
|
|
182
186
|
"start",
|
|
183
187
|
"end",
|
|
184
188
|
"strand",
|
|
@@ -187,13 +191,106 @@ def scan_sequences(
|
|
|
187
191
|
"matched_seq",
|
|
188
192
|
]
|
|
189
193
|
]
|
|
190
|
-
|
|
194
|
+
sites = pd.concat([sites, curr_sites])
|
|
191
195
|
|
|
192
196
|
# Concatenate results from all sequences
|
|
193
|
-
if len(
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
+
if len(sites) > 0:
|
|
198
|
+
sites = sites.reset_index(drop=True)
|
|
199
|
+
sites = sites.rename(columns={"motif_name": "motif"})
|
|
200
|
+
|
|
201
|
+
# Add attribution scores
|
|
202
|
+
if attrs is not None:
|
|
203
|
+
sites = score_sites(sites, attrs, seqs)
|
|
204
|
+
sites = score_motifs(sites, attrs, motifs)
|
|
205
|
+
|
|
206
|
+
return sites
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def score_sites(
|
|
210
|
+
sites: pd.DataFrame, attrs: np.ndarray, seqs: Union[str, List[str]]
|
|
211
|
+
) -> pd.DataFrame:
|
|
212
|
+
"""
|
|
213
|
+
Given a dataframe of motif matching sites identified by FIMO and a set of attributions, this
|
|
214
|
+
function assigns each site a 'site attribution score' corresponding to the average attribution value
|
|
215
|
+
for all nucleotides within the site. This score gives the importance of the sequence region but does
|
|
216
|
+
not reflect the similarity between the PWM and the shape of the attributions.
|
|
217
|
+
|
|
218
|
+
Args:
|
|
219
|
+
sites: A dataframe containing the output of scan_sequences
|
|
220
|
+
attrs: An optional numpy array of shape (B, 4, L) containing attributions
|
|
221
|
+
for the sequences.
|
|
222
|
+
seqs: A string or a list of DNA sequences as strings, which were the input to scan_sequences.
|
|
223
|
+
|
|
224
|
+
Returns:
|
|
225
|
+
pd.DataFrame containing columns 'motif', 'sequence', 'start', 'end',
|
|
226
|
+
'strand', 'score', 'pval', 'matched_seq', and 'site_attr_score'.
|
|
227
|
+
"""
|
|
228
|
+
df = sites.copy()
|
|
229
|
+
|
|
230
|
+
# Format sequences
|
|
231
|
+
seqs = make_list(seqs)
|
|
232
|
+
|
|
233
|
+
# Format attributions
|
|
234
|
+
if attrs.ndim == 2:
|
|
235
|
+
attrs = np.expand_dims(attrs, 0)
|
|
236
|
+
assert attrs.shape[0] == len(seqs)
|
|
237
|
+
|
|
238
|
+
# Score sites for each sequence
|
|
239
|
+
df["site_attr_score"] = df.apply(
|
|
240
|
+
lambda row: attrs[row.seq_idx, :, row.start : row.end].mean(), axis=1
|
|
241
|
+
)
|
|
242
|
+
|
|
243
|
+
return df
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def score_motifs(
|
|
247
|
+
sites: pd.DataFrame, attrs: np.ndarray, motifs: Union[Dict[str, np.ndarray], str]
|
|
248
|
+
) -> pd.DataFrame:
|
|
249
|
+
"""
|
|
250
|
+
Given a dataframe of motif matching sites identified by FIMO and a set of attributions, this
|
|
251
|
+
function assigns each site a 'motif attribution score' which is the sum of the element-wise
|
|
252
|
+
product of the motif and the attributions. This score is higher when the shape of the motif
|
|
253
|
+
matches the shape of the attribution profile, and is particularly useful for ranking multiple
|
|
254
|
+
motifs that all match to the same sequence region.
|
|
255
|
+
|
|
256
|
+
Args:
|
|
257
|
+
sites: A dataframe containing the output of scan_sequences
|
|
258
|
+
attrs: An optional numpy array of shape (B, 4, L) containing attributions
|
|
259
|
+
for the sequences.
|
|
260
|
+
motifs: A dictionary whose values are Position Probability Matrices
|
|
261
|
+
(PPMs) of shape (4, L), or the path to a MEME file. This should be the
|
|
262
|
+
same as the input passed to scan_sequences.
|
|
263
|
+
|
|
264
|
+
Returns:
|
|
265
|
+
pd.DataFrame containing columns 'motif', 'sequence', 'start', 'end',
|
|
266
|
+
'strand', 'score', 'pval', 'matched_seq', and 'motif_attr_score'.
|
|
267
|
+
"""
|
|
268
|
+
df = sites.copy()
|
|
269
|
+
|
|
270
|
+
# Format attributions
|
|
271
|
+
if attrs.ndim == 2:
|
|
272
|
+
attrs = np.expand_dims(attrs, 0)
|
|
273
|
+
|
|
274
|
+
# Format motifs
|
|
275
|
+
if isinstance(motifs, str):
|
|
276
|
+
motifs = read_meme_file(motifs)
|
|
277
|
+
motifs = {
|
|
278
|
+
motif_name: {"+": ppm, "-": np.flip(ppm, (0, 1))}
|
|
279
|
+
for motif_name, ppm in motifs.items()
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
# Calculate attr x PWM product for each site
|
|
283
|
+
df["motif_attr_score"] = df.apply(
|
|
284
|
+
lambda row: np.multiply(
|
|
285
|
+
attrs[row.seq_idx, :, row.start : row.end],
|
|
286
|
+
motifs[row.motif][row.strand],
|
|
287
|
+
)
|
|
288
|
+
.sum(0)
|
|
289
|
+
.mean(),
|
|
290
|
+
axis=1,
|
|
291
|
+
)
|
|
292
|
+
|
|
293
|
+
return df
|
|
197
294
|
|
|
198
295
|
|
|
199
296
|
def marginalize_patterns(
|
|
@@ -339,3 +436,48 @@ def compare_motifs(
|
|
|
339
436
|
scan["foldChange"] = scan.alt / scan.ref
|
|
340
437
|
scan = scan.sort_values("foldChange").reset_index(drop=True)
|
|
341
438
|
return scan
|
|
439
|
+
|
|
440
|
+
|
|
441
|
+
def run_tomtom(motifs: Dict[str, np.ndarray], meme_file: str) -> pd.DataFrame:
|
|
442
|
+
"""
|
|
443
|
+
Function to compare given motifs to reference motifs using the
|
|
444
|
+
tomtom algorithm, as implemented in tangermeme.
|
|
445
|
+
|
|
446
|
+
Args:
|
|
447
|
+
motifs: A dictionary whose values are Position Probability Matrices
|
|
448
|
+
(PPMs) of shape (4, L).
|
|
449
|
+
meme_file: Path to a meme file containing reference motifs.
|
|
450
|
+
|
|
451
|
+
Returns:
|
|
452
|
+
df: Pandas dataframe containing all tomtom results.
|
|
453
|
+
"""
|
|
454
|
+
from statsmodels.stats.multitest import fdrcorrection
|
|
455
|
+
from tangermeme.tools.tomtom import tomtom
|
|
456
|
+
|
|
457
|
+
from grelu.interpret.motifs import motifs_to_strings
|
|
458
|
+
from grelu.resources import get_meme_file_path
|
|
459
|
+
|
|
460
|
+
meme_file = get_meme_file_path(meme_file)
|
|
461
|
+
ref_motifs = read_meme_file(meme_file)
|
|
462
|
+
query_consensuses = {k: motifs_to_strings(v) for k, v in motifs.items()}
|
|
463
|
+
target_consensuses = {k: motifs_to_strings(v) for k, v in ref_motifs.items()}
|
|
464
|
+
pvals, scores, offsets, overlaps, strands = tomtom(
|
|
465
|
+
list(motifs.values()), list(ref_motifs.values())
|
|
466
|
+
)
|
|
467
|
+
|
|
468
|
+
df = pd.DataFrame(
|
|
469
|
+
{
|
|
470
|
+
"Query_ID": np.repeat(list(motifs.keys()), len(ref_motifs)),
|
|
471
|
+
"Target_ID": list(ref_motifs.keys()) * len(motifs),
|
|
472
|
+
"Optimal_offset": offsets.flatten(),
|
|
473
|
+
"p-value": pvals.flatten(),
|
|
474
|
+
}
|
|
475
|
+
)
|
|
476
|
+
df["E-value"] = df["p-value"] * len(ref_motifs)
|
|
477
|
+
df["q-value"] = fdrcorrection(df["p-value"])[1]
|
|
478
|
+
df["Overlap"] = overlaps.flatten()
|
|
479
|
+
df["Query_consensus"] = df.Query_ID.map(query_consensuses)
|
|
480
|
+
df["Target_consensus"] = df.Target_ID.map(target_consensuses)
|
|
481
|
+
df["Orientation"] = ["+" if x == 0 else "-" for x in strands.flatten()]
|
|
482
|
+
|
|
483
|
+
return df
|