File size: 11,480 Bytes
2a79cd9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import re
import shutil
from tqdm import tqdm

from IPython.display import display
from morfeus.buried_volume import BuriedVolume
from morfeus.conformer import ConformerEnsemble
from morfeus.dispersion import Dispersion
from morfeus.sasa import SASA
from morfeus.xtb import XTB
import numpy as np
import pandas as pd
from rdkit import Chem
from rdkit.Chem import rdFMCS, Draw


def calculate_morfeus_descriptors (smiles_list,
                                   filename,
                                   common_core=None,
                                   chunk_size=10,
                                   find_restart = True,
                                   starting_smiles_nr=1,
                                   chunk_label=1):
    """
    Calculate morfeus descriptors at the GFN2-xTB level for  a list of given smiles strings.
    ---------------
    smiles_list: list
        list of smiles strings
    common_core: str or None
        smarts for the common core of interest
        Default is None --> will look for the largest common substructure in the molecule
    filename: str
        path for the generated dataset
    common_core: str or None
        SMARTS for a substructure for which atom descriptors will be extracted
        If common_core=None (Default), the atom descriptors will be calculated for the
        maximum common substructure.
    chunk_size: int
        number of compounds that will be calculated in one chunk before saving the obtained data
        at the end of the run, all chunks will be concatenated.
        Default: 10
    find_restart: Boolean
        If True, the  algorithm will parse if some chunks were already calculated and auto-restart 
        with the next chunk, overwriting the starting_smiles_nr and chunk_label variables.
        NOTE: Assumes that the chunk_size was not changed
    starting_smiles_nr: int (one-indexed)
        first entry of the smiles list to be calculated
        Default: 1
        (useful for restarting in case the calculation crashes)
        NOTE: overwritten if find_restart = True
    chunk_label: int
        label for the next chunk to be calculated
        Default: 1
        (useful for restarting in case the calculation crashes)
        NOTE: overwritten if find_restart = True
    ----------------------
    Save the descriptor data under the indicated filename
    Also returns a list of pd.DataFrames for the data of the individual chunks
    as well as a pd.DataFrame for the combined Data of all calculated structures

    """

    print("This might take several minutes or even hours. Please stand by.")
    # Find common substructure and align the template
    # Create a folder to save the separate chunks of calculation results
    if not os.path.exists("./featurization_temp"):
        # Create the folder
        os.makedirs("./featurization_temp")

    # Create a template for the common core with consistent atom ordering
    template = None
    if common_core is None:
        # find the maximum common substructure if no common core is provided
        template = _get_mcs_template_with_consistent_atom_order(smiles_list)
    else:
        # use the provided common core
        template = _map_common_core_with_consistent_atom_order(smiles_list,common_core)

    # draw the template
    print("Atom properties will be calculated for the following common substructure:")
    depiction = Draw.MolToImage(template)
    display(depiction)

    pt = Chem.GetPeriodicTable()

    results = []
    smiles_list_chunk = []
    properties = None

    # check if some chunks have already been calculated and automatically restart
    if find_restart:

        # check if ./featurization_temp (temporary results folder) is empty
        last_chunk = None
        chunk_folder = "./featurization_temp"
        if not os.listdir(chunk_folder):
            last_chunk = 0  # no chunks run yet
        else: # some chunks already exist
            # check which chunk was run last
            pattern = re.compile(r"feat_chunk_(\d+)\.csv$")
            for fname in os.listdir(chunk_folder):
                match = pattern.match(fname)
                if match:
                    obs_chunk = int(match.group(1))
                    if last_chunk is None or obs_chunk > last_chunk:
                        last_chunk = obs_chunk

        # update the next chunk label and the starting_smiles_nr
        chunk_label = last_chunk + 1
        starting_smiles_nr = last_chunk * chunk_size +1

    # go through the provided smiles
    for smiles_index, smiles in enumerate(tqdm(smiles_list[(starting_smiles_nr-1):])):
        smiles_index = smiles_index + starting_smiles_nr -1
        current_results = {}

        # Generate conformer ensemble
        ce = ConformerEnsemble.from_rdkit(smiles,optimize="MMFF94")
        ce.prune_rmsd()
        ce.sort()
        if len(ce) > 5:
            ce = ce[:5]  # prune to top 5 conformers 
        
        # Optimize conformers
        model = {"method": "GFN2-xTB"}
        ce.optimize_qc_engine(program="xtb",model=model,procedure="geometric")
        ce.sp_qc_engine(program="xtb",model=model)
        ce.prune_energy()

        # Get the matching substructure (excluding hydrogens)
        match = ce.mol.GetSubstructMatch(template)
        substruct_atoms = [pt.GetElementSymbol(int(ce.elements[nr])) for nr in match]
        substruct_labels = _append_occurrence_numbers(substruct_atoms)

        # calculate properties for each conformer
        for conformer in ce:
            props = conformer.properties
            sasa = SASA(ce.elements, conformer.coordinates)
            disp = Dispersion(ce.elements, conformer.coordinates)
            xtb = XTB(ce.elements, conformer.coordinates)

            # save the global property values
            props["SASA"] = sasa.area
            props["Volume"] = disp.volume
            props["HOMO"] = xtb.get_homo()
            props["LUMO"] = xtb.get_lumo()
            props["IP"] = xtb.get_ip(corrected=True)
            props["EA"] = xtb.get_ea(corrected=True)
            props["Dipole"] = np.linalg.norm(xtb.get_dipole())

            # calculate atom properties
            sasa_atom_areas = sasa.atom_areas
            disp_atom_p_int = disp.atom_p_int
            charges = xtb.get_charges()
            electrophilicity = xtb.get_fukui("electrophilicity")
            nucleophilicity = xtb.get_fukui("nucleophilicity")
            radical_fukui = xtb.get_fukui("radical")

            # save the atom properties
            for i,idx in enumerate(match):
                atom_label = substruct_labels[i]
                bv = BuriedVolume(ce.elements, conformer.coordinates, idx+1)
                props[f"{atom_label}_BV"] = bv.fraction_buried_volume
                props[f"{atom_label}_SASA"] = sasa_atom_areas[idx+1]
                props[f"{atom_label}_P_int"] = disp_atom_p_int[idx+1]
                props[f"{atom_label}_charge"] = charges[idx+1]
                props[f"{atom_label}_electrophilicity"] = electrophilicity[idx+1]
                props[f"{atom_label}_nucleophilicity"] = nucleophilicity[idx+1]
                props[f"{atom_label}_radicalFukui"] = radical_fukui[idx+1]

            # collect the property names during the first iteration
            if smiles == smiles_list[(starting_smiles_nr-1)] and conformer == ce[0]:
                properties = props.keys()

        # calculate Boltzmann-weighted average for each property
        for property in properties:
            current_results[property] = ce.boltzmann_statistic(property)
        results.append(current_results)

        smiles_list_chunk.append(smiles)  # add the smiles to the list of smiles in this chunk

        if (smiles_index + 1) % chunk_size == 0:  # check if the chunk is full; +1 due to zero-indexing
            # save the current chunk
            pd.DataFrame(results,index=smiles_list_chunk,columns=properties).to_csv(f"./featurization_temp/feat_chunk_{chunk_label}.csv",
                                                                                    index=True, header=True)
            
            # clean out the collection variables for the next chunk
            results = []
            smiles_list_chunk = []
            chunk_label += 1  # update the chunk label for the next chunk
    
    # once all smiles have been calculated, save the last samples in a final chunk
    if smiles_list_chunk:
        pd.DataFrame(results,index=smiles_list_chunk,columns=properties).to_csv(f"./featurization_temp/feat_chunk_{chunk_label}.csv",index=True,header=True)

    # combine the chunks and clean up
    dfs = []
    for chunk_file in os.listdir("./featurization_temp"):
        dfs.append(pd.read_csv(f"./featurization_temp/{chunk_file}",index_col=0,header=0))
    df_combined = pd.concat(dfs,axis=0)
    df_combined.to_csv(filename,index=True,header=True)
    shutil.rmtree("./featurization_temp")
    os.remove("qce_optim.xyz")

    print("Finished descriptor calculation.")

    return dfs, df_combined


