PageRenderTime 40ms CodeModel.GetById 29ms app.highlight 7ms RepoModel.GetById 2ms app.codeStats 0ms

/tools/peak_calling/ccat_wrapper.py

https://bitbucket.org/cistrome/cistrome-harvard/
Python | 41 lines | 35 code | 6 blank | 0 comment | 5 complexity | 2e2d7f62f405275c5b17be597e76d561 MD5 | raw file
 1import sys, subprocess, tempfile, shutil, os.path
 2
 3CCAT_BINARY = "CCAT"
 4
 5def get_top_count( filename ):
 6    for line in open( filename ):
 7        if line.startswith( 'outputNum' ):
 8            return int( line.split()[-1].strip() ) 
 9
10def stop_err( tmp_dir, exception ):
11    print >> sys.stderr, "Error running CCAT."
12    shutil.rmtree( tmp_dir ) #some error has occurred, provide info and remove possibly non-empty temp directory
13    raise exception
14
15def main():
16    input_tag_file = sys.argv[1]
17    input_control_file = sys.argv[2]
18    chrom_info_file = sys.argv[3]
19    input_config_file = sys.argv[4]
20    project_name = sys.argv[5]
21    output_peak_file = sys.argv[6]
22    output_region_file = sys.argv[7]
23    output_top_file = sys.argv[8]
24    output_log_file = sys.argv[9]
25    
26    tmp_dir = tempfile.mkdtemp()
27    try:
28        assert os.path.exists( chrom_info_file ), "The required chromosome length file does not exist."
29        proc = subprocess.Popen( args="%s %s > %s" % ( CCAT_BINARY, " ".join( map( lambda x: "'%s'" % x, [ input_tag_file, input_control_file, chrom_info_file, input_config_file, project_name ] ) ), output_log_file ), shell=True, cwd=tmp_dir )
30        proc.wait()
31        if proc.returncode:
32            raise Exception( "Error code: %i" % proc.returncode )
33        output_num = get_top_count( input_config_file )
34        shutil.move( os.path.join( tmp_dir, "%s.significant.peak" % project_name ), output_peak_file )
35        shutil.move( os.path.join( tmp_dir, "%s.significant.region" % project_name ), output_region_file )
36        shutil.move( os.path.join( tmp_dir, "%s.top%i.peak" % ( project_name, output_num ) ), output_top_file )
37    except Exception, e:
38        return stop_err( tmp_dir, e )
39    os.rmdir( tmp_dir ) #clean up empty temp working directory
40
41if __name__ == "__main__": main()