-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathloader.py
More file actions
259 lines (217 loc) · 9.61 KB
/
loader.py
File metadata and controls
259 lines (217 loc) · 9.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
description = """
Lightning Data Module for model training
Given bed file, return sequence and chromatin info
"""
import math
import logging
import torch
import pysam
import pyfaidx
import numpy as np
import pandas as pd
import webdataset as wds
from itertools import islice
from torch.utils.data import IterableDataset, DataLoader
from pybedtools import BedTool
from seqchromloader import utils, config
logger = logging.getLogger(__name__)
class SeqChromLoader():
"""
:param dataloader_kws: keyword arguments passed to ``torch.utils.data.DataLoader``
:type dataloader_kws: dict of kwargs
"""
def __init__(self, SeqChromDataset):
self.SeqChromDataset = SeqChromDataset
self.__doc__ = self.__doc__ + self.SeqChromDataset.__doc__
def __call__(self, *args, dataloader_kws:dict={}, **kwargs):
# default dataloader kws
if dataloader_kws is not None:
num_workers = dataloader_kws.pop("num_workers", 1)
else:
num_workers = 1
return DataLoader(self.SeqChromDataset(*args, **kwargs),
num_workers=num_workers, **dataloader_kws)
def seqChromLoaderCurry(SeqChromDataset):
return SeqChromLoader(SeqChromDataset)
class _SeqChromDatasetByWds(IterableDataset):
"""
:param wds: list of webdataset files to get samples from
:type wds: list of str
:param transforms: A dictionary of functions to transform the output data, accepted keys are **["seq", "chrom", "target", "label"]**
:type transforms: dict of functions
"""
def __init__(self, wds, transforms:dict=None, rank=0, world_size=1, keep_key=False):
self.wds = wds
self.transforms = transforms
self.rank = rank
self.world_size = world_size
self.keep_key = keep_key
def initialize(self):
# this function will be called by worker_init_function in DataLoader
pass
def __iter__(self):
pipeline = [
wds.SimpleShardList(self.wds),
split_by_node(self.rank, self.world_size),
wds.split_by_worker,
wds.tarfile_to_samples(),
wds.decode(),
wds.rename(seq="seq.npy",
chrom="chrom.npy",
target="target.npy",
label="label.npy")
]
# transform
if self.transforms is not None:
pipeline.append(wds.map_dict(**self.transforms))
if self.keep_key:
pipeline.append(wds.to_tuple("__key__", "seq", "chrom", "target", "label"))
else:
pipeline.append(wds.to_tuple("seq", "chrom", "target", "label"))
ds = wds.DataPipeline(*pipeline)
return iter(ds)
SeqChromDatasetByWds = seqChromLoaderCurry(_SeqChromDatasetByWds)
class _SeqChromDatasetByDataFrame(IterableDataset):
"""
:param dataframe: pandas dataframe describing genomics regions to extract info from, every region has to be of the same length.
:type dataframe: pd.DataFrame
:param genome_fasta: Genome fasta file.
:type genome_fasta: str
:param bigwig_filelist: A list of bigwig files containing track information (e.g., histone modifications)
:type bigwig_filelist: list of str or None
:param target_bam: single or list of bam file to get # reads in each region
:type target_bam: str or None
:param transforms: A dictionary of functions to transform the output data, accepted keys are *["seq", "chrom", "target", "label"]*
:type transforms: dict of functions
"""
def __init__(self,
dataframe: pd.DataFrame,
genome_fasta: str,
bigwig_filelist:list=None,
target_bam=None,
transforms:dict=None,
return_region=False,
patch_left=0, patch_right=0,
shuffle=False):
self.dataframe = dataframe
self.genome_fasta = genome_fasta
self.genome_pyfaidx = None
self.bigwig_filelist = bigwig_filelist
self.bigwigs = None
self.target_bam = target_bam
self.target_pysam = None
self.transforms = transforms
self.return_region = return_region
self.patch_left = patch_left
self.patch_right = patch_right
self.shuffle = shuffle
self.start = 0; self.end = len(self.dataframe)
def __len__(self):
return len(self.dataframe)
def initialize(self):
# create the stream handler after child processes spawned to enable parallel reading
# this function will be called by worker_init_function in DataLoader
self.genome_pyfaidx = pyfaidx.Fasta(self.genome_fasta)
self.bigwigs = [utils.BigWig(bw_path, backend=config.BIGWIG_BACKEND) for bw_path in self.bigwig_filelist] if self.bigwig_filelist is not None else None
if self.target_bam is not None:
if isinstance(self.target_bam, list):
self.target_pysam = [pysam.AlignmentFile(b) for b in self.target_bam]
else:
self.target_pysam = pysam.AlignmentFile(self.target_bam)
# shuffle the dataframe if need
if self.shuffle:
self.dataframe.sample(frac=1., replace=False)
def __iter__(self):
self.initialize()
worker_info = torch.utils.data.get_worker_info()
if worker_info is not None: # single-process data loading, return the full iterator
# split workload
per_worker = int(math.ceil((self.end - self.start) / float(worker_info.num_workers)))
worker_id = worker_info.id
iter_start = self.start + worker_id * per_worker
iter_end = min(iter_start + per_worker, self.end)
# replace start and end
self.start = iter_start; self.end = iter_end
for idx in range(self.start, self.end):
item = self.dataframe.iloc[idx,]
try:
feature = utils.extract_info(
item.chrom,
item.start,
item.end,
item.label,
genome_pyfaidx=self.genome_pyfaidx,
bigwigs=self.bigwigs,
target=self.target_pysam,
strand=item.strand,
transforms=self.transforms,
patch_left=self.patch_left,
patch_right=self.patch_right
)
except utils.BigWigInaccessible as e:
logger.warning(f"Inaccessible bigwig error detected in region {item.chrom}:{item.start}-{item.end}, Skipping...")
continue
except AssertionError as e:
logger.warning(f"AssertionError detected in region {item.chrom}:{item.start}-{item.end}, Skipping")
continue
if not self.return_region:
yield feature['seq'], feature['chrom'], feature['target'], feature['label']
else:
yield f'{item.chrom}:{item.start}-{item.end}', feature['seq'], feature['chrom'], feature['target'], feature['label']
SeqChromDatasetByDataFrame = seqChromLoaderCurry(_SeqChromDatasetByDataFrame)
class _SeqChromDatasetByBed(_SeqChromDatasetByDataFrame):
"""
:param bed: Bed file describing genomics regions to extract info from, every region has to be of the same length.
:type bed: str
:param genome_fasta: Genome fasta file.
:type genome_fasta: str
:param bigwig_filelist: A list of bigwig files containing track information (e.g., histone modifications)
:type bigwig_filelist: list of str or None
:param target_bam: bam file to get # reads in each region
:type target_bam: str or None
:param transforms: A dictionary of functions to transform the output data, accepted keys are *["seq", "chrom", "target", "label"]*
:type transforms: dict of functions
"""
def __init__(self, bed: str, genome_fasta: str, bigwig_filelist:list=None, target_bam=None,
transforms:dict=None, return_region=False,
patch_left=0, patch_right=0, shuffle=False):
dataframe = BedTool(bed).to_dataframe().iloc[:, :6]
dataframe = dataframe.rename(columns={'name': 'label'})
# assign fake labels and strands if missing
if not 'label' in dataframe.columns:
dataframe['label'] = -1
if not 'strand' in dataframe.columns:
dataframe['strand'] = '+'
super().__init__(dataframe,
genome_fasta,
bigwig_filelist,
target_bam,
transforms,
return_region,
patch_left, patch_right, shuffle)
SeqChromDatasetByBed = seqChromLoaderCurry(_SeqChromDatasetByBed)
def count_lines(fp):
with open(fp, 'r') as f:
for count, line in enumerate(f):
pass
return count+1
def _split_by_node(src, global_rank, world_size):
if world_size > 1:
for s in islice(src, global_rank, None, world_size):
yield s
else:
for s in src:
yield s
split_by_node = wds.pipelinefilter(_split_by_node)
def _scale_chrom(sample, scaler_mean, scaler_std):
# standardize chrom by provided mean and std
seq, chrom, target, label = sample
chrom = np.divide(chrom - scaler_mean, scaler_std, dtype=np.float32)
return seq, chrom, target, label
scale_chrom = wds.pipelinefilter(_scale_chrom)
def _target_vlog(sample):
# take log(n+1) on target
seq, chrom, target, label = sample
target = np.log(target + 1, dtype=np.float32)
return seq, chrom, target, label
target_vlog = wds.pipelinefilter(_target_vlog)