File size: 9,513 Bytes
40d185e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
276
277


"""Utilities for manipulating chemical components data."""

from collections.abc import Iterable, Mapping, Sequence
import dataclasses
import functools
from typing import Self

from flax_model.alphafold3.constants import chemical_components
from flax_model.alphafold3.constants import residue_names
from flax_model.alphafold3.structure import mmcif
import rdkit.Chem as rd_chem


@dataclasses.dataclass(frozen=True)
class ChemCompEntry:
  """Items of _chem_comp category.

  For the full list of items and their semantics see
  http://mmcif.rcsb.org/dictionaries/mmcif_pdbx_v50.dic/Categories/chem_comp.html
  """

  type: str
  name: str = '?'
  pdbx_synonyms: str = '?'
  formula: str = '?'
  formula_weight: str = '?'
  mon_nstd_flag: str = '?'
  pdbx_smiles: str | None = None

  def __post_init__(self):
    for field, value in vars(self).items():
      if not value and value is not None:
        raise ValueError(f"{field} value can't be an empty string.")

  def extends(self, other: Self) -> bool:
    """Checks whether this ChemCompEntry extends another one."""
    for field, value in vars(self).items():
      other_value = getattr(other, field)
      if _value_is_missing(other_value):
        continue
      if value != other_value:
        return False
    return True

  @property
  def rdkit_mol(self) -> rd_chem.Mol:
    """Returns an RDKit Mol, created via RDKit from entry SMILES string."""
    if not self.pdbx_smiles:
      raise ValueError('Cannot construct RDKit Mol with empty pdbx_smiles')
    return rd_chem.MolFromSmiles(self.pdbx_smiles)


_REQUIRED_MMCIF_COLUMNS = ('_chem_comp.id', '_chem_comp.type')


class MissingChemicalComponentsDataError(Exception):
  """Raised when chemical components data is missing from an mmCIF."""


@dataclasses.dataclass(frozen=True)
class ChemicalComponentsData:
  """Extra information for chemical components occurring in mmCIF.

  Fields:
    chem_comp: A mapping from _chem_comp.id to associated items in the
      chem_comp category.
  """

  chem_comp: Mapping[str, ChemCompEntry]

  @classmethod
  def from_mmcif(
      cls, cif: mmcif.Mmcif, fix_mse: bool, fix_unknown_dna: bool
  ) -> Self:
    """Constructs an instance of ChemicalComponentsData from an Mmcif object."""
    for col in _REQUIRED_MMCIF_COLUMNS:
      if col not in cif:
        raise MissingChemicalComponentsDataError(col)

    id_ = cif['_chem_comp.id']  # Guaranteed to be present.
    type_ = cif['_chem_comp.type']  # Guaranteed to be present.
    name = cif.get('_chem_comp.name', ['?'] * len(id_))
    synonyms = cif.get('_chem_comp.pdbx_synonyms', ['?'] * len(id_))
    formula = cif.get('_chem_comp.formula', ['?'] * len(id_))
    weight = cif.get('_chem_comp.formula_weight', ['?'] * len(id_))
    mon_nstd_flag = cif.get('_chem_comp.mon_nstd_flag', ['?'] * len(id_))
    smiles = cif.get('_chem_comp.pdbx_smiles', ['?'] * len(id_))
    smiles = [None if s == '?' else s for s in smiles]

    chem_comp = {
        component_name: ChemCompEntry(*entry)
        for component_name, *entry in zip(
            id_, type_, name, synonyms, formula, weight, mon_nstd_flag, smiles
        )
    }

    if fix_mse and 'MSE' in chem_comp:
      if 'MET' not in chem_comp:
        chem_comp['MET'] = ChemCompEntry(
            type='L-PEPTIDE LINKING',
            name='METHIONINE',
            pdbx_synonyms='?',
            formula='C5 H11 N O2 S',
            formula_weight='149.211',
            mon_nstd_flag='y',
            pdbx_smiles=None,
        )

    if fix_unknown_dna and 'N' in chem_comp:
      # Do not delete 'N' as it may be needed for RNA in the system.
      if 'DN' not in chem_comp:
        chem_comp['DN'] = ChemCompEntry(
            type='DNA LINKING',
            name="UNKNOWN 2'-DEOXYNUCLEOTIDE",
            pdbx_synonyms='?',
            formula='C5 H11 O6 P',
            formula_weight='198.111',
            mon_nstd_flag='y',
            pdbx_smiles=None,
        )

    return ChemicalComponentsData(chem_comp)

  def to_mmcif_dict(self) -> Mapping[str, Sequence[str]]:
    """Returns chemical components data as a dict suitable for `mmcif.Mmcif`."""
    mmcif_dict = {}

    mmcif_fields = set()
    for entry in self.chem_comp.values():
      for field, value in vars(entry).items():
        if value:
          mmcif_fields.add(field)
    chem_comp_ids = []
    for component_id in sorted(self.chem_comp):
      entry = self.chem_comp[component_id]
      chem_comp_ids.append(component_id)
      for field in mmcif_fields:
        mmcif_dict.setdefault(f'_chem_comp.{field}', []).append(
            getattr(entry, field) or '?'
        )
    if chem_comp_ids:
      mmcif_dict['_chem_comp.id'] = chem_comp_ids
    return mmcif_dict


