comparison data_manager/data_manager_fetch_tx2gene.py @ 0:a4d4da89aae1 draft

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