Debian Codegraph @

cclib/method/volume.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 """Calculation methods related to volume based on cclib data."""
9
10 from __future__ import print_function
11 import copy
12
13 import numpy
14
15 from cclib.parser.utils import convertor
16 from cclib.parser.utils import find_package
17
18 _found_pyquante = find_package("PyQuante")
19 if _found_pyquante:
20 from PyQuante.CGBF import CGBF
21 from cclib.bridge import cclib2pyquante
22
23 _found_pyvtk = find_package("pyvtk")
24 if _found_pyvtk:
25 from pyvtk import *
26 from pyvtk.DataSetAttr import *
27
28
29 def _check_pyvtk(found_pyvtk):
30 if not found_pyvtk:
31 raise ImportError("You must install `pyvtk` to use this function")
32
33
34 class Volume(object):
35 """Represent a volume in space.
36
37 Required parameters:
38 origin -- the bottom left hand corner of the volume
39 topcorner -- the top right hand corner
40 spacing -- the distance between the points in the cube
41
42 Attributes:
43 data -- a NumPy array of values for each point in the volume
44 (set to zero at initialisation)
45 numpts -- the numbers of points in the (x,y,z) directions
46 """
47
48 def __init__(self, origin, topcorner, spacing):
49
50 self.origin = numpy.asarray(origin, dtype=float)
51 self.topcorner = numpy.asarray(topcorner, dtype=float)
52 self.spacing = numpy.asarray(spacing, dtype=float)
53 self.numpts = []
54 for i in range(3):
55 self.numpts.append(int((self.topcorner[i] - self.origin[i]) / self.spacing[i] + 1))
56 self.data = numpy.zeros(tuple(self.numpts), "d")
57
58 def __str__(self):
59 """Return a string representation."""
60 return "Volume %s to %s (density: %s)" % (self.origin, self.topcorner,
61 self.spacing)
62
63 def write(self, filename, fformat="Cube"):
64 """Write the volume to a file."""
65
66 fformat = fformat.lower()
67
68 writers = {
69 "vtk": self.writeasvtk,
70 "cube": self.writeascube,
71 }
72
73 if fformat not in writers:
74 raise RuntimeError("File format must be either VTK or Cube")
75
76 writers[fformat](filename)
77
78 def writeasvtk(self, filename):
79 _check_pyvtk(_found_pyvtk)
80 ranges = (numpy.arange(self.data.shape[2]),
81 numpy.arange(self.data.shape[1]),
82 numpy.arange(self.data.shape[0]))
83 v = VtkData(RectilinearGrid(*ranges), "Test",
84 PointData(Scalars(self.data.ravel(), "from cclib", "default")))
85 v.tofile(filename)
86
87 def integrate(self):
88 boxvol = (self.spacing[0] * self.spacing[1] * self.spacing[2] *
89 convertor(1, "Angstrom", "bohr") ** 3)
90 return sum(self.data.ravel()) * boxvol
91
92 def integrate_square(self):
93 boxvol = (self.spacing[0] * self.spacing[1] * self.spacing[2] *
94 convertor(1, "Angstrom", "bohr") ** 3)
95 return sum(self.data.ravel() ** 2) * boxvol
96
97 def writeascube(self, filename):
98 # Remember that the units are bohr, not Angstroms
99 def convert(x):
100 return convertor(x, "Angstrom", "bohr")
101 ans = []
102 ans.append("Cube file generated by cclib")
103 ans.append("")
104 format = "%4d%12.6f%12.6f%12.6f"
105 origin = [convert(x) for x in self.origin]
106 ans.append(format % (0, origin[0], origin[1], origin[2]))
107 ans.append(format % (self.data.shape[0], convert(self.spacing[0]), 0.0, 0.0))
108 ans.append(format % (self.data.shape[1], 0.0, convert(self.spacing[1]), 0.0))
109 ans.append(format % (self.data.shape[2], 0.0, 0.0, convert(self.spacing[2])))
110 line = []
111 for i in range(self.data.shape[0]):
112 for j in range(self.data.shape[1]):
113 for k in range(self.data.shape[2]):
114 line.append(scinotation(self.data[i, j, k]))
115 if len(line) == 6:
116 ans.append(" ".join(line))
117 line = []
118 if line:
119 ans.append(" ".join(line))
120 line = []
121 with open(filename, "w") as outputfile:
122 outputfile.write("\n".join(ans))
123
124
125 def scinotation(num):
126 """Write in scientific notation."""
127 ans = "%10.5E" % num
128 broken = ans.split("E")
129 exponent = int(broken[1])
130 if exponent < -99:
131 return " 0.000E+00"
132 if exponent < 0:
133 sign = "-"
134 else:
135 sign = "+"
136 return ("%sE%s%s" % (broken[0], sign, broken[1][-2:])).rjust(12)
137
138
139 def getbfs(coords, gbasis):
140 """Convenience function for both wavefunction and density based on PyQuante Ints.py."""
141 mymol = cclib2pyquante.makepyquante(coords, [0 for _ in coords])
142
143 sym2powerlist = {
144 'S' : [(0, 0, 0)],
145 'P' : [(1, 0, 0), (0, 1, 0), (0, 0, 1)],
146 'D' : [(2, 0, 0), (0, 2, 0), (0, 0, 2), (1, 1, 0), (0, 1, 1), (1, 0, 1)],
147 'F' : [(3, 0, 0), (2, 1, 0), (2, 0, 1), (1, 2, 0), (1, 1, 1), (1, 0, 2),
148 (0, 3, 0), (0, 2, 1), (0, 1, 2), (0, 0, 3)]
149 }
150
151 bfs = []
152 for i, atom in enumerate(mymol):
153 bs = gbasis[i]
154 for sym, prims in bs:
155 for power in sym2powerlist[sym]:
156 bf = CGBF(atom.pos(), power)
157 for expnt, coef in prims:
158 bf.add_primitive(expnt, coef)
159 bf.normalize()
160 bfs.append(bf)
161
162 return bfs
163
164
165 def wavefunction(coords, mocoeffs, gbasis, volume):
166 """Calculate the magnitude of the wavefunction at every point in a volume.
167
168 Attributes:
169 coords -- the coordinates of the atoms
170 mocoeffs -- mocoeffs for one eigenvalue
171 gbasis -- gbasis from a parser object
172 volume -- a template Volume object (will not be altered)
173 """
174 bfs = getbfs(coords, gbasis)
175
176 wavefn = copy.copy(volume)
177 wavefn.data = numpy.zeros(wavefn.data.shape, "d")
178
179 conversion = convertor(1, "bohr", "Angstrom")
180 x = numpy.arange(wavefn.origin[0], wavefn.topcorner[0] + wavefn.spacing[0], wavefn.spacing[0]) / conversion
181 y = numpy.arange(wavefn.origin[1], wavefn.topcorner[1] + wavefn.spacing[1], wavefn.spacing[1]) / conversion
182 z = numpy.arange(wavefn.origin[2], wavefn.topcorner[2] + wavefn.spacing[2], wavefn.spacing[2]) / conversion
183
184 for bs in range(len(bfs)):
185 data = numpy.zeros(wavefn.data.shape, "d")
186 for i, xval in enumerate(x):
187 for j, yval in enumerate(y):
188 for k, zval in enumerate(z):
189 data[i, j, k] = bfs[bs].amp(xval, yval, zval)
190 data *= mocoeffs[bs]
191 wavefn.data += data
192
193 return wavefn
194
195
196 def electrondensity(coords, mocoeffslist, gbasis, volume):
197 """Calculate the magnitude of the electron density at every point in a volume.
198
199 Attributes:
200 coords -- the coordinates of the atoms
201 mocoeffs -- mocoeffs for all of the occupied eigenvalues
202 gbasis -- gbasis from a parser object
203 volume -- a template Volume object (will not be altered)
204
205 Note: mocoeffs is a list of NumPy arrays. The list will be of length 1
206 for restricted calculations, and length 2 for unrestricted.
207 """
208 bfs = getbfs(coords, gbasis)
209
210 density = copy.copy(volume)
211 density.data = numpy.zeros(density.data.shape, "d")
212
213 conversion = convertor(1, "bohr", "Angstrom")
214 x = numpy.arange(density.origin[0], density.topcorner[0] + density.spacing[0], density.spacing[0]) / conversion
215 y = numpy.arange(density.origin[1], density.topcorner[1] + density.spacing[1], density.spacing[1]) / conversion
216 z = numpy.arange(density.origin[2], density.topcorner[2] + density.spacing[2], density.spacing[2]) / conversion
217
218 for mocoeffs in mocoeffslist:
219 for mocoeff in mocoeffs:
220 wavefn = numpy.zeros(density.data.shape, "d")
221 for bs in range(len(bfs)):
222 data = numpy.zeros(density.data.shape, "d")
223 for i, xval in enumerate(x):
224 for j, yval in enumerate(y):
225 tmp = []
226 for zval in z:
227 tmp.append(bfs[bs].amp(xval, yval, zval))
228 data[i, j, :] = tmp
229 data *= mocoeff[bs]
230 wavefn += data
231 density.data += wavefn ** 2
232
233 # TODO ROHF
234 if len(mocoeffslist) == 1:
235 density.data *= 2.0
236
237 return density
238
239
240 del find_package