#!/usr/bin/env python # Split a protein-ligand complex into protein and ligands and assign ligand bond orders using SMILES strings from Ligand Export # Code requires Python 3.6 import sys from prody import * import pandas as pd from rdkit import Chem from rdkit.Chem import AllChem from io import StringIO import requests from mpi4py import MPI from mpi4py.futures import MPICommExecutor from mpi4py.futures import MPIPoolExecutor import re from functools import partial import gzip from rdkit.Chem.Descriptors import ExactMolWt import numpy as np import os # minimum molecular weight to consider sth a ligand mol_wt_cutoff = 100 # 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])""" max_seq = 2046 # = 2048 - 2 (accounting for [CLS] and [SEP]) max_smiles = 510 # = 512 - 2 def get_protein_sequence_and_coords(receptor): calpha = receptor.select('calpha') xyz = calpha.getCoords() seq = calpha.getSequence() return seq, xyz.tolist() def tokenize_ligand(mol): # convert to SMILES and map atoms smi = Chem.MolToSmiles(mol) # position of atoms in SMILES (not counting punctuation) 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)) return smi, token_pos def read_ligand_expo(): """ Read Ligand Expo data, try to find a file called Components-smiles-stereo-oe.smi in the current directory. If you can't find the file, grab it from the RCSB :return: Ligand Expo as a dictionary with ligand id as the key """ file_name = "Components-smiles-stereo-oe.smi" try: df = pd.read_csv(file_name, sep="\t", header=None, names=["SMILES", "ID", "Name"]) except FileNotFoundError: url = f"http://ligand-expo.rcsb.org/dictionaries/{file_name}" print(url) r = requests.get(url, allow_redirects=True) open('Components-smiles-stereo-oe.smi', 'wb').write(r.content) df = pd.read_csv(file_name, sep="\t", header=None, names=["SMILES", "ID", "Name"]) df.set_index("ID", inplace=True) return df.to_dict() def get_pdb_components(pdb_id): """ Split a protein-ligand pdb into protein and ligand components :param pdb_id: :return: """ with gzip.open(pdb_id,'rt') as f: pdb = parsePDBStream(f) protein = pdb.select('protein') ligand = pdb.select('not protein and not water') return protein, ligand def process_ligand(ligand, res_name, expo_dict): """ Add bond orders to a pdb ligand 1. Select the ligand component with name "res_name" 2. Get the corresponding SMILES from the Ligand Expo dictionary 3. Create a template molecule from the SMILES in step 2 4. Write the PDB file to a stream 5. Read the stream into an RDKit molecule 6. Assign the bond orders from the template from step 3 :param ligand: ligand as generated by prody :param res_name: residue name of ligand to extract :param expo_dict: dictionary with LigandExpo :return: molecule with bond orders assigned """ output = StringIO() sub_mol = ligand.select(f"resname {res_name}") sub_smiles = expo_dict['SMILES'][res_name] template = AllChem.MolFromSmiles(sub_smiles) writePDBStream(output, sub_mol) pdb_string = output.getvalue() rd_mol = AllChem.MolFromPDBBlock(pdb_string) new_mol = AllChem.AssignBondOrdersFromTemplate(template, rd_mol) return new_mol, template def process_entry(df_dict, pdb_fn): try: """ Slit pdb into protein and ligands, parse protein sequence and ligand tokens :param df_dict: ligand expo data :param pdb_fn: pdb entry file name :return: """ protein, ligand = get_pdb_components(pdb_fn) ligand_mols = [] ligand_names = [] if ligand is not None: # filter ligands by molecular weight res_name_list = list(set(ligand.getResnames())) for res in res_name_list: mol, template = process_ligand(ligand, res, df_dict) mol_wt = ExactMolWt(template) if mol_wt >= mol_wt_cutoff: ligand_mols.append(mol) ligand_names.append(res) ligand_smiles = [] ligand_xyz = [] pdb_name = os.path.basename(pdb_fn).split('.')[-3][3:] for mol, name in zip(ligand_mols, ligand_names): print('Processing {} and {}'.format(pdb_name, name)) smi, xyz = tokenize_ligand(mol) ligand_smiles.append(smi) ligand_xyz.append(xyz) seq, receptor_xyz = get_protein_sequence_and_coords(protein) return pdb_name, seq, receptor_xyz, ligand_names, ligand_smiles, ligand_xyz except Exception as e: print(repr(e)) if __name__ == '__main__': import glob filenames = glob.glob('pdb/*/*.gz') filenames = sorted(filenames) comm = MPI.COMM_WORLD with MPICommExecutor(comm, root=0) as executor: # with MPIPoolExecutor() as executor: if executor is not None: # read ligand table df_dict = read_ligand_expo() result = executor.map(partial(process_entry, df_dict), filenames, chunksize=512) result = list(result) # expand sequences and ligands pdb_id = [r[0] for r in result if r is not None for ligand in r[3]] seq = [r[1] for r in result if r is not None for ligand in r[3]] receptor_xyz = [r[2] for r in result if r is not None for ligand in r[3]] lig_id = [l for r in result if r is not None for l in r[3]] lig_smiles = [s for r in result if r is not None for s in r[4]] lig_xyz = [xyz for r in result if r is not None for xyz in r[5]] import pandas as pd df = pd.DataFrame({'pdb_id': pdb_id, 'lig_id': lig_id, 'seq': seq, 'smiles': lig_smiles, 'receptor_xyz': receptor_xyz, 'ligand_xyz': lig_xyz}) df.to_parquet('data/pdb.parquet',index=False)