utils.py 11.6 KB
Newer Older
1
import torch
2
import torch.utils.data
3
import math
4
import numpy as np
5
from collections import defaultdict
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
def pad(species):
    """Put different species together into single tensor.

    If the species are from molecules of different number of total atoms, then
    ghost atoms with atom type -1 will be added to make it fit into the same
    shape.

    Arguments:
        species (:class:`collections.abc.Sequence`): sequence of species.
            Species must be of shape ``(N, A)``, where ``N`` is the number of
            3D structures, ``A`` is the number of atoms.

    Returns:
        :class:`torch.Tensor`: species batched together.
    """
    max_atoms = max([s.shape[1] for s in species])
    padded_species = []
    for s in species:
        natoms = s.shape[1]
        if natoms < max_atoms:
            padding = torch.full((s.shape[0], max_atoms - natoms), -1,
                                 dtype=torch.long, device=s.device)
            s = torch.cat([s, padding], dim=1)
        padded_species.append(s)
    return torch.cat(padded_species)


35
36
def pad_atomic_properties(atomic_properties, padding_values=defaultdict(lambda: 0.0, species=-1)):
    """Put a sequence of atomic properties together into single tensor.
Gao, Xiang's avatar
Gao, Xiang committed
37

38
39
    Inputs are `[{'species': ..., ...}, {'species': ..., ...}, ...]` and the outputs
    are `{'species': padded_tensor, ...}`
Gao, Xiang's avatar
Gao, Xiang committed
40
41
42

    Arguments:
        species_coordinates (:class:`collections.abc.Sequence`): sequence of
43
44
             atomic properties.
        padding_values (dict): the value to fill to pad tensors to same size
Gao, Xiang's avatar
Gao, Xiang committed
45
    """
46
47
48
49
50
    keys = list(atomic_properties[0])
    anykey = keys[0]
    max_atoms = max(x[anykey].shape[1] for x in atomic_properties)
    padded = {k: [] for k in keys}
    for p in atomic_properties:
51
52
53
54
55
        num_molecules = 1
        for v in p.values():
            assert num_molecules in {1, v.shape[0]}, 'Number of molecules in different atomic properties mismatch'
            if v.shape[0] != 1:
                num_molecules = v.shape[0]
56
57
58
59
60
61
        for k, v in p.items():
            shape = list(v.shape)
            padatoms = max_atoms - shape[1]
            shape[1] = padatoms
            padding = v.new_full(shape, padding_values[k])
            v = torch.cat([v, padding], dim=1)
62
63
64
            shape = list(v.shape)
            shape[0] = num_molecules
            v = v.expand(*shape)
65
66
            padded[k].append(v)
    return {k: torch.cat(v) for k, v in padded.items()}
67
68


69
# @torch.jit.script
70
def present_species(species):
Gao, Xiang's avatar
Gao, Xiang committed
71
72
73
74
75
76
77
78
    """Given a vector of species of atoms, compute the unique species present.

    Arguments:
        species (:class:`torch.Tensor`): 1D vector of shape ``(atoms,)``

    Returns:
        :class:`torch.Tensor`: 1D vector storing present atom types sorted.
    """
79
80
    # present_species, _ = species.flatten()._unique(sorted=True)
    present_species = species.flatten().unique(sorted=True)
81
    if present_species[0].item() == -1:
82
83
        present_species = present_species[1:]
    return present_species
84
85


86
def strip_redundant_padding(atomic_properties):
Gao, Xiang's avatar
Gao, Xiang committed
87
88
89
    """Strip trailing padding atoms.

    Arguments:
90
        atomic_properties (dict): properties to strip
Gao, Xiang's avatar
Gao, Xiang committed
91
92

    Returns:
93
        dict: same set of properties with redundant padding atoms stripped.
Gao, Xiang's avatar
Gao, Xiang committed
94
    """
95
    species = atomic_properties['species']
96
    non_padding = (species >= 0).any(dim=0).nonzero().squeeze()
97
98
99
    for k in atomic_properties:
        atomic_properties[k] = atomic_properties[k].index_select(1, non_padding)
    return atomic_properties
