-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathcreate_input_config.py
More file actions
executable file
·305 lines (247 loc) · 9.28 KB
/
create_input_config.py
File metadata and controls
executable file
·305 lines (247 loc) · 9.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
#!/usr/bin/env python3
# See the NOTICE file distributed with this work for additional information
# regarding copyright ownership.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
import configparser
import argparse
import os
import json
import subprocess
import requests
# IMPORTANT: currently this script only supports EVA - we should update the output to have Ensembl data manually; human will be manual as well
EVA_REST_ENDPOINT = "https://www.ebi.ac.uk/eva/webservices/release/v1"
def parse_args(args=None):
"""Parse command-line arguments for create_input_config.
Args:
args (list|None): Optional argument list for testing.
Returns:
argparse.Namespace: Parsed arguments including release_candidates_file, version,
ini_file and output_file.
"""
parser = argparse.ArgumentParser()
parser.add_argument(
dest="release_candidates_file",
type=str,
help="path to a release_canidates.json file",
)
parser.add_argument(dest="version", type=str, help="Ensembl version")
parser.add_argument(
"-I",
"--ini_file",
dest="ini_file",
type=str,
required=False,
help="full path database configuration file, default - DEFAULT.ini in the same directory.",
)
parser.add_argument(
"-O", "--output_file", dest="output_file", type=str, required=False
)
return parser.parse_args(args)
def parse_ini(ini_file: str, section: str = "database") -> dict:
"""Read connection parameters from an ini file section.
Args:
ini_file (str): Path to ini file.
section (str): Section name to read.
Returns:
dict: Mapping containing 'host', 'port' and 'user'.
Exits:
Exits the process with code 1 if the section is missing.
"""
config = configparser.ConfigParser()
config.read(ini_file)
if not section in config:
print(f"[ERROR] Could not find '{section}' config in ini file - {ini_file}")
exit(1)
else:
host = config[section]["host"]
port = config[section]["port"]
user = config[section]["user"]
return {"host": host, "port": port, "user": user}
def get_db_name(
server: dict, version: str, species: str = "homo_sapiens", type: str = "core"
) -> str:
"""Return the database name matching species, type and version on a MySQL server.
Args:
server (dict): Server connection mapping with keys 'host','port','user'.
version (str): Release version fragment to match.
species (str): Species production name.
type (str): Database type, e.g. 'core'.
Returns:
str: First matching database name (stdout of mysql query).
"""
query = f"SHOW DATABASES LIKE '{species}_{type}%{version}%';"
process = subprocess.run(
[
"mysql",
"--host",
server["host"],
"--port",
server["port"],
"--user",
server["user"],
"-N",
"--execute",
query,
],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
return process.stdout.decode().strip()
def get_assembly_name(server: dict, core_db: str) -> str:
"""Retrieve the assembly.default value from a core database meta table.
Args:
server (dict): Server connection mapping.
core_db (str): Core database name.
Returns:
str: Assembly name (as returned by the query).
"""
query = f"SELECT meta_value FROM meta where meta_key = 'assembly.default';"
process = subprocess.run(
[
"mysql",
"--host",
server["host"],
"--port",
server["port"],
"--user",
server["user"],
"--database",
core_db,
"-N",
"--execute",
query,
],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
return process.stdout.decode().strip()
def get_source() -> str:
"""Return the variant source identifier used by this script.
Currently this function is implemented to return 'EVA' only.
Returns:
str: Source string (e.g. 'EVA').
"""
return "EVA"
def get_genome_uuid(server: dict, meta_db: str, species, assembly) -> str:
"""Query metadata DB to obtain genome_uuid for a given species and assembly.
Args:
server (dict): Server connection mapping.
meta_db (str): Metadata database name.
species (str): Species production name.
assembly (str): Assembly accession.
Returns:
str: genome_uuid string (empty if not found).
"""
query = f"SELECT genome_uuid FROM genome AS g, organism AS o, assembly AS a WHERE g.assembly_id = a.assembly_id and g.organism_id = o.organism_id and a.accession = '{assembly}' and o.ensembl_name = '{species}';"
process = subprocess.run(
[
"mysql",
"--host",
server["host"],
"--port",
server["port"],
"--user",
server["user"],
"--database",
meta_db,
"-N",
"--execute",
query,
],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
return process.stdout.decode().strip()
def get_latest_eva_version() -> int:
"""Query EVA REST API to obtain the latest EVA release version.
Returns:
int|None: Latest release version integer if retrievable, otherwise None.
"""
url = EVA_REST_ENDPOINT + "/info/latest"
headers = {"Accept": "application/json"}
response = requests.get(url, headers=headers)
if response.status_code != 200:
print(
f"[WARNING] REST API call for retrieving EVA latest version failed with status - {response.status_code}"
)
try:
content = response.json()
release_version = content["releaseVersion"]
except:
print(
f"[WARNING] Could not get EVA latest version; default version ({EVA_DEFAULT_VERSION}) may be used"
)
release_version = None
return release_version
def main(args=None):
"""Construct an input_config JSON from release candidates and database metadata.
Builds a mapping of genome -> list of source entries including genome_uuid, species,
assembly, source name and file location and writes it to the specified output file.
Args:
args (list|None): Optional argument list for testing.
Returns:
None
"""
args = parse_args(args)
release_candidates_file = args.release_candidates_file
version = args.version
output_file = args.output_file or "input_config.json"
coredb_server = parse_ini(args.ini_file, "core")
metadb_server = parse_ini(args.ini_file, "metadata")
with open(release_candidates_file) as f:
release_candidates = json.load(f)
input_set = {}
for candidate in release_candidates:
for assembly in release_candidates[candidate]["assembly"]:
genome_data = release_candidates[candidate]["assembly"][assembly]
species_production_name = genome_data["sp_production_name"]
file_type = "remote"
if species_production_name.startswith("homo_sapiens"):
file_type = "local"
file_location = "TBD"
if file_type == "remote":
eva_release = get_latest_eva_version() or "TBD"
taxonomy_id = (
f"{genome_data['taxonomy_id']}_" if eva_release == 5 else ""
)
file_location = f"https://ftp.ebi.ac.uk/pub/databases/eva/rs_releases/release_{eva_release}/by_species/{species_production_name}/{assembly}/{taxonomy_id}{assembly}_current_ids.vcf.gz"
core_db = get_db_name(coredb_server, version, species_production_name)
assembly_name = get_assembly_name(coredb_server, core_db) or "TBD"
source = get_source() or "TBD"
genome = f"{species_production_name}_{assembly_name}"
genome_uuid = (
get_genome_uuid(
metadb_server,
"ensembl_genome_metadata",
species_production_name,
assembly,
)
or "TBD"
)
if genome not in input_set:
input_set[genome] = []
input_set[genome].append(
{
"genome_uuid": genome_uuid,
"species": species_production_name,
"assembly": assembly_name,
"source_name": source,
"file_type": file_type,
"file_location": file_location,
}
)
with open(output_file, "w") as file:
json.dump(input_set, file, indent=4)
if __name__ == "__main__":
sys.exit(main())