PersonalBPNet 0.7.0__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.
cli/__init__.py ADDED
@@ -0,0 +1 @@
1
+
cli/_common.py ADDED
@@ -0,0 +1,233 @@
1
+ # _common.py
2
+ # Author: Adam He <adamyhe@gmail.com>
3
+
4
+ """
5
+ Argparse and ensemble-loading helpers shared by the clipnet, pausenet, and
6
+ clipnet_tf CLIs.
7
+ """
8
+
9
+ import argparse
10
+ import os
11
+
12
+ import torch
13
+
14
+
15
+ def build_parent_parser(bed_fname_help=None):
16
+ """The -f/-b/-o/-m/-c/-bs/-v arguments common to every subcommand of every CLI
17
+ in this project. Callers may add further arguments to the returned parser
18
+ before passing it as a `parents=[...]` entry to `subparsers.add_parser`."""
19
+
20
+ parser = argparse.ArgumentParser(add_help=False)
21
+ parser.add_argument(
22
+ "-f",
23
+ "--fa_fname",
24
+ type=str,
25
+ required=True,
26
+ help="Path to uncompressed fasta file.",
27
+ )
28
+ parser.add_argument(
29
+ "-b",
30
+ "--bed_fname",
31
+ type=str,
32
+ required=True,
33
+ help=bed_fname_help
34
+ or "Path to bed file of regions to calculate predictions/attributions for.",
35
+ )
36
+ parser.add_argument(
37
+ "-o", "--out_fname", type=str, required=True, help="Path to output npz file"
38
+ )
39
+ parser.add_argument(
40
+ "-m",
41
+ "--model_fname",
42
+ type=str,
43
+ required=True,
44
+ help="Path to model directory or to specific model file to predict/attribute. "
45
+ "If a directory, loads and calculates average predictions/attributions across "
46
+ "all models in directory. If a specific model file, will only predict/attribute "
47
+ "that model. ",
48
+ )
49
+ parser.add_argument(
50
+ "-c",
51
+ "--chroms",
52
+ type=str,
53
+ nargs="+",
54
+ default=None,
55
+ help="Chromosomes to calculate attributions for. Defaults to all chromosomes.",
56
+ )
57
+ parser.add_argument(
58
+ "-bs",
59
+ "--batch_size",
60
+ type=int,
61
+ default=16,
62
+ help="Batch size to control VRAM usage. Defaults to 16.",
63
+ )
64
+ parser.add_argument(
65
+ "-v", "--verbose", action="store_true", help="Whether to print progress bars."
66
+ )
67
+ return parser
68
+
69
+
70
+ def add_shape_args(parser):
71
+ """The --in_window/--out_window/--n_filters/--n_layers arguments used to
72
+ reconstruct a model from a bare state dict, shared across clipnet/pausenet
73
+ predict/predict_tss/attribute subcommands."""
74
+
75
+ parser.add_argument(
76
+ "--in_window",
77
+ type=int,
78
+ default=2114,
79
+ help="Used to specify model input size. "
80
+ "Should not be needed unless using a custom model.",
81
+ )
82
+ parser.add_argument(
83
+ "--out_window",
84
+ type=int,
85
+ default=1000,
86
+ help="Used to specify model output size. "
87
+ "Should not be needed unless using a custom model.",
88
+ )
89
+ parser.add_argument(
90
+ "--n_filters",
91
+ type=int,
92
+ default=512,
93
+ help="Used to specify model convolutions. "
94
+ "Should not be needed unless using a custom model.",
95
+ )
96
+ parser.add_argument(
97
+ "--n_layers",
98
+ type=int,
99
+ default=8,
100
+ help="Used to specify model layers. "
101
+ "Should not be needed unless using a custom model.",
102
+ )
103
+
104
+
105
+ def add_attribute_args(parser):
106
+ """The -a/-s/-y/-n/-r arguments shared by every CLI's attribute subcommand."""
107
+
108
+ parser.add_argument(
109
+ "-a",
110
+ "--attribute_type",
111
+ type=str,
112
+ default="counts",
113
+ choices={"counts", "profile"},
114
+ help="The type of attribution to calculate.",
115
+ )
116
+ parser.add_argument(
117
+ "-s",
118
+ "--save_ohe",
119
+ type=str,
120
+ default=None,
121
+ help="Where to save OHE of sequences. Defaults to not saving. "
122
+ "Set this & hypothetical if you intend to use these attributions for "
123
+ "tfmodisco-lite.",
124
+ )
125
+ parser.add_argument(
126
+ "-y",
127
+ "--hypothetical",
128
+ action="store_true",
129
+ help="Whether to use hypothetical attributions. Defaults to False. "
130
+ "Set this & save_ohe if you intend to use these attributions for "
131
+ "tfmodisco-lite.",
132
+ )
133
+ parser.add_argument(
134
+ "-n",
135
+ "--n_shuffles",
136
+ type=int,
137
+ default=20,
138
+ help="Number of dinucleotide shuffles for DeepLIFT/SHAP. Defaults to 20.",
139
+ )
140
+ parser.add_argument(
141
+ "-r",
142
+ "--random_state",
143
+ type=int,
144
+ default=47,
145
+ help="Random seed. Defaults to 47.",
146
+ )
147
+
148
+
149
+ def resolve_model_paths(model_fname, pattern="f{i}.torch", n=9):
150
+ """If `model_fname` is a directory, returns the `n` replicate paths matching
151
+ `pattern` (formatted with i=1..n) inside it; otherwise returns `[model_fname]`
152
+ unchanged."""
153
+
154
+ if os.path.isdir(model_fname):
155
+ return [os.path.join(model_fname, pattern.format(i=i)) for i in range(1, n + 1)]
156
+ return [model_fname]
157
+
158
+
159
+ def set_cpu_threads():
160
+ """Use all available CPU cores for inference when no GPU is present, capped by
161
+ SLURM's allocation when running under a SLURM job."""
162
+
163
+ if not torch.cuda.is_available():
164
+ if "SLURM_CPUS_PER_TASK" in os.environ:
165
+ n = min(int(os.environ["SLURM_CPUS_PER_TASK"]), os.cpu_count())
166
+ else:
167
+ n = os.cpu_count()
168
+ torch.set_num_threads(n)
169
+ torch.set_num_interop_threads(n)
170
+
171
+
172
+ def resolve_device():
173
+ return "cuda" if torch.cuda.is_available() else "cpu"
174
+
175
+
176
+ def load_torch_model(path, build_model_fn):
177
+ """Loads a `.torch` file that is either a full serialized module or a bare
178
+ state dict; in the latter case, builds a fresh model via `build_model_fn` and
179
+ loads the state dict into it."""
180
+
181
+ checkpoint = torch.load(path)
182
+ if isinstance(checkpoint, torch.nn.Module):
183
+ return checkpoint
184
+ model = build_model_fn()
185
+ model.load_state_dict(checkpoint)
186
+ return model
187
+
188
+
189
+ def load_ensemble(model_paths, load_fn):
190
+ """Yields one model per path in `model_paths`, loaded via `load_fn(path)`.
191
+ Frees each replicate before loading the next to avoid accumulating VRAM/RAM
192
+ across the ensemble; the caller should fully consume each yielded model
193
+ (e.g. run prediction/attribution on it) before continuing the loop."""
194
+
195
+ for path in model_paths:
196
+ model = load_fn(path)
197
+ yield model
198
+ del model
199
+ torch.cuda.empty_cache()
200
+
201
+
202
+ def average_profile_and_counts(predictions):
203
+ """Ensembles (profile_logits, log_counts) predictions from multiple replicates.
204
+
205
+ Averages the raw profile logits and log-counts across replicates *before*
206
+ applying the softmax/exp nonlinearity, then rescales. Averaging after the
207
+ nonlinearity instead (i.e. averaging already-softmaxed, already-rescaled
208
+ per-replicate tracks) biases the ensembled profile toward uniformity whenever
209
+ replicates disagree, which understates real signal.
210
+
211
+ Parameters
212
+ ----------
213
+ predictions: list of (profile_logits, log_counts) tuples, one per replicate, as
214
+ returned by tangermeme.predict.predict.
215
+
216
+ Returns
217
+ -------
218
+ track: torch.Tensor, shape=profile_logits.shape
219
+ The ensembled, rescaled profile track.
220
+ """
221
+
222
+ profiles, counts = zip(*predictions)
223
+ shape = profiles[0].shape
224
+
225
+ mean_profile = torch.stack(
226
+ [profile.reshape(profile.shape[0], -1) for profile in profiles]
227
+ ).mean(dim=0)
228
+ mean_count = torch.stack(list(counts)).mean(dim=0)
229
+
230
+ track = torch.nn.functional.softmax(mean_profile, dim=-1) * (
231
+ torch.exp(mean_count) - 1
232
+ )
233
+ return track.reshape(*shape)
cli/clipnet.py ADDED
@@ -0,0 +1,340 @@
1
+ #!/usr/bin/env python
2
+ # CLIPNET CLI
3
+ # Author: Adam He <adamyhe@gmail.com>
4
+
5
+ """
6
+ Wrapper script to calculate attributions and predictions for CLIPNET models
7
+ """
8
+
9
+ import random
10
+ import warnings
11
+
12
+ import numpy as np
13
+ import torch
14
+ from argparse import ArgumentParser
15
+ from bpnetlite.bpnet import CountWrapper, ProfileWrapper, _ProfileLogitScaling
16
+ from bpnetlite.performance import pearson_corr, spearman_corr
17
+ from scipy.spatial.distance import jensenshannon
18
+ from sklearn.linear_model import LinearRegression
19
+ from tangermeme.deep_lift_shap import _nonlinear, deep_lift_shap
20
+ from tangermeme.io import extract_loci
21
+ from tangermeme.predict import predict
22
+
23
+ from personal_bpnet.clipnet_pytorch import CLIPNET
24
+
25
+ from ._common import (
26
+ add_attribute_args,
27
+ add_shape_args,
28
+ average_profile_and_counts,
29
+ build_parent_parser,
30
+ load_ensemble,
31
+ load_torch_model,
32
+ resolve_device,
33
+ resolve_model_paths,
34
+ set_cpu_threads,
35
+ )
36
+
37
+ _help = """
38
+ The following commands are available:
39
+ predict Calculate predictions for a CLIPNET model
40
+ predict_tss Calculate TSS predictions (uses aggressive jittering).
41
+ attribute Calculate DeepLIFT/SHAP attributions for a CLIPNET model
42
+ Planned but not implemented commands:
43
+ vep Calculate variant effect prediction using a CLIPNET model
44
+ """
45
+
46
+
47
+ def _build_clipnet(args):
48
+ return CLIPNET(
49
+ n_filters=args.n_filters,
50
+ n_outputs=2,
51
+ n_control_tracks=0,
52
+ n_layers=args.n_layers,
53
+ trimming=(args.in_window - args.out_window) // 2,
54
+ )
55
+
56
+
57
+ def cli():
58
+ parser_parent = build_parent_parser()
59
+
60
+ parser = ArgumentParser(description=__doc__)
61
+ subparsers = parser.add_subparsers(
62
+ help="The following commands are available:", required=True, dest="cmd"
63
+ )
64
+
65
+ # PREDICT PARAMS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
66
+
67
+ parser_predict = subparsers.add_parser(
68
+ "predict",
69
+ help="Calculate predictions for a given set of regions.",
70
+ parents=[parser_parent],
71
+ )
72
+ parser_predict.add_argument(
73
+ "-s",
74
+ "--signal_fname",
75
+ type=str,
76
+ nargs=2,
77
+ default=None,
78
+ help="Signal files containing experimental data to benchmark model "
79
+ "predictions against. Expected order is [plus_bigWig, minus_bigWig]. "
80
+ "If not provided, will not calculate performance metrics.",
81
+ )
82
+ parser_predict.add_argument(
83
+ "-r",
84
+ "--restrict_out",
85
+ type=int,
86
+ default=None,
87
+ help="Restrict output prediction to a specific size. Default is None.",
88
+ )
89
+ add_shape_args(parser_predict)
90
+
91
+ # PREDICT_TSS PARAMS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
92
+
93
+ parser_predict_tss = subparsers.add_parser(
94
+ "predict_tss",
95
+ help="Calculate TSS predictions for a given set of jittered regions.",
96
+ parents=[parser_parent],
97
+ )
98
+ parser_predict_tss.add_argument(
99
+ "-s",
100
+ "--signal_fname",
101
+ type=str,
102
+ nargs=2,
103
+ default=None,
104
+ help="Signal files containing experimental data to benchmark model "
105
+ "predictions against. Expected order is [plus_bigWig, minus_bigWig]. "
106
+ "If not provided, will not calculate performance metrics.",
107
+ )
108
+ parser_predict_tss.add_argument(
109
+ "-j",
110
+ "--max_jitter",
111
+ type=int,
112
+ default=500,
113
+ help="Maximum number of bp to jitter. Default is 500.",
114
+ )
115
+ add_shape_args(parser_predict_tss)
116
+
117
+ # ATTRIBUTE PARAMS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
118
+
119
+ parser_attribute = subparsers.add_parser(
120
+ "attribute",
121
+ help="Calculate attributions for a given set of regions.",
122
+ parents=[parser_parent],
123
+ )
124
+ add_attribute_args(parser_attribute)
125
+ add_shape_args(parser_attribute)
126
+ args = parser.parse_args()
127
+
128
+ # MAIN CODE ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
129
+
130
+ model_paths = resolve_model_paths(args.model_fname)
131
+ set_cpu_threads()
132
+ device = resolve_device()
133
+
134
+ if args.cmd == "predict":
135
+ # Load data
136
+ data = extract_loci(
137
+ loci=args.bed_fname,
138
+ sequences=args.fa_fname,
139
+ signals=args.signal_fname,
140
+ chroms=args.chroms,
141
+ in_window=args.in_window,
142
+ out_window=args.out_window,
143
+ verbose=args.verbose,
144
+ ignore=list("QWERYUIOPSDFHJKLZXVBNM"),
145
+ )
146
+ if args.signal_fname is not None:
147
+ X, signals = data
148
+ else:
149
+ X = data
150
+
151
+ predictions = [
152
+ predict(
153
+ model,
154
+ X,
155
+ batch_size=args.batch_size,
156
+ verbose=args.verbose,
157
+ device=device,
158
+ )
159
+ for model in load_ensemble(
160
+ model_paths, lambda f: load_torch_model(f, lambda: _build_clipnet(args))
161
+ )
162
+ ]
163
+
164
+ # Ensemble and rescale predictions
165
+ track = average_profile_and_counts(predictions)
166
+
167
+ # Save predictions
168
+ np.savez_compressed(args.out_fname, track.numpy())
169
+
170
+ if args.restrict_out is not None:
171
+ if args.restrict_out < args.out_window:
172
+ track = track[
173
+ :,
174
+ :,
175
+ (args.out_window - args.restrict_out) // 2 : (
176
+ args.out_window + args.restrict_out
177
+ )
178
+ // 2,
179
+ ]
180
+ signals = signals[
181
+ :,
182
+ :,
183
+ (args.out_window - args.restrict_out) // 2 : (
184
+ args.out_window + args.restrict_out
185
+ )
186
+ // 2,
187
+ ]
188
+ else:
189
+ warnings.warn(
190
+ f"{args.restrict_out} >= {args.out_window}. Ignoring restrict_out."
191
+ )
192
+
193
+ # Calculate metrics
194
+ if args.signal_fname is not None:
195
+ signals_flattened = torch.abs(signals).reshape(signals.shape[0], -1)
196
+ track_flattened = track.reshape(track.shape[0], -1)
197
+ pred_log_counts = torch.log1p(track_flattened.sum(dim=-1))
198
+
199
+ profile_pearson = pearson_corr(track_flattened, signals_flattened)
200
+ profile_jsd = jensenshannon(
201
+ track_flattened.numpy(), signals_flattened.numpy(), axis=1
202
+ )
203
+ counts_pearson = pearson_corr(
204
+ pred_log_counts, torch.log1p(signals_flattened.sum(dim=-1))
205
+ )
206
+ counts_spearman = spearman_corr(
207
+ pred_log_counts, torch.log1p(signals_flattened.sum(dim=-1))
208
+ )
209
+ lm = LinearRegression(fit_intercept=True).fit(
210
+ pred_log_counts.reshape(-1, 1),
211
+ torch.log1p(signals_flattened.sum(dim=-1).reshape(-1, 1)),
212
+ )
213
+
214
+ print(
215
+ f"Mean profile Pearson: {np.nanmean(profile_pearson)} "
216
+ f"+/- {np.nanstd(profile_pearson, ddof=1)}"
217
+ )
218
+ print(f"Median profile Pearson: {np.nanmedian(profile_pearson)}")
219
+ print(f"Mean profile JSD: {np.nanmean(profile_jsd)}")
220
+ print(f"Median profile JSD: {np.nanmedian(profile_jsd)}")
221
+ print(f"Count Pearson: {counts_pearson}")
222
+ print(f"Count Spearman: {counts_spearman}")
223
+ print(f"Count slope: {lm.coef_[0]}")
224
+ print(f"Count intercept: {lm.intercept_}")
225
+
226
+ np.savez_compressed(
227
+ args.out_fname.replace(".npz", "_metrics.npz"),
228
+ profile_pearson=profile_pearson,
229
+ profile_jsd=profile_jsd,
230
+ counts_pearson=counts_pearson,
231
+ counts_spearman=counts_spearman,
232
+ )
233
+
234
+ elif args.cmd == "predict_tss":
235
+ # Load data
236
+ loci = extract_loci(
237
+ loci=args.bed_fname,
238
+ sequences=args.fa_fname,
239
+ signals=args.signal_fname,
240
+ chroms=args.chroms,
241
+ in_window=args.in_window,
242
+ out_window=args.out_window,
243
+ max_jitter=args.max_jitter,
244
+ verbose=args.verbose,
245
+ )
246
+ if args.signal_fname is not None:
247
+ seqs, signals = loci
248
+ else:
249
+ seqs = loci
250
+ # Jitter
251
+ seqs_jitter = []
252
+ signals_jitter = []
253
+ for i in range(seqs.shape[0]):
254
+ j = random.randint(0, args.max_jitter * 2 - 1)
255
+ seqs_jitter.append(seqs[i, :, j : j + args.in_window])
256
+ signals_jitter.append(signals[i, :, j : j + args.out_window])
257
+
258
+ X = torch.stack(seqs_jitter)
259
+ signals = torch.abs(torch.stack(signals_jitter))
260
+
261
+ # Calculate predictions
262
+ predictions = [
263
+ predict(
264
+ model,
265
+ X,
266
+ batch_size=args.batch_size,
267
+ verbose=args.verbose,
268
+ device=device,
269
+ )
270
+ for model in load_ensemble(
271
+ model_paths, lambda f: load_torch_model(f, lambda: _build_clipnet(args))
272
+ )
273
+ ]
274
+
275
+ # Ensemble and rescale predictions
276
+ track = average_profile_and_counts(predictions)
277
+
278
+ # Calculate metrics
279
+ if args.signal_fname is not None:
280
+ pred_tss = torch.argmax(track, dim=-1).to(torch.float)
281
+ expt_tss = torch.argmax(signals, dim=-1).to(torch.float)
282
+ np.savez_compressed(args.out_fname, pred=pred_tss, expt=expt_tss)
283
+
284
+ print(
285
+ f"+ strand TSS Pearson: {pearson_corr(pred_tss[:, 0], expt_tss[:, 0])}"
286
+ )
287
+ print(
288
+ f"- strand TSS Pearson: {pearson_corr(pred_tss[:, 1], expt_tss[:, 1])}"
289
+ )
290
+
291
+ elif args.cmd == "attribute":
292
+ # Load data
293
+ X = extract_loci(
294
+ loci=args.bed_fname,
295
+ sequences=args.fa_fname,
296
+ chroms=args.chroms,
297
+ in_window=args.in_window,
298
+ out_window=args.out_window,
299
+ verbose=args.verbose,
300
+ ignore=list("QWERYUIOPSDFHJKLZXVBNM"),
301
+ ).to(torch.float)
302
+ if args.save_ohe is not None:
303
+ np.savez_compressed(args.save_ohe, X.to(int).numpy())
304
+
305
+ attributions = []
306
+ for model in load_ensemble(
307
+ model_paths, lambda f: load_torch_model(f, lambda: _build_clipnet(args))
308
+ ):
309
+ additional_nonlinear_ops = None
310
+ # Wrap models depending on args.attribute_type
311
+ if args.attribute_type == "counts":
312
+ model = CountWrapper(model)
313
+ else:
314
+ model = ProfileWrapper(model)
315
+ additional_nonlinear_ops = {_ProfileLogitScaling: _nonlinear}
316
+
317
+ # Calculate and log attributions
318
+ attributions.append(
319
+ deep_lift_shap(
320
+ model,
321
+ X,
322
+ hypothetical=args.hypothetical,
323
+ batch_size=args.batch_size,
324
+ n_shuffles=args.n_shuffles,
325
+ random_state=args.random_state,
326
+ verbose=args.verbose,
327
+ additional_nonlinear_ops=additional_nonlinear_ops,
328
+ device=device,
329
+ ).numpy()
330
+ )
331
+
332
+ # Save
333
+ np.savez_compressed(args.out_fname, np.stack(attributions).mean(axis=0))
334
+
335
+ else:
336
+ raise ValueError(_help)
337
+
338
+
339
+ if __name__ == "__main__":
340
+ cli()