File size: 4,465 Bytes
ce9690f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gzip
import os
from typing import List, Optional, Tuple

import numpy as np
import rdkit.Chem as Chem

from spyrmsd import molecule, utils


def _load_block_gzipped(loader, fname: str):
    """
    Load gzipped files using MolBlocks.

    Parameters
    ----------
    loader:
        RDKit MolBlock loader (MolFromMol2Block, MolFromPDBBlock, ...)
    fname: str
        File name

    Returns
    -------
    Molecule
    """
    with gzip.open(fname, "r") as fgz:
        content = fgz.read()
        rdmol = loader(content, removeHs=False)

    return rdmol


def load(fname: str):
    """
    Load molecule from file.

    Parameters
    ----------
    fname: str
        File name

    Returns
    -------
    Molecule
    """

    gzipped = os.path.splitext(fname)[-1] == ".gz"
    fmt = utils.molformat(fname)

    if fmt == "mol2":
        if not gzipped:
            rdmol = Chem.MolFromMol2File(fname, removeHs=False)
        else:
            rdmol = _load_block_gzipped(Chem.MolFromMol2Block, fname)
    elif fmt == "sdf":
        if not gzipped:
            rdmol = next(Chem.SDMolSupplier(fname, removeHs=False))
        else:
            with gzip.open(fname, "r") as fgz:
                rdmol = next(Chem.ForwardSDMolSupplier(fgz, removeHs=False))
    elif fmt == "pdb":
        if not gzipped:
            rdmol = Chem.MolFromPDBFile(fname, removeHs=False)
        else:
            rdmol = _load_block_gzipped(Chem.MolFromPDBBlock, fname)
    else:
        raise NotImplementedError

    return rdmol


def loadall(fname: str):
    """
    Load molecules from file.

    Parameters
    ----------
    fname: str
        File name

    Returns
    -------
    List of molecules
    """

    gzipped = os.path.splitext(fname)[-1] == ".gz"
    fmt = utils.molformat(fname)

    if fmt == "mol2":
        raise NotImplementedError  # See RDKit Issue #415
    elif fmt == "sdf":
        if not gzipped:
            rdmols = Chem.SDMolSupplier(fname, removeHs=False)
            mols = [rdmol for rdmol in rdmols]
        else:
            with gzip.open(fname, "r") as fgz:
                rdmols = Chem.ForwardSDMolSupplier(fgz, removeHs=False)

                # Load all molecules before closing file
                mols = [rdmol for rdmol in rdmols]
    elif fmt == "pdb":
        # TODO: Implement
        raise NotImplementedError
    else:
        raise NotImplementedError

    return mols


def adjacency_matrix(mol) -> np.ndarray:
    """
    Adjacency matrix from OpenBabel molecule.

    Parameters
    ----------
    mol:
        Molecule

    Returns
    -------
    np.ndarray
        Adjacency matrix of the molecule
    """

    return Chem.rdmolops.GetAdjacencyMatrix(mol)


def to_molecule(mol, adjacency: bool = True):
    """
    Transform molecule to `pyrmsd` molecule.

    Parameters
    ----------
    mol:
        Molecule
    adjacency: boolean, optional
        Flag to decide wether to build the adjacency matrix from molecule

    Returns
    -------
    spyrmsd.molecule.Molecule
        `spyrmsd` molecule
    """

    if mol is None:
        # Propagate RDKit parsing failure
        return None

    atoms = mol.GetAtoms()

    n = len(atoms)

    atomicnums = np.zeros(n, dtype=int)
    coordinates = np.zeros((n, 3))

    conformer = mol.GetConformer()

    for i, atom in enumerate(atoms):
        atomicnums[i] = atom.GetAtomicNum()

        pos = conformer.GetAtomPosition(i)

        coordinates[i] = np.array([pos.x, pos.y, pos.z])

    A: Optional[np.ndarray] = adjacency_matrix(mol) if adjacency else None

    return molecule.Molecule(atomicnums, coordinates, A)


def numatoms(mol) -> int:
    """
    Number of atoms.

    Parameters
    ----------
    mol:
        Molecule

    Returns
    -------
    int
        Number of atoms
    """
    return mol.GetNumAtoms()


def numbonds(mol) -> int:
    """
    Number of bonds.

    Parameters
    ----------
    mol:
        Molecule

    Returns
    -------
    int
        Number of bonds
    """
    return mol.GetNumBonds()


def bonds(mol) -> List[Tuple[int, int]]:
    """
    List of bonds.

    Parameters
    ----------
    mol:
        Molecule

    Returns
    -------
    List[Tuple[int, int]]
        List of bonds

    Notes
    -----
    A bond is defined by a tuple of (0-based) indices of two atoms.
    """
    b = []

    for bond in mol.GetBonds():
        b.append((bond.GetBeginAtomIdx(), bond.GetEndAtomIdx()))

    return b