| 1 |
|
| 2 |
|
| 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 |
|
| 61 |
n |
| 62 |
|
| 63 |
|
| 64 |
|
| 65 |
|
| 66 |
|
| 67 |
|
| 68 |
|
| 69 |
|
| 70 |
|
| 71 |
|
| 72 |
|
| 73 |
|
| 74 |
|
| 75 |
|
| 76 |
|
| 77 |
|
| 78 |
|
| 79 |
|
| 80 |
|
| 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 |
|
| 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 |
|
| 182 |
|
| 183 |
|
| 184 |
|
| 185 |
|
| 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 |
|
| 206 |
first_two_bytes = fin.read(2) |
| 207 |
|
| 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__) |