Debian Codegraph @

cgecore/utility.py

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 #!/usr/bin/env python3
2 """ THIS MODULE CONTAINS ALL THE SHARED WRAPPER FUNCTIONS """
3 ################################################################################
4 # CGE FUNCTION MODULE #
5 ################################################################################
6 # This script is part of the CGE Pipeline structure
7 import sys, os, gzip, shutil, glob, re, json
8 from subprocess import Popen
9 from zipfile import ZipFile
10 from contextlib import closing
11
12 ############# CLASSES #############
13 class Debug():
14 """ Debug object, keeps track of all debug related matters, and provides easy
15 access to logging debug text
16
17 USAGE
18 import os, sys
19 debug = Debug()
20 debug.setup(debug=True, logfile=None, stdout=None, stderr=None)
21 debug.print_out('hello')
22 debug.log_no_newline('Oh')
23 debug.log_no_newline(' my')
24 debug.log(' god!')
25 # The graceful exit is only meant to be used with the integrated CGE platform
26 debug.graceful_exit('error message')
27 IMPORTING THE DEBUG OBJECT
28 from cge.utility import debug
29 """
30 def __init__(self):
31 """ """
32 self.debug = False
33 self.logfile = sys.stderr
34 self.stdout = sys.stdout
35 self.stderr = sys.stderr
36 self.caught_error = None
37 def setup(self, debug=None, logfile=None, stdout=None, stderr=None):
38 """ """
39 if debug is not None: self.debug = debug
40 if logfile is not None: self.logfile = logfile
41 if stdout is not None: self.stdout = stdout
42 if stderr is not None: self.stderr = stderr
43 def print_out(self, *lst):
44 """ Print list of strings to the predefined stdout. """
45 self.print2file(self.stdout, True, True, *lst)
46 def print_err(self, *lst):
47 """ Print list of strings to the predefined stdout. """
48 self.print2file(self.stderr, False, True, *lst)
49 def print2file(self, logfile, print2screen, addLineFeed, *lst):
50 """ This function prints to the screen and logs to a file, all the strings
51 given.
52 # print2screen eg. True, *lst is a commaseparated list of strings
53 """
54 if addLineFeed:
55 linefeed = '\n'
56 else: linefeed = ''
57 if print2screen: print(linefeed.join(str(string) for string in lst))
58 try: file_instance = isinstance(logfile, file)
59 except NameError as e:
60 from io import IOBase
61 try: file_instance = isinstance(logfile, IOBase)
62 except: raise e
63 if file_instance:
64 logfile.write(linefeed.join(str(string) for string in lst) + linefeed)
65 elif isinstance(logfile, str) and os.path.exists(logfile):
66 with open_(logfile, 'a') as f:
67 f.write(linefeed.join(str(string) for string in lst) + linefeed)
68 elif not print2screen: # Print to screen if there is no outputfile
69 print(linefeed.join(str(string) for string in lst))
70 def log(self, *lst):
71 """ Print list of strings to the predefined logfile if debug is set. and
72 sets the caught_error message if an error is found
73 """
74 self.print2file(self.logfile, self.debug, True, *lst)
75 if 'Error' in '\n'.join([str(x) for x in lst]):
76 self.caught_error = '\n'.join([str(x) for x in lst])
77 def log_no_newline(self, msg):
78 """ print the message to the predefined log file without newline """
79 self.print2file(self.logfile, False, False, msg)
80 def graceful_exit(self, msg):
81 """ This function Tries to update the MSQL database before exiting. """
82 # Print stored errors to stderr
83 if self.caught_error:
84 self.print2file(self.stderr, False, False, self.caught_error)
85 # Kill process with error message
86 self.log(msg)
87 sys.exit(1)
88
89 class adv_dict(dict):
90 """ This class expands on the dictionary class by adding the gettree class
91 method.
92 """
93 def get_tree(self, list_of_keys):
94 """ gettree will extract the value from a nested tree
95
96 INPUT
97 list_of_keys: a list of keys ie. ['key1', 'key2']
98 USAGE
99 >>> # Access the value for key2 within the nested dictionary
100 >>> adv_dict({'key1': {'key2': 'value'}}).gettree(['key1', 'key2'])
101 'value'
102 """
103 cur_obj = self
104 for key in list_of_keys:
105 cur_obj = cur_obj.get(key)
106 if not cur_obj: break
107 return cur_obj
108 def invert(self):
109 ''' Return inverse mapping of dictionary with sorted values.
110 USAGE
111 >>> # Switch the keys and values
112 >>> adv_dict({
113 ... 'A': [1, 2, 3],
114 ... 'B': [4, 2],
115 ... 'C': [1, 4],
116 ... }).invert()
117 {1: ['A', 'C'], 2: ['A', 'B'], 3: ['A'], 4: ['B', 'C']}
118 '''
119 inv_map = {}
120 for k, v in self.items():
121 if sys.version_info < (3, 0):
122 acceptable_v_instance = isinstance(v, (str, int, float, long))
123 else:
124 acceptable_v_instance = isinstance(v, (str, int, float))
125 if acceptable_v_instance: v = [v]
126 elif not isinstance(v, list):
127 raise Exception('Error: Non supported value format! Values may only'
128 ' be numerical, strings, or lists of numbers and '
129 'strings.')
130 for val in v:
131 inv_map[val] = inv_map.get(val, [])
132 inv_map[val].append(k)
133 inv_map[val].sort()
134 return inv_map
135
136 class Reg:
137 """
138 NAME: Reg - Extended Regular Expression Handler
139 AUTHOR: Martin Thomsen
140 DESCRIPTION:
141 This class enables a simplistic usage of regular expression to get
142 contained groups in a match statement. But it also allows to do some of
143 the normal re call, such as findall and sub.
144 DEPENDENCIES:
145 re (regular expression module)
146 USAGE:
147 >>> import re
148 >>> RegEx = Reg(pattern, flag)
149 >>> if RegEx.match(string):
150 >>> RegEx.getgroup(index)
151 EXAMPLE:
152 >>> RegEx = Reg('[^a]*(a)[^b]*(b)[^Y]*(Y)(a)?', 'I')
153 >>> if RegEx.match('aBcdefgHIJKLmnOpqrstuvwxyz'):
154 ... print(RegEx.getgroup(0), # index=0 -> full match
155 ... RegEx.getgroup(1),
156 ... RegEx.getgroup(2),
157 ... RegEx.getgroup(3),
158 ... RegEx.getgroup(4))
159 ...
160 ('aBcdefgHIJKLmnOpqrstuvwxy', 'a', 'B', 'y', None)
161 # NIFTY SUBSTITUTION LOOP
162 >>> string = 'There are {%=count%} {%=animal%} on the {%=location%}!'
163 >>> # Dictionary containing place-holders and values
164 ... # (make sure all placeholders in the string is included!)
165 ... d = { 'count': 5, 'animal': 'cows', 'location': 'Battle Field' }
166 >>> # RE Object which matches place-holders in the string
167 ... tmpPH = Reg('\{\%\=(\w+)\%\}', 'I')
168 >>> # substitute all placeholders
169 ... while tmpPH.match(string): string = tmpPH.sub(str(d[tmpPH.getgroup(1)]), string, 1)
170 ...
171 >>> print(string)
172 There are 5 cows on the Battle Field!
173 """
174 def __init__(self, pattern, *flags):
175 sd = {'T': 1, 'I': 2, 'L':4,'M':8,'S':16,'U':32,'X':64}
176 try:
177 flag = sum([sd[f] if f in sd else int(f) for f in set(flags)]) if flags else 0
178 except:
179 for f in flags:
180 if not isinstance(f, int) and not f in sd:
181 raise Exception("Error: Unrecognised flag argument '%s' for Reg call."%f)
182 flag=0
183 if flag: self.re = re.compile(pattern, flag)
184 else: self.re = re.compile(pattern)
185 self.matches = None
186 def sub(self, replace, string, count=0):
187 """ returns new string where the matching cases (limited by the count) in
188 the string is replaced. """
189 return self.re.sub(replace, string, count)
190 def find_all(self, s):
191 """ Finds all matches in the string and returns them in a tuple. """
192 return self.re.findall(s)
193 def match(self, s):
194 """ Matches the string to the stored regular expression, and stores all
195 groups in mathches. Returns False on negative match. """
196 self.matches = self.re.search(s)
197 return self.matches
198 def get_group(self, x):
199 """ Returns requested subgroup. """
200 return self.matches.group(x)
201 def get_groups(self):
202 """ Returns all subgroups. """
203 return self.matches.groups()
204
205 class REGroup():
206 """ Regular Expression group object
207
208 This class simplyfies the use of groups for the Sort2Groups function.
209 """
210 def __init__(self, pattern, flags=''):
211 self.re = Reg(pattern, flags)
212 self.list = []
213 def match(self, s):
214 """ Matching the pattern to the input string, returns True/False and
215 saves the matched string in the internal list
216 """
217 if self.re.match(s):
218 self.list.append(s)
219 return True
220 else: return False
221
222 ############# ITERATORS #############
223 def seqs_from_file(filename, exit_on_err=False, return_qual=False):
224 """Extract sequences from a file
225
226 Name:
227 seqs_from_file
228 Author(s):
229 Martin C F Thomsen
230 Date:
231 18 Jul 2013
232 Description:
233 Iterator which extract sequence data from the input file
234 Args:
235 filename: string which contain a path to the input file
236 Supported Formats:
237 fasta, fastq
238
239 USAGE:
240 >>> import os, sys
241 >>> # Create fasta test file
242 >>> file_content = ('>head1 desc1\nthis_is_seq_1\n>head2 desc2\n'
243 'this_is_seq_2\n>head3 desc3\nthis_is_seq_3\n')
244 >>> with open_('test.fsa', 'w') as f: f.write(file_content)
245 >>> # Parse and print the fasta file
246 >>> for seq, name, desc in SeqsFromFile('test.fsa'):
247 ... print ">%s %s\n%s"%(name, desc, seq)
248 ...
249 >head1 desc1
250 this_is_seq_1
251 >head2 desc2
252 this_is_seq_2
253 >head3 desc3
254 this_is_seq_3
255 """
256 # VALIDATE INPUT
257 if not isinstance(filename, str):
258 msg = 'Filename has to be a string.'
259 if exit_on_err:
260 sys.stderr.write('Error: %s\n'%msg)
261 sys.exit(1)
262 else: raise IOError(msg)
263 if not os.path.exists(filename):
264 msg = 'File "%s" does not exist.'%filename
265 if exit_on_err:
266 sys.stderr.write('Error: %s\n'%msg)
267 sys.exit(1)
268 else: raise IOError(msg)
269
270 # EXTRACT DATA
271 with open_(filename,"rt") as f:
272 query_seq_segments = []
273 seq, name, desc, qual = '', '', '', ''
274 add_segment = query_seq_segments.append
275 for l in f:
276 if len(l.strip()) == 0: continue
277 #sys.stderr.write("%s\n"%line)
278 fields=l.strip().split()
279 if l.startswith(">"):
280 # FASTA HEADER FOUND
281 if query_seq_segments != []:
282 # YIELD SEQUENCE AND RESET
283 seq = ''.join(query_seq_segments)
284 yield (seq, name, desc)
285 seq, name, desc = '', '', ''
286 del query_seq_segments[:]
287 name = fields[0][1:]
288 desc = ' '.join(fields[1:])
289
290 elif l.startswith("@"):
291 # FASTQ HEADER FOUND
292 name = fields[0][1:]
293 desc = ' '.join(fields[1:])
294 try:
295 # EXTRACT FASTQ SEQUENCE
296 seq = next(f).strip().split()[0]
297 # SKIP SECOND HEADER LINE AND QUALITY SCORES
298 l = next(f)
299 qual = next(f).strip() # Qualities
300 except:
301 break
302 else:
303 # YIELD SEQUENCE AND RESET
304 if return_qual:
305 yield (seq, qual, name, desc)
306 else:
307 yield (seq, name, desc)
308 seq, name, desc, qual = '', '', '', ''
309
310 elif len(fields[0])>0:
311 # EXTRACT FASTA SEQUENCE
312 add_segment(fields[0])
313
314 # CHECK FOR LAST FASTA SEQUENCE
315 if query_seq_segments != []:
316 # YIELD SEQUENCE
317 seq = ''.join(query_seq_segments)
318 yield (seq, name, desc)
319
320 ############# FUNCTIONS #############
321 def open_(filename, mode=None, compresslevel=9):
322 """Switch for both open() and gzip.open().
323
324 Determines if the file is normal or gzipped by looking at the file
325 extension.
326
327 The filename argument is required; mode defaults to 'rb' for gzip and 'r'
328 for normal and compresslevel defaults to 9 for gzip.
329
330 >>> import gzip
331 >>> from contextlib import closing
332 >>> with open_(filename) as f:
333 ... f.read()
334 """
335 if filename[-3:] == '.gz':
336 if mode is None: mode = 'rt'
337 return closing(gzip.open(filename, mode, compresslevel))
338 else:
339 if mode is None: mode = 'r'
340 return open(filename, mode)
341
342 def load_json(json_object):
343 ''' Load json from file or file name '''
344 content = None
345 if isinstance(json_object, str) and os.path.exists(json_object):
346 with open_(json_object) as f:
347 try:
348 content = json.load(f)
349 except Exception as e:
350 debug.log("Warning: Content of '%s' file is not json."%f.name)
351 elif hasattr(json_object, 'read'):
352 try:
353 content = json.load(json_object)
354 except Exception as e:
355 debug.log("Warning: Content of '%s' file is not json."%json_object.name)
356 else:
357 debug.log("%s\nWarning: Object type invalid!"%json_object)
358 return content
359
360 def sort2groups(array, gpat=['_R1','_R2']):
361 """ Sort an array of strings to groups by patterns """
362 groups = [REGroup(gp) for gp in gpat]
363 unmatched = []
364 for item in array:
365 matched = False
366 for m in groups:
367 if m.match(item):
368 matched = True
369 break
370 if not matched: unmatched.append(item)
371 return [sorted(m.list) for m in groups], sorted(unmatched)
372
373 def sort_and_distribute(array, splits=2):
374 """ Sort an array of strings to groups by alphabetically continuous
375 distribution
376 """
377 if not isinstance(array, (list,tuple)): raise TypeError("array must be a list")
378 if not isinstance(splits, int): raise TypeError("splits must be an integer")
379 remaining = sorted(array)
380 if sys.version_info < (3, 0):
381 myrange = xrange(splits)
382 else:
383 myrange = range(splits)
384 groups = [[] for i in myrange]
385 while len(remaining) > 0:
386 for i in myrange:
387 if len(remaining) > 0: groups[i].append(remaining.pop(0))
388 return groups
389
390 def mkpath(filepath, permissions=0o777):
391 """ This function executes a mkdir command for filepath and with permissions
392 (octal number with leading 0 or string only)
393 # eg. mkpath("path/to/file", "0o775")
394 """
395 # Converting string of octal to integer, if string is given.
396 if isinstance(permissions, str):
397 permissions = sum([int(x)*8**i for i,x in enumerate(reversed(permissions))])
398 # Creating directory
399 if not os.path.exists(filepath):
400 debug.log("Creating Directory %s (permissions: %s)"%(
401 filepath, permissions))
402 os.makedirs(filepath, permissions)
403 else:
404 debug.log("Warning: The directory "+ filepath +" already exists")
405 return filepath
406
407 def create_zip_dir(zipfile_path, *file_list):
408 """ This function creates a zipfile located in zipFilePath with the files in
409 the file list
410 # fileList can be both a comma separated list or an array
411 """
412 try:
413 if isinstance(file_list, (list, tuple)): #unfolding list of list or tuple
414 if len(file_list) == 1:
415 if isinstance(file_list[0], (list, tuple)): file_list = file_list[0]
416 #converting string to iterable list
417 if isinstance(file_list, str): file_list = [file_list]
418 if file_list:
419 with ZipFile(zipfile_path, 'w') as zf:
420 for cur_file in file_list:
421 if '/' in cur_file:
422 os.chdir('/'.join(cur_file.split('/')[:-1]))
423 elif '/' in zipfile_path:
424 os.chdir('/'.join(zipfile_path.split('/')[:-1]))
425 zf.write(cur_file.split('/')[-1])
426 else:
427 debug.log('Error: No Files in list!',zipfile_path+' was not created!')
428 except Exception as e:
429 debug.log('Error: Could not create zip dir! argtype: '+
430 str(type(file_list)), "FileList: "+ str(file_list),
431 "Errormessage: "+ str(e))
432
433 def file_zipper(root_dir):
434 """ This function will zip the files created in the runroot directory and
435 subdirectories """
436 # FINDING AND ZIPPING UNZIPPED FILES
437 for root, dirs, files in os.walk(root_dir, topdown=False):
438 if root != "":
439 if root[-1] != '/': root += '/'
440 for current_file in files:
441 filepath = "%s/%s"%(root, current_file)
442 try:
443 file_size = os.path.getsize(filepath)
444 except Exception as e:
445 file_size = 0
446 debug.log('Error: file_zipper failed to zip following file '+filepath, e)
447 # Excluding small files, gzipped files and links
448 if ( file_size > 50
449 and current_file[-3:] != ".gz"
450 and not os.path.islink(filepath)
451 ):
452 if current_file[-4:] == ".zip":
453 # Unzip file
454 ec = Popen('unzip -qq "%s" -d %s > /dev/null 2>&1'%(filepath, root), shell=True).wait()
455 if ec > 0:
456 debug.log('Error: fileZipper failed to unzip following file %s'%filepath)
457 continue
458 else:
459 ec = Popen('rm -f "%s" > /dev/null 2>&1'%(filepath), shell=True).wait()
460 if ec > 0: debug.log('Error: fileZipper failed to delete the original zip file (%s)'%filepath)
461 filepath = filepath[:-4]
462 # Saving a gzipped version
463 with open_(filepath, 'rb') as f, open_(filepath+".gz", 'wb', 9) as gz:
464 gz.writelines(f)
465 # Deleting old (non-zipped) file
466 try: os.remove(filepath)
467 except OSError as e:
468 debug.log(("WARNING! The file %s could not be "
469 "removed!\n%s")%(current_file, e))
470
471 def file_unzipper(directory):
472 """ This function will unzip all files in the runroot directory and
473 subdirectories
474 """
475 debug.log("Unzipping directory (%s)..."%directory)
476 #FINDING AND UNZIPPING ZIPPED FILES
477 for root, dirs, files in os.walk(directory, topdown=False):
478 if root != "":
479 orig_dir = os.getcwd()
480 os.chdir(directory)
481 Popen('gunzip -q -f *.gz > /dev/null 2>&1', shell=True).wait()
482 Popen('unzip -qq -o "*.zip" > /dev/null 2>&1', shell=True).wait()
483 Popen('rm -f *.zip > /dev/null 2>&1', shell=True).wait()
484 os.chdir(orig_dir)
485
486 def move_file(src, dst):
487 """ this function will simply move the file from the source path to the dest
488 path given as input
489 """
490 # Sanity checkpoint
491 src = re.sub('[^\w/\-\.\*]', '', src)
492 dst = re.sub('[^\w/\-\.\*]', '', dst)
493 if len(re.sub('[\W]', '', src)) < 5 or len(re.sub('[\W]', '', dst)) < 5:
494 debug.log("Error: Moving file failed. Provided paths are invalid! src='%s' dst='%s'"%(src, dst))
495 else:
496 # Check destination
497 check = False
498 if dst[-1] == '/':
499 if os.path.exists(dst):
500 check = True # Valid Dir
501 else:
502 debug.log("Error: Moving file failed. Destination directory does not exist (%s)"%(dst)) #DEBUG
503 elif os.path.exists(dst):
504 if os.path.isdir(dst):
505 check = True # Valid Dir
506 dst += '/' # Add missing slash
507 else:
508 debug.log("Error: Moving file failed. %s exists!"%dst)
509 elif os.path.exists(os.path.dirname(dst)):
510 check = True # Valid file path
511 else:
512 debug.log("Error: Moving file failed. %s is an invalid distination!"%dst)
513 if check:
514 # Check source
515 files = glob.glob(src)
516 if len(files) != 0:
517 debug.log("Moving File(s)...", "Move from %s"%src, "to %s"%dst)
518 for file_ in files:
519 # Check if file contains invalid symbols:
520 invalid_chars = re.findall('[^\w/\-\.\*]', os.path.basename(file_))
521 if invalid_chars:
522 debug.graceful_exit(("Error: File %s contains invalid "
523 "characters %s!"
524 )%(os.path.basename(file_), invalid_chars))
525 continue
526 # Check file exists
527 if os.path.isfile(file_):
528 debug.log("Moving file: %s"%file_)
529 shutil.move(file_, dst)
530 else:
531 debug.log("Error: Moving file failed. %s is not a regular file!"%file_)
532 else: debug.log("Error: Moving file failed. No files were found! (%s)"%src)
533
534 def copy_file(src, dst, ignore=None):
535 """ this function will simply copy the file from the source path to the dest
536 path given as input
537 """
538 # Sanity checkpoint
539 src = re.sub('[^\w/\-\.\*]', '', src)
540 dst = re.sub('[^\w/\-\.\*]', '', dst)
541 if len(re.sub('[\W]', '', src)) < 5 or len(re.sub('[\W]', '', dst)) < 5:
542 debug.log("Error: Copying file failed. Provided paths are invalid! src='%s' dst='%s'"%(src, dst))
543 else:
544 # Check destination
545 check = False
546 if dst[-1] == '/':
547 if os.path.exists(dst):
548 check = True # Valid Dir
549 else:
550 debug.log("Error: Copying file failed. Destination directory does not exist (%s)"%(dst)) #DEBUG
551 elif os.path.exists(dst):
552 if os.path.isdir(dst):
553 check = True # Valid Dir
554 dst += '/' # Add missing slash
555 else:
556 debug.log("Error: Copying file failed. %s exists!"%dst)
557 elif os.path.exists(os.path.dirname(dst)):
558 check = True # Valid file path
559 else:
560 debug.log("Error: Copying file failed. %s is an invalid distination!"%dst)
561 if check:
562 # Check source
563 files = glob.glob(src)
564 if ignore is not None: files = [fil for fil in files if not ignore in fil]
565 if len(files) != 0:
566 debug.log("Copying File(s)...", "Copy from %s"%src, "to %s"%dst) #DEBUG
567 for file_ in files:
568 # Check file exists
569 if os.path.isfile(file_):
570 debug.log("Copying file: %s"%file_) #DEBUG
571 shutil.copy(file_, dst)
572 else:
573 debug.log("Error: Copying file failed. %s is not a regular file!"%file_) #DEBUG
574 else: debug.log("Error: Copying file failed. No files were found! (%s)"%src) #DEBUG
575
576 def copy_dir(src, dst):
577 """ this function will simply copy the file from the source path to the dest
578 path given as input
579 """
580 try:
581 debug.log("copy dir from "+ src, "to "+ dst)
582 shutil.copytree(src, dst)
583 except Exception as e:
584 debug.log("Error: happened while copying!\n%s\n"%e)
585
586 # Initiate Shared Global Objects
587 debug = Debug()