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
|
|
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 = 'all_gff'
|
|
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 ):
|
5
|
42 dbkey = params['param_dict']['dbkey']
|
0
|
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
|
2
|
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:
|
5
|
53 # dbkey_name = None
|
2
|
54 dbkey_name = dbkey_description
|
0
|
55 sequence_name = params['param_dict']['sequence_name']
|
|
56 if not sequence_name:
|
|
57 sequence_name = dbkey_description
|
|
58 if not sequence_name:
|
|
59 sequence_name = dbkey
|
|
60 return dbkey, dbkey_name, sequence_id, sequence_name
|
|
61
|
|
62
|
|
63 def _get_files_in_ftp_path( ftp, path ):
|
|
64 path_contents = []
|
|
65 ftp.retrlines( 'MLSD %s' % ( path ), path_contents.append )
|
|
66 return [ line.split( ';' )[ -1 ].lstrip() for line in path_contents ]
|
|
67
|
|
68
|
|
69 def _get_stream_readers_for_tar( fh, tmp_dir ):
|
|
70 fasta_tar = tarfile.open( fileobj=fh, mode='r:*' )
|
|
71 return [x for x in [fasta_tar.extractfile(member) for member in fasta_tar.getmembers()] if x]
|
|
72
|
|
73
|
|
74 def _get_stream_readers_for_zip( fh, tmp_dir ):
|
|
75 """
|
|
76 Unpacks all archived files in a zip file.
|
|
77 Individual files will be concatenated (in _stream_fasta_to_file)
|
|
78 """
|
|
79 fasta_zip = zipfile.ZipFile( fh, 'r' )
|
|
80 rval = []
|
|
81 for member in fasta_zip.namelist():
|
|
82 fasta_zip.extract( member, tmp_dir )
|
|
83 rval.append( open( os.path.join( tmp_dir, member ), 'rb' ) )
|
|
84 return rval
|
|
85
|
|
86
|
|
87 def _get_stream_readers_for_gzip( fh, tmp_dir ):
|
|
88 return [ gzip.GzipFile( fileobj=fh, mode='rb') ]
|
|
89
|
|
90
|
|
91 def _get_stream_readers_for_bz2( fh, tmp_dir ):
|
|
92 return [ bz2.BZ2File( fh.name, 'rb') ]
|
|
93
|
|
94
|
|
95 def _download_file(start, fh):
|
|
96 tmp = tempfile.NamedTemporaryFile()
|
|
97 tmp.write(start)
|
|
98 tmp.write(fh.read())
|
|
99 tmp.flush()
|
|
100 tmp.seek(0)
|
|
101 return tmp
|
|
102
|
|
103
|
|
104 def get_stream_reader(fh, tmp_dir):
|
|
105 """
|
|
106 Check if file is compressed and return correct stream reader.
|
|
107 If file has to be downloaded, do it now.
|
|
108 """
|
|
109 magic_dict = {
|
|
110 b"\x1f\x8b\x08": _get_stream_readers_for_gzip,
|
|
111 b"\x42\x5a\x68": _get_stream_readers_for_bz2,
|
|
112 b"\x50\x4b\x03\x04": _get_stream_readers_for_zip,
|
|
113 }
|
|
114 start_of_file = fh.read(CHUNK_SIZE)
|
|
115 try:
|
|
116 fh.seek(0)
|
|
117 except UnsupportedOperation: # This is if fh has been created by urlopen
|
|
118 fh = _download_file(start_of_file, fh)
|
|
119 for k,v in magic_dict.items():
|
|
120 if start_of_file.startswith(k):
|
|
121 return v(fh, tmp_dir)
|
|
122 try: # Check if file is tar file
|
|
123 if tarfile.open(fileobj=StringIO(start_of_file)):
|
|
124 return _get_stream_readers_for_tar(fh, tmp_dir)
|
|
125 except tarfile.ReadError:
|
|
126 pass
|
|
127 return fh
|
|
128
|
|
129
|
|
130
|
|
131 def add_fasta_to_table(data_manager_dict, fasta_readers, target_directory, dbkey, dbkey_name, sequence_id, sequence_name, params):
|
|
132 for data_table_name, data_table_entry in _stream_fasta_to_file( fasta_readers, target_directory, dbkey, dbkey_name, sequence_id, sequence_name, params ):
|
|
133 if data_table_entry:
|
|
134 _add_data_table_entry( data_manager_dict, data_table_entry, data_table_name )
|
|
135
|
|
136
|
|
137 def download_from_url( data_manager_dict, params, target_directory, dbkey, dbkey_name, sequence_id, sequence_name, tmp_dir ):
|
|
138 urls = filter( bool, map( lambda x: x.strip(), params['param_dict']['reference_source']['user_url'].split( '\n' ) ) )
|
|
139 fasta_readers = [ get_stream_reader(urlopen( url ), tmp_dir) for url in urls ]
|
|
140 add_fasta_to_table(data_manager_dict, fasta_readers, target_directory, dbkey, dbkey_name, sequence_id,sequence_name, params)
|
|
141
|
|
142
|
|
143 def download_from_history( data_manager_dict, params, target_directory, dbkey, dbkey_name, sequence_id, sequence_name, tmp_dir ):
|
|
144 input_filename = params['param_dict']['reference_source']['input_fasta']
|
|
145 if isinstance( input_filename, list ):
|
|
146 fasta_readers = [ get_stream_reader(open(filename, 'rb'), tmp_dir) for filename in input_filename ]
|
|
147 else:
|
|
148 fasta_readers = get_stream_reader(open(input_filename), tmp_dir)
|
|
149 add_fasta_to_table(data_manager_dict, fasta_readers, target_directory, dbkey, dbkey_name, sequence_id, sequence_name, params)
|
|
150
|
|
151
|
|
152 def copy_from_directory( data_manager_dict, params, target_directory, dbkey, dbkey_name, sequence_id, sequence_name, tmp_dir ):
|
|
153 input_filename = params['param_dict']['reference_source']['fasta_filename']
|
|
154 create_symlink = params['param_dict']['reference_source']['create_symlink'] == 'create_symlink'
|
|
155 if create_symlink:
|
|
156 data_table_entries = _create_symlink( input_filename, target_directory, dbkey, dbkey_name, sequence_id, sequence_name )
|
|
157 else:
|
|
158 if isinstance( input_filename, list ):
|
|
159 fasta_readers = [ get_stream_reader(open(filename, 'rb'), tmp_dir) for filename in input_filename ]
|
|
160 else:
|
|
161 fasta_readers = get_stream_reader(open(input_filename), tmp_dir)
|
|
162 data_table_entries = _stream_fasta_to_file( fasta_readers, target_directory, dbkey, dbkey_name, sequence_id, sequence_name, params )
|
|
163 for data_table_name, data_table_entry in data_table_entries:
|
|
164 if data_table_entry:
|
|
165 _add_data_table_entry( data_manager_dict, data_table_entry, data_table_name )
|
|
166
|
|
167
|
|
168 def _add_data_table_entry( data_manager_dict, data_table_entry, data_table_name ):
|
|
169 data_manager_dict['data_tables'] = data_manager_dict.get( 'data_tables', {} )
|
|
170 data_manager_dict['data_tables'][data_table_name] = data_manager_dict['data_tables'].get( DATA_TABLE_NAME, [] )
|
|
171 data_manager_dict['data_tables'][data_table_name].append( data_table_entry )
|
|
172 return data_manager_dict
|
|
173
|
|
174
|
|
175 def _stream_fasta_to_file( fasta_stream, target_directory, dbkey, dbkey_name, sequence_id, sequence_name, params, close_stream=True ):
|
|
176 fasta_base_filename = "%s.gff" % sequence_id
|
|
177 fasta_filename = os.path.join( target_directory, fasta_base_filename )
|
|
178 with open( fasta_filename, 'wb+' ) as fasta_writer:
|
|
179
|
|
180 if isinstance( fasta_stream, list ) and len( fasta_stream ) == 1:
|
|
181 fasta_stream = fasta_stream[0]
|
|
182
|
|
183 if isinstance( fasta_stream, list ):
|
|
184 last_char = None
|
|
185 for fh in fasta_stream:
|
|
186 if last_char not in [ None, '\n', '\r', b'\n', b'\r' ]:
|
|
187 fasta_writer.write( b'\n' )
|
|
188 while True:
|
|
189 data = fh.read( CHUNK_SIZE )
|
|
190 if data:
|
|
191 fasta_writer.write( data )
|
|
192 last_char = data[-1]
|
|
193 else:
|
|
194 break
|
|
195 if close_stream:
|
|
196 fh.close()
|
|
197 else:
|
|
198 while True:
|
|
199 data = fasta_stream.read( CHUNK_SIZE )
|
|
200 if data:
|
|
201 fasta_writer.write( data )
|
|
202 else:
|
|
203 break
|
|
204 if close_stream:
|
|
205 fasta_stream.close()
|
|
206
|
|
207 #sort_fasta( fasta_filename, params['param_dict']['sorting']['sort_selector'], params )
|
|
208
|
|
209
|
2
|
210 return [ ( DATA_TABLE_NAME, dict( value=sequence_id, dbkey=dbkey, name=sequence_name, path=fasta_base_filename ) ) ]
|
0
|
211
|
|
212
|
|
213 def compute_fasta_length( fasta_file, out_file, keep_first_word=False ):
|
|
214
|
|
215 infile = fasta_file
|
|
216 out = open( out_file, 'w')
|
|
217
|
|
218 fasta_title = ''
|
|
219 seq_len = 0
|
|
220
|
|
221 first_entry = True
|
|
222
|
|
223 for line in open( infile ):
|
|
224 line = line.strip()
|
|
225 if not line or line.startswith( '#' ):
|
|
226 continue
|
|
227 if line[0] == '>':
|
|
228 if first_entry == False:
|
|
229 if keep_first_word:
|
|
230 fasta_title = fasta_title.split()[0]
|
|
231 out.write( "%s\t%d\n" % ( fasta_title[ 1: ], seq_len ) )
|
|
232 else:
|
|
233 first_entry = False
|
|
234 fasta_title = line
|
|
235 seq_len = 0
|
|
236 else:
|
|
237 seq_len += len(line)
|
|
238
|
|
239 # last fasta-entry
|
|
240 if keep_first_word:
|
|
241 fasta_title = fasta_title.split()[0]
|
|
242 out.write( "%s\t%d\n" % ( fasta_title[ 1: ], seq_len ) )
|
|
243 out.close()
|
|
244
|
|
245
|
|
246 def _create_symlink( input_filename, target_directory, dbkey, dbkey_name, sequence_id, sequence_name ):
|
|
247 fasta_base_filename = "%s.fa" % sequence_id
|
|
248 fasta_filename = os.path.join( target_directory, fasta_base_filename )
|
|
249 os.symlink( input_filename, fasta_filename )
|
2
|
250 return [ ( DATA_TABLE_NAME, dict( value=sequence_id, dbkey=dbkey, name=sequence_name, path=fasta_base_filename ) ) ]
|
0
|
251
|
|
252
|
3
|
253 #REFERENCE_SOURCE_TO_DOWNLOAD = dict( ucsc=download_from_ucsc, ncbi=download_from_ncbi, url=download_from_url, history=download_from_history, directory=copy_from_directory )
|
|
254 REFERENCE_SOURCE_TO_DOWNLOAD = dict( url=download_from_url, history=download_from_history, directory=copy_from_directory )
|
|
255 #SORTING_METHODS = dict( as_is=_sort_fasta_as_is, lexicographical=_sort_fasta_lexicographical, gatk=_sort_fasta_gatk, custom=_sort_fasta_custom )
|
0
|
256
|
|
257
|
|
258 def main():
|
|
259 #Parse Command Line
|
|
260 parser = optparse.OptionParser()
|
|
261 parser.add_option( '-d', '--dbkey_description', dest='dbkey_description', action='store', type="string", default=None, help='dbkey_description' )
|
|
262 (options, args) = parser.parse_args()
|
|
263
|
|
264 filename = args[0]
|
3
|
265 #global DATA_TABLE_NAME
|
0
|
266 params = loads( open( filename ).read() )
|
|
267 target_directory = params[ 'output_data' ][0]['extra_files_path']
|
|
268 os.mkdir( target_directory )
|
|
269 data_manager_dict = {}
|
|
270
|
|
271 dbkey, dbkey_name, sequence_id, sequence_name = get_dbkey_dbname_id_name( params, dbkey_description=options.dbkey_description )
|
|
272
|
|
273 if dbkey in [ None, '', '?' ]:
|
|
274 raise Exception( '"%s" is not a valid dbkey. You must specify a valid dbkey.' % ( dbkey ) )
|
|
275
|
|
276 # Create a tmp_dir, in case a zip file needs to be uncompressed
|
|
277 tmp_dir = tempfile.mkdtemp()
|
|
278 #Fetch the FASTA
|
|
279 try:
|
|
280 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 )
|
|
281 finally:
|
|
282 cleanup_before_exit(tmp_dir)
|
|
283 #save info to json file
|
|
284 open( filename, 'wb' ).write( dumps( data_manager_dict ).encode() )
|
|
285
|
|
286 if __name__ == "__main__":
|
|
287 main()
|