Mercurial > repos > devteam > sam_to_bam
annotate sam_to_bam.py @ 5:c73bf16b45df draft
Uploaded
| author | devteam |
|---|---|
| date | Thu, 05 Mar 2015 21:28:25 -0500 |
| parents | ab4c4e07eb3c |
| children |
| rev | line source |
|---|---|
| 0 | 1 #!/usr/bin/env python |
| 2 """ | |
| 3 Converts SAM data to sorted BAM data. | |
| 4 usage: sam_to_bam.py [options] | |
| 5 --input1: SAM file to be converted | |
|
1
93f2e3337a33
Update sam_to_bam to use the fasta_indexes data table.
Dave Bouvier <dave@bx.psu.edu>
parents:
0
diff
changeset
|
6 --index: path of the indexed reference genome |
| 0 | 7 --ref_file: Reference file if choosing from history |
| 8 --output1: output dataset in bam format | |
| 9 """ | |
| 10 | |
|
1
93f2e3337a33
Update sam_to_bam to use the fasta_indexes data table.
Dave Bouvier <dave@bx.psu.edu>
parents:
0
diff
changeset
|
11 import optparse, os, sys, subprocess, tempfile, shutil |
| 0 | 12 |
| 13 def stop_err( msg ): | |
| 14 sys.stderr.write( '%s\n' % msg ) | |
| 15 sys.exit() | |
| 16 | |
| 17 def __main__(): | |
| 18 #Parse Command Line | |
| 19 parser = optparse.OptionParser() | |
| 20 parser.add_option( '', '--input1', dest='input1', help='The input SAM dataset' ) | |
|
1
93f2e3337a33
Update sam_to_bam to use the fasta_indexes data table.
Dave Bouvier <dave@bx.psu.edu>
parents:
0
diff
changeset
|
21 |
|
93f2e3337a33
Update sam_to_bam to use the fasta_indexes data table.
Dave Bouvier <dave@bx.psu.edu>
parents:
0
diff
changeset
|
22 parser.add_option( '', '--index', dest='index', help='The path of the indexed reference genome' ) |
| 0 | 23 parser.add_option( '', '--ref_file', dest='ref_file', help='The reference dataset from the history' ) |
| 24 parser.add_option( '', '--output1', dest='output1', help='The output BAM dataset' ) | |
| 25 ( options, args ) = parser.parse_args() | |
| 26 | |
| 27 # output version # of tool | |
| 28 try: | |
| 29 tmp = tempfile.NamedTemporaryFile().name | |
| 30 tmp_stdout = open( tmp, 'wb' ) | |
| 31 proc = subprocess.Popen( args='samtools 2>&1', shell=True, stdout=tmp_stdout ) | |
| 32 tmp_stdout.close() | |
| 33 returncode = proc.wait() | |
| 34 stdout = None | |
| 35 for line in open( tmp_stdout.name, 'rb' ): | |
| 36 if line.lower().find( 'version' ) >= 0: | |
| 37 stdout = line.strip() | |
| 38 break | |
| 39 if stdout: | |
| 40 sys.stdout.write( 'Samtools %s\n' % stdout ) | |
| 41 else: | |
| 42 raise Exception | |
| 43 except: | |
| 44 sys.stdout.write( 'Could not determine Samtools version\n' ) | |
| 45 | |
| 46 tmp_dir = tempfile.mkdtemp( dir='.' ) | |
| 47 if not options.ref_file or options.ref_file == 'None': | |
| 48 # We're using locally cached reference sequences( e.g., /galaxy/data/equCab2/sam_index/equCab2.fa ). | |
| 49 # The indexes for /galaxy/data/equCab2/sam_index/equCab2.fa will be contained in | |
| 50 # a file named /galaxy/data/equCab2/sam_index/equCab2.fa.fai | |
|
1
93f2e3337a33
Update sam_to_bam to use the fasta_indexes data table.
Dave Bouvier <dave@bx.psu.edu>
parents:
0
diff
changeset
|
51 fai_index_file_path = '%s.fai' % options.index |
| 0 | 52 if not os.path.exists( fai_index_file_path ): |
| 53 #clean up temp files | |
| 54 if os.path.exists( tmp_dir ): | |
| 55 shutil.rmtree( tmp_dir ) | |
|
1
93f2e3337a33
Update sam_to_bam to use the fasta_indexes data table.
Dave Bouvier <dave@bx.psu.edu>
parents:
0
diff
changeset
|
56 stop_err( 'Indexed genome %s not present, request it by reporting this error.' % options.index ) |
| 0 | 57 else: |
| 58 try: | |
| 59 # Create indexes for history reference ( e.g., ~/database/files/000/dataset_1.dat ) using samtools faidx, which will: | |
| 60 # - index reference sequence in the FASTA format or extract subsequence from indexed reference sequence | |
| 61 # - if no region is specified, faidx will index the file and create <ref.fasta>.fai on the disk | |
| 62 # - if regions are specified, the subsequences will be retrieved and printed to stdout in the FASTA format | |
| 63 # - the input file can be compressed in the RAZF format. | |
| 64 # IMPORTANT NOTE: a real weakness here is that we are creating indexes for the history dataset | |
| 65 # every time we run this tool. It would be nice if we could somehow keep track of user's specific | |
| 66 # index files so they could be re-used. | |
| 67 fai_index_file_base = tempfile.NamedTemporaryFile( dir=tmp_dir ).name | |
| 68 # At this point, fai_index_file_path will look something like /tmp/dataset_13.dat | |
| 69 os.symlink( options.ref_file, fai_index_file_base ) | |
| 70 fai_index_file_path = '%s.fai' % fai_index_file_base | |
| 71 command = 'samtools faidx %s' % fai_index_file_base | |
| 72 tmp = tempfile.NamedTemporaryFile( dir=tmp_dir ).name | |
| 73 tmp_stderr = open( tmp, 'wb' ) | |
| 74 proc = subprocess.Popen( args=command, shell=True, cwd=tmp_dir, stderr=tmp_stderr.fileno() ) | |
| 75 returncode = proc.wait() | |
| 76 tmp_stderr.close() | |
| 77 # get stderr, allowing for case where it's very large | |
| 78 tmp_stderr = open( tmp, 'rb' ) | |
| 79 stderr = '' | |
| 80 buffsize = 1048576 | |
| 81 try: | |
| 82 while True: | |
| 83 stderr += tmp_stderr.read( buffsize ) | |
| 84 if not stderr or len( stderr ) % buffsize != 0: | |
| 85 break | |
| 86 except OverflowError: | |
| 87 pass | |
| 88 tmp_stderr.close() | |
| 89 if returncode != 0: | |
| 90 raise Exception, stderr | |
| 91 if os.path.getsize( fai_index_file_path ) == 0: | |
| 92 raise Exception, 'Index file empty, there may be an error with your reference file or settings.' | |
| 93 except Exception, e: | |
| 94 #clean up temp files | |
| 95 if os.path.exists( tmp_dir ): | |
| 96 shutil.rmtree( tmp_dir ) | |
| 97 stop_err( 'Error creating indexes from reference (%s), %s' % ( options.ref_file, str( e ) ) ) | |
| 98 try: | |
| 99 # Extract all alignments from the input SAM file to BAM format ( since no region is specified, all the alignments will be extracted ). | |
| 100 tmp_aligns_file = tempfile.NamedTemporaryFile( dir=tmp_dir ) | |
| 101 tmp_aligns_file_name = tmp_aligns_file.name | |
| 102 tmp_aligns_file.close() | |
| 103 command = 'samtools view -bt %s -o %s %s' % ( fai_index_file_path, tmp_aligns_file_name, options.input1 ) | |
| 104 tmp = tempfile.NamedTemporaryFile( dir=tmp_dir ).name | |
| 105 tmp_stderr = open( tmp, 'wb' ) | |
| 106 proc = subprocess.Popen( args=command, shell=True, cwd=tmp_dir, stderr=tmp_stderr.fileno() ) | |
| 107 returncode = proc.wait() | |
| 108 tmp_stderr.close() | |
| 109 # get stderr, allowing for case where it's very large | |
| 110 tmp_stderr = open( tmp, 'rb' ) | |
| 111 stderr = '' | |
| 112 buffsize = 1048576 | |
| 113 try: | |
| 114 while True: | |
| 115 stderr += tmp_stderr.read( buffsize ) | |
| 116 if not stderr or len( stderr ) % buffsize != 0: | |
| 117 break | |
| 118 except OverflowError: | |
| 119 pass | |
| 120 tmp_stderr.close() | |
| 121 if returncode != 0: | |
| 122 raise Exception, stderr | |
| 123 except Exception, e: | |
| 124 #clean up temp files | |
| 125 if os.path.exists( tmp_dir ): | |
| 126 shutil.rmtree( tmp_dir ) | |
| 127 stop_err( 'Error extracting alignments from (%s), %s' % ( options.input1, str( e ) ) ) | |
| 128 try: | |
| 129 # Sort alignments by leftmost coordinates. File <out.prefix>.bam will be created. This command | |
| 130 # may also create temporary files <out.prefix>.%d.bam when the whole alignment cannot be fitted | |
| 131 # into memory ( controlled by option -m ). | |
| 132 tmp_sorted_aligns_file = tempfile.NamedTemporaryFile( dir=tmp_dir ) | |
| 133 tmp_sorted_aligns_file_name = tmp_sorted_aligns_file.name | |
| 134 tmp_sorted_aligns_file.close() | |
| 135 command = 'samtools sort %s %s' % ( tmp_aligns_file_name, tmp_sorted_aligns_file_name ) | |
| 136 tmp = tempfile.NamedTemporaryFile( dir=tmp_dir ).name | |
| 137 tmp_stderr = open( tmp, 'wb' ) | |
| 138 proc = subprocess.Popen( args=command, shell=True, cwd=tmp_dir, stderr=tmp_stderr.fileno() ) | |
| 139 returncode = proc.wait() | |
| 140 tmp_stderr.close() | |
| 141 # get stderr, allowing for case where it's very large | |
| 142 tmp_stderr = open( tmp, 'rb' ) | |
| 143 stderr = '' | |
| 144 buffsize = 1048576 | |
| 145 try: | |
| 146 while True: | |
| 147 stderr += tmp_stderr.read( buffsize ) | |
| 148 if not stderr or len( stderr ) % buffsize != 0: | |
| 149 break | |
| 150 except OverflowError: | |
| 151 pass | |
| 152 tmp_stderr.close() | |
| 153 if returncode != 0: | |
| 154 raise Exception, stderr | |
| 155 except Exception, e: | |
| 156 #clean up temp files | |
| 157 if os.path.exists( tmp_dir ): | |
| 158 shutil.rmtree( tmp_dir ) | |
| 159 stop_err( 'Error sorting alignments from (%s), %s' % ( tmp_aligns_file_name, str( e ) ) ) | |
| 160 # Move tmp_aligns_file_name to our output dataset location | |
| 161 sorted_bam_file = '%s.bam' % tmp_sorted_aligns_file_name | |
| 162 shutil.move( sorted_bam_file, options.output1 ) | |
| 163 #clean up temp files | |
| 164 if os.path.exists( tmp_dir ): | |
| 165 shutil.rmtree( tmp_dir ) | |
| 166 # check that there are results in the output file | |
| 167 if os.path.getsize( options.output1 ) > 0: | |
| 168 sys.stdout.write( 'SAM file converted to BAM' ) | |
| 169 else: | |
| 170 stop_err( 'Error creating sorted version of BAM file.' ) | |
| 171 | |
| 172 if __name__=="__main__": __main__() |
