calculate_A_spaces.py 13.8 KB
Newer Older
nsoler's avatar
nsoler committed
1
2
3
# Nico: Jan 2021
# Uses the data calculator class to get all A spaces preprocessed data
# Inspired from the cc pipeline
nsoler's avatar
nsoler committed
4
import os, json
5
6
import numpy as np
import h5py
nsoler's avatar
nsoler committed
7
8
9
import collections

from chemicalchecker.util.parser import DataCalculator
10
from chemicalchecker.core.signature_data import DataSignature
nsoler's avatar
nsoler committed
11
12
13
14
15
16
17
18
19
20
21
22
23
from chemicalchecker.core.preprocess import Preprocess
from chemicalchecker.util.parser import fetch_features_A
from chemicalchecker.util.parser import Converter
from chemicalchecker.core.chemcheck import ChemicalChecker

# type of data, space_name, format size
# Note A3 contains both caffold and framework each encoded on 1024 bits, so we have 2048 total ex: f647,c92 
# A4: supposed to be 166 groups but 152 keys are present in raw 2020_01 preprocess.h5 


class Aspaces_prop_calculator(object):


nsoler's avatar
nsoler committed
24
    def __init__(self, inchikey_list=None, output_directory='tmp', inchikey2inchi_map=None):
nsoler's avatar
nsoler committed
25
26
27
28
29
30
31
32
33
        """
        Class to create the preprocessed h5 data files
        for spaces A1 to A5 for the molecules specified in the input inchikey_inchi dictionary
        It can then create a sign0 object for each class and try to predict sign1 and 2

        Here we cannot use the predict method from Preprocess.save_output since it requires connection to the database
        whereas we work locally.

        Arguments:
nsoler's avatar
nsoler committed
34
35
            - inchikey_list: list or set of inchikeys, (inchis will the be recovered)
            - inchikey2inchi_map (dict): mapping between inchikeys and inchis entered
nsoler's avatar
nsoler committed
36
            - outDir (str): where to put the output h5 files
nsoler's avatar
nsoler committed
37
38
39
40

        # Note: you have to entered the inchikeys by either inchikey_list (then the inchis will be retrieved automatically)
                or by a dictionary with inchikeys as keys and inchis as values. Or by a path to a json file.

nsoler's avatar
nsoler committed
41
42
        """

nsoler's avatar
nsoler committed
43
44
45
46
47
        
        if inchikey_list is None and inchikey2inchi_map is None:
            print("Please enter the inchikeys to process by either inchikey_list or inchikey2inchi_map arguments")
            return

nsoler's avatar
nsoler committed
48
        self.inchikey_list= inchikey_list
nsoler's avatar
nsoler committed
49

nsoler's avatar
nsoler committed
50
51
52
53
54
55
56
57
58
59
        self.data_calculators = {
             'A1': 'morgan_fp_r2_2048',
             'A2': 'e3fp_3conf_1024', 
             'A3': 'murcko_1024_cframe_1024',
             'A4': 'maccs_keys_166',
             'A5': 'general_physchem_properties'}

        self.Aspaces= ('A1', 'A2', 'A3', 'A4', 'A5')
        self.converter= Converter()

nsoler's avatar
nsoler committed
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
        if inchikey2inchi_map is None:
            self.dict_inchikey_inchi= self.inchikey2inchi()

        elif type(inchikey2inchi_map) is str:
            # json file
            try:
                with open(inchikey2inchi_map) as f:
                    self.dict_inchikey_inchi=json.load(f)
            except:
                print("Please provide a dictionary or a path to a json file for inchikey2inchi_map, currently (",inchikey2inchi_map,")")
                return
        else:
            #mapping
            self.dict_inchikey_inchi= inchikey2inchi_map

nsoler's avatar
nsoler committed
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
        self.outDir= output_directory
        if not os.path.exists(self.outDir):
            try:
                os.makedirs(self.outDir)
            except Exception as e:
                print("ERROR: cannot create output directory for ",self.outDir)
                print(e)

        # Our cc instance
        # Put this CC instance inside our output directory
        cc_directory= os.path.join(self.outDir,'cc_absent')

        if not os.path.exists(cc_directory):
            os.makedirs(cc_directory)

nsoler's avatar
nsoler committed
90
        self.cc=ChemicalChecker(cc_root= cc_directory,dbconnect=False)
nsoler's avatar
nsoler committed
91
92


nsoler's avatar
nsoler committed
93
94
95
96
97
98
    def save_inchikey2inchi(self, outputFile="inchikey2inchis.json"):

        with open(outputFile, 'w') as f:
            json.dump(self.dict_inchikey_inchi,f)
            print("Mapping inchikeys / InChIs saved as",outputFile)

nsoler's avatar
nsoler committed
99
100
101
102
    def inchikey2inchi(self):
        # Try with the Molecule class, otherwise use Converter (requires web)
        itWorks=False # no inchikey so far
        dict_inchikey_inchi=dict()
