pdb_protein_ligand_complexes / parse_complexes.py
jglaser's picture
use openfold features
28974f4
#!/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
import random
import traceback
from openfold import data_transforms, protein
from openfold.residue_constants import aatype_to_str_sequence
import torch
# minimum molecular weight to consider sth a ligand
mol_wt_cutoff = 100
# minimum number of atoms
min_atoms = 3
# 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])"""
# filter out these common additives which occur in more than 75 complexes in the PDB
ubiquitous_ligands = ['PEG', 'ADP', 'FAD', 'NAD', 'ATP', 'MPD', 'NAP', 'GDP', 'MES',
'GTP', 'FMN', 'HEC', 'TRS', 'CIT', 'PGE', 'ANP', 'SAH', 'NDP',
'PG4', 'EPE', 'AMP', 'COA', 'MLI', 'FES', 'GNP', 'MRD', 'GSH',
'FLC', 'AGS', 'NAI', 'SAM', 'PCW', '1PE', 'TLA', 'BOG', 'CYC',
'UDP', 'PX4', 'NAG', 'IMP', 'POP', 'UMP', 'PLM', 'HEZ', 'TPP',
'ACP', 'LDA', 'ACO', 'CLR', 'BGC', 'P6G', 'LMT', 'OGA', 'DTT',
'POV', 'FBP', 'AKG', 'MLA', 'ADN', 'NHE', '7Q9', 'CMP', 'BTB',
'PLP', 'CAC', 'SIN', 'C2E', '2AN', 'OCT', '17F', 'TAR', 'BTN',
'XYP', 'MAN', '5GP', 'GAL', 'GLC', 'DTP', 'DGT', 'PEB', 'THP',
'BEZ', 'CTP', 'GSP', 'HED', 'ADE', 'TYD', 'TTP', 'BNG', 'IHP',
'FDA', 'PEP', 'ALF', 'APR', 'MTX', 'MLT', 'LU8', 'UTP', 'APC',
'BLA', 'C8E', 'D10', 'CHT', 'BO2', '3BV', 'ORO', 'MPO', 'Y01',
'OLC', 'B3P', 'G6P', 'PMP', 'D12', 'NDG', 'A3P', '78M', 'F6P',
'U5P', 'PRP', 'UPG', 'THM', 'SFG', 'MYR', 'FEO', 'PG0', 'CXS',
'AR6', 'CHD', 'WO4', 'C5P', 'UFP', 'GCP', 'HDD', 'SRT', 'STU',
'CDP', 'TCL', '04C', 'MYA', 'URA', 'PLG', 'MTA', 'BMP', 'SAL',
'TA1', 'UD1', 'OLA', 'BCN', 'LMR', 'BMA', 'OAA', 'TAM', 'MBO',
'MMA', 'SPD', 'MTE', 'AP5', 'TMP', 'PGA', 'GLA', '3PG', 'FUL',
'PQQ', '9TY', 'DUR', 'PPV', 'SPM', 'SIA', 'DUP', 'GTX', '1PG',
'GUN', 'ETF', 'FDP', 'MFU', 'G2P', 'PC', 'DST', 'INI']
def get_protein_sequence_and_coords(receptor, pdb_str):
chains = [chain.getChid() for chain in receptor.getHierView()]
aatype = []
atom_positions = []
atom_mask = []
for chain in chains:
p = protein.from_pdb_string(pdb_str, chain)
aatype.append(p.aatype)
atom_positions.append(p.atom_positions)
atom_mask.append(p.atom_mask)
# concatenate chains
aatype = np.concatenate(aatype)
atom_positions = np.concatenate(atom_positions)
atom_mask = np.concatenate(atom_mask)
# determine torsion angles
features = {'aatype': torch.tensor(aatype),
'all_atom_positions': torch.tensor(atom_positions),
'all_atom_mask': torch.tensor(atom_mask)}
features = data_transforms.atom37_to_torsion_angles()(features)
features = data_transforms.atom37_to_frames(features)
features = data_transforms.make_atom14_masks(features)
features = data_transforms.make_atom14_positions(features)
features = {k: v.numpy() for k, v in features.items() if isinstance(v, torch.Tensor)}
seq = aatype_to_str_sequence(aatype)
return seq, features
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))
k = 0
conf_2d = AllChem.Compute2DCoords(mol)
token_pos_2d = []
atom_idx = []
for i,token in enumerate(masked_tokens):
if token != '':
token_pos_2d.append(tuple(mol.GetConformer(conf_2d).GetAtomPosition(atom_order[k])))
atom_idx.append(atom_order[k])
k += 1
else:
token_pos_2d.append((0.,0.,0.))
atom_idx.append(None)
return smi, token_pos, token_pos_2d, atom_idx
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=r"[\t]+",
header=None,
names=["SMILES", "ID", "Name"],
engine='python')
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"],
na_filter=False)
return df
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, df_expo):
"""
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 df_expo: dictionary with LigandExpo
:return: molecule with bond orders assigned
"""
sub_smiles = df_expo[df_expo['ID'].values == res_name]['SMILES'].values[0]
template = AllChem.MolFromSmiles(sub_smiles)
allres = ligand.select(f"resname {res_name}")
res = np.unique(allres.getResindices())
mols = []
for i in res:
sub_mol = ligand.select(f"resname {res_name} and resindex {i}")
output = StringIO()
writePDBStream(output, sub_mol)
pdb_string = output.getvalue()
rd_mol = AllChem.MolFromPDBBlock(pdb_string)
mols.append(AllChem.AssignBondOrdersFromTemplate(template, rd_mol))
return mols, template
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 process_entry(df, pdb_fn):
try:
"""
Slit pdb into protein and ligands,
parse protein sequence and ligand tokens
:param df: ligand expo data
:param pdb_fn: pdb entry file name
:return:
"""
protein, ligand = get_pdb_components(pdb_fn)
pdb_name = os.path.basename(pdb_fn).split('.')[-3][3:]
ligand_mols = []
ligand_names = []
ligand_bonds = []
if ligand is not None:
# filter ligands by molecular weight
res_name_list = list(set(ligand.getResnames()))
for res in res_name_list:
if res in ubiquitous_ligands:
continue
mols, template = process_ligand(ligand, res, df)
mol_wt = ExactMolWt(template)
natoms = template.GetNumAtoms()
if mol_wt >= mol_wt_cutoff and natoms >= min_atoms:
# only use first copy of ligand
mols = mols[:1]
ligand_mols += mols
ligand_names += [res]*len(mols)
bonds = []
for b in template.GetBonds():
bonds.append((b.GetBeginAtomIdx(), b.GetEndAtomIdx()))
ligand_bonds.append(bonds)
ligand_smiles = []
ligand_xyz = []
ligand_xyz_2d = []
ligand_token_bonds = []
for mol, name, bonds in zip(ligand_mols, ligand_names, ligand_bonds):
print('Processing {} and {}'.format(pdb_name, name))
smi, xyz, xyz_2d, atom_idx = tokenize_ligand(mol)
ligand_smiles.append(smi)
ligand_xyz.append(xyz)
ligand_xyz_2d.append(xyz_2d)
ligand_token_bonds.append([ (atom_idx.index(b[0]), atom_idx.index(b[1])) for b in bonds ])
pdb_str = StringIO()
writePDBStream(pdb_str, protein)
seq, features = get_protein_sequence_and_coords(protein, pdb_str.getvalue())
features = { 'rigidgroups_gt_frames': features['rigidgroups_gt_frames'],
'torsion_angles_sin_cos': features['torsion_angles_sin_cos']}
return pdb_name, seq, features, ligand_names, ligand_smiles, ligand_xyz, ligand_xyz_2d, ligand_token_bonds
except Exception as e:
print(traceback.format_exc())
print(repr(e))
def write_result(fn, data):
# expand sequences and ligands
pdb_id = [r[0] for r in data if r is not None for ligand in r[3]]
seq = [r[1] for r in data if r is not None for ligand in r[3]]
receptor_features = [r[2] for r in data if r is not None for ligand in r[3]]
lig_id = [l for r in data if r is not None for l in r[3]]
lig_smiles = [s for r in data if r is not None for s in r[4]]
lig_xyz = [xyz for r in data if r is not None for xyz in r[5]]
lig_xyz_2d = [xyz for r in data if r is not None for xyz in r[6]]
lig_bonds = [b for r in data if r is not None for b in r[7]]
import pandas as pd
df = pd.DataFrame({
'pdb_id': pdb_id,
'lig_id': lig_id,
'seq': seq,
'smiles': lig_smiles,
'receptor_features': receptor_features,
'ligand_xyz': lig_xyz,
'ligand_xyz_2d': lig_xyz_2d,
'ligand_bonds': lig_bonds})
df.to_pickle(fn)
if __name__ == '__main__':
import glob
filenames = glob.glob('pdb/*/*.gz')
filenames = sorted(filenames)
random.seed(42)
random.shuffle(filenames)
split_idx = int(0.9*len(filenames))
train = filenames[:split_idx]
test = filenames[split_idx:]
comm = MPI.COMM_WORLD
with MPICommExecutor(comm, root=0) as executor:
# with MPIPoolExecutor() as executor:
if executor is not None:
# read ligand table
df = read_ligand_expo()
result = executor.map(partial(process_entry, df), train, chunksize=128)
result = list(result)
write_result('data/pdb_train.p', result)
result = executor.map(partial(process_entry, df), test, chunksize=128)
result = list(result)
write_result('data/pdb_test.p', result)