from mpi4py import MPI from mpi4py.futures import MPICommExecutor import warnings from Bio.PDB import PDBParser, PPBuilder, CaPPBuilder from Bio.PDB.NeighborSearch import NeighborSearch from Bio.PDB.Selection import unfold_entities import numpy as np import dask.array as da from rdkit import Chem from functools import partial import os import re import sys import io import random import gzip import copy from atomic_renamer import AtomicNamer from prody import * import webdataset as wd amino_acids = {'L': 'LEU', 'A': 'ALA', 'G': 'GLY', 'V': 'VAL', 'E': 'GLU', 'S': 'SER', 'I': 'ILE', 'K': 'LYS', 'R': 'ARG', 'D': 'ASP', 'T': 'THR', 'P': 'PRO', 'N': 'ASN', 'Q': 'GLN', 'F': 'PHE', 'Y': 'TYR', 'M': 'MET', 'H': 'HIS', 'C': 'CYS', 'W': 'TRP'} nfeat = 15 # number of heavy atom coordinates # all punctuation punctuation_regex = r"""(\(|\)|\.|=|#|-|\+|\\|\/|:|~|@|\?|>>?|\*|\$|\%[0-9]{2}|[0-9])""" # tokenization regex (Schwaller) molecule_regex = r"""(\[[^\]]+]|Br?|Cl?|N|O|S|P|F|I|b|c|n|o|s|p|\(|\)|\.|=|#|-|\+|\\|\/|:|~|@|\?|>>?|\*|\$|\%[0-9]{2}|[0-9])""" def get_protein_sequence_and_coords(structure): hv = structure.getHierView() seq = '' xyz = [] resindex = [] for chain in hv: cid = chain.getChid() calpha = structure.select(f'calpha chain {cid} icode _') N = structure.select(f'name N chain {cid} icode _') C = structure.select(f'name C chain {cid} icode _') xyz += [(ca,n,c) for ca,n,c in zip(calpha.getCoords(), N.getCoords(), C.getCoords())] seq += calpha.getSequence() resindex += [ca.getResindex() for ca in calpha] return seq, xyz, resindex def get_pdb_components(pdb_id): """ Split a protein-ligand pdb into protein and ligand components :param pdb_id: :return: """ with open(pdb_id,'r') as f: pdb = parsePDBStream(f,model=1) protein = pdb.select('protein') return protein def rot_from_two_vecs(e0_unnormalized, e1_unnormalized): """Create rotation matrices from unnormalized vectors for the x and y-axes. This creates a rotation matrix from two vectors using Gram-Schmidt orthogonalization. Args: e0_unnormalized: vectors lying along x-axis of resulting rotation e1_unnormalized: vectors lying in xy-plane of resulting rotation Returns: Rotations resulting from Gram-Schmidt procedure. """ # Normalize the unit vector for the x-axis, e0. e0 = e0_unnormalized / np.linalg.norm(e0_unnormalized) # make e1 perpendicular to e0. c = np.dot(e1_unnormalized, e0) e1 = e1_unnormalized - c * e0 e1 = e1 / np.linalg.norm(e1) # Compute e2 as cross product of e0 and e1. e2 = np.cross(e0, e1) # local to space frame return np.stack([e0,e1,e2]).T def parse_complex(aa, data_dir, i_pdb_fns): shard_idx, pdb_fns = i_pdb_fns chunk_name = [] chunk_smiles = [] chunk_lig_xyz = [] chunk_seq = [] chunk_rec_xyz = [] chunk_rec_R = [] chunk_rec_feat = [] for pdb_fn in pdb_fns: try: name = os.path.basename(pdb_fn) protein = get_pdb_components(pdb_fn+'/'+name+'_protein.pdb') seq, xyz, resindex = get_protein_sequence_and_coords(protein) if len(seq) < 3: raise ValueError assert len(xyz) == len(seq), "sequence and coord mismatch" R_receptor = [] for t in xyz: CA = np.array(t[0]) N = np.array(t[1]) C = np.array(t[2]) R_receptor.append(rot_from_two_vecs(N-CA,C-CA).flatten().tolist()) # atom features feat = np.zeros((len(resindex),nfeat,3),dtype=np.float32) feat[:] = np.nan for i,(n, res) in enumerate(zip(resindex, seq)): atoms = protein.select(f'resindex {n}') ss = io.StringIO() prody.writePDBStream(ss, atoms) try: mol = Chem.MolFromPDBBlock(ss.getvalue()) ref_aa = copy.deepcopy(aa[res]) reflabels = [l.split()[0] for l in ref_aa.reflabels] labels = [l.split()[0] for l in ref_aa.name(mol)] pos = mol.GetConformer().GetPositions() xyz_labels = sorted([(xyz, reflabels.index(l)) for xyz,l in zip(pos,labels) if l in reflabels], key=lambda t: t[1]) for r, j in xyz_labels: feat[i,j,:] = r except Exception as e: print('Unsuccesful in assigning atoms to amino acid letter {}'.format(res),ss.getvalue(),e) raise # parse ligand, convert to SMILES and map atoms suppl = Chem.SDMolSupplier(pdb_fn+'/'+name+'_ligand.sdf') mol = next(suppl) # position of atoms in SMILES (not counting punctuation) smi = Chem.MolToSmiles(mol) atom_order = [int(s) for s in list(filter(None,re.sub(r'[\[\]]','',mol.GetProp("_smilesAtomOutputOrder")).split(',')))] # tokenize the SMILES tokens = list(filter(None, re.split(molecule_regex, smi))) # remove punctuation masked_tokens = [re.sub(punctuation_regex,'',s) for s in tokens] k = 0 token_pos = [] for i,token in enumerate(masked_tokens): if token != '': token_pos.append(tuple(mol.GetConformer().GetAtomPosition(atom_order[k]))) k += 1 else: token_pos.append((np.nan, np.nan, np.nan)) chunk_name.append(name) chunk_seq.append(seq) chunk_rec_xyz.append(np.array([np.array(t[0]).tolist() for t in xyz])) chunk_rec_R.append(np.array(R_receptor)) chunk_rec_feat.append(feat) chunk_smiles.append(smi) chunk_lig_xyz.append(token_pos) except Exception as e: print(e) pass try: shard_idx = str(shard_idx) with wd.TarWriter(f'{data_dir}/part-' + shard_idx + '.tar', compress=True) as sink: for index in range(len(chunk_name)): sink.write({ '__key__': "%s_%06d" % (shard_idx, index), 'name.txt': chunk_name[index], 'seq.txt': chunk_seq[index], 'smiles.txt': chunk_smiles[index], 'rec_xyz.pyd': chunk_rec_xyz[index], 'rec_R.pyd': chunk_rec_R[index], 'rec_feat.pyd': chunk_rec_feat[index], 'lig_xyz.pyd': chunk_lig_xyz[index], }) return len(chunk_name) except Exception as e: print('Exception while writing', repr(e)) if __name__ == '__main__': import glob filenames = glob.glob('data/pdbbind/v2020-other-PL/*') filenames.extend(glob.glob('data/pdbbind/refined-set/*')) filenames = sorted(filenames) with open('split_direction/timesplit_no_lig_overlap_train','r') as f: train_rec = f.read().split() with open('split_direction/timesplit_no_lig_overlap_val','r') as f: val_rec = f.read().split() with open('split_direction/timesplit_test','r') as f: test_rec = f.read().split() train = [x for x in filenames if x.split('/')[-1] in train_rec] val = [x for x in filenames if x.split('/')[-1] in val_rec] test = [x for x in filenames if x.split('/')[-1] in test_rec] print(f'Train has {len(train)} items and first 5 are {train[:5]}') print(f'Val has {len(val)} items and first 5 are {val[:5]}') print(f'Test has {len(test)} items and first 5 are {test[:5]}') def chunks(lst, n): """Yield successive n-sized chunks from lst.""" for i in range(0, len(lst), n): yield lst[i:i + n] comm = MPI.COMM_WORLD with MPICommExecutor(comm, root=0) as executor: if executor is not None: aa = {k: AtomicNamer(v) for k,v in amino_acids.items()} chunk_sizes = executor.map(partial(parse_complex, aa, 'train'), enumerate(chunks(train, 512))) total_train_rows = 0 for s in chunk_sizes: total_train_rows += s chunk_sizes = executor.map(partial(parse_complex, aa, 'val'), enumerate(chunks(val, 512))) total_val_rows = 0 for s in chunk_sizes: total_val_rows += s chunk_sizes = executor.map(partial(parse_complex, aa, 'test'), enumerate(chunks(test, 512))) total_test_rows = 0 for s in chunk_sizes: total_test_rows += s print('Total number of train rows {}'.format(total_train_rows)) print('Total number of val rows {}'.format(total_val_rows)) print('Total number of test rows {}'.format(total_test_rows))