Debian Codegraph @

gavo/protocols/linetap.py

raw
1 """
2 Support code for linetap.
3
4 This, in particular, contains bindings to the InChI library.
5 Use getILib() to obtain the bindings, and see the _InChIBindings
6 docstrings on what you can all. It probably helps to be aware of
7 https://www.inchi-trust.org/wp/download/104/InChI_API_Reference.pdf
8 although the binding is substantially different.
9
10 This binding probably leaks memory left and right; I have not given
11 this a great deal of thought so far, as I don't expect InChI manipulations
12 will be common in long-running code. If that's overly optimistic, then
13 we'll need a round of leak hunting.
14 """
15
16 #c Copyright 2008-2025, the GAVO project <[email protected]>
17 #c
18 #c This program is free software, covered by the GNU GPL. See the
19 #c COPYING file in the source distribution.
20
21
22 import contextlib
23 import ctypes
24 import functools
25 import re
26 import warnings
27 from ctypes.util import find_library
28
29 from gavo import base
30 from gavo import utils
31
32
33 class InChIError(utils.Error):
34 """is raised when a libinchi function indicates an error has
35 occurred.
36
37 This is usually rather cryptic but ought to return a numeric
38 code that can be decoded using the libinchi API document.
39 """
40
41
42 _EL_DATA_RE = re.compile(r'\{\s*"([A-Za-z]+)",' # Element name
43 r"\s*(\d+)," # average mass
44 r"\s*(\d+)," # norm mass
45 r"\s*([\d.]+)," # avg mass
46 r"\s*(METAL2?|0)\s*," # type
47 r"\s*(\d+)," # electronegativity
48 r"\s*(\d)," # "No H" (no clue:-)
49 r"\s*([0-9,{}]+)"
50 r"\}")
51
52 def _parseInchiElData(line):
53 """returns a dictionary of parsed items for a line in data/element_data.txt.
54
55 These are C structure literals, but I blindly kill things with REs.
56 """
57 mat = _EL_DATA_RE.match(line)
58 return {
59 "name": mat.group(1),
60 "avg weight": int(mat.group(2)),
61 "weight": int(mat.group(3)),
62 "exact weight": float(mat.group(4)),
63 "type": mat.group(5),
64 "el. neg": int(mat.group(6)),
65 # TODO: parse out valences, perhaps do something with "No H"
66 }
67
68
69 @functools.lru_cache(None)
70 def getElementData():
71 """returns a dictionary from element names to a dictionary of
72 element properties.
73 """
74 elementData = {}
75 with base.openDistFile("data/element_data.txt") as f:
76 for lineNumber, line in utils.iterSimpleText(f):
77 el = _parseInchiElData(line)
78 elementData[el["name"]] = el
79 return elementData
80
81
82 # The following values should really be parsed from /usr/include/inchi_api.h
83 # Maximum bonds per atom
84 MAXVAL = 20
85 ATOM_EL_LEN = 6
86
87 class _inchi_Atom(ctypes.Structure):
88 _fields_ = [
89 ("x", ctypes.c_double),
90 ("y", ctypes.c_double),
91 ("z", ctypes.c_double),
92 ("neighbor", ctypes.c_short*MAXVAL),
93 ("bond_type", ctypes.c_byte*MAXVAL),
94 ("bond_stereo", ctypes.c_char*MAXVAL),
95 ("elname", ctypes.c_char*ATOM_EL_LEN),
96 ("num_bonds", ctypes.c_short),
97 ("num_iso_H", ctypes.c_byte*4),
98 ("isotopic_mass", ctypes.c_short),
99 ("radical", ctypes.c_char),
100 ("charge", ctypes.c_byte)]
101
102 def connect(self, otherAtomIndex, bond_type):
103 """Adds a connection to otherAtomIndex.
104
105 User code will probably rather use _inchi_Input's connect method,
106 as it usually cannot know otherAtomIndex.
107 """
108 if self.num_bonds==MAXVAL:
109 raise InChIError("Too many connections")
110 self.neighbor[self.num_bonds] = otherAtomIndex
111 self.bond_type[self.num_bonds] = bond_type
112 self.num_bonds += 1
113
114 def getElementInfo(self):
115 res = getElementData()[utils.debytify(self.elname)]
116 if self.isotopic_mass:
117 res = res.copy()
118 if self.isotopic_mass>1000:
119 res["weight"] += self.isotopic_mass-10000
120 else:
121 res["weight"] = self.isotopic_mass
122 return res
123
124
125 class _inchi_Stereo0D(ctypes.Structure):
126 _fields_ = [
127 ("neighbor", ctypes.c_short*4),
128 ("central_atom", ctypes.c_short),
129 ("type", ctypes.c_char),
130 ("parity", ctypes.c_char),
131 ]
132
133
134 class _MoleculeMixin:
135 """a mixin for structs having atoms.
136 """
137 def iterAtoms(self):
138 for atomIndex in range(self.num_atoms):
139 yield self.atom[atomIndex]
140
141 def getTotalWeight(self):
142 """returns the total molecular weight of the substance.
143
144 This takes isotopy into account.
145 """
146 totalWeight = 0
147 for atom in self.iterAtoms():
148 totalWeight += atom.getElementInfo()["weight"]
149
150 for hIso in range(1, 4):
151 totalWeight += atom.num_iso_H[hIso]*hIso
152 # no idea what the implicit H-s should really count as.
153 totalWeight += atom.num_iso_H[0]
154
155 return totalWeight
156
157 def getTotalCharge(self):
158 """returns the total charge of all compounds.
159 """
160 return sum(atom.charge
161 for atom in self.iterAtoms())
162
163
164 class _inchi_Input(ctypes.Structure, _MoleculeMixin):
165 _fields_ = [
166 ("atom", ctypes.POINTER(_inchi_Atom)),
167 ("stereo0D", ctypes.POINTER(_inchi_Stereo0D)),
168 ("szOptions", ctypes.c_char_p),
169 ("num_atoms", ctypes.c_int),
170 ("num_stereo0D", ctypes.c_int),]
171
172 def connect(self, atomIndex1, atomIndex2, bond_type=1):
173 """add a bond between the atom at index1 and index2.
174 """
175 if (not 0<=atomIndex1<self.num_atoms
176 or not 0<=atomIndex2<self.num_atoms):
177 raise InChIError("Atom indexes must be < {} here".format(
178 self.num_atoms))
179
180 self.atom[atomIndex1].connect(atomIndex2, bond_type)
181 self.atom[atomIndex2].connect(atomIndex1, bond_type)
182
183
184
185 class _inchi_OutputStruct(ctypes.Structure, _MoleculeMixin):
186 _fields_ = [
187 ("atom", ctypes.POINTER(_inchi_Atom)),
188 ("stereo0D", ctypes.POINTER(_inchi_Stereo0D)),
189 ("num_atoms", ctypes.c_short),
190 ("num_stereo0D", ctypes.c_short),
191 ("szMessage", ctypes.c_char_p),
192 ("szLog", ctypes.c_char_p),
193 ("WarningFlags", ctypes.c_long*4)]
194
195
196 class _inchi_Output(ctypes.Structure):
197 _fields_ = [
198 ("szInChI", ctypes.c_char_p),
199 ("szAuxInfo", ctypes.c_char_p),
200 ("szMessage", ctypes.c_char_p),
201 ("szLog", ctypes.c_char_p)]
202
203
204 class _inchi_InputINCHI(ctypes.Structure):
205 _fields_ = [
206 ("szInChI", ctypes.c_char_p),
207 ("szOptions", ctypes.c_char_p),
208 ]
209
210
211 class _InChIBinding:
212 """A class encapsulating our binding to libinchi.
213
214 This is intended to be a singleton; users ought to obtain it through
215 the getInChI function below.
216
217 This will raise a ReportableError if the inchi C library cannot be found.
218 """
219 _libname = "inchi"
220
221 def __init__(self):
222 self.libPath = find_library(self._libname)
223 if self.libPath is None:
224 raise base.ReportableError("No libinchi found.",
225 hint="On Debian systems, install libinchi1 to get it.")
226
227 self.lib = ctypes.CDLL(self.libPath)
228
229 for wrappedName, argtypes in [
230 ("CheckINCHI", [ctypes.c_char_p, ctypes.c_int]),
231 ("GetStdINCHIKeyFromStdINCHI",
232 [ctypes.c_char_p, ctypes.c_char_p]),
233 ("GetINCHIKeyFromINCHI",
234 [ctypes.c_char_p, ctypes.c_int, ctypes.c_int, ctypes.c_char_p,
235 ctypes.c_char_p, ctypes.c_char_p]),
236 ("GetINCHI",
237 [ctypes.POINTER(_inchi_Input), ctypes.POINTER(_inchi_Output)]),
238 ("GetStdINCHI",
239 [ctypes.POINTER(_inchi_Input), ctypes.POINTER(_inchi_Output)]),
240 ("GetINCHIfromINCHI",
241 [ctypes.POINTER(_inchi_InputINCHI), ctypes.POINTER(_inchi_Output)]),
242 ("GetStructFromINCHI",
243 [ctypes.POINTER(_inchi_InputINCHI),
244 ctypes.POINTER(_inchi_OutputStruct)]),
245 ("FreeStdINCHI", [ctypes.POINTER(_inchi_Output)]),
246 ("FreeStructFromINCHI", [ctypes.POINTER(_inchi_OutputStruct)]),
247 ]:
248 setattr(self, "_"+wrappedName, getattr(self.lib, wrappedName))
249 getattr(self, "_"+wrappedName).argtypes = argtypes
250
251 def checkInChI(self, inchi, strict=1):
252 """returns 0 if inchi is ok, something else (cf. API docs) otherwise.
253 """
254 return self._CheckINCHI(utils.bytify(inchi), ctypes.c_int(strict))
255
256 def getInChIKey(self, inChI):
257 """returns an InChIKey for a standard InChI.
258 """
259 buf = ctypes.create_string_buffer(28)
260 retval = self._GetINCHIKeyFromINCHI(
261 utils.bytify(inChI), 0, 0, buf, None, None)
262 if retval!=0:
263 raise InChIError(f"Could not generate InChIKey: {retval}")
264 return utils.debytify(buf.value)
265
266 def getInput(self, atoms):
267 """returns an _inchi_Input for a list of inchi_Atoms.
268
269 This is what you need to call to generate an InChI(Key). Essentially,
270 you create atoms using getAtom, put them into a list, pass them
271 to getInput and then call connect(index1, index2) to make the
272 molecule connections.
273 """
274 atomsArray = (_inchi_Atom*len(atoms))(*atoms)
275 return _inchi_Input(
276 atom=atomsArray,
277 stereo0D=None,
278 szOptions=b"-DoNotAddH",
279 num_atoms=len(atoms),
280 num_stereo0D=0)
281
282 def getAtom(self, elname, isotopic_mass=0, charge=0):
283 """returns a new atom.
284
285 Only pass isotopic_mass if you actually care about isotopism.
286 """
287 neighbor = (ctypes.c_short*MAXVAL)(*([0]*MAXVAL))
288 bond_type = (ctypes.c_byte*MAXVAL)(*([0]*MAXVAL))
289
290 return _inchi_Atom(
291 x=0, y=0, z=0,
292 neighbor=neighbor,
293 bond_type=bond_type, # (i.e., single, double... binding)
294 bond_stereo=b"", # (let's see when we want it)
295 elname=utils.bytify(elname),
296 num_bonds=0,
297 num_iso_H=(ctypes.c_byte*4)(0, 0, 0, 0),
298 isotopic_mass=isotopic_mass,
299 radical=0,
300 charge=ctypes.c_byte(charge))
301
302 def _handleAndFree(self, retval, output, input=None):
303 try:
304 self._interpretICReturnCode(retval, output, input)
305 return utils.debytify(output.szInChI)
306 finally:
307 self._FreeStdINCHI(output)
308
309 _errcodes = {
310 0: "Success",
311 2: "No InChi created",
312 3: "Severe error (out of memory?)",
313 4: "Unknown error",
314 5: "Previous call has not returned yet",
315 -1: "No structural data provided"}
316
317 def _interpretICReturnCode(self, retval, output, input=None):
318 if retval==1:
319 if input is not None:
320 warnings.warn("Source for the following warning: "+input)
321 warnings.warn("InChI warning: "+utils.debytify(output.szMessage))
322 elif retval!=0:
323 raise InChIError(utils.debytify(output.szMessage
324 or self._errcodes.get(retval, "(Unclear problem)")),
325 hint=utils.debytify(output.szLog))
326
327 def getInChI(self, inchiInput, rawInput=None):
328 """returns the InChI of the molecule described through inchiInput
329 as a string.
330 """
331 output = _inchi_Output()
332 res = self._GetStdINCHI(inchiInput, output)
333 return self._handleAndFree(res, output, rawInput)
334
335 def normalizeInChI(self, inChI):
336 """returns a string inChI in normalised form.
337 """
338 output = _inchi_Output()
339 res = self._GetINCHIfromINCHI(
340 _inchi_InputINCHI(utils.bytify(inChI)), output)
341 return self._handleAndFree(res, output)
342
343 _dcodeAtom = re.compile(r"(?P<iso>\d+)?(?P<at>[A-Z][a-z]?)(?P<ch>[-+]+)?$")
344 _dcodeConn = re.compile(r"(\d+)([-=#])(\d+)$")
345 _dcodeMult = {'-': 1, '=': 2, '#': 3}
346
347 def _freeStructAfterUse(self, struct):
348 """returns a context manager returning struct and freeing it once
349 the controlled block is through.
350 """
351 def _():
352 try:
353 yield struct
354 finally:
355 self._FreeStructFromINCHI(struct)
356
357 return contextlib.contextmanager(_)()
358
359 def parseInChI(self, inchi):
360 """returns a context manager for a parsed inchi from a string inchi.
361
362 The result is probably not fun to work with, but it has
363 getTotalWeight and getTotalCharge methods that are handy
364 for filling LineTAP tables with incoming inchis.
365
366 This returns a context manager so the stuff allocated by
367 libinchi gets freed again. So, you'll use this like::
368
369 with ilib.parseInChI("InChI=1S...") as molecule:
370 (do something)
371 """
372 struct = _inchi_OutputStruct()
373 input = _inchi_InputINCHI(utils.bytify(inchi))
374 retval = self._GetStructFromINCHI(input, struct)
375 self._interpretICReturnCode(retval, struct, inchi)
376
377 return self._freeStructAfterUse(struct)
378
379
380 def getInChIFromCode(self, code):
381 """returns a pair on (input, InChI) from a rather simple heuristic code.
382
383 The input part may be useful if you want to manipulate it further;
384 it's an _inchi_Input with iterAtoms and getTotalWeight methods.
385
386 This consists of whitespace-separated atoms or connections in arbitrary
387 order. An atom is [isotope]Atom[charge], where isotope is a number
388 and charge a number of + or -. A connection is index(-=#)index, where
389 index enumerates the atom, 1-based and -,=,# is a single, double, or
390 triple bind.
391
392 Yeah, I know it sucks there's *another* molecule input format, but,
393 really, the chemistry people drove me crazy.
394
395 Examples for this are found in tests/slaptest.py
396 """
397 atoms, connections = [], []
398 for tok in code.split():
399 mat = self._dcodeConn.match(tok)
400 if mat:
401 connections.append((self._dcodeMult[mat.group(2)],
402 int(mat.group(1)), int(mat.group(3))))
403 continue
404
405 mat = self._dcodeAtom.match(tok)
406 if mat:
407 pars = mat.groupdict("")
408 charge = 0
409 if pars["ch"]:
410 charge = len(pars["ch"])*{"+": 1, "-": -1}[pars["ch"][0]]
411
412 atoms.append(self.getAtom(
413 mat.group("at"),
414 int(mat.group("iso") or "0"),
415 charge))
416
417 continue
418
419 raise ValueError(f"Invalid molecule code token: '{tok}'")
420
421 mol = self.getInput(atoms)
422 for bond_type, index1, index2 in connections:
423 mol.connect(index1-1, index2-1, bond_type)
424
425 return mol, self.getInChI(mol, code)
426
427
428 @functools.lru_cache(None)
429 def getILib():
430 """returns a shallow binding to the InChI library.
431
432 This will always return the same object if called multiple times.
433 It will raise a ReportableError if the library is not available.
434 """
435 return _InChIBinding()