PersonalBPNet 0.8.0__tar.gz → 0.9.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {personalbpnet-0.8.0/src/PersonalBPNet.egg-info → personalbpnet-0.9.0}/PKG-INFO +4 -4
- {personalbpnet-0.8.0 → personalbpnet-0.9.0}/README.md +3 -3
- {personalbpnet-0.8.0 → personalbpnet-0.9.0}/pyproject.toml +1 -1
- {personalbpnet-0.8.0 → personalbpnet-0.9.0/src/PersonalBPNet.egg-info}/PKG-INFO +4 -4
- {personalbpnet-0.8.0 → personalbpnet-0.9.0}/src/cli/tf.py +127 -0
- {personalbpnet-0.8.0 → personalbpnet-0.9.0}/src/personal_bpnet/clipnet_tf_fast.py +370 -1
- {personalbpnet-0.8.0 → personalbpnet-0.9.0}/tests/test_cli_common.py +38 -0
- {personalbpnet-0.8.0 → personalbpnet-0.9.0}/tests/test_clipnet_tf_fast.py +105 -0
- {personalbpnet-0.8.0 → personalbpnet-0.9.0}/LICENSE +0 -0
- {personalbpnet-0.8.0 → personalbpnet-0.9.0}/setup.cfg +0 -0
- {personalbpnet-0.8.0 → personalbpnet-0.9.0}/src/PersonalBPNet.egg-info/SOURCES.txt +0 -0
- {personalbpnet-0.8.0 → personalbpnet-0.9.0}/src/PersonalBPNet.egg-info/dependency_links.txt +0 -0
- {personalbpnet-0.8.0 → personalbpnet-0.9.0}/src/PersonalBPNet.egg-info/entry_points.txt +0 -0
- {personalbpnet-0.8.0 → personalbpnet-0.9.0}/src/PersonalBPNet.egg-info/requires.txt +0 -0
- {personalbpnet-0.8.0 → personalbpnet-0.9.0}/src/PersonalBPNet.egg-info/top_level.txt +0 -0
- {personalbpnet-0.8.0 → personalbpnet-0.9.0}/src/cli/__init__.py +0 -0
- {personalbpnet-0.8.0 → personalbpnet-0.9.0}/src/cli/_common.py +0 -0
- {personalbpnet-0.8.0 → personalbpnet-0.9.0}/src/cli/clipnet.py +0 -0
- {personalbpnet-0.8.0 → personalbpnet-0.9.0}/src/cli/pausenet.py +0 -0
- {personalbpnet-0.8.0 → personalbpnet-0.9.0}/src/personal_bpnet/__init__.py +0 -0
- {personalbpnet-0.8.0 → personalbpnet-0.9.0}/src/personal_bpnet/clipnet_pytorch.py +0 -0
- {personalbpnet-0.8.0 → personalbpnet-0.9.0}/src/personal_bpnet/clipnet_tensorflow.py +0 -0
- {personalbpnet-0.8.0 → personalbpnet-0.9.0}/src/personal_bpnet/losses.py +0 -0
- {personalbpnet-0.8.0 → personalbpnet-0.9.0}/src/personal_bpnet/personal_bpnet.py +0 -0
- {personalbpnet-0.8.0 → personalbpnet-0.9.0}/src/personal_bpnet/procapnet.py +0 -0
- {personalbpnet-0.8.0 → personalbpnet-0.9.0}/src/personal_bpnet/procapnet_orig.py +0 -0
- {personalbpnet-0.8.0 → personalbpnet-0.9.0}/src/personal_bpnet/utils.py +0 -0
- {personalbpnet-0.8.0 → personalbpnet-0.9.0}/tests/test_losses.py +0 -0
- {personalbpnet-0.8.0 → personalbpnet-0.9.0}/tests/test_models.py +0 -0
- {personalbpnet-0.8.0 → personalbpnet-0.9.0}/tests/test_utils.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: PersonalBPNet
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.9.0
|
|
4
4
|
Summary: PyTorch BPNet-family models (CLIPNET, ProCapNet, PauseNet) for base-resolution genomic signal prediction, extending bpnetlite.
|
|
5
5
|
Author-email: Adam He <adamyhe@gmail.com>
|
|
6
6
|
License: MIT License
|
|
@@ -64,7 +64,7 @@ A PyTorch library of [BPNet](https://github.com/jmschrei/bpnet-lite)-family mode
|
|
|
64
64
|
- **CLIPNET** — `PersonalBPNet` plus batch normalization; PyTorch port of the original TensorFlow [CLIPNET](https://github.com/Danko-Lab/clipnet).
|
|
65
65
|
- **ProCapNet** — `BPNet` with a masked profile loss, improving attributions (from the [ProCapNet paper](https://www.biorxiv.org/content/10.1101/2024.05.28.596138v2)).
|
|
66
66
|
- **PauseNet** — transfer-learns a base-resolution model to predict a single scalar phenotype per locus.
|
|
67
|
-
- **CLIPNET_TF** — the original TensorFlow CLIPNET architecture in PyTorch, loading its published weights. It comes with fast DeepLIFT/SHAP, in silico mutagenesis and
|
|
67
|
+
- **CLIPNET_TF** — the original TensorFlow CLIPNET architecture in PyTorch, loading its published weights. It comes with fast DeepLIFT/SHAP, in silico mutagenesis, PISA and feature interaction map (DFIM) engines written for it.
|
|
68
68
|
|
|
69
69
|
## Install
|
|
70
70
|
|
|
@@ -89,11 +89,11 @@ Installing from source, for local development, is covered in [CONTRIBUTING.md](C
|
|
|
89
89
|
| | |
|
|
90
90
|
| --- | --- |
|
|
91
91
|
| [docs/clipnet.md](docs/clipnet.md) | `PersonalBPNet` and `CLIPNET`, incl. pretrained weights |
|
|
92
|
-
| [docs/clipnet-tf.md](docs/clipnet-tf.md) | `CLIPNET_TF`: the original TensorFlow CLIPNET weights, and fast DeepLIFT/SHAP, ISM and
|
|
92
|
+
| [docs/clipnet-tf.md](docs/clipnet-tf.md) | `CLIPNET_TF`: the original TensorFlow CLIPNET weights, and fast DeepLIFT/SHAP, ISM, PISA and DFIM for them |
|
|
93
93
|
| [docs/procapnet.md](docs/procapnet.md) | `ProCapNet` |
|
|
94
94
|
| [docs/pausenet.md](docs/pausenet.md) | `PauseNet` |
|
|
95
95
|
| [docs/cli.md](docs/cli.md) | `clipnet`, `pausenet`, and `clipnet_tf` command line tools |
|
|
96
|
-
| [examples/promoter_interpretation](examples/promoter_interpretation/) | Comparing attribution references for `CLIPNET_TF` at 11 promoters |
|
|
96
|
+
| [examples/promoter_interpretation](examples/promoter_interpretation/) | Comparing attribution references for `CLIPNET_TF` at 11 promoters, and a DFIM heatmap of the IRF4 promoter |
|
|
97
97
|
| [CONTRIBUTING.md](CONTRIBUTING.md) | Installing from source and local development |
|
|
98
98
|
|
|
99
99
|
This package is under active development; APIs may change between releases. See [CHANGELOG.md](CHANGELOG.md).
|
|
@@ -10,7 +10,7 @@ A PyTorch library of [BPNet](https://github.com/jmschrei/bpnet-lite)-family mode
|
|
|
10
10
|
- **CLIPNET** — `PersonalBPNet` plus batch normalization; PyTorch port of the original TensorFlow [CLIPNET](https://github.com/Danko-Lab/clipnet).
|
|
11
11
|
- **ProCapNet** — `BPNet` with a masked profile loss, improving attributions (from the [ProCapNet paper](https://www.biorxiv.org/content/10.1101/2024.05.28.596138v2)).
|
|
12
12
|
- **PauseNet** — transfer-learns a base-resolution model to predict a single scalar phenotype per locus.
|
|
13
|
-
- **CLIPNET_TF** — the original TensorFlow CLIPNET architecture in PyTorch, loading its published weights. It comes with fast DeepLIFT/SHAP, in silico mutagenesis and
|
|
13
|
+
- **CLIPNET_TF** — the original TensorFlow CLIPNET architecture in PyTorch, loading its published weights. It comes with fast DeepLIFT/SHAP, in silico mutagenesis, PISA and feature interaction map (DFIM) engines written for it.
|
|
14
14
|
|
|
15
15
|
## Install
|
|
16
16
|
|
|
@@ -35,11 +35,11 @@ Installing from source, for local development, is covered in [CONTRIBUTING.md](C
|
|
|
35
35
|
| | |
|
|
36
36
|
| --- | --- |
|
|
37
37
|
| [docs/clipnet.md](docs/clipnet.md) | `PersonalBPNet` and `CLIPNET`, incl. pretrained weights |
|
|
38
|
-
| [docs/clipnet-tf.md](docs/clipnet-tf.md) | `CLIPNET_TF`: the original TensorFlow CLIPNET weights, and fast DeepLIFT/SHAP, ISM and
|
|
38
|
+
| [docs/clipnet-tf.md](docs/clipnet-tf.md) | `CLIPNET_TF`: the original TensorFlow CLIPNET weights, and fast DeepLIFT/SHAP, ISM, PISA and DFIM for them |
|
|
39
39
|
| [docs/procapnet.md](docs/procapnet.md) | `ProCapNet` |
|
|
40
40
|
| [docs/pausenet.md](docs/pausenet.md) | `PauseNet` |
|
|
41
41
|
| [docs/cli.md](docs/cli.md) | `clipnet`, `pausenet`, and `clipnet_tf` command line tools |
|
|
42
|
-
| [examples/promoter_interpretation](examples/promoter_interpretation/) | Comparing attribution references for `CLIPNET_TF` at 11 promoters |
|
|
42
|
+
| [examples/promoter_interpretation](examples/promoter_interpretation/) | Comparing attribution references for `CLIPNET_TF` at 11 promoters, and a DFIM heatmap of the IRF4 promoter |
|
|
43
43
|
| [CONTRIBUTING.md](CONTRIBUTING.md) | Installing from source and local development |
|
|
44
44
|
|
|
45
45
|
This package is under active development; APIs may change between releases. See [CHANGELOG.md](CHANGELOG.md).
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "PersonalBPNet"
|
|
7
|
-
version = "0.
|
|
7
|
+
version = "0.9.0"
|
|
8
8
|
description = "PyTorch BPNet-family models (CLIPNET, ProCapNet, PauseNet) for base-resolution genomic signal prediction, extending bpnetlite."
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
authors = [{ name = "Adam He", email = "adamyhe@gmail.com" }]
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: PersonalBPNet
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.9.0
|
|
4
4
|
Summary: PyTorch BPNet-family models (CLIPNET, ProCapNet, PauseNet) for base-resolution genomic signal prediction, extending bpnetlite.
|
|
5
5
|
Author-email: Adam He <adamyhe@gmail.com>
|
|
6
6
|
License: MIT License
|
|
@@ -64,7 +64,7 @@ A PyTorch library of [BPNet](https://github.com/jmschrei/bpnet-lite)-family mode
|
|
|
64
64
|
- **CLIPNET** — `PersonalBPNet` plus batch normalization; PyTorch port of the original TensorFlow [CLIPNET](https://github.com/Danko-Lab/clipnet).
|
|
65
65
|
- **ProCapNet** — `BPNet` with a masked profile loss, improving attributions (from the [ProCapNet paper](https://www.biorxiv.org/content/10.1101/2024.05.28.596138v2)).
|
|
66
66
|
- **PauseNet** — transfer-learns a base-resolution model to predict a single scalar phenotype per locus.
|
|
67
|
-
- **CLIPNET_TF** — the original TensorFlow CLIPNET architecture in PyTorch, loading its published weights. It comes with fast DeepLIFT/SHAP, in silico mutagenesis and
|
|
67
|
+
- **CLIPNET_TF** — the original TensorFlow CLIPNET architecture in PyTorch, loading its published weights. It comes with fast DeepLIFT/SHAP, in silico mutagenesis, PISA and feature interaction map (DFIM) engines written for it.
|
|
68
68
|
|
|
69
69
|
## Install
|
|
70
70
|
|
|
@@ -89,11 +89,11 @@ Installing from source, for local development, is covered in [CONTRIBUTING.md](C
|
|
|
89
89
|
| | |
|
|
90
90
|
| --- | --- |
|
|
91
91
|
| [docs/clipnet.md](docs/clipnet.md) | `PersonalBPNet` and `CLIPNET`, incl. pretrained weights |
|
|
92
|
-
| [docs/clipnet-tf.md](docs/clipnet-tf.md) | `CLIPNET_TF`: the original TensorFlow CLIPNET weights, and fast DeepLIFT/SHAP, ISM and
|
|
92
|
+
| [docs/clipnet-tf.md](docs/clipnet-tf.md) | `CLIPNET_TF`: the original TensorFlow CLIPNET weights, and fast DeepLIFT/SHAP, ISM, PISA and DFIM for them |
|
|
93
93
|
| [docs/procapnet.md](docs/procapnet.md) | `ProCapNet` |
|
|
94
94
|
| [docs/pausenet.md](docs/pausenet.md) | `PauseNet` |
|
|
95
95
|
| [docs/cli.md](docs/cli.md) | `clipnet`, `pausenet`, and `clipnet_tf` command line tools |
|
|
96
|
-
| [examples/promoter_interpretation](examples/promoter_interpretation/) | Comparing attribution references for `CLIPNET_TF` at 11 promoters |
|
|
96
|
+
| [examples/promoter_interpretation](examples/promoter_interpretation/) | Comparing attribution references for `CLIPNET_TF` at 11 promoters, and a DFIM heatmap of the IRF4 promoter |
|
|
97
97
|
| [CONTRIBUTING.md](CONTRIBUTING.md) | Installing from source and local development |
|
|
98
98
|
|
|
99
99
|
This package is under active development; APIs may change between releases. See [CHANGELOG.md](CHANGELOG.md).
|
|
@@ -20,6 +20,9 @@ from tangermeme.predict import predict
|
|
|
20
20
|
|
|
21
21
|
from personal_bpnet.clipnet_tensorflow import CLIPNET_TF, TwoHotToOneHot
|
|
22
22
|
from personal_bpnet.clipnet_tf_fast import deep_lift_shap as fast_deep_lift_shap
|
|
23
|
+
from personal_bpnet.clipnet_tf_fast import dfim as fast_dfim
|
|
24
|
+
from personal_bpnet.clipnet_tf_fast import dfim_extrema
|
|
25
|
+
from personal_bpnet.clipnet_tf_fast import dfim_shuffle as fast_dfim_shuffle
|
|
23
26
|
from personal_bpnet.clipnet_tf_fast import pisa as fast_pisa
|
|
24
27
|
from personal_bpnet.clipnet_tf_fast import saturation_mutagenesis
|
|
25
28
|
|
|
@@ -40,6 +43,8 @@ The following commands are available:
|
|
|
40
43
|
ism Calculate in silico saturation mutagenesis for a CLIPNET model
|
|
41
44
|
pisa Calculate PISA attributions (DeepLIFT/SHAP of every profile
|
|
42
45
|
output position) for a CLIPNET model
|
|
46
|
+
dfim Calculate single-nucleotide Deep Feature Interaction Maps
|
|
47
|
+
dfim_shuffle Calculate window-shuffle Deep Feature Interaction Maps
|
|
43
48
|
Planned but not implemented commands:
|
|
44
49
|
vep Calculate variant effect prediction using a CLIPNET model
|
|
45
50
|
"""
|
|
@@ -294,6 +299,84 @@ def cli():
|
|
|
294
299
|
help="Random seed. Defaults to 47.",
|
|
295
300
|
)
|
|
296
301
|
|
|
302
|
+
# DFIM PARAMS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
303
|
+
|
|
304
|
+
def dfim_parent():
|
|
305
|
+
p = _parent_parser()
|
|
306
|
+
for action in p._actions:
|
|
307
|
+
if action.dest == "batch_size":
|
|
308
|
+
action.default = None
|
|
309
|
+
action.help = (
|
|
310
|
+
"Variants per step, each against all -n references. Defaults to "
|
|
311
|
+
"as many as `attribute` takes regions per step."
|
|
312
|
+
)
|
|
313
|
+
p.add_argument(
|
|
314
|
+
"-a",
|
|
315
|
+
"--attribute_type",
|
|
316
|
+
type=str,
|
|
317
|
+
default="counts",
|
|
318
|
+
choices=("counts", "profile", "shape"),
|
|
319
|
+
help="Which attributions to compare between each variant and the region: "
|
|
320
|
+
"as for `attribute -a`. Defaults to counts.",
|
|
321
|
+
)
|
|
322
|
+
p.add_argument("--profile_rule", type=str, default="product",
|
|
323
|
+
choices=("product", "rescale"), help="As for `attribute`.")
|
|
324
|
+
p.add_argument("-n", "--n_shuffles", type=int, default=20,
|
|
325
|
+
help="Dinucleotide-shuffled references per region, shared by "
|
|
326
|
+
"all its variants. Defaults to 20.")
|
|
327
|
+
p.add_argument("-r", "--random_state", type=int, default=47,
|
|
328
|
+
help="Random seed. Defaults to 47.")
|
|
329
|
+
p.add_argument("-s", "--save_ohe", type=str, default=None,
|
|
330
|
+
help="Where to save the one-hot encoded sequences.")
|
|
331
|
+
return p
|
|
332
|
+
|
|
333
|
+
parser_dfim = subparsers.add_parser(
|
|
334
|
+
"dfim",
|
|
335
|
+
help="Calculate single-nucleotide Deep Feature Interaction Maps: the change "
|
|
336
|
+
"in every position's attribution when each source position is substituted.",
|
|
337
|
+
parents=[dfim_parent()],
|
|
338
|
+
)
|
|
339
|
+
parser_dfim.add_argument("--start", type=int, default=250,
|
|
340
|
+
help="First source position. Defaults to 250 (as CLIPNET).")
|
|
341
|
+
parser_dfim.add_argument("--end", type=int, default=750,
|
|
342
|
+
help="Position after the last source position (-1: the end "
|
|
343
|
+
"of the window). Defaults to 750 (as CLIPNET).")
|
|
344
|
+
parser_dfim.add_argument(
|
|
345
|
+
"--all_substitutions",
|
|
346
|
+
action="store_true",
|
|
347
|
+
help="Save the FIS of every substitution, shape (n, end - start, 4, 1000), "
|
|
348
|
+
"instead of the most extreme over the three at each source position "
|
|
349
|
+
"(n, end - start, 1000).",
|
|
350
|
+
)
|
|
351
|
+
|
|
352
|
+
parser_dfim_shuffle = subparsers.add_parser(
|
|
353
|
+
"dfim_shuffle",
|
|
354
|
+
help="Calculate window-shuffle Deep Feature Interaction Maps: the change in "
|
|
355
|
+
"every position's attribution when a source window is shuffled.",
|
|
356
|
+
parents=[dfim_parent()],
|
|
357
|
+
)
|
|
358
|
+
parser_dfim_shuffle.add_argument("--start", type=int, required=True,
|
|
359
|
+
help="First position of the source window.")
|
|
360
|
+
parser_dfim_shuffle.add_argument("--end", type=int, required=True,
|
|
361
|
+
help="Position after the source window.")
|
|
362
|
+
parser_dfim_shuffle.add_argument("--n_window_shuffles", type=int, default=5,
|
|
363
|
+
help="Shuffles of the window. Defaults to 5.")
|
|
364
|
+
parser_dfim_shuffle.add_argument(
|
|
365
|
+
"--shuffle",
|
|
366
|
+
type=str,
|
|
367
|
+
default="sequence",
|
|
368
|
+
choices=("sequence", "window"),
|
|
369
|
+
help="'sequence' (default, as CLIPNET): fill the window from a dinucleotide "
|
|
370
|
+
"shuffle of the whole region. 'window': dinucleotide-shuffle the window "
|
|
371
|
+
"itself, keeping its composition.",
|
|
372
|
+
)
|
|
373
|
+
parser_dfim_shuffle.add_argument(
|
|
374
|
+
"--all_shuffles",
|
|
375
|
+
action="store_true",
|
|
376
|
+
help="Save each shuffle's FIS, shape (n, n_window_shuffles, 1000), instead "
|
|
377
|
+
"of their mean (n, 1000).",
|
|
378
|
+
)
|
|
379
|
+
|
|
297
380
|
args = parser.parse_args()
|
|
298
381
|
|
|
299
382
|
# MAIN CODE ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
@@ -615,6 +698,50 @@ def cli():
|
|
|
615
698
|
n_models += 1
|
|
616
699
|
np.savez_compressed(args.out_fname, (total / n_models).numpy())
|
|
617
700
|
|
|
701
|
+
elif args.cmd in ("dfim", "dfim_shuffle"):
|
|
702
|
+
if args.counts_head_only and args.attribute_type != "counts":
|
|
703
|
+
raise ValueError("Counts head only models only support -a counts.")
|
|
704
|
+
X = extract_loci(
|
|
705
|
+
loci=args.bed_fname,
|
|
706
|
+
sequences=args.fa_fname,
|
|
707
|
+
chroms=args.chroms,
|
|
708
|
+
in_window=1000,
|
|
709
|
+
verbose=args.verbose,
|
|
710
|
+
ignore=list("QWERYUIOPSDFHJKLZXVBNM"),
|
|
711
|
+
).to(torch.float)
|
|
712
|
+
if args.save_ohe is not None:
|
|
713
|
+
np.savez_compressed(args.save_ohe, X.to(int).numpy())
|
|
714
|
+
|
|
715
|
+
common = dict(
|
|
716
|
+
target=args.attribute_type,
|
|
717
|
+
n_shuffles=args.n_shuffles,
|
|
718
|
+
random_state=args.random_state,
|
|
719
|
+
batch_size=args.batch_size,
|
|
720
|
+
profile_rule=args.profile_rule,
|
|
721
|
+
device=device,
|
|
722
|
+
verbose=args.verbose,
|
|
723
|
+
tf32=args.tf32,
|
|
724
|
+
)
|
|
725
|
+
# Average the unreduced maps over the ensemble, then reduce: FIS is linear
|
|
726
|
+
# in the attributions, the extremum over substitutions is not.
|
|
727
|
+
total, n_models = None, 0
|
|
728
|
+
for model in load_ensemble(model_paths, _load_tf_model):
|
|
729
|
+
if args.cmd == "dfim":
|
|
730
|
+
fis = fast_dfim(model, X, args.start, args.end, reduce=None, **common)
|
|
731
|
+
else:
|
|
732
|
+
fis = fast_dfim_shuffle(
|
|
733
|
+
model, X, args.start, args.end, n=args.n_window_shuffles,
|
|
734
|
+
shuffle=args.shuffle, reduce=None, **common,
|
|
735
|
+
)
|
|
736
|
+
total = fis if total is None else total.add_(fis)
|
|
737
|
+
n_models += 1
|
|
738
|
+
fis = total / n_models
|
|
739
|
+
if args.cmd == "dfim" and not args.all_substitutions:
|
|
740
|
+
fis = dfim_extrema(fis, X, args.start, args.end)
|
|
741
|
+
elif args.cmd == "dfim_shuffle" and not args.all_shuffles:
|
|
742
|
+
fis = fis.mean(1)
|
|
743
|
+
np.savez_compressed(args.out_fname, fis.numpy())
|
|
744
|
+
|
|
618
745
|
else:
|
|
619
746
|
raise ValueError(_help)
|
|
620
747
|
|
|
@@ -350,8 +350,15 @@ def _forward(m, x):
|
|
|
350
350
|
|
|
351
351
|
|
|
352
352
|
def _split(t, S, K):
|
|
353
|
-
"""Rows [x_0..x_{S-1}, r_00..r_{S-1,K-1}] as (S, 1, ...) and (S, K, ...).
|
|
353
|
+
"""Rows [x_0..x_{S-1}, r_00..r_{S-1,K-1}] as (S, 1, ...) and (S, K, ...).
|
|
354
354
|
|
|
355
|
+
Rows [x_0..x_{S-1}, r_0..r_{K-1}], with one set of K references shared by
|
|
356
|
+
every sequence (as DFIM's variants of one sequence share it), give the
|
|
357
|
+
references as a broadcast view, also (S, K, ...): the references are then
|
|
358
|
+
forwarded once rather than once per sequence."""
|
|
359
|
+
|
|
360
|
+
if len(t) == S + K and S > 1:
|
|
361
|
+
return t[:S].unsqueeze(1), t[S:].unsqueeze(0).expand(S, K, *t.shape[1:])
|
|
355
362
|
return t[:S].unsqueeze(1), t[S:].reshape(S, K, *t.shape[1:])
|
|
356
363
|
|
|
357
364
|
|
|
@@ -1606,3 +1613,365 @@ def _pisa(m, in_scale, X, channel, target, outputs, references, n_shuffles,
|
|
|
1606
1613
|
if not hypothetical:
|
|
1607
1614
|
attr = attr * X.cpu().to(dtype)[:, None]
|
|
1608
1615
|
return (attr, deltas) if return_deltas else attr
|
|
1616
|
+
|
|
1617
|
+
|
|
1618
|
+
# ======================================================================= DFIM
|
|
1619
|
+
#
|
|
1620
|
+
# Deep Feature Interaction Maps (Greenside et al. 2018): the interaction of a
|
|
1621
|
+
# source feature with every target position is the change in the target's
|
|
1622
|
+
# attribution when the source is perturbed, FIS(t) = C_x[t] - C_x'[t], with C
|
|
1623
|
+
# the attribution of the observed base (of x, or of the variant x'). Every
|
|
1624
|
+
# variant of a sequence is attributed against that sequence's references, as
|
|
1625
|
+
# CLIPNET's `epistasis` does, so the references are forwarded once per step
|
|
1626
|
+
# rather than once per variant (`_split`'s shared layout); the backward runs
|
|
1627
|
+
# over every (variant, reference) pair, as `deep_lift_shap`'s does.
|
|
1628
|
+
|
|
1629
|
+
|
|
1630
|
+
def _dfim_step(m, target, V, R, in_scale, profile_rule, mode):
|
|
1631
|
+
"""Observed-base attributions (B, L) of variants V (B, 4, L), each against
|
|
1632
|
+
the same references R (K, 4, L), and the deltas (B, K)."""
|
|
1633
|
+
|
|
1634
|
+
B, K, L = len(V), len(R), V.shape[-1]
|
|
1635
|
+
s = _forward(m, torch.cat([V, R]) * in_scale)
|
|
1636
|
+
if target == "counts":
|
|
1637
|
+
y, G = _counts_target(m, s, B, K)
|
|
1638
|
+
elif target == "shape":
|
|
1639
|
+
y, G = _shape_target(m, s, B, K)
|
|
1640
|
+
else:
|
|
1641
|
+
y, G = _profile_target(m, s, B, K, profile_rule)
|
|
1642
|
+
M = _backward(m, s, G, B, K, in_scale, L, mode).reshape(B, K, 4, L)
|
|
1643
|
+
del s, G
|
|
1644
|
+
# the references' outputs: one per reference, or one per (variant,
|
|
1645
|
+
# reference) pair for targets that depend on the variant (the shape
|
|
1646
|
+
# target's weights are each variant's own profile)
|
|
1647
|
+
yx = y[:B]
|
|
1648
|
+
yr = y[B:].reshape(B, K) if len(y) == B + B * K else y[B:][None]
|
|
1649
|
+
delta = ((yx[:, None] - yr) - ((V[:, None] - R[None]) * M).sum((-2, -1))).abs()
|
|
1650
|
+
hyp = M - (R[None] * M).sum(-2, keepdim=True) # tangermeme's hypothetical
|
|
1651
|
+
return (hyp.mean(1) * V).sum(1), delta
|
|
1652
|
+
|
|
1653
|
+
|
|
1654
|
+
def _dfim_batch_size(m, K, L, device, dtype):
|
|
1655
|
+
"""Variants per step: as many as `deep_lift_shap` takes sequences (the
|
|
1656
|
+
same number of pairs in the backward), and fewer rows in the forward."""
|
|
1657
|
+
|
|
1658
|
+
return _default_batch_size(m, K, L, device, dtype)
|
|
1659
|
+
|
|
1660
|
+
|
|
1661
|
+
def _attribute_variants(m, in_scale, x, variants, R, target, profile_rule, mode,
|
|
1662
|
+
B, device, dtype):
|
|
1663
|
+
"""Observed-base attributions (1 + n, L) of x and its variants (n, 4, L),
|
|
1664
|
+
all against x's references R (K, 4, L), in steps of B variants (the last
|
|
1665
|
+
padded to B, as the fused rules specialize on shape), and the deltas."""
|
|
1666
|
+
|
|
1667
|
+
rows = torch.cat([x[None], variants])
|
|
1668
|
+
n = len(rows)
|
|
1669
|
+
C = torch.empty(n, x.shape[-1], dtype=dtype)
|
|
1670
|
+
D = torch.empty(n, len(R), dtype=dtype)
|
|
1671
|
+
Rd = R.to(device, dtype)
|
|
1672
|
+
for i in range(0, n, B):
|
|
1673
|
+
V = rows[i : i + B]
|
|
1674
|
+
k = len(V)
|
|
1675
|
+
if k < B and n > B:
|
|
1676
|
+
V = torch.cat([V, V[-1:].expand(B - k, -1, -1)])
|
|
1677
|
+
with _recompile_limit(mode):
|
|
1678
|
+
c, d = _dfim_step(m, target, V.to(device, dtype), Rd, in_scale, profile_rule,
|
|
1679
|
+
mode)
|
|
1680
|
+
C[i : i + k] = c[:k].cpu()
|
|
1681
|
+
D[i : i + k] = d[:k].cpu()
|
|
1682
|
+
return C, D
|
|
1683
|
+
|
|
1684
|
+
|
|
1685
|
+
def _dfim_setup(model, X, target, references, n_shuffles, profile_rule, device, compile):
|
|
1686
|
+
m, in_scale = _unwrap(model)
|
|
1687
|
+
if target not in ("counts", "profile", "shape"):
|
|
1688
|
+
raise ValueError("target must be 'counts', 'profile' or 'shape'")
|
|
1689
|
+
if profile_rule not in ("product", "rescale"):
|
|
1690
|
+
raise ValueError("profile_rule must be 'product' or 'rescale'")
|
|
1691
|
+
if target != "counts" and m.counts_head_only:
|
|
1692
|
+
raise ValueError("a counts-head-only model has no profile to attribute")
|
|
1693
|
+
if X.ndim != 3 or X.shape[1] != 4:
|
|
1694
|
+
raise ValueError(f"X must have shape (N, 4, L), got {tuple(X.shape)}")
|
|
1695
|
+
N, _, L = X.shape
|
|
1696
|
+
if references is not None and (
|
|
1697
|
+
references.ndim != 4 or references.shape[0] != N or references.shape[2:] != X.shape[1:]
|
|
1698
|
+
):
|
|
1699
|
+
raise ValueError(
|
|
1700
|
+
f"references must have shape ({N}, K, 4, {L}), got {tuple(references.shape)}"
|
|
1701
|
+
)
|
|
1702
|
+
if device is None:
|
|
1703
|
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
|
1704
|
+
device = torch.device(device)
|
|
1705
|
+
return m, in_scale, device, _resolve_compile(compile, device)
|
|
1706
|
+
|
|
1707
|
+
|
|
1708
|
+
def _span(start, end, L):
|
|
1709
|
+
end = L + 1 + end if end < 0 else end
|
|
1710
|
+
if not 0 <= start < end <= L:
|
|
1711
|
+
raise ValueError(f"need 0 <= start < end <= {L}; got start={start}, end={end}")
|
|
1712
|
+
return start, end
|
|
1713
|
+
|
|
1714
|
+
|
|
1715
|
+
def _check_deltas(deltas, warning_threshold):
|
|
1716
|
+
if warning_threshold is not None and bool((deltas > warning_threshold).any()):
|
|
1717
|
+
warnings.warn(
|
|
1718
|
+
f"Convergence deltas too high: {int((deltas > warning_threshold).sum())} "
|
|
1719
|
+
f"of {deltas.numel()} > {warning_threshold:g}, the largest "
|
|
1720
|
+
f"{float(deltas.max()):.4g}",
|
|
1721
|
+
RuntimeWarning,
|
|
1722
|
+
stacklevel=3,
|
|
1723
|
+
)
|
|
1724
|
+
|
|
1725
|
+
|
|
1726
|
+
def dfim_extrema(fis, X, start=0, end=-1):
|
|
1727
|
+
"""Reduce single-nucleotide DFIMs (N, W, 4, L), as `dfim(reduce=None)`
|
|
1728
|
+
returns them, over the substitutions at each source position to the most
|
|
1729
|
+
extreme FIS, keeping its sign, as CLIPNET does: (N, W, L). X (N, 4, L) and
|
|
1730
|
+
[start, end) are the sequences and source positions they were computed
|
|
1731
|
+
for. To ensemble, average the unreduced maps first, then reduce: the
|
|
1732
|
+
extremum of an average is not the average of the extrema."""
|
|
1733
|
+
|
|
1734
|
+
X = X.to(torch.int8).cpu()
|
|
1735
|
+
start, end = _span(start, end, X.shape[-1])
|
|
1736
|
+
src = X[:, :, start:end]
|
|
1737
|
+
subst = ~((src == 1) & (src.sum(1, keepdim=True) == 1)) # (N, 4, W)
|
|
1738
|
+
return _extrema(fis, subst.permute(0, 2, 1)[..., None], dim=2)
|
|
1739
|
+
|
|
1740
|
+
|
|
1741
|
+
def _extrema(a, mask, dim):
|
|
1742
|
+
"""The most extreme value of `a` along `dim` among the entries where
|
|
1743
|
+
`mask` holds, keeping its sign: CLIPNET's reduction of a DFIM over the
|
|
1744
|
+
substitutions at each source position (the paper's maxFIS takes the
|
|
1745
|
+
maximum)."""
|
|
1746
|
+
|
|
1747
|
+
hi = torch.where(mask, a, -torch.inf).amax(dim)
|
|
1748
|
+
lo = torch.where(mask, a, torch.inf).amin(dim)
|
|
1749
|
+
return torch.where(-lo > hi, lo, hi)
|
|
1750
|
+
|
|
1751
|
+
|
|
1752
|
+
@torch.no_grad()
|
|
1753
|
+
def dfim(
|
|
1754
|
+
model,
|
|
1755
|
+
X,
|
|
1756
|
+
start=0,
|
|
1757
|
+
end=-1,
|
|
1758
|
+
target="counts",
|
|
1759
|
+
references=None,
|
|
1760
|
+
n_shuffles=20,
|
|
1761
|
+
random_state=None,
|
|
1762
|
+
reduce="extrema",
|
|
1763
|
+
batch_size=None,
|
|
1764
|
+
profile_rule="product",
|
|
1765
|
+
warning_threshold=1e-3,
|
|
1766
|
+
return_deltas=False,
|
|
1767
|
+
device=None,
|
|
1768
|
+
verbose=False,
|
|
1769
|
+
tf32=False,
|
|
1770
|
+
compile=None,
|
|
1771
|
+
):
|
|
1772
|
+
"""Single-nucleotide Deep Feature Interaction Maps (Greenside et al. 2018)
|
|
1773
|
+
of a CLIPNET_TF model, as CLIPNET's `epistasis` computes them.
|
|
1774
|
+
|
|
1775
|
+
For every source position s in [start, end) of each sequence and every base
|
|
1776
|
+
other than the observed one, the feature interaction score of every target
|
|
1777
|
+
position t is FIS(t | s, b) = C_x[t] - C_x'[t]: the DeepLIFT/SHAP
|
|
1778
|
+
attribution of the observed base at t in the sequence x, minus that in x'
|
|
1779
|
+
(x with base b at s). The attributions are those of `deep_lift_shap` with
|
|
1780
|
+
the same `target`, and every variant of a sequence is attributed against
|
|
1781
|
+
that sequence's references, so FIS reflects the substitution rather than a
|
|
1782
|
+
change of references. They equal `deep_lift_shap(model, x', target,
|
|
1783
|
+
references=<x's references>)`; the references are forwarded once per step
|
|
1784
|
+
instead of once per variant.
|
|
1785
|
+
|
|
1786
|
+
Parameters
|
|
1787
|
+
----------
|
|
1788
|
+
model: CLIPNET_TF or TwoHotToOneHot
|
|
1789
|
+
X: torch.Tensor, shape=(N, 4, L)
|
|
1790
|
+
One-hot sequences.
|
|
1791
|
+
start, end: int
|
|
1792
|
+
The source positions, [start, end); end=-1 means the end of the
|
|
1793
|
+
sequence. Default: every position (L * 3 variants per sequence).
|
|
1794
|
+
target: "counts", "profile" or "shape"
|
|
1795
|
+
As in `deep_lift_shap`. Default "counts".
|
|
1796
|
+
references: torch.Tensor, shape=(N, K, 4, L), optional
|
|
1797
|
+
Default: `n_shuffles` dinucleotide shuffles of each sequence, drawn as
|
|
1798
|
+
`deep_lift_shap` draws them.
|
|
1799
|
+
n_shuffles, random_state, profile_rule, warning_threshold, device, tf32,
|
|
1800
|
+
compile:
|
|
1801
|
+
As in `deep_lift_shap`.
|
|
1802
|
+
reduce: "extrema" or None
|
|
1803
|
+
"extrema" (default) reduces over the substitutions at each source
|
|
1804
|
+
position to the most extreme FIS, keeping its sign, as CLIPNET does:
|
|
1805
|
+
shape (N, W, L). None keeps every substitution: shape
|
|
1806
|
+
(N, W, 4, L), with zeros for the observed base (not a substitution);
|
|
1807
|
+
`dfim_extrema` reduces it later, e.g. after averaging an ensemble.
|
|
1808
|
+
batch_size: int, optional
|
|
1809
|
+
Variants per step, each against all K references. Default: as many
|
|
1810
|
+
as `deep_lift_shap` takes sequences.
|
|
1811
|
+
return_deltas: bool
|
|
1812
|
+
Also return the convergence deltas: a list of (1 + n_variants, K) per
|
|
1813
|
+
sequence, the sequence first, then its variants in (position, base)
|
|
1814
|
+
order (3W of them, more at positions holding an N). Default False.
|
|
1815
|
+
verbose: bool
|
|
1816
|
+
Show a progress bar over sequences. Default False.
|
|
1817
|
+
|
|
1818
|
+
Returns
|
|
1819
|
+
-------
|
|
1820
|
+
fis: torch.Tensor, on the CPU
|
|
1821
|
+
(N, W, L) with reduce="extrema", (N, W, 4, L) with reduce=None, where
|
|
1822
|
+
W = end - start. fis[n, i, ..., t] is the interaction of target
|
|
1823
|
+
position t with source position start + i.
|
|
1824
|
+
"""
|
|
1825
|
+
|
|
1826
|
+
from tqdm import trange
|
|
1827
|
+
|
|
1828
|
+
if reduce not in ("extrema", None):
|
|
1829
|
+
raise ValueError("reduce must be 'extrema' or None")
|
|
1830
|
+
m, in_scale, device, mode = _dfim_setup(model, X, target, references, n_shuffles,
|
|
1831
|
+
profile_rule, device, compile)
|
|
1832
|
+
N, A, L = X.shape
|
|
1833
|
+
start, end = _span(start, end, L)
|
|
1834
|
+
W = end - start
|
|
1835
|
+
with _eval_mode(m), _tf32(tf32):
|
|
1836
|
+
if next(m.parameters()).device != device:
|
|
1837
|
+
import copy
|
|
1838
|
+
|
|
1839
|
+
m = copy.deepcopy(m).to(device)
|
|
1840
|
+
dtype = next(m.parameters()).dtype
|
|
1841
|
+
K = n_shuffles if references is None else references.shape[1]
|
|
1842
|
+
B = batch_size or _dfim_batch_size(m, K, L, device, dtype)
|
|
1843
|
+
out = torch.zeros(N, W, A, L, dtype=dtype)
|
|
1844
|
+
deltas = []
|
|
1845
|
+
X = X.to(torch.int8).cpu()
|
|
1846
|
+
# every base at every source position that isn't already there (all
|
|
1847
|
+
# four where the position holds an N), (N, A, W)
|
|
1848
|
+
src = X[:, :, start:end]
|
|
1849
|
+
subst = ~((src == 1) & (src.sum(1, keepdim=True) == 1))
|
|
1850
|
+
for n in trange(N, disable=not verbose):
|
|
1851
|
+
x = X[n].to(dtype)
|
|
1852
|
+
R = (references[n].to(dtype) if references is not None
|
|
1853
|
+
else _shuffle_references(x[None], K, random_state)[0])
|
|
1854
|
+
bases, pos = torch.where(subst[n])
|
|
1855
|
+
variants = x[None].repeat(len(pos), 1, 1)
|
|
1856
|
+
variants[torch.arange(len(pos)), :, start + pos] = 0
|
|
1857
|
+
variants[torch.arange(len(pos)), bases, start + pos] = 1
|
|
1858
|
+
C, D = _attribute_variants(m, in_scale, x, variants, R, target, profile_rule,
|
|
1859
|
+
mode, B, device, dtype)
|
|
1860
|
+
out[n, pos, bases] = C[:1] - C[1:]
|
|
1861
|
+
deltas.append(D)
|
|
1862
|
+
_check_deltas(torch.cat([d.flatten() for d in deltas]), warning_threshold)
|
|
1863
|
+
if reduce == "extrema":
|
|
1864
|
+
out = dfim_extrema(out, X, start, end)
|
|
1865
|
+
return (out, deltas) if return_deltas else out
|
|
1866
|
+
|
|
1867
|
+
|
|
1868
|
+
def _window_variants(x, start, end, n, shuffle, random_state):
|
|
1869
|
+
"""n copies of x with [start, end) replaced: by the same span of a
|
|
1870
|
+
dinucleotide shuffle of the whole sequence (shuffle="sequence", as
|
|
1871
|
+
CLIPNET's `dfim_shuffle` replaces it, in distribution), or by a
|
|
1872
|
+
dinucleotide shuffle of the window itself (shuffle="window")."""
|
|
1873
|
+
|
|
1874
|
+
from tangermeme.ersatz import dinucleotide_shuffle
|
|
1875
|
+
|
|
1876
|
+
if shuffle == "sequence":
|
|
1877
|
+
src = dinucleotide_shuffle(x[None], n=n, random_state=random_state)[0][..., start:end]
|
|
1878
|
+
elif shuffle == "window":
|
|
1879
|
+
src = dinucleotide_shuffle(x[None, :, start:end], n=n, random_state=random_state)[0]
|
|
1880
|
+
else:
|
|
1881
|
+
raise ValueError("shuffle must be 'sequence' or 'window'")
|
|
1882
|
+
variants = x[None].repeat(n, 1, 1)
|
|
1883
|
+
variants[..., start:end] = src.to(x.dtype)
|
|
1884
|
+
return variants
|
|
1885
|
+
|
|
1886
|
+
|
|
1887
|
+
@torch.no_grad()
|
|
1888
|
+
def dfim_shuffle(
|
|
1889
|
+
model,
|
|
1890
|
+
X,
|
|
1891
|
+
start,
|
|
1892
|
+
end,
|
|
1893
|
+
n=5,
|
|
1894
|
+
shuffle="sequence",
|
|
1895
|
+
target="counts",
|
|
1896
|
+
references=None,
|
|
1897
|
+
n_shuffles=20,
|
|
1898
|
+
random_state=None,
|
|
1899
|
+
shuffle_random_state=None,
|
|
1900
|
+
reduce="mean",
|
|
1901
|
+
batch_size=None,
|
|
1902
|
+
profile_rule="product",
|
|
1903
|
+
warning_threshold=1e-3,
|
|
1904
|
+
return_deltas=False,
|
|
1905
|
+
device=None,
|
|
1906
|
+
verbose=False,
|
|
1907
|
+
tf32=False,
|
|
1908
|
+
compile=None,
|
|
1909
|
+
):
|
|
1910
|
+
"""Window-shuffle Deep Feature Interaction Maps of a CLIPNET_TF model, as
|
|
1911
|
+
CLIPNET's `epistasis.dfim_shuffle` computes them: the interaction of
|
|
1912
|
+
every target position with a source window [start, end), as the change in
|
|
1913
|
+
the target's attribution when the window is shuffled, averaged over `n`
|
|
1914
|
+
shuffles: FIS(t) = mean_i (C_x[t] - C_x'_i[t]).
|
|
1915
|
+
|
|
1916
|
+
The attributions are those of `deep_lift_shap` with the same `target`, all
|
|
1917
|
+
against the sequence's references (see `dfim`).
|
|
1918
|
+
|
|
1919
|
+
Parameters
|
|
1920
|
+
----------
|
|
1921
|
+
start, end: int
|
|
1922
|
+
The source window.
|
|
1923
|
+
n: int
|
|
1924
|
+
Window shuffles. Default 5 (CLIPNET's default).
|
|
1925
|
+
shuffle: "sequence" or "window"
|
|
1926
|
+
"sequence" (default): replace the window with the same span of a
|
|
1927
|
+
dinucleotide shuffle of the whole sequence, as CLIPNET does (which
|
|
1928
|
+
takes a span starting at 1 of the shuffle instead: the same in
|
|
1929
|
+
distribution, not the same draws). This replaces the window's
|
|
1930
|
+
composition with the sequence's, and avoids the few permutations a
|
|
1931
|
+
short window has. "window": a dinucleotide shuffle of the window
|
|
1932
|
+
itself, which keeps its composition.
|
|
1933
|
+
shuffle_random_state: int or None
|
|
1934
|
+
Seed of the window shuffles. Default: `random_state`.
|
|
1935
|
+
reduce: "mean" or None
|
|
1936
|
+
"mean" (default): (N, L). None: every shuffle's FIS, (N, n, L).
|
|
1937
|
+
Other parameters as in `dfim`.
|
|
1938
|
+
|
|
1939
|
+
Returns
|
|
1940
|
+
-------
|
|
1941
|
+
fis: torch.Tensor, (N, L) or (N, n, L), on the CPU
|
|
1942
|
+
deltas: torch.Tensor, (N, 1 + n, K), if `return_deltas`
|
|
1943
|
+
"""
|
|
1944
|
+
|
|
1945
|
+
from tqdm import trange
|
|
1946
|
+
|
|
1947
|
+
if reduce not in ("mean", None):
|
|
1948
|
+
raise ValueError("reduce must be 'mean' or None")
|
|
1949
|
+
m, in_scale, device, mode = _dfim_setup(model, X, target, references, n_shuffles,
|
|
1950
|
+
profile_rule, device, compile)
|
|
1951
|
+
N, _, L = X.shape
|
|
1952
|
+
start, end = _span(start, end, L)
|
|
1953
|
+
if shuffle_random_state is None:
|
|
1954
|
+
shuffle_random_state = random_state
|
|
1955
|
+
with _eval_mode(m), _tf32(tf32):
|
|
1956
|
+
if next(m.parameters()).device != device:
|
|
1957
|
+
import copy
|
|
1958
|
+
|
|
1959
|
+
m = copy.deepcopy(m).to(device)
|
|
1960
|
+
dtype = next(m.parameters()).dtype
|
|
1961
|
+
K = n_shuffles if references is None else references.shape[1]
|
|
1962
|
+
B = batch_size or _dfim_batch_size(m, K, L, device, dtype)
|
|
1963
|
+
out = torch.empty(N, n, L, dtype=dtype)
|
|
1964
|
+
deltas = torch.empty(N, 1 + n, K, dtype=dtype)
|
|
1965
|
+
for i in trange(N, disable=not verbose):
|
|
1966
|
+
x = X[i].to(torch.int8).to(dtype)
|
|
1967
|
+
R = (references[i].to(dtype) if references is not None
|
|
1968
|
+
else _shuffle_references(x[None], K, random_state)[0])
|
|
1969
|
+
variants = _window_variants(x, start, end, n, shuffle, shuffle_random_state)
|
|
1970
|
+
C, D = _attribute_variants(m, in_scale, x, variants, R, target, profile_rule,
|
|
1971
|
+
mode, B, device, dtype)
|
|
1972
|
+
out[i] = C[:1] - C[1:]
|
|
1973
|
+
deltas[i] = D
|
|
1974
|
+
_check_deltas(deltas, warning_threshold)
|
|
1975
|
+
if reduce == "mean":
|
|
1976
|
+
out = out.mean(1)
|
|
1977
|
+
return (out, deltas) if return_deltas else out
|
|
@@ -147,3 +147,41 @@ def test_clipnet_tf_attribute_accepts_shape(monkeypatch):
|
|
|
147
147
|
add_attribute_args(parser)
|
|
148
148
|
with pytest.raises(SystemExit):
|
|
149
149
|
parse_args(parser, ["-a", "shape"])
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def test_clipnet_tf_dfim_parser_defaults(monkeypatch):
|
|
153
|
+
"""`clipnet_tf dfim` defaults to CLIPNET's source range 250..750 and leaves
|
|
154
|
+
-bs to the engine; `dfim_shuffle` requires its window."""
|
|
155
|
+
|
|
156
|
+
import argparse
|
|
157
|
+
import sys
|
|
158
|
+
|
|
159
|
+
import cli.tf as tf
|
|
160
|
+
|
|
161
|
+
seen = {}
|
|
162
|
+
parse_args = argparse.ArgumentParser.parse_args
|
|
163
|
+
|
|
164
|
+
def spy(self, *args, **kwargs):
|
|
165
|
+
seen["ns"] = parse_args(self, *args, **kwargs)
|
|
166
|
+
raise SystemExit
|
|
167
|
+
|
|
168
|
+
monkeypatch.setattr(argparse.ArgumentParser, "parse_args", spy)
|
|
169
|
+
required = ["-f", "a.fa", "-b", "a.bed", "-o", "o.npz", "-m", "m.h5"]
|
|
170
|
+
monkeypatch.setattr(sys, "argv", ["clipnet_tf", "dfim", *required])
|
|
171
|
+
with pytest.raises(SystemExit):
|
|
172
|
+
tf.cli()
|
|
173
|
+
ns = seen["ns"]
|
|
174
|
+
assert (ns.start, ns.end, ns.batch_size, ns.attribute_type) == (250, 750, None, "counts")
|
|
175
|
+
assert not ns.all_substitutions
|
|
176
|
+
|
|
177
|
+
monkeypatch.setattr(sys, "argv", ["clipnet_tf", "dfim_shuffle", "--start", "1",
|
|
178
|
+
"--end", "9", "--shuffle", "window", *required])
|
|
179
|
+
with pytest.raises(SystemExit):
|
|
180
|
+
tf.cli()
|
|
181
|
+
ns = seen["ns"]
|
|
182
|
+
assert (ns.start, ns.end, ns.shuffle, ns.n_window_shuffles) == (1, 9, "window", 5)
|
|
183
|
+
|
|
184
|
+
monkeypatch.setattr(argparse.ArgumentParser, "parse_args", parse_args)
|
|
185
|
+
monkeypatch.setattr(sys, "argv", ["clipnet_tf", "dfim_shuffle", *required])
|
|
186
|
+
with pytest.raises(SystemExit): # --start/--end are required
|
|
187
|
+
tf.cli()
|
|
@@ -415,3 +415,108 @@ def test_deep_lift_shap_shape_matches_tangermeme(hypothetical):
|
|
|
415
415
|
device="cpu")
|
|
416
416
|
assert _rel(got, torch.cat(expected)) < 1e-10
|
|
417
417
|
assert float(deltas.max()) < 1e-10
|
|
418
|
+
|
|
419
|
+
|
|
420
|
+
# ----------------------------------------------------------------------- DFIM
|
|
421
|
+
|
|
422
|
+
|
|
423
|
+
def _observed(a, x):
|
|
424
|
+
return (a * x).sum(-2)
|
|
425
|
+
|
|
426
|
+
|
|
427
|
+
@pytest.mark.skipif(BilinearOp is None, reason="needs tangermeme >= 1.5")
|
|
428
|
+
@pytest.mark.parametrize("target", ["counts", "profile", "shape"])
|
|
429
|
+
def test_dfim_matches_tangermeme_per_substitution(target):
|
|
430
|
+
"""Each FIS row is C_x - C_x' for one substitution, with both attributed
|
|
431
|
+
by tangermeme against the sequence's references."""
|
|
432
|
+
|
|
433
|
+
from personal_bpnet.clipnet_tf_fast import dfim
|
|
434
|
+
|
|
435
|
+
model, X = _model(), _X(2, seed=4)
|
|
436
|
+
refs = torch.stack([random_one_hot((3, 4, 1000), random_state=i) for i in range(2)]).double()
|
|
437
|
+
start, end = 100, 104
|
|
438
|
+
|
|
439
|
+
def wrapper(z):
|
|
440
|
+
if target == "counts":
|
|
441
|
+
return CountWrapper(model), None
|
|
442
|
+
if target == "profile":
|
|
443
|
+
return _ProductProfileWrapper(model), None
|
|
444
|
+
model.eval() # tangermeme leaves the model in train mode
|
|
445
|
+
with torch.no_grad():
|
|
446
|
+
y = model(z)[0]
|
|
447
|
+
return _ShapeWrapper(model, y / (y.sum(-1, keepdim=True) + 1e-3)), {_Reciprocal: _nonlinear}
|
|
448
|
+
|
|
449
|
+
def attr(z, R):
|
|
450
|
+
w, ops = wrapper(z)
|
|
451
|
+
return _observed(tm_deep_lift_shap(w, z, references=R, device="cpu",
|
|
452
|
+
warning_threshold=1e9,
|
|
453
|
+
additional_nonlinear_ops=ops), z)[0]
|
|
454
|
+
|
|
455
|
+
got, deltas = dfim(model, X, start, end, target=target, references=refs, reduce=None,
|
|
456
|
+
return_deltas=True, device="cpu", batch_size=5) # 5 doesn't divide 13
|
|
457
|
+
assert got.shape == (2, end - start, 4, 1000)
|
|
458
|
+
for n in range(2):
|
|
459
|
+
x, R = X[n : n + 1], refs[n : n + 1]
|
|
460
|
+
c0 = attr(x, R)
|
|
461
|
+
for i, s in enumerate(range(start, end)):
|
|
462
|
+
for b in range(4):
|
|
463
|
+
if X[n, b, s] == 1:
|
|
464
|
+
assert torch.equal(got[n, i, b], torch.zeros(1000, dtype=got.dtype))
|
|
465
|
+
continue
|
|
466
|
+
xm = x.clone()
|
|
467
|
+
xm[0, :, s] = 0
|
|
468
|
+
xm[0, b, s] = 1
|
|
469
|
+
assert _rel(got[n, i, b], c0 - attr(xm, R)) < 1e-10
|
|
470
|
+
assert all(d.shape == (1 + 3 * (end - start), 3) for d in deltas)
|
|
471
|
+
assert max(float(d.max()) for d in deltas) < 1e-10
|
|
472
|
+
|
|
473
|
+
|
|
474
|
+
def test_dfim_extrema_and_n_positions():
|
|
475
|
+
from personal_bpnet.clipnet_tf_fast import dfim
|
|
476
|
+
|
|
477
|
+
model, X = _model(counts_head_only=True), _X(2, seed=5)
|
|
478
|
+
X[1, :, 52] = 0 # an N: all four bases are substitutions
|
|
479
|
+
# (tangermeme's shuffles refuse an N, so the references are given)
|
|
480
|
+
refs = torch.stack([random_one_hot((2, 4, 1000), random_state=i) for i in range(2)]).double()
|
|
481
|
+
kwargs = dict(start=50, end=55, references=refs, device="cpu")
|
|
482
|
+
full, deltas = dfim(model, X, reduce=None, return_deltas=True, **kwargs)
|
|
483
|
+
ext = dfim(model, X, **kwargs)
|
|
484
|
+
assert [len(d) for d in deltas] == [1 + 15, 1 + 16]
|
|
485
|
+
subst = ~X[:, :, 50:55].bool().permute(0, 2, 1)[..., None]
|
|
486
|
+
hi = torch.where(subst, full, -torch.inf).amax(2)
|
|
487
|
+
lo = torch.where(subst, full, torch.inf).amin(2)
|
|
488
|
+
assert ext.shape == (2, 5, 1000)
|
|
489
|
+
assert torch.equal(ext, torch.where(-lo > hi, lo, hi))
|
|
490
|
+
|
|
491
|
+
|
|
492
|
+
def test_dfim_shuffle_matches_tangermeme():
|
|
493
|
+
from personal_bpnet.clipnet_tf_fast import _window_variants, dfim_shuffle
|
|
494
|
+
|
|
495
|
+
model, X = _model(), _X(2, seed=6)
|
|
496
|
+
refs = torch.stack([random_one_hot((2, 4, 1000), random_state=i) for i in range(2)]).double()
|
|
497
|
+
got = dfim_shuffle(model, X, 480, 520, n=3, references=refs, random_state=0, reduce=None,
|
|
498
|
+
device="cpu", batch_size=2)
|
|
499
|
+
mean = dfim_shuffle(model, X, 480, 520, n=3, references=refs, random_state=0, device="cpu")
|
|
500
|
+
assert got.shape == (2, 3, 1000) and torch.allclose(mean, got.mean(1))
|
|
501
|
+
for n in range(2):
|
|
502
|
+
V = _window_variants(X[n], 480, 520, 3, "sequence", 0)
|
|
503
|
+
assert torch.equal(V[..., :480], X[n, :, :480].expand(3, -1, -1))
|
|
504
|
+
assert torch.equal(V[..., 520:], X[n, :, 520:].expand(3, -1, -1))
|
|
505
|
+
c0 = _observed(tm_deep_lift_shap(CountWrapper(model), X[n : n + 1],
|
|
506
|
+
references=refs[n : n + 1], device="cpu",
|
|
507
|
+
warning_threshold=1e9), X[n : n + 1])
|
|
508
|
+
for i in range(3):
|
|
509
|
+
c1 = _observed(tm_deep_lift_shap(CountWrapper(model), V[i : i + 1],
|
|
510
|
+
references=refs[n : n + 1], device="cpu",
|
|
511
|
+
warning_threshold=1e9), V[i : i + 1])
|
|
512
|
+
assert _rel(got[n, i], (c0 - c1)[0]) < 1e-10
|
|
513
|
+
|
|
514
|
+
|
|
515
|
+
def test_window_variants_window_mode_keeps_composition():
|
|
516
|
+
from personal_bpnet.clipnet_tf_fast import _window_variants
|
|
517
|
+
|
|
518
|
+
x = _X(1, seed=7)[0]
|
|
519
|
+
V = _window_variants(x, 300, 340, 4, "window", 1)
|
|
520
|
+
assert torch.equal(V[..., 300:340].sum(-1), x[:, 300:340].sum(-1).expand(4, -1))
|
|
521
|
+
with pytest.raises(ValueError):
|
|
522
|
+
_window_variants(x, 300, 340, 4, "motif", 1)
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|