Mercurial > repos > ieguinoa > data_manager_fetch_gff
comparison data_manager/data_manager_fetch_gff.py @ 3:cb0fa3584aeb draft
Uploaded
author | ieguinoa |
---|---|
date | Tue, 09 Oct 2018 14:32:48 -0400 |
parents | c57bd7f3fb46 |
children | 0bdfe2e85fb0 |
comparison
equal
deleted
inserted
replaced
2:c57bd7f3fb46 | 3:cb0fa3584aeb |
---|---|
91 | 91 |
92 def _get_stream_readers_for_bz2( fh, tmp_dir ): | 92 def _get_stream_readers_for_bz2( fh, tmp_dir ): |
93 return [ bz2.BZ2File( fh.name, 'rb') ] | 93 return [ bz2.BZ2File( fh.name, 'rb') ] |
94 | 94 |
95 | 95 |
96 def sort_fasta( fasta_filename, sort_method, params ): | |
97 if sort_method is None: | |
98 return | |
99 assert sort_method in SORTING_METHODS, ValueError( "%s is not a valid sorting option." % sort_method ) | |
100 return SORTING_METHODS[ sort_method ]( fasta_filename, params ) | |
101 | |
102 | |
103 def _move_and_index_fasta_for_sorting( fasta_filename ): | |
104 unsorted_filename = tempfile.NamedTemporaryFile().name | |
105 shutil.move( fasta_filename, unsorted_filename ) | |
106 fasta_offsets = {} | |
107 unsorted_fh = open( unsorted_filename ) | |
108 while True: | |
109 offset = unsorted_fh.tell() | |
110 line = unsorted_fh.readline() | |
111 if not line: | |
112 break | |
113 if line.startswith( ">" ): | |
114 line = line.split( None, 1 )[0][1:] | |
115 fasta_offsets[ line ] = offset | |
116 unsorted_fh.close() | |
117 current_order = map( lambda x: x[1], sorted( map( lambda x: ( x[1], x[0] ), fasta_offsets.items() ) ) ) | |
118 return ( unsorted_filename, fasta_offsets, current_order ) | |
119 | |
120 | |
121 def _write_sorted_fasta( sorted_names, fasta_offsets, sorted_fasta_filename, unsorted_fasta_filename ): | |
122 unsorted_fh = open( unsorted_fasta_filename ) | |
123 sorted_fh = open( sorted_fasta_filename, 'wb+' ) | |
124 | |
125 for name in sorted_names: | |
126 offset = fasta_offsets[ name ] | |
127 unsorted_fh.seek( offset ) | |
128 sorted_fh.write( unsorted_fh.readline() ) | |
129 while True: | |
130 line = unsorted_fh.readline() | |
131 if not line or line.startswith( ">" ): | |
132 break | |
133 sorted_fh.write( line ) | |
134 unsorted_fh.close() | |
135 sorted_fh.close() | |
136 | |
137 | |
138 def _sort_fasta_as_is( fasta_filename, params ): | |
139 return | |
140 | |
141 def _sort_fasta_lexicographical( fasta_filename, params ): | |
142 ( unsorted_filename, fasta_offsets, current_order ) = _move_and_index_fasta_for_sorting( fasta_filename ) | |
143 sorted_names = sorted( fasta_offsets.keys() ) | |
144 if sorted_names == current_order: | |
145 shutil.move( unsorted_filename, fasta_filename ) | |
146 else: | |
147 _write_sorted_fasta( sorted_names, fasta_offsets, fasta_filename, unsorted_filename ) | |
148 | |
149 | |
150 def _sort_fasta_gatk( fasta_filename, params ): | |
151 #This method was added by reviewer request. | |
152 ( unsorted_filename, fasta_offsets, current_order ) = _move_and_index_fasta_for_sorting( fasta_filename ) | |
153 sorted_names = map( str, range( 1, 23 ) ) + [ 'X', 'Y' ] | |
154 #detect if we have chrN, or just N | |
155 has_chr = False | |
156 for chrom in sorted_names: | |
157 if "chr%s" % chrom in current_order: | |
158 has_chr = True | |
159 break | |
160 | |
161 if has_chr: | |
162 sorted_names = map( lambda x: "chr%s" % x, sorted_names) | |
163 sorted_names.insert( 0, "chrM" ) | |
164 else: | |
165 sorted_names.insert( 0, "MT" ) | |
166 sorted_names.extend( map( lambda x: "%s_random" % x, sorted_names ) ) | |
167 | |
168 existing_sorted_names = [] | |
169 for name in sorted_names: | |
170 if name in current_order: | |
171 existing_sorted_names.append( name ) | |
172 for name in current_order: | |
173 #TODO: confirm that non-canonical names do not need to be sorted specially | |
174 if name not in existing_sorted_names: | |
175 existing_sorted_names.append( name ) | |
176 | |
177 if existing_sorted_names == current_order: | |
178 shutil.move( unsorted_filename, fasta_filename ) | |
179 else: | |
180 _write_sorted_fasta( existing_sorted_names, fasta_offsets, fasta_filename, unsorted_filename ) | |
181 | |
182 | |
183 def _sort_fasta_custom( fasta_filename, params ): | |
184 ( unsorted_filename, fasta_offsets, current_order ) = _move_and_index_fasta_for_sorting( fasta_filename ) | |
185 sorted_names = [] | |
186 for id_repeat in params['param_dict']['sorting']['sequence_identifiers']: | |
187 sorted_names.append( id_repeat[ 'identifier' ] ) | |
188 handle_not_listed = params['param_dict']['sorting']['handle_not_listed_selector'] | |
189 if handle_not_listed.startswith( 'keep' ): | |
190 add_list = [] | |
191 for name in current_order: | |
192 if name not in sorted_names: | |
193 add_list.append( name ) | |
194 if add_list: | |
195 if handle_not_listed == 'keep_append': | |
196 sorted_names.extend( add_list ) | |
197 else: | |
198 add_list.extend( sorted_names ) | |
199 sorted_names = add_list | |
200 if sorted_names == current_order: | |
201 shutil.move( unsorted_filename, fasta_filename ) | |
202 else: | |
203 _write_sorted_fasta( sorted_names, fasta_offsets, fasta_filename, unsorted_filename ) | |
204 | |
205 | |
206 def _download_file(start, fh): | 96 def _download_file(start, fh): |
207 tmp = tempfile.NamedTemporaryFile() | 97 tmp = tempfile.NamedTemporaryFile() |
208 tmp.write(start) | 98 tmp.write(start) |
209 tmp.write(fh.read()) | 99 tmp.write(fh.read()) |
210 tmp.flush() | 100 tmp.flush() |
236 except tarfile.ReadError: | 126 except tarfile.ReadError: |
237 pass | 127 pass |
238 return fh | 128 return fh |
239 | 129 |
240 | 130 |
241 def _get_ucsc_download_address(params, dbkey): | |
242 """ | |
243 Check if we can find the correct file for the supplied dbkey on UCSC's FTP server | |
244 """ | |
245 UCSC_FTP_SERVER = 'hgdownload.cse.ucsc.edu' | |
246 UCSC_DOWNLOAD_PATH = '/goldenPath/%s/bigZips/' | |
247 COMPRESSED_EXTENSIONS = ['.tar.gz', '.tgz', '.tar.bz2', '.zip', '.fa.gz', '.fa.bz2'] | |
248 | |
249 email = params['param_dict']['__user_email__'] | |
250 if not email: | |
251 email = 'anonymous@example.com' | |
252 | |
253 ucsc_dbkey = params['param_dict']['reference_source']['requested_dbkey'] or dbkey | |
254 UCSC_CHROM_FA_FILENAMES = ['%s.chromFa' % ucsc_dbkey, 'chromFa', ucsc_dbkey] | |
255 | |
256 ftp = FTP(UCSC_FTP_SERVER) | |
257 ftp.login('anonymous', email) | |
258 | |
259 ucsc_path = UCSC_DOWNLOAD_PATH % ucsc_dbkey | |
260 path_contents = _get_files_in_ftp_path(ftp, ucsc_path) | |
261 ftp.quit() | |
262 | |
263 for ucsc_chrom_fa_filename in UCSC_CHROM_FA_FILENAMES: | |
264 for ext in COMPRESSED_EXTENSIONS: | |
265 if "%s%s" % (ucsc_chrom_fa_filename, ext) in path_contents: | |
266 ucsc_file_name = "%s%s%s" % (ucsc_path, ucsc_chrom_fa_filename, ext) | |
267 return "ftp://%s%s" % (UCSC_FTP_SERVER, ucsc_file_name) | |
268 | |
269 raise Exception('Unable to determine filename for UCSC Genome for %s: %s' % (ucsc_dbkey, path_contents)) | |
270 | 131 |
271 def add_fasta_to_table(data_manager_dict, fasta_readers, target_directory, dbkey, dbkey_name, sequence_id, sequence_name, params): | 132 def add_fasta_to_table(data_manager_dict, fasta_readers, target_directory, dbkey, dbkey_name, sequence_id, sequence_name, params): |
272 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 for data_table_name, data_table_entry in _stream_fasta_to_file( fasta_readers, target_directory, dbkey, dbkey_name, sequence_id, sequence_name, params ): |
273 if data_table_entry: | 134 if data_table_entry: |
274 _add_data_table_entry( data_manager_dict, data_table_entry, data_table_name ) | 135 _add_data_table_entry( data_manager_dict, data_table_entry, data_table_name ) |
275 | 136 |
276 | 137 |
277 def download_from_ucsc( data_manager_dict, params, target_directory, dbkey, dbkey_name, sequence_id, sequence_name, tmp_dir ): | |
278 url = _get_ucsc_download_address(params, dbkey) | |
279 fasta_readers = get_stream_reader(urlopen(url), tmp_dir) | |
280 add_fasta_to_table(data_manager_dict, fasta_readers, target_directory, dbkey, dbkey_name, sequence_id, sequence_name, params) | |
281 | |
282 | |
283 def download_from_ncbi( data_manager_dict, params, target_directory, dbkey, dbkey_name, sequence_id, sequence_name, tmp_dir ): | |
284 NCBI_DOWNLOAD_URL = 'http://togows.dbcls.jp/entry/ncbi-nucleotide/%s.fasta' #FIXME: taken from dave's genome manager...why some japan site? | |
285 requested_identifier = params['param_dict']['reference_source']['requested_identifier'] | |
286 url = NCBI_DOWNLOAD_URL % requested_identifier | |
287 fasta_readers = get_stream_reader(urlopen(url), tmp_dir) | |
288 add_fasta_to_table(data_manager_dict, fasta_readers, target_directory, dbkey, dbkey_name, sequence_id, sequence_name, params) | |
289 | |
290 | |
291 def download_from_url( data_manager_dict, params, target_directory, dbkey, dbkey_name, sequence_id, sequence_name, tmp_dir ): | 138 def download_from_url( data_manager_dict, params, target_directory, dbkey, dbkey_name, sequence_id, sequence_name, tmp_dir ): |
292 urls = filter( bool, map( lambda x: x.strip(), params['param_dict']['reference_source']['user_url'].split( '\n' ) ) ) | 139 urls = filter( bool, map( lambda x: x.strip(), params['param_dict']['reference_source']['user_url'].split( '\n' ) ) ) |
293 fasta_readers = [ get_stream_reader(urlopen( url ), tmp_dir) for url in urls ] | 140 fasta_readers = [ get_stream_reader(urlopen( url ), tmp_dir) for url in urls ] |
294 add_fasta_to_table(data_manager_dict, fasta_readers, target_directory, dbkey, dbkey_name, sequence_id,sequence_name, params) | 141 add_fasta_to_table(data_manager_dict, fasta_readers, target_directory, dbkey, dbkey_name, sequence_id,sequence_name, params) |
295 | 142 |
296 | 143 |
297 def download_from_history( data_manager_dict, params, target_directory, dbkey, dbkey_name, sequence_id, sequence_name, tmp_dir ): | 144 def download_from_history( data_manager_dict, params, target_directory, dbkey, dbkey_name, sequence_id, sequence_name, tmp_dir ): |
298 #TODO: allow multiple FASTA input files | |
299 input_filename = params['param_dict']['reference_source']['input_fasta'] | 145 input_filename = params['param_dict']['reference_source']['input_fasta'] |
300 if isinstance( input_filename, list ): | 146 if isinstance( input_filename, list ): |
301 fasta_readers = [ get_stream_reader(open(filename, 'rb'), tmp_dir) for filename in input_filename ] | 147 fasta_readers = [ get_stream_reader(open(filename, 'rb'), tmp_dir) for filename in input_filename ] |
302 else: | 148 else: |
303 fasta_readers = get_stream_reader(open(input_filename), tmp_dir) | 149 fasta_readers = get_stream_reader(open(input_filename), tmp_dir) |
403 fasta_filename = os.path.join( target_directory, fasta_base_filename ) | 249 fasta_filename = os.path.join( target_directory, fasta_base_filename ) |
404 os.symlink( input_filename, fasta_filename ) | 250 os.symlink( input_filename, fasta_filename ) |
405 return [ ( DATA_TABLE_NAME, dict( value=sequence_id, dbkey=dbkey, name=sequence_name, path=fasta_base_filename ) ) ] | 251 return [ ( DATA_TABLE_NAME, dict( value=sequence_id, dbkey=dbkey, name=sequence_name, path=fasta_base_filename ) ) ] |
406 | 252 |
407 | 253 |
408 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( ucsc=download_from_ucsc, ncbi=download_from_ncbi, url=download_from_url, history=download_from_history, directory=copy_from_directory ) |
409 | 255 REFERENCE_SOURCE_TO_DOWNLOAD = dict( url=download_from_url, history=download_from_history, directory=copy_from_directory ) |
410 SORTING_METHODS = dict( as_is=_sort_fasta_as_is, lexicographical=_sort_fasta_lexicographical, gatk=_sort_fasta_gatk, custom=_sort_fasta_custom ) | 256 #SORTING_METHODS = dict( as_is=_sort_fasta_as_is, lexicographical=_sort_fasta_lexicographical, gatk=_sort_fasta_gatk, custom=_sort_fasta_custom ) |
411 | 257 |
412 | 258 |
413 def main(): | 259 def main(): |
414 #Parse Command Line | 260 #Parse Command Line |
415 parser = optparse.OptionParser() | 261 parser = optparse.OptionParser() |
416 parser.add_option( '-d', '--dbkey_description', dest='dbkey_description', action='store', type="string", default=None, help='dbkey_description' ) | 262 parser.add_option( '-d', '--dbkey_description', dest='dbkey_description', action='store', type="string", default=None, help='dbkey_description' ) |
417 parser.add_option( '-t', '--type', dest='file_type', action='store', type='string', default=None, help='file_type') | |
418 (options, args) = parser.parse_args() | 263 (options, args) = parser.parse_args() |
419 | 264 |
420 filename = args[0] | 265 filename = args[0] |
421 global DATA_TABLE_NAME | 266 #global DATA_TABLE_NAME |
422 if options.file_type == 'representative': | |
423 DATA_TABLE_NAME= 'representative_gff' | |
424 params = loads( open( filename ).read() ) | 267 params = loads( open( filename ).read() ) |
425 target_directory = params[ 'output_data' ][0]['extra_files_path'] | 268 target_directory = params[ 'output_data' ][0]['extra_files_path'] |
426 os.mkdir( target_directory ) | 269 os.mkdir( target_directory ) |
427 data_manager_dict = {} | 270 data_manager_dict = {} |
428 | 271 |