def _value_is_missing(value: str) -> bool:
  return not value or value in ('.', '?')


def get_data_for_ccd_components(
    ccd: chemical_components.Ccd,
    chemical_component_ids: Iterable[str],
    populate_pdbx_smiles: bool = False,
) -> ChemicalComponentsData:
  """Returns `ChemicalComponentsData` for chemical components known by PDB."""
  chem_comp = {}
  for chemical_component_id in chemical_component_ids:
    chem_data = chemical_components.component_name_to_info(
        ccd=ccd, res_name=chemical_component_id
    )
    if not chem_data:
      continue
    chem_comp[chemical_component_id] = ChemCompEntry(
        type=chem_data.type,
        name=chem_data.name,
        pdbx_synonyms=chem_data.pdbx_synonyms,
        formula=chem_data.formula,
        formula_weight=chem_data.formula_weight,
        mon_nstd_flag=chem_data.mon_nstd_flag,
        pdbx_smiles=(
            chem_data.pdbx_smiles or None if populate_pdbx_smiles else None
        ),
    )
  return ChemicalComponentsData(chem_comp=chem_comp)


def populate_missing_ccd_data(
    ccd: chemical_components.Ccd,
    chemical_components_data: ChemicalComponentsData,
    chemical_component_ids: Iterable[str] | None = None,
    populate_pdbx_smiles: bool = False,
) -> ChemicalComponentsData:
  """Populates missing data for the chemical components from CCD.

  Args:
    ccd: The chemical components database.
    chemical_components_data: ChemicalComponentsData to populate missing values
      for. This function doesn't modify the object, extended version is provided
      as a return value.
    chemical_component_ids: chemical components to populate missing values for.
      If not specified, the function will consider all chemical components which
      are already present in `chemical_components_data`.
    populate_pdbx_smiles: whether to populate `pdbx_smiles` field using SMILES
      descriptors from _pdbx_chem_comp_descriptor CCD table. If CCD provides
      multiple SMILES strings, any of them could be used.

  Returns:
    New instance of ChemicalComponentsData without missing values for CCD
    entries.
  """
  if chemical_component_ids is None:
    chemical_component_ids = chemical_components_data.chem_comp.keys()

  ccd_data = get_data_for_ccd_components(
      ccd, chemical_component_ids, populate_pdbx_smiles
  )
  chem_comp = dict(chemical_components_data.chem_comp)
  for component_id, ccd_entry in ccd_data.chem_comp.items():
    if component_id not in chem_comp:
      chem_comp[component_id] = ccd_entry
    else:
      already_specified_fields = {
          field: value
          for field, value in vars(chem_comp[component_id]).items()
          if not _value_is_missing(value)
      }
      chem_comp[component_id] = ChemCompEntry(
          **{**vars(ccd_entry), **already_specified_fields}
      )
  return ChemicalComponentsData(chem_comp=chem_comp)


def get_all_atoms_in_entry(
    ccd: chemical_components.Ccd, res_name: str
) -> Mapping[str, Sequence[str]]:
  """Get all possible atoms and bonds for this residue in a standard order.

  Args:
    ccd: The chemical components dictionary.
    res_name: Full CCD name.

  Returns:
    A dictionary table of the atoms and bonds for this residue in this residue
    type.
  """
  # The CCD version of 'UNK' is weird. It has a CB and a CG atom. We just want
  # the minimal amino-acid here which is GLY.
  if res_name == 'UNK':
    res_name = 'GLY'
  ccd_data = ccd.get(res_name)
  if not ccd_data:
    raise ValueError(f'Unknown residue type {res_name}')

  keys = (
      '_chem_comp_atom.atom_id',
      '_chem_comp_atom.type_symbol',
      '_chem_comp_bond.atom_id_1',
      '_chem_comp_bond.atom_id_2',
  )

  # Add terminal hydrogens for protonation of the N-terminal
  if res_name == 'PRO':
    res_atoms = {key: [*ccd_data.get(key, [])] for key in keys}
    res_atoms['_chem_comp_atom.atom_id'].extend(['H2', 'H3'])
    res_atoms['_chem_comp_atom.type_symbol'].extend(['H', 'H'])
    res_atoms['_chem_comp_bond.atom_id_1'].extend(['N', 'N'])
    res_atoms['_chem_comp_bond.atom_id_2'].extend(['H2', 'H3'])
  elif res_name in residue_names.PROTEIN_TYPES_WITH_UNKNOWN:
    res_atoms = {key: [*ccd_data.get(key, [])] for key in keys}
    res_atoms['_chem_comp_atom.atom_id'].append('H3')
    res_atoms['_chem_comp_atom.type_symbol'].append('H')
    res_atoms['_chem_comp_bond.atom_id_1'].append('N')
    res_atoms['_chem_comp_bond.atom_id_2'].append('H3')
  else:
    res_atoms = {key: ccd_data.get(key, []) for key in keys}

  return res_atoms


@functools.lru_cache(maxsize=128)
def get_res_atom_names(ccd: chemical_components.Ccd, res_name: str) -> set[str]:
  """Gets the names of the atoms in a given CCD residue."""
  atoms = get_all_atoms_in_entry(ccd, res_name)['_chem_comp_atom.atom_id']
  return set(atoms)