Debian Codegraph @

cclib/bridge/cclib2openbabel.py

raw
1 # -*- coding: utf-8 -*-
2 #
3 # Copyright (c) 2017, the cclib development team
4 #
5 # This file is part of cclib (http://cclib.github.io) and is distributed under
6 # the terms of the BSD 3-Clause License.
7
8 """Bridge between cclib data and openbabel (http://openbabel.org)."""
9
10 from cclib.parser.data import ccData
11 from cclib.parser.utils import find_package
12
13 _found_openbabel = find_package("openbabel")
14 if _found_openbabel:
15 import openbabel as ob
16
17
18 def _check_openbabel(found_openbabel):
19 if not found_openbabel:
20 raise ImportError("You must install `openbabel` to use this function")
21
22
23 def makecclib(mol):
24 """Create cclib attributes and return a ccData from an OpenBabel molecule.
25
26 Beyond the numbers, masses and coordinates, we could also set the total charge
27 and multiplicity, but often these are calculated from atomic formal charges
28 so it is better to assume that would not be correct.
29 """
30 _check_openbabel(_found_openbabel)
31 attributes = {
32 'atomcoords': [],
33 'atommasses': [],
34 'atomnos': [],
35 'natom': mol.NumAtoms(),
36 }
37 for atom in ob.OBMolAtomIter(mol):
38 attributes['atomcoords'].append([atom.GetX(), atom.GetY(), atom.GetZ()])
39 attributes['atommasses'].append(atom.GetAtomicMass())
40 attributes['atomnos'].append(atom.GetAtomicNum())
41 return ccData(attributes)
42
43
44 def makeopenbabel(atomcoords, atomnos, charge=0, mult=1):
45 """Create an Open Babel molecule."""
46 _check_openbabel(_found_openbabel)
47 obmol = ob.OBMol()
48 for i in range(len(atomnos)):
49 # Note that list(atomcoords[i]) is not equivalent!!!
50 # For now, only take the last geometry.
51 # TODO: option to export last geometry or all geometries?
52 coords = atomcoords[-1][i].tolist()
53 atomno = int(atomnos[i])
54 obatom = ob.OBAtom()
55 obatom.SetAtomicNum(atomno)
56 obatom.SetVector(*coords)
57 obmol.AddAtom(obatom)
58 obmol.ConnectTheDots()
59 obmol.PerceiveBondOrders()
60 obmol.SetTotalSpinMultiplicity(mult)
61 obmol.SetTotalCharge(int(charge))
62 return obmol
63
64
65 def readfile(fname, format):
66 """Read a file with OpenBabel and extract cclib attributes."""
67 _check_openbabel(_found_openbabel)
68 obc = ob.OBConversion()
69 if obc.SetInFormat(format):
70 mol = ob.OBMol()
71 obc.ReadFile(mol, fname)
72 return makecclib(mol)
73 else:
74 print("Unable to load the %s reader from OpenBabel." % format)
75 return {}
76
77
78 del find_package