mmcif.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. # Copyright 2021 DeepMind Technologies Limited
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """Parses the mmCIF file format."""
  15. import collections
  16. import dataclasses
  17. import functools
  18. import io
  19. from typing import Any, Mapping, Optional, Sequence, Tuple
  20. from absl import logging
  21. from Bio import PDB
  22. from Bio.Data import SCOPData
  23. from Bio.PDB.MMCIFParser import MMCIFParser
  24. # Type aliases:
  25. ChainId = str
  26. PdbHeader = Mapping[str, Any]
  27. PdbStructure = PDB.Structure.Structure
  28. SeqRes = str
  29. MmCIFDict = Mapping[str, Sequence[str]]
  30. @dataclasses.dataclass(frozen=True)
  31. class Monomer:
  32. id: str
  33. num: int
  34. # Note - mmCIF format provides no guarantees on the type of author-assigned
  35. # sequence numbers. They need not be integers.
  36. @dataclasses.dataclass(frozen=True)
  37. class AtomSite:
  38. residue_name: str
  39. author_chain_id: str
  40. mmcif_chain_id: str
  41. author_seq_num: str
  42. mmcif_seq_num: int
  43. insertion_code: str
  44. hetatm_atom: str
  45. model_num: int
  46. # Used to map SEQRES index to a residue in the structure.
  47. @dataclasses.dataclass(frozen=True)
  48. class ResiduePosition:
  49. chain_id: str
  50. residue_number: int
  51. insertion_code: str
  52. @dataclasses.dataclass(frozen=True)
  53. class ResidueAtPosition:
  54. position: Optional[ResiduePosition]
  55. name: str
  56. is_missing: bool
  57. hetflag: str
  58. @dataclasses.dataclass(frozen=True)
  59. class MmcifObject:
  60. """Representation of a parsed mmCIF file.
  61. Contains:
  62. file_id: A meaningful name, e.g. a pdb_id. Should be unique amongst all
  63. files being processed.
  64. header: Biopython header.
  65. structure: Biopython structure.
  66. chain_to_seqres: Dict mapping chain_id to 1 letter amino acid sequence. E.g.
  67. {'A': 'ABCDEFG'}
  68. seqres_to_structure: Dict; for each chain_id contains a mapping between
  69. SEQRES index and a ResidueAtPosition. e.g. {'A': {0: ResidueAtPosition, 1: ResidueAtPosition, ...}}
  70. raw_string: The raw string used to construct the MmcifObject.
  71. """
  72. file_id: str
  73. header: PdbHeader
  74. structure: PdbStructure
  75. chain_to_seqres: Mapping[ChainId, SeqRes]
  76. seqres_to_structure: Mapping[ChainId, Mapping[int, ResidueAtPosition]]
  77. raw_string: Any
  78. mmcif_to_author_chain_id: Mapping[ChainId, ChainId]
  79. valid_chains: Mapping[ChainId, str]
  80. @dataclasses.dataclass(frozen=True)
  81. class ParsingResult:
  82. """Returned by the parse function.
  83. Contains:
  84. mmcif_object: A MmcifObject, may be None if no chain could be successfully
  85. parsed.
  86. errors: A dict mapping (file_id, chain_id) to any exception generated.
  87. """
  88. mmcif_object: Optional[MmcifObject]
  89. errors: Mapping[Tuple[str, str], Any]
  90. class ParseError(Exception):
  91. """An error indicating that an mmCIF file could not be parsed."""
  92. def mmcif_loop_to_list(prefix: str,
  93. parsed_info: MmCIFDict) -> Sequence[Mapping[str, str]]:
  94. """Extracts loop associated with a prefix from mmCIF data as a list.
  95. Reference for loop_ in mmCIF:
  96. http://mmcif.wwpdb.org/docs/tutorials/mechanics/pdbx-mmcif-syntax.html
  97. Args:
  98. prefix: Prefix shared by each of the data items in the loop.
  99. e.g. '_entity_poly_seq.', where the data items are _entity_poly_seq.num,
  100. _entity_poly_seq.mon_id. Should include the trailing period.
  101. parsed_info: A dict of parsed mmCIF data, e.g. _mmcif_dict from a Biopython
  102. parser.
  103. Returns:
  104. Returns a list of dicts; each dict represents 1 entry from an mmCIF loop.
  105. """
  106. cols = []
  107. data = []
  108. for key, value in parsed_info.items():
  109. if key.startswith(prefix):
  110. cols.append(key)
  111. data.append(value)
  112. assert all([
  113. len(xs) == len(data[0]) for xs in data
  114. ]), ('mmCIF error: Not all loops are the same length: %s' % cols)
  115. return [dict(zip(cols, xs)) for xs in zip(*data)]
  116. def mmcif_loop_to_dict(
  117. prefix: str,
  118. index: str,
  119. parsed_info: MmCIFDict,
  120. ) -> Mapping[str, Mapping[str, str]]:
  121. """Extracts loop associated with a prefix from mmCIF data as a dictionary.
  122. Args:
  123. prefix: Prefix shared by each of the data items in the loop.
  124. e.g. '_entity_poly_seq.', where the data items are _entity_poly_seq.num,
  125. _entity_poly_seq.mon_id. Should include the trailing period.
  126. index: Which item of loop data should serve as the key.
  127. parsed_info: A dict of parsed mmCIF data, e.g. _mmcif_dict from a Biopython
  128. parser.
  129. Returns:
  130. Returns a dict of dicts; each dict represents 1 entry from an mmCIF loop,
  131. indexed by the index column.
  132. """
  133. entries = mmcif_loop_to_list(prefix, parsed_info)
  134. return {entry[index]: entry for entry in entries}
  135. @functools.lru_cache(16, typed=False)
  136. def fast_parse(*,
  137. file_id: str,
  138. mmcif_string: str,
  139. catch_all_errors: bool = True) -> ParsingResult:
  140. """Entry point, parses an mmcif_string.
  141. Args:
  142. file_id: A string identifier for this file. Should be unique within the
  143. collection of files being processed.
  144. mmcif_string: Contents of an mmCIF file.
  145. catch_all_errors: If True, all exceptions are caught and error messages are
  146. returned as part of the ParsingResult. If False exceptions will be allowed
  147. to propagate.
  148. Returns:
  149. A ParsingResult.
  150. """
  151. errors = {}
  152. try:
  153. parser = MMCIFParser(QUIET=True)
  154. # handle = io.StringIO(mmcif_string)
  155. # full_structure = parser.get_structure('', handle)
  156. parsed_info = parser._mmcif_dict # pylint:disable=protected-access
  157. # Ensure all values are lists, even if singletons.
  158. for key, value in parsed_info.items():
  159. if not isinstance(value, list):
  160. parsed_info[key] = [value]
  161. header = _get_header(parsed_info)
  162. # Determine the protein chains, and their start numbers according to the
  163. # internal mmCIF numbering scheme (likely but not guaranteed to be 1).
  164. valid_chains = _get_protein_chains(parsed_info=parsed_info)
  165. if not valid_chains:
  166. return ParsingResult(
  167. None, {(file_id, ''): 'No protein chains found in this file.'})
  168. mmcif_to_author_chain_id = {}
  169. # seq_to_structure_mappings = {}
  170. for atom in _get_atom_site_list(parsed_info):
  171. if atom.model_num != '1':
  172. # We only process the first model at the moment.
  173. continue
  174. mmcif_to_author_chain_id[
  175. atom.mmcif_chain_id] = atom.author_chain_id
  176. mmcif_object = MmcifObject(
  177. file_id=file_id,
  178. header=header,
  179. structure=None,
  180. chain_to_seqres=None,
  181. seqres_to_structure=None,
  182. raw_string=parsed_info,
  183. mmcif_to_author_chain_id=mmcif_to_author_chain_id,
  184. valid_chains=valid_chains,
  185. )
  186. return ParsingResult(mmcif_object=mmcif_object, errors=errors)
  187. except Exception as e: # pylint:disable=broad-except
  188. errors[(file_id, '')] = e
  189. if not catch_all_errors:
  190. raise
  191. return ParsingResult(mmcif_object=None, errors=errors)
  192. @functools.lru_cache(16, typed=False)
  193. def parse(*,
  194. file_id: str,
  195. mmcif_string: str,
  196. catch_all_errors: bool = True) -> ParsingResult:
  197. """Entry point, parses an mmcif_string.
  198. Args:
  199. file_id: A string identifier for this file. Should be unique within the
  200. collection of files being processed.
  201. mmcif_string: Contents of an mmCIF file.
  202. catch_all_errors: If True, all exceptions are caught and error messages are
  203. returned as part of the ParsingResult. If False exceptions will be allowed
  204. to propagate.
  205. Returns:
  206. A ParsingResult.
  207. """
  208. errors = {}
  209. try:
  210. parser = PDB.MMCIFParser(QUIET=True)
  211. handle = io.StringIO(mmcif_string)
  212. full_structure = parser.get_structure('', handle)
  213. first_model_structure = _get_first_model(full_structure)
  214. # Extract the _mmcif_dict from the parser, which contains useful fields not
  215. # reflected in the Biopython structure.
  216. parsed_info = parser._mmcif_dict # pylint:disable=protected-access
  217. # Ensure all values are lists, even if singletons.
  218. for key, value in parsed_info.items():
  219. if not isinstance(value, list):
  220. parsed_info[key] = [value]
  221. header = _get_header(parsed_info)
  222. # Determine the protein chains, and their start numbers according to the
  223. # internal mmCIF numbering scheme (likely but not guaranteed to be 1).
  224. valid_chains = _get_protein_chains(parsed_info=parsed_info)
  225. if not valid_chains:
  226. return ParsingResult(
  227. None, {(file_id, ''): 'No protein chains found in this file.'})
  228. seq_start_num = {
  229. chain_id: min([monomer.num for monomer in seq])
  230. for chain_id, seq in valid_chains.items()
  231. }
  232. # Loop over the atoms for which we have coordinates. Populate two mappings:
  233. # -mmcif_to_author_chain_id (maps internal mmCIF chain ids to chain ids used
  234. # the authors / Biopython).
  235. # -seq_to_structure_mappings (maps idx into sequence to ResidueAtPosition).
  236. mmcif_to_author_chain_id = {}
  237. seq_to_structure_mappings = {}
  238. for atom in _get_atom_site_list(parsed_info):
  239. if atom.model_num != '1':
  240. # We only process the first model at the moment.
  241. continue
  242. mmcif_to_author_chain_id[
  243. atom.mmcif_chain_id] = atom.author_chain_id
  244. if atom.mmcif_chain_id in valid_chains:
  245. hetflag = ' '
  246. if atom.hetatm_atom == 'HETATM':
  247. # Water atoms are assigned a special hetflag of W in Biopython. We
  248. # need to do the same, so that this hetflag can be used to fetch
  249. # a residue from the Biopython structure by id.
  250. if atom.residue_name in ('HOH', 'WAT'):
  251. hetflag = 'W'
  252. else:
  253. hetflag = 'H_' + atom.residue_name
  254. insertion_code = atom.insertion_code
  255. if not _is_set(atom.insertion_code):
  256. insertion_code = ' '
  257. position = ResiduePosition(
  258. chain_id=atom.author_chain_id,
  259. residue_number=int(atom.author_seq_num),
  260. insertion_code=insertion_code,
  261. )
  262. seq_idx = int(
  263. atom.mmcif_seq_num) - seq_start_num[atom.mmcif_chain_id]
  264. current = seq_to_structure_mappings.get(
  265. atom.author_chain_id, {})
  266. current[seq_idx] = ResidueAtPosition(
  267. position=position,
  268. name=atom.residue_name,
  269. is_missing=False,
  270. hetflag=hetflag,
  271. )
  272. seq_to_structure_mappings[atom.author_chain_id] = current
  273. # Add missing residue information to seq_to_structure_mappings.
  274. for chain_id, seq_info in valid_chains.items():
  275. author_chain = mmcif_to_author_chain_id[chain_id]
  276. current_mapping = seq_to_structure_mappings[author_chain]
  277. for idx, monomer in enumerate(seq_info):
  278. if idx not in current_mapping:
  279. current_mapping[idx] = ResidueAtPosition(
  280. position=None,
  281. name=monomer.id,
  282. is_missing=True,
  283. hetflag=' ')
  284. author_chain_to_sequence = {}
  285. for chain_id, seq_info in valid_chains.items():
  286. author_chain = mmcif_to_author_chain_id[chain_id]
  287. seq = []
  288. for monomer in seq_info:
  289. code = SCOPData.protein_letters_3to1.get(monomer.id, 'X')
  290. seq.append(code if len(code) == 1 else 'X')
  291. seq = ''.join(seq)
  292. author_chain_to_sequence[author_chain] = seq
  293. mmcif_object = MmcifObject(
  294. file_id=file_id,
  295. header=header,
  296. structure=first_model_structure,
  297. chain_to_seqres=author_chain_to_sequence,
  298. seqres_to_structure=seq_to_structure_mappings,
  299. raw_string=parsed_info,
  300. mmcif_to_author_chain_id=mmcif_to_author_chain_id,
  301. valid_chains=valid_chains,
  302. )
  303. return ParsingResult(mmcif_object=mmcif_object, errors=errors)
  304. except Exception as e: # pylint:disable=broad-except
  305. errors[(file_id, '')] = e
  306. if not catch_all_errors:
  307. raise
  308. return ParsingResult(mmcif_object=None, errors=errors)
  309. def _get_first_model(structure: PdbStructure) -> PdbStructure:
  310. """Returns the first model in a Biopython structure."""
  311. return next(structure.get_models())
  312. _MIN_LENGTH_OF_CHAIN_TO_BE_COUNTED_AS_PEPTIDE = 21
  313. def get_release_date(parsed_info: MmCIFDict) -> str:
  314. """Returns the oldest revision date."""
  315. revision_dates = parsed_info['_pdbx_audit_revision_history.revision_date']
  316. return min(revision_dates)
  317. def _get_header(parsed_info: MmCIFDict) -> PdbHeader:
  318. """Returns a basic header containing method, release date and resolution."""
  319. header = {}
  320. experiments = mmcif_loop_to_list('_exptl.', parsed_info)
  321. header['structure_method'] = ','.join(
  322. [experiment['_exptl.method'].lower() for experiment in experiments])
  323. # Note: The release_date here corresponds to the oldest revision. We prefer to
  324. # use this for dataset filtering over the deposition_date.
  325. if '_pdbx_audit_revision_history.revision_date' in parsed_info:
  326. header['release_date'] = get_release_date(parsed_info)
  327. else:
  328. logging.warning('Could not determine release_date: %s',
  329. parsed_info['_entry.id'])
  330. header['resolution'] = 0.00
  331. for res_key in (
  332. '_refine.ls_d_res_high',
  333. '_em_3d_reconstruction.resolution',
  334. '_reflns.d_resolution_high',
  335. ):
  336. if res_key in parsed_info:
  337. try:
  338. raw_resolution = parsed_info[res_key][0]
  339. header['resolution'] = float(raw_resolution)
  340. except ValueError:
  341. logging.debug('Invalid resolution format: %s',
  342. parsed_info[res_key])
  343. return header
  344. def _get_atom_site_list(parsed_info: MmCIFDict) -> Sequence[AtomSite]:
  345. """Returns list of atom sites; contains data not present in the structure."""
  346. return [
  347. AtomSite(*site) for site in zip( # pylint:disable=g-complex-comprehension
  348. parsed_info['_atom_site.label_comp_id'],
  349. parsed_info['_atom_site.auth_asym_id'],
  350. parsed_info['_atom_site.label_asym_id'],
  351. parsed_info['_atom_site.auth_seq_id'],
  352. parsed_info['_atom_site.label_seq_id'],
  353. parsed_info['_atom_site.pdbx_PDB_ins_code'],
  354. parsed_info['_atom_site.group_PDB'],
  355. parsed_info['_atom_site.pdbx_PDB_model_num'],
  356. )
  357. ]
  358. def _get_protein_chains(
  359. *, parsed_info: Mapping[str,
  360. Any]) -> Mapping[ChainId, Sequence[Monomer]]:
  361. """Extracts polymer information for protein chains only.
  362. Args:
  363. parsed_info: _mmcif_dict produced by the Biopython parser.
  364. Returns:
  365. A dict mapping mmcif chain id to a list of Monomers.
  366. """
  367. # Get polymer information for each entity in the structure.
  368. entity_poly_seqs = mmcif_loop_to_list('_entity_poly_seq.', parsed_info)
  369. polymers = collections.defaultdict(list)
  370. for entity_poly_seq in entity_poly_seqs:
  371. polymers[entity_poly_seq['_entity_poly_seq.entity_id']].append(
  372. Monomer(
  373. id=entity_poly_seq['_entity_poly_seq.mon_id'],
  374. num=int(entity_poly_seq['_entity_poly_seq.num']),
  375. ))
  376. # Get chemical compositions. Will allow us to identify which of these polymers
  377. # are proteins.
  378. chem_comps = mmcif_loop_to_dict('_chem_comp.', '_chem_comp.id',
  379. parsed_info)
  380. # Get chains information for each entity. Necessary so that we can return a
  381. # dict keyed on chain id rather than entity.
  382. struct_asyms = mmcif_loop_to_list('_struct_asym.', parsed_info)
  383. entity_to_mmcif_chains = collections.defaultdict(list)
  384. for struct_asym in struct_asyms:
  385. chain_id = struct_asym['_struct_asym.id']
  386. entity_id = struct_asym['_struct_asym.entity_id']
  387. entity_to_mmcif_chains[entity_id].append(chain_id)
  388. # Identify and return the valid protein chains.
  389. valid_chains = {}
  390. for entity_id, seq_info in polymers.items():
  391. chain_ids = entity_to_mmcif_chains[entity_id]
  392. # Reject polymers without any peptide-like components, such as DNA/RNA.
  393. if any([
  394. 'peptide' in chem_comps[monomer.id]['_chem_comp.type']
  395. for monomer in seq_info
  396. ]):
  397. for chain_id in chain_ids:
  398. valid_chains[chain_id] = seq_info
  399. return valid_chains
  400. def _is_set(data: str) -> bool:
  401. """Returns False if data is a special mmCIF character indicating 'unset'."""
  402. return data not in ('.', '?')