/
datastruct.py
286 lines (228 loc) · 8.89 KB
/
datastruct.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
"""
Density Functional Theory Data Structure Utilities
"""
from typing import Union, TypeVar, Generic, Optional, Callable, List, Dict
from dataclasses import dataclass
import torch
import numpy as np
from deepchem.utils import gaussian_integral
__all__ = ["ZType"]
T = TypeVar('T')
P = TypeVar('P')
# type of the atom Z
ZType = Union[int, float, torch.Tensor]
# input types
AtomZsType = Union[List[str], List[ZType], torch.Tensor]
AtomPosType = Union[List[List[float]], np.ndarray, torch.Tensor]
@dataclass
class SpinParam(Generic[T]):
"""Data structure to store different values for spin-up and spin-down electrons.
Examples
--------
>>> import torch
>>> from deepchem.utils.dft_utils import SpinParam
>>> dens_u = torch.ones(1)
>>> dens_d = torch.zeros(1)
>>> sp = SpinParam(u=dens_u, d=dens_d)
>>> sp.u
tensor([1.])
>>> sp.sum()
tensor([1.])
>>> sp.reduce(torch.multiply)
tensor([0.])
"""
def __init__(self, u: T, d: T):
"""Initialize the SpinParam object.
Parameters
----------
u: any type
The parameters that corresponds to the spin-up electrons.
d: any type
The parameters that corresponds to the spin-down electrons.
"""
self.u = u
self.d = d
def __repr__(self) -> str:
"""Return the string representation of the SpinParam object."""
return f"SpinParam(u={self.u}, d={self.d})"
def sum(self):
"""Returns the sum of up and down parameters."""
return self.u + self.d
def reduce(self, fcn: Callable) -> T:
"""Reduce up and down parameters with the given function."""
return fcn(self.u, self.d)
@dataclass
class ValGrad:
"""Data structure that contains local information about density profiles.
Data structure used as a umbrella class for density profiles and the
derivative of the potential w.r.t. density profiles.
Examples
--------
>>> import torch
>>> from deepchem.utils.dft_utils import ValGrad
>>> dens = torch.ones(1)
>>> grad = torch.zeros(1)
>>> lapl = torch.ones(1)
>>> kin = torch.ones(1)
>>> vg = ValGrad(value=dens, grad=grad, lapl=lapl, kin=kin)
>>> vg + vg
ValGrad(value=tensor([2.]), grad=tensor([0.]), lapl=tensor([2.]), kin=tensor([2.]))
>>> vg * 5
ValGrad(value=tensor([5.]), grad=tensor([0.]), lapl=tensor([5.]), kin=tensor([5.]))
"""
def __init__(self,
value: torch.Tensor,
grad: Optional[torch.Tensor] = None,
lapl: Optional[torch.Tensor] = None,
kin: Optional[torch.Tensor] = None):
"""Initialize the ValGrad object.
Parameters
----------
value: torch.Tensor
Tensors containing the value of the local information.
grad: torch.Tensor or None
If tensor, it represents the gradient of the local information with
shape ``(..., 3)`` where ``...`` should be the same shape as ``value``.
lapl: torch.Tensor or None
If tensor, represents the laplacian value of the local information.
It should have the same shape as ``value``.
kin: torch.Tensor or None
If tensor, represents the local kinetic energy density.
It should have the same shape as ``value``.
"""
self.value = value
self.grad = grad
self.lapl = lapl
self.kin = kin
def __add__(self, b):
"""Add two ValGrad objects together."""
return ValGrad(
value=self.value + b.value,
grad=self.grad + b.grad if self.grad is not None else None,
lapl=self.lapl + b.lapl if self.lapl is not None else None,
kin=self.kin + b.kin if self.kin is not None else None,
)
def __mul__(self, f: Union[float, int, torch.Tensor]):
"""Multiply the ValGrad object with a scalar."""
if isinstance(f, torch.Tensor):
assert f.numel(
) == 1, "ValGrad multiplication with tensor can only be done with 1-element tensor"
return ValGrad(
value=self.value * f,
grad=self.grad * f if self.grad is not None else None,
lapl=self.lapl * f if self.lapl is not None else None,
kin=self.kin * f if self.kin is not None else None,
)
def __repr__(self):
return f"ValGrad(value={self.value}, grad={self.grad}, lapl={self.lapl}, kin={self.kin})"
@dataclass
class CGTOBasis:
"""Data structure that contains information about a contracted gaussian
type orbital (CGTO).
Examples
--------
>>> import torch
>>> from deepchem.utils.dft_utils import CGTOBasis
>>> alphas = torch.ones(1)
>>> coeffs = torch.ones(1)
>>> cgto = CGTOBasis(angmom=0, alphas=alphas, coeffs=coeffs)
>>> cgto.wfnormalize_()
CGTOBasis(angmom=0, alphas=tensor([1.]), coeffs=tensor([2.5265]), normalized=True)
"""
def __init__(self, angmom: int, alphas: torch.Tensor, coeffs: torch.Tensor):
"""Initialize the CGTOBasis object.
Parameters
----------
angmom: int
The angular momentum of the basis.
alphas: torch.Tensor
The gaussian exponents of the basis. Shape: (nbasis,)
coeffs: torch.Tensor
The coefficients of the basis. Shape: (nbasis,)
"""
self.angmom = angmom
self.alphas = alphas
self.coeffs = coeffs
self.normalized = False
def __repr__(self):
"""Return the string representation of the CGTOBasis object.
Returns
-------
angmom: int
The angular momentum of the basis.
alphas: torch.Tensor
The gaussian exponents of the basis. Shape: (nbasis,)
coeffs: torch.Tensor
The coefficients of the basis. Shape: (nbasis,)
"""
return f"CGTOBasis(angmom={self.angmom}, alphas={self.alphas}, coeffs={self.coeffs}, normalized={self.normalized})"
def wfnormalize_(self) -> "CGTOBasis":
"""Wavefunction normalization
The normalization is obtained from CINTgto_norm from
libcint/src/misc.c, or
https://github.com/sunqm/libcint/blob/b8594f1d27c3dad9034984a2a5befb9d607d4932/src/misc.c#L80
Please note that the square of normalized wavefunctions do not integrate
to 1, but e.g. for s: 4*pi, p: (4*pi/3)
"""
# if the basis has been normalized before, then do nothing
if self.normalized:
return self
coeffs = self.coeffs
# normalize to have individual gaussian integral to be 1 (if coeff is 1)
value = gaussian_integral(2 * self.angmom + 2, 2 * self.alphas)
assert isinstance(value, torch.Tensor)
coeffs = coeffs / torch.sqrt(value)
# normalize the coefficients in the basis (because some basis such as
# def2-svp-jkfit is not normalized to have 1 in overlap)
ee = self.alphas.unsqueeze(-1) + self.alphas.unsqueeze(
-2) # (ngauss, ngauss)
ee = gaussian_integral(2 * self.angmom + 2, ee) # type: ignore
s1 = 1 / torch.sqrt(torch.einsum("a,ab,b", coeffs, ee, coeffs))
coeffs = coeffs * s1
self.coeffs = coeffs
self.normalized = True
return self
@dataclass
class AtomCGTOBasis:
"""Data structure that contains information about a atom and its contracted
gaussian type orbital (CGTO).
Examples
--------
>>> import torch
>>> from deepchem.utils.dft_utils import AtomCGTOBasis, CGTOBasis
>>> alphas = torch.ones(1)
>>> coeffs = torch.ones(1)
>>> cgto = CGTOBasis(angmom=0, alphas=alphas, coeffs=coeffs)
>>> atomcgto = AtomCGTOBasis(atomz=1, bases=[cgto], pos=[[0.0, 0.0, 0.0]])
>>> atomcgto
AtomCGTOBasis(atomz=1, bases=[CGTOBasis(angmom=0, alphas=tensor([1.]), coeffs=tensor([1.]), normalized=False)], pos=tensor([[0., 0., 0.]]))
"""
def __init__(self, atomz: ZType, bases: List[CGTOBasis], pos: AtomPosType):
"""Initialize the AtomCGTOBasis object.
Parameters
----------
atomz: ZType
Atomic number of the atom.
bases: List[CGTOBasis]
List of CGTOBasis objects.
pos: AtomPosType
Position of the atom. Shape: (ndim,)
"""
self.atomz = atomz
self.bases = bases
self.pos = torch.tensor(pos)
def __repr__(self):
"""Return the string representation of the AtomCGTOBasis object.
Returns
-------
atomz: ZType
Atomic number of the atom.
bases: List[CGTOBasis]
List of CGTOBasis objects.
pos: AtomPosType
Position of the atom.
"""
return f"AtomCGTOBasis(atomz={self.atomz}, bases={self.bases}, pos={self.pos})"
# input basis type
BasisInpType = Union[str, List[CGTOBasis], List[str], List[List[CGTOBasis]],
Dict[Union[str, int], Union[List[CGTOBasis], str]]]