nsoler's avatar
nsoler committed
103
104
105
106
107

        setIn= set(self.inchikey_list)
        print("Recovering InChI for the ", len(setIn),"unique inchickeys entered")
        print("Please wait..")
        for ink in setIn:
nsoler's avatar
nsoler committed
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
            try:
                inchi= self.converter.inchikey_to_inchi(ink)[0]["standardinchi"]
                itWorks=True
                dict_inchikey_inchi[ink]=inchi
            except Exception as e:
                print("ERROR: ",e)
                dict_inchikey_inchi[ink]=None


        # If no inchi could be retrieved:
        if not itWorks:
            print("ERROR: no inchi could be retrieved from the input inchikey list")
            print("Please check your internet connection (required by rdkit)")
            print(self.inchikey_list)
            return None
        else:
            return dict_inchikey_inchi


    def calculate_data_fn(self, space):
        """
        Launch the (chemistry) data calculation for one type of space

        Returns: a list containing the molecular properties in dense format
        ex: [{'inchikey': 'ASXBYYWOLISCLQ-UHFFFAOYSA-N', 'raw': ..raw_string}, {}...]

        Arguments:
        - space (str): either A1, A2, A3, A4, A5, A5
        - dict_inchikey_inchi (dict): mapping of the molecules to calculate properties from

        """

        type_data= self.data_calculators.get(space,None)
        assert type_data is not None, "Space "+space+" is not part of the CC A spaces!"

        print("\nCalculating data for " + type_data)
        parse_fn = DataCalculator.calc_fn(type_data)

        for i,chunk in enumerate(parse_fn(self.dict_inchikey_inchi)):
            if len(chunk) == 0:
                continue
            else:
                return chunk

        return None
            

155
    def calculate_mol_properties(self,outputfiles):
nsoler's avatar
nsoler committed
156
157
158
159
160
161
162
        """
        Calls calculate_data_fn for all spaces

        Returns: a dict containing the molecular properties in dense format for all spaces

        Arguments:
        - space (str): either A1, A2, A3, A4, A5, A5
163
        - outputfiles (dict):mapping space : outputfile path
nsoler's avatar
nsoler committed
164
165
166
        """
        result=dict()
                
167
168
169
170
171
        for space in outputfiles:
            if not os.path.exists(outputfiles[space]):
                result[space]=self.calculate_data_fn(space)
            else:
                print("File", outputfiles[space], "already present, nothing to do")
nsoler's avatar
nsoler committed
172
173
174
175
176
177
178

            # dictionary {'A1': [{'inchikey': 'ASXBYYWOLISCLQ-UHFFFAOYSA-N', 'raw': ..raw_string}, {}...]}
        return result

    # Trying to save the result of A1 (from A1)


nsoler's avatar
nsoler committed
179
    def create_h5(self):
nsoler's avatar
nsoler committed
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195

        print("Retrieving InChI strings from the list of input InChIkeys")

        for i, (inchikey, inchi) in enumerate(self.dict_inchikey_inchi.items()):
            print(i+1,')',inchikey)
            print(inchi)
            print('\n')


        outputfiles= {space: os.path.join(self.outDir,space+'_outsideUniv.h5') for space in self.Aspaces}
        method='predict'
        model_path='tmp'  # Dummy tmp folder
        

        # Compute the raw properties

196
197
        all_properties= self.calculate_mol_properties(outputfiles)
        all_features= fetch_features_A()  # features from the fit() method
