| 1 |
|
| 2 |
import os |
| 3 |
os.environ["MKL_NUM_THREADS"] = "1" |
| 4 |
os.environ["MKL_THREADING_LAYER"] = "sequential" |
| 5 |
os.environ["NUMEXPR_NUM_THREADS"] = "1" |
| 6 |
os.environ["OMP_NUM_THREADS"] = "1" |
| 7 |
os.environ['OPENBLAS_NUM_THREADS'] = '1' |
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
import multiprocessing as mp |
| 12 |
from time import time |
| 13 |
from collections import * |
| 14 |
import traceback |
| 15 |
import logging |
| 16 |
|
| 17 |
|
| 18 |
import numpy as np |
| 19 |
import pandas as pd |
| 20 |
import h5py |
| 21 |
from tqdm import tqdm |
| 22 |
|
| 23 |
|
| 24 |
from pycoQC.common import * |
| 25 |
|
| 26 |
|
| 27 |
logging.basicConfig(level=logging.INFO, format='%(message)s') |
| 28 |
logger = logging.getLogger(__name__) |
| 29 |
logLevel_dict = logLevel_dict = {2:logging.DEBUG, 1:logging.INFO, 0:logging.WARNING} |
| 30 |
|
| 31 |
|
| 32 |
class Fast5_to_seq_summary (): |
| 33 |
""" |
| 34 |
Create a summary file akin the one generated by Albacore or Guppy from a directory containing |
| 35 |
multiple fast5 files. The script will attempt to extract all the required fields but will not |
| 36 |
raise an error if not found. |
| 37 |
""" |
| 38 |
|
| 39 |
attrs_grp_dict = { |
| 40 |
"mean_qscore_template": {"grp":"summary_basecall", "attrs": "mean_qscore"}, |
| 41 |
"sequence_length_template": {"grp":"summary_basecall", "attrs": "sequence_length"}, |
| 42 |
"called_events": {"grp":"summary_basecall", "attrs": "called_events"}, |
| 43 |
"skip_prob": {"grp":"summary_basecall", "attrs": "skip_prob"}, |
| 44 |
"stay_prob": {"grp":"summary_basecall", "attrs": "stay_prob"}, |
| 45 |
"step_prob": {"grp":"summary_basecall", "attrs": "step_prob"}, |
| 46 |
"strand_score": {"grp":"summary_basecall", "attrs": "strand_score"}, |
| 47 |
"read_id": {"grp":"raw_read", "attrs": "read_id"}, |
| 48 |
"start_time": {"grp":"raw_read", "attrs": "start_time"}, |
| 49 |
"duration": {"grp":"raw_read", "attrs": "duration"}, |
| 50 |
"start_mux": {"grp":"raw_read", "attrs": "start_mux"}, |
| 51 |
"read_number": {"grp":"raw_read", "attrs": "read_number"}, |
| 52 |
"channel": {"grp":"channel_id", "attrs": "channel_number"}, |
| 53 |
"channel_digitisation": {"grp":"channel_id", "attrs": "digitisation"}, |
| 54 |
"channel_offset": {"grp":"channel_id", "attrs": "offset"}, |
| 55 |
"channel_range": {"grp":"channel_id", "attrs": "range"}, |
| 56 |
"channel_sampling_rate": {"grp":"channel_id", "attrs": "sampling_rate"}, |
| 57 |
"run_id": {"grp":"tracking_id", "attrs": "run_id"}, |
| 58 |
"sample_id": {"grp":"tracking_id", "attrs": "sample_id"}, |
| 59 |
"device_id": {"grp":"tracking_id", "attrs": "device_id"}, |
| 60 |
"protocol_run_id": {"grp":"tracking_id", "attrs": "protocol_run_id"}, |
| 61 |
"flow_cell_id": {"grp":"tracking_id", "attrs": "flow_cell_id"}, |
| 62 |
"calibration_strand_genome_template": {"grp":"summary_calibration", "attrs": "genome"}, |
| 63 |
"calibration_strand_end": {"grp":"summary_calibration", "attrs": "genome_end"}, |
| 64 |
"calibration_strand_start": {"grp":"summary_calibration", "attrs": "genome_start"}, |
| 65 |
"calibration_strand_identity": {"grp":"summary_calibration", "attrs": "identity"}, |
| 66 |
"barcode_arrangement": {"grp":"summary_barcoding", "attrs": "barcode_arrangement"}, |
| 67 |
"barcode_full_arrangement": {"grp":"summary_barcoding", "attrs": "barcode_full_arrangement"}, |
| 68 |
"barcode_score": {"grp":"summary_barcoding", "attrs": "barcode_score"}, |
| 69 |
} |
| 70 |
|
| 71 |
def __init__ (self, |
| 72 |
fast5_dir:str, |
| 73 |
seq_summary_fn:str, |
| 74 |
max_fast5:int=0, |
| 75 |
threads:int=4, |
| 76 |
basecall_id:int=0, |
| 77 |
verbose_level:int=0, |
| 78 |
include_path:bool=False, |
| 79 |
fields:list=[ |
| 80 |
"read_id", "run_id", "channel", "start_time", |
| 81 |
"sequence_length_template", "mean_qscore_template", |
| 82 |
"calibration_strand_genome_template", "barcode_arrangement"]): |
| 83 |
""" |
| 84 |
* fast5_dir |
| 85 |
Directory containing fast5 files. Can contain multiple subdirectories |
| 86 |
* seq_summary_fn |
| 87 |
path of the summary sequencing file where to write the data extracted from the fast5 files |
| 88 |
* max_fast5 |
| 89 |
Maximum number of file to try to parse. 0 to deactivate |
| 90 |
* threads |
| 91 |
Total number of threads to use. 1 thread is used for the reader and 1 for the writer. Minimum 3 (default = 4) |
| 92 |
* fields |
| 93 |
list of field names corresponding to attributes to try to fetch from the fast5 files. List a valid field names: |
| 94 |
mean_qscore_template, sequence_length_template, called_events, skip_prob, stay_prob, step_prob, strand_score, read_id, start_time, |
| 95 |
duration, start_mux, read_number, channel, channel_digitisation, channel_offset, channel_range, channel_sampling, |
| 96 |
run_id, sample_id, device_id, protocol_run, flow_cell, calibration_strand, calibration_strand, calibration_strand, |
| 97 |
calibration_strand, barcode_arrangement, barcode_full, barcode_score |
| 98 |
* basecall_id |
| 99 |
id of the basecalling group. By default leave to 0, but if you perfome multiple basecalling on the same fast5 files, |
| 100 |
this can be used to indicate the corresponding group (1, 2 ...) |
| 101 |
* include_path |
| 102 |
If True the absolute path to the corresponding file is added in an extra column |
| 103 |
* verbose_level |
| 104 |
Level of verbosity, from 2 (Chatty) to 0 (Nothing) |
| 105 |
""" |
| 106 |
|
| 107 |
logger.setLevel(logLevel_dict.get(verbose_level, logging.WARNING)) |
| 108 |
|
| 109 |
|
| 110 |
logger.info ("Check input data and options") |
| 111 |
if not os.access(fast5_dir, os.R_OK): |
| 112 |
raise pycoQCError ("Cannot read the indicated fast5 directory") |
| 113 |
if not os.access(os.path.dirname(seq_summary_fn), os.W_OK): |
| 114 |
raise pycoQCError ("Cannot write the indicated seq_summary_fn") |
| 115 |
if threads < 3: |
| 116 |
raise pycoQCError ("At least 3 threads required") |
| 117 |
for field in fields: |
| 118 |
if not field in self.attrs_grp_dict: |
| 119 |
raise pycoQCError ("Field {} is not valid, please choose among the following valid fields: {}".format(field, ",".join(self.attrs_grp_dict.keys()))) |
| 120 |
|
| 121 |
|
| 122 |
self.fast5_dir = fast5_dir |
| 123 |
self.seq_summary_fn = seq_summary_fn |
| 124 |
self.threads = threads-2 |
| 125 |
self.max_fast5 = max_fast5 |
| 126 |
self.fields = fields |
| 127 |
self.basecall_id = basecall_id |
| 128 |
self.include_path = include_path |
| 129 |
self.verbose_level = verbose_level |
| 130 |
|
| 131 |
|
| 132 |
in_q = mp.Queue (maxsize=1000) |
| 133 |
out_q = mp.Queue (maxsize=1000) |
| 134 |
error_q = mp.Queue () |
| 135 |
counter_q = mp.Queue () |
| 136 |
|
| 137 |
|
| 138 |
ps_list = [] |
| 139 |
ps_list.append (mp.Process (target=self._list_fast5, args=(in_q, error_q))) |
| 140 |
for i in range (self.threads): |
| 141 |
ps_list.append (mp.Process (target=self._read_fast5, args=(in_q, out_q, error_q, counter_q, i))) |
| 142 |
ps_list.append (mp.Process (target=self._write_seq_summary, args=(out_q, error_q, counter_q))) |
| 143 |
|
| 144 |
|
| 145 |
logger.info ("Start processing fast5 files") |
| 146 |
try: |
| 147 |
|
| 148 |
for ps in ps_list: |
| 149 |
ps.start () |
| 150 |
|
| 151 |
for tb in iter (error_q.get, None): |
| 152 |
raise pycoQCError(tb) |
| 153 |
|
| 154 |
for ps in ps_list: |
| 155 |
ps.join () |
| 156 |
|
| 157 |
|
| 158 |
except (BrokenPipeError, KeyboardInterrupt, pycoQCError) as E: |
| 159 |
for ps in ps_list: |
| 160 |
ps.terminate () |
| 161 |
logger.info ("\nAn error occured. All processes were killed\n") |
| 162 |
raise E |
| 163 |
|
| 164 |
def _list_fast5 (self, in_q, error_q): |
| 165 |
""" |
| 166 |
Mono-threaded worker adding fast5 files found in a directory tree recursively |
| 167 |
to a feeder queue for the multiprocessing workers |
| 168 |
""" |
| 169 |
logger.debug ("[READER] Start listing fast5 files") |
| 170 |
try: |
| 171 |
|
| 172 |
for i, fast5_fn in enumerate(recursive_file_gen (dir=self.fast5_dir, ext="fast5")): |
| 173 |
if self.max_fast5 and i == self.max_fast5: |
| 174 |
break |
| 175 |
in_q.put(fast5_fn) |
| 176 |
|
| 177 |
|
| 178 |
if i == 0: |
| 179 |
raise pycoQCError ("No valid fast5 files found in indicated folder") |
| 180 |
|
| 181 |
logger.debug ("[READER] Add a total of {} files to input queue".format(i+1)) |
| 182 |
|
| 183 |
|
| 184 |
except Exception: |
| 185 |
error_q.put (traceback.format_exc()) |
| 186 |
finally: |
| 187 |
for i in range (self.threads): |
| 188 |
in_q.put(None) |
| 189 |
|
| 190 |
def _read_fast5 (self, in_q, out_q, error_q, counter_q, worker_id): |
| 191 |
""" |
| 192 |
Multi-threaded workers in charge of parsing fast5 file. |
| 193 |
""" |
| 194 |
logger.debug ("[WORKER_{:02}] Start processing fast5 files".format(worker_id)) |
| 195 |
try: |
| 196 |
c = {"overall":Counter (), "fields_found":Counter(), "fields_not_found":Counter()} |
| 197 |
|
| 198 |
for fast5_fn in iter(in_q.get, None): |
| 199 |
|
| 200 |
with h5py.File(fast5_fn, "r") as h5_fp: |
| 201 |
|
| 202 |
multi_read = 'file_type' in h5_fp.attrs.keys() and h5_fp.attrs['file_type'] == b'multi-read' |
| 203 |
|
| 204 |
if multi_read: |
| 205 |
read_ids = list(h5_fp["/"].keys()) |
| 206 |
else: |
| 207 |
read_ids = list(h5_fp["/Raw/Reads"].keys()) |
| 208 |
|
| 209 |
for read_id in read_ids: |
| 210 |
|
| 211 |
d = OrderedDict() |
| 212 |
|
| 213 |
if multi_read: |
| 214 |
grp_dict = { |
| 215 |
"raw_read" : "/{}/Raw/".format(read_id), |
| 216 |
"summary_basecall" : "/{read_id}/Analyses/Basecall_1D_{bc_id:03}/Summary/basecall_1d_template/".format(read_id=read_id, bc_id=self.basecall_id), |
| 217 |
"summary_calibration" : "/{read_id}/Analyses/Calibration_Strand_Detection_{bc_id:03}/Summary/calibration_strand_template/".format(read_id=read_id, bc_id=self.basecall_id), |
| 218 |
"summary_barcoding" : "/{read_id}/Analyses/Barcoding_{bc_id:03}/Summary/barcoding/".format(read_id=read_id, bc_id=self.basecall_id), |
| 219 |
"tracking_id" : "/{}/tracking_id".format(read_id), |
| 220 |
"channel_id" : "/{}/channel_id".format(read_id)} |
| 221 |
|
| 222 |
else: |
| 223 |
|
| 224 |
grp_dict = { |
| 225 |
"raw_read" : "/Raw/Reads/{}/".format(read_id), |
| 226 |
"summary_basecall" : "/Analyses/Basecall_1D_{:03}/Summary/basecall_1d_template/".format(self.basecall_id), |
| 227 |
"summary_calibration" : "/Analyses/Calibration_Strand_Detection_{:03}/Summary/calibration_strand_template/".format(self.basecall_id), |
| 228 |
"summary_barcoding" : "/Analyses/Barcoding_{:03}/Summary/barcoding/".format(self.basecall_id), |
| 229 |
"tracking_id" : "UniqueGlobalKey/tracking_id", |
| 230 |
"channel_id" : "UniqueGlobalKey/channel_id"} |
| 231 |
|
| 232 |
|
| 233 |
for field in self.fields: |
| 234 |
|
| 235 |
|
| 236 |
if field == "start_time": |
| 237 |
start_time = self._get_h5_attrs (fp=h5_fp, |
| 238 |
grp=grp_dict[self.attrs_grp_dict["start_time"]["grp"]], |
| 239 |
attrs=self.attrs_grp_dict["start_time"]["attrs"]) |
| 240 |
sampling_rate = self._get_h5_attrs (fp=h5_fp, |
| 241 |
grp=grp_dict[self.attrs_grp_dict["channel_sampling_rate"]["grp"]], |
| 242 |
attrs=self.attrs_grp_dict["channel_sampling_rate"]["attrs"]) |
| 243 |
if start_time and sampling_rate: |
| 244 |
d[field] = int(start_time/sampling_rate) |
| 245 |
c["fields_found"][field] +=1 |
| 246 |
else: |
| 247 |
c["fields_not_found"][field] +=1 |
| 248 |
|
| 249 |
else: |
| 250 |
v = self._get_h5_attrs ( |
| 251 |
fp=h5_fp, grp=grp_dict[self.attrs_grp_dict[field]["grp"]], attrs=self.attrs_grp_dict[field]["attrs"]) |
| 252 |
if v: |
| 253 |
d[field] = v |
| 254 |
c["fields_found"][field] +=1 |
| 255 |
else: |
| 256 |
c["fields_not_found"][field] +=1 |
| 257 |
|
| 258 |
if self.include_path: |
| 259 |
d["path"] = os.path.abspath(fast5_fn) |
| 260 |
|
| 261 |
|
| 262 |
if d: |
| 263 |
out_q.put(d) |
| 264 |
c["overall"]["valid files"] += 1 |
| 265 |
else: |
| 266 |
c["overall"]["invalid files"] += 1 |
| 267 |
|
| 268 |
|
| 269 |
counter_q.put(c) |
| 270 |
|
| 271 |
|
| 272 |
except Exception: |
| 273 |
error_q.put (traceback.format_exc()) |
| 274 |
finally: |
| 275 |
out_q.put(None) |
| 276 |
|
| 277 |
def _write_seq_summary (self, out_q, error_q, counter_q): |
| 278 |
""" |
| 279 |
Mono-threaded Worker writing the sequencing summary file |
| 280 |
""" |
| 281 |
logger.debug ("[WRITER] Start collecting summary data") |
| 282 |
|
| 283 |
t = time() |
| 284 |
try: |
| 285 |
l = [] |
| 286 |
with tqdm (unit=" reads", mininterval=0.1, smoothing=0.1, disable=self.verbose_level==2) as pbar: |
| 287 |
|
| 288 |
for _ in range (self.threads): |
| 289 |
for d in iter (out_q.get, None): |
| 290 |
l.append(d) |
| 291 |
pbar.update(1) |
| 292 |
|
| 293 |
|
| 294 |
logger.debug ("[WRITER] Write data to file") |
| 295 |
df = pd.DataFrame(l) |
| 296 |
df.to_csv(self.seq_summary_fn, sep="\t", index=False) |
| 297 |
|
| 298 |
|
| 299 |
logger.debug ("[WRITER] Summarize counters") |
| 300 |
c = {"overall":Counter (), "fields_found":Counter(), "fields_not_found":Counter()} |
| 301 |
for _ in range (self.threads): |
| 302 |
worker_c = counter_q.get() |
| 303 |
for k, v in worker_c.items(): |
| 304 |
for k2, v2 in v.items(): |
| 305 |
c[k][k2] += v2 |
| 306 |
|
| 307 |
logger.info ("Overall counts {}".format(dict_to_str(c["overall"]))) |
| 308 |
logger.info ("fields found {}".format(dict_to_str(c["fields_found"]))) |
| 309 |
logger.info ("fields not found {}".format(dict_to_str(c["fields_not_found"]))) |
| 310 |
|
| 311 |
|
| 312 |
logger.warning ("Total reads: {} / Average speed: {} reads/s\n".format(len(df), round (len(df)/(time()-t), 2))) |
| 313 |
|
| 314 |
|
| 315 |
except Exception: |
| 316 |
error_q.put (traceback.format_exc()) |
| 317 |
finally: |
| 318 |
error_q.put(None) |
| 319 |
|
| 320 |
@staticmethod |
| 321 |
def _get_h5_attrs (fp, grp, attrs): |
| 322 |
try: |
| 323 |
v = fp[grp].attrs[attrs] |
| 324 |
if type(v) == np.bytes_: |
| 325 |
v = v.decode("utf8") |
| 326 |
return v |
| 327 |
except KeyError : |
| 328 |
return None |