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
|
|
32 def download_file(link, local_file_name):
|
|
33 req = urllib2.Request(link)
|
|
34 src_file = urllib2.urlopen(req)
|
|
35 local_file = open(local_file_name, 'wb')
|
|
36 local_file.write(src_file.read())
|
|
37 local_file.close()
|
|
38
|
|
39 def uncompress_gz(gz_file_name, uncompressed_file_name):
|
7
|
40 print("____________________________________________________________")
|
|
41 print("*** Uncompressing %s" % gz_file_name)
|
0
|
42 uncompressed_file = open(uncompressed_file_name, 'wb')
|
|
43 with gzip.open(gz_file_name, 'rb') as src_file:
|
|
44 uncompressed_file.write(src_file.read())
|
|
45 uncompressed_file.close()
|
7
|
46 print("-> Uncompressed !\n")
|
0
|
47
|
|
48 def add_data_table_entry( data_manager_dict, data_table_entry ):
|
|
49 data_manager_dict['data_tables'] = data_manager_dict.get( 'data_tables', {} )
|
|
50 data_manager_dict['data_tables']['alfa_indexes'] = data_manager_dict['data_tables'].get( 'alfa_indexes', data_table_entry )
|
|
51 return data_manager_dict
|
|
52
|
|
53 def standardize_species_name(species_name):
|
|
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):
|
7
|
69 print("____________________________________________________________")
|
|
70 print ("*** Testing whether %s is referenced in Ensembl %s" % (species_name, kingdom))
|
0
|
71 list_species_file_name = 'species_Ensembl%s%s.txt' % (kingdom[0].upper(), kingdom[1:])
|
|
72 if kingdom=='vertebrates':
|
|
73 download_file(url, list_species_file_name)
|
|
74 else:
|
|
75 download_file(url + list_species_file_name, list_species_file_name)
|
|
76
|
|
77 grep_result = subprocess.Popen(['grep', species_name, list_species_file_name], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
|
|
78 species_lines_matched, grep_error = grep_result.communicate()
|
|
79 if grep_error != None or species_lines_matched == "":
|
|
80 msg = 'The species \'%s\' is not referenced on Ensembl (%s)' % (species_name, kingdom)
|
|
81 sys.exit(msg)
|
|
82
|
|
83 species_lines = species_lines_matched.split('\n')
|
|
84 del species_lines[-1]
|
|
85 nb_lines = len(species_lines)
|
|
86
|
|
87 if nb_lines == 1:
|
15
|
88 if kingdom == 'vertebrates':
|
|
89 fields = species_lines[0].split(' ')
|
|
90 columns = fields[-1].split('\r')
|
|
91 found_species_name = columns[0]
|
|
92 else:
|
|
93 columns = species_lines[0].split('\t')
|
|
94 found_species_name = columns[1]
|
0
|
95 if species_name != found_species_name:
|
7
|
96 print('-> \'%s\' has been replace with the complete species name \'%s\'' % (species_name, found_species_name))
|
0
|
97 return found_species_name, species_lines_matched
|
7
|
98 print("-> Referenced !\n")
|
0
|
99 return species_name, species_lines_matched
|
|
100 else:
|
|
101 list_species = [''] * nb_lines
|
|
102 for i in range(0, nb_lines):
|
15
|
103 if kingdom == 'vertebrates':
|
21
|
104 fields = species_lines[i].split(' ')
|
15
|
105 columns = fields[-1].split('\r')
|
|
106 list_species[i] = columns[0]
|
|
107 else:
|
21
|
108 columns = species_lines[i].split('\t')
|
15
|
109 list_species[i] = columns[1]
|
0
|
110 exact_match = re.search('^%s$' % species_name, list_species[i])
|
|
111 if exact_match:
|
7
|
112 print("-> Referenced !\n")
|
0
|
113 return species_name, species_lines[i]
|
|
114 msg = 'The string \'%s\' has been matched against the list of Ensembl Species but is not a complete species name.\nPlease retry with one of the following species names:\n%s' % (species_name, list_species[0:])
|
|
115 sys.exit(msg)
|
|
116
|
|
117 def get_ensembl_collection(kingdom, species_line):
|
7
|
118 print("*** Extracting the %s_collection of the species" % kingdom)
|
0
|
119 collection_regex = re.compile('%s_.+_collection' % kingdom.lower())
|
|
120 collection_match = re.search(collection_regex, species_line)
|
|
121 if not collection_match:
|
7
|
122 print("-> Skiped: this species is not classified in a Ensembl %s collection\n" % kingdom)
|
0
|
123 return None
|
7
|
124 print("-> Extracted !\n")
|
0
|
125 return collection_match.group(0)
|
|
126
|
|
127 def get_ensembl_gtf_archive_name(url_dir, species_name):
|
7
|
128 print("____________________________________________________________")
|
|
129 print("*** Extracting the gtf archive name of %s" % species_name)
|
0
|
130 gtf_archive_regex = re.compile('%s\..*\.[0-9]+\.gtf\.gz' % species_name, flags = re.IGNORECASE)
|
|
131 dir_content = get_page_content(url_dir)
|
|
132 gtf_archive_match = re.search(gtf_archive_regex, dir_content)
|
|
133 if not gtf_archive_match:
|
|
134 sys.exit('The species is referenced on Ensembl but error of nomenclature led to download failure')
|
|
135 gtf_archive_name = gtf_archive_match.group(0)
|
7
|
136 print("-> Extracted !\n")
|
0
|
137 return gtf_archive_name
|
|
138
|
|
139 def get_ensembl_gtf_archive(kingdom, url, species_name, species_line):
|
|
140 if kingdom != 'vertebrates':
|
|
141 url = url + 'gtf/'
|
|
142 if kingdom == 'bacteria' or kingdom == 'protists' or kingdom == 'fungi':
|
|
143 collection = get_ensembl_collection(kingdom, species_line)
|
|
144 if collection != None:
|
|
145 url = url + "%s/" % collection
|
|
146 final_url = url + species_name + '/'
|
|
147 gtf_archive_name = get_ensembl_gtf_archive_name(final_url, species_name)
|
7
|
148 print("____________________________________________________________")
|
|
149 print("*** Download the gtf archive of %s" % species_name)
|
0
|
150 download_file(final_url + gtf_archive_name, gtf_archive_name)
|
7
|
151 print("-> Downloaded !\n")
|
0
|
152 return gtf_archive_name
|
|
153
|
|
154 def generate_alfa_indexes(path_to_alfa, gtf_file_name):
|
7
|
155 print("____________________________________________________________")
|
|
156 print("*** Generating alfa indexes from %s" % gtf_file_name)
|
4
|
157 alfa_result = subprocess.Popen(['python', path_to_alfa, '-a', gtf_file_name], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
|
0
|
158 alfa_out, alfa_err = alfa_result.communicate()
|
|
159 if alfa_err != None and not re.search('### End of program', alfa_err):
|
|
160 msg = 'Generation Failed due an alfa error: %s' % (alfa_err)
|
|
161 sys.exit(msg)
|
10
|
162 print("Alfa prompt:\n%s" % alfa_out)
|
7
|
163 print("-> Generated !\n")
|
0
|
164
|
|
165 def get_data_table_new_entry(gtf_archive_name):
|
|
166 info_list = gtf_archive_name.split('.')
|
|
167 species = info_list[0]
|
|
168 version = info_list[1]
|
|
169 release = info_list[2]
|
|
170 value = '%s_%s_%s' % (species, version, release)
|
|
171 dbkey = value
|
|
172 name = '%s: %s (release %s)' % (species, version, release)
|
|
173 prefix = '%s.%s.%s' % (species, version, release)
|
|
174 entry_dict = { 'species': species, 'version': version, 'release': release, 'value': value, 'dbkey': dbkey, 'name': name, 'prefix': prefix }
|
|
175 return entry_dict
|
|
176
|
|
177 def main():
|
|
178 options, args = get_arg()
|
15
|
179 tool_dir = args[0]
|
0
|
180
|
4
|
181 path_to_alfa = os.path.join(tool_dir, 'ALFA.py')
|
0
|
182
|
|
183 if options.output_filename == None:
|
|
184 msg = 'No json output file specified'
|
|
185 sys.exit(msg)
|
|
186 output_filename = options.output_filename
|
|
187 params = from_json_string(open(output_filename).read())
|
|
188 target_directory = params['output_data'][0]['extra_files_path']
|
|
189 os.mkdir(target_directory)
|
|
190
|
15
|
191 tmp_dir = tempfile.mkdtemp(prefix='tmp', suffix='')
|
0
|
192 os.chdir(tmp_dir)
|
15
|
193
|
0
|
194 data_manager_dict = {}
|
|
195
|
|
196 if options.ensembl_info:
|
|
197 kingdom, species_name = options.ensembl_info
|
|
198 species_name = standardize_species_name(species_name)
|
|
199 url = get_ensembl_url_root(kingdom)
|
|
200 species_name, species_line = test_ensembl_species_exists(kingdom, url, species_name)
|
|
201 gtf_archive_name = get_ensembl_gtf_archive(kingdom, url, species_name, species_line)
|
|
202 data_table_entry = get_data_table_new_entry(gtf_archive_name)
|
|
203 gtf_file_name = '%s.gtf' % data_table_entry['prefix']
|
|
204 uncompress_gz(gtf_archive_name, gtf_file_name)
|
|
205 generate_alfa_indexes(path_to_alfa, gtf_file_name)
|
|
206 stranded_index_name = '%s.stranded.index' % data_table_entry['prefix']
|
|
207 unstranded_index_name = '%s.unstranded.index' % data_table_entry['prefix']
|
|
208 add_data_table_entry(data_manager_dict, data_table_entry)
|
|
209
|
7
|
210 print("____________________________________________________________")
|
|
211 print("*** General Info")
|
|
212 print("TMP DIR:\t%s" % tmp_dir)
|
|
213 print("TARGET DIR:\t%s" % target_directory)
|
|
214 print("URL ROOT:\t%s" % url)
|
|
215 print("SPECIES:\t%s" % data_table_entry['species'])
|
|
216 print("VERSION:\t%s" % data_table_entry['version'])
|
|
217 print("RELEASE:\t%s" % data_table_entry['release'])
|
|
218 print("VALUE:\t%s" % data_table_entry['value'])
|
|
219 print("DBKEY:\t%s" % data_table_entry['dbkey'])
|
|
220 print("NAME:\t%s" % data_table_entry['name'])
|
|
221 print("PREFIX:\t%s" % data_table_entry['prefix'])
|
|
222 print("____________________________________________________________")
|
|
223 print("*** Intial dictionary")
|
|
224 print("%s" % params)
|
0
|
225
|
6
|
226
|
0
|
227 shutil.copyfile(stranded_index_name, os.path.join(target_directory, stranded_index_name))
|
|
228 shutil.copyfile(unstranded_index_name, os.path.join(target_directory, unstranded_index_name))
|
|
229
|
|
230 cleanup_before_exit(tmp_dir)
|
|
231
|
|
232 open(output_filename, 'wb').write(to_json_string(data_manager_dict))
|
21
|
233 main()
|