0
|
1 #!/usr/bin/python
|
|
2
|
|
3 import sys
|
|
4 import shutil
|
|
5 import re
|
|
6 import urllib2
|
|
7 import subprocess
|
|
8 import gzip
|
|
9 import os
|
|
10 import tempfile
|
|
11 from optparse import OptionParser
|
|
12 from galaxy.util.json import from_json_string, to_json_string
|
|
13
|
|
14 def get_arg():
|
|
15 parser = OptionParser()
|
|
16 parser.add_option("-e", "--ensembl", dest = 'ensembl_info', action = "store", nargs = 2, metavar = ("kingdom", "species_name"), type = "str")
|
|
17 parser.add_option("-o", "--output", dest='output_filename', action="store", nargs = 1, metavar = 'JSON_FILE')
|
7
|
18 parser.add_option("--log", dest='log_filename', action="store", nargs=1, metavar='log_report')
|
0
|
19 (options, args) = parser.parse_args()
|
|
20 return options, args
|
|
21
|
|
22 def cleanup_before_exit(tmp_dir):
|
|
23 if tmp_dir and os.path.exists(tmp_dir):
|
|
24 shutil.rmtree(tmp_dir)
|
|
25
|
|
26 def get_page_content(url):
|
|
27 req = urllib2.Request(url)
|
|
28 page = urllib2.urlopen(req)
|
|
29 return page.read()
|
|
30
|
|
31 def download_file(link, local_file_name):
|
|
32 req = urllib2.Request(link)
|
|
33 src_file = urllib2.urlopen(req)
|
|
34 local_file = open(local_file_name, 'wb')
|
|
35 local_file.write(src_file.read())
|
|
36 local_file.close()
|
|
37
|
|
38 def uncompress_gz(gz_file_name, uncompressed_file_name):
|
7
|
39 print("____________________________________________________________")
|
|
40 print("*** Uncompressing %s" % gz_file_name)
|
0
|
41 uncompressed_file = open(uncompressed_file_name, 'wb')
|
|
42 with gzip.open(gz_file_name, 'rb') as src_file:
|
|
43 uncompressed_file.write(src_file.read())
|
|
44 uncompressed_file.close()
|
7
|
45 print("-> Uncompressed !\n")
|
0
|
46
|
|
47 def add_data_table_entry( data_manager_dict, data_table_entry ):
|
|
48 data_manager_dict['data_tables'] = data_manager_dict.get( 'data_tables', {} )
|
|
49 data_manager_dict['data_tables']['alfa_indexes'] = data_manager_dict['data_tables'].get( 'alfa_indexes', data_table_entry )
|
|
50 return data_manager_dict
|
|
51
|
|
52 def standardize_species_name(species_name):
|
28
|
53 # substitute all capital letters, replace every succession of chars that are not letters to one underscore
|
0
|
54 standard_species_name = re.sub(r'[)]$', '', species_name)
|
|
55 standard_species_name = re.sub(r'[ _),-.(=]+ *', '_', standard_species_name)
|
|
56 return standard_species_name.lower()
|
|
57
|
|
58 def get_ensembl_url_root(kingdom):
|
7
|
59 print("____________________________________________________________")
|
|
60 print("*** Determining Ensembl ftp root url")
|
0
|
61 if kingdom == 'vertebrates':
|
|
62 root = 'ftp://ftp.ensembl.org/pub/current_gtf/'
|
|
63 else:
|
|
64 root = 'ftp://ftp.ensemblgenomes.org/pub/%s/current/' % kingdom
|
7
|
65 print("-> Determined !\n")
|
0
|
66 return root
|
|
67
|
|
68 def test_ensembl_species_exists(kingdom, url, species_name):
|
28
|
69 """
|
|
70 Test if a species exist on the ftp & return the species name with the species_line if so.
|
|
71 if the species_name matches a single string, then this string will be returned as the species name
|
|
72 if the species_name matches several strings, then an error is printed with all the possible species to enter for a new run
|
|
73 """
|
7
|
74 print("____________________________________________________________")
|
|
75 print ("*** Testing whether %s is referenced in Ensembl %s" % (species_name, kingdom))
|
0
|
76 list_species_file_name = 'species_Ensembl%s%s.txt' % (kingdom[0].upper(), kingdom[1:])
|
|
77 if kingdom=='vertebrates':
|
|
78 download_file(url, list_species_file_name)
|
|
79 else:
|
|
80 download_file(url + list_species_file_name, list_species_file_name)
|
|
81
|
|
82 grep_result = subprocess.Popen(['grep', species_name, list_species_file_name], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
|
|
83 species_lines_matched, grep_error = grep_result.communicate()
|
|
84 if grep_error != None or species_lines_matched == "":
|
|
85 msg = 'The species \'%s\' is not referenced on Ensembl (%s)' % (species_name, kingdom)
|
|
86 sys.exit(msg)
|
|
87
|
|
88 species_lines = species_lines_matched.split('\n')
|
|
89 del species_lines[-1]
|
|
90 nb_lines = len(species_lines)
|
|
91
|
|
92 if nb_lines == 1:
|
15
|
93 if kingdom == 'vertebrates':
|
|
94 fields = species_lines[0].split(' ')
|
|
95 columns = fields[-1].split('\r')
|
|
96 found_species_name = columns[0]
|
|
97 else:
|
|
98 columns = species_lines[0].split('\t')
|
|
99 found_species_name = columns[1]
|
0
|
100 if species_name != found_species_name:
|
7
|
101 print('-> \'%s\' has been replace with the complete species name \'%s\'' % (species_name, found_species_name))
|
0
|
102 return found_species_name, species_lines_matched
|
7
|
103 print("-> Referenced !\n")
|
0
|
104 return species_name, species_lines_matched
|
|
105 else:
|
|
106 list_species = [''] * nb_lines
|
|
107 for i in range(0, nb_lines):
|
15
|
108 if kingdom == 'vertebrates':
|
21
|
109 fields = species_lines[i].split(' ')
|
15
|
110 columns = fields[-1].split('\r')
|
|
111 list_species[i] = columns[0]
|
|
112 else:
|
21
|
113 columns = species_lines[i].split('\t')
|
15
|
114 list_species[i] = columns[1]
|
0
|
115 exact_match = re.search('^%s$' % species_name, list_species[i])
|
|
116 if exact_match:
|
7
|
117 print("-> Referenced !\n")
|
0
|
118 return species_name, species_lines[i]
|
28
|
119 msg = ("The string \'%s\' has been matched against the list of Ensembl Species but is not a complete species name.\n"
|
|
120 "Please retry with one of these following species names:\n" % species_name)
|
|
121 for s in list_species:
|
|
122 msg = ("%s- %s\n" % (msg, s))
|
0
|
123 sys.exit(msg)
|
|
124
|
|
125 def get_ensembl_collection(kingdom, species_line):
|
7
|
126 print("*** Extracting the %s_collection of the species" % kingdom)
|
0
|
127 collection_regex = re.compile('%s_.+_collection' % kingdom.lower())
|
|
128 collection_match = re.search(collection_regex, species_line)
|
|
129 if not collection_match:
|
7
|
130 print("-> Skiped: this species is not classified in a Ensembl %s collection\n" % kingdom)
|
0
|
131 return None
|
7
|
132 print("-> Extracted !\n")
|
0
|
133 return collection_match.group(0)
|
|
134
|
|
135 def get_ensembl_gtf_archive_name(url_dir, species_name):
|
7
|
136 print("____________________________________________________________")
|
|
137 print("*** Extracting the gtf archive name of %s" % species_name)
|
0
|
138 gtf_archive_regex = re.compile('%s\..*\.[0-9]+\.gtf\.gz' % species_name, flags = re.IGNORECASE)
|
|
139 dir_content = get_page_content(url_dir)
|
|
140 gtf_archive_match = re.search(gtf_archive_regex, dir_content)
|
|
141 if not gtf_archive_match:
|
|
142 sys.exit('The species is referenced on Ensembl but error of nomenclature led to download failure')
|
|
143 gtf_archive_name = gtf_archive_match.group(0)
|
7
|
144 print("-> Extracted !\n")
|
0
|
145 return gtf_archive_name
|
|
146
|
|
147 def get_ensembl_gtf_archive(kingdom, url, species_name, species_line):
|
|
148 if kingdom != 'vertebrates':
|
|
149 url = url + 'gtf/'
|
|
150 if kingdom == 'bacteria' or kingdom == 'protists' or kingdom == 'fungi':
|
|
151 collection = get_ensembl_collection(kingdom, species_line)
|
|
152 if collection != None:
|
|
153 url = url + "%s/" % collection
|
|
154 final_url = url + species_name + '/'
|
|
155 gtf_archive_name = get_ensembl_gtf_archive_name(final_url, species_name)
|
7
|
156 print("____________________________________________________________")
|
|
157 print("*** Download the gtf archive of %s" % species_name)
|
0
|
158 download_file(final_url + gtf_archive_name, gtf_archive_name)
|
7
|
159 print("-> Downloaded !\n")
|
0
|
160 return gtf_archive_name
|
|
161
|
|
162 def generate_alfa_indexes(path_to_alfa, gtf_file_name):
|
7
|
163 print("____________________________________________________________")
|
|
164 print("*** Generating alfa indexes from %s" % gtf_file_name)
|
4
|
165 alfa_result = subprocess.Popen(['python', path_to_alfa, '-a', gtf_file_name], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
|
0
|
166 alfa_out, alfa_err = alfa_result.communicate()
|
|
167 if alfa_err != None and not re.search('### End of program', alfa_err):
|
|
168 msg = 'Generation Failed due an alfa error: %s' % (alfa_err)
|
|
169 sys.exit(msg)
|
10
|
170 print("Alfa prompt:\n%s" % alfa_out)
|
7
|
171 print("-> Generated !\n")
|
0
|
172
|
|
173 def get_data_table_new_entry(gtf_archive_name):
|
|
174 info_list = gtf_archive_name.split('.')
|
|
175 species = info_list[0]
|
|
176 version = info_list[1]
|
|
177 release = info_list[2]
|
|
178 value = '%s_%s_%s' % (species, version, release)
|
|
179 dbkey = value
|
|
180 name = '%s: %s (release %s)' % (species, version, release)
|
|
181 prefix = '%s.%s.%s' % (species, version, release)
|
|
182 entry_dict = { 'species': species, 'version': version, 'release': release, 'value': value, 'dbkey': dbkey, 'name': name, 'prefix': prefix }
|
|
183 return entry_dict
|
|
184
|
|
185 def main():
|
|
186 options, args = get_arg()
|
15
|
187 tool_dir = args[0]
|
0
|
188
|
4
|
189 path_to_alfa = os.path.join(tool_dir, 'ALFA.py')
|
0
|
190
|
|
191 if options.output_filename == None:
|
|
192 msg = 'No json output file specified'
|
|
193 sys.exit(msg)
|
|
194 output_filename = options.output_filename
|
28
|
195
|
|
196 # Interestingly the output file to return is not empty initially.
|
|
197 # it contains a dictionary, with notably the path to the dir where the alfa_indexes
|
|
198 # are expected to be found
|
0
|
199 params = from_json_string(open(output_filename).read())
|
|
200 target_directory = params['output_data'][0]['extra_files_path']
|
|
201 os.mkdir(target_directory)
|
|
202
|
15
|
203 tmp_dir = tempfile.mkdtemp(prefix='tmp', suffix='')
|
0
|
204 os.chdir(tmp_dir)
|
15
|
205
|
0
|
206 data_manager_dict = {}
|
|
207
|
|
208 if options.ensembl_info:
|
|
209 kingdom, species_name = options.ensembl_info
|
|
210 species_name = standardize_species_name(species_name)
|
|
211 url = get_ensembl_url_root(kingdom)
|
|
212 species_name, species_line = test_ensembl_species_exists(kingdom, url, species_name)
|
|
213 gtf_archive_name = get_ensembl_gtf_archive(kingdom, url, species_name, species_line)
|
|
214 data_table_entry = get_data_table_new_entry(gtf_archive_name)
|
|
215 gtf_file_name = '%s.gtf' % data_table_entry['prefix']
|
|
216 uncompress_gz(gtf_archive_name, gtf_file_name)
|
|
217 generate_alfa_indexes(path_to_alfa, gtf_file_name)
|
|
218 stranded_index_name = '%s.stranded.index' % data_table_entry['prefix']
|
|
219 unstranded_index_name = '%s.unstranded.index' % data_table_entry['prefix']
|
|
220 add_data_table_entry(data_manager_dict, data_table_entry)
|
|
221
|
7
|
222 print("____________________________________________________________")
|
|
223 print("*** General Info")
|
|
224 print("URL ROOT:\t%s" % url)
|
|
225 print("SPECIES:\t%s" % data_table_entry['species'])
|
|
226 print("VERSION:\t%s" % data_table_entry['version'])
|
|
227 print("RELEASE:\t%s" % data_table_entry['release'])
|
|
228 print("VALUE:\t%s" % data_table_entry['value'])
|
|
229 print("DBKEY:\t%s" % data_table_entry['dbkey'])
|
|
230 print("NAME:\t%s" % data_table_entry['name'])
|
|
231 print("PREFIX:\t%s" % data_table_entry['prefix'])
|
6
|
232
|
0
|
233 shutil.copyfile(stranded_index_name, os.path.join(target_directory, stranded_index_name))
|
|
234 shutil.copyfile(unstranded_index_name, os.path.join(target_directory, unstranded_index_name))
|
|
235
|
|
236 cleanup_before_exit(tmp_dir)
|
|
237
|
|
238 open(output_filename, 'wb').write(to_json_string(data_manager_dict))
|
21
|
239 main()
|