PENNe-pytorch 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
PENNe_pytorch/PENNe.py ADDED
@@ -0,0 +1,741 @@
1
+ from __future__ import annotations
2
+ from functools import partial
3
+ from math import pi
4
+
5
+ import torch
6
+ from torch import arange, Tensor
7
+ from torch.autograd import grad
8
+ from torch.nn import Module, ModuleList, Linear, Embedding, Parameter, GELU
9
+ import torch.nn.functional as F
10
+
11
+ # einstein notation
12
+
13
+ # b - batch
14
+ # n, i, j - atoms (center, neighbor)
15
+ # d - scalar feature dimension
16
+ # x - spatial coordinates (3)
17
+ # c - vector channels (c1, c2 for virtual-site pairs)
18
+ # k - virtual sites
19
+ # m - particles per atom (core + virtual sites)
20
+ # a, p - flattened virtual sites / particles
21
+ # f - radial basis functions
22
+ # s - readout scalar terms
23
+
24
+ import einx
25
+ from einops import rearrange, repeat, reduce, einsum, pack, unpack
26
+
27
+ from torch_einops_utils import device_dtype, exclusive_cumprod, Sequential
28
+ from torch_einops_utils.shape import shape, size
29
+
30
+ from x_mlps_pytorch import MLP
31
+
32
+ # constants
33
+
34
+ NUM_CORES = 1
35
+
36
+ READOUT_SCALARS = (
37
+ 'short_range_energy',
38
+ 'mbd_energy',
39
+ 'core_charge',
40
+ 'c6',
41
+ 'polarizability'
42
+ )
43
+
44
+ # helpers
45
+
46
+ def exists(v):
47
+ return v is not None
48
+
49
+ def default(v, d):
50
+ return v if exists(v) else d
51
+
52
+ def cast_tuple(v, length = 1):
53
+ return v if isinstance(v, tuple) else ((v,) * length)
54
+
55
+ def resolve_cutoffs(
56
+ cutoffs: float | tuple[float, ...] | list[float] | None,
57
+ depth: int | None = None,
58
+ *,
59
+ default_cutoffs: tuple[float, ...] = (6.0, 6.0, 6.0, 4.0),
60
+ default_cutoff = 6.0
61
+ ):
62
+ if not exists(cutoffs):
63
+ return cast_tuple(default_cutoff, depth) if exists(depth) else default_cutoffs
64
+
65
+ if isinstance(cutoffs, (int, float)):
66
+ return cast_tuple(float(cutoffs), default(depth, len(default_cutoffs)))
67
+
68
+ cutoffs = tuple(float(c) for c in cutoffs)
69
+ assert not exists(depth) or len(cutoffs) == depth, f'expected {depth} cutoffs, got {len(cutoffs)}'
70
+ return cutoffs
71
+
72
+ def eval_poly(x, coeffs):
73
+ powers = exclusive_cumprod(repeat(x, '... -> ... p', p = len(coeffs)))
74
+ return einsum(powers, x.new_tensor(coeffs), '... p, p -> ...')
75
+
76
+ def poly_deriv_coeffs(coeffs, *, start_power = 1):
77
+ _, *higher_coeffs = coeffs
78
+ return tuple(power * coeff for power, coeff in enumerate(higher_coeffs, start = start_power))
79
+
80
+ def sigmoid_range(t, low, high):
81
+ return low + (high - low) * t.sigmoid()
82
+
83
+ def safe_norm(t):
84
+ sq = reduce(t.square(), '... x -> ...', 'sum')
85
+ is_zero = ~sq.bool()
86
+ safe_sq = torch.where(is_zero, torch.ones_like(sq), sq)
87
+ return torch.where(is_zero, torch.zeros_like(sq), safe_sq.sqrt())
88
+
89
+ def pairwise_disp_and_dist(pos_a, pos_b = None):
90
+ pos_b = default(pos_b, pos_a)
91
+ disp = einx.subtract('b i x, b j x -> b i j x', pos_a, pos_b)
92
+ return disp, safe_norm(disp)
93
+
94
+ def off_diagonal_mask(num_atoms, device):
95
+ return ~torch.eye(num_atoms, device = device, dtype = torch.bool)
96
+
97
+ def interatomic_mask(num_atoms, sites_per_atom_a, sites_per_atom_b = None, *, device):
98
+ sites_per_atom_b = default(sites_per_atom_b, sites_per_atom_a)
99
+ atom_idx = arange(num_atoms, device = device)
100
+ idx_a = repeat(atom_idx, 'n -> (n m1)', m1 = sites_per_atom_a)
101
+ idx_b = repeat(atom_idx, 'n -> (n m2)', m2 = sites_per_atom_b)
102
+ return einx.not_equal('p1, p2 -> p1 p2', idx_a, idx_b)
103
+
104
+ def flatten_particle_pos(core_pos, site_pos):
105
+ packed, _ = pack([core_pos, site_pos], 'b n * x')
106
+ return rearrange(packed, 'b n m x -> b (n m) x')
107
+
108
+ def flatten_particle_scalars(core_vals, site_vals, num_virtual_sites):
109
+ site_vals = repeat(site_vals, 'b n -> b n k', k = num_virtual_sites)
110
+ packed, _ = pack([core_vals, site_vals], 'b n *')
111
+ return rearrange(packed, 'b n m -> b (n m)')
112
+
113
+ def cap_vector_norm(vectors, max_norm):
114
+ norms = safe_norm(vectors)
115
+ is_zero = ~norms.bool()
116
+ ones = torch.ones_like(norms)
117
+ safe_norms = torch.where(is_zero, ones, norms)
118
+ scale = torch.where(is_zero, ones, norms.tanh() / safe_norms)
119
+ return max_norm * einx.multiply('..., ... x -> ... x', scale, vectors)
120
+
121
+ def cutoff_envelope(distances, *, cutoff, exponent):
122
+ return F.relu(torch.ones_like(distances) - distances / cutoff).pow(exponent)
123
+
124
+ # nonbonded physics terms
125
+
126
+ def electrostatic_energy(
127
+ kernel,
128
+ charges,
129
+ pair_mask,
130
+ *,
131
+ coulomb_const = 332.06,
132
+ pair_factor = 0.5
133
+ ):
134
+ charge_prod = einx.multiply('b i, b j -> b i j', charges, charges)
135
+ pair_terms = einx.multiply('i j, b i j -> b i j', pair_mask.to(kernel.dtype), charge_prod * kernel)
136
+ return pair_factor * coulomb_const * reduce(pair_terms, 'b i j -> b', 'sum')
137
+
138
+ def coulomb_kernel(
139
+ distances,
140
+ widths,
141
+ *,
142
+ clamp_dist = 0.1,
143
+ damping_coeffs: tuple[float, ...] = (1.0, 11 / 16, 3 / 16, 1 / 48),
144
+ rms_factor = 0.5
145
+ ):
146
+ clamped = distances.clamp(min = clamp_dist)
147
+ ones = torch.ones_like(clamped)
148
+
149
+ is_diffuse = widths.bool()
150
+ both_diffuse = einx.logical_and('b i, b j -> b i j', is_diffuse, is_diffuse)
151
+ any_diffuse = einx.logical_or('b i, b j -> b i j', is_diffuse, is_diffuse)
152
+
153
+ width_sq = widths.square()
154
+ width_sq_avg = einx.add('b i, b j -> b i j', width_sq, width_sq) * rms_factor
155
+ width_sum = einx.add('b i, b j -> b i j', widths, widths)
156
+
157
+ rms_width = torch.where(both_diffuse, width_sq_avg, ones).sqrt()
158
+ pair_width = torch.where(both_diffuse, rms_width, width_sum)
159
+
160
+ scaled = clamped / torch.where(any_diffuse, pair_width, ones)
161
+ damping = ones - eval_poly(scaled, damping_coeffs) * (-scaled).exp()
162
+
163
+ return clamped.reciprocal() * torch.where(any_diffuse, damping, ones)
164
+
165
+ def coulomb_energy(
166
+ distances,
167
+ charges,
168
+ widths,
169
+ pair_mask,
170
+ *,
171
+ coulomb_const = 332.06,
172
+ clamp_dist = 0.1
173
+ ):
174
+ kernel = coulomb_kernel(distances, widths, clamp_dist = clamp_dist)
175
+ return electrostatic_energy(kernel, charges, pair_mask, coulomb_const = coulomb_const)
176
+
177
+ def soft_coulomb_kernel(
178
+ distances,
179
+ *,
180
+ sigma_pol = 6.0,
181
+ poly_coeffs: tuple[float, ...] = (15 / 8, -5 / 4, 3 / 8)
182
+ ):
183
+ x = (distances / sigma_pol).square()
184
+ near = eval_poly(x, poly_coeffs) / sigma_pol
185
+
186
+ is_near = distances < sigma_pol
187
+ far = torch.where(is_near, torch.ones_like(distances), distances).reciprocal()
188
+ return torch.where(is_near, near, far)
189
+
190
+ def soft_coulomb_force_factor(
191
+ distances,
192
+ *,
193
+ sigma_pol = 6.0,
194
+ poly_coeffs: tuple[float, ...] = (15 / 8, -5 / 4, 3 / 8),
195
+ deriv_scale = -2.0,
196
+ far_power = 3
197
+ ):
198
+ x = (distances / sigma_pol).square()
199
+ dp_dx = eval_poly(x, poly_deriv_coeffs(poly_coeffs))
200
+ near = deriv_scale * dp_dx / (sigma_pol ** far_power)
201
+
202
+ is_near = distances < sigma_pol
203
+ far = torch.where(is_near, torch.ones_like(distances), distances).pow(far_power).reciprocal()
204
+ return torch.where(is_near, near, far)
205
+
206
+ def spring_energy(
207
+ drude_disp,
208
+ spring_const,
209
+ *,
210
+ spring_cap = 1.0,
211
+ eps = 1e-12
212
+ ):
213
+ disp_sq = reduce(drude_disp.square(), 'b n k x -> b n k', 'sum')
214
+ ones = torch.ones_like(disp_sq)
215
+ cap_sq = spring_cap * spring_cap
216
+ ratio = (ones - disp_sq / cap_sq).clamp(min = eps)
217
+
218
+ site_energy = einx.multiply('b n, b n k -> b n k', spring_const * cap_sq, ones - ratio.sqrt())
219
+ return reduce(site_energy, 'b n k -> b', 'sum')
220
+
221
+ def dispersion_energy(
222
+ nuclear_dist,
223
+ c6,
224
+ *,
225
+ softening_radius = 6.0,
226
+ softening_coeffs: tuple[float, ...] = (3 / 8, 6 / 8, -1 / 8),
227
+ harmonic_mean_factor = 2.0,
228
+ dispersion_power = 6,
229
+ pair_factor = 0.5
230
+ ):
231
+ num_atoms = size(nuclear_dist, 'b [i] j')
232
+ off_diag = off_diagonal_mask(num_atoms, nuclear_dist.device)
233
+
234
+ u_sq = (nuclear_dist / softening_radius).square()
235
+ soft_dist = softening_radius * eval_poly(u_sq, softening_coeffs)
236
+ eff_dist = torch.where(nuclear_dist < softening_radius, soft_dist, nuclear_dist)
237
+
238
+ c6_pair = harmonic_mean_factor * einx.multiply('b i, b j -> b i j', c6, c6) / einx.add('b i, b j -> b i j', c6, c6)
239
+
240
+ safe_dist = einx.where('i j, b i j, b i j', off_diag, eff_dist, torch.ones_like(eff_dist))
241
+ inv_r_pow = einx.where('i j, b i j, b i j', off_diag, safe_dist.pow(dispersion_power).reciprocal(), torch.zeros_like(eff_dist))
242
+
243
+ return -pair_factor * reduce(c6_pair * inv_r_pow, 'b i j -> b', 'sum')
244
+
245
+ @torch.no_grad()
246
+ def relax_drude_sites(
247
+ coords,
248
+ site_pos,
249
+ all_charges,
250
+ virtual_charges,
251
+ spring_const,
252
+ *,
253
+ coulomb_const = 332.06,
254
+ sigma_pol = 6.0,
255
+ spring_cap = 1.0,
256
+ max_iter = 50,
257
+ tol = 1e-7,
258
+ damping = 0.5
259
+ ):
260
+ num_atoms, num_virtual_sites = shape(site_pos, 'b [n k] x')
261
+ num_particles_per_atom = size(all_charges, 'b [p]') // num_atoms
262
+
263
+ drude_disp = torch.zeros_like(site_pos)
264
+ diff_atom_mask = interatomic_mask(num_atoms, num_virtual_sites, num_particles_per_atom, device = site_pos.device)
265
+
266
+ field_to_disp = coulomb_const * virtual_charges / spring_const
267
+ cap_sq = spring_cap * spring_cap
268
+
269
+ for _ in range(max_iter):
270
+ relaxed_sites = site_pos + drude_disp
271
+
272
+ all_pos = flatten_particle_pos(coords, relaxed_sites)
273
+ sites_flat = rearrange(relaxed_sites, 'b n k x -> b (n k) x')
274
+ disp_vec, dist = pairwise_disp_and_dist(sites_flat, all_pos)
275
+
276
+ force_factor = einx.multiply(
277
+ 'a p, b a p -> b a p',
278
+ diff_atom_mask.to(dist.dtype),
279
+ soft_coulomb_force_factor(dist, sigma_pol = sigma_pol)
280
+ )
281
+
282
+ raw_field = einsum(force_factor, all_charges, disp_vec, 'b a p, b p, b a p x -> b a x')
283
+ raw_field = rearrange(raw_field, 'b (n k) x -> b n k x', n = num_atoms, k = num_virtual_sites)
284
+
285
+ harmonic_disp = einx.multiply('b n, b n k x -> b n k x', field_to_disp, raw_field)
286
+ harmonic_disp_sq = reduce(harmonic_disp.square(), 'b n k x -> b n k', 'sum')
287
+ disp_scale = (torch.ones_like(harmonic_disp_sq) + harmonic_disp_sq / cap_sq).rsqrt()
288
+
289
+ target_disp = einx.multiply('b n k x, b n k -> b n k x', harmonic_disp, disp_scale)
290
+ next_disp = torch.lerp(drude_disp, target_disp, damping)
291
+
292
+ converged = safe_norm(next_disp - drude_disp).max() < tol
293
+ drude_disp = next_disp
294
+
295
+ if converged:
296
+ break
297
+
298
+ return drude_disp
299
+
300
+ def polarization_energy(
301
+ coords,
302
+ site_pos,
303
+ virtual_charges,
304
+ polarizability,
305
+ unrelaxed_dist,
306
+ all_charges,
307
+ diff_atom_mask,
308
+ *,
309
+ coulomb_const = 332.06,
310
+ sigma_pol = 6.0,
311
+ spring_cap = 1.0,
312
+ min_spring_const = 1e-8,
313
+ max_iter = 50,
314
+ tol = 1e-7,
315
+ damping = 0.5
316
+ ):
317
+ num_virtual_sites = size(site_pos, 'b n [k] x')
318
+
319
+ spring_const = (
320
+ num_virtual_sites * virtual_charges.square() * coulomb_const / polarizability
321
+ ).clamp(min = min_spring_const)
322
+
323
+ drude_disp = relax_drude_sites(
324
+ coords,
325
+ site_pos,
326
+ all_charges,
327
+ virtual_charges,
328
+ spring_const,
329
+ coulomb_const = coulomb_const,
330
+ sigma_pol = sigma_pol,
331
+ spring_cap = spring_cap,
332
+ max_iter = max_iter,
333
+ tol = tol,
334
+ damping = damping
335
+ )
336
+
337
+ relaxed_pos = flatten_particle_pos(coords, site_pos + drude_disp)
338
+ _, relaxed_dist = pairwise_disp_and_dist(relaxed_pos)
339
+
340
+ delta_soft_kernel = (
341
+ soft_coulomb_kernel(relaxed_dist, sigma_pol = sigma_pol)
342
+ - soft_coulomb_kernel(unrelaxed_dist, sigma_pol = sigma_pol)
343
+ )
344
+
345
+ e_soft_delta = electrostatic_energy(delta_soft_kernel, all_charges, diff_atom_mask, coulomb_const = coulomb_const)
346
+ e_spring = spring_energy(drude_disp, spring_const, spring_cap = spring_cap)
347
+
348
+ return e_soft_delta + e_spring
349
+
350
+ # classes
351
+
352
+ class FourierRadialBasis(Module):
353
+ def __init__(
354
+ self,
355
+ num_basis,
356
+ *,
357
+ cutoff,
358
+ envelope_exponent = 6,
359
+ first_freq = 1.0
360
+ ):
361
+ super().__init__()
362
+ self.cutoff = cutoff
363
+ self.envelope = partial(cutoff_envelope, cutoff = cutoff, exponent = envelope_exponent)
364
+
365
+ freqs = torch.linspace(first_freq, num_basis, num_basis)
366
+ self.register_buffer('freqs', freqs, persistent = False)
367
+
368
+ def forward(self, distances):
369
+ envelope = self.envelope(distances)
370
+ angles = einx.multiply('..., f -> ... f', distances * (pi / self.cutoff), self.freqs)
371
+ return einx.multiply('... f, ... -> ... f', angles.sin(), envelope)
372
+
373
+ class EGNNLayer(Module):
374
+ def __init__(
375
+ self,
376
+ *,
377
+ dim,
378
+ num_vector_channels,
379
+ num_radial_basis,
380
+ cutoff,
381
+ mlp_hidden_dims: tuple[int, ...] = (256, 128),
382
+ radial_envelope_exponent = 6,
383
+ edge_taper_exponent = 2,
384
+ message_scale = 1e-2,
385
+ vector_coeff_bound = 0.5
386
+ ):
387
+ super().__init__()
388
+ self.message_scale = message_scale
389
+ self.vector_coeff_bound = vector_coeff_bound
390
+
391
+ self.radial_basis = FourierRadialBasis(
392
+ num_radial_basis,
393
+ cutoff = cutoff,
394
+ envelope_exponent = radial_envelope_exponent
395
+ )
396
+
397
+ self.edge_taper = partial(cutoff_envelope, cutoff = cutoff, exponent = edge_taper_exponent)
398
+
399
+ dim_interaction, *mlp_rest_dims = mlp_hidden_dims
400
+ dim_node = dim + NUM_CORES + num_vector_channels
401
+
402
+ self.to_nuclear_pair = Linear(num_radial_basis, dim_interaction, bias = False)
403
+ self.to_nuclear_virtual = Linear(num_vector_channels * num_radial_basis, dim_interaction, bias = False)
404
+ self.to_virtual_virtual = Linear(num_vector_channels * num_vector_channels, dim_interaction, bias = False)
405
+ self.to_center_node = Linear(dim_node, dim_interaction, bias = False)
406
+ self.to_neighbor_node = Linear(dim_node, dim_interaction)
407
+
408
+ self.message_mlp = Sequential(
409
+ GELU(),
410
+ MLP(dim_interaction, *mlp_rest_dims, dim_node, activation = GELU())
411
+ )
412
+
413
+ def forward(
414
+ self,
415
+ scalar_feats,
416
+ vector_feats,
417
+ core_charges,
418
+ virtual_charges,
419
+ nuclear_disp,
420
+ nuclear_dist
421
+ ):
422
+ num_atoms = size(scalar_feats, 'b [n] d')
423
+ num_vector_channels = size(vector_feats, 'b n [c] x')
424
+
425
+ # pairwise virtual-site geometry (eq. S1)
426
+
427
+ nuclear_virtual_disp = einx.add('b i j x, b i c x -> b i j c x', nuclear_disp, vector_feats)
428
+ nuclear_virtual_dist = safe_norm(nuclear_virtual_disp)
429
+
430
+ virtual_virtual_disp = einx.subtract('b i j c1 x, b j c2 x -> b i j c1 c2 x', nuclear_virtual_disp, vector_feats)
431
+ virtual_virtual_dist = safe_norm(virtual_virtual_disp)
432
+ rel_virtual_virtual_dist = einx.subtract('b i j c1 c2, b i j -> b i j c1 c2', virtual_virtual_dist, nuclear_dist)
433
+
434
+ # fourier radial basis (eq. S2)
435
+
436
+ nuclear_basis = self.radial_basis(nuclear_dist)
437
+ nuclear_virtual_basis = rearrange(self.radial_basis(nuclear_virtual_dist), 'b i j c f -> b i j (c f)')
438
+ rel_virtual_virtual_dist = rearrange(rel_virtual_virtual_dist, 'b i j c1 c2 -> b i j (c1 c2)')
439
+
440
+ # interaction space and message mlp (eq. S4)
441
+
442
+ node_feats, node_packed_shape = pack([scalar_feats, core_charges, virtual_charges], 'b n *')
443
+
444
+ interaction = (
445
+ self.to_nuclear_pair(nuclear_basis)
446
+ + self.to_nuclear_virtual(nuclear_virtual_basis)
447
+ + self.to_virtual_virtual(rel_virtual_virtual_dist)
448
+ + einx.add('b i d, b j d -> b i j d', self.to_center_node(node_feats), self.to_neighbor_node(node_feats))
449
+ )
450
+
451
+ messages = self.message_mlp(interaction)
452
+
453
+ # edge taper and rescale (eq. S3)
454
+
455
+ off_diag = off_diagonal_mask(num_atoms, scalar_feats.device)
456
+ edge_taper = self.edge_taper(nuclear_dist)
457
+ edge_taper = einx.multiply('i j, b i j -> b i j', off_diag.to(edge_taper.dtype), edge_taper)
458
+
459
+ messages = self.message_scale * einx.multiply('b i j, b i j d -> b i j d', edge_taper, messages)
460
+ delta_scalar, charge_flow, vector_coeffs = unpack(messages, node_packed_shape, 'b i j *')
461
+ vector_coeffs = self.vector_coeff_bound * vector_coeffs.tanh()
462
+
463
+ # updates (eq. S5, S6, S7)
464
+
465
+ scalar_feats = scalar_feats + reduce(delta_scalar, 'b i j d -> b i d', 'sum')
466
+
467
+ antisym_charge_flow = charge_flow - rearrange(charge_flow, 'b i j -> b j i')
468
+ charge_transfer = reduce(antisym_charge_flow, 'b i j -> b i', 'sum') / num_vector_channels
469
+ virtual_charges = einx.subtract('b n c, b n -> b n c', virtual_charges, charge_transfer)
470
+
471
+ vector_feats = vector_feats + einsum(vector_coeffs, nuclear_virtual_disp, 'b i j c, b i j c x -> b i c x')
472
+
473
+ return scalar_feats, vector_feats, virtual_charges
474
+
475
+ class EGNNTrunk(Module):
476
+ def __init__(
477
+ self,
478
+ *,
479
+ dim = 64,
480
+ depth: int | None = None,
481
+ cutoffs: float | tuple[float, ...] | list[float] | None = None,
482
+ num_vector_channels = 8,
483
+ num_radial_basis = 16,
484
+ mlp_hidden_dims: tuple[int, ...] = (256, 128),
485
+ radial_envelope_exponent = 6,
486
+ edge_taper_exponent = 2,
487
+ message_scale = 1e-2,
488
+ vector_coeff_bound = 0.5
489
+ ):
490
+ super().__init__()
491
+ cutoffs = resolve_cutoffs(cutoffs, depth = depth)
492
+
493
+ self.depth = len(cutoffs)
494
+ self.cutoffs = cutoffs
495
+
496
+ self.layers = ModuleList([
497
+ EGNNLayer(
498
+ dim = dim,
499
+ num_vector_channels = num_vector_channels,
500
+ num_radial_basis = num_radial_basis,
501
+ cutoff = cutoff,
502
+ mlp_hidden_dims = mlp_hidden_dims,
503
+ radial_envelope_exponent = radial_envelope_exponent,
504
+ edge_taper_exponent = edge_taper_exponent,
505
+ message_scale = message_scale,
506
+ vector_coeff_bound = vector_coeff_bound
507
+ )
508
+ for cutoff in cutoffs
509
+ ])
510
+
511
+ def forward(
512
+ self,
513
+ scalar_feats,
514
+ vector_feats,
515
+ core_charges,
516
+ virtual_charges,
517
+ coords
518
+ ):
519
+ nuclear_disp, nuclear_dist = pairwise_disp_and_dist(coords)
520
+
521
+ for layer in self.layers:
522
+ scalar_feats, vector_feats, virtual_charges = layer(
523
+ scalar_feats,
524
+ vector_feats,
525
+ core_charges,
526
+ virtual_charges,
527
+ nuclear_disp,
528
+ nuclear_dist
529
+ )
530
+
531
+ return scalar_feats, vector_feats, virtual_charges
532
+
533
+ class PENNe(Module):
534
+ def __init__(
535
+ self,
536
+ *,
537
+ num_species = 100,
538
+ dim = 64,
539
+ depth: int | None = None,
540
+ cutoffs: float | tuple[float, ...] | list[float] | None = None,
541
+ num_vector_channels = 8,
542
+ num_virtual_sites = 4,
543
+ num_radial_basis = 16,
544
+ mlp_hidden_dims: tuple[int, ...] = (256, 128),
545
+ radial_envelope_exponent = 6,
546
+ edge_taper_exponent = 2,
547
+ message_scale = 1e-2,
548
+ vector_coeff_bound = 0.5,
549
+ trunk: Module | None = None,
550
+ virtual_site_cap = 0.8,
551
+ init_polarizability = 1.0,
552
+ polarizability_delta_scale = 0.1,
553
+ polarizability_range: tuple[float, float] = (1e-3, 7.0),
554
+ c6_log_offset = 4.5,
555
+ c6_log_scale = 7.0,
556
+ core_charge_quad_scale = 2.0,
557
+ core_charge_offset = 1.0,
558
+ core_charge_alpha_offset = 0.2,
559
+ width_range: tuple[float, float] = (0.01, 0.2),
560
+ coulomb_const = 332.06,
561
+ coulomb_clamp = 0.1,
562
+ dispersion_softening = 6.0,
563
+ sigma_pol = 6.0,
564
+ spring_cap = 1.0,
565
+ min_spring_const = 1e-8,
566
+ scf_max_iter = 50,
567
+ scf_tol = 1e-7,
568
+ scf_damping = 0.5
569
+ ):
570
+ super().__init__()
571
+ self.num_vector_channels = num_vector_channels
572
+ self.num_virtual_sites = num_virtual_sites
573
+ self.num_particles_per_atom = NUM_CORES + num_virtual_sites
574
+ self.virtual_site_cap = virtual_site_cap
575
+ self.polarizability_delta_scale = polarizability_delta_scale
576
+ self.polarizability_range = polarizability_range
577
+ self.c6_log_offset = c6_log_offset
578
+ self.c6_log_scale = c6_log_scale
579
+ self.core_charge_quad_scale = core_charge_quad_scale
580
+ self.core_charge_offset = core_charge_offset
581
+ self.core_charge_alpha_offset = core_charge_alpha_offset
582
+ self.width_range = width_range
583
+
584
+ # per-species parameters before message passing (section S1.2)
585
+
586
+ self.species_embed = Embedding(num_species, dim)
587
+ self.species_core_charge = Parameter(torch.randn(num_species))
588
+ self.species_polarizability = Parameter(torch.full((num_species,), init_polarizability))
589
+ self.species_width_logit = Parameter(torch.zeros(num_species))
590
+
591
+ # equivariant message passing trunk
592
+
593
+ if not exists(trunk):
594
+ trunk = EGNNTrunk(
595
+ dim = dim,
596
+ depth = depth,
597
+ cutoffs = cutoffs,
598
+ num_vector_channels = num_vector_channels,
599
+ num_radial_basis = num_radial_basis,
600
+ mlp_hidden_dims = mlp_hidden_dims,
601
+ radial_envelope_exponent = radial_envelope_exponent,
602
+ edge_taper_exponent = edge_taper_exponent,
603
+ message_scale = message_scale,
604
+ vector_coeff_bound = vector_coeff_bound
605
+ )
606
+
607
+ self.trunk = trunk
608
+
609
+ # readout (section S1.5)
610
+
611
+ readout_dim_in = dim + NUM_CORES + num_vector_channels + num_vector_channels
612
+ self.readout_mlp = MLP(readout_dim_in, *mlp_hidden_dims, len(READOUT_SCALARS), activation = GELU())
613
+ self.to_virtual_sites = Linear(num_vector_channels, num_virtual_sites, bias = False)
614
+
615
+ # explicit nonbonded physics terms (section S1.6)
616
+
617
+ self.coulomb_energy = partial(
618
+ coulomb_energy,
619
+ coulomb_const = coulomb_const,
620
+ clamp_dist = coulomb_clamp
621
+ )
622
+
623
+ self.dispersion_energy = partial(
624
+ dispersion_energy,
625
+ softening_radius = dispersion_softening
626
+ )
627
+
628
+ self.polarization_energy = partial(
629
+ polarization_energy,
630
+ coulomb_const = coulomb_const,
631
+ sigma_pol = sigma_pol,
632
+ spring_cap = spring_cap,
633
+ min_spring_const = min_spring_const,
634
+ max_iter = scf_max_iter,
635
+ tol = scf_tol,
636
+ damping = scf_damping
637
+ )
638
+
639
+ @property
640
+ def cutoffs(self):
641
+ return getattr(self.trunk, 'cutoffs', None)
642
+
643
+ @property
644
+ def depth(self):
645
+ return getattr(self.trunk, 'depth', None)
646
+
647
+ def forward(
648
+ self,
649
+ species: Tensor,
650
+ coords: Tensor,
651
+ resonant_charges: Tensor | None = None,
652
+ return_forces = False
653
+ ):
654
+ if return_forces and not coords.requires_grad:
655
+ coords = coords.detach().requires_grad_(True)
656
+
657
+ batch, num_atoms = shape(species, '[b n]')
658
+ coord_dim = size(coords, 'b n [x]', b = batch, n = num_atoms)
659
+
660
+ # initial features
661
+
662
+ scalar_feats = self.species_embed(species)
663
+ init_core_charges = self.species_core_charge[species]
664
+ init_polarizability = self.species_polarizability[species]
665
+ virtual_widths = sigmoid_range(self.species_width_logit[species], *self.width_range)
666
+
667
+ init_total_charges = default(resonant_charges, torch.zeros_like(init_core_charges))
668
+ virtual_charges = repeat(
669
+ (init_total_charges - init_core_charges) / self.num_vector_channels,
670
+ 'b n -> b n c',
671
+ c = self.num_vector_channels
672
+ )
673
+
674
+ vector_feats = torch.zeros(
675
+ (batch, num_atoms, self.num_vector_channels, coord_dim),
676
+ **device_dtype(coords)
677
+ )
678
+
679
+ # message passing
680
+
681
+ scalar_feats, vector_feats, virtual_charges = self.trunk(
682
+ scalar_feats,
683
+ vector_feats,
684
+ init_core_charges,
685
+ virtual_charges,
686
+ coords
687
+ )
688
+
689
+ # readout (section S1.5)
690
+
691
+ vector_norms = safe_norm(vector_feats)
692
+ readout_in, _ = pack([scalar_feats, vector_norms, init_core_charges, virtual_charges], 'b n *')
693
+
694
+ short_range_energy, mbd_energy, raw_core_charge, raw_c6, raw_polarizability = rearrange(
695
+ self.readout_mlp(readout_in),
696
+ 'b n s -> s b n'
697
+ )
698
+
699
+ virtual_site_disp = einsum(vector_feats, self.to_virtual_sites.weight, 'b n c x, k c -> b n k x')
700
+ virtual_site_disp = cap_vector_norm(virtual_site_disp, self.virtual_site_cap)
701
+
702
+ c6 = (self.c6_log_offset + self.c6_log_scale * raw_c6.tanh()).exp()
703
+ polarizability = (init_polarizability + self.polarizability_delta_scale * raw_polarizability).clamp(*self.polarizability_range)
704
+
705
+ core_charges = (
706
+ self.core_charge_quad_scale * raw_core_charge.square()
707
+ + self.core_charge_offset
708
+ + self.core_charge_alpha_offset * polarizability
709
+ )
710
+
711
+ total_virtual_charge = reduce(virtual_charges, 'b n c -> b n', 'sum')
712
+ virtual_site_charges = (total_virtual_charge - (core_charges - init_core_charges)) / self.num_virtual_sites
713
+
714
+ # explicit nonbonded physics energies (section S1.6)
715
+
716
+ site_pos = einx.add('b n x, b n k x -> b n k x', coords, virtual_site_disp)
717
+
718
+ all_pos = flatten_particle_pos(coords, site_pos)
719
+ all_charges = flatten_particle_scalars(core_charges, virtual_site_charges, self.num_virtual_sites)
720
+ all_widths = flatten_particle_scalars(torch.zeros_like(core_charges), virtual_widths, self.num_virtual_sites)
721
+ diff_atom_mask = interatomic_mask(num_atoms, self.num_particles_per_atom, device = coords.device)
722
+
723
+ _, nuclear_dist = pairwise_disp_and_dist(coords)
724
+ _, all_dist = pairwise_disp_and_dist(all_pos)
725
+
726
+ e_coul = self.coulomb_energy(all_dist, all_charges, all_widths, diff_atom_mask)
727
+ e_disp = self.dispersion_energy(nuclear_dist, c6)
728
+ e_pol = self.polarization_energy(coords, site_pos, virtual_site_charges, polarizability, all_dist, all_charges, diff_atom_mask)
729
+
730
+ # total energy (eq. 1)
731
+
732
+ e_short = reduce(short_range_energy, 'b n -> b', 'sum')
733
+ e_mbd = reduce(mbd_energy, 'b n -> b', 'sum')
734
+
735
+ energy = e_short + e_coul + e_pol + e_disp + e_mbd
736
+
737
+ if not return_forces:
738
+ return energy
739
+
740
+ forces, = grad(energy.sum(), coords, create_graph = self.training)
741
+ return energy, -forces
@@ -0,0 +1,5 @@
1
+ from PENNe_pytorch.PENNe import (
2
+ PENNe,
3
+ EGNNTrunk,
4
+ EGNNLayer
5
+ )
@@ -0,0 +1,98 @@
1
+ Metadata-Version: 2.5
2
+ Name: PENNe-pytorch
3
+ Version: 0.0.1
4
+ Summary: PENNe - PyTorch
5
+ Project-URL: Homepage, https://pypi.org/project/PENNe-pytorch/
6
+ Project-URL: Repository, https://github.com/lucidrains/PENNe-pytorch
7
+ Author-email: Phil Wang <lucidrains@gmail.com>
8
+ License: MIT License
9
+
10
+ Copyright (c) 2026 Phil Wang
11
+
12
+ Permission is hereby granted, free of charge, to any person obtaining a copy
13
+ of this software and associated documentation files (the "Software"), to deal
14
+ in the Software without restriction, including without limitation the rights
15
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16
+ copies of the Software, and to permit persons to whom the Software is
17
+ furnished to do so, subject to the following conditions:
18
+
19
+ The above copyright notice and this permission notice shall be included in all
20
+ copies or substantial portions of the Software.
21
+
22
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28
+ SOFTWARE.
29
+ License-File: LICENSE
30
+ Keywords: artificial intelligence,deep learning,equivariance,molecular dynamics
31
+ Classifier: Development Status :: 4 - Beta
32
+ Classifier: Intended Audience :: Developers
33
+ Classifier: License :: OSI Approved :: MIT License
34
+ Classifier: Programming Language :: Python :: 3.10
35
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
36
+ Requires-Python: >=3.10
37
+ Requires-Dist: einops>=0.8.1
38
+ Requires-Dist: einx>=0.4.0
39
+ Requires-Dist: torch-einops-utils>=0.2.10
40
+ Requires-Dist: torch>=2.5
41
+ Requires-Dist: x-mlps-pytorch>=0.6.14
42
+ Provides-Extra: examples
43
+ Requires-Dist: accelerate; extra == 'examples'
44
+ Requires-Dist: fire; extra == 'examples'
45
+ Requires-Dist: numpy; extra == 'examples'
46
+ Provides-Extra: test
47
+ Requires-Dist: pytest; extra == 'test'
48
+ Description-Content-Type: text/markdown
49
+
50
+ <img src="./fig1.png" width="450px"></img>
51
+
52
+ ## PENNe-pytorch (wip)
53
+
54
+ Implementation of [PENNe](https://arxiv.org/abs/2612.04288v1), Enabling Quantum-Mechanical Accuracy at Biomolecular Scale
55
+
56
+ ## Install
57
+
58
+ ```bash
59
+ $ pip install PENNe-pytorch
60
+ ```
61
+
62
+ ## Usage
63
+
64
+ ```python
65
+ import torch
66
+ from PENNe_pytorch import PENNe
67
+
68
+ model = PENNe(
69
+ num_species = 100,
70
+ dim = 64,
71
+ cutoffs = (6.0, 6.0, 6.0, 4.0), # angstrom cutoffs per layer (or a single float with depth)
72
+ num_vector_channels = 8,
73
+ num_virtual_sites = 4,
74
+ num_radial_basis = 16,
75
+ mlp_hidden_dims = (256, 128),
76
+ sigma_pol = 6.0, # polarization switching distance in angstroms
77
+ dispersion_softening = 6.0 # dispersion softening radius in angstroms
78
+ )
79
+
80
+ species = torch.randint(0, 100, (2, 10))
81
+ coords = torch.randn(2, 10, 3)
82
+
83
+ energy, forces = model(species, coords, return_forces = True) # (2,), (2, 10, 3)
84
+ ```
85
+
86
+ ## Citations (wip)
87
+
88
+ ```bibtex
89
+ @misc{dick2026penneenablingquantummechanicalaccuracy,
90
+ title = {PENNe: Enabling Quantum-Mechanical Accuracy at Biomolecular Scale},
91
+ author = {Sebastian Dick and Peter Skopp and Alexander G. Donchev and Michael Bergdorf and Abhijit Raman and Simon Axelrod and Milena Mathew and Mihail Bogojeski and Mark A. Moraes and David E. Shaw},
92
+ year = {2026},
93
+ eprint = {2612.04288},
94
+ archivePrefix = {arXiv},
95
+ primaryClass = {physics.chem-ph},
96
+ url = {https://arxiv.org/abs/2612.04288},
97
+ }
98
+ ```
@@ -0,0 +1,6 @@
1
+ PENNe_pytorch/PENNe.py,sha256=XKnS6ui3_k38XFmu62zprjFhasKV_mWqL42cqsk6zp0,25980
2
+ PENNe_pytorch/__init__.py,sha256=CO-8lJUQDaGjCub1uSTQYhUwJzBx0nHKa1zbMsbUt8Q,76
3
+ penne_pytorch-0.0.1.dist-info/METADATA,sha256=V7aSixB6e74yp4tK9MUBI5JaUZrUfn3b6mpSfeQF0P4,3747
4
+ penne_pytorch-0.0.1.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
5
+ penne_pytorch-0.0.1.dist-info/licenses/LICENSE,sha256=e6AOF7Z8EFdK3IdcL0x0fLw4cY7Q0d0kNR0o0TmBewM,1066
6
+ penne_pytorch-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Phil Wang
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.