File size: 7,708 Bytes
714cf46
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Compute conformers and symmetries for all the CCD molecules."""

import argparse
import multiprocessing
import pickle
import sys
from functools import partial
from pathlib import Path

import pandas as pd
import rdkit
from p_tqdm import p_uimap
from pdbeccdutils.core import ccd_reader
from pdbeccdutils.core.component import ConformerType
from rdkit import rdBase
from rdkit.Chem import AllChem
from rdkit.Chem.rdchem import Conformer, Mol
from tqdm import tqdm


def load_molecules(components: str) -> list[Mol]:
    """Load the CCD components file.

    Parameters
    ----------
    components : str
        Path to the CCD components file.

    Returns
    -------
    list[Mol]

    """
    components: dict[str, ccd_reader.CCDReaderResult]
    components = ccd_reader.read_pdb_components_file(components)

    mols = []
    for name, component in components.items():
        mol = component.component.mol
        mol.SetProp("PDB_NAME", name)
        mols.append(mol)

    return mols


def compute_3d(mol: Mol, version: str = "v3") -> bool:
    """Generate 3D coordinates using EKTDG method.

    Taken from `pdbeccdutils.core.component.Component`.

    Parameters
    ----------
    mol: Mol
        The RDKit molecule to process
    version: str, optional
        The ETKDG version, defaults ot v3

    Returns
    -------
    bool
        Whether computation was successful.

    """
    if version == "v3":
        options = rdkit.Chem.AllChem.ETKDGv3()
    elif version == "v2":
        options = rdkit.Chem.AllChem.ETKDGv2()
    else:
        options = rdkit.Chem.AllChem.ETKDGv2()

    options.clearConfs = False
    conf_id = -1

    try:
        conf_id = rdkit.Chem.AllChem.EmbedMolecule(mol, options)
        rdkit.Chem.AllChem.UFFOptimizeMolecule(mol, confId=conf_id, maxIters=1000)

    except RuntimeError:
        pass  # Force field issue here
    except ValueError:
        pass  # sanitization issue here

    if conf_id != -1:
        conformer = mol.GetConformer(conf_id)
        conformer.SetProp("name", ConformerType.Computed.name)
        conformer.SetProp("coord_generation", f"ETKDG{version}")

        return True

    return False


def get_conformer(mol: Mol, c_type: ConformerType) -> Conformer:
    """Retrieve an rdkit object for a deemed conformer.

    Taken from `pdbeccdutils.core.component.Component`.

    Parameters
    ----------
    mol: Mol
        The molecule to process.
    c_type: ConformerType
        The conformer type to extract.

    Returns
    -------
    Conformer
        The desired conformer, if any.

    Raises
    ------
    ValueError
        If there are no conformers of the given tyoe.

    """
    for c in mol.GetConformers():
        try:
            if c.GetProp("name") == c_type.name:
                return c
        except KeyError:  # noqa: PERF203
            pass

    msg = f"Conformer {c_type.name} does not exist."
    raise ValueError(msg)


def compute_symmetries(mol: Mol) -> list[list[int]]:
    """Compute the symmetries of a molecule.

    Parameters
    ----------
    mol : Mol
        The molecule to process

    Returns
    -------
    list[list[int]]
        The symmetries as a list of index permutations

    """
    mol = AllChem.RemoveHs(mol)
    idx_map = {}
    atom_idx = 0
    for i, atom in enumerate(mol.GetAtoms()):
        # Skip if leaving atoms
        if int(atom.GetProp("leaving_atom")):
            continue
        idx_map[i] = atom_idx
        atom_idx += 1

    # Calculate self permutations
    permutations = []
    raw_permutations = mol.GetSubstructMatches(mol, uniquify=False)
    for raw_permutation in raw_permutations:
        # Filter out permutations with leaving atoms
        try:
            if {raw_permutation[idx] for idx in idx_map} == set(idx_map.keys()):
                permutation = [
                    idx_map[idx] for idx in raw_permutation if idx in idx_map
                ]
                permutations.append(permutation)
        except Exception:  # noqa: S110, PERF203, BLE001
            pass
    serialized_permutations = pickle.dumps(permutations)
    mol.SetProp("symmetries", serialized_permutations.hex())
    return permutations


def process(mol: Mol, output: str) -> tuple[str, str]:
    """Process a CCD component.

    Parameters
    ----------
    mol : Mol
        The molecule to process
    output : str
        The directory to save the molecules

    Returns
    -------
    str
        The name of the component
    str
        The result of the conformer generation

    """
    # Get name
    name = mol.GetProp("PDB_NAME")

    # Check if single atom
    if mol.GetNumAtoms() == 1:
        result = "single"
    else:
        # Get the 3D conformer
        try:
            # Try to generate a 3D conformer with RDKit
            success = compute_3d(mol, version="v3")
            if success:
                _ = get_conformer(mol, ConformerType.Computed)
                result = "computed"

            # Otherwise, default to the ideal coordinates
            else:
                _ = get_conformer(mol, ConformerType.Ideal)
                result = "ideal"
        except ValueError:
            result = "failed"

    # Dump the molecule
    path = Path(output) / f"{name}.pkl"
    with path.open("wb") as f:
        pickle.dump(mol, f)

    # Output the results
    return name, result


def main(args: argparse.Namespace) -> None:
    """Process conformers."""
    # Set property saving
    rdkit.Chem.SetDefaultPickleProperties(rdkit.Chem.PropertyPickleOptions.AllProps)

    # Load components
    print("Loading components")  # noqa: T201
    molecules = load_molecules(args.components)

    # Reset stdout and stderr, as pdbccdutils messes with them
    sys.stdout = sys.__stdout__
    sys.stderr = sys.__stderr__

    # Disable rdkit warnings
    blocker = rdBase.BlockLogs()  # noqa: F841

    # Setup processing function
    outdir = Path(args.outdir)
    outdir.mkdir(parents=True, exist_ok=True)
    mol_output = outdir / "mols"
    mol_output.mkdir(parents=True, exist_ok=True)
    process_fn = partial(process, output=str(mol_output))

    # Process the files in parallel
    print("Processing components")  # noqa: T201
    metadata = []

    # Check if we can run in parallel
    max_processes = multiprocessing.cpu_count()
    num_processes = max(1, min(args.num_processes, max_processes, len(molecules)))
    parallel = num_processes > 1

    if parallel:
        for name, result in p_uimap(
            process_fn,
            molecules,
            num_cpus=num_processes,
        ):
            metadata.append({"name": name, "result": result})
    else:
        for mol in tqdm(molecules):
            name, result = process_fn(mol)
            metadata.append({"name": name, "result": result})

    # Load and group outputs
    molecules = {}
    for item in metadata:
        if item["result"] == "failed":
            continue

        # Load the mol file
        path = mol_output / f"{item['name']}.pkl"
        with path.open("rb") as f:
            mol = pickle.load(f)  # noqa: S301
            molecules[item["name"]] = mol

    # Dump metadata
    path = outdir / "results.csv"
    metadata = pd.DataFrame(metadata)
    metadata.to_csv(path)

    # Dump the components
    path = outdir / "ccd.pkl"
    with path.open("wb") as f:
        pickle.dump(molecules, f)


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--components", type=str)
    parser.add_argument("--outdir", type=str)
    parser.add_argument(
        "--num_processes",
        type=int,
        default=multiprocessing.cpu_count(),
    )
    args = parser.parse_args()
    main(args)