PageRenderTime 47ms CodeModel.GetById 14ms app.highlight 29ms RepoModel.GetById 2ms app.codeStats 0ms

/tools/peak_calling/sicer_wrapper.py

https://bitbucket.org/cistrome/cistrome-harvard/
Python | 156 lines | 135 code | 13 blank | 8 comment | 34 complexity | 975700145157b6a911de3a0fa7360e3f MD5 | raw file
  1#!/usr/bin/env python
  2#Dan Blankenberg
  3
  4"""
  5A wrapper script for running SICER (spatial clustering approach for the identification of ChIP-enriched regions) region caller.
  6"""
  7
  8import sys, optparse, os, tempfile, subprocess, shutil
  9
 10CHUNK_SIZE = 2**20 #1mb
 11
 12VALID_BUILDS = [ 'mm8', 'mm9', 'hg18', 'hg19', 'dm2', 'dm3', 'sacCer1', 'pombe', 'rn4', 'tair8' ] #HACK! FIXME: allow using all specified builds, would currently require hacking SICER's "GenomeData.py" on the fly.
 13
 14def cleanup_before_exit( tmp_dir ):
 15    if tmp_dir and os.path.exists( tmp_dir ):
 16        shutil.rmtree( tmp_dir )
 17
 18
 19def open_file_from_option( filename, mode = 'rb' ):
 20    if filename:
 21        return open( filename, mode = mode )
 22    return None
 23
 24def add_one_to_file_column( filename, column, split_char = "\t", startswith_skip = None ):
 25    tmp_out = tempfile.TemporaryFile( mode='w+b' )
 26    tmp_in = open( filename )
 27    for line in tmp_in:
 28        if startswith_skip and line.startswith( startswith_skip ):
 29            tmp_out.write( line )
 30        else:
 31            fields = line.rstrip( '\n\r' ).split( split_char )
 32            if len( fields ) <= column:
 33                tmp_out.write( line )
 34            else:
 35                fields[ column ] = str( int( fields[ column ] ) + 1 )
 36                tmp_out.write( "%s\n" % ( split_char.join( fields )  ) )
 37    tmp_in.close()
 38    tmp_out.seek( 0 )
 39    tmp_in = open( filename, 'wb' )
 40    while True:
 41        chunk = tmp_out.read( CHUNK_SIZE )
 42        if chunk:
 43            tmp_in.write( chunk )
 44        else:
 45            break
 46    tmp_in.close()
 47    tmp_out.close()
 48
 49def __main__():
 50    #Parse Command Line
 51    parser = optparse.OptionParser()
 52    #stdout/err
 53    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.' )
 54    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.' )
 55    parser.add_option( '', '--fix_off_by_one_errors', dest='fix_off_by_one_errors', action='store_true', default=False, help='If specified, fix off-by-one errors in output files' )
 56    #inputs
 57    parser.add_option( '-b', '--bed_file', dest='bed_file', action='store', type="string", default=None, help='Input ChIP BED file.' )
 58    parser.add_option( '-c', '--control_file', dest='control_file', action='store', type="string", default=None, help='Input control BED file.' )
 59    parser.add_option( '-d', '--dbkey', dest='dbkey', action='store', type="string", default=None, help='Input dbkey.' )
 60    parser.add_option( '-r', '--redundancy_threshold', dest='redundancy_threshold', action='store', type="int", default=1, help='Redundancy Threshold: The number of copies of identical reads allowed in a library.' )
 61    parser.add_option( '-w', '--window_size', dest='window_size', action='store', type="int", default=200, help='Window size: resolution of SICER algorithm. For histone modifications, one can use 200 bp' )
 62    parser.add_option( '-f', '--fragment_size', dest='fragment_size', action='store', type="int", default=150, help='Fragment size: is for determination of the amount of shift from the beginning of a read to the center of the DNA fragment represented by the read. FRAGMENT_SIZE=150 means the shift is 75.' )
 63    parser.add_option( '-e', '--effective_genome_fraction', dest='effective_genome_fraction', action='store', type="float", default=0.74, help='Effective genome fraction: Effective Genome as fraction of the genome size. It depends on read length.' )
 64    parser.add_option( '-g', '--gap_size', dest='gap_size', action='store', type="int", default=600, help='Gap size: needs to be multiples of window size. Namely if the window size is 200, the gap size should be 0, 200, 400, 600, ... .' )
 65    parser.add_option( '-o', '--error_cut_off', dest='error_cut_off', action='store', type="string", default="0.1", help='Error Cut off: FDR or E-value' ) #read as string to construct names properly
 66    #outputs
 67    parser.add_option( '', '--redundancy_removed_test_bed_output_file', dest='redundancy_removed_test_bed_output_file', action='store', type="string", default=None, help='test-1-removed.bed: redundancy_removed test bed file' )
 68    parser.add_option( '', '--redundancy_removed_control_bed_output_file', dest='redundancy_removed_control_bed_output_file', action='store', type="string", default=None, help='control-1-removed.bed: redundancy_removed control bed file' )
 69    parser.add_option( '', '--summary_graph_output_file', dest='summary_graph_output_file', action='store', type="string", default=None, help='test-W200.graph: summary graph file for test-1-removed.bed with window size 200, in bedGraph format.' )
 70    parser.add_option( '', '--test_normalized_wig_output_file', dest='test_normalized_wig_output_file', action='store', type="string", default=None, help='test-W200-normalized.wig: the above file normalized by library size per million and converted into wig format. This file can be uploaded to the UCSC genome browser' )
 71    parser.add_option( '', '--score_island_output_file', dest='score_island_output_file', action='store', type="string", default=None, help='test-W200-G600.scoreisland: an intermediate file for debugging usage.' )
 72    parser.add_option( '', '--islands_summary_output_file', dest='islands_summary_output_file', action='store', type="string", default=None, help='test-W200-G600-islands-summary: summary of all candidate islands with their statistical significance.' )
 73    parser.add_option( '', '--significant_islands_summary_output_file', dest='significant_islands_summary_output_file', action='store', type="string", default=None, help='test-W200-G600-islands-summary-FDR.01: summary file of significant islands with requirement of FDR=0.01.' )
 74    parser.add_option( '', '--significant_islands_output_file', dest='significant_islands_output_file', action='store', type="string", default=None, help='test-W200-G600-FDR.01-island.bed: delineation of significant islands in "chrom start end read-count-from-redundancy_removed-test.bed" format' )
 75    parser.add_option( '', '--island_filtered_output_file', dest='island_filtered_output_file', action='store', type="string", default=None, help='test-W200-G600-FDR.01-islandfiltered.bed: library of raw redundancy_removed reads on significant islands.' )
 76    parser.add_option( '', '--island_filtered_normalized_wig_output_file', dest='island_filtered_normalized_wig_output_file', action='store', type="string", default=None, help='test-W200-G600-FDR.01-islandfiltered-normalized.wig: wig file for the island-filtered redundancy_removed reads.' )
 77    (options, args) = parser.parse_args()
 78    
 79    #check if valid build
 80    assert options.dbkey in VALID_BUILDS, ValueError( "The specified build ('%s') is not available for this tool." % options.dbkey )
 81    
 82    #everything will occur in this temp directory
 83    tmp_dir = tempfile.mkdtemp()
 84    
 85    #link input files into tmp_dir and build command line
 86    bed_base_filename = 'input_bed_file'
 87    bed_filename = '%s.bed' % bed_base_filename
 88    os.symlink( options.bed_file, os.path.join( tmp_dir, bed_filename ) )
 89    if options.control_file is not None:
 90        cmd = "SICER.sh"
 91    else:
 92        cmd = "SICER-rb.sh"
 93    cmd = '%s "%s" "%s"' % ( cmd, tmp_dir, bed_filename )
 94    if options.control_file is not None:
 95        control_base_filename = 'input_control_file'
 96        control_filename = '%s.bed' % control_base_filename
 97        os.symlink( options.control_file, os.path.join( tmp_dir, control_filename ) )
 98        cmd = '%s "%s"' % ( cmd, control_filename )
 99    cmd = '%s "%s" "%s" "%i" "%i" "%i" "%f" "%i" "%s"' % ( cmd, tmp_dir, options.dbkey, options.redundancy_threshold, options.window_size, options.fragment_size, options.effective_genome_fraction, options.gap_size, options.error_cut_off )
