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/graph.py ADDED
@@ -0,0 +1,611 @@
1
+ """The semantic layer: what a diagram is made of, before it is drawn.
2
+
3
+ :mod:`bindview.scene` is a tree of drawing primitives. That is the right thing to
4
+ serialise to SVG and the wrong thing to interact with: a circle has no identity,
5
+ no tether and no weight. A :class:`Graph` says what the picture *is*:
6
+
7
+ * **nodes** -- ligand atoms, ring centroids and charged groups of the ligand,
8
+ residues, the legend -- each with a stable id, a position, what it is anchored
9
+ to, whether it may be moved and how strongly it is held;
10
+ * **contacts** -- the interactions between a residue node and a ligand node,
11
+ each carrying its own distance, occupancy and confidence;
12
+ * **rigid groups** -- sets of nodes that move as one body. The 2D depiction of
13
+ a ligand is one: dragging any atom of it moves all of them.
14
+
15
+ The layout engine's result is turned into a graph, and the renderers draw from
16
+ the graph. Serialised, the same object is three more things: the model a GUI
17
+ drags, the response a web service returns, and a regression target that does
18
+ not move when the SVG's cosmetics do.
19
+
20
+ The JSON form is versioned (:data:`SCHEMA`, :data:`VERSION`) and documented in
21
+ ``docs/graph-schema.md``. This module is data only: it imports neither RDKit
22
+ nor the layout engine.
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import json
28
+ import math
29
+ import numbers
30
+ from dataclasses import dataclass, field
31
+ from pathlib import Path
32
+ from typing import Any, Iterable, Mapping
33
+
34
+ from .errors import GraphError
35
+
36
+ __all__ = ["Graph", "Node", "Contact", "RigidGroup", "SCHEMA", "VERSION", "NODE_KINDS"]
37
+
38
+ #: Name of the JSON schema.
39
+ SCHEMA = "bindview.graph"
40
+ #: Version of the schema this module writes: ``major.minor``. A reader accepts any
41
+ #: document with its own major version; keys it does not know are kept, not dropped.
42
+ VERSION = "1.0"
43
+ #: What a document says when it has a ``ligand_group`` node that is a residue of a ligand drawn as a
44
+ #: chain (``position`` and its other attributes) or the contact key ``ligand_residue``, all of them
45
+ #: optional keys. Such a residue is no node kind of its own: it is a group of ligand atoms that a contact
46
+ #: attaches to as a whole, which is what a ``ligand_group`` is. A graph that has none of this is
47
+ #: written as 1.0.
48
+ VERSION_CHAIN = "1.1"
49
+ #: ... and "1.2" when it is the graph of an interface (``meta.interface``) or a contact carries a
50
+ #: predicted aligned error (``pae``).
51
+ VERSION_INTERFACE = "1.2"
52
+ #: ... and "1.3" when the residues of an interface's spine stand on a plane, each where it lies in space
53
+ #: (``meta.interface.layout`` is ``"plane"``): the positions of those nodes then mean something, and
54
+ #: ``meta.interface.plane`` says how much.
55
+ VERSION_PLANE = "1.3"
56
+ #: ... and "1.4" when it is the graph of two strands and their base pairs (:class:`bindview.BasePairs`,
57
+ #: ``meta.basepairs``): a ``residue`` node for each nucleotide, a ``ligand_group`` for a ligand beside them,
58
+ #: and contacts between two residue nodes (``base_pair``, ``base_stack``, ``hbond``), the second in ``ligand``.
59
+ VERSION_BASEPAIRS = "1.4"
60
+
61
+ #: The node kinds of schema 1. A ``solvent_site`` is a predicted water on a bridge, in a figure that was
62
+ #: asked for them (``render(solvent_sites=True)``).
63
+ NODE_KINDS = ("ligand_atom", "ligand_group", "ring_centroid", "residue", "solvent_site", "legend")
64
+
65
+
66
+ def _clean(value: Any) -> Any:
67
+ """Plain JSON data: tuples become lists, nothing else changes."""
68
+ if isinstance(value, (tuple, list)):
69
+ return [_clean(v) for v in value]
70
+ if isinstance(value, dict):
71
+ return {str(k): _clean(v) for k, v in value.items()}
72
+ return value
73
+
74
+
75
+ def _num(value: Any, what: str) -> float | None:
76
+ if value is None:
77
+ return None
78
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
79
+ raise GraphError(f"{what} must be a number, not {value!r}")
80
+ if not math.isfinite(value):
81
+ raise GraphError(f"{what} must be a finite number, not {value!r}")
82
+ return float(value)
83
+
84
+
85
+ def _finite(value: Any) -> bool:
86
+ """Is it a number with a value: no word, no truth value, not NaN and not infinite?"""
87
+ return isinstance(value, numbers.Real) and not isinstance(value, bool) and math.isfinite(value)
88
+
89
+
90
+ def _pair(value: Any, what: str) -> tuple[float, float]:
91
+ """Two numbers, as a place or a step on the page is given."""
92
+ if isinstance(value, (list, tuple)) and len(value) == 2 and all(_finite(v) for v in value):
93
+ return (float(value[0]), float(value[1]))
94
+ raise GraphError(f"{what} must be two numbers, not {value!r}")
95
+
96
+
97
+ def _names_of(node: "Node") -> set[str]:
98
+ """What a residue of a figure is called, in small letters: by its label, with its chain, by its number."""
99
+ number = f"{node.attrs.get('number', '')}{node.attrs.get('icode', '')}"
100
+ chain = str(node.attrs.get("chain") or "")
101
+ plain = f"{node.attrs.get('resname', '')}{number}"
102
+ out = {node.label, node.id.removeprefix("R:"), plain, number}
103
+ if chain:
104
+ out |= {f"{chain}:{plain}", f"{chain}:{number}"}
105
+ return {t.lower() for t in out if t}
106
+
107
+
108
+ def _turns(node: "Node") -> bool:
109
+ """Is it a residue that is drawn with atoms? Anything else has no direction of its own."""
110
+ return node.kind == "residue" and node.attrs.get("form") == "fragment"
111
+
112
+
113
+ def _strs(value: Any, what: str) -> tuple[str, ...]:
114
+ if value is None:
115
+ return ()
116
+ if isinstance(value, str) or not isinstance(value, Iterable):
117
+ raise GraphError(f"{what} must be a list of ids, not {value!r}")
118
+ return tuple(str(v) for v in value)
119
+
120
+
121
+ @dataclass
122
+ class Node:
123
+ """One thing in the diagram that has an identity and a place.
124
+
125
+ ``x`` / ``y`` are in the diagram's own frame (add :attr:`Graph.origin` for
126
+ the page coordinates of the SVG); ``None`` means the layout could not place
127
+ the node. ``anchors`` are the nodes this one is tethered to and ``spring``
128
+ the summed weight of those tethers -- how strongly it is held where it is.
129
+ ``contacts`` lists the contacts that reference the node; for a residue they
130
+ are in tether order. Everything specific to a kind lives in ``attrs``.
131
+ """
132
+
133
+ id: str
134
+ kind: str
135
+ label: str
136
+ x: float | None = None
137
+ y: float | None = None
138
+ angle: float = 0.0 # rotation of the node's own drawing, radians
139
+ mirror: bool = False # ... and whether it is drawn mirrored
140
+ group: str | None = None # rigid group the node belongs to
141
+ movable: bool = True
142
+ anchors: tuple[str, ...] = ()
143
+ spring: float | None = None # None: not tethered to anything
144
+ contacts: tuple[str, ...] = ()
145
+ members: tuple[str, ...] = () # ring_centroid / ligand_group: the atoms it stands for
146
+ confidence: float | None = None # pLDDT scale, 0-100
147
+ occupancy: float | None = None # share of the ensemble, 0-1
148
+ attrs: dict[str, Any] = field(default_factory=dict)
149
+
150
+ _CORE = ("id", "kind", "label", "x", "y", "angle", "mirror", "group", "movable", "anchors", "spring",
151
+ "contacts", "members", "confidence", "occupancy")
152
+
153
+ def to_dict(self) -> dict[str, Any]:
154
+ out: dict[str, Any] = {"id": self.id, "kind": self.kind, "label": self.label, "x": self.x, "y": self.y}
155
+ if self.angle:
156
+ out["angle"] = self.angle
157
+ if self.mirror:
158
+ out["mirror"] = True
159
+ if self.group is not None:
160
+ out["group"] = self.group
161
+ out["movable"] = self.movable
162
+ if self.anchors:
163
+ out["anchors"] = list(self.anchors)
164
+ if self.spring is not None:
165
+ out["spring"] = self.spring
166
+ if self.contacts:
167
+ out["contacts"] = list(self.contacts)
168
+ if self.members:
169
+ out["members"] = list(self.members)
170
+ if self.confidence is not None:
171
+ out["confidence"] = self.confidence
172
+ if self.occupancy is not None:
173
+ out["occupancy"] = self.occupancy
174
+ for key in sorted(self.attrs):
175
+ out[key] = _clean(self.attrs[key])
176
+ return out
177
+
178
+ @classmethod
179
+ def from_dict(cls, data: Mapping[str, Any]) -> "Node":
180
+ try:
181
+ ident, kind = str(data["id"]), str(data["kind"])
182
+ except KeyError as exc:
183
+ raise GraphError(f"a node lacks {exc.args[0]!r}: {dict(data)!r}") from None
184
+ return cls(
185
+ id=ident, kind=kind, label=str(data.get("label", "")),
186
+ x=_num(data.get("x"), f"{ident}.x"), y=_num(data.get("y"), f"{ident}.y"),
187
+ angle=_num(data.get("angle", 0.0), f"{ident}.angle") or 0.0, mirror=bool(data.get("mirror", False)),
188
+ group=None if data.get("group") is None else str(data["group"]),
189
+ movable=bool(data.get("movable", True)), anchors=_strs(data.get("anchors"), f"{ident}.anchors"),
190
+ spring=_num(data.get("spring"), f"{ident}.spring"),
191
+ contacts=_strs(data.get("contacts"), f"{ident}.contacts"),
192
+ members=_strs(data.get("members"), f"{ident}.members"),
193
+ confidence=_num(data.get("confidence"), f"{ident}.confidence"),
194
+ occupancy=_num(data.get("occupancy"), f"{ident}.occupancy"),
195
+ attrs={k: v for k, v in data.items() if k not in cls._CORE})
196
+
197
+
198
+ @dataclass
199
+ class Contact:
200
+ """One interaction, between a residue node and a ligand node.
201
+
202
+ ``ligand`` is the node the contact attaches to on the ligand -- an atom, a
203
+ ring centroid or a charged group -- and is ``None`` in a consensus view,
204
+ where a contact stands for a whole set of ligands. ``occupancy`` and
205
+ ``confidence`` belong to the contact, not to the residue. ``ideal``,
206
+ ``min_length`` and ``weight`` describe the tether the layout engine used
207
+ for it: a spring of rest length ``ideal``.
208
+ """
209
+
210
+ id: str
211
+ type: str
212
+ residue: str
213
+ ligand: str | None = None
214
+ drawn: bool = True # False: a contact without direction, which gets no line
215
+ distance: float | None = None # angstrom, as reported
216
+ occupancy: float | None = None # share of the ensemble in which the contact is made
217
+ confidence: float | None = None # pLDDT scale; the contact's own
218
+ label: str | None = None # text printed on the line
219
+ label_t: float | None = None # where along the line it sits, 0 = residue end
220
+ ideal: float | None = None
221
+ min_length: float | None = None
222
+ weight: float | None = None
223
+ site: str = "" # what makes it on the residue: atom | ring | group | residue
224
+ protein_atoms: tuple[str, ...] = ()
225
+ records: tuple[int, ...] = () # indices of the interaction records it stands for
226
+ #: For a ligand drawn as a chain: the residue of the ligand that makes the contact, as ``Lys20`` --
227
+ #: the code and the position in the ligand's own chain. ``None`` for a ligand drawn as atoms.
228
+ ligand_residue: str | None = None
229
+ attrs: dict[str, Any] = field(default_factory=dict)
230
+
231
+ _CORE = ("id", "type", "residue", "ligand", "drawn", "distance", "occupancy", "confidence", "label", "label_t",
232
+ "ideal", "min_length", "weight", "site", "protein_atoms", "records", "ligand_residue")
233
+
234
+ def to_dict(self) -> dict[str, Any]:
235
+ out: dict[str, Any] = {"id": self.id, "type": self.type, "residue": self.residue, "ligand": self.ligand,
236
+ "drawn": self.drawn}
237
+ for key in ("distance", "occupancy", "confidence", "label", "label_t", "ideal", "min_length", "weight"):
238
+ value = getattr(self, key)
239
+ if value is not None:
240
+ out[key] = value
241
+ if self.site:
242
+ out["site"] = self.site
243
+ if self.protein_atoms:
244
+ out["protein_atoms"] = list(self.protein_atoms)
245
+ if self.records:
246
+ out["records"] = list(self.records)
247
+ if self.ligand_residue is not None:
248
+ out["ligand_residue"] = self.ligand_residue
249
+ for key in sorted(self.attrs):
250
+ out[key] = _clean(self.attrs[key])
251
+ return out
252
+
253
+ @classmethod
254
+ def from_dict(cls, data: Mapping[str, Any]) -> "Contact":
255
+ try:
256
+ ident, kind, residue = str(data["id"]), str(data["type"]), str(data["residue"])
257
+ except KeyError as exc:
258
+ raise GraphError(f"a contact lacks {exc.args[0]!r}: {dict(data)!r}") from None
259
+ return cls(
260
+ id=ident, type=kind, residue=residue,
261
+ ligand=None if data.get("ligand") is None else str(data["ligand"]), drawn=bool(data.get("drawn", True)),
262
+ distance=_num(data.get("distance"), f"{ident}.distance"),
263
+ occupancy=_num(data.get("occupancy"), f"{ident}.occupancy"),
264
+ confidence=_num(data.get("confidence"), f"{ident}.confidence"),
265
+ label=None if data.get("label") is None else str(data["label"]),
266
+ label_t=_num(data.get("label_t"), f"{ident}.label_t"), ideal=_num(data.get("ideal"), f"{ident}.ideal"),
267
+ min_length=_num(data.get("min_length"), f"{ident}.min_length"),
268
+ weight=_num(data.get("weight"), f"{ident}.weight"), site=str(data.get("site", "")),
269
+ protein_atoms=_strs(data.get("protein_atoms"), f"{ident}.protein_atoms"),
270
+ records=tuple(int(v) for v in data.get("records", ())),
271
+ ligand_residue=None if data.get("ligand_residue") is None else str(data["ligand_residue"]),
272
+ attrs={k: v for k, v in data.items() if k not in cls._CORE})
273
+
274
+
275
+ @dataclass
276
+ class RigidGroup:
277
+ """Nodes that move as one body: their positions relative to each other are fixed."""
278
+
279
+ id: str
280
+ label: str = ""
281
+ members: tuple[str, ...] = ()
282
+ movable: bool = True
283
+ attrs: dict[str, Any] = field(default_factory=dict)
284
+
285
+ _CORE = ("id", "kind", "label", "members", "movable")
286
+
287
+ def to_dict(self) -> dict[str, Any]:
288
+ out: dict[str, Any] = {"id": self.id, "kind": "rigid", "label": self.label, "members": list(self.members),
289
+ "movable": self.movable}
290
+ for key in sorted(self.attrs):
291
+ out[key] = _clean(self.attrs[key])
292
+ return out
293
+
294
+ @classmethod
295
+ def from_dict(cls, data: Mapping[str, Any]) -> "RigidGroup":
296
+ if "id" not in data:
297
+ raise GraphError(f"a group lacks 'id': {dict(data)!r}")
298
+ if data.get("kind", "rigid") != "rigid":
299
+ raise GraphError(f"group {data['id']!r}: unknown kind {data.get('kind')!r} (schema 1 knows 'rigid')")
300
+ return cls(id=str(data["id"]), label=str(data.get("label", "")),
301
+ members=_strs(data.get("members"), f"{data['id']}.members"),
302
+ movable=bool(data.get("movable", True)),
303
+ attrs={k: v for k, v in data.items() if k not in cls._CORE})
304
+
305
+
306
+ @dataclass
307
+ class Graph:
308
+ """A diagram as nodes, contacts and rigid groups.
309
+
310
+ ``view`` names the renderer the graph was laid out for (``detailed``,
311
+ ``schematic``, ``difference``, ``consensus``). Positions are in the
312
+ diagram's own frame, in SVG user units; ``origin`` is the offset of that
313
+ frame on the page and ``size`` the page. ``springs`` holds the layout
314
+ engine's constants, so that whoever moves a node can know what held it.
315
+ """
316
+
317
+ view: str
318
+ bond_length: float
319
+ nodes: list[Node] = field(default_factory=list)
320
+ contacts: list[Contact] = field(default_factory=list)
321
+ groups: list[RigidGroup] = field(default_factory=list)
322
+ origin: tuple[float, float] = (0.0, 0.0)
323
+ size: tuple[float, float] | None = None
324
+ ensemble: str | None = None # what the contacts' occupancy is a share of
325
+ springs: dict[str, float] = field(default_factory=dict)
326
+ panels: list[dict[str, Any]] = field(default_factory=list) # difference view: one per ligand
327
+ meta: dict[str, Any] = field(default_factory=dict)
328
+
329
+ # -- lookups -----------------------------------------------------------
330
+ def find(self, ident: str) -> Node | None:
331
+ """The node with exactly this id, or None."""
332
+ for node in self.nodes:
333
+ if node.id == ident:
334
+ return node
335
+ return None
336
+
337
+ def node(self, ident: str) -> Node:
338
+ """The node with this id, or the residue that the figure calls so: ``"R:A:MET743"``, ``"Met743"``,
339
+ ``"A:Met743"``, ``"743"``; and ``"ligand"`` for any atom of it (it is one body)."""
340
+ hit = self.find(ident)
341
+ if hit is not None:
342
+ return hit
343
+ wanted = ident.strip().lower()
344
+ named = [n for n in self.nodes if n.kind == "residue" and wanted in _names_of(n)]
345
+ if len(named) == 1:
346
+ return named[0]
347
+ if len(named) > 1:
348
+ raise GraphError(f"{ident!r} is {len(named)} nodes of this graph ({', '.join(n.id for n in named)}): "
349
+ "name one by its id")
350
+ if wanted == "ligand":
351
+ atoms = [n for n in self.nodes if n.kind == "ligand_atom" and n.group is not None]
352
+ if atoms:
353
+ return atoms[0]
354
+ raise GraphError(f"no node {ident!r} in the graph")
355
+
356
+ def contact(self, ident: str) -> Contact:
357
+ """The contact with this id."""
358
+ for c in self.contacts:
359
+ if c.id == ident:
360
+ return c
361
+ raise GraphError(f"no contact {ident!r} in the graph")
362
+
363
+ def group(self, ident: str) -> RigidGroup:
364
+ """The rigid group with this id."""
365
+ for g in self.groups:
366
+ if g.id == ident:
367
+ return g
368
+ raise GraphError(f"no group {ident!r} in the graph")
369
+
370
+ def of_kind(self, kind: str) -> list[Node]:
371
+ """All nodes of a kind: ``"residue"``, ``"ligand_atom"``, ..."""
372
+ return [n for n in self.nodes if n.kind == kind]
373
+
374
+ def page(self, node: "Node | str") -> tuple[float, float] | None:
375
+ """Where a node is on the page of the SVG (``None`` if it was not placed)."""
376
+ n = self.node(node) if isinstance(node, str) else node
377
+ if n.x is None or n.y is None:
378
+ return None
379
+ return (n.x + self.origin[0], n.y + self.origin[1])
380
+
381
+ # -- editing -----------------------------------------------------------
382
+ def move(self, ident: str, dx: float, dy: float) -> list[str]:
383
+ """Move a node the way a drag does, and return the ids of what moved.
384
+
385
+ A node of a rigid group takes the whole group with it: the depiction
386
+ of a ligand drawn as atoms is one body, so every atom, ring centroid
387
+ and group node of it shifts by the same vector. A ligand drawn as a
388
+ chain is not one body: each of its residues moves alone, and takes
389
+ with it only what is bonded to it outside the chain. Any other node
390
+ moves alone. Nothing else follows -- tethers are springs, not rods,
391
+ and whether to relax the layout afterwards is the caller's decision.
392
+ """
393
+ if not (_finite(dx) and _finite(dy)):
394
+ raise GraphError(f"move takes a step of two finite numbers, not dx={dx!r} and dy={dy!r}")
395
+ dx, dy = float(dx), float(dy)
396
+ node = self.node(ident)
397
+ if not node.movable:
398
+ raise GraphError(f"node {ident!r} is not movable")
399
+ targets = [node]
400
+ if node.group is not None:
401
+ group = self.group(node.group)
402
+ if not group.movable:
403
+ raise GraphError(f"group {group.id!r} is not movable")
404
+ members = set(group.members)
405
+ targets = [n for n in self.nodes if n.id in members]
406
+ if node.kind == "legend":
407
+ offset = self.legend_offset()
408
+ node.attrs["offset"] = [offset[0] + dx, offset[1] + dy]
409
+ for n in targets:
410
+ if n.x is not None and n.y is not None:
411
+ n.x, n.y = n.x + dx, n.y + dy
412
+ return [n.id for n in targets]
413
+
414
+ def rotate(self, ident: str, degrees: float) -> list[str]:
415
+ """Turn a node about itself, clockwise on the page, and return the ids of what turned.
416
+
417
+ A residue that is drawn with atoms turns on the spot; its name and its lines follow when the figure is
418
+ drawn again. One that is drawn without them (an eyelash, a bubble, a name) faces the ligand wherever it
419
+ stands, and there is nothing to turn. ``"ligand"`` turns a ligand that is drawn as atoms about its
420
+ middle and leaves the residues where they are; ``"figure"`` turns everything, the ligand with its
421
+ residues, about the ligand's middle.
422
+ """
423
+ if not _finite(degrees):
424
+ raise GraphError(f"rotate takes an angle in degrees, a finite number, not {degrees!r}")
425
+ angle = math.radians(float(degrees))
426
+ if ident in ("ligand", "figure") and self.find(ident) is None:
427
+ group = self._body()
428
+ placed = [n for n in self.nodes if n.id in set(group.members) and n.x is not None and n.y is not None]
429
+ atoms = [n for n in placed if n.kind == "ligand_atom"] or placed
430
+ cx = sum(n.x for n in atoms if n.x is not None) / len(atoms)
431
+ cy = sum(n.y for n in atoms if n.y is not None) / len(atoms)
432
+ if ident == "figure":
433
+ placed = [n for n in self.nodes if n.kind != "legend" and n.x is not None and n.y is not None]
434
+ c, s = math.cos(angle), math.sin(angle)
435
+ for n in placed:
436
+ dx, dy = float(n.x or 0.0) - cx, float(n.y or 0.0) - cy
437
+ n.x, n.y = cx + dx * c - dy * s, cy + dx * s + dy * c
438
+ if n.kind == "residue" and _turns(n):
439
+ n.angle += angle
440
+ return [n.id for n in placed]
441
+ node = self.node(ident)
442
+ if not _turns(node):
443
+ raise GraphError(f"{node.label} is drawn as {node.attrs.get('form', node.kind)!r}: it has no atoms to turn, and "
444
+ "faces the ligand wherever it stands")
445
+ node.angle += angle
446
+ return [node.id]
447
+
448
+ def flip(self, ident: str) -> list[str]:
449
+ """Mirror a residue that is drawn with atoms in its own axis, as a page is turned over. (A ligand is not
450
+ flipped: its drawing shows its stereochemistry.)"""
451
+ node = self.node(ident)
452
+ if not _turns(node):
453
+ raise GraphError(f"{node.label} is drawn as {node.attrs.get('form', node.kind)!r}: there is nothing to flip")
454
+ node.mirror = not node.mirror
455
+ return [node.id]
456
+
457
+ def legend_offset(self) -> tuple[float, float]:
458
+ """How far the legend was moved from where the page puts it; ``(0, 0)`` for a graph without one."""
459
+ legend = self.find("legend")
460
+ if legend is None or "offset" not in legend.attrs:
461
+ return (0.0, 0.0)
462
+ return _pair(legend.attrs["offset"], "the offset of the legend")
463
+
464
+ def _body(self) -> RigidGroup:
465
+ bodies = [g for g in self.groups if g.movable and g.id == "ligand"]
466
+ if not bodies:
467
+ raise GraphError("this graph has no ligand that is one body: a ligand drawn as a chain is moved residue by "
468
+ "residue")
469
+ return bodies[0]
470
+
471
+ # -- checking ----------------------------------------------------------
472
+ def validate(self) -> "Graph":
473
+ """Raise :class:`GraphError` unless ids are unique, every reference resolves, and the scale and every
474
+ place are numbers that a figure can be drawn from."""
475
+ if not _finite(self.bond_length) or self.bond_length <= 0:
476
+ raise GraphError(f"bond_length must be a positive number, not {self.bond_length!r}")
477
+ self.legend_offset()
478
+ ids: set[str] = set()
479
+ for n in self.nodes:
480
+ if n.id in ids:
481
+ raise GraphError(f"node id {n.id!r} occurs twice")
482
+ ids.add(n.id)
483
+ for name in ("x", "y", "angle"):
484
+ value = getattr(n, name)
485
+ if value is not None and not _finite(value):
486
+ raise GraphError(f"{n.id}.{name} must be a finite number, not {value!r}")
487
+ if n.kind not in NODE_KINDS:
488
+ raise GraphError(f"node {n.id!r}: unknown kind {n.kind!r}; schema {VERSION} knows "
489
+ f"{', '.join(NODE_KINDS)}")
490
+ cids: set[str] = set()
491
+ for c in self.contacts:
492
+ if c.id in cids:
493
+ raise GraphError(f"contact id {c.id!r} occurs twice")
494
+ cids.add(c.id)
495
+ if c.residue not in ids:
496
+ raise GraphError(f"contact {c.id!r} refers to an unknown node {c.residue!r}")
497
+ if c.ligand is not None and c.ligand not in ids:
498
+ raise GraphError(f"contact {c.id!r} refers to an unknown node {c.ligand!r}")
499
+ if c.occupancy is not None and not 0.0 <= c.occupancy <= 1.0:
500
+ raise GraphError(f"contact {c.id!r}: occupancy {c.occupancy!r} is not between 0 and 1")
501
+ gids = {g.id for g in self.groups}
502
+ if len(gids) != len(self.groups):
503
+ raise GraphError("a group id occurs twice")
504
+ for g in self.groups:
505
+ for m in g.members:
506
+ if m not in ids:
507
+ raise GraphError(f"group {g.id!r} lists an unknown node {m!r}")
508
+ for n in self.nodes:
509
+ if n.group is not None and n.group not in gids:
510
+ raise GraphError(f"node {n.id!r} belongs to an unknown group {n.group!r}")
511
+ for ref in n.anchors + n.members:
512
+ if ref not in ids:
513
+ raise GraphError(f"node {n.id!r} refers to an unknown node {ref!r}")
514
+ for ref in n.contacts:
515
+ if ref not in cids:
516
+ raise GraphError(f"node {n.id!r} refers to an unknown contact {ref!r}")
517
+ return self
518
+
519
+ # -- JSON --------------------------------------------------------------
520
+ def to_dict(self) -> dict[str, Any]:
521
+ """The graph as plain data (``docs/graph-schema.md``)."""
522
+ chain = (any(n.kind == "ligand_group" and "position" in n.attrs for n in self.nodes)
523
+ or any(c.ligand_residue is not None for c in self.contacts))
524
+ interface = "interface" in self.meta or any("pae" in c.attrs for c in self.contacts)
525
+ version = VERSION_INTERFACE if interface else VERSION_CHAIN if chain else VERSION
526
+ if interface and (self.meta.get("interface") or {}).get("layout") == "plane":
527
+ version = VERSION_PLANE
528
+ if "basepairs" in self.meta:
529
+ version = VERSION_BASEPAIRS
530
+ out: dict[str, Any] = {"schema": SCHEMA, "version": version, "view": self.view,
531
+ "bond_length": self.bond_length, "origin": list(self.origin)}
532
+ if self.size is not None:
533
+ out["size"] = list(self.size)
534
+ if self.ensemble is not None:
535
+ out["ensemble"] = self.ensemble
536
+ if self.springs:
537
+ out["springs"] = {k: self.springs[k] for k in sorted(self.springs)}
538
+ if self.panels:
539
+ out["panels"] = _clean(self.panels)
540
+ if self.meta:
541
+ out["meta"] = {k: _clean(self.meta[k]) for k in sorted(self.meta)}
542
+ out["groups"] = [g.to_dict() for g in self.groups]
543
+ out["nodes"] = [n.to_dict() for n in self.nodes]
544
+ out["contacts"] = [c.to_dict() for c in self.contacts]
545
+ return out
546
+
547
+ def to_json(self, path: "str | Path | None" = None, indent: int | None = 1) -> str:
548
+ """The graph as JSON text (key order fixed, floats in full precision, so the same graph
549
+ always gives the same bytes). Written to ``path`` when given; always returned."""
550
+ text = json.dumps(self.to_dict(), indent=indent, ensure_ascii=False) + "\n"
551
+ if path is not None:
552
+ try:
553
+ Path(path).write_text(text, encoding="utf-8")
554
+ except OSError as exc:
555
+ raise GraphError(f"cannot write {path}: {exc}") from exc
556
+ return text
557
+
558
+ @classmethod
559
+ def from_dict(cls, data: Mapping[str, Any]) -> "Graph":
560
+ """A graph from plain data; refused where it is not one."""
561
+ if not isinstance(data, Mapping) or data.get("schema") != SCHEMA:
562
+ raise GraphError(f"not a {SCHEMA} document (its 'schema' is {data.get('schema')!r})"
563
+ if isinstance(data, Mapping) else "a graph document must be a JSON object")
564
+ version = str(data.get("version", ""))
565
+ if version.split(".")[0] != VERSION.split(".")[0]:
566
+ raise GraphError(f"graph schema version {version!r} is not supported: this is bindview.graph {VERSION}, "
567
+ f"which reads version {VERSION.split('.')[0]}.x")
568
+ try:
569
+ size = data.get("size")
570
+ graph = cls(
571
+ view=str(data["view"]), bond_length=_num(data["bond_length"], "bond_length") or 0.0,
572
+ nodes=[Node.from_dict(n) for n in data.get("nodes", ())],
573
+ contacts=[Contact.from_dict(c) for c in data.get("contacts", ())],
574
+ groups=[RigidGroup.from_dict(g) for g in data.get("groups", ())],
575
+ origin=_pair(data.get("origin", (0.0, 0.0)), "origin"),
576
+ size=None if size is None else _pair(size, "size"),
577
+ ensemble=None if data.get("ensemble") is None else str(data["ensemble"]),
578
+ springs={str(k): float(v) for k, v in dict(data.get("springs", {})).items()},
579
+ panels=[dict(p) for p in data.get("panels", ())], meta=dict(data.get("meta", {})))
580
+ except KeyError as exc:
581
+ raise GraphError(f"the graph document lacks {exc.args[0]!r}") from None
582
+ except (TypeError, ValueError, IndexError) as exc:
583
+ raise GraphError(f"malformed graph document: {exc}") from exc
584
+ return graph.validate()
585
+
586
+ @classmethod
587
+ def from_json(cls, source: "str | Path") -> "Graph":
588
+ """Read a graph from a file or from JSON text. A ``Path`` is a file; a string is one where it is the name
589
+ of a file that is there, and JSON text where it is not."""
590
+ text, file = str(source), isinstance(source, Path) or _names_a_file(str(source))
591
+ if file:
592
+ try:
593
+ text = Path(source).read_text(encoding="utf-8")
594
+ except (OSError, ValueError) as exc: # (ValueError: it is not text)
595
+ raise GraphError(f"cannot read {source}: {exc}") from exc
596
+ try:
597
+ data = json.loads(text.removeprefix("\ufeff"))
598
+ except ValueError as exc:
599
+ if file:
600
+ raise GraphError(f"{source} is not valid JSON: {exc}") from exc
601
+ shown = repr(text if len(text) <= 60 else text[:60] + "...")
602
+ raise GraphError(f"not valid JSON, and not the name of a file that is there: {shown} ({exc})") from exc
603
+ return cls.from_dict(data)
604
+
605
+
606
+ def _names_a_file(text: str) -> bool:
607
+ """Is it the name of a file that is there? No JSON document is: a name has no line break in it."""
608
+ try:
609
+ return "\n" not in text and Path(text).is_file()
610
+ except (OSError, ValueError): # too long for a name, or with a character no name has
611
+ return False