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 +1 -0
- cli/_common.py +233 -0
- cli/clipnet.py +340 -0
- cli/pausenet.py +189 -0
- cli/tf.py +345 -0
- personal_bpnet/__init__.py +20 -0
- personal_bpnet/clipnet_pytorch.py +294 -0
- personal_bpnet/clipnet_tensorflow.py +357 -0
- personal_bpnet/losses.py +117 -0
- personal_bpnet/personal_bpnet.py +276 -0
- personal_bpnet/procapnet.py +256 -0
- personal_bpnet/procapnet_orig.py +83 -0
- personal_bpnet/utils.py +390 -0
- personalbpnet-0.7.0.dist-info/METADATA +106 -0
- personalbpnet-0.7.0.dist-info/RECORD +19 -0
- personalbpnet-0.7.0.dist-info/WHEEL +5 -0
- personalbpnet-0.7.0.dist-info/entry_points.txt +4 -0
- personalbpnet-0.7.0.dist-info/licenses/LICENSE +21 -0
- personalbpnet-0.7.0.dist-info/top_level.txt +2 -0
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
# procapnet_orig.py
|
|
2
|
+
# Kelly Cochran
|
|
3
|
+
# Copied from the ENCODE accession:
|
|
4
|
+
# https://www.encodeproject.org/files/ENCFF976FHE/@@download/ENCFF976FHE.tar.gz
|
|
5
|
+
# This class is included to make loading ProCapNet models easier and to ensure full
|
|
6
|
+
# reproducibility of Kelly's original code.
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
import torch
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class ProCapNet(torch.nn.Module):
|
|
13
|
+
def __init__(self, n_filters=512, n_layers=8, n_outputs=2):
|
|
14
|
+
super(ProCapNet, self).__init__()
|
|
15
|
+
self.n_filters = n_filters
|
|
16
|
+
self.n_layers = n_layers
|
|
17
|
+
self.n_outputs = n_outputs
|
|
18
|
+
self.trimming = 557
|
|
19
|
+
self.deconv_kernel_size = 75
|
|
20
|
+
|
|
21
|
+
self.iconv = torch.nn.Conv1d(4, n_filters, kernel_size=21, padding=10)
|
|
22
|
+
self.rconvs = torch.nn.ModuleList(
|
|
23
|
+
[
|
|
24
|
+
torch.nn.Conv1d(
|
|
25
|
+
n_filters, n_filters, kernel_size=3, padding=2**i, dilation=2**i
|
|
26
|
+
)
|
|
27
|
+
for i in range(1, self.n_layers + 1)
|
|
28
|
+
]
|
|
29
|
+
)
|
|
30
|
+
self.fconv = torch.nn.Conv1d(
|
|
31
|
+
n_filters, n_outputs, kernel_size=self.deconv_kernel_size
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
self.relus = torch.nn.ModuleList(
|
|
35
|
+
[torch.nn.ReLU() for _ in range(0, self.n_layers + 1)]
|
|
36
|
+
)
|
|
37
|
+
self.linear = torch.nn.Linear(n_filters, 1)
|
|
38
|
+
|
|
39
|
+
def forward(self, X):
|
|
40
|
+
start, end = self.trimming, X.shape[2] - self.trimming
|
|
41
|
+
|
|
42
|
+
X = self.relus[0](self.iconv(X))
|
|
43
|
+
for i in range(self.n_layers):
|
|
44
|
+
X_conv = self.relus[i + 1](self.rconvs[i](X))
|
|
45
|
+
X = torch.add(X, X_conv)
|
|
46
|
+
|
|
47
|
+
X = X[
|
|
48
|
+
:,
|
|
49
|
+
:,
|
|
50
|
+
start - self.deconv_kernel_size // 2 : end + self.deconv_kernel_size // 2,
|
|
51
|
+
]
|
|
52
|
+
|
|
53
|
+
y_profile = self.fconv(X)
|
|
54
|
+
|
|
55
|
+
X = torch.mean(X, axis=2)
|
|
56
|
+
y_counts = self.linear(X).reshape(X.shape[0], 1)
|
|
57
|
+
|
|
58
|
+
return y_profile, y_counts
|
|
59
|
+
|
|
60
|
+
def predict(self, X, batch_size=64, logits=False):
|
|
61
|
+
with torch.no_grad():
|
|
62
|
+
starts = np.arange(0, X.shape[0], batch_size)
|
|
63
|
+
ends = starts + batch_size
|
|
64
|
+
|
|
65
|
+
y_profiles, y_counts = [], []
|
|
66
|
+
for start, end in zip(starts, ends):
|
|
67
|
+
X_batch = X[start:end]
|
|
68
|
+
|
|
69
|
+
y_profiles_, y_counts_ = self(X_batch)
|
|
70
|
+
if not logits: # apply softmax
|
|
71
|
+
y_profiles_ = self.log_softmax(y_profiles_)
|
|
72
|
+
y_profiles.append(y_profiles_.cpu().detach().numpy())
|
|
73
|
+
y_counts.append(y_counts_.cpu().detach().numpy())
|
|
74
|
+
|
|
75
|
+
y_profiles = np.concatenate(y_profiles)
|
|
76
|
+
y_counts = np.concatenate(y_counts)
|
|
77
|
+
return y_profiles, y_counts
|
|
78
|
+
|
|
79
|
+
def log_softmax(self, y_profile):
|
|
80
|
+
y_profile = y_profile.reshape(y_profile.shape[0], -1)
|
|
81
|
+
y_profile = torch.nn.LogSoftmax(dim=-1)(y_profile)
|
|
82
|
+
y_profile = y_profile.reshape(y_profile.shape[0], self.n_outputs, -1)
|
|
83
|
+
return y_profile
|
personal_bpnet/utils.py
ADDED
|
@@ -0,0 +1,390 @@
|
|
|
1
|
+
# utils.py
|
|
2
|
+
# Author: Adam He <adamyhe@gmail.com>
|
|
3
|
+
|
|
4
|
+
"""
|
|
5
|
+
A bunch of utility functions for working with personal genome sequences.
|
|
6
|
+
Notably includes a data loader for loading chunked data to train CLIPNET.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import random
|
|
10
|
+
|
|
11
|
+
import matplotlib.pyplot as plt
|
|
12
|
+
import numba
|
|
13
|
+
import numpy as np
|
|
14
|
+
import pyfaidx
|
|
15
|
+
import torch
|
|
16
|
+
import tqdm
|
|
17
|
+
from torch.utils.data import DataLoader, Dataset, Sampler
|
|
18
|
+
|
|
19
|
+
# IUPAC ambiguity codes for heterozygotes, in (A, C, G, T) channel order. Values
|
|
20
|
+
# are pre-halved so `twohot_encode` needs no division at call time.
|
|
21
|
+
_TWOHOT_CODES = {
|
|
22
|
+
"A": (1.0, 0, 0, 0),
|
|
23
|
+
"C": (0, 1.0, 0, 0),
|
|
24
|
+
"G": (0, 0, 1.0, 0),
|
|
25
|
+
"T": (0, 0, 0, 1.0),
|
|
26
|
+
"N": (0, 0, 0, 0),
|
|
27
|
+
"M": (0.5, 0.5, 0, 0),
|
|
28
|
+
"R": (0.5, 0, 0.5, 0),
|
|
29
|
+
"W": (0.5, 0, 0, 0.5),
|
|
30
|
+
"S": (0, 0.5, 0.5, 0),
|
|
31
|
+
"Y": (0, 0.5, 0, 0.5),
|
|
32
|
+
"K": (0, 0, 0.5, 0.5),
|
|
33
|
+
}
|
|
34
|
+
# Byte-indexed lookup table (0-255) so encoding is a gather from a small table
|
|
35
|
+
# instead of per-character dict lookups; unrecognized bytes (e.g. "-" gaps or the
|
|
36
|
+
# rest of the IUPAC alphabet) fall back to the all-zero row, same as "N".
|
|
37
|
+
_TWOHOT_LOOKUP = np.zeros((256, 4), dtype=np.float64)
|
|
38
|
+
for _base, _code in _TWOHOT_CODES.items():
|
|
39
|
+
_TWOHOT_LOOKUP[ord(_base)] = _code
|
|
40
|
+
_TWOHOT_LOOKUP[ord(_base.lower())] = _code
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@numba.njit(cache=True)
|
|
44
|
+
def _twohot_gather(codes, lookup, out):
|
|
45
|
+
"""Gathers `lookup[codes[n, i]]` into `out[n, :, i]`.
|
|
46
|
+
|
|
47
|
+
`codes` is (n_seqs, seq_len) ASCII byte codes and `out` is the
|
|
48
|
+
(n_seqs, 4, seq_len) output buffer to fill in place. A compiled loop beats
|
|
49
|
+
`lookup[codes]`-style numpy fancy-indexing here (~5x faster), and lets a
|
|
50
|
+
single call encode an entire batch of equal-length sequences at once
|
|
51
|
+
instead of looping in Python over one sequence at a time.
|
|
52
|
+
"""
|
|
53
|
+
for n in range(codes.shape[0]):
|
|
54
|
+
for i in range(codes.shape[1]):
|
|
55
|
+
for j in range(4):
|
|
56
|
+
out[n, j, i] = lookup[codes[n, i], j]
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def twohot_encode(seq):
|
|
60
|
+
"""
|
|
61
|
+
Calculates a two-hot encoding of a given DNA sequence. Handles IUPAC ambiguity
|
|
62
|
+
codes for heterozygotes. IMPORTANT: Note that this script halves the encoding
|
|
63
|
+
for compatibility with models/methods that require one-hot encoded sequences.
|
|
64
|
+
Heterozygous positions are represented as 0.5 pairs. This differs from the
|
|
65
|
+
original implementation used in CLIPNET tensorflow, which has double values.
|
|
66
|
+
"""
|
|
67
|
+
codes = np.frombuffer(seq.encode("ascii"), dtype=np.uint8).reshape(1, -1)
|
|
68
|
+
out = np.empty((1, 4, codes.shape[1]), dtype=_TWOHOT_LOOKUP.dtype)
|
|
69
|
+
_twohot_gather(codes, _TWOHOT_LOOKUP, out)
|
|
70
|
+
return out[0]
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def reverse_complement_twohot(seq_twohot):
|
|
74
|
+
"""
|
|
75
|
+
Computes reverse-complement twohot. Handles heterozygotes encoded via IUPAC
|
|
76
|
+
ambiguity codes.
|
|
77
|
+
|
|
78
|
+
seqs_twohot should be (4, n) where n is the length of the sequence.
|
|
79
|
+
"""
|
|
80
|
+
# Reversing the channel axis (order A, C, G, T) swaps A<->T and C<->G, i.e.
|
|
81
|
+
# complementation; reversing the position axis reverses the strand direction.
|
|
82
|
+
# This also correctly self-complements the A/T and C/G heterozygote codes
|
|
83
|
+
# (their two channels are symmetric around the reversal), so no special-casing
|
|
84
|
+
# is needed. `.copy()` avoids returning a view aliased to the input, which
|
|
85
|
+
# would let an in-place assignment on the result silently mutate the input.
|
|
86
|
+
return seq_twohot[::-1, ::-1].copy()
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def get_twohot_fasta_sequences(fasta_fp):
|
|
90
|
+
"""
|
|
91
|
+
Given a fasta file where every record is the same length, returns a
|
|
92
|
+
twohot-encoded array of shape (n, 4, len) of all sequences.
|
|
93
|
+
|
|
94
|
+
All records are encoded in a single batched call to `_twohot_gather` rather
|
|
95
|
+
than looping over sequences one at a time. Note: this function used to
|
|
96
|
+
optionally parallelize per-sequence encoding across processes, back when
|
|
97
|
+
each call to `twohot_encode` did a Python-level per-character loop. Now that
|
|
98
|
+
encoding is a single compiled gather, a single sequence encodes in a few
|
|
99
|
+
microseconds — well below the per-task IPC/pickling overhead of a process
|
|
100
|
+
pool, and batching removes the per-sequence Python overhead entirely, so
|
|
101
|
+
multiprocessing (measured to be over an order of magnitude *slower* here)
|
|
102
|
+
was removed rather than reimplemented.
|
|
103
|
+
"""
|
|
104
|
+
fa = pyfaidx.Fasta(fasta_fp)
|
|
105
|
+
seqs = [str(rec) for rec in fa]
|
|
106
|
+
lengths = {len(seq) for seq in seqs}
|
|
107
|
+
if len(lengths) != 1:
|
|
108
|
+
raise ValueError(
|
|
109
|
+
"All sequences must be the same length to be stacked into one "
|
|
110
|
+
f"array; found lengths {sorted(lengths)}."
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
length = lengths.pop()
|
|
114
|
+
codes = np.frombuffer("".join(seqs).encode("ascii"), dtype=np.uint8).reshape(
|
|
115
|
+
len(seqs), length
|
|
116
|
+
)
|
|
117
|
+
out = np.empty((len(seqs), 4, length), dtype=_TWOHOT_LOOKUP.dtype)
|
|
118
|
+
_twohot_gather(codes, _TWOHOT_LOOKUP, out)
|
|
119
|
+
return out
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
class ChunkedDataset(Dataset):
|
|
123
|
+
def __init__(
|
|
124
|
+
self,
|
|
125
|
+
seq_chunks,
|
|
126
|
+
signal_chunks,
|
|
127
|
+
in_window=2114,
|
|
128
|
+
out_window=1000,
|
|
129
|
+
reverse_complement=True,
|
|
130
|
+
jitter=True,
|
|
131
|
+
):
|
|
132
|
+
self.seq_chunks = seq_chunks
|
|
133
|
+
self.signal_chunks = signal_chunks
|
|
134
|
+
if len(self.seq_chunks) != len(self.signal_chunks):
|
|
135
|
+
raise ValueError(
|
|
136
|
+
"len(seq_chunks) != len(signal_chunks) (%d, %d)"
|
|
137
|
+
% (len(self.seq_chunks), len(self.signal_chunks))
|
|
138
|
+
)
|
|
139
|
+
self.in_window = in_window
|
|
140
|
+
self.out_window = out_window
|
|
141
|
+
self.jitter = jitter
|
|
142
|
+
self.reverse_complement = reverse_complement
|
|
143
|
+
self.chunk_indices = list(range(len(self.seq_chunks)))
|
|
144
|
+
self.chunk_lengths = [
|
|
145
|
+
# len(pyfaidx.Fasta(...)) counts total bases, not records; use the
|
|
146
|
+
# number of keys in the index for the number of sequences instead.
|
|
147
|
+
len(pyfaidx.Fasta(chunk).keys())
|
|
148
|
+
for chunk in tqdm.tqdm(seq_chunks, desc="Calculating dataset length")
|
|
149
|
+
]
|
|
150
|
+
self.chunk_data_indices = None
|
|
151
|
+
self.current_chunk_data = None
|
|
152
|
+
self.current_chunk_signals = None
|
|
153
|
+
self.current_chunk_index = -1
|
|
154
|
+
|
|
155
|
+
def __len__(self):
|
|
156
|
+
return sum(self.chunk_lengths)
|
|
157
|
+
|
|
158
|
+
def __getitem__(self, idx):
|
|
159
|
+
# Load the chunk if it is not already loaded
|
|
160
|
+
chunk_idx, data_idx = self.chunk_data_indices[idx]
|
|
161
|
+
if chunk_idx != self.current_chunk_index:
|
|
162
|
+
self.current_chunk_seq, self.current_chunk_signal = self._load_chunk(
|
|
163
|
+
chunk_idx
|
|
164
|
+
)
|
|
165
|
+
self.current_chunk_index = chunk_idx
|
|
166
|
+
# Get the data. We do the twohot encoding here to save memory.
|
|
167
|
+
X = twohot_encode(self.current_chunk_seq[data_idx])
|
|
168
|
+
y = self.current_chunk_signal[data_idx, :, :]
|
|
169
|
+
|
|
170
|
+
# If self.jitter == True, randomly select a region of length self.in/out_window
|
|
171
|
+
# else, take the middle subsequence of length self.in/out_window
|
|
172
|
+
pad = (X.shape[-1] - self.in_window) // 2
|
|
173
|
+
j = random.randint(0, pad * 2) if self.jitter else pad
|
|
174
|
+
X = X[:, j : j + self.in_window]
|
|
175
|
+
y = y[:, j : j + self.out_window]
|
|
176
|
+
|
|
177
|
+
# If self.reverse_complement == True, randomly reverse complement the sequence
|
|
178
|
+
if self.reverse_complement and random.random() > 0.5:
|
|
179
|
+
X = reverse_complement_twohot(X)
|
|
180
|
+
y = y[::-1, ::-1]
|
|
181
|
+
|
|
182
|
+
# Convert to tensors
|
|
183
|
+
X_torch = torch.from_numpy(X.copy()).to(torch.float)
|
|
184
|
+
y_torch = torch.from_numpy(y.copy()).to(torch.float)
|
|
185
|
+
return X_torch, y_torch
|
|
186
|
+
|
|
187
|
+
def _load_chunk(self, idx):
|
|
188
|
+
seq_file = self.seq_chunks[idx]
|
|
189
|
+
signal_file = self.signal_chunks[idx]
|
|
190
|
+
seqs = [str(rec) for rec in pyfaidx.Fasta(seq_file)]
|
|
191
|
+
signals = np.load(signal_file)["arr_0"]
|
|
192
|
+
return seqs, signals
|
|
193
|
+
|
|
194
|
+
def set_chunk_data_indices(self, chunk_data_indices):
|
|
195
|
+
self.chunk_data_indices = chunk_data_indices
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
class ChunkSampler(Sampler):
|
|
199
|
+
def __init__(self, dataset, batch_size=32):
|
|
200
|
+
self.dataset = dataset
|
|
201
|
+
|
|
202
|
+
def __iter__(self):
|
|
203
|
+
# shuffle chunk order
|
|
204
|
+
random.shuffle(self.dataset.chunk_indices)
|
|
205
|
+
|
|
206
|
+
# shuffle data order within chunks
|
|
207
|
+
chunk_data_indices = []
|
|
208
|
+
for chunk_idx in self.dataset.chunk_indices:
|
|
209
|
+
chunk_length = self.dataset.chunk_lengths[chunk_idx]
|
|
210
|
+
shuffled_indices = list(range(chunk_length))
|
|
211
|
+
random.shuffle(shuffled_indices)
|
|
212
|
+
chunk_data_indices.extend([(chunk_idx, i) for i in shuffled_indices])
|
|
213
|
+
|
|
214
|
+
self.dataset.set_chunk_data_indices(chunk_data_indices)
|
|
215
|
+
return iter(range(len(self.dataset)))
|
|
216
|
+
|
|
217
|
+
def __len__(self):
|
|
218
|
+
return len(self.dataset)
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
class ChunkedDataLoader(DataLoader):
|
|
222
|
+
def __init__(
|
|
223
|
+
self,
|
|
224
|
+
dataset,
|
|
225
|
+
batch_size=64,
|
|
226
|
+
batch_sampler=None,
|
|
227
|
+
# num_workers=0,
|
|
228
|
+
collate_fn=None,
|
|
229
|
+
pin_memory=False,
|
|
230
|
+
drop_last=False,
|
|
231
|
+
timeout=0,
|
|
232
|
+
worker_init_fn=None,
|
|
233
|
+
# multiprocessing_context=None,
|
|
234
|
+
generator=None,
|
|
235
|
+
# prefetch_factor=None,
|
|
236
|
+
persistent_workers=False,
|
|
237
|
+
):
|
|
238
|
+
sampler = ChunkSampler(dataset, batch_size=batch_size)
|
|
239
|
+
super().__init__(
|
|
240
|
+
dataset,
|
|
241
|
+
batch_size=batch_size,
|
|
242
|
+
sampler=sampler,
|
|
243
|
+
batch_sampler=batch_sampler,
|
|
244
|
+
# num_workers=num_workers,
|
|
245
|
+
collate_fn=collate_fn,
|
|
246
|
+
pin_memory=pin_memory,
|
|
247
|
+
drop_last=drop_last,
|
|
248
|
+
timeout=timeout,
|
|
249
|
+
worker_init_fn=worker_init_fn,
|
|
250
|
+
# multiprocessing_context=multiprocessing_context,
|
|
251
|
+
generator=generator,
|
|
252
|
+
# prefetch_factor=prefetch_factor,
|
|
253
|
+
persistent_workers=persistent_workers,
|
|
254
|
+
)
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
class ScalarLoader(torch.utils.data.Dataset):
|
|
258
|
+
"""A data generator for sequence networks w/ single scalar outputs.
|
|
259
|
+
|
|
260
|
+
This generator takes in an extracted set of sequences and output signal
|
|
261
|
+
(single scalar/sequence) and will return a single element with random
|
|
262
|
+
jitter and reverse-complement augmentation applied. Note that unlike with
|
|
263
|
+
BPNet's data generator, the output is not jittered/rev comped. Jitter is
|
|
264
|
+
implemented efficiently by taking in data that is wider than the in windows
|
|
265
|
+
by two times the maximum jitter and windows are extracted from that.
|
|
266
|
+
Essentially, if an input window is 1000 and the maximum jitter is 128, one
|
|
267
|
+
would pass in data with a length of 1256 and a length 1000 window would be
|
|
268
|
+
extracted starting between position 0 and 256. This generator must be
|
|
269
|
+
wrapped by a PyTorch generator object.
|
|
270
|
+
|
|
271
|
+
Parameters
|
|
272
|
+
----------
|
|
273
|
+
sequences: torch.tensor, shape=(n, 4, in_window+2*max_jitter)
|
|
274
|
+
A one-hot encoded tensor of `n` example sequences, each of input
|
|
275
|
+
length `in_window`. See description above for connection with jitter.
|
|
276
|
+
|
|
277
|
+
signals: torch.tensor, shape=(n,)
|
|
278
|
+
The signals to predict. A single scalar per sequence.
|
|
279
|
+
|
|
280
|
+
in_window: int, optional
|
|
281
|
+
The input window size. Default is 2114.
|
|
282
|
+
|
|
283
|
+
max_jitter: int, optional
|
|
284
|
+
The maximum amount of jitter to add, in either direction, to the
|
|
285
|
+
midpoints that are passed in. Default is 0.
|
|
286
|
+
|
|
287
|
+
reverse_complement: bool, optional
|
|
288
|
+
Whether to reverse complement-augment half of the data. Default is False.
|
|
289
|
+
|
|
290
|
+
random_state: int or None, optional
|
|
291
|
+
Whether to use a deterministic seed or not.
|
|
292
|
+
"""
|
|
293
|
+
|
|
294
|
+
def __init__(
|
|
295
|
+
self,
|
|
296
|
+
sequences,
|
|
297
|
+
signals,
|
|
298
|
+
in_window=2114,
|
|
299
|
+
max_jitter=0,
|
|
300
|
+
reverse_complement=False,
|
|
301
|
+
random_state=None,
|
|
302
|
+
):
|
|
303
|
+
self.in_window = in_window
|
|
304
|
+
self.max_jitter = max_jitter
|
|
305
|
+
|
|
306
|
+
self.reverse_complement = reverse_complement
|
|
307
|
+
self.random_state = np.random.RandomState(random_state)
|
|
308
|
+
|
|
309
|
+
self.signals = signals
|
|
310
|
+
self.sequences = sequences
|
|
311
|
+
if signals.shape[0] != sequences.shape[0]:
|
|
312
|
+
raise ValueError(
|
|
313
|
+
f"({sequences.shape[0]}) sequences and ({signals.shape[0]}) signals"
|
|
314
|
+
)
|
|
315
|
+
|
|
316
|
+
def __len__(self):
|
|
317
|
+
return len(self.sequences)
|
|
318
|
+
|
|
319
|
+
def __getitem__(self, idx):
|
|
320
|
+
i = self.random_state.choice(len(self.sequences))
|
|
321
|
+
j = (
|
|
322
|
+
(self.sequences.shape[-1] - self.in_window) // 2
|
|
323
|
+
if self.max_jitter == 0
|
|
324
|
+
else self.random_state.randint(self.max_jitter * 2)
|
|
325
|
+
)
|
|
326
|
+
|
|
327
|
+
X = self.sequences[i, :, j : j + self.in_window]
|
|
328
|
+
y = self.signals[i]
|
|
329
|
+
|
|
330
|
+
if self.reverse_complement and self.random_state.choice(2) == 1:
|
|
331
|
+
X = torch.stack([reverse_complement_twohot(x.numpy().copy()) for x in X])
|
|
332
|
+
|
|
333
|
+
return X, y
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
class WarmupScheduler:
|
|
337
|
+
def __init__(self, optimizer, warmup_steps=10, initial_lr=0.0001, target_lr=0.0005):
|
|
338
|
+
self.optimizer = optimizer
|
|
339
|
+
self.warmup_steps = warmup_steps
|
|
340
|
+
self.initial_lr = initial_lr
|
|
341
|
+
self.current_lr = initial_lr
|
|
342
|
+
self.target_lr = target_lr
|
|
343
|
+
self.current_steps = 0
|
|
344
|
+
|
|
345
|
+
def zero_grad(self):
|
|
346
|
+
self.optimizer.zero_grad()
|
|
347
|
+
|
|
348
|
+
def state_dict(self):
|
|
349
|
+
return self.optimizer.state_dict()
|
|
350
|
+
|
|
351
|
+
def step(self):
|
|
352
|
+
self.current_steps += 1
|
|
353
|
+
if self.current_steps <= self.warmup_steps:
|
|
354
|
+
lr = self.initial_lr + (self.target_lr - self.initial_lr) * (
|
|
355
|
+
self.current_steps / self.warmup_steps
|
|
356
|
+
)
|
|
357
|
+
self.current_lr = lr
|
|
358
|
+
for param_group in self.optimizer.param_groups:
|
|
359
|
+
param_group["lr"] = lr
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
def plot_side(arr, ylim=[-2, 2.5], yticks=[0, 2], xticks=[], pic_name=None):
|
|
363
|
+
"""
|
|
364
|
+
Adapted from APARENT code (Bogard et al. 2019)
|
|
365
|
+
"""
|
|
366
|
+
if arr.shape[0] % 2 != 0:
|
|
367
|
+
raise ValueError("arr must have even length.")
|
|
368
|
+
midpoint = int(arr.shape[0] / 2)
|
|
369
|
+
pl = arr[:midpoint]
|
|
370
|
+
mn = arr[midpoint:]
|
|
371
|
+
plt.bar(
|
|
372
|
+
range(pl.shape[0]),
|
|
373
|
+
pl,
|
|
374
|
+
width=-2,
|
|
375
|
+
color="r",
|
|
376
|
+
)
|
|
377
|
+
plt.bar(range(mn.shape[0]), -mn, width=-2, color="b")
|
|
378
|
+
axes = plt.gca()
|
|
379
|
+
axes.set_ylim(ylim)
|
|
380
|
+
axes.set_yticks(yticks)
|
|
381
|
+
axes.set_xticks(xticks)
|
|
382
|
+
axes.spines[["right", "top", "bottom"]].set_visible(False)
|
|
383
|
+
plt.xlim(-0.5, pl.shape[0] - 0.5)
|
|
384
|
+
axes.tick_params(labelleft=False)
|
|
385
|
+
|
|
386
|
+
if pic_name is None:
|
|
387
|
+
plt.show()
|
|
388
|
+
else:
|
|
389
|
+
plt.savefig(pic_name, transparent=True)
|
|
390
|
+
plt.close()
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: PersonalBPNet
|
|
3
|
+
Version: 0.7.0
|
|
4
|
+
Summary: PyTorch BPNet-family models (CLIPNET, ProCapNet, PauseNet) for base-resolution genomic signal prediction, extending bpnetlite.
|
|
5
|
+
Author-email: Adam He <adamyhe@gmail.com>
|
|
6
|
+
License: MIT License
|
|
7
|
+
|
|
8
|
+
Copyright (c) 2024 Adam Youlin He
|
|
9
|
+
|
|
10
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
11
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
12
|
+
in the Software without restriction, including without limitation the rights
|
|
13
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
14
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
15
|
+
furnished to do so, subject to the following conditions:
|
|
16
|
+
|
|
17
|
+
The above copyright notice and this permission notice shall be included in all
|
|
18
|
+
copies or substantial portions of the Software.
|
|
19
|
+
|
|
20
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
21
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
22
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
23
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
24
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
25
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
26
|
+
SOFTWARE.
|
|
27
|
+
|
|
28
|
+
Project-URL: Homepage, https://github.com/adamyhe/PersonalBPNet
|
|
29
|
+
Project-URL: Repository, https://github.com/adamyhe/PersonalBPNet
|
|
30
|
+
Project-URL: Issues, https://github.com/adamyhe/PersonalBPNet/issues
|
|
31
|
+
Project-URL: Changelog, https://github.com/adamyhe/PersonalBPNet/blob/main/CHANGELOG.md
|
|
32
|
+
Project-URL: Documentation, https://github.com/adamyhe/PersonalBPNet/tree/main/docs
|
|
33
|
+
Keywords: genomics,deep-learning,pytorch,bpnet,clipnet,pro-cap,regulatory-genomics
|
|
34
|
+
Classifier: Development Status :: 3 - Alpha
|
|
35
|
+
Classifier: Intended Audience :: Science/Research
|
|
36
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
37
|
+
Classifier: Programming Language :: Python :: 3
|
|
38
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
39
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
40
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
41
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
42
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
43
|
+
Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
|
|
44
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
45
|
+
Requires-Python: >=3.9
|
|
46
|
+
Description-Content-Type: text/markdown
|
|
47
|
+
License-File: LICENSE
|
|
48
|
+
Requires-Dist: bpnet-lite>=1.0.0
|
|
49
|
+
Requires-Dist: tangermeme>=1.0.0
|
|
50
|
+
Requires-Dist: pyfaidx
|
|
51
|
+
Requires-Dist: numba
|
|
52
|
+
Provides-Extra: tf
|
|
53
|
+
Requires-Dist: h5py; extra == "tf"
|
|
54
|
+
Dynamic: license-file
|
|
55
|
+
|
|
56
|
+
# PersonalBPNet
|
|
57
|
+
|
|
58
|
+
A PyTorch library of [BPNet](https://github.com/jmschrei/bpnet-lite)-family models for predicting base-resolution genomic signal (e.g., PRO-cap read coverage) from DNA sequence, plus CLI tools for prediction and attribution.
|
|
59
|
+
|
|
60
|
+
- **PersonalBPNet** — `bpnetlite.bpnet.BPNet`, with a `fit()` that validates against a PyTorch `DataLoader` instead of holding the whole validation set in memory.
|
|
61
|
+
- **CLIPNET** — `PersonalBPNet` plus batch normalization; PyTorch port of the original TensorFlow [CLIPNET](https://github.com/Danko-Lab/clipnet).
|
|
62
|
+
- **ProCapNet** — `BPNet` with a masked profile loss, improving attributions (from the [ProCapNet paper](https://www.biorxiv.org/content/10.1101/2024.05.28.596138v2)).
|
|
63
|
+
- **PauseNet** — transfer-learns a base-resolution model to predict a single scalar phenotype per locus.
|
|
64
|
+
|
|
65
|
+
## Install
|
|
66
|
+
|
|
67
|
+
With [uv](https://docs.astral.sh/uv/):
|
|
68
|
+
|
|
69
|
+
```sh
|
|
70
|
+
uv add personalbpnet
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
Or with pip:
|
|
74
|
+
|
|
75
|
+
```sh
|
|
76
|
+
pip install personalbpnet
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
To load TensorFlow-trained weights (requires `h5py`), install with the `tf` extra: `uv add "personalbpnet[tf]"` or `pip install "personalbpnet[tf]"`.
|
|
80
|
+
|
|
81
|
+
Installing from source, for local development, is covered in [CONTRIBUTING.md](CONTRIBUTING.md).
|
|
82
|
+
|
|
83
|
+
## Documentation
|
|
84
|
+
|
|
85
|
+
| | |
|
|
86
|
+
| --- | --- |
|
|
87
|
+
| [docs/clipnet.md](docs/clipnet.md) | `PersonalBPNet` and `CLIPNET`, incl. pretrained weights |
|
|
88
|
+
| [docs/clipnet-tf.md](docs/clipnet-tf.md) | Porting the original TensorFlow CLIPNET weights |
|
|
89
|
+
| [docs/procapnet.md](docs/procapnet.md) | `ProCapNet` |
|
|
90
|
+
| [docs/pausenet.md](docs/pausenet.md) | `PauseNet` |
|
|
91
|
+
| [docs/cli.md](docs/cli.md) | `clipnet`, `pausenet`, and `clipnet_tf` command line tools |
|
|
92
|
+
| [CONTRIBUTING.md](CONTRIBUTING.md) | Installing from source and local development |
|
|
93
|
+
|
|
94
|
+
This package is under active development; APIs may change between releases. See [CHANGELOG.md](CHANGELOG.md).
|
|
95
|
+
|
|
96
|
+
## Citing
|
|
97
|
+
|
|
98
|
+
If you use `PersonalBPNet`/`CLIPNET`/`ProCapNet`, or the underlying `BPNet` architecture (via the `bpnet-lite` dependency), please cite the corresponding paper (see [CITATION.cff](CITATION.cff)):
|
|
99
|
+
|
|
100
|
+
- Avsec et al. (2021). [Base-resolution models of transcription-factor binding reveal soft motif syntax](https://doi.org/10.1038/s41588-021-00782-6). *Nature Genetics* 53:354–366. — BPNet
|
|
101
|
+
- He & Danko (2024). [Dissection of core promoter syntax through single nucleotide resolution modeling of transcription initiation](https://www.biorxiv.org/content/10.1101/2024.03.13.583868). *bioRxiv*. — CLIPNET
|
|
102
|
+
- Cochran et al. (2024). [Dissecting the cis-regulatory syntax of transcription initiation with deep learning](https://www.biorxiv.org/content/10.1101/2024.05.28.596138). *bioRxiv*. — ProCapNet
|
|
103
|
+
|
|
104
|
+
## License
|
|
105
|
+
|
|
106
|
+
[MIT](LICENSE)
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
cli/__init__.py,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
|
|
2
|
+
cli/_common.py,sha256=FPHCKEk9W34QQA5EHUnwe-n-tTko-wCXT6w6uC_BamE,7280
|
|
3
|
+
cli/clipnet.py,sha256=TqF02qWPuQekAlkttEuNil43-793EaLcpJ-QdPPk-f4,11376
|
|
4
|
+
cli/pausenet.py,sha256=h2Jy6i2wwiChLmV2X1eBW_oui5gtE8tSmCPIeJsE8PQ,5837
|
|
5
|
+
cli/tf.py,sha256=DdJ7R23b0_wBr8Hg7ct_fdltROKhBjSLFspxHlFb4F4,12343
|
|
6
|
+
personal_bpnet/__init__.py,sha256=ahMbrdtyVRVX1nNpkfxxjKinyrERvyarfv_NSEhtl6Y,438
|
|
7
|
+
personal_bpnet/clipnet_pytorch.py,sha256=rEKj54zSNURloJ558lLwmrfsEr5Dyyv8n3wT7EZTFmU,10736
|
|
8
|
+
personal_bpnet/clipnet_tensorflow.py,sha256=-_MinKGADjPVaAmX5_Nbg_to9wwtKK_Lw0tIQ19f2yk,13982
|
|
9
|
+
personal_bpnet/losses.py,sha256=8Wdw4-eVJDn8npmGElIvV89X5VZzP7lgJ-4zoe_xR5c,4146
|
|
10
|
+
personal_bpnet/personal_bpnet.py,sha256=uYgc-F_7MbLrxf5mF8ptrWWYLwbvP-ZGdJlTGscMXoE,11797
|
|
11
|
+
personal_bpnet/procapnet.py,sha256=j8etQt96Lf5JnJIRdEliktdSbWMfdNbR8dgKpngGo-s,9252
|
|
12
|
+
personal_bpnet/procapnet_orig.py,sha256=z2ZpwO75ZeB8Pe1Tg6ZoVjEJ8Hj9deW8ewoCcBYa7os,2857
|
|
13
|
+
personal_bpnet/utils.py,sha256=1qikmfTy4efeUsSSD9dogaQI_lW5iEkuT-fasnKLYeA,14164
|
|
14
|
+
personalbpnet-0.7.0.dist-info/licenses/LICENSE,sha256=1oCfZIEMHobs-ob8MgSCJ8UojO6cIN83UZrrSVSexFA,1071
|
|
15
|
+
personalbpnet-0.7.0.dist-info/METADATA,sha256=VcH1W3uCP3Ay-VGLcSi4bEOHt7NRuMMGBW73cJKGpPA,5480
|
|
16
|
+
personalbpnet-0.7.0.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91
|
|
17
|
+
personalbpnet-0.7.0.dist-info/entry_points.txt,sha256=E08LjRTjP7ks9mgzdJwRwOcHAOvM3yvMQOveAYPZDzc,96
|
|
18
|
+
personalbpnet-0.7.0.dist-info/top_level.txt,sha256=9n2UNf2TzC6qFMw3dHqQdV5Zx5DhaQMsqx89A5OR3sY,19
|
|
19
|
+
personalbpnet-0.7.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 Adam Youlin He
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|