2 from ConfigParser import SafeConfigParser
6 from optparse import OptionParser
8 from pprint import pprint, pformat
10 from StringIO import StringIO
19 from htsworkflow.util import api
20 from htsworkflow.pipelines.sequences import \
21 create_sequence_table, \
24 def make_submission_name(ininame):
25 base = os.path.basename(ininame)
26 name, ext = os.path.splitext(base)
29 def make_ddf_name(pathname):
30 base = os.path.basename(pathname)
31 name, ext = os.path.splitext(base)
34 def make_condor_name(pathname):
35 base = os.path.basename(pathname)
36 name, ext = os.path.splitext(base)
37 return name + '.condor'
39 def make_submit_script(target, header, body_list):
43 this was intended for condor submit scripts
46 target (str or stream):
47 if target is a string, we will open and close the file
48 if target is a stream, the caller is responsible.
51 header to write at the beginning of the file
52 body_list (list of strs):
53 a list of blocks to add to the file.
55 if type(target) in types.StringTypes:
60 for entry in body_list:
62 if type(target) in types.StringTypes:
65 def parse_filelist(file_string):
66 return file_string.split(',')
68 def validate_filelist(files):
70 Die if a file doesn't exist in a file list
73 if not os.path.exists(f):
74 raise RuntimeError("%s does not exist" % (f,))
76 def read_ddf_ini(filename, output=sys.stdout):
78 Read a ini file and dump out a tab delmited text file
81 config = SafeConfigParser()
84 order_by = shlex.split(config.get("config", "order_by"))
86 output.write("\t".join(order_by))
87 output.write(os.linesep)
88 sections = config.sections()
90 for section in sections:
91 if section == "config":
92 # skip the config block
96 v = config.get(section, key)
99 file_list.extend(parse_filelist(v))
101 output.write("\t".join(values))
102 output.write(os.linesep)
105 def make_condor_archive_script(ininame, files):
106 script = """Universe = vanilla
108 Executable = /bin/tar
109 arguments = czvf ../%(archivename)s %(filelist)s
111 Error = compress.err.$(Process).log
112 Output = compress.out.$(Process).log
114 initialdir = %(initialdir)s
119 if not os.path.exists(f):
120 raise RuntimeError("Missing %s" % (f,))
122 context = {'archivename': make_submission_name(ininame),
123 'filelist': " ".join(files),
124 'initialdir': os.getcwd()}
126 condor_script = make_condor_name(ininame)
127 condor_stream = open(condor_script,'w')
128 condor_stream.write(script % context)
129 condor_stream.close()
131 def make_ddf(ininame, daf_name, guess_ddf=False, make_condor=False, outdir=None):
133 Make ddf files, and bonus condor file
136 if outdir is not None:
141 ddf_name = make_ddf_name(ininame)
143 output = open(ddf_name,'w')
145 file_list = read_ddf_ini(ininame, output)
147 file_list.append(daf_name)
148 if ddf_name is not None:
149 file_list.append(ddf_name)
152 make_condor_archive_script(ininame, file_list)
157 def get_library_info(host, apidata, library_id):
158 url = api.library_url(host, library_id)
159 contents = api.retrieve_info(url, apidata)
162 def read_library_result_map(filename):
163 stream = open(filename,'r')
167 library_id, result_dir = line.strip().split()
168 results.append((library_id, result_dir))
171 def condor_srf_to_fastq(srf_file, target_pathname):
172 script = """output=%(target_pathname)s
173 arguments="-c %(srf_file)s"
176 params = {'srf_file': srf_file,
177 'target_pathname': target_pathname}
179 return script % params
181 def condor_qseq_to_fastq(qseq_file, target_pathname):
183 arguments="-i %(qseq_file)s -o %(target_pathname)s"
186 params = {'qseq_file': qseq_file,
187 'target_pathname': target_pathname}
189 return script % params
191 def find_archive_sequence_files(host, apidata, sequences_path,
194 Find all the archive sequence files possibly associated with our results.
197 logging.debug("Searching for sequence files in: %s" %(sequences_path,))
201 #seq_dirs = set(os.path.join(sequences_path, 'srfs'))
203 for lib_id, result_dir in library_result_map:
204 lib_info = get_library_info(host, apidata, lib_id)
205 lib_db[lib_id] = lib_info
207 for lane in lib_info['lane_set']:
208 lane_key = (lane['flowcell'], lane['lane_number'])
209 candidate_lanes[lane_key] = lib_id
210 seq_dirs.add(os.path.join(sequences_path,
213 logging.debug("Seq_dirs = %s" %(unicode(seq_dirs)))
214 candidate_seq_list = scan_for_sequences(seq_dirs)
216 # at this point we have too many sequences as scan_for_sequences
217 # returns all the sequences in a flowcell directory
218 # so lets filter out the extras
220 for seq in candidate_seq_list:
221 lane_key = (seq.flowcell, seq.lane)
222 lib_id = candidate_lanes.get(lane_key, None)
223 if lib_id is not None:
224 lib_info = lib_db[lib_id]
225 lanes = lib_info.setdefault('lanes', {})
226 lanes.setdefault(lane_key, set()).add(seq)
230 def build_fastqs(host, apidata, sequences_path, library_result_map,
233 Generate condor scripts to build any needed fastq files
236 host (str): root of the htsworkflow api server
237 apidata (dict): id & key to post to the server
238 sequences_path (str): root of the directory tree to scan for files
239 library_result_map (list): [(library_id, destination directory), ...]
240 paired: should we assume that we are processing paired end records?
241 if False, we will treat this as single ended.
243 qseq_condor_header = """
245 executable=/woldlab/rattus/lvol0/mus/home/diane/proj/gaworkflow/scripts/qseq2fastq
246 error=qseqfastq.err.$(process).log
247 output=qseqfastq.out.$(process).log
251 qseq_condor_entries = []
252 srf_condor_header = """
254 executable=/woldlab/rattus/lvol0/mus/home/diane/bin/srf2fastq
255 output=srf2fastq.out.$(process).log
256 error=srf2fastq.err.$(process).log
260 srf_condor_entries = []
261 fastq_paired_template = '%(lib_id)s_%(flowcell)s_c%(cycle)s_l%(lane)s_r%(read)s.fastq'
262 fastq_single_template = '%(lib_id)s_%(flowcell)s_c%(cycle)s_l%(lane)s.fastq'
263 lib_db = find_archive_sequence_files(host,
268 # find what targets we're missing
270 for lib_id, result_dir in library_result_map:
272 for lane_key, sequences in lib['lanes'].items():
273 for seq in sequences:
274 filename_attributes = {
275 'flowcell': seq.flowcell,
281 # throw out test runs
282 # FIXME: this should probably be configurable
285 if seq.flowcell == '30CUUAAXX':
286 # 30CUUAAXX run sucked
291 target_name = fastq_paired_template % filename_attributes
293 target_name = fastq_single_template % filename_attributes
295 target_pathname = os.path.join(result_dir, target_name)
296 if not os.path.exists(target_pathname):
297 t = needed_targets.setdefault(target_pathname, {})
298 t[seq.filetype] = seq
300 for target_pathname, available_sources in needed_targets.items():
301 logging.debug(' target : %s' % (target_pathname,))
302 logging.debug(' candidate sources: %s' % (available_sources,))
303 if available_sources.has_key('qseq'):
304 source = available_sources['qseq']
305 qseq_condor_entries.append(
306 condor_qseq_to_fastq(source.path, target_pathname)
308 elif available_sources.has_key('srf'):
309 source = available_sources['srf']
310 if source.read is not None:
312 "srf -> fastq paired end doesn't work yet: %s" % (source,)
315 srf_condor_entries.append(
316 condor_srf_to_fastq(source.path, target_pathname)
319 print " need file", target_pathname
321 if len(srf_condor_entries) > 0:
322 make_submit_script('srf.fastq.condor',
326 if len(qseq_condor_entries) > 0:
327 make_submit_script('qseq.fastq.condor',
331 def find_best_extension(extension_map, filename):
333 Search through extension_map looking for the best extension
334 The 'best' is the longest match
337 extension_map (dict): '.ext' -> { 'view': 'name' or None }
338 filename (str): the filename whose extention we are about to examine
341 path, last_ext = os.path.splitext(filename)
343 for ext in extension_map.keys():
344 if filename.endswith(ext):
347 elif len(ext) > len(best_ext):
351 def add_submission_section(line_counter, files, standard_attributes, file_attributes):
353 Create a section in the submission ini file
355 inifile = [ '[line%s]' % (line_counter,) ]
356 inifile += ["files=%s" % (",".join(files))]
358 cur_attributes.update(standard_attributes)
359 cur_attributes.update(file_attributes)
361 for k,v in cur_attributes.items():
362 inifile += ["%s=%s" % (k,v)]
365 def make_submission_ini(host, apidata, library_result_map):
367 '.bai': {'view': None}, # bam index
368 '.bam': {'view': 'Signal'},
369 '.condor': {'view': None},
370 '.daf': {'view': None},
371 '.ddf': {'view': None},
372 '.splices.bam': {'view': 'Splices'},
373 '.bed': {'view': 'TopHatJunctions'},
374 '.ini': {'view': None},
375 '.log': {'view': None},
376 '_r1.fastq': {'view': 'FastqRd1'},
377 '_r2.fastq': {'view': 'FastqRd2'},
378 '.tar.bz2': {'view': None},
379 'novel.genes.expr': {'view': 'GeneDeNovoFPKM'},
380 'novel.transcripts.expr': {'view': 'TranscriptDeNovoFPKM'},
381 '.genes.expr': {'view': 'GeneFPKM'},
382 '.transcripts.expr': {'view': 'TranscriptFPKM'},
383 '.stats.txt': {'view': 'InsLength'},
384 '.gtf': {'view': 'CufflinksGeneModel'},
385 '.wig': {'view': 'RawSignal'},
388 candidate_fastq_src = {}
390 for lib_id, result_dir in library_result_map:
391 inifile = ['[config]']
392 inifile += ['order_by=files view cell localization rnaExtract mapAlgorithm readType replicate labVersion']
395 lib_info = get_library_info(host, apidata, lib_id)
396 result_ini = os.path.join(result_dir, result_dir+'.ini')
398 standard_attributes = {'cell': lib_info['cell_line'],
399 'insertLength': '200', # ali
400 'labVersion': 'TopHat',
401 'localization': 'cell',
402 'mapAlgorithm': 'TopHat',
403 'readType': '2x75', #ali
404 'replicate': lib_info['replicate'],
405 'rnaExtract': 'longPolyA',
410 #for lane in lib_info['lane_set']:
411 # target_name = "%s_%s_%s.fastq" % (lane['flowcell'], lib_id, lane['lane_number'])
412 # fastqs.append(target_name)
414 # make_run_block(line_counter, fastqs, standard_attributes, attributes['.fastq'])
420 submission_files = os.listdir(result_dir)
421 for f in submission_files:
422 best_ext = find_best_extension(attributes, f)
424 if best_ext is not None:
425 if attributes[best_ext]['view'] is None:
428 add_submission_section(line_counter,
437 raise ValueError("Unrecognized file: %s" % (f,))
439 f = open(result_ini,'w')
440 f.write(os.linesep.join(inifile))
443 def link_daf(daf_path, library_result_map):
444 if not os.path.exists(daf_path):
445 raise RuntimeError("%s does not exist, how can I link to it?" % (daf_path,))
447 base_daf = os.path.basename(daf_path)
449 for lib_id, result_dir in library_result_map:
450 submission_daf = os.path.join(result_dir, base_daf)
451 if not os.path.exists(submission_daf):
452 os.link(daf_path, submission_daf)
454 def make_all_ddfs(library_result_map, daf_name):
455 for lib_id, result_dir in library_result_map:
456 ininame = result_dir+'.ini'
457 inipathname = os.path.join(result_dir, ininame)
458 if os.path.exists(inipathname):
459 make_ddf(ininame, daf_name, True, True, result_dir)
462 # Load defaults from the config files
463 config = SafeConfigParser()
464 config.read([os.path.expanduser('~/.htsworkflow.ini'), '/etc/htsworkflow.ini'])
466 sequence_archive = None
470 SECTION = 'sequence_archive'
471 if config.has_section(SECTION):
472 sequence_archive = config.get(SECTION, 'sequence_archive',sequence_archive)
473 sequence_archive = os.path.expanduser(sequence_archive)
474 apiid = config.get(SECTION, 'apiid', apiid)
475 apikey = config.get(SECTION, 'apikey', apikey)
476 apihost = config.get(SECTION, 'host', apihost)
478 parser = OptionParser()
481 parser.add_option('--fastq', help="generate scripts for making fastq files",
482 default=False, action="store_true")
484 parser.add_option('--ini', help="generate submission ini file", default=False,
487 parser.add_option('--makeddf', help='make the ddfs', default=False,
490 parser.add_option('--daf', default=None, help='specify daf name')
492 # configuration options
493 parser.add_option('--apiid', default=apiid, help="Specify API ID")
494 parser.add_option('--apikey', default=apikey, help="Specify API KEY")
495 parser.add_option('--host', default=apihost,
496 help="specify HTSWorkflow host",)
497 parser.add_option('--sequence', default=sequence_archive,
498 help="sequence repository")
499 parser.add_option('--single', default=False, action="store_true",
500 help="treat the sequences as single ended runs")
503 parser.add_option('--verbose', default=False, action="store_true",
504 help='verbose logging')
505 parser.add_option('--debug', default=False, action="store_true",
506 help='debug logging')
510 def main(cmdline=None):
511 parser = make_parser()
512 opts, args = parser.parse_args(cmdline)
515 logging.basicConfig(level = logging.DEBUG )
517 logging.basicConfig(level = logging.INFO )
519 logging.basicConfig(level = logging.WARNING )
522 apidata = {'apiid': opts.apiid, 'apikey': opts.apikey }
524 if opts.host is None or opts.apiid is None or opts.apikey is None:
525 parser.error("Please specify host url, apiid, apikey")
528 parser.error("I need at least one library submission-dir input file")
530 library_result_map = []
532 library_result_map.extend(read_library_result_map(a))
534 if opts.daf is not None:
535 link_daf(opts.daf, library_result_map)
538 build_fastqs(opts.host,
545 make_submission_ini(opts.host, apidata, library_result_map)
548 make_all_ddfs(library_result_map, opts.daf)
550 if __name__ == "__main__":