0
|
1 #!/usr/bin/env python
|
|
2 #Dan Blankenberg
|
|
3
|
|
4 import sys
|
|
5 import os
|
|
6 import tempfile
|
|
7 import shutil
|
|
8 import optparse
|
|
9 from ftplib import FTP
|
|
10 import tarfile
|
|
11 import zipfile
|
|
12 import gzip
|
|
13 import bz2
|
3
|
14 import subprocess
|
0
|
15 try:
|
|
16 # For Python 3.0 and later
|
|
17 from urllib.request import urlopen
|
|
18 from io import BytesIO as StringIO
|
|
19 from io import UnsupportedOperation
|
|
20 except ImportError:
|
|
21 # Fall back to Python 2's urllib2
|
|
22 from urllib2 import urlopen
|
|
23 from StringIO import StringIO
|
|
24 UnsupportedOperation = AttributeError
|
|
25 from json import loads, dumps
|
|
26
|
|
27
|
|
28 CHUNK_SIZE = 2**20 # 1mb
|
|
29
|
5
|
30 DATA_TABLE_NAME = 'tx2gene_table'
|
0
|
31
|
|
32 def cleanup_before_exit( tmp_dir ):
|
|
33 if tmp_dir and os.path.exists( tmp_dir ):
|
|
34 shutil.rmtree( tmp_dir )
|
|
35
|
|
36
|
|
37 def stop_err(msg):
|
|
38 sys.stderr.write(msg)
|
|
39 sys.exit(1)
|
|
40
|
|
41
|
|
42 def get_dbkey_dbname_id_name( params, dbkey_description=None ):
|
|
43 # dbkey = params['param_dict']['dbkey_source']['dbkey']
|
|
44 #TODO: ensure sequence_id is unique and does not already appear in location file
|
|
45 sequence_id = params['param_dict']['sequence_id']
|
|
46 if not sequence_id:
|
|
47 sequence_id = dbkey #uuid.uuid4() generate and use an uuid instead?
|
5
|
48
|
0
|
49 # if params['param_dict']['dbkey_source']['dbkey_source_selector'] == 'new':
|
|
50 # dbkey_name = params['param_dict']['dbkey_source']['dbkey_name']
|
|
51 # if not dbkey_name:
|
|
52 # dbkey_name = dbkey
|
|
53 # else:
|
|
54 # dbkey_name = None
|
5
|
55 dbkey = params['param_dict']['dbkey']
|
0
|
56 dbkey_name = dbkey_description
|
|
57 sequence_name = params['param_dict']['sequence_name']
|
|
58 if not sequence_name:
|
|
59 sequence_name = dbkey_description
|
|
60 if not sequence_name:
|
|
61 sequence_name = dbkey
|
|
62 return dbkey, dbkey_name, sequence_id, sequence_name
|
|
63
|
|
64
|
|
65 def _get_files_in_ftp_path( ftp, path ):
|
|
66 path_contents = []
|
|
67 ftp.retrlines( 'MLSD %s' % ( path ), path_contents.append )
|
|
68 return [ line.split( ';' )[ -1 ].lstrip() for line in path_contents ]
|
|
69
|
|
70
|
|
71 def _get_stream_readers_for_tar( fh, tmp_dir ):
|
|
72 fasta_tar = tarfile.open( fileobj=fh, mode='r:*' )
|
|
73 return [x for x in [fasta_tar.extractfile(member) for member in fasta_tar.getmembers()] if x]
|
|
74
|
|
75
|
|
76 def _get_stream_readers_for_zip( fh, tmp_dir ):
|
|
77 """
|
|
78 Unpacks all archived files in a zip file.
|
|
79 Individual files will be concatenated (in _stream_fasta_to_file)
|
|
80 """
|
|
81 fasta_zip = zipfile.ZipFile( fh, 'r' )
|
|
82 rval = []
|
|
83 for member in fasta_zip.namelist():
|
|
84 fasta_zip.extract( member, tmp_dir )
|
|
85 rval.append( open( os.path.join( tmp_dir, member ), 'rb' ) )
|
|
86 return rval
|
|
87
|
|
88
|
|
89 def _get_stream_readers_for_gzip( fh, tmp_dir ):
|
|
90 return [ gzip.GzipFile( fileobj=fh, mode='rb') ]
|
|
91
|
|
92
|
|
93 def _get_stream_readers_for_bz2( fh, tmp_dir ):
|
|
94 return [ bz2.BZ2File( fh.name, 'rb') ]
|
|
95
|
|
96
|
3
|
97 def convert_to_tx2gene( rscript_gff_to_tx2gene, fasta_filename, file_type, params ):
|
|
98 if file_type == 'tx2gene':
|
0
|
99 return #no need to extract tx2gene table
|
3
|
100 #print file_type
|
0
|
101 #If the file is actually a GFF/GTF file then extract the tx2gene
|
|
102 gff_temp_filename = tempfile.NamedTemporaryFile().name
|
|
103 shutil.move(fasta_filename, gff_temp_filename)
|
|
104 args= ['Rscript']
|
3
|
105 args.append(rscript_gff_to_tx2gene)
|
|
106 args.extend(['-x',gff_temp_filename])
|
|
107 args.extend(['-o',fasta_filename])
|
|
108 args.extend(['-t',file_type])
|
|
109 tmp_stderr = tempfile.NamedTemporaryFile( prefix = "tmp-stderr" )
|
|
110 return_code = subprocess.call( args=args, shell=False, stderr=tmp_stderr.fileno() )
|
|
111 #return_code = subprocess.call( args=args, shell=False, stderr=None)
|
|
112 if return_code:
|
|
113 tmp_stderr.flush()
|
|
114 tmp_stderr.seek(0)
|
|
115 print >> sys.stderr, "Error in process call"
|
|
116 while True:
|
|
117 chunk = tmp_stderr.read( CHUNK_SIZE )
|
|
118 if not chunk:
|
|
119 break
|
|
120 sys.stderr.write( chunk )
|
|
121 sys.exit( return_code )
|
|
122 tmp_stderr.close()
|
0
|
123
|
3
|
124
|
|
125
|
0
|
126 def _download_file(start, fh):
|
|
127 tmp = tempfile.NamedTemporaryFile()
|
|
128 tmp.write(start)
|
|
129 tmp.write(fh.read())
|
|
130 tmp.flush()
|
|
131 tmp.seek(0)
|
|
132 return tmp
|
|
133
|
|
134
|
|
135 def get_stream_reader(fh, tmp_dir):
|
|
136 """
|
|
137 Check if file is compressed and return correct stream reader.
|
|
138 If file has to be downloaded, do it now.
|
|
139 """
|
|
140 magic_dict = {
|
|
141 b"\x1f\x8b\x08": _get_stream_readers_for_gzip,
|
|
142 b"\x42\x5a\x68": _get_stream_readers_for_bz2,
|
|
143 b"\x50\x4b\x03\x04": _get_stream_readers_for_zip,
|
|
144 }
|
|
145 start_of_file = fh.read(CHUNK_SIZE)
|
|
146 try:
|
|
147 fh.seek(0)
|
|
148 except UnsupportedOperation: # This is if fh has been created by urlopen
|
|
149 fh = _download_file(start_of_file, fh)
|
|
150 for k,v in magic_dict.items():
|
|
151 if start_of_file.startswith(k):
|
|
152 return v(fh, tmp_dir)
|
|
153 try: # Check if file is tar file
|
|
154 if tarfile.open(fileobj=StringIO(start_of_file)):
|
|
155 return _get_stream_readers_for_tar(fh, tmp_dir)
|
|
156 except tarfile.ReadError:
|
|
157 pass
|
|
158 return fh
|
|
159
|
|
160
|
|
161
|
3
|
162 def add_fasta_to_table(rscript_gff_to_tx2gene, data_manager_dict, fasta_readers, target_directory, dbkey, dbkey_name, sequence_id, sequence_name, params):
|
|
163 for data_table_name, data_table_entry in _stream_fasta_to_file(rscript_gff_to_tx2gene, fasta_readers, target_directory, dbkey, dbkey_name, sequence_id, sequence_name, params ):
|
0
|
164 if data_table_entry:
|
|
165 _add_data_table_entry( data_manager_dict, data_table_entry, data_table_name )
|
|
166
|
|
167
|
3
|
168 def download_from_url(rscript_gff_to_tx2gene, data_manager_dict, params, target_directory, dbkey, dbkey_name, sequence_id, sequence_name, tmp_dir ):
|
0
|
169 urls = filter( bool, map( lambda x: x.strip(), params['param_dict']['reference_source']['user_url'].split( '\n' ) ) )
|
|
170 fasta_readers = [ get_stream_reader(urlopen( url ), tmp_dir) for url in urls ]
|
3
|
171 add_fasta_to_table(rscript_gff_to_tx2gene,data_manager_dict, fasta_readers, target_directory, dbkey, dbkey_name, sequence_id,sequence_name, params)
|
0
|
172
|
|
173
|
3
|
174 def download_from_history(rscript_gff_to_tx2gene, data_manager_dict, params, target_directory, dbkey, dbkey_name, sequence_id, sequence_name, tmp_dir ):
|
0
|
175 #TODO: allow multiple FASTA input files
|
|
176 input_filename = params['param_dict']['reference_source']['input_fasta']
|
|
177 if isinstance( input_filename, list ):
|
|
178 fasta_readers = [ get_stream_reader(open(filename, 'rb'), tmp_dir) for filename in input_filename ]
|
|
179 else:
|
|
180 fasta_readers = get_stream_reader(open(input_filename), tmp_dir)
|
3
|
181 add_fasta_to_table(rscript_gff_to_tx2gene,data_manager_dict, fasta_readers, target_directory, dbkey, dbkey_name, sequence_id, sequence_name, params)
|
0
|
182
|
|
183
|
3
|
184 def copy_from_directory(rscript_gff_to_tx2gene, data_manager_dict, params, target_directory, dbkey, dbkey_name, sequence_id, sequence_name, tmp_dir ):
|
0
|
185 input_filename = params['param_dict']['reference_source']['fasta_filename']
|
|
186 create_symlink = params['param_dict']['reference_source']['create_symlink'] == 'create_symlink'
|
|
187 if create_symlink:
|
|
188 data_table_entries = _create_symlink( input_filename, target_directory, dbkey, dbkey_name, sequence_id, sequence_name )
|
|
189 else:
|
|
190 if isinstance( input_filename, list ):
|
|
191 fasta_readers = [ get_stream_reader(open(filename, 'rb'), tmp_dir) for filename in input_filename ]
|
|
192 else:
|
|
193 fasta_readers = get_stream_reader(open(input_filename), tmp_dir)
|
3
|
194 data_table_entries = _stream_fasta_to_file(rscript_gff_to_tx2gene, fasta_readers, target_directory, dbkey, dbkey_name, sequence_id, sequence_name, params )
|
0
|
195 for data_table_name, data_table_entry in data_table_entries:
|
|
196 if data_table_entry:
|
|
197 _add_data_table_entry( data_manager_dict, data_table_entry, data_table_name )
|
|
198
|
|
199
|
|
200 def _add_data_table_entry( data_manager_dict, data_table_entry, data_table_name ):
|
|
201 data_manager_dict['data_tables'] = data_manager_dict.get( 'data_tables', {} )
|
|
202 data_manager_dict['data_tables'][data_table_name] = data_manager_dict['data_tables'].get( DATA_TABLE_NAME, [] )
|
|
203 data_manager_dict['data_tables'][data_table_name].append( data_table_entry )
|
|
204 return data_manager_dict
|
|
205
|
|
206
|
3
|
207 def _stream_fasta_to_file( rscript_gff_to_tx2gene, fasta_stream, target_directory, dbkey, dbkey_name, sequence_id, sequence_name, params, close_stream=True ):
|
0
|
208 fasta_base_filename = "%s_tx2gene.tab" % sequence_id
|
|
209 fasta_filename = os.path.join( target_directory, fasta_base_filename )
|
|
210 with open( fasta_filename, 'wb+' ) as fasta_writer:
|
|
211
|
|
212 if isinstance( fasta_stream, list ) and len( fasta_stream ) == 1:
|
|
213 fasta_stream = fasta_stream[0]
|
|
214
|
|
215 if isinstance( fasta_stream, list ):
|
|
216 last_char = None
|
|
217 for fh in fasta_stream:
|
|
218 if last_char not in [ None, '\n', '\r', b'\n', b'\r' ]:
|
|
219 fasta_writer.write( b'\n' )
|
|
220 while True:
|
|
221 data = fh.read( CHUNK_SIZE )
|
|
222 if data:
|
|
223 fasta_writer.write( data )
|
|
224 last_char = data[-1]
|
|
225 else:
|
|
226 break
|
|
227 if close_stream:
|
|
228 fh.close()
|
|
229 else:
|
|
230 while True:
|
|
231 data = fasta_stream.read( CHUNK_SIZE )
|
|
232 if data:
|
|
233 fasta_writer.write( data )
|
|
234 else:
|
|
235 break
|
|
236 if close_stream:
|
|
237 fasta_stream.close()
|
|
238
|
3
|
239 convert_to_tx2gene( rscript_gff_to_tx2gene,fasta_filename, params['param_dict']['file_type'], params )
|
0
|
240 return [ ( DATA_TABLE_NAME, dict( value=sequence_id, dbkey=dbkey, name=sequence_name, path=fasta_base_filename ) ) ]
|
|
241
|
|
242
|
|
243 def compute_fasta_length( fasta_file, out_file, keep_first_word=False ):
|
|
244
|
|
245 infile = fasta_file
|
|
246 out = open( out_file, 'w')
|
|
247
|
|
248 fasta_title = ''
|
|
249 seq_len = 0
|
|
250
|
|
251 first_entry = True
|
|
252
|
|
253 for line in open( infile ):
|
|
254 line = line.strip()
|
|
255 if not line or line.startswith( '#' ):
|
|
256 continue
|
|
257 if line[0] == '>':
|
|
258 if first_entry == False:
|
|
259 if keep_first_word:
|
|
260 fasta_title = fasta_title.split()[0]
|
|
261 out.write( "%s\t%d\n" % ( fasta_title[ 1: ], seq_len ) )
|
|
262 else:
|
|
263 first_entry = False
|
|
264 fasta_title = line
|
|
265 seq_len = 0
|
|
266 else:
|
|
267 seq_len += len(line)
|
|
268
|
|
269 # last fasta-entry
|
|
270 if keep_first_word:
|
|
271 fasta_title = fasta_title.split()[0]
|
|
272 out.write( "%s\t%d\n" % ( fasta_title[ 1: ], seq_len ) )
|
|
273 out.close()
|
|
274
|
|
275
|
|
276 def _create_symlink( input_filename, target_directory, dbkey, dbkey_name, sequence_id, sequence_name ):
|
|
277 fasta_base_filename = "%s.fa" % sequence_id
|
|
278 fasta_filename = os.path.join( target_directory, fasta_base_filename )
|
|
279 os.symlink( input_filename, fasta_filename )
|
|
280 return [ ( DATA_TABLE_NAME, dict( value=sequence_id, dbkey=dbkey, name=sequence_name, path=fasta_base_filename ) ) ]
|
|
281
|
|
282
|
|
283 REFERENCE_SOURCE_TO_DOWNLOAD = dict( url=download_from_url, history=download_from_history, directory=copy_from_directory )
|
|
284
|
|
285
|
|
286 def main():
|
|
287 #Parse Command Line
|
|
288 parser = optparse.OptionParser()
|
|
289 parser.add_option( '-d', '--dbkey_description', dest='dbkey_description', action='store', type="string", default=None, help='dbkey_description' )
|
3
|
290 parser.add_option( '-b', '--base_dir', dest='base_dir', action='store', type='string', default=None, help='base_dir')
|
0
|
291 parser.add_option( '-t', '--type', dest='file_type', action='store', type='string', default=None, help='file_type')
|
|
292 (options, args) = parser.parse_args()
|
|
293 filename = args[0]
|
|
294 #global DATA_TABLE_NAME
|
3
|
295 rscript_gff_to_tx2gene=os.path.join( options.base_dir, 'get_tx2gene_table.R')
|
0
|
296
|
3
|
297 #input_type='gff_gtf'
|
|
298 #if options.file_type != 'gff_gtf':
|
|
299 # file_type='tx2gene'
|
5
|
300
|
0
|
301 params = loads( open( filename ).read() )
|
|
302 target_directory = params[ 'output_data' ][0]['extra_files_path']
|
|
303 os.mkdir( target_directory )
|
|
304 data_manager_dict = {}
|
5
|
305
|
0
|
306 dbkey, dbkey_name, sequence_id, sequence_name = get_dbkey_dbname_id_name( params, dbkey_description=options.dbkey_description )
|
5
|
307
|
0
|
308 if dbkey in [ None, '', '?' ]:
|
|
309 raise Exception( '"%s" is not a valid dbkey. You must specify a valid dbkey.' % ( dbkey ) )
|
|
310
|
|
311 # Create a tmp_dir, in case a zip file needs to be uncompressed
|
|
312 tmp_dir = tempfile.mkdtemp()
|
|
313 #Fetch the input file
|
|
314 try:
|
3
|
315 REFERENCE_SOURCE_TO_DOWNLOAD[ params['param_dict']['reference_source']['reference_source_selector'] ]( rscript_gff_to_tx2gene, data_manager_dict, params, target_directory, dbkey, dbkey_name, sequence_id, sequence_name, tmp_dir)
|
0
|
316 finally:
|
|
317 cleanup_before_exit(tmp_dir)
|
|
318 #save info to json file
|
|
319 open( filename, 'wb' ).write( dumps( data_manager_dict ).encode() )
|
5
|
320
|
0
|
321 if __name__ == "__main__":
|
|
322 main()
|