jglaser commited on
Commit
1d7245f
0 Parent(s):

initial commit

Browse files
.gitattributes ADDED
@@ -0,0 +1 @@
 
 
1
+ data/pdb.parquet filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1 @@
 
 
1
+ slurm-*
README.md ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## How to use the data sets
2
+
3
+ This dataset contains more about 80,000 unique pairs of protein sequences and ligand SMILES, and the coordinates
4
+ of their complexes from the PDB. Only ligands with a molecular weight >= 100 Da are included.
5
+
6
+ SMILES are assumed to be tokenized by the regex from P. Schwaller.
7
+
8
+ Every (x,y,z) ligand coordinate maps onto a SMILES token, and is *nan* if the token does not represent an atom
9
+
10
+ Every receptor coordinate maps onto the Calpha coordinate of that residue.
11
+
12
+ The dataset can be used to fine-tune a language model, all data comes from PDBind-cn.
13
+
14
+ ### Use the already preprocessed data
15
+
16
+ Load a test/train split using
17
+
18
+ ```
19
+ from datasets import load_dataset
20
+ train = load_dataset("jglaser/pdb_protein_ligand_complexes",split='train[:90%]')
21
+ validation = load_dataset("jglaser/pdb_protein_ligand_complexes",split='train[90%:]')
22
+ ```
23
+
24
+ ### Manual update from PDB
25
+
26
+ ```
27
+ # download the PDB archive into folder pdb/
28
+ sh rsync.sh 24 # number of parallel download processes
29
+
30
+ # extract sequences and coordinates in parallel
31
+ sbatch pdb.slurm
32
+ # or
33
+ mpirun -n 42 parse_complexes.py # desired number of tasks
34
+ ```
batch_download.sh ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ # Script to download files from RCSB http file download services.
4
+ # Use the -h switch to get help on usage.
5
+
6
+ if ! command -v curl &> /dev/null
7
+ then
8
+ echo "'curl' could not be found. You need to install 'curl' for this script to work."
9
+ exit 1
10
+ fi
11
+
12
+ PROGNAME=$0
13
+ BASE_URL="https://files.rcsb.org/download"
14
+
15
+ usage() {
16
+ cat << EOF >&2
17
+ Usage: $PROGNAME -f <file> [-o <dir>] [-c] [-p]
18
+
19
+ -f <file>: the input file containing a comma-separated list of PDB ids
20
+ -o <dir>: the output dir, default: current dir
21
+ -c : download a cif.gz file for each PDB id
22
+ -p : download a pdb.gz file for each PDB id (not available for large structures)
23
+ -a : download a pdb1.gz file (1st bioassembly) for each PDB id (not available for large structures)
24
+ -x : download a xml.gz file for each PDB id
25
+ -s : download a sf.cif.gz file for each PDB id (diffraction only)
26
+ -m : download a mr.gz file for each PDB id (NMR only)
27
+ -r : download a mr.str.gz for each PDB id (NMR only)
28
+ EOF
29
+ exit 1
30
+ }
31
+
32
+ download() {
33
+ url="$BASE_URL/$1"
34
+ out=$2/$1
35
+ echo "Downloading $url to $out"
36
+ curl -s -f $url -o $out || echo "Failed to download $url"
37
+ }
38
+
39
+ listfile=""
40
+ outdir="."
41
+ cif=false
42
+ pdb=false
43
+ pdb1=false
44
+ xml=false
45
+ sf=false
46
+ mr=false
47
+ mrstr=false
48
+ while getopts f:o:cpaxsmr o
49
+ do
50
+ case $o in
51
+ (f) listfile=$OPTARG;;
52
+ (o) outdir=$OPTARG;;
53
+ (c) cif=true;;
54
+ (p) pdb=true;;
55
+ (a) pdb1=true;;
56
+ (x) xml=true;;
57
+ (s) sf=true;;
58
+ (m) mr=true;;
59
+ (r) mrstr=true;;
60
+ (*) usage
61
+ esac
62
+ done
63
+ shift "$((OPTIND - 1))"
64
+
65
+ if [ "$listfile" == "" ]
66
+ then
67
+ echo "Parameter -f must be provided"
68
+ exit 1
69
+ fi
70
+ contents=$(cat $listfile)
71
+
72
+ # see https://stackoverflow.com/questions/918886/how-do-i-split-a-string-on-a-delimiter-in-bash#tab-top
73
+ IFS=',' read -ra tokens <<< "$contents"
74
+
75
+ for token in "${tokens[@]}"
76
+ do
77
+ if [ "$cif" == true ]
78
+ then
79
+ download ${token}.cif.gz $outdir
80
+ fi
81
+ if [ "$pdb" == true ]
82
+ then
83
+ download ${token}.pdb.gz $outdir
84
+ fi
85
+ if [ "$pdb1" == true ]
86
+ then
87
+ download ${token}.pdb1.gz $outdir
88
+ fi
89
+ if [ "$xml" == true ]
90
+ then
91
+ download ${token}.xml.gz $outdir
92
+ fi
93
+ if [ "$sf" == true ]
94
+ then
95
+ download ${token}-sf.cif.gz $outdir
96
+ fi
97
+ if [ "$mr" == true ]
98
+ then
99
+ download ${token}.mr.gz $outdir
100
+ fi
101
+ if [ "$mrstr" == true ]
102
+ then
103
+ download ${token}_mr.str.gz $outdir
104
+ fi
105
+
106
+ done
107
+
108
+
109
+
110
+
111
+
112
+
113
+
114
+
data/pdb.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c503ec9218e87f192d710838a0123f01ac1e48b75b288f0adc229cb025d1b592
3
+ size 1005021071
get_pdb_ids.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from rcsbsearch import Terminal
2
+ from rcsbsearch import rcsb_attributes as attrs
3
+
4
+ # Create terminals for each query
5
+ q1 = attrs.rcsb_entry_info.nonpolymer_entity_count > 0
6
+ q2 = attrs.rcsb_entry_info.polymer_entity_count_protein > 0
7
+ q3 = Terminal('chem_comp.formula_weight','greater_or_equal',150,service='text_chem')
8
+
9
+ # combined using bitwise operators (&, |, ~, etc)
10
+ query = q1 & q2 & q3 # AND of all queries
11
+
12
+ # Call the query to execute it
13
+ for assemblyid in query("entry"):
14
+ print(assemblyid)
parse_complexes.py ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ # Split a protein-ligand complex into protein and ligands and assign ligand bond orders using SMILES strings from Ligand Export
4
+ # Code requires Python 3.6
5
+
6
+ import sys
7
+ from prody import *
8
+ import pandas as pd
9
+ from rdkit import Chem
10
+ from rdkit.Chem import AllChem
11
+ from io import StringIO
12
+ import requests
13
+
14
+ from mpi4py import MPI
15
+ from mpi4py.futures import MPICommExecutor
16
+ from mpi4py.futures import MPIPoolExecutor
17
+
18
+ import re
19
+ from functools import partial
20
+ import gzip
21
+ from rdkit.Chem.Descriptors import ExactMolWt
22
+ import numpy as np
23
+
24
+ import os
25
+
26
+ # minimum molecular weight to consider sth a ligand
27
+ mol_wt_cutoff = 100
28
+
29
+ # all punctuation
30
+ punctuation_regex = r"""(\(|\)|\.|=|#|-|\+|\\|\/|:|~|@|\?|>>?|\*|\$|\%[0-9]{2}|[0-9])"""
31
+
32
+ # tokenization regex (Schwaller)
33
+ molecule_regex = r"""(\[[^\]]+]|Br?|Cl?|N|O|S|P|F|I|b|c|n|o|s|p|\(|\)|\.|=|#|-|\+|\\|\/|:|~|@|\?|>>?|\*|\$|\%[0-9]{2}|[0-9])"""
34
+
35
+ max_seq = 2046 # = 2048 - 2 (accounting for [CLS] and [SEP])
36
+ max_smiles = 510 # = 512 - 2
37
+
38
+ def get_protein_sequence_and_coords(receptor):
39
+ calpha = receptor.select('calpha')
40
+ xyz = calpha.getCoords()
41
+ seq = calpha.getSequence()
42
+ return seq, xyz.tolist()
43
+
44
+ def tokenize_ligand(mol):
45
+ # convert to SMILES and map atoms
46
+ smi = Chem.MolToSmiles(mol)
47
+
48
+ # position of atoms in SMILES (not counting punctuation)
49
+ atom_order = [int(s) for s in list(filter(None,re.sub(r'[\[\]]','',mol.GetProp("_smilesAtomOutputOrder")).split(',')))]
50
+
51
+ # tokenize the SMILES
52
+ tokens = list(filter(None, re.split(molecule_regex, smi)))
53
+
54
+ # remove punctuation
55
+ masked_tokens = [re.sub(punctuation_regex,'',s) for s in tokens]
56
+
57
+ k = 0
58
+ token_pos = []
59
+ for i,token in enumerate(masked_tokens):
60
+ if token != '':
61
+ token_pos.append(tuple(mol.GetConformer().GetAtomPosition(atom_order[k])))
62
+ k += 1
63
+ else:
64
+ token_pos.append((np.nan, np.nan, np.nan))
65
+
66
+ return smi, token_pos
67
+
68
+ def read_ligand_expo():
69
+ """
70
+ Read Ligand Expo data, try to find a file called
71
+ Components-smiles-stereo-oe.smi in the current directory.
72
+ If you can't find the file, grab it from the RCSB
73
+ :return: Ligand Expo as a dictionary with ligand id as the key
74
+ """
75
+ file_name = "Components-smiles-stereo-oe.smi"
76
+ try:
77
+ df = pd.read_csv(file_name, sep="\t",
78
+ header=None,
79
+ names=["SMILES", "ID", "Name"])
80
+ except FileNotFoundError:
81
+ url = f"http://ligand-expo.rcsb.org/dictionaries/{file_name}"
82
+ print(url)
83
+ r = requests.get(url, allow_redirects=True)
84
+ open('Components-smiles-stereo-oe.smi', 'wb').write(r.content)
85
+ df = pd.read_csv(file_name, sep="\t",
86
+ header=None,
87
+ names=["SMILES", "ID", "Name"])
88
+ df.set_index("ID", inplace=True)
89
+ return df.to_dict()
90
+
91
+
92
+ def get_pdb_components(pdb_id):
93
+ """
94
+ Split a protein-ligand pdb into protein and ligand components
95
+ :param pdb_id:
96
+ :return:
97
+ """
98
+ with gzip.open(pdb_id,'rt') as f:
99
+ pdb = parsePDBStream(f)
100
+
101
+ protein = pdb.select('protein')
102
+ ligand = pdb.select('not protein and not water')
103
+ return protein, ligand
104
+
105
+
106
+ def process_ligand(ligand, res_name, expo_dict):
107
+ """
108
+ Add bond orders to a pdb ligand
109
+ 1. Select the ligand component with name "res_name"
110
+ 2. Get the corresponding SMILES from the Ligand Expo dictionary
111
+ 3. Create a template molecule from the SMILES in step 2
112
+ 4. Write the PDB file to a stream
113
+ 5. Read the stream into an RDKit molecule
114
+ 6. Assign the bond orders from the template from step 3
115
+ :param ligand: ligand as generated by prody
116
+ :param res_name: residue name of ligand to extract
117
+ :param expo_dict: dictionary with LigandExpo
118
+ :return: molecule with bond orders assigned
119
+ """
120
+ output = StringIO()
121
+ sub_mol = ligand.select(f"resname {res_name}")
122
+ sub_smiles = expo_dict['SMILES'][res_name]
123
+ template = AllChem.MolFromSmiles(sub_smiles)
124
+ writePDBStream(output, sub_mol)
125
+ pdb_string = output.getvalue()
126
+ rd_mol = AllChem.MolFromPDBBlock(pdb_string)
127
+ new_mol = AllChem.AssignBondOrdersFromTemplate(template, rd_mol)
128
+ return new_mol, template
129
+
130
+ def process_entry(df_dict, pdb_fn):
131
+ try:
132
+ """
133
+ Slit pdb into protein and ligands,
134
+ parse protein sequence and ligand tokens
135
+ :param df_dict: ligand expo data
136
+ :param pdb_fn: pdb entry file name
137
+ :return:
138
+ """
139
+ protein, ligand = get_pdb_components(pdb_fn)
140
+
141
+ ligand_mols = []
142
+ ligand_names = []
143
+
144
+ if ligand is not None:
145
+ # filter ligands by molecular weight
146
+ res_name_list = list(set(ligand.getResnames()))
147
+ for res in res_name_list:
148
+ mol, template = process_ligand(ligand, res, df_dict)
149
+
150
+ mol_wt = ExactMolWt(template)
151
+
152
+ if mol_wt >= mol_wt_cutoff:
153
+ ligand_mols.append(mol)
154
+ ligand_names.append(res)
155
+
156
+ ligand_smiles = []
157
+ ligand_xyz = []
158
+
159
+ pdb_name = os.path.basename(pdb_fn).split('.')[-3][3:]
160
+ for mol, name in zip(ligand_mols, ligand_names):
161
+ print('Processing {} and {}'.format(pdb_name, name))
162
+ smi, xyz = tokenize_ligand(mol)
163
+ ligand_smiles.append(smi)
164
+ ligand_xyz.append(xyz)
165
+
166
+ seq, receptor_xyz = get_protein_sequence_and_coords(protein)
167
+ return pdb_name, seq, receptor_xyz, ligand_names, ligand_smiles, ligand_xyz
168
+ except Exception as e:
169
+ print(repr(e))
170
+
171
+ if __name__ == '__main__':
172
+ import glob
173
+
174
+ filenames = glob.glob('pdb/*/*.gz')
175
+ filenames = sorted(filenames)
176
+ comm = MPI.COMM_WORLD
177
+ with MPICommExecutor(comm, root=0) as executor:
178
+ # with MPIPoolExecutor() as executor:
179
+ if executor is not None:
180
+ # read ligand table
181
+ df_dict = read_ligand_expo()
182
+
183
+ result = executor.map(partial(process_entry, df_dict), filenames, chunksize=512)
184
+ result = list(result)
185
+
186
+ # expand sequences and ligands
187
+ pdb_id = [r[0] for r in result if r is not None for ligand in r[3]]
188
+ seq = [r[1] for r in result if r is not None for ligand in r[3]]
189
+ receptor_xyz = [r[2] for r in result if r is not None for ligand in r[3]]
190
+ lig_id = [l for r in result if r is not None for l in r[3]]
191
+ lig_smiles = [s for r in result if r is not None for s in r[4]]
192
+ lig_xyz = [xyz for r in result if r is not None for xyz in r[5]]
193
+
194
+ import pandas as pd
195
+ df = pd.DataFrame({'pdb_id': pdb_id, 'lig_id': lig_id, 'seq': seq, 'smiles': lig_smiles, 'receptor_xyz': receptor_xyz, 'ligand_xyz': lig_xyz})
196
+ df.to_parquet('data/pdb.parquet',index=False)
pdb.slurm ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ #SBATCH -J preprocess
3
+ #SBATCH -p batch
4
+ #SBATCH -A STF006
5
+ #SBATCH -t 3:00:00
6
+ #SBATCH -N 36
7
+ #SBATCH --ntasks-per-node=16
8
+
9
+ export PYTHONUNBUFFERED=1
10
+ srun python parse_complexes.py
pdb_protein_ligand_complexes.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2020 The HuggingFace Datasets Authors and the current dataset script contributor.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """TODO: A dataset of protein sequences, ligand SMILES, and complex coordinates."""
16
+
17
+ import huggingface_hub
18
+ import os
19
+ import pyarrow.parquet as pq
20
+ import datasets
21
+
22
+
23
+ # TODO: Add BibTeX citation
24
+ # Find for instance the citation on arxiv or on the dataset repo/website
25
+ _CITATION = """\
26
+ @InProceedings{huggingface:dataset,
27
+ title = {jglaser/pdb_protein_ligand_complexes},
28
+ author={Jens Glaser, ORNL
29
+ },
30
+ year={2022}
31
+ }
32
+ """
33
+
34
+ # TODO: Add description of the dataset here
35
+ # You can copy an official description
36
+ _DESCRIPTION = """\
37
+ A dataset to fine-tune language models on protein-ligand complex structures
38
+ """
39
+
40
+ # TODO: Add a link to an official homepage for the dataset here
41
+ _HOMEPAGE = ""
42
+
43
+ # TODO: Add the licence for the dataset here if you can find it
44
+ _LICENSE = "BSD two-clause"
45
+
46
+ # TODO: Add link to the official dataset URLs here
47
+ # The HuggingFace dataset library don't host the datasets but only point to the original files
48
+ # This can be an arbitrary nested dict/list of URLs (see below in `_split_generators` method)
49
+ _URL = "https://huggingface.co/datasets/jglaser/pdb_protein_ligand_complexes/resolve/main/"
50
+ _data_dir = "data/"
51
+ _file_names = {'default': _data_dir+'pdb.parquet'}
52
+
53
+ _URLs = {name: _URL+_file_names[name] for name in _file_names}
54
+
55
+
56
+ # TODO: Name of the dataset usually match the script name with CamelCase instead of snake_case
57
+ class ProteinLigandContacts(datasets.ArrowBasedBuilder):
58
+ """List of protein sequences, ligand SMILES, and complex contacts."""
59
+
60
+ VERSION = datasets.Version("1.0.0")
61
+
62
+ def _info(self):
63
+ # TODO: This method specifies the datasets.DatasetInfo object which contains informations and typings for the dataset
64
+ #if self.config.name == "first_domain": # This is the name of the configuration selected in BUILDER_CONFIGS above
65
+ # features = datasets.Features(
66
+ # {
67
+ # "sentence": datasets.Value("string"),
68
+ # "option1": datasets.Value("string"),
69
+ # "answer": datasets.Value("string")
70
+ # # These are the features of your dataset like images, labels ...
71
+ # }
72
+ # )
73
+ #else: # This is an example to show how to have different features for "first_domain" and "second_domain"
74
+ features = datasets.Features(
75
+ {
76
+ "pdb_id": datasets.Value("string"),
77
+ "lig_id": datasets.Value("string"),
78
+ "seq": datasets.Value("string"),
79
+ "smiles": datasets.Value("string"),
80
+ "ligand_xyz": datasets.Sequence(datasets.Sequence(datasets.Value('float32'))),
81
+ "receptor_xyz": datasets.Sequence(datasets.Sequence(datasets.Value('float32'))),
82
+ # These are the features of your dataset like images, labels ...
83
+ }
84
+ )
85
+ return datasets.DatasetInfo(
86
+ # This is the description that will appear on the datasets page.
87
+ description=_DESCRIPTION,
88
+ # This defines the different columns of the dataset and their types
89
+ features=features, # Here we define them above because they are different between the two configurations
90
+ # If there's a common (input, target) tuple from the features,
91
+ # specify them here. They'll be used if as_supervised=True in
92
+ # builder.as_dataset.
93
+ supervised_keys=None,
94
+ # Homepage of the dataset for documentation
95
+ homepage=_HOMEPAGE,
96
+ # License for the dataset if available
97
+ license=_LICENSE,
98
+ # Citation for the dataset
99
+ citation=_CITATION,
100
+ )
101
+
102
+ def _split_generators(self, dl_manager):
103
+ """Returns SplitGenerators."""
104
+ # TODO: This method is tasked with downloading/extracting the data and defining the splits depending on the configuration
105
+ # If several configurations are possible (listed in BUILDER_CONFIGS), the configuration selected by the user is in self.config.name
106
+
107
+ # dl_manager is a datasets.download.DownloadManager that can be used to download and extract URLs
108
+ # It can accept any type or nested list/dict and will give back the same structure with the url replaced with path to local files.
109
+ # By default the archives will be extracted and a path to a cached folder where they are extracted is returned instead of the archive
110
+ files = dl_manager.download_and_extract(_URLs)
111
+
112
+ return [
113
+ datasets.SplitGenerator(
114
+ # These kwargs will be passed to _generate_examples
115
+ name=datasets.Split.TRAIN,
116
+ gen_kwargs={
117
+ 'filepath': files["default"],
118
+ },
119
+ ),
120
+
121
+ ]
122
+
123
+ def _generate_tables(
124
+ self, filepath
125
+ ):
126
+ from pyarrow import fs
127
+ local = fs.LocalFileSystem()
128
+
129
+ for i, f in enumerate([filepath]):
130
+ yield i, pq.read_table(f,filesystem=local)
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ prody
2
+ mpi4py
3
+ numpy
4
+ pandas
5
+ rdkit
rsync.sh ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/sh
2
+
3
+ NPROCS=$1
4
+ MIRRORDIR=pdb # your top level rsync directory
5
+ RSYNC=rsync # location of local rsync
6
+
7
+ SERVER=rsync.wwpdb.org::ftp # RCSB PDB server name
8
+ PORT=33444 # port RCSB PDB server is using
9
+
10
+ # get file list, remove first and last 3 lines from output (double-check that these lines are not needed)
11
+ ${RSYNC} -lpt -v -z --delete --port=$PORT --no-h --list-only ${SERVER}/data/structures/divided/pdb/ | cut -c 44- | head -n -3 | tail -n +3 > dirlist.txt
12
+
13
+ cat dirlist.txt | xargs -n1 -P${NPROCS} -I% rsync -rlpt -v -z --port=$PORT -P ${SERVER}/data/structures/divided/pdb/% $MIRRORDIR
14
+ rm dirlist.txt
split_complex.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ # Split a protein-ligand complex into protein and ligands and assign ligand bond orders using SMILES strings from Ligand Export
4
+ # Code requires Python 3.6
5
+
6
+ import sys
7
+ from prody import *
8
+ import pandas as pd
9
+ from rdkit import Chem
10
+ from rdkit.Chem import AllChem
11
+ from io import StringIO
12
+ import requests
13
+
14
+
15
+ def read_ligand_expo():
16
+ """
17
+ Read Ligand Expo data, try to find a file called
18
+ Components-smiles-stereo-oe.smi in the current directory.
19
+ If you can't find the file, grab it from the RCSB
20
+ :return: Ligand Expo as a dictionary with ligand id as the key
21
+ """
22
+ file_name = "Components-smiles-stereo-oe.smi"
23
+ try:
24
+ df = pd.read_csv(file_name, sep="\t",
25
+ header=None,
26
+ names=["SMILES", "ID", "Name"])
27
+ except FileNotFoundError:
28
+ url = f"http://ligand-expo.rcsb.org/dictionaries/{file_name}"
29
+ print(url)
30
+ r = requests.get(url, allow_redirects=True)
31
+ open('Components-smiles-stereo-oe.smi', 'wb').write(r.content)
32
+ df = pd.read_csv(file_name, sep="\t",
33
+ header=None,
34
+ names=["SMILES", "ID", "Name"])
35
+ df.set_index("ID", inplace=True)
36
+ return df.to_dict()
37
+
38
+
39
+ def get_pdb_components(pdb_id):
40
+ """
41
+ Split a protein-ligand pdb into protein and ligand components
42
+ :param pdb_id:
43
+ :return:
44
+ """
45
+ pdb = parsePDB(pdb_id)
46
+ protein = pdb.select('protein')
47
+ ligand = pdb.select('not protein and not water')
48
+ return protein, ligand
49
+
50
+
51
+ def process_ligand(ligand, res_name, expo_dict):
52
+ """
53
+ Add bond orders to a pdb ligand
54
+ 1. Select the ligand component with name "res_name"
55
+ 2. Get the corresponding SMILES from the Ligand Expo dictionary
56
+ 3. Create a template molecule from the SMILES in step 2
57
+ 4. Write the PDB file to a stream
58
+ 5. Read the stream into an RDKit molecule
59
+ 6. Assign the bond orders from the template from step 3
60
+ :param ligand: ligand as generated by prody
61
+ :param res_name: residue name of ligand to extract
62
+ :param expo_dict: dictionary with LigandExpo
63
+ :return: molecule with bond orders assigned
64
+ """
65
+ output = StringIO()
66
+ sub_mol = ligand.select(f"resname {res_name}")
67
+ sub_smiles = expo_dict['SMILES'][res_name]
68
+ template = AllChem.MolFromSmiles(sub_smiles)
69
+ writePDBStream(output, sub_mol)
70
+ pdb_string = output.getvalue()
71
+ rd_mol = AllChem.MolFromPDBBlock(pdb_string)
72
+ new_mol = AllChem.AssignBondOrdersFromTemplate(template, rd_mol)
73
+ return new_mol
74
+
75
+
76
+ def write_pdb(protein, pdb_name):
77
+ """
78
+ Write a prody protein to a pdb file
79
+ :param protein: protein object from prody
80
+ :param pdb_name: base name for the pdb file
81
+ :return: None
82
+ """
83
+ output_pdb_name = f"{pdb_name}_protein.pdb"
84
+ writePDB(f"{output_pdb_name}", protein)
85
+ print(f"wrote {output_pdb_name}")
86
+
87
+
88
+ def write_sdf(new_mol, pdb_name, res_name):
89
+ """
90
+ Write an RDKit molecule to an SD file
91
+ :param new_mol:
92
+ :param pdb_name:
93
+ :param res_name:
94
+ :return:
95
+ """
96
+ outfile_name = f"{pdb_name}_{res_name}_ligand.sdf"
97
+ writer = Chem.SDWriter(f"{outfile_name}")
98
+ writer.write(new_mol)
99
+ print(f"wrote {outfile_name}")
100
+
101
+
102
+ def main(pdb_name):
103
+ """
104
+ Read Ligand Expo data, split pdb into protein and ligands,
105
+ write protein pdb, write ligand sdf files
106
+ :param pdb_name: id from the pdb, doesn't need to have an extension
107
+ :return:
108
+ """
109
+ df_dict = read_ligand_expo()
110
+ protein, ligand = get_pdb_components(pdb_name)
111
+ write_pdb(protein, pdb_name)
112
+
113
+ res_name_list = list(set(ligand.getResnames()))
114
+ for res in res_name_list:
115
+ new_mol = process_ligand(ligand, res, df_dict)
116
+ write_sdf(new_mol, pdb_name, res)
117
+
118
+
119
+ if __name__ == "__main__":
120
+ if len(sys.argv) == 2:
121
+ main(sys.argv[1])
122
+ else:
123
+ print("Usage: {sys.argv[1]} pdb_id", file=sys.stderr)