bindview 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. bindview/__init__.py +88 -0
  2. bindview/__main__.py +6 -0
  3. bindview/align.py +493 -0
  4. bindview/arrange.js +347 -0
  5. bindview/arrange.py +248 -0
  6. bindview/backends.py +290 -0
  7. bindview/basepairs.py +1711 -0
  8. bindview/chains.py +264 -0
  9. bindview/chem.py +57 -0
  10. bindview/clearance.py +123 -0
  11. bindview/cli.py +990 -0
  12. bindview/compare.py +1854 -0
  13. bindview/confidence.py +531 -0
  14. bindview/consensus.py +303 -0
  15. bindview/covalent.py +220 -0
  16. bindview/depict.py +790 -0
  17. bindview/detect.py +378 -0
  18. bindview/diagram.py +1891 -0
  19. bindview/distance_table.py +589 -0
  20. bindview/ensemble.py +787 -0
  21. bindview/errors.py +47 -0
  22. bindview/exposure.py +207 -0
  23. bindview/features.py +179 -0
  24. bindview/fingerprint.py +469 -0
  25. bindview/fragments.py +304 -0
  26. bindview/geometry.py +482 -0
  27. bindview/graph.py +611 -0
  28. bindview/graphbuild.py +431 -0
  29. bindview/interactions.py +418 -0
  30. bindview/interactive.py +334 -0
  31. bindview/interface.py +1329 -0
  32. bindview/ions.py +155 -0
  33. bindview/layout/__init__.py +15 -0
  34. bindview/layout/body.py +421 -0
  35. bindview/layout/engine.py +1084 -0
  36. bindview/layout/field.py +261 -0
  37. bindview/ligand.py +583 -0
  38. bindview/near.py +67 -0
  39. bindview/options.py +92 -0
  40. bindview/pae.py +991 -0
  41. bindview/peptide.py +610 -0
  42. bindview/plane.py +320 -0
  43. bindview/polymer.py +678 -0
  44. bindview/py.typed +0 -0
  45. bindview/report.py +1407 -0
  46. bindview/residues.py +296 -0
  47. bindview/resolve.py +493 -0
  48. bindview/scene.py +239 -0
  49. bindview/solvent.py +254 -0
  50. bindview/structure.py +1145 -0
  51. bindview/styles/__init__.py +2 -0
  52. bindview/styles/absence.py +180 -0
  53. bindview/styles/base.py +2128 -0
  54. bindview/styles/closeup.py +146 -0
  55. bindview/styles/detailed.py +690 -0
  56. bindview/styles/ligand_draw.py +289 -0
  57. bindview/styles/mixed.py +70 -0
  58. bindview/styles/polymer_draw.py +354 -0
  59. bindview/styles/rings.py +75 -0
  60. bindview/styles/schematic.py +311 -0
  61. bindview/styles/summary.py +147 -0
  62. bindview/svg.py +310 -0
  63. bindview/textmetrics.py +64 -0
  64. bindview/theme.py +317 -0
  65. bindview-0.1.0.dist-info/METADATA +270 -0
  66. bindview-0.1.0.dist-info/RECORD +70 -0
  67. bindview-0.1.0.dist-info/WHEEL +4 -0
  68. bindview-0.1.0.dist-info/entry_points.txt +2 -0
  69. bindview-0.1.0.dist-info/licenses/LICENSE +21 -0
  70. bindview-0.1.0.dist-info/licenses/NOTICE +48 -0
