-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathdata_utils.py
More file actions
1296 lines (1069 loc) · 46.8 KB
/
Copy pathdata_utils.py
File metadata and controls
1296 lines (1069 loc) · 46.8 KB
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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import numpy as np
import pandas as pd
import networkx as nx
import torch
import copy
import itertools
from pymatgen.core.structure import Structure
from pymatgen.core.lattice import Lattice
from pymatgen.analysis.graphs import StructureGraph
from pymatgen.analysis import local_env
from networkx.algorithms.components import is_connected
from sklearn.metrics import accuracy_score, recall_score, precision_score
from torch_scatter import scatter
from torch_scatter import segment_coo, segment_csr
from p_tqdm import p_umap
from pymatgen.symmetry.analyzer import SpacegroupAnalyzer
from pathos.pools import ProcessPool as Pool
# from multiprocessing import Pool
from tqdm import tqdm
from functools import partial
import faulthandler
faulthandler.enable()
# Tensor of unit cells. Assumes 27 cells in -1, 0, 1 offsets in the x and y dimensions
# Note that differing from OCP, we have 27 offsets here because we are in 3D
OFFSET_LIST = [
[-1, -1, -1],
[-1, -1, 0],
[-1, -1, 1],
[-1, 0, -1],
[-1, 0, 0],
[-1, 0, 1],
[-1, 1, -1],
[-1, 1, 0],
[-1, 1, 1],
[0, -1, -1],
[0, -1, 0],
[0, -1, 1],
[0, 0, -1],
[0, 0, 0],
[0, 0, 1],
[0, 1, -1],
[0, 1, 0],
[0, 1, 1],
[1, -1, -1],
[1, -1, 0],
[1, -1, 1],
[1, 0, -1],
[1, 0, 0],
[1, 0, 1],
[1, 1, -1],
[1, 1, 0],
[1, 1, 1],
]
EPSILON = 1e-5
chemical_symbols = [
# 0
'X',
# 1
'H', 'He',
# 2
'Li', 'Be', 'B', 'C', 'N', 'O', 'F', 'Ne',
# 3
'Na', 'Mg', 'Al', 'Si', 'P', 'S', 'Cl', 'Ar',
# 4
'K', 'Ca', 'Sc', 'Ti', 'V', 'Cr', 'Mn', 'Fe', 'Co', 'Ni', 'Cu', 'Zn',
'Ga', 'Ge', 'As', 'Se', 'Br', 'Kr',
# 5
'Rb', 'Sr', 'Y', 'Zr', 'Nb', 'Mo', 'Tc', 'Ru', 'Rh', 'Pd', 'Ag', 'Cd',
'In', 'Sn', 'Sb', 'Te', 'I', 'Xe',
# 6
'Cs', 'Ba', 'La', 'Ce', 'Pr', 'Nd', 'Pm', 'Sm', 'Eu', 'Gd', 'Tb', 'Dy',
'Ho', 'Er', 'Tm', 'Yb', 'Lu',
'Hf', 'Ta', 'W', 'Re', 'Os', 'Ir', 'Pt', 'Au', 'Hg', 'Tl', 'Pb', 'Bi',
'Po', 'At', 'Rn',
# 7
'Fr', 'Ra', 'Ac', 'Th', 'Pa', 'U', 'Np', 'Pu', 'Am', 'Cm', 'Bk',
'Cf', 'Es', 'Fm', 'Md', 'No', 'Lr',
'Rf', 'Db', 'Sg', 'Bh', 'Hs', 'Mt', 'Ds', 'Rg', 'Cn', 'Nh', 'Fl', 'Mc',
'Lv', 'Ts', 'Og']
CrystalNN = local_env.CrystalNN(
distance_cutoffs=None, x_diff_weight=-1, porous_adjustment=False)
def build_crystal(crystal_str, niggli=True, primitive=False):
"""Build crystal from cif string."""
crystal = Structure.from_str(crystal_str, fmt='cif')
if primitive:
crystal = crystal.get_primitive_structure()
if niggli:
crystal = crystal.get_reduced_structure()
canonical_crystal = Structure(
lattice=Lattice.from_parameters(*crystal.lattice.parameters),
species=crystal.species,
coords=crystal.frac_coords,
coords_are_cartesian=False,
)
# match is gaurantteed because cif only uses lattice params & frac_coords
# assert canonical_crystal.matches(crystal)
return canonical_crystal
def refine_spacegroup(crystal, tol=0.01):
spga = SpacegroupAnalyzer(crystal, symprec=tol)
crystal = spga.get_conventional_standard_structure()
space_group = spga.get_space_group_number()
crystal = Structure(
lattice=Lattice.from_parameters(*crystal.lattice.parameters),
species=crystal.species,
coords=crystal.frac_coords,
coords_are_cartesian=False,
)
return crystal, space_group
def build_crystal_graph(crystal, graph_method='crystalnn'):
"""
"""
if graph_method == 'crystalnn':
try:
crystal_graph = StructureGraph.with_local_env_strategy(crystal, CrystalNN)
except:
crystalNN_tmp = local_env.CrystalNN(distance_cutoffs=None, x_diff_weight=-1, porous_adjustment=False, search_cutoff=10)
crystal_graph = StructureGraph.with_local_env_strategy(crystal, crystalNN_tmp)
elif graph_method == 'none':
pass
else:
raise NotImplementedError
frac_coords = crystal.frac_coords
atom_types = crystal.atomic_numbers
lattice_parameters = crystal.lattice.parameters
lengths = lattice_parameters[:3]
angles = lattice_parameters[3:]
assert np.allclose(crystal.lattice.matrix,
lattice_params_to_matrix(*lengths, *angles))
edge_indices, to_jimages = [], []
if graph_method != 'none':
for i, j, to_jimage in crystal_graph.graph.edges(data='to_jimage'):
edge_indices.append([j, i])
to_jimages.append(to_jimage)
edge_indices.append([i, j])
to_jimages.append(tuple(-tj for tj in to_jimage))
atom_types = np.array(atom_types)
lengths, angles = np.array(lengths), np.array(angles)
edge_indices = np.array(edge_indices)
to_jimages = np.array(to_jimages)
num_atoms = atom_types.shape[0]
return frac_coords, atom_types, lengths, angles, edge_indices, to_jimages, num_atoms
def abs_cap(val, max_abs_val=1):
"""
Returns the value with its absolute value capped at max_abs_val.
Particularly useful in passing values to trignometric functions where
numerical errors may result in an argument > 1 being passed in.
https://github.com/materialsproject/pymatgen/blob/b789d74639aa851d7e5ee427a765d9fd5a8d1079/pymatgen/util/num.py#L15
Args:
val (float): Input value.
max_abs_val (float): The maximum absolute value for val. Defaults to 1.
Returns:
val if abs(val) < 1 else sign of val * max_abs_val.
"""
return max(min(val, max_abs_val), -max_abs_val)
def lattice_params_to_matrix(a, b, c, alpha, beta, gamma):
"""Converts lattice from abc, angles to matrix.
https://github.com/materialsproject/pymatgen/blob/b789d74639aa851d7e5ee427a765d9fd5a8d1079/pymatgen/core/lattice.py#L311
"""
angles_r = np.radians([alpha, beta, gamma])
cos_alpha, cos_beta, cos_gamma = np.cos(angles_r)
sin_alpha, sin_beta, sin_gamma = np.sin(angles_r)
val = (cos_alpha * cos_beta - cos_gamma) / (sin_alpha * sin_beta)
# Sometimes rounding errors result in values slightly > 1.
val = abs_cap(val)
gamma_star = np.arccos(val)
vector_a = [a * sin_beta, 0.0, a * cos_beta]
vector_b = [
-b * sin_alpha * np.cos(gamma_star),
b * sin_alpha * np.sin(gamma_star),
b * cos_alpha,
]
vector_c = [0.0, 0.0, float(c)]
return np.array([vector_a, vector_b, vector_c])
def lattice_params_to_matrix_torch(lengths, angles):
"""Batched torch version to compute lattice matrix from params.
lengths: torch.Tensor of shape (N, 3), unit A
angles: torch.Tensor of shape (N, 3), unit degree
"""
angles_r = torch.deg2rad(angles)
coses = torch.cos(angles_r)
sins = torch.sin(angles_r)
val = (coses[:, 0] * coses[:, 1] - coses[:, 2]) / (sins[:, 0] * sins[:, 1])
# Sometimes rounding errors result in values slightly > 1.
val = torch.clamp(val, -1., 1.)
gamma_star = torch.arccos(val)
vector_a = torch.stack([
lengths[:, 0] * sins[:, 1],
torch.zeros(lengths.size(0), device=lengths.device),
lengths[:, 0] * coses[:, 1]], dim=1)
vector_b = torch.stack([
-lengths[:, 1] * sins[:, 0] * torch.cos(gamma_star),
lengths[:, 1] * sins[:, 0] * torch.sin(gamma_star),
lengths[:, 1] * coses[:, 0]], dim=1)
vector_c = torch.stack([
torch.zeros(lengths.size(0), device=lengths.device),
torch.zeros(lengths.size(0), device=lengths.device),
lengths[:, 2]], dim=1)
return torch.stack([vector_a, vector_b, vector_c], dim=1)
def compute_volume(batch_lattice):
"""Compute volume from batched lattice matrix
batch_lattice: (N, 3, 3)
"""
vector_a, vector_b, vector_c = torch.unbind(batch_lattice, dim=1)
return torch.abs(torch.einsum('bi,bi->b', vector_a,
torch.cross(vector_b, vector_c, dim=1)))
def lengths_angles_to_volume(lengths, angles):
lattice = lattice_params_to_matrix_torch(lengths, angles)
return compute_volume(lattice)
def lattice_matrix_to_params(matrix):
lengths = np.sqrt(np.sum(matrix ** 2, axis=1)).tolist()
angles = np.zeros(3)
for i in range(3):
j = (i + 1) % 3
k = (i + 2) % 3
angles[i] = abs_cap(np.dot(matrix[j], matrix[k]) /
(lengths[j] * lengths[k]))
angles = np.arccos(angles) * 180.0 / np.pi
a, b, c = lengths
alpha, beta, gamma = angles
return a, b, c, alpha, beta, gamma
def lattices_to_params_shape(lattices):
lengths = torch.sqrt(torch.sum(lattices ** 2, dim=-1))
angles = torch.zeros_like(lengths)
for i in range(3):
j = (i + 1) % 3
k = (i + 2) % 3
angles[...,i] = torch.clamp(torch.sum(lattices[...,j,:] * lattices[...,k,:], dim = -1) /
(lengths[...,j] * lengths[...,k]), -1., 1.)
angles = torch.arccos(angles) * 180.0 / np.pi
return lengths, angles
def frac_to_cart_coords(
frac_coords,
lengths,
angles,
num_atoms,
regularized = True,
lattices = None
):
if regularized:
frac_coords = frac_coords % 1.
if lattices is None:
lattices = lattice_params_to_matrix_torch(lengths, angles)
lattice_nodes = torch.repeat_interleave(lattices, num_atoms, dim=0)
pos = torch.einsum('bi,bij->bj', frac_coords, lattice_nodes) # cart coords
return pos
def cart_to_frac_coords(
cart_coords,
lengths,
angles,
num_atoms,
regularized = True
):
lattice = lattice_params_to_matrix_torch(lengths, angles)
# use pinv in case the predicted lattice is not rank 3
inv_lattice = torch.linalg.pinv(lattice)
inv_lattice_nodes = torch.repeat_interleave(inv_lattice, num_atoms, dim=0)
frac_coords = torch.einsum('bi,bij->bj', cart_coords, inv_lattice_nodes)
if regularized:
frac_coords = frac_coords % 1.
return frac_coords
def get_pbc_distances(
coords,
edge_index,
lengths,
angles,
to_jimages,
num_atoms,
num_bonds,
coord_is_cart=False,
return_offsets=False,
return_distance_vec=False,
lattices=None
):
if lattices is None:
lattices = lattice_params_to_matrix_torch(lengths, angles)
if coord_is_cart:
pos = coords
else:
lattice_nodes = torch.repeat_interleave(lattices, num_atoms, dim=0)
pos = torch.einsum('bi,bij->bj', coords, lattice_nodes) # cart coords
j_index, i_index = edge_index
distance_vectors = pos[j_index] - pos[i_index]
# correct for pbc
lattice_edges = torch.repeat_interleave(lattices, num_bonds, dim=0)
offsets = torch.einsum('bi,bij->bj', to_jimages.float(), lattice_edges)
distance_vectors += offsets
# compute distances
distances = distance_vectors.norm(dim=-1)
out = {
"edge_index": edge_index,
"distances": distances,
}
if return_distance_vec:
out["distance_vec"] = distance_vectors
if return_offsets:
out["offsets"] = offsets
return out
def radius_graph_pbc_wrapper(data, radius, max_num_neighbors_threshold, device):
cart_coords = frac_to_cart_coords(
data.frac_coords, data.lengths, data.angles, data.num_atoms)
return radius_graph_pbc(
cart_coords, data.lengths, data.angles, data.num_atoms, radius,
max_num_neighbors_threshold, device)
def repeat_blocks(
sizes,
repeats,
continuous_indexing=True,
start_idx=0,
block_inc=0,
repeat_inc=0,
):
"""Repeat blocks of indices.
Adapted from https://stackoverflow.com/questions/51154989/numpy-vectorized-function-to-repeat-blocks-of-consecutive-elements
continuous_indexing: Whether to keep increasing the index after each block
start_idx: Starting index
block_inc: Number to increment by after each block,
either global or per block. Shape: len(sizes) - 1
repeat_inc: Number to increment by after each repetition,
either global or per block
Examples
--------
sizes = [1,3,2] ; repeats = [3,2,3] ; continuous_indexing = False
Return: [0 0 0 0 1 2 0 1 2 0 1 0 1 0 1]
sizes = [1,3,2] ; repeats = [3,2,3] ; continuous_indexing = True
Return: [0 0 0 1 2 3 1 2 3 4 5 4 5 4 5]
sizes = [1,3,2] ; repeats = [3,2,3] ; continuous_indexing = True ;
repeat_inc = 4
Return: [0 4 8 1 2 3 5 6 7 4 5 8 9 12 13]
sizes = [1,3,2] ; repeats = [3,2,3] ; continuous_indexing = True ;
start_idx = 5
Return: [5 5 5 6 7 8 6 7 8 9 10 9 10 9 10]
sizes = [1,3,2] ; repeats = [3,2,3] ; continuous_indexing = True ;
block_inc = 1
Return: [0 0 0 2 3 4 2 3 4 6 7 6 7 6 7]
sizes = [0,3,2] ; repeats = [3,2,3] ; continuous_indexing = True
Return: [0 1 2 0 1 2 3 4 3 4 3 4]
sizes = [2,3,2] ; repeats = [2,0,2] ; continuous_indexing = True
Return: [0 1 0 1 5 6 5 6]
"""
assert sizes.dim() == 1
assert all(sizes >= 0)
# Remove 0 sizes
sizes_nonzero = sizes > 0
if not torch.all(sizes_nonzero):
assert block_inc == 0 # Implementing this is not worth the effort
sizes = torch.masked_select(sizes, sizes_nonzero)
if isinstance(repeats, torch.Tensor):
repeats = torch.masked_select(repeats, sizes_nonzero)
if isinstance(repeat_inc, torch.Tensor):
repeat_inc = torch.masked_select(repeat_inc, sizes_nonzero)
if isinstance(repeats, torch.Tensor):
assert all(repeats >= 0)
insert_dummy = repeats[0] == 0
if insert_dummy:
one = sizes.new_ones(1)
zero = sizes.new_zeros(1)
sizes = torch.cat((one, sizes))
repeats = torch.cat((one, repeats))
if isinstance(block_inc, torch.Tensor):
block_inc = torch.cat((zero, block_inc))
if isinstance(repeat_inc, torch.Tensor):
repeat_inc = torch.cat((zero, repeat_inc))
else:
assert repeats >= 0
insert_dummy = False
# Get repeats for each group using group lengths/sizes
r1 = torch.repeat_interleave(
torch.arange(len(sizes), device=sizes.device), repeats
)
# Get total size of output array, as needed to initialize output indexing array
N = (sizes * repeats).sum()
# Initialize indexing array with ones as we need to setup incremental indexing
# within each group when cumulatively summed at the final stage.
# Two steps here:
# 1. Within each group, we have multiple sequences, so setup the offsetting
# at each sequence lengths by the seq. lengths preceding those.
id_ar = torch.ones(N, dtype=torch.long, device=sizes.device)
id_ar[0] = 0
insert_index = sizes[r1[:-1]].cumsum(0)
insert_val = (1 - sizes)[r1[:-1]]
if isinstance(repeats, torch.Tensor) and torch.any(repeats == 0):
diffs = r1[1:] - r1[:-1]
indptr = torch.cat((sizes.new_zeros(1), diffs.cumsum(0)))
if continuous_indexing:
# If a group was skipped (repeats=0) we need to add its size
insert_val += segment_csr(sizes[: r1[-1]], indptr, reduce="sum")
# Add block increments
if isinstance(block_inc, torch.Tensor):
insert_val += segment_csr(
block_inc[: r1[-1]], indptr, reduce="sum"
)
else:
insert_val += block_inc * (indptr[1:] - indptr[:-1])
if insert_dummy:
insert_val[0] -= block_inc
else:
idx = r1[1:] != r1[:-1]
if continuous_indexing:
# 2. For each group, make sure the indexing starts from the next group's
# first element. So, simply assign 1s there.
insert_val[idx] = 1
# Add block increments
insert_val[idx] += block_inc
# Add repeat_inc within each group
if isinstance(repeat_inc, torch.Tensor):
insert_val += repeat_inc[r1[:-1]]
if isinstance(repeats, torch.Tensor):
repeat_inc_inner = repeat_inc[repeats > 0][:-1]
else:
repeat_inc_inner = repeat_inc[:-1]
else:
insert_val += repeat_inc
repeat_inc_inner = repeat_inc
# Subtract the increments between groups
if isinstance(repeats, torch.Tensor):
repeats_inner = repeats[repeats > 0][:-1]
else:
repeats_inner = repeats
insert_val[r1[1:] != r1[:-1]] -= repeat_inc_inner * repeats_inner
# Assign index-offsetting values
id_ar[insert_index] = insert_val
if insert_dummy:
id_ar = id_ar[1:]
if continuous_indexing:
id_ar[0] -= 1
# Set start index now, in case of insertion due to leading repeats=0
id_ar[0] += start_idx
# Finally index into input array for the group repeated o/p
res = id_ar.cumsum(0)
return res
def radius_graph_pbc(pos, lengths, angles, natoms, radius, max_num_neighbors_threshold, device, lattices=None):
# device = pos.device
batch_size = len(natoms)
if lattices is None:
cell = lattice_params_to_matrix_torch(lengths, angles)
else:
cell = lattices
# position of the atoms
atom_pos = pos
# Before computing the pairwise distances between atoms, first create a list of atom indices to compare for the entire batch
num_atoms_per_image = natoms
num_atoms_per_image_sqr = (num_atoms_per_image**2).long()
# index offset between images
index_offset = (
torch.cumsum(num_atoms_per_image, dim=0) - num_atoms_per_image
)
index_offset_expand = torch.repeat_interleave(
index_offset, num_atoms_per_image_sqr
)
num_atoms_per_image_expand = torch.repeat_interleave(
num_atoms_per_image, num_atoms_per_image_sqr
)
# Compute a tensor containing sequences of numbers that range from 0 to num_atoms_per_image_sqr for each image
# that is used to compute indices for the pairs of atoms. This is a very convoluted way to implement
# the following (but 10x faster since it removes the for loop)
# for batch_idx in range(batch_size):
# batch_count = torch.cat([batch_count, torch.arange(num_atoms_per_image_sqr[batch_idx], device=device)], dim=0)
num_atom_pairs = torch.sum(num_atoms_per_image_sqr)
index_sqr_offset = (
torch.cumsum(num_atoms_per_image_sqr, dim=0) - num_atoms_per_image_sqr
)
index_sqr_offset = torch.repeat_interleave(
index_sqr_offset, num_atoms_per_image_sqr
)
atom_count_sqr = (
torch.arange(num_atom_pairs, device=device) - index_sqr_offset
)
# Compute the indices for the pairs of atoms (using division and mod)
# If the systems get too large this apporach could run into numerical precision issues
index1 = (
torch.div(
atom_count_sqr, num_atoms_per_image_expand, rounding_mode="floor"
)
) + index_offset_expand
index2 = (
atom_count_sqr % num_atoms_per_image_expand
) + index_offset_expand
# Get the positions for each atom
pos1 = torch.index_select(atom_pos, 0, index1)
pos2 = torch.index_select(atom_pos, 0, index2)
# Calculate required number of unit cells in each direction.
# Smallest distance between planes separated by a1 is
# 1 / ||(a2 x a3) / V||_2, since a2 x a3 is the area of the plane.
# Note that the unit cell volume V = a1 * (a2 x a3) and that
# (a2 x a3) / V is also the reciprocal primitive vector
# (crystallographer's definition).
cross_a2a3 = torch.cross(cell[:, 1], cell[:, 2], dim=-1)
cell_vol = torch.sum(cell[:, 0] * cross_a2a3, dim=-1, keepdim=True)
inv_min_dist_a1 = torch.norm(cross_a2a3 / cell_vol, p=2, dim=-1)
min_dist_a1 = (1 / inv_min_dist_a1).reshape(-1,1)
cross_a3a1 = torch.cross(cell[:, 2], cell[:, 0], dim=-1)
inv_min_dist_a2 = torch.norm(cross_a3a1 / cell_vol, p=2, dim=-1)
min_dist_a2 = (1 / inv_min_dist_a2).reshape(-1,1)
cross_a1a2 = torch.cross(cell[:, 0], cell[:, 1], dim=-1)
inv_min_dist_a3 = torch.norm(cross_a1a2 / cell_vol, p=2, dim=-1)
min_dist_a3 = (1 / inv_min_dist_a3).reshape(-1,1)
# Take the max over all images for uniformity. This is essentially padding.
# Note that this can significantly increase the number of computed distances
# if the required repetitions are very different between images
# (which they usually are). Changing this to sparse (scatter) operations
# might be worth the effort if this function becomes a bottleneck.
max_rep = torch.ones(3, dtype=torch.long, device=device)
min_dist = torch.cat([min_dist_a1, min_dist_a2, min_dist_a3], dim=-1) # N_graphs * 3
# reps = torch.cat([rep_a1.reshape(-1,1), rep_a2.reshape(-1,1), rep_a3.reshape(-1,1)], dim=1) # N_graphs * 3
unit_cell_all = []
num_cells_all = []
# Tensor of unit cells
cells_per_dim = [
torch.arange(-rep, rep + 1, device=device, dtype=torch.float)
for rep in max_rep
]
unit_cell = torch.cat([_.reshape(-1,1) for _ in torch.meshgrid(cells_per_dim)], dim=-1)
num_cells = len(unit_cell)
unit_cell_per_atom = unit_cell.view(1, num_cells, 3).repeat(
len(index2), 1, 1
)
unit_cell = torch.transpose(unit_cell, 0, 1)
unit_cell_batch = unit_cell.view(1, 3, num_cells).expand(
batch_size, -1, -1
)
# Compute the x, y, z positional offsets for each cell in each image
data_cell = torch.transpose(cell, 1, 2)
pbc_offsets = torch.bmm(data_cell, unit_cell_batch)
pbc_offsets_per_atom = torch.repeat_interleave(
pbc_offsets, num_atoms_per_image_sqr, dim=0
)
# Expand the positions and indices for the 9 cells
pos1 = pos1.view(-1, 3, 1).expand(-1, -1, num_cells)
pos2 = pos2.view(-1, 3, 1).expand(-1, -1, num_cells)
index1 = index1.view(-1, 1).repeat(1, num_cells).view(-1)
index2 = index2.view(-1, 1).repeat(1, num_cells).view(-1)
# Add the PBC offsets for the second atom
pos2 = pos2 + pbc_offsets_per_atom
# # Compute the squared distance between atoms
atom_distance_sqr = torch.sum((pos1 - pos2) ** 2, dim=1)
atom_distance_sqr = atom_distance_sqr.view(-1)
# Remove pairs that are too far apart
radius_real = (min_dist.min(dim=-1)[0] + 0.01)#.clamp(max=radius)
radius_real = torch.repeat_interleave(radius_real, num_atoms_per_image_sqr * num_cells)
# print(min_dist.min(dim=-1)[0])
# radius_real = radius
mask_within_radius = torch.le(atom_distance_sqr, radius_real * radius_real)
# Remove pairs with the same atoms (distance = 0.0)
mask_not_same = torch.gt(atom_distance_sqr, 0.0001)
mask = torch.logical_and(mask_within_radius, mask_not_same)
index1 = torch.masked_select(index1, mask)
index2 = torch.masked_select(index2, mask)
unit_cell = torch.masked_select(
unit_cell_per_atom.view(-1, 3), mask.view(-1, 1).expand(-1, 3)
)
unit_cell = unit_cell.view(-1, 3)
atom_distance_sqr = torch.masked_select(atom_distance_sqr, mask)
if max_num_neighbors_threshold is not None:
mask_num_neighbors, num_neighbors_image = get_max_neighbors_mask(
natoms=natoms,
index=index1,
atom_distance=atom_distance_sqr,
max_num_neighbors_threshold=max_num_neighbors_threshold,
)
if not torch.all(mask_num_neighbors):
# Mask out the atoms to ensure each atom has at most max_num_neighbors_threshold neighbors
index1 = torch.masked_select(index1, mask_num_neighbors)
index2 = torch.masked_select(index2, mask_num_neighbors)
unit_cell = torch.masked_select(
unit_cell.view(-1, 3), mask_num_neighbors.view(-1, 1).expand(-1, 3)
)
unit_cell = unit_cell.view(-1, 3)
else:
ones = index1.new_ones(1).expand_as(index1)
num_neighbors = segment_coo(ones, index1, dim_size=natoms.sum())
# Get number of (thresholded) neighbors per image
image_indptr = torch.zeros(
natoms.shape[0] + 1, device=device, dtype=torch.long
)
image_indptr[1:] = torch.cumsum(natoms, dim=0)
num_neighbors_image = segment_csr(num_neighbors, image_indptr)
edge_index = torch.stack((index2, index1))
return edge_index, unit_cell, num_neighbors_image
def get_max_neighbors_mask(
natoms, index, atom_distance, max_num_neighbors_threshold
):
"""
Give a mask that filters out edges so that each atom has at most
`max_num_neighbors_threshold` neighbors.
Assumes that `index` is sorted.
"""
device = natoms.device
num_atoms = natoms.sum()
# Get number of neighbors
# segment_coo assumes sorted index
ones = index.new_ones(1).expand_as(index)
num_neighbors = segment_coo(ones, index, dim_size=num_atoms)
max_num_neighbors = num_neighbors.max()
num_neighbors_thresholded = num_neighbors.clamp(
max=max_num_neighbors_threshold
)
# Get number of (thresholded) neighbors per image
image_indptr = torch.zeros(
natoms.shape[0] + 1, device=device, dtype=torch.long
)
image_indptr[1:] = torch.cumsum(natoms, dim=0)
num_neighbors_image = segment_csr(num_neighbors_thresholded, image_indptr)
# If max_num_neighbors is below the threshold, return early
if (
max_num_neighbors <= max_num_neighbors_threshold
or max_num_neighbors_threshold <= 0
):
mask_num_neighbors = torch.tensor(
[True], dtype=bool, device=device
).expand_as(index)
return mask_num_neighbors, num_neighbors_image
# Create a tensor of size [num_atoms, max_num_neighbors] to sort the distances of the neighbors.
# Fill with infinity so we can easily remove unused distances later.
distance_sort = torch.full(
[num_atoms * max_num_neighbors], np.inf, device=device
)
# Create an index map to map distances from atom_distance to distance_sort
# index_sort_map assumes index to be sorted
index_neighbor_offset = torch.cumsum(num_neighbors, dim=0) - num_neighbors
index_neighbor_offset_expand = torch.repeat_interleave(
index_neighbor_offset, num_neighbors
)
index_sort_map = (
index * max_num_neighbors
+ torch.arange(len(index), device=device)
- index_neighbor_offset_expand
)
distance_sort.index_copy_(0, index_sort_map, atom_distance)
distance_sort = distance_sort.view(num_atoms, max_num_neighbors)
# Sort neighboring atoms based on distance
distance_sort, index_sort = torch.sort(distance_sort, dim=1)
# Select the max_num_neighbors_threshold neighbors that are closest
distance_real_cutoff = distance_sort[:,max_num_neighbors_threshold].reshape(-1,1).expand(-1,max_num_neighbors) + 0.01
mask_distance = distance_sort < distance_real_cutoff
index_sort = index_sort + index_neighbor_offset.view(-1, 1).expand(
-1, max_num_neighbors
)
# Remove "unused pairs" with infinite distances
mask_finite = torch.isfinite(distance_sort)
# index_sort = torch.masked_select(index_sort, mask_finite)
index_sort = torch.masked_select(index_sort, mask_finite & mask_distance)
num_neighbor_per_node = (mask_finite & mask_distance).sum(dim=-1)
num_neighbors_image = segment_csr(num_neighbor_per_node, image_indptr)
# At this point index_sort contains the index into index of the
# closest max_num_neighbors_threshold neighbors per atom
# Create a mask to remove all pairs not in index_sort
mask_num_neighbors = torch.zeros(len(index), device=device, dtype=bool)
mask_num_neighbors.index_fill_(0, index_sort, True)
return mask_num_neighbors, num_neighbors_image
def radius_graph_pbc_(cart_coords, lengths, angles, num_atoms,
radius, max_num_neighbors_threshold, device,
topk_per_pair=None):
"""Computes pbc graph edges under pbc.
topk_per_pair: (num_atom_pairs,), select topk edges per atom pair
Note: topk should take into account self-self edge for (i, i)
"""
batch_size = len(num_atoms)
# position of the atoms
atom_pos = cart_coords
# Before computing the pairwise distances between atoms, first create a list of atom indices to compare for the entire batch
num_atoms_per_image = num_atoms
num_atoms_per_image_sqr = (num_atoms_per_image ** 2).long()
# index offset between images
index_offset = (
torch.cumsum(num_atoms_per_image, dim=0) - num_atoms_per_image
)
index_offset_expand = torch.repeat_interleave(
index_offset, num_atoms_per_image_sqr
)
num_atoms_per_image_expand = torch.repeat_interleave(
num_atoms_per_image, num_atoms_per_image_sqr
)
# Compute a tensor containing sequences of numbers that range from 0 to num_atoms_per_image_sqr for each image
# that is used to compute indices for the pairs of atoms. This is a very convoluted way to implement
# the following (but 10x faster since it removes the for loop)
# for batch_idx in range(batch_size):
# batch_count = torch.cat([batch_count, torch.arange(num_atoms_per_image_sqr[batch_idx], device=device)], dim=0)
num_atom_pairs = torch.sum(num_atoms_per_image_sqr)
index_sqr_offset = (
torch.cumsum(num_atoms_per_image_sqr, dim=0) - num_atoms_per_image_sqr
)
index_sqr_offset = torch.repeat_interleave(
index_sqr_offset, num_atoms_per_image_sqr
)
atom_count_sqr = (
torch.arange(num_atom_pairs, device=device) - index_sqr_offset
)
# Compute the indices for the pairs of atoms (using division and mod)
# If the systems get too large this apporach could run into numerical precision issues
index1 = (
(atom_count_sqr // num_atoms_per_image_expand)
).long() + index_offset_expand
index2 = (
atom_count_sqr % num_atoms_per_image_expand
).long() + index_offset_expand
# Get the positions for each atom
pos1 = torch.index_select(atom_pos, 0, index1)
pos2 = torch.index_select(atom_pos, 0, index2)
unit_cell = torch.tensor(OFFSET_LIST, device=device).float()
num_cells = len(unit_cell)
unit_cell_per_atom = unit_cell.view(1, num_cells, 3).repeat(
len(index2), 1, 1
)
unit_cell = torch.transpose(unit_cell, 0, 1)
unit_cell_batch = unit_cell.view(1, 3, num_cells).expand(
batch_size, -1, -1
)
# lattice matrix
lattice = lattice_params_to_matrix_torch(lengths, angles)
# Compute the x, y, z positional offsets for each cell in each image
data_cell = torch.transpose(lattice, 1, 2)
pbc_offsets = torch.bmm(data_cell, unit_cell_batch)
pbc_offsets_per_atom = torch.repeat_interleave(
pbc_offsets, num_atoms_per_image_sqr, dim=0
)
# Expand the positions and indices for the 9 cells
pos1 = pos1.view(-1, 3, 1).expand(-1, -1, num_cells)
pos2 = pos2.view(-1, 3, 1).expand(-1, -1, num_cells)
index1 = index1.view(-1, 1).repeat(1, num_cells).view(-1)
index2 = index2.view(-1, 1).repeat(1, num_cells).view(-1)
# Add the PBC offsets for the second atom
pos2 = pos2 + pbc_offsets_per_atom
# Compute the squared distance between atoms
atom_distance_sqr = torch.sum((pos1 - pos2) ** 2, dim=1)
if topk_per_pair is not None:
assert topk_per_pair.size(0) == num_atom_pairs
atom_distance_sqr_sort_index = torch.argsort(atom_distance_sqr, dim=1)
assert atom_distance_sqr_sort_index.size() == (num_atom_pairs, num_cells)
atom_distance_sqr_sort_index = (
atom_distance_sqr_sort_index +
torch.arange(num_atom_pairs, device=device)[:, None] * num_cells).view(-1)
topk_mask = (torch.arange(num_cells, device=device)[None, :] <
topk_per_pair[:, None])
topk_mask = topk_mask.view(-1)
topk_indices = atom_distance_sqr_sort_index.masked_select(topk_mask)
topk_mask = torch.zeros(num_atom_pairs * num_cells, device=device)
topk_mask.scatter_(0, topk_indices, 1.)
topk_mask = topk_mask.bool()
atom_distance_sqr = atom_distance_sqr.view(-1)
# Remove pairs that are too far apart
mask_within_radius = torch.le(atom_distance_sqr, radius * radius)
# Remove pairs with the same atoms (distance = 0.0)
mask_not_same = torch.gt(atom_distance_sqr, 0.0001)
mask = torch.logical_and(mask_within_radius, mask_not_same)
index1 = torch.masked_select(index1, mask)
index2 = torch.masked_select(index2, mask)
unit_cell = torch.masked_select(
unit_cell_per_atom.view(-1, 3), mask.view(-1, 1).expand(-1, 3)
)
unit_cell = unit_cell.view(-1, 3)
if topk_per_pair is not None:
topk_mask = torch.masked_select(topk_mask, mask)
num_neighbors = torch.zeros(len(cart_coords), device=device)
num_neighbors.index_add_(0, index1, torch.ones(len(index1), device=device))
num_neighbors = num_neighbors.long()
max_num_neighbors = torch.max(num_neighbors).long()
# Compute neighbors per image
_max_neighbors = copy.deepcopy(num_neighbors)
_max_neighbors[
_max_neighbors > max_num_neighbors_threshold
] = max_num_neighbors_threshold
_num_neighbors = torch.zeros(len(cart_coords) + 1, device=device).long()
_natoms = torch.zeros(num_atoms.shape[0] + 1, device=device).long()
_num_neighbors[1:] = torch.cumsum(_max_neighbors, dim=0)
_natoms[1:] = torch.cumsum(num_atoms, dim=0)
num_neighbors_image = (
_num_neighbors[_natoms[1:]] - _num_neighbors[_natoms[:-1]]
)
# If max_num_neighbors is below the threshold, return early
if (
max_num_neighbors <= max_num_neighbors_threshold
or max_num_neighbors_threshold <= 0
):
if topk_per_pair is None:
return torch.stack((index2, index1)), unit_cell, num_neighbors_image
else:
return torch.stack((index2, index1)), unit_cell, num_neighbors_image, topk_mask
atom_distance_sqr = torch.masked_select(atom_distance_sqr, mask)
# Create a tensor of size [num_atoms, max_num_neighbors] to sort the distances of the neighbors.
# Fill with values greater than radius*radius so we can easily remove unused distances later.
distance_sort = torch.zeros(
len(cart_coords) * max_num_neighbors, device=device
).fill_(radius * radius + 1.0)
# Create an index map to map distances from atom_distance_sqr to distance_sort
index_neighbor_offset = torch.cumsum(num_neighbors, dim=0) - num_neighbors
index_neighbor_offset_expand = torch.repeat_interleave(
index_neighbor_offset, num_neighbors
)
index_sort_map = (
index1 * max_num_neighbors
+ torch.arange(len(index1), device=device)
- index_neighbor_offset_expand
)
distance_sort.index_copy_(0, index_sort_map, atom_distance_sqr)
distance_sort = distance_sort.view(len(cart_coords), max_num_neighbors)
# Sort neighboring atoms based on distance
distance_sort, index_sort = torch.sort(distance_sort, dim=1)
# Select the max_num_neighbors_threshold neighbors that are closest
distance_sort = distance_sort[:, :max_num_neighbors_threshold]
index_sort = index_sort[:, :max_num_neighbors_threshold]
# Offset index_sort so that it indexes into index1
index_sort = index_sort + index_neighbor_offset.view(-1, 1).expand(
-1, max_num_neighbors_threshold
)
# Remove "unused pairs" with distances greater than the radius
mask_within_radius = torch.le(distance_sort, radius * radius)
index_sort = torch.masked_select(index_sort, mask_within_radius)
# At this point index_sort contains the index into index1 of the closest max_num_neighbors_threshold neighbors per atom
# Create a mask to remove all pairs not in index_sort
mask_num_neighbors = torch.zeros(len(index1), device=device).bool()
mask_num_neighbors.index_fill_(0, index_sort, True)
# Finally mask out the atoms to ensure each atom has at most max_num_neighbors_threshold neighbors
index1 = torch.masked_select(index1, mask_num_neighbors)
index2 = torch.masked_select(index2, mask_num_neighbors)
unit_cell = torch.masked_select(
unit_cell.view(-1, 3), mask_num_neighbors.view(-1, 1).expand(-1, 3)
)
unit_cell = unit_cell.view(-1, 3)
if topk_per_pair is not None:
topk_mask = torch.masked_select(topk_mask, mask_num_neighbors)
edge_index = torch.stack((index2, index1))
if topk_per_pair is None:
return edge_index, unit_cell, num_neighbors_image
else:
return edge_index, unit_cell, num_neighbors_image, topk_mask
def min_distance_sqr_pbc(cart_coords1, cart_coords2, lengths, angles,
num_atoms, device, return_vector=False,
return_to_jimages=False):