Gao, Xiang's avatar
Gao, Xiang committed
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
def map2central(cell, coordinates, pbc):
    """Map atoms outside the unit cell into the cell using PBC.

    Arguments:
        cell (:class:`torch.Tensor`): tensor of shape (3, 3) of the three
            vectors defining unit cell:

            .. code-block:: python

                tensor([[x1, y1, z1],
                        [x2, y2, z2],
                        [x3, y3, z3]])

        coordinates (:class:`torch.Tensor`): Tensor of shape
            ``(molecules, atoms, 3)``.

        pbc (:class:`torch.Tensor`): boolean vector of size 3 storing
            if pbc is enabled for that direction.

    Returns:
        :class:`torch.Tensor`: coordinates of atoms mapped back to unit cell.
    """
    # Step 1: convert coordinates from standard cartesian coordinate to unit
    # cell coordinates
    inv_cell = torch.inverse(cell)
    coordinates_cell = torch.matmul(coordinates, inv_cell)
    # Step 2: wrap cell coordinates into [0, 1)
    coordinates_cell -= coordinates_cell.floor() * pbc.to(coordinates_cell.dtype)
    # Step 3: convert from cell coordinates back to standard cartesian
    # coordinate
    return torch.matmul(coordinates_cell, cell)


Gao, Xiang's avatar
Gao, Xiang committed
135
class EnergyShifter(torch.nn.Module):
Gao, Xiang's avatar
Gao, Xiang committed
136
137
138
139
140
141
142
143
144
    """Helper class for adding and subtracting self atomic energies

    This is a subclass of :class:`torch.nn.Module`, so it can be used directly
    in a pipeline as ``[input->AEVComputer->ANIModel->EnergyShifter->output]``.

    Arguments:
        self_energies (:class:`collections.abc.Sequence`): Sequence of floating
            numbers for the self energy of each atom type. The numbers should
            be in order, i.e. ``self_energies[i]`` should be atom type ``i``.
145
146
        fit_intercept (bool): Whether to calculate the intercept during the LSTSQ
            fit. The intercept will also be taken into account to shift energies.
Gao, Xiang's avatar
Gao, Xiang committed
147
    """
Gao, Xiang's avatar
Gao, Xiang committed
148

149
    def __init__(self, self_energies, fit_intercept=False):
Gao, Xiang's avatar
Gao, Xiang committed
150
        super(EnergyShifter, self).__init__()
151

152
        self.fit_intercept = fit_intercept
153
154
155
        if self_energies is not None:
            self_energies = torch.tensor(self_energies, dtype=torch.double)

156
        self.register_buffer('self_energies', self_energies)
Gao, Xiang's avatar
Gao, Xiang committed
157

158
    def sae_from_dataset(self, atomic_properties, properties):
159
160
161
162
163
164
165
166
167
168
        """Compute atomic self energies from dataset.

        Least-squares solution to a linear equation is calculated to output
        ``self_energies`` when ``self_energies = None`` is passed to
        :class:`torchani.EnergyShifter`
        """
        species = atomic_properties['species']
        energies = properties['energies']
        present_species_ = present_species(species)
        X = (species.unsqueeze(-1) == present_species_).sum(dim=1).to(torch.double)
169
170
171
        # Concatenate a vector of ones to find fit intercept
        if self.fit_intercept:
            X = torch.cat((X, torch.ones(X.shape[0], 1).to(torch.double)), dim=-1)
172
173
174
175
        y = energies.unsqueeze(dim=-1)
        coeff_, _, _, _ = np.linalg.lstsq(X, y, rcond=None)
        return coeff_.squeeze()

Gao, Xiang's avatar
Gao, Xiang committed
176
    def sae(self, species):
Gao, Xiang's avatar
Gao, Xiang committed
177
178
179
180
181
182
183
184
185
186
187
188
        """Compute self energies for molecules.

        Padding atoms will be automatically excluded.

        Arguments:
            species (:class:`torch.Tensor`): Long tensor in shape
                ``(conformations, atoms)``.

        Returns:
            :class:`torch.Tensor`: 1D vector in shape ``(conformations,)``
            for molecular self energies.
        """
189
190
191
192
        intercept = 0.0
        if self.fit_intercept:
            intercept = self.self_energies[-1]

193
        self_energies = self.self_energies[species]
Gao, Xiang's avatar
Gao, Xiang committed
194
        self_energies[species == -1] = 0
195
        return self_energies.sum(dim=1) + intercept
Gao, Xiang's avatar
Gao, Xiang committed
196

197
    def subtract_from_dataset(self, atomic_properties, properties):
Gao, Xiang's avatar
Gao, Xiang committed
198
199
200
        """Transformer for :class:`torchani.data.BatchedANIDataset` that
        subtract self energies.
        """
201
202
203
204
        if self.self_energies is None:
            self_energies = self.sae_from_dataset(atomic_properties, properties)
            self.self_energies = torch.tensor(self_energies, dtype=torch.double)

205
        species = atomic_properties['species']
206
207
208
209
        energies = properties['energies']
        device = energies.device
        energies = energies.to(torch.double) - self.sae(species).to(device)
        properties['energies'] = energies
210
        return atomic_properties, properties
Gao, Xiang's avatar
Gao, Xiang committed
211
212

    def forward(self, species_energies):
