Debian Codegraph @

pycoQC/common.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2
3 # Standard library imports
4 from os import access, R_OK, listdir, path, makedirs
5 import inspect
6 from glob import iglob, glob
7 import sys
8 import logging
9 from collections import *
10
11 # Third party imports
12 import pandas as pd
13 import pysam as ps
14
15 #~~~~~~~~~~~~~~CUSTOM EXCEPTION AND WARN CLASSES~~~~~~~~~~~~~~#
16 class pycoQCError (Exception):
17 """ Basic exception class for pycoQC package """
18 pass
19
20 class pycoQCWarning (Warning):
21 """ Basic Warning class for pycoQC package """
22 pass
23
24 ##~~~~~~~ FUNCTIONS ~~~~~~~#
25
26 def is_readable_file (fn):
27 """Verify the readability of a file or list of file"""
28 return path.isfile (fn) and access (fn, R_OK)
29
30 def check_arg (arg_name, arg_val, required_type, allow_none=True, min=None, max=None, choices=[]):
31 """Check argument values and type"""
32 if allow_none and arg_val is None:
33 return arg_val
34
35 if not isinstance(arg_val, required_type):
36 try:
37 arg_val = required_type(arg_val)
38 except:
39 raise Exception ("Argument `{}` value `{}` is not in correct type: `{}` and cannot be coerced".format(arg_name, arg_val, required_type.__name__))
40
41 if required_type in [float, int]:
42 if min and arg_val < min:
43 raise Exception ("Argument `{}` value `{}` is too low. Minimal value: {}".format(arg_name, arg_val, min))
44 if max and arg_val > max:
45 raise Exception ("Argument `{}` value `{}` is too high. Maximal value: {}".format(arg_name, arg_val, max))
46
47 if choices and arg_val not in choices:
48 raise Exception ("Argument `{}` value `{}` is not in the list of possible choices. Choices: {}".format(arg_name, arg_val, ", ".join(choices)))
49
50 return arg_val
51
52 def sequencing_summary_file_sample (infile, outfile=None, n_seq=10000):
53 """
54 Sample a number read lines in infile and write the output_over_time in output_file
55 If the file contains several runids the function will sample proportionally to the
56 * infile: STR
57 Path to a sequencing_summary input file
58 * outfile: STR (default None)
59 Path to a sequencing_summary output file. If not given, will return a dataframe instead
60 * n_seq: STR (default 10000)
61 Overall number of sequence lines to sample
62 """
63 df = pd.read_csv(infile, sep ="\t")
64 df.dropna (inplace=True)
65 total = len(df)
66 print ("{} sequences".format(total))
67
68 l = []
69 for runid, runid_df in df.groupby("run_id", sort=False):
70 n_to_sample = int (round (len (runid_df)/total*n_seq, 0))
71 if n_to_sample == 0:
72 n_to_sample=1
73 print ("{} = {} seq, to sample = {}".format (runid, len(runid_df), n_to_sample))
74 sdf = runid_df.sample(n_to_sample)
75 sdf.sort_values("start_time", inplace=True)
76 l.append(sdf)
77
78 df = pd.concat(l)
79 df.reset_index(inplace=True, drop=True)
80 if outfile:
81 if outfile.endswith("gz"):
82 df.to_csv(outfile, index=False, sep="\t", compression="gzip")
83 else:
84 df.to_csv(outfile, index=False, sep="\t", compression=None)
85 else:
86 return df
87
88 def dict_to_str (c, prefix="\t", suffix="\n"):
89 """ Transform a dict to a tabulated str """
90 m = ""
91 if type(c) == Counter:
92 for i, j in c.most_common():
93 m += "{}{}: {:,}{}".format(prefix, i, j, suffix)
94 else:
95 for i, j in c.items():
96 m += "{}{}: {}{}".format(prefix, i, j, suffix)
97 return m
98
99 def recursive_file_gen (dir, ext):
100 """
101 create a generator listing all files with a particular extension in a folder arborescence
102 The recursivity is broken when at least 1 file with a particular extenssion is found.
103 """
104 # In the case where the folder is a file
105 if path.isdir(dir):
106
107 # If matching files in the folder
108 file_found=False
109 for fn in iglob (path.join(dir, "*."+ext)):
110 yield fn
111 file_found=True
112
113 # If no matching file go deeper until a leaf containing fast5 is found
114 if not file_found:
115 for item in listdir(dir):
116 for fn in recursive_file_gen (path.join(dir, item), ext):
117 yield fn
118
119 def get_logger (name=None, verbose=False, quiet=False):
120 """Set logger to appropriate log level"""
121
122 logging.basicConfig(format='%(message)s')
123 logger = logging.getLogger(name)
124
125 # Define overall verbose level
126 if verbose:
127 logger.setLevel(logging.DEBUG)
128 elif quiet:
129 logger.setLevel(logging.WARNING)
130 else:
131 logger.setLevel(logging.INFO)
132
133 return logger
134
135 def doc_func (func):
136 """Parse the function description string"""
137
138 docstr_list = []
139 for l in inspect.getdoc(func).split("\n"):
140 l = l.strip()
141 if l:
142 if l.startswith("*"):
143 break
144 else:
145 docstr_list.append(l)
146
147 return " ".join(docstr_list)
148
149 def make_arg_dict (func):
150 """Parse the arguments default value, type and doc"""
151
152 # Init method for classes
153 if inspect.isclass(func):
154 func = func.__init__
155
156 if inspect.isfunction(func) or inspect.ismethod(func):
157 # Parse arguments default values and annotations
158 d = OrderedDict()
159 for name, p in inspect.signature(func).parameters.items():
160 if p.name not in ["self","cls"]: # Object stuff. Does not make sense to include in doc
161 d[name] = OrderedDict()
162 if name not in ["kwargs","args"]: # Include but skip default required and type
163 # Get Annotation
164 if p.annotation != inspect._empty:
165 d[name]["type"] = p.annotation
166 # Get default value if available
167 if p.default == inspect._empty:
168 d[name]["required"] = True
169 else:
170 d[name]["default"] = p.default
171
172 # Parse the docstring in a dict
173 docstr_dict = OrderedDict()
174 lab=None
175 for l in inspect.getdoc(func).split("\n"):
176 l = l.strip()
177 if l:
178 if l.startswith("*"):
179 lab = l[1:].strip()
180 docstr_dict[lab] = []
181 elif lab:
182 docstr_dict[lab].append(l)
183
184 # Concatenate and copy doc in main dict
185 for name in d.keys():
186 if name in docstr_dict:
187 d[name]["help"] = " ".join(docstr_dict[name])
188 return d
189
190 def arg_opt (func, arg, **kwargs):
191 """Get options corresponding to argument name and deal with special cases"""
192 arg_dict = make_arg_dict(func)[arg]
193
194 if "default" in arg_dict and "help" in arg_dict:
195 arg_dict["help"] += " (default: %(default)s)"
196
197 if "type" in arg_dict and "help" in arg_dict:
198 arg_dict["help"] += " [%(type)s]"
199
200 # Special case for boolean args
201 if arg_dict["type"] == bool:
202 if arg_dict["default"] is False:
203 arg_dict["action"] = 'store_true'
204 del arg_dict["type"]
205 elif arg_dict["default"] is True:
206 arg_dict["action"] = 'store_false'
207 del arg_dict["type"]
208
209 # Special case for lists args
210 elif arg_dict["type"] == list:
211 arg_dict["nargs"]='*'
212
213 return arg_dict
214
215 def jhelp (f:"python function or method"):
216 """
217 Display a Markdown pretty help message for functions and class methods (default __init__ is a class is passed)
218 jhelp also display default values and type annotations if available.
219 The docstring synthax should follow the same synthax as the one used for this function
220 * f
221 Function or method to display the help message for
222 """
223 # Private import as this is only needed if using jupyter
224 from IPython.core.display import display, Markdown
225
226 f_doc = doc_func(f)
227 arg_doc = make_arg_dict(f)
228
229 # Signature and function documentation
230 s = "**{}** ({})\n\n{}\n\n---\n\n".format(f.__name__, ", ".join(arg_doc.keys()), f_doc)
231
232 # Args doc
233 for arg_name, arg_val in arg_doc.items():
234 # Arg signature section
235 s+= "* **{}**".format(arg_name)
236 if "default" in arg_val:
237 if arg_val["default"] == "":
238 arg_val["default"] = "\"\""
239 s+= " (default: {})".format(arg_val["default"])
240 if "required" in arg_val:
241 s+= " (required)"
242 if "type" in arg_val:
243 if type(list) == type:
244 s+= " [{}]".format(arg_val["type"].__name__)
245 else:
246 s+= " [{}]".format(arg_val["type"])
247 s+="\n\n"
248 # Arg doc section
249 if "help" in arg_val:
250 s+= "{}\n\n".format(arg_val["help"])
251
252 # Display in Jupyter
253 display (Markdown(s))
254
255 def head (fp, n=10, sep="\t", comment=None):
256 """
257 Emulate linux head cmd. Handle gziped files and bam files
258 * fp
259 Path to the file to be parse.
260 * n
261 Number of lines to print starting from the begining of the file (Default 10)
262 """
263 line_list = []
264
265 # Get lines
266 try:
267 with open(fp) as fh:
268 line_num = 0
269 while (line_num < n):
270 l= next(fh).strip()
271 if comment and l.startswith(comment):
272 continue
273 if sep:
274 line_list.append (l.split(sep))
275 else:
276 line_list.append (l)
277 line_num+=1
278
279 except StopIteration:
280 pass
281
282 # Add padding if sep given
283 if sep:
284 try:
285 # Find longest elem per col
286 col_len_list = [0 for _ in range (len(line_list[0]))]
287 for ls in line_list:
288 for i in range (len(ls)):
289 len_col = len(ls[i])
290 if len_col > col_len_list[i]:
291 col_len_list[i] = len_col
292
293 # Add padding
294 line_list_tab = []
295 for ls in line_list:
296 s = ""
297 for i in range (len(ls)):
298 len_col = col_len_list[i]
299 len_cur_col = len(ls[i])
300 s += ls[i][0:len_col] + " "*(len_col-len_cur_col)+" "
301 line_list_tab.append(s)
302 line_list = line_list_tab
303
304 # Fall back to non tabulated display
305 except IndexError:
306 return head (fp=fp, n=n, sep=None)
307
308 for l in line_list:
309 print (l)
310 print()
311
312 def ls (dir_path):
313 for f in listdir(dir_path):
314 print(f)
315
316 def expand_file_names(fn, bam_check=False):
317 """"""
318 # Try to expand file name to list
319 if isinstance(fn, list):
320 if len(fn) ==1:
321 fn_list=glob(fn[0])
322 else:
323 fn_list = []
324 for f in fn:
325 fn_list.extend(glob(f))
326 elif isinstance(fn, str):
327 fn_list=glob(fn)
328 else:
329 raise pycoQCError ("{} has to be either a file or a regular expression or a list of files".format(fn))
330
331 # Verify that files are readable
332 if not fn_list:
333 raise pycoQCError("No files found in {}".format(fn))
334 for f in fn_list:
335 if not is_readable_file (f):
336 raise pycoQCError("Cannot read file {}".format(f))
337 # Extra checks for bam files
338 if bam_check:
339 with ps.AlignmentFile(f, "rb") as bam:
340 if not bam.has_index():
341 raise pycoQCError("No index found for bam file: {}. Please index with samtools index".format(f))
342 if not bam.header['HD']['SO'] == 'coordinate':
343 raise pycoQCError("Bam file not sorted: {}. Please sort with samtools sort".format(f))
344 return fn_list
345
346 def merge_files_to_df(fn_list):
347 """"""
348 if len(fn_list) == 1:
349 df = pd.read_csv(fn_list[0], sep ="\t")
350
351 else:
352 df_list = []
353 for fn in fn_list:
354 df_list.append (pd.read_csv(fn, sep ="\t"))
355 df = pd.concat(df_list, ignore_index=True, sort=False, join="inner")
356
357 if len(df) == 0:
358 raise pycoQCError ("No valid read found in input file")
359
360 return df
361
362 def mkdir (fn, exist_ok=False):
363 """ Create directory recursivelly. Raise IO error if path exist or if error at creation """
364 try:
365 makedirs (fn, exist_ok=exist_ok)
366 except:
367 raise pycoMethError ("Error creating output folder `{}`".format(fn))
368
369 def mkbasedir (fn, exist_ok=False):
370 """ Create directory for a given file recursivelly. Raise IO error if path exist or if error at creation """
371 dir_fn = path.dirname(fn)
372 if dir_fn:
373 mkdir (dir_fn, exist_ok=True)