Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
124 changes: 85 additions & 39 deletions mlipops/chargeequilibration.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from .coulombrf import CoulombRF
from .coulombewald import CoulombEwald
from .minres import minres
from .utils import pairwise_displacements
from .utils import pairwise_displacements, batch_pairwise_displacements


class ChargeEquilibration(torch.nn.Module):
Expand Down Expand Up @@ -47,36 +47,43 @@ def __init__(self, coulomb: CoulombNC | CoulombRF | CoulombEwald):
self.coulomb = coulomb

def forward(self, positions: torch.Tensor, electronegativity: torch.Tensor, hardness: torch.Tensor,
radius: torch.Tensor, total_charge: float | None = None, molecules: list | None = None,
radius: torch.Tensor, total_charge: float | torch.Tensor | None = None, molecules: list | None = None,
box_vectors: torch.Tensor | None = None, potential: torch.Tensor | None = None,
solver: str = 'direct') -> torch.Tensor:
batch: torch.Tensor | None = None, solver: str = 'direct') -> torch.Tensor:
"""Perform charge equilibration to compute atomic partial charges.

Parameters
----------
positions: torch.Tensor
a Tensor of shape (n_particles, 3) containing the Cartesian coordinates of each particle
electronegativity: torch.Tensor
a Tensor of shape (n_particles,) containing the electronegativity ($\chi$) of each particle
a Tensor of shape (n_particles,) containing the electronegativity ($\\chi$) of each particle
hardness: torch.Tensor,
a Tensor of shape (n_particles,) containing the hardness ($J_{ii}$) of each particle
radius: torch.Tensor
a Tensor of shape (n_particles,) containing the radius ($\alpha$) of each particle
total_charge: float | None
the total charge of the system. You must specify either total_charge or molecules, but not both.
a Tensor of shape (n_particles,) containing the radius ($\\alpha$) of each particle
total_charge: float | torch.Tensor | None
the total charge of the system. If batch is None, this should be a float or scalar Tensor. If batch is not
None, this should be a Tensor of shape (n_systems,) containing the charge of each system. You must specify
either total_charge or molecules, but not both.
molecules: list | None
the list of molecules. Each element should be a tuple with two elements. The first element is a Tensor
containing the indices of the particles that belong to the molecule. The second element is a float with the
total charge of the molecule. You must specify either total_charge or molecules, but not both.
box_vectors: torch.Tensor | None
a Tensor of shape (3, 3) containing box vectors defining the periodic box. If None, periodic boundary
conditions are not used.
if batch is None, a Tensor of shape (3, 3) containing box vectors defining the periodic box. If batch is
not None, a Tensor of shape (n_systems, 3, 3) containing the box vectors for each system. If None, periodic
boundary conditions are not used.
potential: torch.Tensor
a Tensor of shape (n_particles,) containing the external electric potential at the location of each particle
solver: str
the method to use for solving the system of equations. Options are 'direct' (use torch.linalg.solve() to
directly compute the result) and 'minres' (an iterative solver that tends to be faster, especially for large
systems, at the cost of slightly lower accuracy).
batch: torch.Tensor | None
a Tensor of shape (n_particles,) containing the index of the system each particle belongs to. This must be
sorted in ascending order, and every system must contain at least one particle. If None, the calculation
is performed for a single system instead of a batch of systems.

Returns
-------
Expand All @@ -85,16 +92,17 @@ def forward(self, positions: torch.Tensor, electronegativity: torch.Tensor, hard
"""
# Build the interaction matrix.

num_systems = 1 if batch is None else batch[-1]+1
if isinstance(self.coulomb, CoulombNC):
if box_vectors is not None:
raise ValueError('Cannot use periodic boundary conditions with CoulombNC')
interaction = self._compute_interactions_nc(positions, hardness, radius)
interaction = self._compute_interactions_nc(positions, hardness, radius, batch)
elif isinstance(self.coulomb, CoulombRF):
interaction = self._compute_interactions_rf(positions, hardness, radius, box_vectors)
interaction = self._compute_interactions_rf(positions, hardness, radius, box_vectors, batch)
elif isinstance(self.coulomb, CoulombEwald):
if box_vectors is None:
raise ValueError('Must specify box_vectors for CoulombEwald')
interaction = self._compute_interactions_ewald(positions, hardness, radius, box_vectors)
interaction = self._compute_interactions_ewald(positions, hardness, radius, box_vectors, batch, num_systems)
else:
raise ValueError('coulomb must be a CoulombNC, CoulombRF, or CoulombEwald')

