Debian Codegraph @

cgecore/organisminfo/species.py

raw symbols SCIP
1 #!/usr/bin/env python3
2 import urllib.parse
3 import requests
4 import time
5
6
7 def eprint(*args, **kwargs):
8 print(*args, file=sys.stderr, **kwargs)
9
10
11 class Species():
12
13 ensembl_server = "http://rest.ensembl.org/taxonomy/classification/"
14
15 def __init__(self, species):
16 """
17 """
18 self.species = species.lower()
19 self.ensembl_response = Species.get_ensembl_tax(self.species)
20 self.ensembl_dict = self.ensembl_list_to_dict(self.ensembl_response)
21 self.tax_tuple = self.get_taxonomy_as_tuple(self.ensembl_dict)
22 self.tax_dict = self.get_taxonomy_as_dict(self.tax_tuple)
23
24 def ensembl_list_to_dict(self, ensembl_response):
25 """
26 """
27 ensembl_dict = {self.species: None}
28 for dict in ensembl_response:
29 name = dict["scientific_name"].lower()
30 child_name = dict["children"][0]["scientific_name"].lower()
31 ensembl_dict[name] = child_name
32 return ensembl_dict
33
34 @staticmethod
35 def get_ensembl_tax(species):
36 """
37 """
38 ensembl_query = "{}{}?".format(Species.ensembl_server,
39 urllib.parse.quote(species, safe=""))
40 try:
41 r = requests.get(ensembl_query,
42 headers={"Content-Type": "application/json"})
43 # Make sure less than 15 requests per second (ENSEMBL rule).
44 time.sleep(1)
45 except Exception as e:
46 print("Error while interacting ENSEMBEL REST API")
47 print("Error: {}".format(e))
48 raise Exception("Error while interacting ENSEMBEL REST API")
49
50 if not r.ok:
51 eprint("Possible source of error: Missing or misspelling of "
52 "organism name.")
53 eprint("Query was: {}".format(query))
54 eprint("r url: {}".format(r.url))
55 eprint("r text: {}".format(r.text))
56 raise Exception("Possible source of error: Missing or misspelling "
57 "of organism name.")
58
59 return r.json()
60
61 @staticmethod
62 def get_taxonomy_as_tuple(ensembl_dict):
63 """
64 """
65 root = None
66 children = tuple(ensembl_dict.values())
67 for name in ensembl_dict:
68 if(name not in children):
69 root = name
70 break
71 out_lst = [root, ]
72
73 parent = root
74 child = ""
75 while(True):
76 child = ensembl_dict.get(parent, None)
77 if(child is None):
78 break
79 out_lst.append(child)
80 parent = child
81 child = ""
82
83 return tuple(out_lst)
84
85 @staticmethod
86 def get_taxonomy_as_dict(tax_tuple):
87 """
88 """
89 return {"domain": tax_tuple[0],
90 "phylum": tax_tuple[1],
91 "class": tax_tuple[2],
92 "order": tax_tuple[3],
93 "family": tax_tuple[4],
94 "genus": tax_tuple[5],
95 "species": tax_tuple[6]}