Gao, Xiang's avatar
Gao, Xiang committed
213
214
        """(species, molecular energies)->(species, molecular energies + sae)
        """
Gao, Xiang's avatar
Gao, Xiang committed
215
216
217
        species, energies = species_energies
        sae = self.sae(species).to(energies.dtype).to(energies.device)
        return species, energies + sae
218
219


Gao, Xiang's avatar
Gao, Xiang committed
220
221
222
223
224
225
226
227
228
class ChemicalSymbolsToInts:
    """Helper that can be called to convert chemical symbol string to integers

    Arguments:
        all_species (:class:`collections.abc.Sequence` of :class:`str`):
            sequence of all supported species, in order.
    """

    def __init__(self, all_species):
229
        self.rev_species = {s: i for i, s in enumerate(all_species)}
Gao, Xiang's avatar
Gao, Xiang committed
230
231
232
233
234
235

    def __call__(self, species):
        """Convert species from squence of strings to 1D tensor"""
        rev = [self.rev_species[s] for s in species]
        return torch.tensor(rev, dtype=torch.long)

236
237
238
    def __len__(self):
        return len(self.rev_species)

Gao, Xiang's avatar
Gao, Xiang committed
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
def hessian(coordinates, energies=None, forces=None):
    """Compute analytical hessian from the energy graph or force graph.

    Arguments:
        coordinates (:class:`torch.Tensor`): Tensor of shape `(molecules, atoms, 3)`
        energies (:class:`torch.Tensor`): Tensor of shape `(molecules,)`, if specified,
            then `forces` must be `None`. This energies must be computed from
            `coordinates` in a graph.
        forces (:class:`torch.Tensor`): Tensor of shape `(molecules, atoms, 3)`, if specified,
            then `energies` must be `None`. This forces must be computed from
            `coordinates` in a graph.

    Returns:
        :class:`torch.Tensor`: Tensor of shape `(molecules, 3A, 3A)` where A is the number of
        atoms in each molecule
    """
    if energies is None and forces is None:
        raise ValueError('Energies or forces must be specified')
    if energies is not None and forces is not None:
        raise ValueError('Energies or forces can not be specified at the same time')
    if forces is None:
        forces = -torch.autograd.grad(energies.sum(), coordinates, create_graph=True)[0]
    flattened_force = forces.flatten(start_dim=1)
    force_components = flattened_force.unbind(dim=1)
    return -torch.stack([
        torch.autograd.grad(f.sum(), coordinates, retain_graph=True)[0].flatten(start_dim=1)
        for f in force_components
    ], dim=1)


def vibrational_analysis(masses, hessian, unit='cm^-1'):
    """Computing the vibrational wavenumbers from hessian."""
    if unit != 'cm^-1':
        raise ValueError('Only cm^-1 are supported right now')
    assert hessian.shape[0] == 1, 'Currently only supporting computing one molecule a time'
    # Solving the eigenvalue problem: Hq = w^2 * T q
    # where H is the Hessian matrix, q is the normal coordinates,
    # T = diag(m1, m1, m1, m2, m2, m2, ....) is the mass
    # We solve this eigenvalue problem through Lowdin diagnolization:
    # Hq = w^2 * Tq ==> Hq = w^2 * T^(1/2) T^(1/2) q
    # Letting q' = T^(1/2) q, we then have
281
    # T^(-1/2) H T^(-1/2) q' = w^2 * q'
282
283
284
285
286
    inv_sqrt_mass = (1 / masses.sqrt()).repeat_interleave(3, dim=1)  # shape (molecule, 3 * atoms)
    mass_scaled_hessian = hessian * inv_sqrt_mass.unsqueeze(1) * inv_sqrt_mass.unsqueeze(2)
    if mass_scaled_hessian.shape[0] != 1:
        raise ValueError('The input should contain only one molecule')
    mass_scaled_hessian = mass_scaled_hessian.squeeze(0)
287
    eigenvalues, eigenvectors = torch.symeig(mass_scaled_hessian, eigenvectors=True)
288
289
290
291
    angular_frequencies = eigenvalues.sqrt()
    frequencies = angular_frequencies / (2 * math.pi)
    # converting from sqrt(hartree / (amu * angstrom^2)) to cm^-1
    wavenumbers = frequencies * 17092
292
293
    modes = (eigenvectors.t() * inv_sqrt_mass).reshape(frequencies.numel(), -1, 3)
    return wavenumbers, modes
294
295


296
__all__ = ['pad', 'pad_atomic_properties', 'present_species', 'hessian',
297
298
           'vibrational_analysis', 'strip_redundant_padding',
           'ChemicalSymbolsToInts']