-
Notifications
You must be signed in to change notification settings - Fork 0
/
GetTensorCoulombMatrix.py
48 lines (34 loc) · 1.52 KB
/
GetTensorCoulombMatrix.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
from rdkit import Chem
from rdkit.Chem import AllChem, rdMolDescriptors
import torch
def GetTensorCoulombMatrix(molecule, pad_up_to = None, skipConformerGeneration = False):
"""
Generates a Coulomb Matrix as tensor from a rdkit.Chem.rdchem.Mol or SMILES string.
Arguments:
molecule: rdkit.Chem.rdchem.Mol or SMILES-string (str)
pad_up_to: If not None, the output Tensor is padded up to this number along the 1st dimension.
Returns:
A torch.tensor of size (n_atoms x atoms) if pad_up_to = None
Otherwise returns a tensor of size (n_atoms x pad_up_to)
"""
assert type(molecule) in [str, rdkit.Chem.rdchem.Mol], "Molecule is neither an rdkit mol or string"
if type(molecule) == str:
molecule = Chem.MolFromSmiles(molecule)
if not skipConformerGeneration:
molecule = Chem.AddHs(molecule)
ps = AllChem.ETKDGv2()
AllChem.EmbedMolecule(molecule, ps)
if molecule.GetNumConformers() == 0: # If conformer generation fails the first time around, try to start from random coordinates
ps.useRandomCoords = True
AllChem.EmbedMolecule(molecule, ps)
try:
cmat = rdMolDescriptors.CalcCoulombMat(molecule)
cmat_as_tensor = torch.vstack([torch.tensor(row, dtype = torch.float) for row in cmat])
except:
raise ValueError("Failed to generate coulomb matrix :(")
if pad_up_to is not None:
width = cmat_as_tensor.shape[1]
needed_pad = pad_up_to - width
return torch.nn.functional.pad(input = cmat_as_tensor, pad = (0, needed_pad))
else:
return cmat_as_tensor