gReLU 1.0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- gReLU-1.0.1.dist-info/LICENSE.txt +21 -0
- gReLU-1.0.1.dist-info/METADATA +106 -0
- gReLU-1.0.1.dist-info/RECORD +58 -0
- gReLU-1.0.1.dist-info/WHEEL +5 -0
- gReLU-1.0.1.dist-info/top_level.txt +1 -0
- grelu/__init__.py +16 -0
- grelu/data/__init__.py +0 -0
- grelu/data/augment.py +227 -0
- grelu/data/dataset.py +1013 -0
- grelu/data/preprocess.py +710 -0
- grelu/data/utils.py +63 -0
- grelu/design.py +287 -0
- grelu/interpret/__init__.py +0 -0
- grelu/interpret/motifs.py +319 -0
- grelu/interpret/score.py +390 -0
- grelu/io/__init__.py +136 -0
- grelu/io/bed.py +97 -0
- grelu/io/bigwig.py +98 -0
- grelu/io/fasta.py +48 -0
- grelu/io/genome.py +93 -0
- grelu/io/meme.py +115 -0
- grelu/lightning/__init__.py +1097 -0
- grelu/lightning/losses.py +77 -0
- grelu/lightning/metrics.py +146 -0
- grelu/model/__init__.py +0 -0
- grelu/model/blocks.py +761 -0
- grelu/model/heads.py +135 -0
- grelu/model/layers.py +399 -0
- grelu/model/models.py +692 -0
- grelu/model/position.py +80 -0
- grelu/model/trunks/__init__.py +338 -0
- grelu/model/trunks/borzoi.py +166 -0
- grelu/model/trunks/enformer.py +277 -0
- grelu/model/trunks/explainn.py +119 -0
- grelu/resources/__init__.py +138 -0
- grelu/resources/__pycache__/__init__.cpython-310.pyc +0 -0
- grelu/resources/blacklists/encode/hg19-blacklist.v2.bed +834 -0
- grelu/resources/blacklists/encode/hg38-blacklist.v2.bed +636 -0
- grelu/resources/blacklists/encode/mm10-blacklist.v2.bed +3435 -0
- grelu/resources/blacklists/mito_combined/hg19.full.blacklist.bed +902 -0
- grelu/resources/blacklists/mito_combined/hg19_mm10_c.full.blacklist.bed +1425 -0
- grelu/resources/blacklists/mito_combined/hg38.full.blacklist.bed +820 -0
- grelu/resources/blacklists/mito_combined/mm10.full.blacklist.bed +523 -0
- grelu/resources/blacklists/mito_combined/mm9.full.blacklist.bed +3415 -0
- grelu/resources/meme/JASPAR2022_CORE_non-redundant_pfms_meme.txt +32224 -0
- grelu/resources/meme/jvierstra_consensus_pwms.meme +10405 -0
- grelu/sequence/__init__.py +0 -0
- grelu/sequence/format.py +428 -0
- grelu/sequence/metrics.py +105 -0
- grelu/sequence/mutate.py +252 -0
- grelu/sequence/utils.py +452 -0
- grelu/transforms/__init__.py +0 -0
- grelu/transforms/label_transforms.py +50 -0
- grelu/transforms/prediction_transforms.py +248 -0
- grelu/transforms/seq_transforms.py +132 -0
- grelu/utils.py +153 -0
- grelu/variant.py +389 -0
- grelu/visualize.py +740 -0
grelu/data/preprocess.py
ADDED
|
@@ -0,0 +1,710 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Functions to preprocess genomic datasets.
|
|
3
|
+
"""
|
|
4
|
+
import os
|
|
5
|
+
import subprocess
|
|
6
|
+
import tempfile
|
|
7
|
+
from typing import Callable, List, Optional, Union
|
|
8
|
+
|
|
9
|
+
import bioframe as bf
|
|
10
|
+
import numpy as np
|
|
11
|
+
import pandas as pd
|
|
12
|
+
from anndata import AnnData
|
|
13
|
+
|
|
14
|
+
from grelu.data.utils import get_chromosomes
|
|
15
|
+
from grelu.utils import get_aggfunc
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def filter_intervals(
|
|
19
|
+
data: Union[pd.DataFrame, AnnData],
|
|
20
|
+
keep: np.ndarray,
|
|
21
|
+
inplace: bool = False,
|
|
22
|
+
) -> Optional[Union[pd.DataFrame, AnnData]]:
|
|
23
|
+
"""
|
|
24
|
+
Filter intervals by boolean mask
|
|
25
|
+
|
|
26
|
+
Args:
|
|
27
|
+
data: Either a pandas dataframe of genomic intervals or an
|
|
28
|
+
Anndata object with intervals in .var
|
|
29
|
+
keep: Boolean mask of same length as data
|
|
30
|
+
inplace: If True, the input is modified in place. If False, a new
|
|
31
|
+
dataframe or anndata object is returned.
|
|
32
|
+
|
|
33
|
+
Returns:
|
|
34
|
+
Filtered intervals in the same format (if inplace = False)
|
|
35
|
+
"""
|
|
36
|
+
print("Keeping {} intervals".format(sum(keep)))
|
|
37
|
+
if isinstance(data, pd.DataFrame):
|
|
38
|
+
return data.drop(index=data.index[~keep], inplace=inplace)
|
|
39
|
+
elif isinstance(data, AnnData):
|
|
40
|
+
if inplace:
|
|
41
|
+
data._inplace_subset_var(index=data.var_names[keep])
|
|
42
|
+
else:
|
|
43
|
+
return data[:, keep]
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def filter_obs(
|
|
47
|
+
adata: AnnData, keep: np.ndarray, inplace: bool = False
|
|
48
|
+
) -> Optional[AnnData]:
|
|
49
|
+
"""
|
|
50
|
+
Filter the `.obs` dataframe in an anndata object using a boolean mask
|
|
51
|
+
|
|
52
|
+
Args:
|
|
53
|
+
adata: anndata object
|
|
54
|
+
keep: boolean mask of same length as adata.obs
|
|
55
|
+
inplace: If True, the input is modified in place. If False, a new
|
|
56
|
+
anndata object is returned.
|
|
57
|
+
|
|
58
|
+
Returns:
|
|
59
|
+
Filtered anndata object (if inplace = False)
|
|
60
|
+
"""
|
|
61
|
+
print("Initial shape: ", adata.shape)
|
|
62
|
+
print("Keeping {} observations".format(sum(keep)))
|
|
63
|
+
if inplace:
|
|
64
|
+
adata._inplace_subset_obs(index=adata.obs_names[keep])
|
|
65
|
+
else:
|
|
66
|
+
return adata[keep, :]
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def filter_coverage(
|
|
70
|
+
adata: AnnData,
|
|
71
|
+
aggfunc: Union[str, Callable] = np.mean,
|
|
72
|
+
method: str = "cutoff",
|
|
73
|
+
cutoff: int = 1,
|
|
74
|
+
negative_frac: float = 0.0,
|
|
75
|
+
inplace: bool = False,
|
|
76
|
+
) -> Optional[AnnData]:
|
|
77
|
+
"""
|
|
78
|
+
Filter genomic intervals based on their maximum or mean coverage
|
|
79
|
+
across cell types
|
|
80
|
+
|
|
81
|
+
Args:
|
|
82
|
+
adata: An Anndata object containing genomic intervals in .var
|
|
83
|
+
aggfunc: Function to aggregate coverage values
|
|
84
|
+
method: Method to use for filtering intervals. The options are
|
|
85
|
+
"cutoff" to apply a raw coverage cutoff, "top" to select
|
|
86
|
+
the top n intervals or "percentile" to select a top percentile
|
|
87
|
+
of intervals
|
|
88
|
+
cutoff: the raw cutoff value (if method = "cutoff"), number of
|
|
89
|
+
intervals (if method = "top") or the percentile to select
|
|
90
|
+
(if method = "percentile")
|
|
91
|
+
negative_frac: Select a number of intervals below the cutoff, equal
|
|
92
|
+
to the given fraction of the number of above-cutoff intervals
|
|
93
|
+
inplace: If True, the input is modified in place. If False, a new
|
|
94
|
+
anndata object is returned.
|
|
95
|
+
|
|
96
|
+
Returns:
|
|
97
|
+
Filtered anndata object
|
|
98
|
+
"""
|
|
99
|
+
# Aggregate coverage over all tasks / cell types
|
|
100
|
+
coverages = get_aggfunc(aggfunc)(adata.X, axis=0)
|
|
101
|
+
|
|
102
|
+
# Make boolean mask for positive (over cutoff) intervals
|
|
103
|
+
if method == "cutoff":
|
|
104
|
+
keep = coverages >= cutoff
|
|
105
|
+
|
|
106
|
+
elif method == "top":
|
|
107
|
+
# Keep top n intervals
|
|
108
|
+
keep = np.ma.make_mask_none(len(adata.var))
|
|
109
|
+
keep[coverages.argsort()[-cutoff:]] = True
|
|
110
|
+
|
|
111
|
+
elif method == "percentile":
|
|
112
|
+
# Keep intervals in the nth percentile based on cutoff
|
|
113
|
+
keep = np.percentile(coverages) > cutoff
|
|
114
|
+
|
|
115
|
+
else:
|
|
116
|
+
raise NotImplementedError
|
|
117
|
+
|
|
118
|
+
# Count number of intervals retained
|
|
119
|
+
n_keep_pos = keep.sum()
|
|
120
|
+
print("Selected {} intervals with coverage above cutoff".format(n_keep_pos))
|
|
121
|
+
|
|
122
|
+
# Select a fraction of negative (below cutoff) regions if required
|
|
123
|
+
if (n_keep_pos in range(1, adata.shape[0])) and (negative_frac > 0):
|
|
124
|
+
# Index all regions below cutoff
|
|
125
|
+
negative_idxs = np.where(~keep)
|
|
126
|
+
|
|
127
|
+
# Select such regions based on the number of positive intervals
|
|
128
|
+
n_negatives = min(negative_frac * n_keep_pos, len(negative_idxs))
|
|
129
|
+
negative_idxs = np.random.choice(negative_idxs, n_negatives, replace=False)
|
|
130
|
+
print(
|
|
131
|
+
"Selected {} intervals with coverage below cutoff".format(
|
|
132
|
+
len(negative_idxs)
|
|
133
|
+
)
|
|
134
|
+
)
|
|
135
|
+
keep[negative_idxs] = True
|
|
136
|
+
|
|
137
|
+
# Filter
|
|
138
|
+
return filter_intervals(adata, keep, inplace=inplace)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def filter_cells(
|
|
142
|
+
adata: AnnData,
|
|
143
|
+
cutoff: int = 1000,
|
|
144
|
+
count_key: str = "n_cells",
|
|
145
|
+
inplace: bool = False,
|
|
146
|
+
) -> Optional[AnnData]:
|
|
147
|
+
"""
|
|
148
|
+
Drop cell types that are composed of few cells
|
|
149
|
+
|
|
150
|
+
Args:
|
|
151
|
+
adata: anndata object with intervals in .var and cell counts in .obs
|
|
152
|
+
cutoff: minimum cell count
|
|
153
|
+
count_key: key under which cell count is stored in adata.obs
|
|
154
|
+
inplace: If True, the input is modified in place. If False, a new anndata
|
|
155
|
+
object is returned.
|
|
156
|
+
|
|
157
|
+
Returns:
|
|
158
|
+
Filtered anndata object
|
|
159
|
+
"""
|
|
160
|
+
# Get boolean mask
|
|
161
|
+
keep = adata.obs[count_key] >= cutoff
|
|
162
|
+
# Filter
|
|
163
|
+
return filter_obs(adata, keep, inplace=inplace)
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
# Functions to filter intervals. All these functions can be applied either to
|
|
167
|
+
# an interval dataframe or to an anndata object.
|
|
168
|
+
def filter_random(
|
|
169
|
+
data: Union[pd.DataFrame, AnnData],
|
|
170
|
+
n: int,
|
|
171
|
+
seed: Optional[int] = None,
|
|
172
|
+
inplace: bool = False,
|
|
173
|
+
) -> Optional[Union[pd.DataFrame, AnnData]]:
|
|
174
|
+
"""
|
|
175
|
+
Filter n randomly chosen intervals
|
|
176
|
+
|
|
177
|
+
Args:
|
|
178
|
+
data: genomic intervals or anndata object with intervals in .var
|
|
179
|
+
n: Number of intervals to select
|
|
180
|
+
inplace: If True, the input is modified in place. If False, a new
|
|
181
|
+
dataframe or anndata object is returned.
|
|
182
|
+
|
|
183
|
+
Returns:
|
|
184
|
+
Filtered intervals in the same format
|
|
185
|
+
"""
|
|
186
|
+
# Number of intervals
|
|
187
|
+
if isinstance(data, pd.DataFrame):
|
|
188
|
+
n_intervals = len(data)
|
|
189
|
+
elif isinstance(data, AnnData):
|
|
190
|
+
n_intervals = len(data.var)
|
|
191
|
+
|
|
192
|
+
# Sample intervals to keep
|
|
193
|
+
rng = np.random.RandomState(seed)
|
|
194
|
+
keep = np.array([False] * n_intervals)
|
|
195
|
+
keep[rng.choice(list(range(n_intervals)), n, replace=False)] = True
|
|
196
|
+
|
|
197
|
+
# Filter
|
|
198
|
+
filter_intervals(data, keep, inplace=inplace)
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def filter_chromosomes(
|
|
202
|
+
data: Union[pd.DataFrame, AnnData],
|
|
203
|
+
include: Optional[List[str]] = None,
|
|
204
|
+
exclude: Optional[List[str]] = None,
|
|
205
|
+
inplace: bool = False,
|
|
206
|
+
):
|
|
207
|
+
"""
|
|
208
|
+
Filter to sequence elements in selected chromosomes.
|
|
209
|
+
|
|
210
|
+
Args:
|
|
211
|
+
data: Either a pandas dataframe of genomic intervals or an
|
|
212
|
+
Anndata object with intervals in .var
|
|
213
|
+
include: list of chromosome names to keep
|
|
214
|
+
exclude: list of chromosome names to drop
|
|
215
|
+
inplace: If True, the input is modified in place. If False, a
|
|
216
|
+
new dataframe or anndata object is returned.
|
|
217
|
+
|
|
218
|
+
Returns:
|
|
219
|
+
Filtered intervals in the same format
|
|
220
|
+
"""
|
|
221
|
+
# Get genomic intervals
|
|
222
|
+
if isinstance(data, pd.DataFrame):
|
|
223
|
+
intervals = data
|
|
224
|
+
elif isinstance(data, AnnData):
|
|
225
|
+
intervals = data.var
|
|
226
|
+
|
|
227
|
+
# Get boolean mask
|
|
228
|
+
keep = ~intervals.chrom.isin([])
|
|
229
|
+
|
|
230
|
+
if include is not None:
|
|
231
|
+
include = get_chromosomes(include)
|
|
232
|
+
keep = intervals["chrom"].isin(include)
|
|
233
|
+
|
|
234
|
+
if exclude is not None:
|
|
235
|
+
keep = keep & ~intervals["chrom"].isin(exclude)
|
|
236
|
+
|
|
237
|
+
# Filter
|
|
238
|
+
return filter_intervals(data, keep, inplace=inplace)
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def clip_intervals(
|
|
242
|
+
intervals: pd.DataFrame,
|
|
243
|
+
start: Optional[int] = None,
|
|
244
|
+
end: Optional[int] = None,
|
|
245
|
+
):
|
|
246
|
+
"""
|
|
247
|
+
Clip the ends of intervals to the given boundaries.
|
|
248
|
+
|
|
249
|
+
Args:
|
|
250
|
+
intervals: Dataframe containing the genomic intervals to clip.
|
|
251
|
+
start: The minimum start coordinate. All start coordinates less than this
|
|
252
|
+
will be clipped to this value.
|
|
253
|
+
end: The maximum start coordinate. All end coordinates greater than this
|
|
254
|
+
will be clipped to this value.
|
|
255
|
+
|
|
256
|
+
Returns:
|
|
257
|
+
Dataframe containing clipped intervals.
|
|
258
|
+
"""
|
|
259
|
+
# Clip start
|
|
260
|
+
if start is not None:
|
|
261
|
+
intervals["start"] = intervals["start"].apply(lambda x: max(x, start))
|
|
262
|
+
|
|
263
|
+
# Clip end
|
|
264
|
+
if end is not None:
|
|
265
|
+
intervals["end"] = intervals["end"].apply(lambda x: min(x, end))
|
|
266
|
+
|
|
267
|
+
return intervals
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def filter_overlapping(
|
|
271
|
+
data: Union[pd.DataFrame, AnnData],
|
|
272
|
+
ref_intervals: pd.DataFrame,
|
|
273
|
+
window: int = 0,
|
|
274
|
+
invert: bool = False,
|
|
275
|
+
inplace: bool = False,
|
|
276
|
+
method: str = "any",
|
|
277
|
+
):
|
|
278
|
+
"""
|
|
279
|
+
Filter intervals based on their overlap with a set of reference intervals.
|
|
280
|
+
|
|
281
|
+
Args:
|
|
282
|
+
data: Intervals, variants or anndata object with intervals in .var.
|
|
283
|
+
ref_intervals: Reference intervals to filter the data against
|
|
284
|
+
window: Number of bases to extend the reference intervals
|
|
285
|
+
invert: if False, return intervals in data that overlap with ref_intervals.
|
|
286
|
+
If True, return intervals in data that are non-overlapping with ref_intervals.
|
|
287
|
+
inplace: If True, the input is modified in place. If False, a new dataframe
|
|
288
|
+
or anndata object is returned.
|
|
289
|
+
method: "any" or "all". If "any", any amount of overlap is counted. If "all",
|
|
290
|
+
the complete interval must fall within a reference interval.
|
|
291
|
+
"""
|
|
292
|
+
from grelu.sequence.format import check_intervals
|
|
293
|
+
from grelu.variant import variants_to_intervals
|
|
294
|
+
|
|
295
|
+
if isinstance(data, AnnData):
|
|
296
|
+
intervals = data.var
|
|
297
|
+
elif isinstance(data, pd.DataFrame):
|
|
298
|
+
if check_intervals(data):
|
|
299
|
+
intervals = data
|
|
300
|
+
elif "pos" in data.columns:
|
|
301
|
+
intervals = variants_to_intervals(data, seq_len=1)
|
|
302
|
+
|
|
303
|
+
# Overlap
|
|
304
|
+
if method == "any":
|
|
305
|
+
overlap = bf.overlap(
|
|
306
|
+
intervals,
|
|
307
|
+
bf.expand(ref_intervals, pad=window),
|
|
308
|
+
how="inner",
|
|
309
|
+
return_index=True,
|
|
310
|
+
return_input=False,
|
|
311
|
+
)
|
|
312
|
+
elif method == "all":
|
|
313
|
+
overlap = bf.overlap(
|
|
314
|
+
intervals,
|
|
315
|
+
bf.expand(ref_intervals, pad=window),
|
|
316
|
+
how="inner",
|
|
317
|
+
return_index=True,
|
|
318
|
+
return_input=True,
|
|
319
|
+
)
|
|
320
|
+
overlap = overlap[
|
|
321
|
+
(overlap.start >= overlap.start_) & ((overlap.end <= overlap.end_))
|
|
322
|
+
]
|
|
323
|
+
|
|
324
|
+
# list intervals to keep
|
|
325
|
+
keep = intervals.index.isin(overlap["index"])
|
|
326
|
+
if invert:
|
|
327
|
+
keep = ~keep
|
|
328
|
+
|
|
329
|
+
# Filter
|
|
330
|
+
return filter_intervals(data, keep, inplace=inplace)
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
def filter_blacklist(
|
|
334
|
+
data: Union[pd.DataFrame, AnnData],
|
|
335
|
+
genome: str,
|
|
336
|
+
blacklist: Optional[str] = None,
|
|
337
|
+
inplace: bool = False,
|
|
338
|
+
window: int = 0,
|
|
339
|
+
):
|
|
340
|
+
"""
|
|
341
|
+
Remove intervals that overlap with blacklist regions
|
|
342
|
+
|
|
343
|
+
Args:
|
|
344
|
+
data: Either a pandas dataframe of genomic intervals or an Anndata
|
|
345
|
+
object with intervals in .var
|
|
346
|
+
genome: name of the genome corresponding to intervals
|
|
347
|
+
blacklist (str): path to blacklist file. If not given, will be
|
|
348
|
+
extracted from the package resources.
|
|
349
|
+
inplace: If True, the input is modified in place. If False, a new
|
|
350
|
+
dataframe or anndata object is returned.
|
|
351
|
+
window: Number of bases to extend the reference intervals
|
|
352
|
+
|
|
353
|
+
Returns:
|
|
354
|
+
Filtered intervals in the same format
|
|
355
|
+
"""
|
|
356
|
+
from grelu.io.bed import read_bed
|
|
357
|
+
from grelu.resources import get_blacklist_file
|
|
358
|
+
|
|
359
|
+
# Read blacklist
|
|
360
|
+
if genome is not None:
|
|
361
|
+
blacklist = get_blacklist_file(genome)
|
|
362
|
+
|
|
363
|
+
if isinstance(blacklist, str):
|
|
364
|
+
blacklist = read_bed(blacklist, str_index=False)
|
|
365
|
+
|
|
366
|
+
# Filter
|
|
367
|
+
return filter_overlapping(
|
|
368
|
+
data, blacklist, invert=True, inplace=inplace, window=window
|
|
369
|
+
)
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
def filter_chrom_ends(
|
|
373
|
+
data: Union[pd.DataFrame, AnnData],
|
|
374
|
+
genome: Optional[str] = None,
|
|
375
|
+
pad: int = 0,
|
|
376
|
+
inplace: bool = False,
|
|
377
|
+
):
|
|
378
|
+
"""
|
|
379
|
+
Filter intervals that extend beyond the ends of the chromosome.
|
|
380
|
+
|
|
381
|
+
Args:
|
|
382
|
+
data: Either a pandas dataframe of genomic intervals or an Anndata
|
|
383
|
+
object with intervals in .var
|
|
384
|
+
genome: name of the genome corresponding to intervals
|
|
385
|
+
pad: Number of bases to ignore at each end of the chromosome
|
|
386
|
+
inplace: If True, the input is modified in place. If False, a new
|
|
387
|
+
dataframe or anndata object is returned.
|
|
388
|
+
|
|
389
|
+
Returns:
|
|
390
|
+
Filtered intervals in the same format
|
|
391
|
+
"""
|
|
392
|
+
from grelu.io.genome import read_sizes
|
|
393
|
+
|
|
394
|
+
# Get genomic intervals
|
|
395
|
+
if isinstance(data, AnnData):
|
|
396
|
+
intervals = data.var
|
|
397
|
+
elif isinstance(data, pd.DataFrame):
|
|
398
|
+
intervals = data
|
|
399
|
+
|
|
400
|
+
# Filter start
|
|
401
|
+
keep = intervals.start >= pad
|
|
402
|
+
|
|
403
|
+
# Filter end if the genome is provided
|
|
404
|
+
if genome is not None:
|
|
405
|
+
sizes = read_sizes(genome)
|
|
406
|
+
for chrom, size in sizes.values:
|
|
407
|
+
drop = (intervals.chrom == chrom) & (intervals.end > (size - pad))
|
|
408
|
+
keep = keep & ~drop
|
|
409
|
+
|
|
410
|
+
# Filter
|
|
411
|
+
return filter_intervals(data, keep, inplace=inplace)
|
|
412
|
+
|
|
413
|
+
|
|
414
|
+
def split(
|
|
415
|
+
data: Union[pd.DataFrame, AnnData],
|
|
416
|
+
train_chroms: Optional[List[str]] = None,
|
|
417
|
+
val_chroms: List[str] = ["chr10"],
|
|
418
|
+
test_chroms: List[str] = ["chr11"],
|
|
419
|
+
sample: List[int] = [],
|
|
420
|
+
seed: Optional[int] = None,
|
|
421
|
+
):
|
|
422
|
+
"""
|
|
423
|
+
Split Anndata object into training, validation and test samples
|
|
424
|
+
based on chromosomes
|
|
425
|
+
|
|
426
|
+
Args:
|
|
427
|
+
data: Either a pandas dataframe of genomic intervals or an Anndata
|
|
428
|
+
object with intervals in .var
|
|
429
|
+
train_chroms: chromosomes to use for training data. If `None`, all
|
|
430
|
+
chromosomes except `val_chroms` and `test_chroms` will be used.
|
|
431
|
+
val_chroms: chromosomes to use for validation data. default `["chr10"]`
|
|
432
|
+
test_chroms: chromosomes to use for test data. default `["chr11"]`.
|
|
433
|
+
sample: List of number of random intervals to subsample for each split.
|
|
434
|
+
The order of the numbers should be `[train_sample, val_sample,
|
|
435
|
+
test_sample]`. If any element of the list is `None`, the corresponding
|
|
436
|
+
split will not be sampled.
|
|
437
|
+
seed: Random seed for sampling
|
|
438
|
+
|
|
439
|
+
Returns:
|
|
440
|
+
train_ad: Anndata object containing training samples
|
|
441
|
+
val_ad: Anndata object containing validation samples
|
|
442
|
+
test_ad: Anndata object containing test samples
|
|
443
|
+
"""
|
|
444
|
+
print("Selecting training samples")
|
|
445
|
+
train = filter_chromosomes(
|
|
446
|
+
data, include=train_chroms, exclude=val_chroms + test_chroms
|
|
447
|
+
)
|
|
448
|
+
print("\n")
|
|
449
|
+
|
|
450
|
+
print("Selecting validation samples")
|
|
451
|
+
val = filter_chromosomes(data, include=val_chroms)
|
|
452
|
+
print("\n")
|
|
453
|
+
|
|
454
|
+
print("Selecting test samples")
|
|
455
|
+
test = filter_chromosomes(data, include=test_chroms)
|
|
456
|
+
|
|
457
|
+
# Apply random sampling if requested
|
|
458
|
+
if len(sample) > 0:
|
|
459
|
+
assert len(sample) == 3
|
|
460
|
+
print("Selecting random intervals")
|
|
461
|
+
if sample[0] is not None:
|
|
462
|
+
train = filter_random(train, sample[0], seed=seed)
|
|
463
|
+
if sample[1] is not None:
|
|
464
|
+
val = filter_random(val, sample[1], seed=seed)
|
|
465
|
+
if sample[2] is not None:
|
|
466
|
+
test = filter_random(test, sample[2], seed=seed)
|
|
467
|
+
|
|
468
|
+
print(
|
|
469
|
+
"Final sizes: train: {}, val: {}, test: {}".format(
|
|
470
|
+
train.shape, val.shape, test.shape
|
|
471
|
+
)
|
|
472
|
+
)
|
|
473
|
+
|
|
474
|
+
return train, val, test
|
|
475
|
+
|
|
476
|
+
|
|
477
|
+
def get_gc_matched_intervals(
|
|
478
|
+
intervals: pd.DataFrame,
|
|
479
|
+
genome: str,
|
|
480
|
+
binwidth: float = 0.1,
|
|
481
|
+
chroms: str = "autosomes",
|
|
482
|
+
gc_bw_file: str = None,
|
|
483
|
+
blacklist: str = "hg38",
|
|
484
|
+
seed: Optional[int] = None,
|
|
485
|
+
) -> pd.DataFrame:
|
|
486
|
+
"""
|
|
487
|
+
Get GC-matched intervals for a set of given intervals.
|
|
488
|
+
|
|
489
|
+
Args:
|
|
490
|
+
intervals: genomic intervals
|
|
491
|
+
genome: Name of the genome corresponding to intervals
|
|
492
|
+
binwidth: Resolution of GC content
|
|
493
|
+
chroms: Chromosomes to search for matched intervals
|
|
494
|
+
gc_bw_file: Path to a bigWig file of genomewide GC content.
|
|
495
|
+
If None, will be created.
|
|
496
|
+
blacklist: Blacklist file of regions to exclude
|
|
497
|
+
seed: Random seed
|
|
498
|
+
|
|
499
|
+
Returns:
|
|
500
|
+
A pandas dataframe containing GC-matched negative intervals.
|
|
501
|
+
"""
|
|
502
|
+
from bpnetlite.negatives import calculate_gc_genomewide, extract_matching_loci
|
|
503
|
+
|
|
504
|
+
from grelu.io.genome import get_genome
|
|
505
|
+
from grelu.sequence.utils import get_unique_length
|
|
506
|
+
|
|
507
|
+
genome = get_genome(genome)
|
|
508
|
+
chroms = get_chromosomes(chroms)
|
|
509
|
+
|
|
510
|
+
# Get seq_len
|
|
511
|
+
seq_len = get_unique_length(intervals)
|
|
512
|
+
|
|
513
|
+
# Get bigWig file of GC content
|
|
514
|
+
if gc_bw_file is None:
|
|
515
|
+
gc_bw_file = "gc_{}_{}.bw".format(genome.name, seq_len)
|
|
516
|
+
print("Calculating GC content genomewide and saving to {}".format(gc_bw_file))
|
|
517
|
+
calculate_gc_genomewide(
|
|
518
|
+
fasta=genome.genome_file,
|
|
519
|
+
bigwig=gc_bw_file,
|
|
520
|
+
width=seq_len,
|
|
521
|
+
include_chroms=chroms,
|
|
522
|
+
verbose=True,
|
|
523
|
+
)
|
|
524
|
+
|
|
525
|
+
print("Extracting matching intervals")
|
|
526
|
+
_, tmpfile = tempfile.mkstemp()
|
|
527
|
+
intervals.iloc[:, :3].to_csv(tmpfile, sep="\t", index=False, header=False)
|
|
528
|
+
matched_loci = extract_matching_loci(
|
|
529
|
+
bed=tmpfile, bigwig=gc_bw_file, width=seq_len, bin_width=binwidth, verbose=True
|
|
530
|
+
)
|
|
531
|
+
os.remove(tmpfile)
|
|
532
|
+
print("Filtering blacklist")
|
|
533
|
+
if blacklist is not None:
|
|
534
|
+
matched_loci = filter_blacklist(matched_loci, blacklist)
|
|
535
|
+
return matched_loci
|
|
536
|
+
|
|
537
|
+
|
|
538
|
+
def add_negatives(
|
|
539
|
+
adata: AnnData,
|
|
540
|
+
negative_intervals: pd.DataFrame,
|
|
541
|
+
negative_labels: int = 0,
|
|
542
|
+
inplace: bool = False,
|
|
543
|
+
) -> Optional[AnnData]:
|
|
544
|
+
"""
|
|
545
|
+
Append negative control intervals onto an anndata object containing
|
|
546
|
+
positive intervals in .var.
|
|
547
|
+
|
|
548
|
+
Args:
|
|
549
|
+
adata: AnnData containing positive intervals in .var
|
|
550
|
+
negative_intervals: negative intervals
|
|
551
|
+
negative_labels: Label to be assigned to all negative intervals
|
|
552
|
+
inplace: If True, the input is modified in place. If False, a
|
|
553
|
+
new anndata object is returned.
|
|
554
|
+
"""
|
|
555
|
+
from anndata import concat
|
|
556
|
+
|
|
557
|
+
# Create negative labels
|
|
558
|
+
if negative_labels == 0:
|
|
559
|
+
X = np.zeros(shape=(adata.shape[0], len(negative_intervals)))
|
|
560
|
+
else:
|
|
561
|
+
assert negative_labels.shape[0] == adata.shape[0]
|
|
562
|
+
assert negative_labels.shape[1] == len(negative_intervals)
|
|
563
|
+
|
|
564
|
+
# Create negative anndata
|
|
565
|
+
negative_adata = AnnData(
|
|
566
|
+
X=X.astype(np.float32),
|
|
567
|
+
obs=adata.obs,
|
|
568
|
+
var=negative_intervals,
|
|
569
|
+
)
|
|
570
|
+
|
|
571
|
+
# Combine anndatas
|
|
572
|
+
if inplace:
|
|
573
|
+
adata = concat(
|
|
574
|
+
[adata, negative_adata],
|
|
575
|
+
axis=1,
|
|
576
|
+
join="outer",
|
|
577
|
+
label="class",
|
|
578
|
+
keys=["positive", "negative"],
|
|
579
|
+
index_unique="_",
|
|
580
|
+
)
|
|
581
|
+
else:
|
|
582
|
+
return concat(
|
|
583
|
+
[adata, negative_adata],
|
|
584
|
+
axis=1,
|
|
585
|
+
join="outer",
|
|
586
|
+
label="class",
|
|
587
|
+
keys=["positive", "negative"],
|
|
588
|
+
index_unique="_",
|
|
589
|
+
)
|
|
590
|
+
|
|
591
|
+
|
|
592
|
+
def extend_from_coord(
|
|
593
|
+
df: pd.DataFrame, seq_len: int, center_col: str = "summit"
|
|
594
|
+
) -> pd.DataFrame:
|
|
595
|
+
"""
|
|
596
|
+
Create intervals centered on the given coordinates.
|
|
597
|
+
|
|
598
|
+
Args:
|
|
599
|
+
df: A pandas dataframe
|
|
600
|
+
seq_len: Length of the output intervals.
|
|
601
|
+
center_col: Name of the column that contains the position to be centered
|
|
602
|
+
|
|
603
|
+
Returns:
|
|
604
|
+
Summit-extended peak coordinates
|
|
605
|
+
"""
|
|
606
|
+
centers = df[center_col].astype(int)
|
|
607
|
+
starts = df.iloc[:, 1] + centers - seq_len // 2
|
|
608
|
+
return pd.DataFrame.from_dict(
|
|
609
|
+
{"chrom": df.iloc[:, 0], "start": starts, "end": starts + seq_len}
|
|
610
|
+
)
|
|
611
|
+
|
|
612
|
+
|
|
613
|
+
def merge_intervals_by_column(intervals: pd.DataFrame, group_col: str) -> pd.DataFrame:
|
|
614
|
+
"""
|
|
615
|
+
Merge intervals that have the same value in a given column. The output
|
|
616
|
+
is a dataframe containing one interval per unique value, with the start corresponding
|
|
617
|
+
to the minimum of all start positions for intervals with that value, and the end
|
|
618
|
+
corresponding to the maximum of all end positions for intervals with that value.
|
|
619
|
+
|
|
620
|
+
Args:
|
|
621
|
+
intervals: Dataframe containing genomic intervals.
|
|
622
|
+
group_col: Column by which to group and merge intervals.
|
|
623
|
+
|
|
624
|
+
Returns:
|
|
625
|
+
A dataframe containing one merged interval for each value in group_col.
|
|
626
|
+
"""
|
|
627
|
+
output = intervals.groupby(group_col).apply(
|
|
628
|
+
lambda x: (x.chrom.unique().tolist(), x.start.min(), x.end.max())
|
|
629
|
+
)
|
|
630
|
+
output = pd.DataFrame(output).reset_index()
|
|
631
|
+
output[["chrom", "start", "end"]] = pd.DataFrame(output[0].tolist())
|
|
632
|
+
output = output.drop(columns=0)
|
|
633
|
+
assert (
|
|
634
|
+
output.chrom.apply(len).unique() == 1
|
|
635
|
+
), "At least one group of intervals spans multiple chromosomes"
|
|
636
|
+
output.chrom = output.chrom.apply(lambda x: x[0])
|
|
637
|
+
return output
|
|
638
|
+
|
|
639
|
+
|
|
640
|
+
def make_insertion_bigwig(
|
|
641
|
+
frag_file: str,
|
|
642
|
+
genome: str,
|
|
643
|
+
out_prefix: Optional[str] = None,
|
|
644
|
+
plus_shift: int = 0,
|
|
645
|
+
minus_shift: int = 0,
|
|
646
|
+
chroms: Optional[Union[List[str], str]] = None,
|
|
647
|
+
tmp_dir: str = "./",
|
|
648
|
+
out_dir: str = "./",
|
|
649
|
+
) -> str:
|
|
650
|
+
"""
|
|
651
|
+
Given a fragment file, create a bigwig of Tn5 insertion sites
|
|
652
|
+
|
|
653
|
+
Args:
|
|
654
|
+
frag_file: Path to fragment file
|
|
655
|
+
genome: Name of genome to load with genomepy
|
|
656
|
+
out_prefix: Prefix for output bigwig file
|
|
657
|
+
plus_shift: Additional shift to add to positive strand
|
|
658
|
+
minus_shift: Additional shift to add to negative strand
|
|
659
|
+
chroms: The chromosome name(s) or shortcut name(s).
|
|
660
|
+
tmp_dir: Directory for temporary file
|
|
661
|
+
out_dir: Directory for bigwig file
|
|
662
|
+
|
|
663
|
+
Returns:
|
|
664
|
+
bw_file (str): Path to bigWig file
|
|
665
|
+
"""
|
|
666
|
+
from grelu.data.utils import get_chromosomes
|
|
667
|
+
from grelu.io.genome import get_genome
|
|
668
|
+
|
|
669
|
+
# Load the genome
|
|
670
|
+
genome = get_genome(genome)
|
|
671
|
+
|
|
672
|
+
# Generate output file path
|
|
673
|
+
frag_file_prefix = os.path.splitext(os.path.basename(frag_file))[0]
|
|
674
|
+
bedgraph_file = os.path.join(tmp_dir, frag_file_prefix + ".bedGraph")
|
|
675
|
+
|
|
676
|
+
# Fragment file -> shift -> bedgraph file -> sort
|
|
677
|
+
print("Making bedgraph file")
|
|
678
|
+
open_cmd = (
|
|
679
|
+
f"zcat {frag_file} | " if frag_file.endswith(".gz") else f"cat {frag_file} | "
|
|
680
|
+
)
|
|
681
|
+
shift_cmd = (
|
|
682
|
+
"""awk -v OFS="\\t" """
|
|
683
|
+
+ """'{{print $1,$2{0:+},$3,1000,0,"+";
|
|
684
|
+
print $1,$2,$3{1:+},1000,0,"-"}}' | sort -k1,1 | """.format(
|
|
685
|
+
plus_shift, minus_shift
|
|
686
|
+
)
|
|
687
|
+
)
|
|
688
|
+
filter_cmd = (
|
|
689
|
+
""
|
|
690
|
+
if chroms is None
|
|
691
|
+
else f"""grep {"".join([ f"-e ^{chrom} " for chrom in get_chromosomes(chroms)])} | """
|
|
692
|
+
)
|
|
693
|
+
bedgraph_cmd = f"bedtools genomecov -bg -5 -i stdin -g {genome.sizes_file} | "
|
|
694
|
+
sort_cmd = f"bedtools sort -i stdin > {bedgraph_file}"
|
|
695
|
+
cmd = open_cmd + shift_cmd + filter_cmd + bedgraph_cmd + sort_cmd
|
|
696
|
+
print(cmd)
|
|
697
|
+
subprocess.run(cmd, shell=True, check=True)
|
|
698
|
+
|
|
699
|
+
# bedgraph file -> bigWig file
|
|
700
|
+
print("Making bigWig file")
|
|
701
|
+
bw_file = os.path.join(out_dir, out_prefix or frag_file_prefix + ".bw")
|
|
702
|
+
cmd = "bedGraphToBigWig {} {} {}".format(bedgraph_file, genome.sizes_file, bw_file)
|
|
703
|
+
print(cmd)
|
|
704
|
+
subprocess.run(cmd, shell=True, check=True)
|
|
705
|
+
|
|
706
|
+
# Delete bedgraph file
|
|
707
|
+
print("Deleting temporary files")
|
|
708
|
+
os.remove(bedgraph_file)
|
|
709
|
+
|
|
710
|
+
return bw_file
|