Debian Codegraph @

pymzml/obo.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 # encoding: utf-8
3 """
4 Class to parse the obo file and set up the accessions library
5
6 The OBO parser has been designed to convert MS:xxxxx tags to their appropriate
7 names. A minimal set of MS accession is used in pymzML, but additional
8 accessions can easily be queried.
9
10 The obo translator is used internally to associate names with MS:xxxxxxx tags.
11
12 The OboTranslator Class generates a dictionary and several lookup tables.
13 e.g.
14
15 ::
16
17 >>> from pymzml.obo import OboTranslator as OT
18 >>> translator = OT()
19 >>> translator['MS:1000127']
20 'centroid mass spectrum'
21 >>> translator['positive scan']
22 {'is_a': 'MS:1000465 ! scan polarity', 'id': 'MS:1000130', 'def':
23 '"Polarity of the scan is positive." [PSI:MS]', 'name': 'positive scan'}
24 >>> translator['scan']
25 {'relationship': 'part_of MS:0000000 ! Proteomics Standards Initiative Mass
26 Spectrometry Ontology', 'id': 'MS:1000441', 'def': '"Function or process of
27 the mass spectrometer where it records a spectrum." [PSI:MS]', 'name':
28 'scan'}
29 >>> translator['unit']
30 {'relationship': 'part_of MS:0000000 ! Proteomics Standards Initiative Mass
31 Spectrometry Ontology', 'id': 'MS:1000460', 'def': '"Terms to describe
32 units." [PSI:MS]', 'name': 'unit'}
33
34 pymzML comes with the queryOBO.py script that can be used to interrogate the
35 OBO file. Please refer to :ref:`example_scripts` for further usage information.
36
37 ::
38
39 $ ./example_scripts/queryOBO.py "scan time"
40 MS:1000016
41 scan time
42 "The time taken for an acquisition by scanning analyzers." [PSI:MS]
43 Is a: MS:1000503 ! scan attribute
44 $
45
46
47 ::
48
49 $ ./example_scripts/queryOBO.py 1000016
50 MS:1000016
51 scan time
52 "The time taken for an acquisition by scanning analyzers." [PSI:MS]
53 MS:1000503 ! scan attribute
54 $
55
56
57 """
58
59
60 # Python mzML module - pymzml
61 # Copyright (C) 2010-2019 M. Kösters, C. Fufezan
62 # The MIT License (MIT)
63
64 # Permission is hereby granted, free of charge, to any person obtaining a copy
65 # of this software and associated documentation files (the "Software"), to deal
66 # in the Software without restriction, including without limitation the rights
67 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
68 # copies of the Software, and to permit persons to whom the Software is
69 # furnished to do so, subject to the following conditions:
70
71 # The above copyright notice and this permission notice shall be included in all
72 # copies or substantial portions of the Software.
73
74 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
75 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
76 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
77 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
78 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
79 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
80 # SOFTWARE.
81
82
83 import sys
84 import os
85 import re
86 import gzip
87 import urllib
88
89
90 class OboTranslator(object):
91 """
92 Generates a mapping from MS:xxxxx to names and vice versa for a specific
93 obo version
94
95 Args:
96 version (str): obo version
97 """
98
99 _obo_instance_cache = {}
100
101 def __init__(self, version=None):
102 self.version = self.__normalize_version(version)
103 self.all_dicts = []
104 self.id = {}
105 self.name = {}
106 self.definition = {}
107 self.lookups = [self.id, self.name, self.definition]
108 self.MS_tag_regex = re.compile(r"MS:[0-9]*")
109
110 # Only parse the OBO when necessary, not upon object construction
111 self.__obo_parsed = False
112
113 @classmethod
114 def from_cache(cls, version):
115 version = cls.__normalize_version(version)
116 try:
117 return cls._obo_instance_cache[version]
118 except KeyError:
119 inst = cls._obo_instance_cache[version] = cls(version)
120 return inst
121
122 def __setitem__(self, key, value):
123 raise TypeError("OBO translator dictionaries only support assignment via .add")
124
125 def __getitem__(self, key):
126 if not self.__obo_parsed:
127 self.parseOBO()
128
129 for lookup in self.lookups:
130 if key in lookup:
131 if self.MS_tag_regex.match(key):
132 try:
133 return lookup[key]["name"]
134 except:
135 pass
136 return lookup[key]
137 return None
138
139 @staticmethod
140 def __normalize_version(version):
141 """
142 Ensure that a version has 3 components, defaulting to .0 for the
143 missing components.
144
145 Args:
146 version (str): The original version to modify.
147
148 Returns:
149 version (str): The version, normalized to ensure that it has 3
150 parts.
151 """
152 if version is not None:
153 parts = version.split(".")
154
155 missing_parts = 3 - len(parts)
156 if missing_parts > 0:
157 version = ".".join(parts + ["0"] * missing_parts)
158
159 return version
160
161 def download_obo(self, version, obo_file):
162 uri = f"https://raw.githubusercontent.com/pymzml/psi-ms-CV/v{self.version}/psi-ms.obo"
163 urllib.request.urlretrieve(uri, obo_file)
164
165 with open(obo_file, "rb") as fin, gzip.open(obo_file + ".gz", "wb") as fout:
166 fout.writelines(fin.readlines())
167 os.remove(obo_file)
168 return
169
170 def parseOBO(self):
171 self.__obo_parsed = True
172 """
173 Locate and parse the OBO file in the OBO root directory.
174
175 Note:
176
177 cx_Freeze friendly. If using cx_Freeze, place the OBO folder at
178 the location of sys.executable.
179 """
180
181 # TODO: Try to get all the versions, even those without well-defined
182 # version numbers, or get remote hosting of all of the versions
183 # and only download one at will on demand.
184
185 # Modify the root for cx_freeze
186 if getattr(sys, "frozen", False):
187 obo_root = os.path.dirname(sys.executable)
188 else:
189 obo_root = os.path.dirname(__file__)
190
191 obo_file = os.path.join(
192 obo_root,
193 "obo",
194 "psi-ms{0}.obo".format("-" + self.version if self.version else ""),
195 )
196 if os.path.exists(obo_file):
197 pass
198 elif os.path.exists(obo_file + ".gz"):
199 obo_file = obo_file + ".gz"
200 else:
201 self.download_obo(self.version, obo_file)
202 obo_file += ".gz"
203
204 with open(obo_file, "rb") as fin:
205 # never rely on file extensions!
206 first_two_bytes = fin.read(2)
207 # check if file is gzipped by magic bytes
208 if first_two_bytes == b"\x1f\x8b":
209 open_func = gzip.open
210 else:
211 raise Exception(
212 "Filename has .gz extension but is missing the gzip magic bytes.\n"
213 "The file may be corrupted or not gzipped."
214 )
215
216 with open_func(obo_file, "rt", encoding="utf-8") as obo:
217 collections = {}
218 collect = False
219 for line in obo:
220 if line.strip() in ("[Term]", ""):
221 collect = True
222 if not collections:
223 continue
224 self.add(collections)
225 collections = {}
226 else:
227 if line.strip() != "" and collect is True:
228 k = line.find(":")
229 collections[line[:k]] = line[k + 1 :].strip()
230 return
231
232 def add(self, collection_dict):
233 """
234 Add a new dict to the translator.
235
236 Args:
237 collection_dict (dict): python dict containing MS:xxxxxxx name
238 mapping.
239 """
240 if not self.__obo_parsed:
241 self.parseOBO()
242
243 self.all_dicts.append(collection_dict)
244 if "id" in collection_dict.keys():
245 self.id[collection_dict["id"]] = self.all_dicts[-1]
246 if "name" in collection_dict.keys():
247 self.name[collection_dict["name"]] = self.all_dicts[-1]
248 if "def" in collection_dict.keys():
249 self.definition[collection_dict["def"]] = self.all_dicts[-1]
250
251 return
252
253 def checkOBO(self, idTag, name):
254 """
255 Check if idTag equals name in currently used obo version.
256
257 Args:
258 idTag (str): MS accession tag
259 name (str): trivial name of the accession
260
261 Returns:
262 boolean: True if idTag and name correspond, else False.
263 """
264 if not self.__obo_parsed:
265 self.parseOBO()
266
267 if self.id[idTag]["name"] == name:
268 return True
269 else:
270 return False
271
272
273 if __name__ == "__main__":
274 print(__doc__)