Debian Codegraph @

pytools/lib/rqc_utility.py

raw symbols SCIP
1 #!/usr/bin/env python
2
3 import os
4 import sys
5 import time # sleep
6 import re # pod_path
7
8 srcDir = os.path.dirname(__file__)
9 sys.path.append(os.path.join(srcDir, '../assemblyqc/lib'))
10
11 # from assemblyqc_constants import *
12 from common import *
13 from rqc_constants import *
14 from os_utility import run_sh_command, make_dir_p
15 from html_utility import html_link
16
17
18 '''
19 Run Stephan Trong's blast plus wrapper instead of megablast.
20 It specifies default parameters for megablast and megablast is the default aligner.
21 The dbs for which run_blastplus is called do not have masking and are not really indexed with makembindex.
22 TODO: Run all databases in parallel.
23 Use the same blastn parameters as used in run_blastn, which are set as follows
24 defaults = " -num_threads " + str(num_threads) + " " + RQCBlast.BLASTN_DEFAULTS;
25 '''
26 # def run_blastplus(queryFastaFile, db, outputPath, log, num_threads=16):
27 # REMOVED! 09092016
28
29
30 def get_cat_cmd(seqUnitName, log):
31 zcatCmd = ""
32
33 if seqUnitName.endswith(".bz2"):
34 zcatCmd = RQCCommands.BZCAT_CMD
35 elif seqUnitName.endswith(".gz"):
36 zcatCmd = RQCCommands.ZCAT_CMD
37 elif seqUnitName.endswith(".fastq") or seqUnitName.endswith(".fa"):
38 zcatCmd = RQCCommands.CAT_CMD
39 else:
40 log.error("source_fastq should be either bzipped or gzipped fastq. " + str(seqUnitName))
41 return zcatCmd, RQCExitCodes.JGI_FAILURE
42
43
44 return zcatCmd, RQCExitCodes.JGI_SUCCESS
45
46
47
48 """
49 Localize specified file to /scratch/rqc
50 - Bryce added the file check and wait
51
52 @param: fileName: full path to file
53 @param: log
54
55 sulsj ([email protected])
56 """
57 def localize_file(fileNameFullPath, log):
58 done = 0
59 loopCount = 0
60
61 while done == 0:
62 loopCount += 1
63
64 if os.path.isfile(fileNameFullPath):
65 done = 1 # congratulations! The file system seems to be working for the moment
66 else:
67 sleepTime = 60 * loopCount
68 log.error("Filename doesn't exist on the system: %s, sleeping for %s seconds.", fileNameFullPath, sleepTime)
69 time.sleep(sleepTime)
70
71 if loopCount > 3:
72 done = 1 # probably failed
73
74 if not os.path.isfile(fileNameFullPath):
75 return None
76
77 destinationPath = "/scratch/rqc/localized-file"
78 if not os.path.isdir(destinationPath):
79 # make_dir_p(destinationPath)
80 _, _, exitCode = run_sh_command("mkdir -p /scratch/rqc/localized-file && chmod 777 /scratch/rqc/localized-file", True, log, True)
81 assert exitCode == 0
82
83 fileName = safe_basename(fileNameFullPath, log)[0]
84 localizeCmd = "rsync -av --omit-dir-times --no-perms " + fileNameFullPath + " " + os.path.join(destinationPath, fileName)
85
86 _, _, exitCode = run_sh_command(localizeCmd, True, log, True)
87
88 localizedFileNameFullPath = None
89
90 if exitCode == RQCExitCodes.JGI_SUCCESS:
91 localizedFileNameFullPath = os.path.join(destinationPath, fileName)
92 log.info("File localization completed for %s" % (fileName))
93 else:
94 localizedFileNameFullPath = None
95 log.error("File localization failed for %s" % (fileName))
96
97
98 return localizedFileNameFullPath
99
100
101 # def localize_dir(dbFileOrDirName, log):
102 # REMOVED! 09092016
103
104
105 """
106 New localize_dir
107
108 Revisions
109 08022017 Enabled burst buffer on cori
110 08072017 Added support for persistent bbuffer on cori for localized NCBI databases
111
112 """
113 def localize_dir2(db, log, bbuffer=None):
114 safeBaseName, exitCode = safe_basename(db, log)
115 safeDirName, exitCode = safe_dirname(db, log)
116 targetScratchDir = None
117
118 nerscDb = "/scratch/blastdb/global/dna/shared/rqc/ref_databases/ncbi/CURRENT"
119 # nerscDb = "/" ## temporarily do not use NERSC db
120 ## nerscDbPersistentBBuffer = "/var/opt/cray/dws/mounts/batch/NCBI_DB_striped_scratch/ncbi"
121
122 ## check if persistent burst buffer is ready
123 if bbuffer is None and "DW_PERSISTENT_STRIPED_NCBI_DB" in os.environ and os.environ['DW_PERSISTENT_STRIPED_NCBI_DB'] is not None:
124 nerscDb = os.path.join(os.environ['DW_PERSISTENT_STRIPED_NCBI_DB'], "ncbi")
125
126 else:
127 targetScratchDir = "/scratch/rqc"
128
129 if bbuffer is not None:
130 if not os.path.isdir(bbuffer):
131 log.error("Burst Buffer does not initiated: %s", bbuffer)
132 return None, RQCExitCodes.JGI_FAILURE
133 else:
134 targetScratchDir = bbuffer
135 log.info("Localization will use Burst Buffer location at %s", targetScratchDir)
136
137 elif not os.path.isdir(targetScratchDir):
138 _, _, exitCode = run_sh_command("mkdir %s && chmod 777 %s" % (targetScratchDir, targetScratchDir), True, log, True)
139 assert exitCode == 0
140
141 rsyncOption = ""
142 src = db
143 dest = ""
144
145 ## For
146 # GREEN_GENES = "/global/dna/shared/rqc/ref_databases/misc/CURRENT/green_genes16s.insa_gg16S.fasta"
147 # LSU_REF = "/global/dna/shared/rqc/ref_databases/misc/CURRENT/LSURef_115_tax_silva.fasta"
148 # SSU_REF = "/global/dna/shared/rqc/ref_databases/misc/CURRENT/SSURef_NR99_115_tax_silva.fasta"
149 # LSSU_REF = "/global/dna/shared/rqc/ref_databases/misc/CURRENT/LSSURef_115_tax_silva.fasta"
150 # CONTAMINANTS = "/global/dna/shared/rqc/ref_databases/misc/CURRENT/JGIContaminants.fa"
151 # COLLAB16S = "/global/dna/shared/rqc/ref_databases/misc/CURRENT/collab16s.fa"
152 if db.endswith(".fa") or db.endswith(".fasta"):
153 rsyncOption = "--include '*.n??' --exclude '*.fa' --exclude '*.fasta' --exclude '%s' --exclude '*.log'" % (safeBaseName)
154 src = db + ".n??"
155 dest = os.path.join(targetScratchDir, safeBaseName)
156 blastDb = dest
157 if os.path.isfile(dest): ## just in case for the file name already exists
158 rmCmd = "rm -rf %s" % (dest)
159 run_sh_command(rmCmd, True, log, True)
160
161 ## For
162 # NT_maskedYindexedN_BB = "/global/dna/shared/rqc/ref_databases/ncbi/CURRENT/nt/bbtools_dedupe_mask/nt_bbdedupe_bbmasked_formatted"
163 elif db.endswith("nt_bbdedupe_bbmasked_formatted"):
164 if os.path.isdir(os.path.join(nerscDb, "nt/bbtools_dedupe_mask")):
165 blastDb = os.path.join(nerscDb, "nt/bbtools_dedupe_mask")
166 log.info("NERSC NCBI Database found: %s" % (blastDb))
167 return blastDb, RQCExitCodes.JGI_SUCCESS
168
169 rsyncOption = "--include '*.n??' --exclude '*.fna' --exclude 'nt_bbdedupe_bbmasked_formatted' --exclude '*.log'"
170 src = safeDirName + '/'
171 dest = os.path.join(targetScratchDir, safeBaseName)
172 blastDb = dest
173
174 ## For
175 # NR = "/global/dna/shared/rqc/ref_databases/ncbi/CURRENT/nr/nr"
176 # REFSEQ_ARCHAEA = "/global/dna/shared/rqc/ref_databases/ncbi/CURRENT/refseq.archaea/refseq.archaea"
177 # REFSEQ_BACTERIA = "/global/dna/shared/rqc/ref_databases/ncbi/CURRENT/refseq.bacteria/refseq.bacteria"
178 # REFSEQ_FUNGI = "/global/dna/shared/rqc/ref_databases/ncbi/CURRENT/refseq.fungi/refseq.fungi"
179 # REFSEQ_MITOCHONDRION = "/global/dna/shared/rqc/ref_databases/ncbi/CURRENT/refseq.mitochondrion/refseq.mitochondrion"
180 # REFSEQ_PLANT = "/global/dna/shared/rqc/ref_databases/ncbi/CURRENT/refseq.plant/refseq.plant"
181 # REFSEQ_PLASMID = "/global/dna/shared/rqc/ref_databases/ncbi/CURRENT/refseq.plasmid/refseq.plasmid"
182 # REFSEQ_PLASTID = "/global/dna/shared/rqc/ref_databases/ncbi/CURRENT/refseq.plastid/refseq.plastid"
183 # REFSEQ_VIRAL = "/global/dna/shared/rqc/ref_databases/ncbi/CURRENT/refseq.viral/refseq.viral"
184 else:
185 if os.path.isdir(os.path.join(nerscDb, safeBaseName)):
186 blastDb = os.path.join(nerscDb, safeBaseName)
187 log.info("NERSC NCBI Database found: %s" % (blastDb))
188 return blastDb, RQCExitCodes.JGI_SUCCESS
189
190 rsyncOption = "--include '*.n??' --exclude '*.fna' --exclude '%s' --exclude '*.log'" % (safeBaseName)
191 src = safeDirName + '/'
192 dest = os.path.join(targetScratchDir, safeBaseName)
193 blastDb = os.path.join(dest, dest)
194
195
196 rsyncCmd = "rsync -av --omit-dir-times --no-perms %s %s %s" % (rsyncOption, src, dest)
197 dbDirNameLocalized, _, exitCode = run_sh_command(rsyncCmd, True, log, True)
198
199 if exitCode != 0:
200 log.error("rsync failed. Cannot localize " + str(db))
201 return dbDirNameLocalized, RQCExitCodes.JGI_FAILURE
202
203 else:
204 cmd = "chmod -f -R 777 %s" % (dest)
205 _, _, exitCode = run_sh_command(cmd, True, log)
206
207
208 return blastDb, RQCExitCodes.JGI_SUCCESS
209
210
211 def safe_dirname(pathName, log):
212 dirName = ""
213
214 if pathName is None:
215 return dirName, RQCExitCodes.JGI_FAILURE
216
217 dirName = os.path.dirname(pathName)
218
219 if dirName is None:
220 log.error("Could not get basename for " + str(pathName))
221 return dirName, RQCExitCodes.JGI_FAILURE
222
223 return dirName, RQCExitCodes.JGI_SUCCESS
224
225
226 def safe_basename(pathName, log):
227 baseName = ""
228
229 if pathName is None:
230 return baseName, RQCExitCodes.JGI_FAILURE
231
232 baseName = os.path.basename(pathName)
233
234 if baseName is None:
235 log.error("Could not get basename for " + str(pathName))
236 return baseName, RQCExitCodes.JGI_FAILURE
237
238 return baseName, RQCExitCodes.JGI_SUCCESS
239
240
241 ## ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
242 ## qsub functions
243
244 ## module load uge
245 def submit_qsub(qsub_opt, qsub_cmd, qsub_name, output_path, log):
246 job_id = 0
247 job_share = 150
248
249 cluster_project = "gentech-rqc.p"
250 qsub_path = os.path.join(output_path, "qsub")
251
252 if not os.path.isdir(qsub_path):
253 os.makedirs(qsub_path)
254
255 output_log = os.path.join(qsub_path, "qsub-%s.log" % qsub_name)
256
257 my_qsub = "qsub -b y -j y -m n -w e -terse -N %s -P %s -o %s -js %s %s '%s'" % (qsub_name, cluster_project, output_log, job_share, qsub_opt, qsub_cmd)
258 # append to qsub.txt
259
260 cmd = "module load uge;%s" % my_qsub
261 stdOut, stdErr, exitCode = run_sh_command(cmd, True, log)
262 post_mortem_cmd(cmd, exitCode, stdOut, stdErr, log)
263
264 if exitCode == 0:
265 job_id = int(stdOut.strip())
266
267 log.info("- cluster job id: %s", job_id)
268
269 if job_id > 0:
270 qsub_log = os.path.join(output_path, "qsub_list.txt")
271 fh = open(qsub_log, "a")
272 fh.write("%s,%s\n" % (job_id, "submitted"))
273 fh.close()
274
275 return job_id
276
277
278 ## watch jobs running on the cluster
279 def watch_cluster(output_path, log, sleep_time=300):
280 log.info("watch_cluster")
281
282 is_job_complete = "/usr/common/usg/bin/isjobcomplete.new" # + job_id = nice way to ask if job is done
283 qsub_log = os.path.join(output_path, "qsub_list.txt")
284
285 #sleep_time = 300 # check isjobrunning every xx seconds
286
287 hb_max = (180 * 3600) / sleep_time # total number of heartbeats before we give up, 180 hours worth of run time
288 #hb_max = 5 # temp
289
290 done = 0
291 hb_cnt = 0 # heartbeat count
292
293 if not os.path.isfile(qsub_log):
294 done = 1
295
296 while done == 0:
297
298 hb_cnt += 1
299 log.info("- heartbeat: %s", hb_cnt)
300
301 qsub_list = []
302
303
304 qsub_cnt = 0
305 qsub_complete = 0
306 qsub_err = 0
307 fh = open(qsub_log, "r")
308 for line in fh:
309
310 qsub_list.append(line.strip())
311 qsub_cnt += 1
312 fh.close()
313
314 fh = open(qsub_log, "w")
315
316
317 for qsub in qsub_list:
318
319 job_id, status = qsub.split(",")
320 new_status = status
321
322 if status in ("complete", "fail"):
323 continue
324 else:
325 cmd = "%s %s" % (is_job_complete, job_id)
326 stdOut, stdErr, exitCode = run_sh_command(cmd, True, log)
327 #post_mortem_cmd(cmd, exitCode, stdOut, stdErr, log)
328
329 running = "%s queued/running" % job_id
330 not_running = "%s not queued/running" % job_id
331 error_qw = "%s queued/running/error" % job_id
332
333 if stdOut.strip == running:
334 new_status = "running"
335
336 elif stdOut.strip() == not_running:
337 new_status = "complete" # might have failed
338 qsub_complete += 1
339
340 elif stdOut.strip() == error_qw:
341 new_status = "error"
342 qsub_err += 1
343
344 if stdOut.strip() == "not queued/running":
345 new_status = "complete"
346
347 fh.write("%s,%s\n" % (job_id, new_status))
348 log.info("- job_id: %s, status: %s", job_id, new_status)
349
350 fh.close()
351
352 qsub_running = qsub_cnt - (qsub_complete + qsub_err)
353 log.info("- job count: %s, running: %s, err: %s", qsub_cnt, qsub_running, qsub_err)
354
355 if qsub_cnt == (qsub_complete + qsub_err):
356 done = 1
357
358 if hb_cnt >= hb_max:
359 done = 1
360
361 if done == 0:
362 time.sleep(sleep_time)
363
364
365 '''
366 Open the file, count number of lines/hits
367 - skip header (#)
368
369 Used in sag.py and sag_decontam.py, ce.py and iso.py too
370 * out of memory when reading big files ...
371 '''
372 def get_blast_hit_count(blast_file):
373 hit_count = 0
374
375 if os.path.isfile(blast_file):
376 # if more than a gig we get a memory error doing this, even though its not supposed to cause a problem ...
377 # - maybe the hit_count var grows too big? no, not counting the hits still causes issues
378 if os.path.getsize(blast_file) < 100000000:
379 fh_blast = open(blast_file, "r")
380 for line in fh_blast:
381 if line.startswith("#"):
382 continue
383 hit_count += 1
384 fh_blast.close()
385 else:
386 hit_count = 9999
387 return hit_count
388
389
390 '''
391 Pads a string with 0's and splits into groups of 2
392 e.g. padStringPath(44) returns "00/00/00/44"
393
394 @param myString: string to pad
395 @return: padded string
396 '''
397
398 def pad_string_path(myString, padLength=8, depth=None):
399 myString = str(myString)
400 padLength = int(padLength)
401
402 if padLength > 8 or padLength <= 0:
403 padLength = 8
404
405 # left-pad with 0's
406 myString = myString.zfill(padLength)
407
408 # use re.findall function to split into pairs of strings
409 stringList = re.findall("..", myString)
410
411 # create ss/ss/ss/ss
412 if not depth:
413 padString = "/".join(stringList)
414 else:
415 padString = "/".join(stringList[:depth])
416
417 padString = padString + "/"
418
419 return padString
420
421 def get_dict_obj(sfile):
422 kvmap = {}
423 if os.path.isfile(sfile):
424 with open(sfile, 'r') as fh:
425 for line in fh:
426 line = line.strip()
427 if not line or line.startswith('#'):
428 continue
429
430 tks = line.strip().split('=')
431 if len(tks) == 2:
432 kvmap[tks[0].strip().lower()] = tks[1].strip()
433 return kvmap
434
435 # helper function
436 def pipeline_val(keyname, kwargs, stats, files=None, file_path_prefix=None):
437 keyname = keyname.lower()
438 form = kwargs.get('type')
439 if form == 'file' and files:
440 val = files.get(keyname)
441 if val:
442 if kwargs.get('filter') == 'base':
443 val = os.path.basename(val)
444 elif kwargs.get('filter') != 'full' and file_path_prefix and val.startswith(file_path_prefix): # make the file path relative to run dir
445 val = val[len(file_path_prefix)+1:]
446
447 if kwargs.get('filter') == 'link':
448 val = html_link(val, kwargs.get('label'))
449 elif stats:
450 val = stats.get(keyname, 'n.a.')
451 if val != 'n.a.':
452 if val.endswith('%'): # remove last "%"
453 val = val[:-1]
454 if form == 'bigint' or form == 'int':
455 try:
456 tmp = int(val)
457 if form == 'bigint':
458 val = format(tmp, ',') # e.g. 123,456,789
459 else:
460 val = tmp # int
461 except:
462 pass
463 elif form == 'pct':
464 try:
465 tmp = 100.0 * float(val)
466 if 'filter' in kwargs and type(kwargs['filter']) == int:
467 fformat = '%.' + str(kwargs['filter']) + 'f'
468 else:
469 fformat = '%.2f'
470
471 val = fformat % tmp
472 except Exception as e:
473 print('ERROR pipeline_val - form=pct: %s' % e)
474
475 elif form == 'floatstr' or form == 'float':
476 try:
477 tmp = float(val)
478 if form == 'floatstr':
479 val = '%.4f' % tmp
480 elif form == 'float':
481 val = tmp # float
482 if 'filter' in kwargs and type(kwargs['filter']) == int:
483 fformat = '%.' + str(kwargs['filter']) + 'f'
484 val = fformat % val
485 except Exception as e:
486 print('ERROR pipeline_val - form=floatstr|float: %s' % e)
487
488
489 if val == 'n.a.' and kwargs.get('filter') == 0:
490 if form == 'int':
491 val = 0
492 else:
493 val = '0'
494 else:
495 val = None
496
497 if 'vtype' not in kwargs or kwargs['vtype'] != 'numeric':
498 val = str(val)
499
500 return val # this is for string replacement, so return string
501
502 ## EOF
503
504 if __name__ == '__main__':
505 print('unit test ...')
506 tok_map = {
507 'overall bases Q score mean' : {'token' : '[_BASE-QUALITY-SCORE_]', 'type': 'float', 'filter': 1},
508 'overall bases Q score std' : {'token' : '[_BASE-QUALITY-SCORE-STD_]', 'type': 'float'},
509 'Q30 bases Q score mean' : {'token' : '[_Q30-BASE-QUALITY-SCORE_]', 'type': 'float'},
510 'Q30 bases Q score std' : {'token' : '[_Q30-BASE-QUALITY-SCORE-STD_]', 'type': 'float'},
511 }
512
513 odir = '/global/projectb/scratch/syao/standalone/readqc_bb'
514 stats = get_dict_obj(os.path.join(odir, 'readqc_stats.txt'))
515 # rawCnt = pipeline_val('inputReads', {'type': 'int'}, stats)
516 # print(rawCnt)
517 # print(type(rawCnt))
518 # from pprint import pprint
519 # pprint(stats)
520
521 for key in tok_map:
522 dat = tok_map[key]
523 key = key.lower()
524 print(key)
525 print(pipeline_val(key, dat, stats))
526 print(stats[key])
527 print('\n')
528
529
530