bindview/errors.py ADDED
@@ -0,0 +1,47 @@
1
+ """Exception types.
2
+
3
+ Errors are reserved for *failures*: a file that cannot be parsed, a ligand that
4
+ is not in the structure, a molecule that cannot be built. A complex that was
5
+ analysed and has no interactions is **not** an error -- it produces a normal
6
+ result whose ``status`` is ``"empty"``. Keeping the two apart is a hard
7
+ requirement of the library: callers must be able to tell "nothing found" from
8
+ "could not look".
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+
14
+ class BindviewError(Exception):
15
+ """Base class for every error raised by this package."""
16
+
17
+
18
+ class StructureError(BindviewError):
19
+ """The structure file could not be read or contains no usable atoms."""
20
+
21
+
22
+ class LigandNotFoundError(BindviewError):
23
+ """The ligand selection matched nothing (or matched ambiguously)."""
24
+
25
+
26
+ class LigandBuildError(BindviewError):
27
+ """An RDKit molecule could not be built for the ligand."""
28
+
29
+
30
+ class InteractionError(BindviewError):
31
+ """An interaction record is malformed."""
32
+
33
+
34
+ class DetectionUnavailableError(BindviewError):
35
+ """Interaction detection was requested but the optional detector is not installed."""
36
+
37
+
38
+ class EnsembleError(BindviewError):
39
+ """Models given as one ensemble are not models of one complex: another ligand, or another pocket."""
40
+
41
+
42
+ class RenderError(BindviewError):
43
+ """The diagram could not be rendered."""
44
+
45
+
46
+ class GraphError(BindviewError, ValueError):
47
+ """A diagram graph is malformed, of an unsupported version, or does not fit the diagram."""
bindview/exposure.py ADDED
@@ -0,0 +1,207 @@
1
+ """Solvent exposure of the ligand: per atom for drawing, and as a reported number.
2
+
3
+ Both are plain Shrake-Rupley estimates on heavy atoms and need nothing but
4
+ NumPy.
5
+
6
+ * :func:`relative_exposure` -- each ligand atom's accessible surface in the
7
+ complex relative to the same atom in the free ligand. A drawing aid: which
8
+ atoms stick out of the pocket (the schematic style's grey halos).
9
+ * :func:`ligand_burial` -- the ligand's solvent-accessible surface in square
10
+ angstrom, free and in the complex, and from the two the **buried fraction**.
11
+ This one is reported. It measures the model as given: a ligand docked against
12
+ half a site (one chain of an oligomer) stays exposed, and a pocket pLDDT
13
+ read against its usual bands does not say so
14
+ (``docs/reference.md``). The reverse does not hold: a ligand that
15
+ has drifted into a deep enough groove elsewhere is buried, so a high value
16
+ is no evidence that a site is complete.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import math
22
+ from dataclasses import dataclass
23
+ from typing import Any, Sequence
24
+
25
+ import numpy as np
26
+
27
+ __all__ = ["relative_exposure", "ligand_burial", "structure_burial", "Burial", "PROBE", "SASA_POINTS",
28
+ "WATER_NAMES", "BURIAL_WARNING_BELOW", "burial_warning"]
29
+
30
+ #: A ligand less buried than this draws a warning. The value is calibrated: ``docs/reference.md`` says on
31
+ #: what, and what the result does not show.
32
+ BURIAL_WARNING_BELOW = 0.70
33
+
34
+ #: The names a file gives a water molecule, in capitals. Water is solvent: it buries no ligand, holds no ion as
35
+ #: a residue does and is no partner of a bond or of a contact. One set for every module that asks.
36
+ WATER_NAMES = frozenset({"HOH", "WAT", "DOD", "H2O", "D2O", "TIP", "TIP3", "SOL"})
37
+
38
+ #: Radius of the solvent probe, angstrom.
39
+ PROBE = 1.4
40
+ #: Points per atom for the reported surface. 240 keeps the buried fraction of a
41
+ #: drug-sized ligand stable to about one part in a hundred.
42
+ SASA_POINTS = 240
43
+ #: Points per atom for the drawing aid, which needs no more than which atoms stick out.
44
+ _DRAWING_POINTS = 96
45
+
46
+ _VDW = {"C": 1.7, "N": 1.55, "O": 1.52, "S": 1.8, "P": 1.8, "F": 1.47, "Cl": 1.75, "Br": 1.85, "I": 1.98,
47
+ "Se": 1.9, "B": 1.92, "H": 1.1}
48
+ _DEFAULT_VDW = 1.8
49
+
50
+
51
+ def _radius(element: str) -> float:
52
+ return _VDW.get(element, _DEFAULT_VDW)
53
+
54
+
55
+ def _sphere(n: int) -> np.ndarray:
56
+ """``n`` points spread evenly on the unit sphere (golden-angle spiral)."""
57
+ k = np.arange(n) + 0.5
58
+ phi = np.arccos(1.0 - 2.0 * k / n)
59
+ theta = math.pi * (1.0 + 5.0 ** 0.5) * k
60
+ return np.column_stack([np.cos(theta) * np.sin(phi), np.sin(theta) * np.sin(phi), np.cos(phi)])
61
+
62
+
63
+ def relative_exposure(lig_xyz: np.ndarray, lig_elements: Sequence[str], env_xyz: np.ndarray,
64
+ env_elements: Sequence[str]) -> np.ndarray:
65
+ """Per ligand atom: accessible surface in the complex / accessible surface when free (0..1)."""
66
+ n = len(lig_xyz)
67
+ if n == 0:
68
+ return np.zeros(0)
69
+ sphere = _sphere(_DRAWING_POINTS)
70
+ lig_r = np.array([_radius(e) for e in lig_elements]) + PROBE
71
+ if len(env_xyz):
72
+ lo, hi = lig_xyz.min(axis=0) - 9.0, lig_xyz.max(axis=0) + 9.0
73
+ near = ((env_xyz >= lo) & (env_xyz <= hi)).all(axis=1)
74
+ env_xyz = env_xyz[near]
75
+ env_r = np.array([_radius(e) for e, keep in zip(env_elements, near) if keep]) + PROBE
76
+ else:
77
+ env_r = np.zeros(0)
78
+ out = np.zeros(n)
79
+ for i in range(n):
80
+ pts = lig_xyz[i] + lig_r[i] * sphere # (P, 3)
81
+ others = np.arange(n) != i
82
+ d_lig = np.linalg.norm(pts[:, None, :] - lig_xyz[others][None, :, :], axis=2)
83
+ free = ~(d_lig < lig_r[others][None, :]).any(axis=1)
84
+ n_free = int(free.sum())
85
+ if n_free == 0:
86
+ continue
87
+ if len(env_xyz):
88
+ d_env = np.linalg.norm(pts[free][:, None, :] - env_xyz[None, :, :], axis=2)
89
+ open_ = ~(d_env < env_r[None, :]).any(axis=1)
90
+ out[i] = float(open_.sum()) / n_free
91
+ else:
92
+ out[i] = 1.0
93
+ return out
94
+
95
+
96
+ @dataclass(frozen=True)
97
+ class Burial:
98
+ """How much of the ligand's surface the rest of the model covers."""
99
+
100
+ sasa_free: float # A^2: the ligand alone
101
+ sasa_complex: float # A^2: the ligand with everything else in the model around it
102
+ atom_free: tuple[float, ...] # the same per ligand atom, in the order of ``atoms``
103
+ atom_complex: tuple[float, ...]
104
+ probe: float = PROBE
105
+ n_points: int = SASA_POINTS
106
+ atoms: tuple[str, ...] = () # names of the ligand's heavy atoms, when known
107
+
108
+ @property
109
+ def buried_fraction(self) -> float:
110
+ """``1 - SASA_complex / SASA_free``: 0 for a ligand in open solvent, 1 for one fully enclosed.
111
+
112
+ A low value is a warning. A high one is not reassurance: a ligand buried in the wrong groove is
113
+ buried all the same.
114
+ """
115
+ return 1.0 - self.sasa_complex / self.sasa_free if self.sasa_free > 0.0 else 0.0
116
+
117
+ @property
118
+ def exposed_fraction(self) -> float:
119
+ return 1.0 - self.buried_fraction
120
+
121
+ def as_dict(self) -> dict[str, Any]:
122
+ return {"sasa_free": round(self.sasa_free, 1), "sasa_complex": round(self.sasa_complex, 1),
123
+ "buried_fraction": round(self.buried_fraction, 3), "exposed_fraction": round(self.exposed_fraction, 3),
124
+ "probe": self.probe, "n_points": self.n_points}
125
+
126
+
127
+ def ligand_burial(lig_xyz: np.ndarray, lig_elements: Sequence[str], env_xyz: np.ndarray,
128
+ env_elements: Sequence[str], probe: float = PROBE, n_points: int = SASA_POINTS) -> Burial:
129
+ """Solvent-accessible surface of the ligand, free and in the complex.
130
+
131
+ Heavy atoms only, on both sides; van der Waals radii as for the drawing
132
+ aid. ``env_xyz`` / ``env_elements`` are whatever surrounds the ligand in
133
+ the model: the caller decides what that is (the diagram leaves waters
134
+ out, since they are solvent, and keeps everything else).
135
+ """
136
+ lig_xyz = np.asarray(lig_xyz, dtype=float).reshape(-1, 3)
137
+ n = len(lig_xyz)
138
+ if n == 0:
139
+ return Burial(0.0, 0.0, (), (), probe, n_points)
140
+ sphere = _sphere(n_points)
141
+ lig_r = np.array([_radius(e) for e in lig_elements]) + probe
142
+ env_xyz = np.asarray(env_xyz, dtype=float).reshape(-1, 3)
143
+ env_r = np.array([_radius(e) for e in env_elements]) + probe
144
+ if len(env_xyz):
145
+ reach = float(lig_r.max() + env_r.max())
146
+ lo, hi = lig_xyz.min(axis=0) - reach, lig_xyz.max(axis=0) + reach
147
+ near = ((env_xyz >= lo) & (env_xyz <= hi)).all(axis=1)
148
+ env_xyz, env_r = env_xyz[near], env_r[near]
149
+ free = np.zeros(n)
150
+ bound = np.zeros(n)
151
+ for i in range(n):
152
+ pts = lig_xyz[i] + lig_r[i] * sphere # (P, 3)
153
+ area = 4.0 * math.pi * lig_r[i] ** 2 / n_points
154
+ others = np.arange(n) != i
155
+ open_ = np.ones(n_points, dtype=bool)
156
+ if others.any():
157
+ d_lig = np.linalg.norm(pts[:, None, :] - lig_xyz[others][None, :, :], axis=2)
158
+ open_ = ~(d_lig < lig_r[others][None, :]).any(axis=1)
159
+ free[i] = area * float(open_.sum())
160
+ if open_.any() and len(env_xyz):
161
+ # Only atoms whose probe-expanded sphere can reach this one's matter.
162
+ close = np.linalg.norm(env_xyz - lig_xyz[i], axis=1) < (lig_r[i] + env_r)
163
+ if close.any():
164
+ d_env = np.linalg.norm(pts[open_][:, None, :] - env_xyz[close][None, :, :], axis=2)
165
+ bound[i] = area * float((~(d_env < env_r[close][None, :]).any(axis=1)).sum())
166
+ else:
167
+ bound[i] = free[i]
168
+ else:
169
+ bound[i] = free[i] if open_.any() else 0.0
170
+ return Burial(float(free.sum()), float(bound.sum()), tuple(float(v) for v in free),
171
+ tuple(float(v) for v in bound), probe, n_points)
172
+
173
+
174
+ def structure_burial(structure: Any, ligand: Any, probe: float = PROBE, n_points: int = SASA_POINTS) -> Burial:
175
+ """Burial of one residue of a parsed structure by everything else in the model.
176
+
177
+ "Everything else" is every heavy atom that is not the ligand and not water:
178
+ protein, nucleic acid, cofactors, ions, other ligands. Water is solvent --
179
+ counting a crystallographic water shell as burial would make a ligand on
180
+ the surface of a well-resolved structure look enclosed.
181
+ """
182
+ lig = [a for a in structure.residue_atoms(ligand) if a.element not in ("H", "D")]
183
+ env = [a for a in structure.atoms
184
+ if a.residue != ligand and a.element not in ("H", "D") and a.resname.upper() not in WATER_NAMES]
185
+ out = ligand_burial(np.array([a.xyz for a in lig], dtype=float).reshape(-1, 3), [a.element for a in lig],
186
+ np.array([a.xyz for a in env], dtype=float).reshape(-1, 3), [a.element for a in env],
187
+ probe, n_points)
188
+ return Burial(out.sasa_free, out.sasa_complex, out.atom_free, out.atom_complex, probe, n_points,
189
+ tuple(a.name for a in lig))
190
+
191
+
192
+ def burial_warning(burial: "Burial | None") -> str | None:
193
+ """The note a poorly buried ligand gets, or ``None``.
194
+
195
+ It states the observation -- most of the ligand's surface is open to
196
+ solvent in this model -- and offers the two readings the calibration set
197
+ contains: a site this model cannot form (one chain of an oligomer, a
198
+ missing cofactor), or a ligand that is not in a pocket at all. It does not
199
+ say which. A well buried ligand proves nothing either: one that has
200
+ drifted into another cavity of an incomplete model is buried too.
201
+ """
202
+ if burial is None or burial.sasa_free <= 0.0 or burial.buried_fraction >= BURIAL_WARNING_BELOW:
203
+ return None
204
+ return (f"the ligand is only {100.0 * burial.buried_fraction:.0f} % buried: "
205
+ f"{100.0 * burial.exposed_fraction:.0f} % of its surface stays solvent-exposed in this model "
206
+ f"(below the calibrated {100.0 * BURIAL_WARNING_BELOW:.0f} %). The site may be incomplete here "
207
+ "(one chain of an oligomer, a missing cofactor), or the ligand may not sit in a pocket at all")
bindview/features.py ADDED
@@ -0,0 +1,179 @@
1
+ """Perception of the ligand features interactions attach to: rings and charged groups.
2
+
3
+ Pi interactions attach to a ring centroid and salt bridges to a charged group,
4
+ and detectors usually report those without atom names. This module enumerates
5
+ the candidates on the ligand; :mod:`bindview.resolve` then picks the one whose
6
+ geometry reproduces the reported distance.
7
+
8
+ The definitions are written from the chemistry, deliberately a little broader
9
+ than any one detector's, and each candidate carries a ``rank`` saying how
10
+ canonical it is (0 = textbook) so that ties are broken toward chemical sense.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from dataclasses import dataclass
16
+
17
+ import numpy as np
18
+ from rdkit import Chem
19
+
20
+ from .chem import is_metal
21
+ from .ligand import Ligand
22
+
23
+ __all__ = ["LigandGroup", "perceive_rings", "perceive_charged_groups", "perceive_metals"]
24
+
25
+
26
+ @dataclass(frozen=True)
27
+ class LigandGroup:
28
+ """A ring or functional group on the ligand.
29
+
30
+ ``atoms`` are the members (what gets highlighted, and whose 2D centroid is
31
+ the drawing anchor). ``center_atoms`` are the atoms whose 3D centroid is
32
+ the interaction centre a detector measures to -- e.g. the phosphorus of a
33
+ phosphate, the two oxygens of a carboxylate.
34
+ """
35
+
36
+ kind: str
37
+ atoms: tuple[int, ...]
38
+ center_atoms: tuple[int, ...]
39
+ charge: int
40
+ rank: int
41
+
42
+ def center3d(self, coords: np.ndarray) -> np.ndarray:
43
+ return coords[list(self.center_atoms)].mean(axis=0)
44
+
45
+
46
+ def _ring_planarity(coords: np.ndarray, ring: tuple[int, ...]) -> float:
47
+ """RMS distance (angstrom) of ring atoms from their best-fit plane."""
48
+ pts = coords[list(ring)]
49
+ centred = pts - pts.mean(axis=0)
50
+ # Smallest singular value direction is the plane normal.
51
+ _, s, _ = np.linalg.svd(centred, full_matrices=False)
52
+ return float(s[-1] / np.sqrt(len(ring)))
53
+
54
+
55
+ def perceive_rings(lig: Ligand) -> list[LigandGroup]:
56
+ """Five- and six-membered rings, aromatic ones first.
57
+
58
+ Non-aromatic rings are kept as lower-ranked candidates when they are planar
59
+ in the model, because detectors working from geometry accept those too.
60
+ """
61
+ out: list[LigandGroup] = []
62
+ mol = lig.mol
63
+ for ring in mol.GetRingInfo().AtomRings():
64
+ if not 5 <= len(ring) <= 6:
65
+ continue
66
+ aromatic = all(mol.GetAtomWithIdx(i).GetIsAromatic() for i in ring)
67
+ if aromatic:
68
+ rank = 0
69
+ elif _ring_planarity(lig.coords3d, ring) < 0.12:
70
+ rank = 1
71
+ else:
72
+ rank = 3
73
+ members = tuple(ring)
74
+ out.append(LigandGroup("ring", members, members, 0, rank))
75
+ out.sort(key=lambda g: (g.rank, g.atoms))
76
+ return out
77
+
78
+
79
+ def _in_aromatic_six_ring(atom: Chem.Atom) -> bool:
80
+ return atom.GetIsAromatic() and atom.IsInRingSize(6)
81
+
82
+
83
+ def _second_amino(atom: Chem.Atom) -> bool:
84
+ """Another carbon of the atom's aromatic six-ring carries an amino group (2,4-diaminopyrimidines, pteridines)."""
85
+ mol = atom.GetOwningMol()
86
+ for ring in mol.GetRingInfo().AtomRings():
87
+ if len(ring) != 6 or atom.GetIdx() not in ring:
88
+ continue
89
+ for j in ring:
90
+ other = mol.GetAtomWithIdx(j)
91
+ if j == atom.GetIdx() or other.GetSymbol() != "C":
92
+ continue
93
+ if any(n.GetSymbol() == "N" and not n.IsInRing() and n.GetTotalNumHs() > 0 for n in other.GetNeighbors()):
94
+ return True
95
+ return False
96
+
97
+
98
+ def _heavy_neighbors(atom: Chem.Atom) -> list[Chem.Atom]:
99
+ return [n for n in atom.GetNeighbors() if n.GetAtomicNum() > 1]
100
+
101
+
102
+ def _is_terminal_oxygen(atom: Chem.Atom) -> bool:
103
+ return atom.GetSymbol() == "O" and len(_heavy_neighbors(atom)) == 1
104
+
105
+
106
+ def _is_amide_like(n_atom: Chem.Atom) -> bool:
107
+ """Nitrogen whose lone pair is tied up: amide, sulfonamide, aniline, enamine, N-oxide..."""
108
+ for nb in n_atom.GetNeighbors():
109
+ if nb.GetIsAromatic():
110
+ return True
111
+ if nb.GetSymbol() in ("S", "P"):
112
+ return True
113
+ for b in nb.GetBonds():
114
+ if b.GetBondTypeAsDouble() >= 2 and b.GetOtherAtomIdx(nb.GetIdx()) != n_atom.GetIdx():
115
+ return True
116
+ return False
117
+
118
+
119
+ def perceive_charged_groups(lig: Ligand) -> list[LigandGroup]:
120
+ """Groups that carry (or readily carry) a charge at physiological pH."""
121
+ mol = lig.mol
122
+ out: list[LigandGroup] = []
123
+ seen_single: set[int] = set()
124
+ for atom in mol.GetAtoms():
125
+ i = atom.GetIdx()
126
+ sym = atom.GetSymbol()
127
+ nbrs = _heavy_neighbors(atom)
128
+ if sym == "C":
129
+ term_o = [n.GetIdx() for n in nbrs if _is_terminal_oxygen(n)]
130
+ if len(term_o) == 2 and len(nbrs) == 3:
131
+ out.append(LigandGroup("carboxylate", (i, *term_o), tuple(term_o), -1, 0))
132
+ n_nb = [n for n in nbrs if n.GetSymbol() == "N"]
133
+ if len(n_nb) == 3 and len(nbrs) == 3 and (not _in_aromatic_six_ring(atom) or _second_amino(atom)):
134
+ out.append(LigandGroup("guanidinium", (i, *(n.GetIdx() for n in n_nb)), (i,), +1, 0))
135
+ elif len(n_nb) == 2 and len(nbrs) == 3 and not atom.GetIsAromatic() \
136
+ and all(not n.GetIsAromatic() for n in n_nb):
137
+ out.append(LigandGroup("amidinium", (i, *(n.GetIdx() for n in n_nb)), (i,), +1, 1))
138
+ elif sym == "P":
139
+ o_nb = [n.GetIdx() for n in nbrs if n.GetSymbol() == "O"]
140
+ if len(o_nb) >= 2:
141
+ term = [j for j in o_nb if _is_terminal_oxygen(mol.GetAtomWithIdx(j))]
142
+ out.append(LigandGroup("phosphate", (i, *(term or o_nb)), (i,), -1, 0 if len(o_nb) >= 3 else 1))
143
+ elif sym == "S":
144
+ o_nb = [n.GetIdx() for n in nbrs if n.GetSymbol() == "O"]
145
+ term = [j for j in o_nb if _is_terminal_oxygen(mol.GetAtomWithIdx(j))]
146
+ if len(o_nb) >= 3:
147
+ out.append(LigandGroup("sulfonate", (i, *term), (i,), -1, 0))
148
+ elif len(nbrs) == 3 and all(n.GetSymbol() == "C" for n in nbrs) and atom.GetFormalCharge() > 0:
149
+ out.append(LigandGroup("sulfonium", (i,), (i,), +1, 0))
150
+ elif sym == "N":
151
+ if atom.GetFormalCharge() > 0 and not any(n.GetFormalCharge() < 0 for n in nbrs):
152
+ out.append(LigandGroup("ammonium", (i,), (i,), +1, 0))
153
+ seen_single.add(i)
154
+ elif not atom.GetIsAromatic() and atom.GetHybridization() == Chem.HybridizationType.SP3 \
155
+ and all(n.GetSymbol() == "C" for n in nbrs) and not _is_amide_like(atom):
156
+ # Basic aliphatic amine. Tertiary first: that is the class detectors treat as cationic.
157
+ rank = 0 if len(nbrs) == 3 else 1
158
+ out.append(LigandGroup("amine", (i,), (i,), +1, rank))
159
+ seen_single.add(i)
160
+ elif is_metal(sym):
161
+ out.append(LigandGroup("metal", (i,), (i,), +1, 0))
162
+ seen_single.add(i)
163
+ if atom.GetFormalCharge() < 0 and sym in ("O", "N", "S") and i not in seen_single:
164
+ covered = any(i in g.atoms for g in out if g.charge < 0)
165
+ if not covered:
166
+ out.append(LigandGroup("anion", (i,), (i,), -1, 2))
167
+ seen_single.add(i)
168
+ # Any remaining nitrogen is a last-resort cation candidate: a detector with
169
+ # different typing rules may have called it charged, and the reported
170
+ # distance will say so unambiguously.
171
+ for atom in mol.GetAtoms():
172
+ if atom.GetSymbol() == "N" and atom.GetIdx() not in seen_single:
173
+ out.append(LigandGroup("nitrogen", (atom.GetIdx(),), (atom.GetIdx(),), +1, 4))
174
+ out.sort(key=lambda g: (g.rank, g.kind, g.atoms))
175
+ return out
176
+
177
+
178
+ def perceive_metals(lig: Ligand) -> list[int]:
179
+ return [a.GetIdx() for a in lig.mol.GetAtoms() if is_metal(a.GetSymbol())]