|
| 1 | +# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +""" |
| 16 | +Convert Kiba and Davis datasets into npz file which can be trained directly. |
| 17 | +
|
| 18 | +Note that the dataset split is inherited from GraphDTA and DeepDTA |
| 19 | +""" |
| 20 | + |
| 21 | +import os |
| 22 | +import sys |
| 23 | +import json |
| 24 | +import random |
| 25 | +import pickle |
| 26 | +import argparse |
| 27 | +import numpy as np |
| 28 | +from rdkit import Chem |
| 29 | +from rdkit.Chem import AllChem |
| 30 | +from collections import OrderedDict |
| 31 | + |
| 32 | +from pahelix.utils.compound_tools import mol_to_graph_data |
| 33 | +from pahelix.utils.protein_tools import ProteinTokenizer |
| 34 | +from pahelix.utils.data_utils import save_data_list_to_npz |
| 35 | + |
| 36 | + |
| 37 | +def main(): |
| 38 | + """Entry for data preprocessing.""" |
| 39 | + tokenizer = ProteinTokenizer() |
| 40 | + for dataset in ['davis', 'kiba']: |
| 41 | + data_dir = os.path.join(args.dataset_root, dataset) |
| 42 | + if not os.path.exists(data_dir): |
| 43 | + print('Cannot find {}'.format(data_dir)) |
| 44 | + continue |
| 45 | + |
| 46 | + train_fold = json.load( |
| 47 | + open(os.path.join(data_dir, 'folds', 'train_fold_setting1.txt'))) |
| 48 | + train_fold = [ee for e in train_fold for ee in e] # flatten |
| 49 | + test_fold = json.load( |
| 50 | + open(os.path.join(data_dir, 'folds', 'test_fold_setting1.txt'))) |
| 51 | + ligands = json.load( |
| 52 | + open(os.path.join(data_dir, 'ligands_can.txt')), |
| 53 | + object_pairs_hook=OrderedDict) |
| 54 | + proteins = json.load( |
| 55 | + open(os.path.join(data_dir, 'proteins.txt')), |
| 56 | + object_pairs_hook=OrderedDict) |
| 57 | + # Use encoding 'latin1' to load py2 pkl from py3 |
| 58 | + # pylint: disable=E1123 |
| 59 | + affinity = pickle.load( |
| 60 | + open(os.path.join(data_dir, 'Y'), 'rb'), encoding='latin1') |
| 61 | + |
| 62 | + smiles_lst, protein_lst = [], [] |
| 63 | + for k in ligands.keys(): |
| 64 | + smiles = Chem.MolToSmiles(Chem.MolFromSmiles(ligands[k]), |
| 65 | + isomericSmiles=True) |
| 66 | + smiles_lst.append(smiles) |
| 67 | + |
| 68 | + for k in proteins.keys(): |
| 69 | + protein_lst.append(proteins[k]) |
| 70 | + |
| 71 | + if dataset == 'davis': |
| 72 | + # Kd data |
| 73 | + affinity = [-np.log10(y / 1e9) for y in affinity] |
| 74 | + |
| 75 | + affinity = np.asarray(affinity) |
| 76 | + |
| 77 | + # pylint: disable=E1123 |
| 78 | + os.makedirs(os.path.join(data_dir, 'processed'), exist_ok=True) |
| 79 | + for split in ['train', 'test']: |
| 80 | + print('processing {} set of {}'.format(split, dataset)) |
| 81 | + |
| 82 | + split_dir = os.path.join(data_dir, 'processed', split) |
| 83 | + # pylint: disable=E1123 |
| 84 | + os.makedirs(split_dir, exist_ok=True) |
| 85 | + |
| 86 | + fold = train_fold if split == 'train' else test_fold |
| 87 | + rows, cols = np.where(np.isnan(affinity) == False) |
| 88 | + rows, cols = rows[fold], cols[fold] |
| 89 | + |
| 90 | + data_lst = [] |
| 91 | + for idx in range(len(rows)): |
| 92 | + mol = AllChem.MolFromSmiles(smiles_lst[rows[idx]]) |
| 93 | + mol_graph = mol_to_graph_data(mol) |
| 94 | + data = {k: v for k, v in mol_graph.items()} |
| 95 | + |
| 96 | + seqs = [] |
| 97 | + for seq in protein_lst[cols[idx]].split('\x01'): |
| 98 | + seqs.extend(tokenizer.gen_token_ids(seq)) |
| 99 | + data['protein_token_ids'] = np.array(seqs) |
| 100 | + |
| 101 | + af = affinity[rows[idx], cols[idx]] |
| 102 | + if dataset == 'davis': |
| 103 | + data['Log10_Kd'] = np.array([af]) |
| 104 | + elif dataset == 'kiba': |
| 105 | + data['KIBA'] = np.array([af]) |
| 106 | + |
| 107 | + data_lst.append(data) |
| 108 | + |
| 109 | + random.shuffle(data_lst) |
| 110 | + npz = os.path.join(split_dir, '{}_{}.npz'.format(dataset, split)) |
| 111 | + save_data_list_to_npz(data_lst, npz) |
| 112 | + |
| 113 | + print('==============================') |
| 114 | + print('dataset:', dataset) |
| 115 | + print('train_fold:', len(train_fold)) |
| 116 | + print('test_fold:', len(test_fold)) |
| 117 | + print('unique drugs:', len(set(smiles_lst))) |
| 118 | + print('unique proteins:', len(set(protein_lst))) |
| 119 | + |
| 120 | + |
| 121 | +if __name__ == '__main__': |
| 122 | + parser = argparse.ArgumentParser() |
| 123 | + parser.add_argument('--dataset_root', type=str, default='data') |
| 124 | + parser.add_argument('--npz_files', type=int, default=1) # set it > 1 for multi trainers |
| 125 | + args = parser.parse_args() |
| 126 | + main() |
0 commit comments