Skip to content

to_rdmol

to_rdmol(data: GraphData, kekulize: bool = False) -> Any

Converts a GraphData with the features of from_rdmol() back to an RDKit molecule, as PyG's to_rdmol.

Parameters:

Name Type Description Default
data GraphData

The molecular graph.

required
kekulize bool

Whether to convert the aromatic bonds to single and double bonds. Default: False

False

Returns:

Type Description
Any

The sanitized rdkit.Chem.Mol.

Source code in mlx_graphs/utils/smiles.py
def to_rdmol(data: "GraphData", kekulize: bool = False) -> Any:
    r"""Converts a :class:`~mlx_graphs.data.GraphData` with the features of
    :func:`from_rdmol` back to an RDKit molecule, as PyG's ``to_rdmol``.

    Args:
        data: The molecular graph.
        kekulize: Whether to convert the aromatic bonds to single and double
            bonds. Default: ``False``

    Returns:
        The sanitized ``rdkit.Chem.Mol``.
    """
    Chem, _ = _import_rdkit()
    if data.node_features is None or data.edge_features is None:
        raise ValueError("The graph needs node_features and edge_features")

    x = _numpy(data.node_features).astype(np.int64)
    edge_index = _numpy(data.edge_index).astype(np.int64)
    edge_attr = _numpy(data.edge_features).astype(np.int64)

    mol = Chem.RWMol()
    for i in range(x.shape[0]):
        atom = Chem.Atom(int(x[i, 0]))
        atom.SetChiralTag(Chem.rdchem.ChiralType.values[int(x[i, 1])])
        atom.SetFormalCharge(x_map["formal_charge"][int(x[i, 3])])
        atom.SetNumExplicitHs(x_map["num_hs"][int(x[i, 4])])
        atom.SetNumRadicalElectrons(x_map["num_radical_electrons"][int(x[i, 5])])
        atom.SetHybridization(Chem.rdchem.HybridizationType.values[int(x[i, 6])])
        atom.SetIsAromatic(bool(x[i, 7]))
        mol.AddAtom(atom)

    visited = set()
    for k, (src, dst) in enumerate(edge_index.T.tolist()):
        key = (min(src, dst), max(src, dst))
        if key in visited:
            continue
        mol.AddBond(src, dst, Chem.BondType.values[int(edge_attr[k, 0])])

        stereo = Chem.rdchem.BondStereo.values[int(edge_attr[k, 1])]
        if stereo != Chem.rdchem.BondStereo.STEREONONE:
            bond = mol.GetBondBetweenAtoms(src, dst)
            bond.SetStereoAtoms(dst, src)
            bond.SetStereo(stereo)

        mol.GetBondBetweenAtoms(src, dst).SetIsConjugated(bool(edge_attr[k, 2]))
        visited.add(key)

    mol = mol.GetMol()
    if kekulize:
        Chem.Kekulize(mol)
    Chem.SanitizeMol(mol)
    Chem.AssignStereochemistry(mol)
    return mol

from mlx_graphs.utils import to_rdmol · mlx_graphs/utils/smiles.py