| 1 |
# -*- coding: utf-8 -*- |
| 2 |
# |
| 3 |
# Copyright (c) 2018, 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 |
"""Generic file writer and related tools""" |
| 9 |
|
| 10 |
import logging |
| 11 |
import sys |
| 12 |
from abc import ABCMeta, abstractmethod |
| 13 |
from six import add_metaclass |
| 14 |
|
| 15 |
|
| 16 |
if sys.version_info <= (3, 3): |
| 17 |
from collections import Iterable |
| 18 |
else: |
| 19 |
from collections.abc import Iterable |
| 20 |
|
| 21 |
import numpy |
| 22 |
|
| 23 |
from cclib.parser.utils import PeriodicTable |
| 24 |
from cclib.parser.utils import find_package |
| 25 |
|
| 26 |
_has_openbabel = find_package("openbabel") |
| 27 |
if _has_openbabel: |
| 28 |
from cclib.bridge import makeopenbabel |
| 29 |
import openbabel as ob |
| •30 |
import openbabel.pybel as pb |
| 31 |
|
| 32 |
|
| 33 |
class MissingAttributeError(Exception): |
| 34 |
pass |
| 35 |
|
| 36 |
|
| 37 |
@add_metaclass(ABCMeta) |
| 38 |
class Writer: |
| 39 |
"""Abstract class for writer objects.""" |
| 40 |
|
| 41 |
required_attrs = () |
| 42 |
|
| 43 |
def __init__(self, ccdata, jobfilename=None, indices=None, terse=False, |
| 44 |
*args, **kwargs): |
| 45 |
"""Initialize the Writer object. |
| 46 |
|
| 47 |
This should be called by a subclass in its own __init__ method. |
| 48 |
|
| 49 |
Inputs: |
| 50 |
ccdata - An instance of ccData, parsed from a logfile. |
| 51 |
jobfilename - The filename of the parsed logfile. |
| 52 |
indices - One or more indices for extracting specific geometries/etc. (zero-based) |
| 53 |
terse - Whether to print the terse version of the output file - currently limited to cjson/json formats |
| 54 |
""" |
| 55 |
|
| 56 |
self.ccdata = ccdata |
| 57 |
self.jobfilename = jobfilename |
| 58 |
self.indices = indices |
| 59 |
self.terse = terse |
| 60 |
self.ghost = kwargs.get("ghost") |
| 61 |
|
| 62 |
self.pt = PeriodicTable() |
| 63 |
|
| 64 |
self._check_required_attributes() |
| 65 |
|
| 66 |
# Open Babel isn't necessarily present. |
| 67 |
if _has_openbabel: |
| 68 |
# Generate the Open Babel/Pybel representation of the molecule. |
| 69 |
# Used for calculating SMILES/InChI, formula, MW, etc. |
| 70 |
self.obmol, self.pbmol = self._make_openbabel_from_ccdata() |
| 71 |
self.bond_connectivities = self._make_bond_connectivity_from_openbabel(self.obmol) |
| 72 |
|
| 73 |
self._fix_indices() |
| 74 |
|
| 75 |
@abstractmethod |
| 76 |
def generate_repr(self): |
| 77 |
"""Generate the written representation of the logfile data.""" |
| 78 |
|
| 79 |
def _calculate_total_dipole_moment(self): |
| 80 |
"""Calculate the total dipole moment.""" |
| 81 |
|
| 82 |
# ccdata.moments may exist, but only contain center-of-mass coordinates |
| 83 |
if len(getattr(self.ccdata, 'moments', [])) > 1: |
| 84 |
return numpy.linalg.norm(self.ccdata.moments[1]) |
| 85 |
|
| 86 |
def _check_required_attributes(self): |
| 87 |
"""Check if required attributes are present in ccdata.""" |
| 88 |
missing = [x for x in self.required_attrs |
| 89 |
if not hasattr(self.ccdata, x)] |
| 90 |
if missing: |
| 91 |
missing = ' '.join(missing) |
| 92 |
raise MissingAttributeError( |
| 93 |
'Could not parse required attributes to write file: ' + missing) |
| 94 |
|
| 95 |
def _make_openbabel_from_ccdata(self): |
| 96 |
"""Create Open Babel and Pybel molecules from ccData.""" |
| 97 |
if not hasattr(self.ccdata, 'charge'): |
| 98 |
logging.warning("ccdata object does not have charge, setting to 0") |
| 99 |
_charge = 0 |
| 100 |
else: |
| 101 |
_charge = self.ccdata.charge |
| 102 |
if not hasattr(self.ccdata, 'mult'): |
| 103 |
logging.warning("ccdata object does not have spin multiplicity, setting to 1") |
| 104 |
_mult = 1 |
| 105 |
else: |
| 106 |
_mult = self.ccdata.mult |
| 107 |
obmol = makeopenbabel(self.ccdata.atomcoords, |
| 108 |
self.ccdata.atomnos, |
| 109 |
charge=_charge, |
| 110 |
mult=_mult) |
| 111 |
if self.jobfilename is not None: |
| 112 |
obmol.SetTitle(self.jobfilename) |
| 113 |
return (obmol, pb.Molecule(obmol)) |
| 114 |
|
| 115 |
def _make_bond_connectivity_from_openbabel(self, obmol): |
| 116 |
"""Based upon the Open Babel/Pybel molecule, create a list of tuples |
| 117 |
to represent bonding information, where the three integers are |
| 118 |
the index of the starting atom, the index of the ending atom, |
| 119 |
and the bond order. |
| 120 |
""" |
| 121 |
bond_connectivities = [] |
| 122 |
for obbond in ob.OBMolBondIter(obmol): |
| 123 |
bond_connectivities.append((obbond.GetBeginAtom().GetIndex(), |
| 124 |
obbond.GetEndAtom().GetIndex(), |
| 125 |
obbond.GetBondOrder())) |
| 126 |
return bond_connectivities |
| 127 |
|
| 128 |
def _fix_indices(self): |
| 129 |
"""Clean up the index container type and remove zero-based indices to |
| 130 |
prevent duplicate structures and incorrect ordering when |
| 131 |
indices are later sorted. |
| 132 |
""" |
| 133 |
if not self.indices: |
| 134 |
self.indices = set() |
| 135 |
elif not isinstance(self.indices, Iterable): |
| 136 |
self.indices = set([self.indices]) |
| 137 |
# This is the most likely place to get the number of |
| 138 |
# geometries from. |
| 139 |
if hasattr(self.ccdata, 'atomcoords'): |
| 140 |
lencoords = len(self.ccdata.atomcoords) |
| 141 |
indices = set() |
| 142 |
for i in self.indices: |
| 143 |
if i < 0: |
| 144 |
i += lencoords |
| 145 |
indices.add(i) |
| 146 |
self.indices = indices |
| 147 |
return |
| 148 |
|
| 149 |
|
| 150 |
del find_package |