nsoler's avatar
nsoler committed
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

        print('all_properties',all_properties)
        print('all_features',all_features)

        # Here we need to preprocess the dense format according to which space we have
        for space in self.Aspaces:

            # Dense chemical properties for all spaces
            raw_prop= all_properties.get(space,None)
            features= all_features.get(space, None)
            feature_int= False if space in ('A3','A5') else True
            discrete= False if space == 'A5' else True

            if raw_prop is None or features is None:
                print("WARNING, space",space,"properties or features is None, space skipped")
                continue

            # format the dense chemical properties in tuples (inchikey, raw_str)
            ACTS= [(dic['inchikey'],dic['raw']) for dic in all_properties[space]]

            if space in ('A1','A2','A3','A4'):

                # Copied from the end of A1 preprocess script
                RAW = collections.defaultdict(list)
                for k in ACTS:
                    # k[0] is the inchikey while k[1] is the raw string of chemical properties
                    if k[1] == '' or k[1] is None or k[0] is None:
                        print("\nWARNING (space ",space,": no property for inchikey",k[0],'\n')
                        continue
                    if features is None:
                        vals = [str(t) for t in k[1].split(",")]
                    else:
                        vals = [str(t) for t in k[1].split(",") if str(t) in features]
                    RAW[str(k[0])] = vals


            elif space == 'A5':
                sigs = collections.defaultdict(list)
                words = []
                first = True
                for k in ACTS:
                    if k[1] is None:
                        continue
                    data = k[1].split(",")
                    vals = []
                    for d in data:
                        ele = d.split("(")
                        if first:
                            words.append(str(ele[0]))
                        vals.append(float(ele[1][:-1]))
                    sigs[str(k[0])] = vals
                    first = False

                RAW=sigs

            # NS: Preprocess.save_output will then convert the dense format into binary data
            print("Saving the chemical properties for space", space, "into", outputfiles[space])
            Preprocess.save_output(outputfiles[space], RAW, method, model_path, discrete, features, features_int=feature_int)
            print("\n")

        # dict space: path to raw file
        return outputfiles

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
297
298
299
300
301
302
    # The next three functions are stolen from the Sanitizer
    def chunker(self, n):
        size = 2000
        for i in range(0, n, size):
            yield slice(i, i + size)


    def rewrite_matrix_h5(self, data, mask, axis=1, name='V'):

        name_tmp = "%s_tmp" % name
        with h5py.File(data, "a") as hf:
            n = hf[name].shape[0]
            create = True
            for chunk in self.chunker(n):
                if axis == 1:
                    M_tmp = hf[name][chunk][:, mask]
                else:
                    mask_ = mask[chunk]
                    M_tmp = hf[name][chunk][mask_]
                if create:
                    hf.create_dataset(name_tmp, data=M_tmp,
                                      maxshape=(None, M_tmp.shape[1]))
                    create = False
                else:
                    hf[name_tmp].resize(
                        (hf[name_tmp].shape[0] + M_tmp.shape[0]), axis=0)
                    hf[name_tmp][-M_tmp.shape[0]:] = M_tmp
            del hf[name]
            hf[name] = hf[name_tmp]
            del hf[name_tmp]

    def rewrite_str_array_h5(self, data, mask, name="features"):
        name_tmp = "%s_tmp" % name
        with h5py.File(data, "a") as hf:
            array_tmp = hf[name][:][mask]
            hf.create_dataset(name_tmp, data=np.array(
                array_tmp, DataSignature.string_dtype()))
            del hf[name]
            hf[name] = hf[name_tmp]
            del hf[name_tmp]


nsoler's avatar
nsoler committed
303
304
305
    def createSign0(self, dict_of_Aspaces_h5, sanitize=False):
        """
        Create sign0 from all raw A spaces h5 files created with create_h5_from_inchikeys_inchi
306
307
308
309
        Here we take in a list of 5 paths to raw data (A1 o A5) and return a cc instance that contains 
        sign0 for these 5 spaces.

        Column filtering: we 'Sanitize' (remove features) according to what was done in the CC_repo for spaces A1 to A5.
nsoler's avatar
nsoler committed
310
311
        """

312

nsoler's avatar
nsoler committed
313
314
        # Now creating sign0 for each of the input raw files
        for space, fp in dict_of_Aspaces_h5.items():
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
            for molset in ('full','reference'):

                print("\nCalculating sign0",molset,"for space", space)
                sign0 = self.cc.get_signature('sign0', molset, space+'.001')
                features_from_fit= self.cc.import_features_sign0(sign0)

                if not sign0.available():
                    sign0.fit(data_file=fp,do_triplets=False, overwrite=True,sanitize=sanitize)
                else:
                    print("Sign0", molset, "for space", space+'.001', "already fit, nothing to do")

                # Now remove the required features (columns) from the sign0 h5 file

                mask = np.isin(sign0.features, features_from_fit)
                self.rewrite_matrix_h5(sign0.data_path, mask)
                self.rewrite_str_array_h5(sign0.data_path, mask)
nsoler's avatar
nsoler committed
331
332
333
334
335
336
337

        # Then we can use this cc instance to predict sign1
        return self.cc


    def predictSign1(self):

nsoler's avatar
nsoler committed
338
339
340
341
342
        # Import the prediction models for sign1

        dictSpaces= self.cc.report_available()
        if "reference" in dictSpaces:
            dictSpaces=dictSpaces['reference']
nsoler's avatar
nsoler committed
343
            
nsoler's avatar
nsoler committed
344
345
346
347
        else:
            print("No sign0 available in your cc repo")
            return

nsoler's avatar
nsoler committed
348
349
        for space in self.Aspaces:

350
                assert space+'.001' in dictSpaces.keys(), print("Sign0 for space",space, "not fit!!")
351
                models_imported =False
nsoler's avatar
nsoler committed
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368

                sign0= self.cc.get_signature('sign0', 'full' , space+'.001') # already fitted
                sign1 = self.cc.get_signature('sign1', 'full', space+'.001') # will get converted to reference by the next fct
                sign1.clear()

                # import models from the fit that took place in CC_repo 2020_XX
                if not models_imported:
                    self.cc.import_models_for_prediction(sign1) # Import model for this space
                    models_imported =True

                destination = sign1.data_path
                if not os.path.exists(destination):
                    print("\nPredicting sign1 full for space",space, 'to' ,destination)
                    sign1.predict(sign0,destination=destination)

                # reference
                sign1.save_reference(cpu=1)
nsoler's avatar
nsoler committed
369

nsoler's avatar
nsoler committed
370
371
372
373
374
375
        return self.cc

    def predictSign2(self):
        
        return self.cc