Expand All @@ -105,9 +113,15 @@ def forward(self, positions: torch.Tensor, electronegativity: torch.Tensor, hard
if total_charge is not None:
if molecules is not None:
raise ValueError('total_charge and molecules were both specified')
constraint = torch.ones((n, 1), dtype=torch.float32, device=device)
zeros = torch.zeros((1, 1), dtype=torch.float32, device=device)
mol_charges = torch.tensor([total_charge], dtype=torch.float32, device=device)
if batch is not None:
constraint = torch.zeros((n, num_systems), dtype=torch.float32, device=device)
constraint[torch.arange(n, device=device), batch] = 1
zeros = torch.zeros((num_systems, num_systems), dtype=torch.float32, device=device)
mol_charges = total_charge
else:
constraint = torch.ones((n, 1), dtype=torch.float32, device=device)
zeros = torch.zeros((1, 1), dtype=torch.float32, device=device)
mol_charges = torch.tensor([total_charge], dtype=torch.float32, device=device)
elif molecules is not None:
m = len(molecules)
constraint = torch.zeros((n, m), dtype=torch.float32, device=device)
Expand All @@ -120,40 +134,56 @@ def forward(self, positions: torch.Tensor, electronegativity: torch.Tensor, hard
else:
raise ValueError('Neither total_charge nor molecules was specified')

# Solve the system of equations.
# Build the tensors representing the system of equations.

matrix = torch.cat([torch.cat([interaction, constraint], dim=1),
torch.cat([constraint.T, zeros], dim=1)])
rhs = electronegativity
if potential is not None:
rhs = rhs+potential
x = torch.cat([-rhs, mol_charges])

# Solve the system of equations.

if solver == 'direct':
return torch.linalg.solve(matrix, x)[:n]
if solver == 'minres':
return minres(matrix, x, tol=1e-7)[:n]
raise ValueError(f'Illegal value for solver: {solver}')

def _compute_interactions_nc(self, positions: torch.Tensor, hardness: torch.Tensor, radius: torch.Tensor) -> torch.Tensor:
def _compute_interactions_nc(self, positions: torch.Tensor, hardness: torch.Tensor, radius: torch.Tensor,
batch: torch.Tensor | None) -> torch.Tensor:
"""Build the interaction matrix when using CoulombNC."""
distance = torch.linalg.vector_norm(positions.view((-1,1,3)) - positions, dim=2)
diagonal = torch.eye(positions.shape[0], dtype=torch.bool, device=positions.device)
distance = torch.where(diagonal, 1.0, distance) # Needed to avoid NaNs when computing gradients
n = positions.shape[0]
interactions = torch.zeros((n, n), dtype=torch.float32, device=positions.device)
pairs = self.coulomb.neighbor_list(positions, None, batch)
if batch is None:
delta = pairwise_displacements(positions, pairs, None)
else:
delta = batch_pairwise_displacements(positions, pairs, batch, None)
distance = torch.linalg.vector_norm(delta, dim=1)
radius2 = radius**2
gamma = torch.rsqrt(radius2.view((-1,1)) + radius2)
return torch.where(diagonal,
gamma = torch.rsqrt(radius2[pairs[:,0]] + radius2[pairs[:,1]])
values = torch.erf(gamma*distance)/distance
interactions[pairs[:,0], pairs[:,1]] = values
interactions[pairs[:,1], pairs[:,0]] = values
return torch.where(torch.eye(positions.shape[0], dtype=torch.bool, device=positions.device),
hardness + (math.sqrt(2/math.pi))/radius,
torch.erf(gamma*distance)/distance)
interactions)

def _compute_interactions_rf(self, positions: torch.Tensor, hardness: torch.Tensor, radius: torch.Tensor, box_vectors: torch.Tensor | None) -> torch.Tensor:
def _compute_interactions_rf(self, positions: torch.Tensor, hardness: torch.Tensor, radius: torch.Tensor,
box_vectors: torch.Tensor | None, batch: torch.Tensor | None) -> torch.Tensor:
"""Build the interaction matrix when using CoulombRF."""
n = positions.shape[0]
interactions = torch.zeros((n, n), dtype=torch.float32, device=positions.device)
pairs = self.coulomb.neighbor_list(positions, box_vectors)
delta = pairwise_displacements(positions, pairs, box_vectors)
pairs = self.coulomb.neighbor_list(positions, box_vectors, batch)
if batch is None:
delta = pairwise_displacements(positions, pairs, box_vectors)
else:
delta = batch_pairwise_displacements(positions, pairs, batch, box_vectors)
distance = torch.linalg.vector_norm(delta, dim=1)
radius2 = radius**2
gamma = torch.rsqrt(radius2[pairs[:,0]] + radius2[pairs[:,0]])
gamma = torch.rsqrt(radius2[pairs[:,0]] + radius2[pairs[:,1]])
k = self.coulomb.pairwise.computation.k
c = self.coulomb.pairwise.computation.c
values = torch.erf(gamma*distance) * (1/distance + k*distance**2 - c)
Expand All @@ -163,32 +193,48 @@ def _compute_interactions_rf(self, positions: torch.Tensor, hardness: torch.Tens
hardness + (math.sqrt(2/math.pi))/radius,
interactions)

def _compute_interactions_ewald(self, positions: torch.Tensor, hardness: torch.Tensor, radius: torch.Tensor, box_vectors: torch.Tensor | None) -> torch.Tensor:
def _compute_interactions_ewald(self, positions: torch.Tensor, hardness: torch.Tensor, radius: torch.Tensor,
box_vectors: torch.Tensor | None, batch: torch.Tensor | None, num_systems: int) -> torch.Tensor:
"""Build the interaction matrix when using CoulombEwald."""
n = positions.shape[0]
interactions = torch.zeros((n, n), dtype=torch.float32, device=positions.device)

# Compute direct space interactions.

pairs = self.coulomb.neighbor_list(positions, box_vectors)
delta = pairwise_displacements(positions, pairs, box_vectors)
pairs = self.coulomb.neighbor_list(positions, box_vectors, batch)
if batch is None:
delta = pairwise_displacements(positions, pairs, box_vectors)
else:
delta = batch_pairwise_displacements(positions, pairs, batch, box_vectors)
distance = torch.linalg.vector_norm(delta, dim=1)
radius2 = radius**2
gamma = torch.rsqrt(radius2[pairs[:,0]] + radius2[pairs[:,0]])
gamma = torch.rsqrt(radius2[pairs[:,0]] + radius2[pairs[:,1]])
values = (torch.erf(gamma*distance) - torch.erf(self.coulomb.alpha*distance))/distance
interactions[pairs[:,0], pairs[:,1]] = values
interactions[pairs[:,1], pairs[:,0]] = values

# Compute reciprocal space interactions.

recip_box_vectors = torch.linalg.inv(box_vectors)
k = self.coulomb.wave_indices@(2*torch.pi*recip_box_vectors.T)
phase = k@positions.T
cos = phase.cos()
sin = phase.sin()
k2 = (k*k).sum(dim=1)
ak = torch.exp(self.coulomb._exp_coeff*k2)/k2
interactions += torch.einsum('i,ij,ik->jk', ak, cos, cos) + torch.einsum('i,ij,ik->jk', ak, sin, sin)
if batch is None:
k = self.coulomb.wave_indices@(2*torch.pi*recip_box_vectors.T)
phase = k@positions.T
cos = phase.cos()
sin = phase.sin()
k2 = (k*k).sum(dim=1)
ak = torch.exp(self.coulomb._exp_coeff*k2)/k2
interactions += torch.einsum('i,ij,ik->jk', ak, cos, cos) + torch.einsum('i,ij,ik->jk', ak, sin, sin)
interactions *= 4*torch.pi*recip_box_vectors.diag().prod()
else:
k = self.coulomb.wave_indices.unsqueeze(0)@(2*torch.pi*recip_box_vectors.transpose(1, 2))
phase = torch.einsum('ijk,ik->ji', k[batch], positions)
cos = phase.cos()
sin = phase.sin()
k2 = (k*k).sum(dim=2)
ak = (torch.exp(self.coulomb._exp_coeff*k2)/k2)[batch]
interactions += torch.einsum('ji,ij,ik->jk', ak, cos, cos) + torch.einsum('ji,ij,ik->jk', ak, sin, sin)
box_scale = torch.diagonal(recip_box_vectors, dim1=1, dim2=2).prod(dim=1)[batch]
interactions = torch.where(batch == batch.unsqueeze(1), (4*torch.pi)*interactions*box_scale, 0.0)
return torch.where(torch.eye(positions.shape[0], dtype=torch.bool, device=positions.device),
hardness + (math.sqrt(2/math.pi))/radius,
(4*torch.pi*recip_box_vectors.diag().prod())*interactions)
interactions)
5 changes: 1 addition & 4 deletions mlipops/coulombewald.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,10 +143,7 @@ def forward(self, positions: torch.Tensor, charges: torch.Tensor, box_vectors: t
a torch.Tensor containing the energy of the interaction. If batch is None, this is a scalar containing the
total energy. Otherwise, it has shape (n_systems,) containing the energy of each system in the batch.
"""
if batch is None:
num_systems = 1
else:
num_systems = batch.max()+1
num_systems = 1 if batch is None else batch[-1]+1
energy = torch.zeros((num_systems,), dtype=torch.float32, device=positions.device)
if include_direct:
neighbors = self.neighbor_list(positions, box_vectors, batch)
Expand Down
42 changes: 42 additions & 0 deletions tests/TestChargeEquilibration.py
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,48 @@ def test_qeq_external_potential(device):
assert torch.all(charges[[0,2,3,4]] > charges[[1,5,6,7]])


@pytest.mark.parametrize('device', ['cpu', 'cuda'])
@pytest.mark.parametrize('method, periodic', [('nc', False), ('rf', False), ('rf', True), ('ewald', True)])
def test_qeq_batch(device, method, periodic):
"""Test computing QEq charges for a batch of systems."""
if not torch.cuda.is_available() and device == 'cuda':
pytest.skip('No GPU')
num_systems = 10
positions, electronegativity, hardness, radius = get_nh3_tensors(device)
positions = positions.repeat(num_systems, 1)
positions += 0.3*torch.rand(positions.shape, dtype=torch.float32, device=device)
electronegativity = electronegativity.repeat(num_systems)
hardness = hardness.repeat(num_systems)
radius = radius.repeat(num_systems)
batch = torch.arange(num_systems, device=device).expand((8,-1)).T.flatten()
total_charge = torch.randint(-2, 2, (num_systems,), device=device)
if method == 'nc':
coulomb = CoulombNC(None, 1.0, device=device)
elif method == 'rf':
neighbor_list = NeighborList(2.0, device=device)
coulomb = CoulombRF(neighbor_list, None, 1.0)
else:
neighbor_list = NeighborList(2.0, device=device)
coulomb = CoulombEwald(neighbor_list, None, 7, 5, 5, 2.0, 1.0)
eq = ChargeEquilibration(coulomb)
if periodic:
box_vectors = []
for i in range(num_systems):
scale = 0.9+0.2*torch.rand(1, dtype=torch.float32, device=device)
box_vectors.append(torch.tensor([[9.0, 0.0, 0.0],
[0.3, 5.0, 0.0],
[0.5, 0.2, 6.0]], dtype=torch.float32, device=device)*scale)
box_vectors = torch.stack(box_vectors)
else:
box_vectors = None
charges = eq(positions, electronegativity, hardness, radius, total_charge, box_vectors=box_vectors, batch=batch)
for i in range(num_systems):
mask = batch == i
box = box_vectors[i] if periodic else None
sys_charges = eq(positions[mask], electronegativity[mask], hardness[mask], radius[mask], total_charge[i], box_vectors=box)
assert torch.allclose(charges[mask], sys_charges, rtol=1e-3, atol=1e-4)


@pytest.mark.parametrize('device', ['cpu', 'cuda'])
@pytest.mark.parametrize('solver', ['direct', 'minres'])
def test_compile_and_pickle(device, solver):
Expand Down
Loading