-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathprd_reader.py
More file actions
275 lines (226 loc) · 8.77 KB
/
Copy pathprd_reader.py
File metadata and controls
275 lines (226 loc) · 8.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
#!/usr/bin/env python
# software from PDBe: Protein Data Bank in Europe; https://pdbe.org
#
# Copyright 2018 EMBL - European Bioinformatics Institute
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on
# an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import logging
import os
from typing import Collection, Dict, Optional
import rdkit
from pdbeccdutils.core.component import Component
from pdbeccdutils.core import ccd_reader
from pdbeccdutils.core.exceptions import CCDUtilsError
from pdbeccdutils.core.models import (
CCDProperties,
ReleaseStatus,
)
from pdbeccdutils.helpers import cif_tools, conversions, mol_tools
from gemmi import cif
# categories that need to be 'fixed'
# str => list[str]
preprocessable_categories = [
"_chem_comp_atom.",
"_chem_comp_bond.",
"_pdbx_chem_comp_identifier.",
"_pdbx_chem_comp_descriptor.",
"_chem_comp.",
]
def read_pdb_cif_file(
path_to_cif: str, sanitize: bool = True
) -> ccd_reader.CCDReaderResult:
"""
Read in single wwPDB CCD CIF component and create its internal
representation.
Args:
path_to_cif (str): Path to the cif file
sanitize (bool): [Defaults: True]
Raises:
ValueError: if file does not exist
Returns:
CCDReaderResult: Results of the parsing altogether with
the internal representation of the component.
"""
if not os.path.isfile(path_to_cif):
raise ValueError("File '{}' does not exists".format(path_to_cif))
doc = cif.read(path_to_cif)
cif_block = doc.sole_block()
return _parse_pdb_mmcif(cif_block, sanitize)
def read_pdb_components_file(
path_to_cif: str, sanitize: bool = True, include: Optional[Collection[str]] = None
) -> Dict[str, ccd_reader.CCDReaderResult]:
"""
Process multiple compounds stored in the wwPDB PRD
`prdcc-all.cif` file.
Args:
path_to_cif (str): Path to the `prdcc-all.cif` file with
multiple ligands in it.
sanitize (bool): Whether or not the components should be sanitized
Defaults to True.
include (Optional[Collection[str]]): List of PRDs to be parsed. By default it
is None and parses all the PRDs. If a collection of PRDs is provided, only
those PRDs are parsed. Empty collections parse all PRDs, matching the
previous behavior.
Raises:
ValueError: if the file does not exist.
Returns:
dict[str, CCDReaderResult]: Internal representation of all
the components in the `prdcc-all.cif` file.
"""
if not os.path.isfile(path_to_cif):
raise ValueError("File '{}' does not exists".format(path_to_cif))
result_bag = {}
doc = cif.read(path_to_cif)
if not include:
blocks = doc
else:
blocks = []
for block_name in dict.fromkeys(include):
block = doc.find_block(block_name)
if block is None:
logging.warning(f"Data block {block_name} not found in {path_to_cif}.")
continue
blocks.append(block)
for block in blocks:
try:
result_bag[block.name] = _parse_pdb_mmcif(block, sanitize)
except CCDUtilsError as e:
logging.error(
f"ERROR: Data block {block.name} not processed. Reason: ({str(e)})."
)
return result_bag
# region parse mmcif
def _parse_pdb_mmcif(cif_block, sanitize=True):
"""
Create internal representation of the molecule from mmcif format.
Args:
cif_block (cif.Block): mmcif block object from gemmi
sanitize (bool): Whether or not the rdkit component should
be sanitized. Defaults to True.
Returns:
CCDReaderResult: internal representation with the results
of parsing and Mol object.
"""
warnings = []
errors = []
sanitized = False
mol = rdkit.Chem.RWMol()
for c in preprocessable_categories:
w = cif_tools.preprocess_cif_category(cif_block, c)
if w:
warnings.append(w)
_parse_pdb_atoms(mol, cif_block)
ccd_reader._parse_pdb_conformers(mol, cif_block)
ccd_reader._parse_pdb_bonds(mol, cif_block, errors)
ccd_reader._handle_implicit_hydrogens(mol)
if sanitize:
sanitized_result = mol_tools.sanitize(mol)
mol, sanitized = sanitized_result.mol, sanitized_result.status
descriptors = ccd_reader._parse_pdb_descriptors(
cif_block, "_pdbx_chem_comp_descriptor.", "descriptor"
)
descriptors += ccd_reader._parse_pdb_descriptors(
cif_block, "_pdbx_chem_comp_identifier.", "identifier"
)
properties = _parse_pdb_properties(cif_block)
comp = Component(mol.GetMol(), cif_block, properties, descriptors)
reader_result = ccd_reader.CCDReaderResult(
warnings=warnings, errors=errors, component=comp, sanitized=sanitized
)
return reader_result
def _parse_pdb_atoms(mol, cif_block):
"""
Setup atoms in the component
Args:
mol (rdkit.Chem.rdchem.Mol): Rdkit Mol object with the
compound representation.
cif_block (cif.Block): mmCIF block object from gemmi.
"""
if "_chem_comp_atom." not in cif_block.get_mmcif_category_names():
return
atoms = cif_block.find(
"_chem_comp_atom.",
[
"atom_id",
"type_symbol",
"alt_atom_id",
"pdbx_leaving_atom_flag",
"charge",
"pdbx_component_comp_id",
"pdbx_residue_numbering",
"pdbx_component_atom_id",
"pdbx_polymer_type",
"pdbx_ref_id",
"pdbx_component_id",
],
)
for row in atoms:
atom_id = cif.as_string(row["_chem_comp_atom.atom_id"])
element = cif.as_string(row["_chem_comp_atom.type_symbol"])
alt_atom_id = cif.as_string(row["_chem_comp_atom.alt_atom_id"])
leaving_atom = cif.as_string(row["_chem_comp_atom.pdbx_leaving_atom_flag"])
charge = cif.as_string(row["_chem_comp_atom.charge"])
comp_atom_id = cif.as_string(row["_chem_comp_atom.pdbx_component_atom_id"])
res_name = cif.as_string(row["_chem_comp_atom.pdbx_component_comp_id"])
residue_id = cif.as_string(row["_chem_comp_atom.pdbx_residue_numbering"])
res_type = cif.as_string(row["_chem_comp_atom.pdbx_polymer_type"])
ref_id = cif.as_string(row["_chem_comp_atom.pdbx_ref_id"])
comp_id = cif.as_string(row["_chem_comp_atom.pdbx_component_id"])
element = element if len(element) == 1 else element[0] + element[1].lower()
isotope = None
if element == "D":
element = "H"
isotope = 2
elif element == "X":
element = "*"
atom = rdkit.Chem.Atom(element)
atom.SetProp("name", atom_id)
atom.SetProp("alt_name", alt_atom_id)
atom.SetBoolProp("leaving_atom", leaving_atom == "Y")
atom.SetProp("component_atom_id", comp_atom_id)
atom.SetProp("ref_id", ref_id)
atom.SetProp("comp_id", comp_id)
atom.SetProp("res_type", res_type)
atom.SetProp("residue_id", residue_id)
atom.SetFormalCharge(conversions.str_to_int(charge))
res_info = rdkit.Chem.AtomPDBResidueInfo()
res_info.SetResidueName(res_name)
res_info.SetIsHeteroAtom(True)
atom.SetMonomerInfo(res_info)
if isotope is not None:
atom.SetIsotope(isotope)
mol.AddAtom(atom)
def _parse_pdb_properties(cif_block):
"""Parse useful information from _chem_comp category
Args:
cif_block (cif.Block): mmcif block object from gemmi
Returns:
Properties: dataclass with the CCD properties.
"""
properties = None
if "_chem_comp." in cif_block.get_mmcif_category_names():
rel_status = ReleaseStatus.from_str(
cif_block.find_value("_chem_comp.pdbx_release_status")
)
formula_weight = cif_block.find_value("_chem_comp.formula_weight")
weight = 0.0 if cif.is_null(formula_weight) else cif.as_number(formula_weight)
properties = CCDProperties(
id=cif.as_string(cif_block.find_value("_chem_comp.id")),
name=cif.as_string(cif_block.find_value("_chem_comp.name")),
formula=cif.as_string(cif_block.find_value("_chem_comp.formula")),
modified_date="",
pdbx_release_status=rel_status,
weight=weight,
)
return properties
# endregion parse mmcif