Debian Codegraph @

cclib/method/moments.py

raw
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 """Calculation of electric multipole moments based on data parsed by cclib."""
9
10 import sys
11
12 if sys.version_info <= (3, 3):
13 from collections import Iterable
14 else:
15 from collections.abc import Iterable
16
17 import numpy
18
19 from cclib.parser.utils import convertor
20 from cclib.method.calculationmethod import Method
21
22
23 class Moments(Method):
24 """A class used to calculate electric multipole moments.
25
26 The obtained results are stored in `results` attribute as a
27 dictionary whose keys denote the used charge population scheme.
28 """
29 def __init__(self, data):
30 self.required_attrs = ('atomcoords', 'atomcharges')
31 self.results = {}
32
33 super(Moments, self).__init__(data)
34
35 def __str__(self):
36 """Returns a string representation of the object."""
37 return "Multipole moments of %s" % (self.data)
38
39 def __repr__(self):
40 """Returns a representation of the object."""
41 return 'Moments("%s")' % (self.data)
42
43 def _calculate_dipole(self, charges, coords, origin):
44 """Calculate the dipole moment from the given atomic charges
45 and their coordinates with respect to the origin.
46 """
47 transl_coords_au = convertor(coords - origin, 'Angstrom', 'bohr')
48 dipole = numpy.dot(charges, transl_coords_au)
49
50 return convertor(dipole, 'ebohr', 'Debye')
51
52 def _calculate_quadrupole(self, charges, coords, origin):
53 """Calculate the traceless quadrupole moment from the given
54 atomic charges and their coordinates with respect to the origin.
55 """
56 transl_coords_au = convertor(coords - origin, 'Angstrom', 'bohr')
57
58 delta = numpy.eye(3)
59 Q = numpy.zeros([3, 3])
60 for i in range(3):
61 for j in range(3):
62 for q, r in zip(charges, transl_coords_au):
63 Q[i,j] += 1/2 * q * (3 * r[i] * r[j] - \
64 numpy.linalg.norm(r)**2 * delta[i,j])
65
66 triu_idxs = numpy.triu_indices_from(Q)
67 raveled_idxs = numpy.ravel_multi_index(triu_idxs, Q.shape)
68 quadrupole = numpy.take(Q.flatten(), raveled_idxs)
69
70 return convertor(quadrupole, 'ebohr2', 'Buckingham')
71
72 def calculate(self, origin='nuccharge', population='mulliken',
73 masses=None):
74 """Calculate electric dipole and quadrupole moments using parsed
75 partial atomic charges.
76
77 Inputs:
78 origin - a choice of the origin of coordinate system. Can be
79 either a three-element iterable or a string. If
80 iterable, then it explicitly defines the origin (in
81 Angstrom). If string, then the value can be any one of
82 the following and it describes what is used as the
83 origin:
84 * 'nuccharge' -- center of positive nuclear charge
85 * 'mass' -- center of mass
86 population - a type of population analysis used to extract
87 corresponding atomic charges from the output file.
88 masses - if None, then use default atomic masses. Otherwise,
89 the user-provided will be used.
90
91 Returns:
92 A list where the first element is the origin of coordinates,
93 while other elements are dipole and quadrupole moments
94 expressed in terms of Debye and Buckingham units
95 respectively.
96
97 Raises:
98 ValueError when an argument with incorrect value or of
99 inappropriate type is passed to a method.
100
101 Notes:
102 To calculate the quadrupole moment the Buckingham definition
103 [1]_ is chosen. Hirschfelder et al. [2]_ define it two times
104 as much.
105
106 References:
107 .. [1] Buckingham, A. D. (1959). Molecular quadrupole moments.
108 Quarterly Reviews, Chemical Society, 13(3), 183.
109 https://doi.org:10.1039/qr9591300183.
110 .. [2] Hirschfelder J. O., Curtiss C. F. and Bird R. B. (1954).
111 The Molecular Theory of Gases and Liquids. New York: Wiley.
112 """
113 coords = self.data.atomcoords[-1]
114 try:
115 charges = self.data.atomcharges[population]
116 except KeyError as e:
117 msg = ("charges coming from requested population analysis"
118 "scheme are not parsed")
119 raise ValueError(msg, e)
120
121 if isinstance(origin, Iterable) and not isinstance(origin, str):
122 origin_pos = numpy.asarray(origin)
123 elif origin == 'nuccharge':
124 origin_pos = numpy.average(coords, weights=self.data.atomnos, axis=0)
125 elif origin == 'mass':
126 if masses:
127 atommasses = numpy.asarray(masses)
128 else:
129 try:
130 atommasses = self.data.atommasses
131 except AttributeError as e:
132 msg = ("atomic masses were not parsed, consider provide "
133 "'masses' argument instead")
134 raise ValueError(msg, e)
135 origin_pos = numpy.average(coords, weights=atommasses, axis=0)
136 else:
137 raise ValueError("{} is invalid value for 'origin'".format(origin))
138
139 dipole = self._calculate_dipole(charges, coords, origin_pos)
140 quadrupole = self._calculate_quadrupole(charges, coords, origin_pos)
141
142 rv = [origin_pos, dipole, quadrupole]
143 self.results.update({population: rv})
144
145 return rv