100    
101    #set up stdout and stderr output options
102    stdout = open_file_from_option( options.stdout, mode = 'wb' )
103    stderr = open_file_from_option( options.stderr, mode = 'wb' )
104    #if no stderr file is specified, we'll use our own
105    if stderr is None:
106        stderr = tempfile.NamedTemporaryFile( dir=tmp_dir )
107        stderr.close()
108        stderr = open( stderr.name, 'w+b' )
109    
110    proc = subprocess.Popen( args=cmd, stdout=stdout, stderr=stderr, shell=True, cwd=tmp_dir )
111    return_code = proc.wait()
112    
113    if return_code:
114        stderr_target = sys.stderr
115    else:
116        stderr_target = stdout #sys.stdout
117        stderr_target.write( "\nAdditionally, these warnings were reported:\n" )
118    stderr.flush()
119    stderr.seek(0)
120    while True:
121        chunk = stderr.read( CHUNK_SIZE )
122        if chunk:
123            stderr_target.write( chunk )
124        else:
125            break
126    stderr.close()
127    
128    try:
129        #move files to where they belong
130        shutil.move(  os.path.join( tmp_dir,'%s-%i-removed.bed' % ( bed_base_filename, options.redundancy_threshold ) ), options.redundancy_removed_test_bed_output_file )
131        shutil.move(  os.path.join( tmp_dir,'%s-W%i.graph' % ( bed_base_filename, options.window_size ) ), options.summary_graph_output_file )
132        if options.fix_off_by_one_errors: add_one_to_file_column( options.summary_graph_output_file, 2 )
133        shutil.move(  os.path.join( tmp_dir,'%s-W%i-normalized.wig' % ( bed_base_filename, options.window_size ) ), options.test_normalized_wig_output_file )
134        if options.control_file is not None:
135            shutil.move(  os.path.join( tmp_dir,'%s-%i-removed.bed' % ( control_base_filename, options.redundancy_threshold ) ), options.redundancy_removed_control_bed_output_file )
136            shutil.move(  os.path.join( tmp_dir,'%s-W%i-G%i.scoreisland' % ( bed_base_filename, options.window_size, options.gap_size ) ), options.score_island_output_file )
137            if options.fix_off_by_one_errors: add_one_to_file_column( options.score_island_output_file, 2 )
138            shutil.move(  os.path.join( tmp_dir,'%s-W%i-G%i-islands-summary' % ( bed_base_filename, options.window_size, options.gap_size ) ), options.islands_summary_output_file )
139            if options.fix_off_by_one_errors: add_one_to_file_column( options.islands_summary_output_file, 2 )
140            shutil.move(  os.path.join( tmp_dir,'%s-W%i-G%i-islands-summary-FDR%s' % ( bed_base_filename, options.window_size, options.gap_size, options.error_cut_off ) ), options.significant_islands_summary_output_file )
141            if options.fix_off_by_one_errors: add_one_to_file_column( options.significant_islands_summary_output_file, 2 )
142            shutil.move(  os.path.join( tmp_dir,'%s-W%i-G%i-FDR%s-island.bed' % ( bed_base_filename, options.window_size, options.gap_size, options.error_cut_off ) ), options.significant_islands_output_file )
143            if options.fix_off_by_one_errors: add_one_to_file_column( options.significant_islands_output_file, 2 )
144            shutil.move(  os.path.join( tmp_dir,'%s-W%i-G%i-FDR%s-islandfiltered.bed' % ( bed_base_filename, options.window_size, options.gap_size, options.error_cut_off ) ), options.island_filtered_output_file )
145            shutil.move(  os.path.join( tmp_dir,'%s-W%i-G%i-FDR%s-islandfiltered-normalized.wig' % ( bed_base_filename, options.window_size, options.gap_size, options.error_cut_off ) ), options.island_filtered_normalized_wig_output_file )
146        else:
147            shutil.move(  os.path.join( tmp_dir,'%s-W%i-G%i-E%s.scoreisland' % ( bed_base_filename, options.window_size, options.gap_size, options.error_cut_off ) ), options.score_island_output_file )
148            if options.fix_off_by_one_errors: add_one_to_file_column( options.score_island_output_file, 2 )
149            shutil.move(  os.path.join( tmp_dir,'%s-W%i-G%i-E%s-islandfiltered.bed' % ( bed_base_filename, options.window_size, options.gap_size, options.error_cut_off ) ), options.island_filtered_output_file )
150            shutil.move(  os.path.join( tmp_dir,'%s-W%i-G%i-E%s-islandfiltered-normalized.wig' % ( bed_base_filename, options.window_size, options.gap_size, options.error_cut_off ) ), options.island_filtered_normalized_wig_output_file )
151    except Exception, e:
152        raise e
153    finally:
154        cleanup_before_exit( tmp_dir )
155
156if __name__=="__main__": __main__()