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/pausenet.py ADDED
@@ -0,0 +1,189 @@
1
+ #!/usr/bin/env python
2
+ # PauseNet CLI
3
+ # Author: Adam He <adamyhe@gmail.com>
4
+
5
+ """
6
+ Wrapper script to calculate attributions and predictions for PauseNet models
7
+ """
8
+
9
+ from argparse import ArgumentParser
10
+
11
+ import numpy as np
12
+ import pandas as pd
13
+ import torch
14
+ from scipy.stats import pearsonr, spearmanr
15
+ from tangermeme.deep_lift_shap import deep_lift_shap
16
+ from tangermeme.io import extract_loci
17
+ from tangermeme.predict import predict
18
+
19
+ from personal_bpnet.clipnet_pytorch import CLIPNET, PauseNet
20
+
21
+ from ._common import (
22
+ add_attribute_args,
23
+ add_shape_args,
24
+ build_parent_parser,
25
+ load_ensemble,
26
+ load_torch_model,
27
+ resolve_device,
28
+ resolve_model_paths,
29
+ set_cpu_threads,
30
+ )
31
+
32
+ _help = """
33
+ The following commands are available:
34
+ predict Calculate predictions for a PauseNet model
35
+ attribute Calculate DeepLIFT/SHAP attributions for a PauseNet model
36
+ Planned but not implemented commands:
37
+ vep Calculate variant effect prediction using a PauseNet model
38
+ """
39
+
40
+
41
+ def _build_pausenet(args):
42
+ base_model = CLIPNET(
43
+ n_filters=args.n_filters,
44
+ n_outputs=2,
45
+ n_control_tracks=0,
46
+ n_layers=args.n_layers,
47
+ trimming=(args.in_window - args.out_window) // 2,
48
+ )
49
+ return PauseNet(base_model)
50
+
51
+
52
+ def cli():
53
+ parser_parent = build_parent_parser(
54
+ bed_fname_help=(
55
+ "Path to bed file of regions to calculate predictions/attributions for. "
56
+ "Will assume that the 6th column (if provided for a bed6+ file) is the "
57
+ "target phenotype for this model, and will compute performance metrics "
58
+ "with it."
59
+ )
60
+ )
61
+
62
+ parser = ArgumentParser(description=__doc__)
63
+ subparsers = parser.add_subparsers(
64
+ help="The following commands are available:", required=True, dest="cmd"
65
+ )
66
+
67
+ # PREDICT PARAMS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
68
+
69
+ parser_predict = subparsers.add_parser(
70
+ "predict",
71
+ help="Calculate predictions for a given set of regions.",
72
+ parents=[parser_parent],
73
+ )
74
+ add_shape_args(parser_predict)
75
+
76
+ # ATTRIBUTE PARAMS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
77
+
78
+ parser_attribute = subparsers.add_parser(
79
+ "attribute",
80
+ help="Calculate attributions for a given set of regions.",
81
+ parents=[parser_parent],
82
+ )
83
+ add_attribute_args(parser_attribute)
84
+ add_shape_args(parser_attribute)
85
+ args = parser.parse_args()
86
+
87
+ # MAIN CODE ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
88
+
89
+ model_paths = resolve_model_paths(args.model_fname)
90
+ set_cpu_threads()
91
+ device = resolve_device()
92
+
93
+ if args.cmd == "predict":
94
+ # Load data
95
+ loci = pd.read_csv(args.bed_fname, sep="\t", header=None)
96
+ loci.rename({0: "chrom", 1: "start", 2: "end"}, axis=1, inplace=True)
97
+
98
+ X = extract_loci(
99
+ loci=loci,
100
+ sequences=args.fa_fname,
101
+ chroms=args.chroms,
102
+ in_window=args.in_window,
103
+ out_window=args.out_window,
104
+ verbose=args.verbose,
105
+ ignore=list("QWERYUIOPSDFHJKLZXVBNM"),
106
+ )
107
+
108
+ log_predictions = [
109
+ predict(
110
+ model,
111
+ X,
112
+ batch_size=args.batch_size,
113
+ verbose=args.verbose,
114
+ device=device,
115
+ )
116
+ for model in load_ensemble(
117
+ model_paths, lambda f: load_torch_model(f, lambda: _build_pausenet(args))
118
+ )
119
+ ]
120
+
121
+ # Average log-scale predictions across replicates before exponentiating
122
+ prediction = (
123
+ torch.exp(torch.stack(log_predictions).mean(dim=0) - 1).cpu().numpy()
124
+ )
125
+
126
+ # Save predictions
127
+ np.savez_compressed(args.out_fname, prediction)
128
+
129
+ # Calculate performance metrics if score column is present in bed file
130
+ if loci.shape[1] >= 5:
131
+ if args.chroms is not None:
132
+ loci = loci[loci["chrom"].isin(args.chroms)]
133
+ p = np.log1p(prediction.squeeze())
134
+ signals = np.log1p(loci.iloc[:, 4].to_numpy())
135
+ pearson = pearsonr(p, signals)
136
+ spearman = spearmanr(p, signals)
137
+
138
+ print(f"Pearson: {pearson[0]}, p-value: {pearson[1]}")
139
+ print(f"Spearman: {spearman[0]}, p-value: {spearman[1]}")
140
+
141
+ np.savez_compressed(
142
+ args.out_fname.replace(".npz", "_metrics.npz"),
143
+ pearson=pearson,
144
+ spearman=spearman,
145
+ )
146
+
147
+ elif args.cmd == "attribute":
148
+ # Disable TF32
149
+ torch.backends.cuda.matmul.allow_tf32 = False
150
+ torch.backends.cudnn.allow_tf32 = False
151
+
152
+ # Load data
153
+ X = extract_loci(
154
+ loci=args.bed_fname,
155
+ sequences=args.fa_fname,
156
+ chroms=args.chroms,
157
+ in_window=args.in_window,
158
+ out_window=args.out_window,
159
+ verbose=args.verbose,
160
+ ignore=list("QWERYUIOPSDFHJKLZXVBNM"),
161
+ ).to(torch.float)
162
+ if args.save_ohe is not None:
163
+ np.savez_compressed(args.save_ohe, X.to(int).numpy())
164
+
165
+ attributions = [
166
+ deep_lift_shap(
167
+ model,
168
+ X,
169
+ hypothetical=args.hypothetical,
170
+ batch_size=args.batch_size,
171
+ n_shuffles=args.n_shuffles,
172
+ random_state=args.random_state,
173
+ verbose=args.verbose,
174
+ device=device,
175
+ ).numpy()
176
+ for model in load_ensemble(
177
+ model_paths, lambda f: load_torch_model(f, lambda: _build_pausenet(args))
178
+ )
179
+ ]
180
+
181
+ # Save
182
+ np.savez_compressed(args.out_fname, np.stack(attributions).mean(axis=0))
183
+
184
+ else:
185
+ raise ValueError(_help)
186
+
187
+
188
+ if __name__ == "__main__":
189
+ cli()
cli/tf.py ADDED
@@ -0,0 +1,345 @@
1
+ #!/usr/bin/env python
2
+ # CLIPNET_TF CLI
3
+ # Author: Adam He <adamyhe@gmail.com>
4
+
5
+ """
6
+ Wrapper script to calculate attributions and predictions for CLIPNET TensorFlow models
7
+ """
8
+
9
+ import random
10
+ from argparse import ArgumentParser
11
+
12
+ import numpy as np
13
+ import pandas as pd
14
+ import torch
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_tensorflow import CLIPNET_TF, TwoHotToOneHot
24
+
25
+ from ._common import (
26
+ add_attribute_args,
27
+ build_parent_parser,
28
+ load_ensemble,
29
+ resolve_device,
30
+ resolve_model_paths,
31
+ set_cpu_threads,
32
+ )
33
+
34
+ _help = """
35
+ The following commands are available:
36
+ predict Calculate predictions for a CLIPNET model
37
+ predict_tss Calculate TSS predictions (uses aggressive jittering).
38
+ attribute Calculate DeepLIFT/SHAP attributions for a CLIPNET model
39
+ Planned but not implemented commands:
40
+ vep Calculate variant effect prediction using a CLIPNET model
41
+ """
42
+
43
+
44
+ def cli():
45
+ parser_parent = build_parent_parser()
46
+ parser_parent.add_argument(
47
+ "--counts_head_only",
48
+ action="store_true",
49
+ help="Use this flag to load a model with only the counts head. This is mostly "
50
+ "used for 'PauseNet' models, which trim the profile head and fine-tune the just"
51
+ "the counts head.",
52
+ )
53
+
54
+ parser = ArgumentParser(description=__doc__)
55
+ subparsers = parser.add_subparsers(
56
+ help="The following commands are available:", required=True, dest="cmd"
57
+ )
58
+
59
+ # PREDICT PARAMS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
60
+
61
+ parser_predict = subparsers.add_parser(
62
+ "predict",
63
+ help="Calculate predictions for a given set of regions.",
64
+ parents=[parser_parent],
65
+ )
66
+ parser_predict.add_argument(
67
+ "-s",
68
+ "--signal_fname",
69
+ type=str,
70
+ nargs=2,
71
+ default=None,
72
+ help="Signal files containing experimental data to benchmark model "
73
+ "predictions against. Expected order is [plus_bigWig, minus_bigWig]. "
74
+ "If not provided, will not calculate performance metrics.",
75
+ )
76
+
77
+ # PREDICT_TSS PARAMS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
78
+
79
+ parser_predict_tss = subparsers.add_parser(
80
+ "predict_tss",
81
+ help="Calculate TSS predictions for a given set of jittered regions.",
82
+ parents=[parser_parent],
83
+ )
84
+ parser_predict_tss.add_argument(
85
+ "-s",
86
+ "--signal_fname",
87
+ type=str,
88
+ nargs=2,
89
+ default=None,
90
+ help="Signal files containing experimental data to benchmark model "
91
+ "predictions against. Expected order is [plus_bigWig, minus_bigWig]. "
92
+ "If not provided, will not calculate performance metrics.",
93
+ )
94
+ parser_predict_tss.add_argument(
95
+ "-j",
96
+ "--max_jitter",
97
+ type=int,
98
+ default=250,
99
+ help="Maximum number of bp to jitter. Default is 500.",
100
+ )
101
+
102
+ # ATTRIBUTE PARAMS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
103
+
104
+ parser_attribute = subparsers.add_parser(
105
+ "attribute",
106
+ help="Calculate attributions for a given set of regions.",
107
+ parents=[parser_parent],
108
+ )
109
+ add_attribute_args(parser_attribute)
110
+ args = parser.parse_args()
111
+
112
+ # MAIN CODE ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
113
+
114
+ model_paths = resolve_model_paths(args.model_fname, pattern="fold_{i}.h5")
115
+ set_cpu_threads()
116
+ device = resolve_device()
117
+
118
+ def _load_tf_model(f):
119
+ return TwoHotToOneHot(
120
+ CLIPNET_TF.from_tf(f, counts_head_only=args.counts_head_only)
121
+ )
122
+
123
+ if args.cmd == "predict":
124
+ # Load data
125
+ data = extract_loci(
126
+ loci=args.bed_fname,
127
+ sequences=args.fa_fname,
128
+ signals=args.signal_fname,
129
+ chroms=args.chroms,
130
+ in_window=1000,
131
+ out_window=500,
132
+ verbose=args.verbose,
133
+ ignore=list("QWERYUIOPSDFHJKLZXVBNM"),
134
+ )
135
+ if args.signal_fname is not None:
136
+ X, signals = data
137
+ else:
138
+ X = data
139
+
140
+ counts = []
141
+ profiles = []
142
+ for model in load_ensemble(model_paths, _load_tf_model):
143
+ pred = predict(
144
+ model, X, batch_size=args.batch_size, verbose=args.verbose, device=device
145
+ )
146
+ if args.counts_head_only:
147
+ counts.append(pred)
148
+ else:
149
+ profiles.append(pred[0])
150
+ counts.append(pred[1])
151
+
152
+ # Average predictions
153
+ count = torch.mean(torch.stack(counts), dim=0)
154
+ if args.counts_head_only:
155
+ # Save predictions
156
+ np.savez_compressed(args.out_fname, count.numpy())
157
+ else:
158
+ profile = torch.mean(torch.stack(profiles), dim=0)
159
+ # Rescale predictions
160
+ track = count * profile / (profile.sum(dim=-1, keepdim=True) + 1e-3)
161
+ # Save predictions
162
+ if args.signal_fname is not None:
163
+ signals_flattened = torch.cat(
164
+ [signals[:, 0, :], torch.abs(signals[:, 1, :])], dim=-1
165
+ )
166
+ np.savez_compressed(
167
+ args.out_fname, pred=track.numpy(), obs=signals_flattened.numpy()
168
+ )
169
+ else:
170
+ np.savez_compressed(args.out_fname, track.numpy())
171
+
172
+ # Calculate metrics
173
+ if args.signal_fname is not None:
174
+ pred_log_counts = torch.log10(track.sum(dim=-1) + 1e-3)
175
+
176
+ profile_pearson = pearson_corr(track, signals_flattened)
177
+ profile_jsd = jensenshannon(
178
+ track.numpy(), signals_flattened.numpy(), axis=1
179
+ )
180
+ counts_pearson = pearson_corr(
181
+ pred_log_counts, torch.log10(signals_flattened.sum(dim=-1) + 1e-3)
182
+ )
183
+ counts_linear_pearson = pearson_corr(
184
+ track.sum(dim=-1), signals_flattened.sum(dim=-1)
185
+ )
186
+ counts_spearman = spearman_corr(
187
+ pred_log_counts, torch.log10(signals_flattened.sum(dim=-1) + 1e-3)
188
+ )
189
+ lm = LinearRegression(fit_intercept=True).fit(
190
+ torch.log10(signals_flattened.sum(dim=-1).reshape(-1, 1) + 1e-3),
191
+ pred_log_counts.reshape(-1, 1),
192
+ )
193
+
194
+ print(
195
+ f"Mean profile Pearson: {np.nanmean(profile_pearson)} "
196
+ f"+/- {np.nanstd(profile_pearson, ddof=1)}"
197
+ )
198
+ print(f"Median profile Pearson: {np.nanmedian(profile_pearson)}")
199
+ print(f"Mean profile JSD: {np.nanmean(profile_jsd)}")
200
+ print(f"Median profile JSD: {np.nanmedian(profile_jsd)}")
201
+ print(f"Count Pearson: {counts_pearson}")
202
+ print(f"Count linear Pearson: {counts_linear_pearson}")
203
+ print(f"Count Spearman: {counts_spearman}")
204
+ print(f"Count slope: {lm.coef_[0]}")
205
+ print(f"Count intercept: {lm.intercept_}")
206
+
207
+ np.savez_compressed(
208
+ args.out_fname.replace(".npz", "_metrics.npz"),
209
+ profile_pearson=profile_pearson,
210
+ profile_jsd=profile_jsd,
211
+ counts_pearson=counts_pearson,
212
+ counts_spearman=counts_spearman,
213
+ )
214
+
215
+ elif args.counts_head_only:
216
+ bed = pd.read_csv(args.bed_fname, sep="\t", header=None)
217
+ bed_test = bed[bed.iloc[:, 0].isin(args.chroms)]
218
+ expt = torch.from_numpy(bed_test.iloc[:, 4].to_numpy())
219
+ pred = count.squeeze()
220
+
221
+ counts_pearson = pearson_corr(torch.log1p(pred), torch.log1p(expt))
222
+ counts_spearman = spearman_corr(torch.log1p(pred), torch.log1p(expt))
223
+ lm = LinearRegression(fit_intercept=True).fit(
224
+ torch.log1p(expt).reshape(-1, 1), torch.log1p(pred).reshape(-1, 1)
225
+ )
226
+
227
+ print(f"Pearson: {counts_pearson.item()}")
228
+ print(f"Spearman: {counts_spearman.item()}")
229
+ print(f"Slope: {lm.coef_[0][0]}")
230
+ print(f"Intercept: {lm.intercept_[0]}")
231
+
232
+ np.savez_compressed(
233
+ args.out_fname.replace(".npz", "_metrics.npz"),
234
+ pearson=counts_pearson,
235
+ spearman=counts_spearman,
236
+ slope=lm.coef_[0][0],
237
+ intercept=lm.intercept_[0],
238
+ expt=expt,
239
+ pred=pred,
240
+ )
241
+
242
+ elif args.cmd == "predict_tss":
243
+ if args.counts_head_only:
244
+ raise TypeError("Counts head only models do not support TSS prediction.")
245
+ # Load data
246
+ loci = extract_loci(
247
+ loci=args.bed_fname,
248
+ sequences=args.fa_fname,
249
+ signals=args.signal_fname,
250
+ chroms=args.chroms,
251
+ in_window=1000,
252
+ out_window=500,
253
+ max_jitter=args.max_jitter,
254
+ verbose=args.verbose,
255
+ )
256
+ if args.signal_fname is not None:
257
+ seqs, signals = loci
258
+ else:
259
+ seqs = loci
260
+ # Jitter
261
+ seqs_jitter = []
262
+ signals_jitter = []
263
+ for i in range(seqs.shape[0]):
264
+ j = random.randint(0, args.max_jitter * 2 - 1)
265
+ seqs_jitter.append(seqs[i, :, j : j + 1000])
266
+ signals_jitter.append(signals[i, :, j : j + 500])
267
+
268
+ X = torch.stack(seqs_jitter)
269
+ signals = torch.abs(torch.stack(signals_jitter))
270
+
271
+ # Calculate predictions
272
+ profiles = [
273
+ predict(
274
+ model, X, batch_size=args.batch_size, verbose=args.verbose, device=device
275
+ )[0]
276
+ for model in load_ensemble(model_paths, _load_tf_model)
277
+ ]
278
+
279
+ # Average predictions
280
+ profile = torch.mean(torch.stack(profiles), dim=0)
281
+ profile = torch.stack([profile[:, :500], profile[:, 500:]], dim=1)
282
+
283
+ # Calculate metrics
284
+ if args.signal_fname is not None:
285
+ pred_tss = torch.argmax(profile, dim=-1).to(torch.float)
286
+ expt_tss = torch.argmax(signals, dim=-1).to(torch.float)
287
+ np.savez_compressed(args.out_fname, pred=pred_tss, expt=expt_tss)
288
+
289
+ print(
290
+ f"+ strand TSS Pearson: {pearson_corr(pred_tss[:, 0], expt_tss[:, 0])}"
291
+ )
292
+ print(
293
+ f"- strand TSS Pearson: {pearson_corr(pred_tss[:, 1], expt_tss[:, 1])}"
294
+ )
295
+
296
+ elif args.cmd == "attribute":
297
+ # Load data
298
+ X = extract_loci(
299
+ loci=args.bed_fname,
300
+ sequences=args.fa_fname,
301
+ chroms=args.chroms,
302
+ in_window=1000,
303
+ verbose=args.verbose,
304
+ ignore=list("QWERYUIOPSDFHJKLZXVBNM"),
305
+ ).to(torch.float)
306
+ # Save OHE
307
+ if args.save_ohe is not None:
308
+ np.savez_compressed(args.save_ohe, X.to(int).numpy())
309
+
310
+ attributions = []
311
+ for model in load_ensemble(model_paths, _load_tf_model):
312
+ additional_nonlinear_ops = None
313
+ # Wrap models depending on args.attribute_type
314
+ if args.counts_head_only:
315
+ pass
316
+ elif args.attribute_type == "counts":
317
+ model = CountWrapper(model)
318
+ elif args.attribute_type == "profile":
319
+ model = ProfileWrapper(model)
320
+ additional_nonlinear_ops = {_ProfileLogitScaling: _nonlinear}
321
+
322
+ # Calculate and log attributions
323
+ attributions.append(
324
+ deep_lift_shap(
325
+ model,
326
+ X,
327
+ hypothetical=args.hypothetical,
328
+ batch_size=args.batch_size,
329
+ n_shuffles=args.n_shuffles,
330
+ random_state=args.random_state,
331
+ verbose=args.verbose,
332
+ additional_nonlinear_ops=additional_nonlinear_ops,
333
+ device=device,
334
+ ).numpy()
335
+ )
336
+
337
+ # Save
338
+ np.savez_compressed(args.out_fname, np.stack(attributions).mean(axis=0))
339
+
340
+ else:
341
+ raise ValueError(_help)
342
+
343
+
344
+ if __name__ == "__main__":
345
+ cli()
@@ -0,0 +1,20 @@
1
+ # __init__.py
2
+ # Author: Adam He <adamyhe@gmail.com>
3
+
4
+ from importlib.metadata import version
5
+
6
+ from .clipnet_pytorch import CLIPNET, PauseNet
7
+ from .clipnet_tensorflow import CLIPNET_TF, TwoHotToOneHot
8
+ from .personal_bpnet import PersonalBPNet
9
+ from .procapnet import ProCapNet
10
+
11
+ __version__ = version("PersonalBPNet")
12
+
13
+ __all__ = [
14
+ "CLIPNET",
15
+ "CLIPNET_TF",
16
+ "PauseNet",
17
+ "PersonalBPNet",
18
+ "ProCapNet",
19
+ "TwoHotToOneHot",
20
+ ]