/tools/gatk/gatk_wrapper.py

https://bitbucket.org/cistrome/cistrome-harvard/ · Python · 126 lines · 100 code · 16 blank · 10 comment · 28 complexity · 90f5a44f1e756b8e3020fc40fb22ed76 MD5 · raw file

  1. #!/usr/bin/env python
  2. #Dan Blankenberg
  3. """
  4. A wrapper script for running the GenomeAnalysisTK.jar commands.
  5. """
  6. import sys, optparse, os, tempfile, subprocess, shutil
  7. from binascii import unhexlify
  8. from string import Template
  9. GALAXY_EXT_TO_GATK_EXT = { 'gatk_interval':'intervals', 'bam_index':'bam.bai', 'gatk_dbsnp':'dbSNP', 'picard_interval_list':'interval_list' } #items not listed here will use the galaxy extension as-is
  10. GALAXY_EXT_TO_GATK_FILE_TYPE = GALAXY_EXT_TO_GATK_EXT #for now, these are the same, but could be different if needed
  11. DEFAULT_GATK_PREFIX = "gatk_file"
  12. CHUNK_SIZE = 2**20 #1mb
  13. def cleanup_before_exit( tmp_dir ):
  14. if tmp_dir and os.path.exists( tmp_dir ):
  15. shutil.rmtree( tmp_dir )
  16. def gatk_filename_from_galaxy( galaxy_filename, galaxy_ext, target_dir = None, prefix = None ):
  17. suffix = GALAXY_EXT_TO_GATK_EXT.get( galaxy_ext, galaxy_ext )
  18. if prefix is None:
  19. prefix = DEFAULT_GATK_PREFIX
  20. if target_dir is None:
  21. target_dir = os.getcwd()
  22. gatk_filename = os.path.join( target_dir, "%s.%s" % ( prefix, suffix ) )
  23. os.symlink( galaxy_filename, gatk_filename )
  24. return gatk_filename
  25. def gatk_filetype_argument_substitution( argument, galaxy_ext ):
  26. return argument % dict( file_type = GALAXY_EXT_TO_GATK_FILE_TYPE.get( galaxy_ext, galaxy_ext ) )
  27. def open_file_from_option( filename, mode = 'rb' ):
  28. if filename:
  29. return open( filename, mode = mode )
  30. return None
  31. def html_report_from_directory( html_out, dir ):
  32. html_out.write( '<html>\n<head>\n<title>Galaxy - GATK Output</title>\n</head>\n<body>\n<p/>\n<ul>\n' )
  33. for fname in sorted( os.listdir( dir ) ):
  34. html_out.write( '<li><a href="%s">%s</a></li>\n' % ( fname, fname ) )
  35. html_out.write( '</ul>\n</body>\n</html>\n' )
  36. def index_bam_files( bam_filenames, tmp_dir ):
  37. for bam_filename in bam_filenames:
  38. bam_index_filename = "%s.bai" % bam_filename
  39. if not os.path.exists( bam_index_filename ):
  40. #need to index this bam file
  41. stderr_name = tempfile.NamedTemporaryFile( prefix = "bam_index_stderr" ).name
  42. command = 'samtools index %s %s' % ( bam_filename, bam_index_filename )
  43. proc = subprocess.Popen( args=command, shell=True, stderr=open( stderr_name, 'wb' ) )
  44. return_code = proc.wait()
  45. if return_code:
  46. for line in open( stderr_name ):
  47. print >> sys.stderr, line
  48. os.unlink( stderr_name ) #clean up
  49. cleanup_before_exit( tmp_dir )
  50. raise Exception( "Error indexing BAM file" )
  51. os.unlink( stderr_name ) #clean up
  52. def __main__():
  53. #Parse Command Line
  54. parser = optparse.OptionParser()
  55. parser.add_option( '-p', '--pass_through', dest='pass_through_options', action='append', type="string", help='These options are passed through directly to GATK, without any modification.' )
  56. parser.add_option( '-o', '--pass_through_options', dest='pass_through_options_encoded', action='append', type="string", help='These options are passed through directly to GATK, with decoding from binascii.unhexlify.' )
  57. parser.add_option( '-d', '--dataset', dest='datasets', action='append', type="string", nargs=4, help='"-argument" "original_filename" "galaxy_filetype" "name_prefix"' )
  58. parser.add_option( '', '--max_jvm_heap', dest='max_jvm_heap', action='store', type="string", default=None, help='If specified, the maximum java virtual machine heap size will be set to the provide value.' )
  59. parser.add_option( '', '--max_jvm_heap_fraction', dest='max_jvm_heap_fraction', action='store', type="int", default=None, help='If specified, the maximum java virtual machine heap size will be set to the provide value as a fraction of total physical memory.' )
  60. parser.add_option( '', '--stdout', dest='stdout', action='store', type="string", default=None, help='If specified, the output of stdout will be written to this file.' )
  61. parser.add_option( '', '--stderr', dest='stderr', action='store', type="string", default=None, help='If specified, the output of stderr will be written to this file.' )
  62. parser.add_option( '', '--html_report_from_directory', dest='html_report_from_directory', action='append', type="string", nargs=2, help='"Target HTML File" "Directory"')
  63. (options, args) = parser.parse_args()
  64. tmp_dir = tempfile.mkdtemp( prefix='tmp-gatk-' )
  65. if options.pass_through_options:
  66. cmd = ' '.join( options.pass_through_options )
  67. else:
  68. cmd = ''
  69. if options.pass_through_options_encoded:
  70. cmd = '%s %s' % ( cmd, ' '.join( map( unhexlify, options.pass_through_options_encoded ) ) )
  71. if options.max_jvm_heap is not None:
  72. cmd = cmd.replace( 'java ', 'java -Xmx%s ' % ( options.max_jvm_heap ), 1 )
  73. elif options.max_jvm_heap_fraction is not None:
  74. cmd = cmd.replace( 'java ', 'java -XX:DefaultMaxRAMFraction=%s -XX:+UseParallelGC ' % ( options.max_jvm_heap_fraction ), 1 )
  75. bam_filenames = []
  76. if options.datasets:
  77. for ( dataset_arg, filename, galaxy_ext, prefix ) in options.datasets:
  78. gatk_filename = gatk_filename_from_galaxy( filename, galaxy_ext, target_dir = tmp_dir, prefix = prefix )
  79. if dataset_arg:
  80. cmd = '%s %s "%s"' % ( cmd, gatk_filetype_argument_substitution( dataset_arg, galaxy_ext ), gatk_filename )
  81. if galaxy_ext == "bam":
  82. bam_filenames.append( gatk_filename )
  83. index_bam_files( bam_filenames, tmp_dir )
  84. #set up stdout and stderr output options
  85. stdout = open_file_from_option( options.stdout, mode = 'wb' )
  86. stderr = open_file_from_option( options.stderr, mode = 'wb' )
  87. #if no stderr file is specified, we'll use our own
  88. if stderr is None:
  89. stderr = tempfile.NamedTemporaryFile( prefix="gatk-stderr-", dir=tmp_dir )
  90. proc = subprocess.Popen( args=cmd, stdout=stdout, stderr=stderr, shell=True, cwd=tmp_dir )
  91. return_code = proc.wait()
  92. if return_code:
  93. stderr_target = sys.stderr
  94. else:
  95. stderr_target = sys.stdout
  96. stderr.flush()
  97. stderr.seek(0)
  98. while True:
  99. chunk = stderr.read( CHUNK_SIZE )
  100. if chunk:
  101. stderr_target.write( chunk )
  102. else:
  103. break
  104. stderr.close()
  105. #generate html reports
  106. if options.html_report_from_directory:
  107. for ( html_filename, html_dir ) in options.html_report_from_directory:
  108. html_report_from_directory( open( html_filename, 'wb' ), html_dir )
  109. cleanup_before_exit( tmp_dir )
  110. if __name__=="__main__": __main__()