def _append_occurrence_numbers(strings):
    counts = {}
    result = []
    for s in strings:
        counts[s] = counts.get(s, 0) + 1
        result.append(f"{s}_{counts[s]}")
    return result


def _generate_template(ref_mol,core_mol):
    """
    Generate a template mol with consistent atom ordering 
    based on a reference molecule and a common core.
    """

    match = ref_mol.GetSubstructMatch(core_mol)

    # Create a substructure mol (just the MCS) with atom mapping
    em = Chem.EditableMol(Chem.Mol())
    atom_map = {}
    for new_idx, old_idx in enumerate(match):
        atom = ref_mol.GetAtomWithIdx(old_idx)
        atom_map[old_idx] = new_idx
        new_atom = Chem.Atom(atom.GetAtomicNum())
        new_atom.SetAtomMapNum(new_idx + 1)  # Atom map numbers start at 1
        em.AddAtom(new_atom)

    # Add bonds within the MCS
    for i, idx1 in enumerate(match):
        for j, idx2 in enumerate(match):
            if idx1 >= idx2:
                continue
            bond = ref_mol.GetBondBetweenAtoms(idx1, idx2)
            if bond:
                em.AddBond(atom_map[idx1], atom_map[idx2], bond.GetBondType())

    mcs_submol = em.GetMol()
    smarts_with_map = Chem.MolToSmarts(mcs_submol)
    template = Chem.MolFromSmarts(smarts_with_map)

    return template


def _get_mcs_template_with_consistent_atom_order(smiles_list):
    """Generate a template mol with consistent atom ordering based on the MCS of a list of smiles strings."""

    # Convert SMILES to H-added mols
    mols = [Chem.AddHs(Chem.MolFromSmiles(smi)) for smi in smiles_list]

    # Find MCS
    mcs_result = rdFMCS.FindMCS(mols)
    mcs_mol = Chem.RemoveAllHs(Chem.MolFromSmarts(mcs_result.smartsString))

    # Use first molecule as reference for the template generation
    template = _generate_template(ref_mol=mols[0],core_mol=mcs_mol)
    return template


def _map_common_core_with_consistent_atom_order(smiles_list,common_core):
    """Generate a template mol with consistent atom ordering based on a provided common core and a list of smiles strings."""
    # generate mol objects for smiles_list
    mols = [Chem.AddHs(Chem.MolFromSmiles(smiles)) for smiles in smiles_list]

    # generate mol for common_core
    core_mol = Chem.RemoveAllHs(Chem.MolFromSmarts(common_core))

    # Use first molecule as reference for the template generation
    template = _generate_template(ref_mol=mols[0],core_mol=core_mol)
    return template