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.
- bindview/__init__.py +88 -0
- bindview/__main__.py +6 -0
- bindview/align.py +493 -0
- bindview/arrange.js +347 -0
- bindview/arrange.py +248 -0
- bindview/backends.py +290 -0
- bindview/basepairs.py +1711 -0
- bindview/chains.py +264 -0
- bindview/chem.py +57 -0
- bindview/clearance.py +123 -0
- bindview/cli.py +990 -0
- bindview/compare.py +1854 -0
- bindview/confidence.py +531 -0
- bindview/consensus.py +303 -0
- bindview/covalent.py +220 -0
- bindview/depict.py +790 -0
- bindview/detect.py +378 -0
- bindview/diagram.py +1891 -0
- bindview/distance_table.py +589 -0
- bindview/ensemble.py +787 -0
- bindview/errors.py +47 -0
- bindview/exposure.py +207 -0
- bindview/features.py +179 -0
- bindview/fingerprint.py +469 -0
- bindview/fragments.py +304 -0
- bindview/geometry.py +482 -0
- bindview/graph.py +611 -0
- bindview/graphbuild.py +431 -0
- bindview/interactions.py +418 -0
- bindview/interactive.py +334 -0
- bindview/interface.py +1329 -0
- bindview/ions.py +155 -0
- bindview/layout/__init__.py +15 -0
- bindview/layout/body.py +421 -0
- bindview/layout/engine.py +1084 -0
- bindview/layout/field.py +261 -0
- bindview/ligand.py +583 -0
- bindview/near.py +67 -0
- bindview/options.py +92 -0
- bindview/pae.py +991 -0
- bindview/peptide.py +610 -0
- bindview/plane.py +320 -0
- bindview/polymer.py +678 -0
- bindview/py.typed +0 -0
- bindview/report.py +1407 -0
- bindview/residues.py +296 -0
- bindview/resolve.py +493 -0
- bindview/scene.py +239 -0
- bindview/solvent.py +254 -0
- bindview/structure.py +1145 -0
- bindview/styles/__init__.py +2 -0
- bindview/styles/absence.py +180 -0
- bindview/styles/base.py +2128 -0
- bindview/styles/closeup.py +146 -0
- bindview/styles/detailed.py +690 -0
- bindview/styles/ligand_draw.py +289 -0
- bindview/styles/mixed.py +70 -0
- bindview/styles/polymer_draw.py +354 -0
- bindview/styles/rings.py +75 -0
- bindview/styles/schematic.py +311 -0
- bindview/styles/summary.py +147 -0
- bindview/svg.py +310 -0
- bindview/textmetrics.py +64 -0
- bindview/theme.py +317 -0
- bindview-0.1.0.dist-info/METADATA +270 -0
- bindview-0.1.0.dist-info/RECORD +70 -0
- bindview-0.1.0.dist-info/WHEEL +4 -0
- bindview-0.1.0.dist-info/entry_points.txt +2 -0
- bindview-0.1.0.dist-info/licenses/LICENSE +21 -0
- bindview-0.1.0.dist-info/licenses/NOTICE +48 -0
bindview/diagram.py
ADDED
|
@@ -0,0 +1,1891 @@
|
|
|
1
|
+
"""The public entry point: :class:`Diagram` and :class:`RenderResult`.
|
|
2
|
+
|
|
3
|
+
``Diagram.from_structure`` does the chemistry once (build the named-atom
|
|
4
|
+
ligand, resolve every interaction to what makes it); ``render`` can then be
|
|
5
|
+
called for any style and theme. A render never raises for a complex that is
|
|
6
|
+
merely awkward: it returns a result whose ``status`` says what happened.
|
|
7
|
+
|
|
8
|
+
========== ====================================================================
|
|
9
|
+
status meaning
|
|
10
|
+
========== ====================================================================
|
|
11
|
+
ok an atom-level diagram, every hard requirement met
|
|
12
|
+
empty analysed, no interactions; the figure says so explicitly
|
|
13
|
+
degraded a diagram was drawn but something was left out or assumed (see
|
|
14
|
+
``warnings``): a record that could not be attached, unknown bond
|
|
15
|
+
orders, ...
|
|
16
|
+
unreadable the complex cannot be laid out legibly at the requested figure size;
|
|
17
|
+
by default a per-residue summary table is drawn instead
|
|
18
|
+
========== ====================================================================
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import copy
|
|
24
|
+
import math
|
|
25
|
+
import numbers
|
|
26
|
+
from dataclasses import dataclass, field, replace
|
|
27
|
+
from pathlib import Path
|
|
28
|
+
from typing import TYPE_CHECKING, Any, Iterable, Mapping, Sequence
|
|
29
|
+
|
|
30
|
+
import numpy as np
|
|
31
|
+
|
|
32
|
+
from .backends import Polymer, SmallMolecule, choose_backend, describe as describe_backend
|
|
33
|
+
from .clearance import keep_lines_off_words
|
|
34
|
+
from .plane import ERROR_MAX, KEPT_MIN, SCALE_BAR
|
|
35
|
+
from .polymer import MIN_PITCH as POLYMER_MIN_PITCH, piece_sides, shown_atoms
|
|
36
|
+
from .confidence import MARK, Confidence, ModelConfidence, look_of, pocket_atoms
|
|
37
|
+
from .covalent import as_bound, covalent_bonds, drop_bonded
|
|
38
|
+
from .depict import Depiction
|
|
39
|
+
from .errors import GraphError, RenderError
|
|
40
|
+
from .exposure import BURIAL_WARNING_BELOW, WATER_NAMES, Burial, burial_warning, structure_burial
|
|
41
|
+
from .fragments import check_detail
|
|
42
|
+
from .graph import Graph, Node
|
|
43
|
+
from .graphbuild import diagram_graph, poses_from
|
|
44
|
+
from .interactions import (Interaction, InteractionType, check_confidence_scale, coerce_interactions,
|
|
45
|
+
load_interactions)
|
|
46
|
+
from .interactive import NOTHING_TO_POINT_AT, ROOT_CLASS
|
|
47
|
+
from .ions import bridges, holders, seat, with_ions, without_the_bridge
|
|
48
|
+
from .layout import LayoutParams, LayoutResult, LigandField, audit_layout, layout_bodies, layout_key
|
|
49
|
+
from .ligand import Ligand, build_ligand
|
|
50
|
+
from .pae import Pae, PaeDraws, pae_key, read_pae
|
|
51
|
+
from .residues import format_residue_label
|
|
52
|
+
from .resolve import ResolvedInteraction, resolve_interactions
|
|
53
|
+
from .scene import Group, Item, Paint, Rect, Scene, Span, Text, items_bounds
|
|
54
|
+
from .solvent import VALIDATION, SolventSite, has_waters, predict_solvent_sites
|
|
55
|
+
from .structure import ResidueKey, Structure, read_structure
|
|
56
|
+
from .styles.absence import Absence, absence, from_whom, mark_groups
|
|
57
|
+
from .styles.closeup import atom_hits, closeups
|
|
58
|
+
from .styles.mixed import style_for, unknown_residues
|
|
59
|
+
from .styles.base import (Context, LegendEntry, RenderOptions, beyond_any_page, confidence_legend,
|
|
60
|
+
group_residues, legend_group, page_that_would_do, plddt_legend, split_along_chain,
|
|
61
|
+
too_small_on_page)
|
|
62
|
+
from .styles.summary import summary_table, text_block, wrap_text
|
|
63
|
+
from .svg import svg_and_css
|
|
64
|
+
from .textmetrics import CAP_HEIGHT, text_width
|
|
65
|
+
from .theme import Metrics, Palette, get_palette, scheme
|
|
66
|
+
|
|
67
|
+
if TYPE_CHECKING: # pragma: no cover
|
|
68
|
+
from .consensus import ResidueShare
|
|
69
|
+
from .fingerprint import Fingerprint
|
|
70
|
+
|
|
71
|
+
__all__ = ["Diagram", "RenderResult", "Quality", "STYLES"]
|
|
72
|
+
|
|
73
|
+
_PX_PER_MM = 96.0 / 25.4
|
|
74
|
+
_PT_PER_PX = 0.75
|
|
75
|
+
#: Bond lengths tried, largest first, when the caller does not fix one.
|
|
76
|
+
_BOND_LENGTHS = (30.0, 26.0, 22.0, 19.0)
|
|
77
|
+
#: The longest bond that a figure is drawn with: ten times the longest that is tried where none is asked for. At
|
|
78
|
+
#: its own size such a figure has 79 mm to a bond, far more than a page holds of a ligand, and what a layout
|
|
79
|
+
#: takes of memory grows with the length of a bond.
|
|
80
|
+
_BOND_LENGTH_MAX = 10.0 * _BOND_LENGTHS[0]
|
|
81
|
+
#: A ligand drawn as a chain that is too crowded to lay out is tried again with its residues
|
|
82
|
+
#: further apart, in these steps (bond lengths from one residue to the next). Shrinking, which
|
|
83
|
+
#: is what helps a ligand drawn as atoms, would crowd a chain further.
|
|
84
|
+
_CHAIN_PITCHES = (0.9, 1.0, 1.1, 1.2, 1.35, 1.55, 1.8, 2.1, 2.5, 3.0)
|
|
85
|
+
#: A short peptide in a closed groove has two or three residues of the protein for each of its own,
|
|
86
|
+
#: and each of those needs its place beside the column. When the first layout fails and there are
|
|
87
|
+
#: that many, the next one is not the next step but the pitch at which there is about this much
|
|
88
|
+
#: room (in bond lengths) for every residue of the protein per residue of the ligand.
|
|
89
|
+
_ROOM_PER_RESIDUE = 0.9
|
|
90
|
+
#: ... and how many layouts of a chain are tried before the best of them is taken for what there is.
|
|
91
|
+
_CHAIN_ATTEMPTS = 6
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
#: How many a diagram keeps at most of what it keeps of its figures, each kind by itself: the figures as they
|
|
95
|
+
#: were drawn, the fields round the ligand, and the placements of the residues. The one that was used longest
|
|
96
|
+
#: ago goes first. A figure that is asked for again after it went is drawn again on a placement that stayed,
|
|
97
|
+
#: which costs a drawing and no layout.
|
|
98
|
+
_KEPT_AT_MOST = {"figure": 32, "field": 32, "layout": 128}
|
|
99
|
+
|
|
100
|
+
STYLES = ("detailed", "schematic")
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
@dataclass(frozen=True)
|
|
104
|
+
class Quality:
|
|
105
|
+
"""Measured properties of a laid-out diagram."""
|
|
106
|
+
|
|
107
|
+
width: float # natural size, SVG user units (px at 96 dpi)
|
|
108
|
+
height: float
|
|
109
|
+
bond_length: float
|
|
110
|
+
n_residues: int
|
|
111
|
+
n_interactions: int
|
|
112
|
+
overlaps: int # residue pairs that overlap; 0 for a valid layout
|
|
113
|
+
unplaced: int # residues the engine could not seat
|
|
114
|
+
line_crossings: int # interaction lines crossing each other
|
|
115
|
+
bond_crossings: int # interaction lines crossing ligand bonds
|
|
116
|
+
max_stretch: float # longest link relative to its ideal length
|
|
117
|
+
min_font_pt: float # smallest text when printed at the figure size
|
|
118
|
+
#: Figure width at which the smallest text reaches the minimum; infinite where no width does,
|
|
119
|
+
#: because the minimum is above what the text is at full size.
|
|
120
|
+
required_width_mm: float
|
|
121
|
+
readable: bool
|
|
122
|
+
ligand_width: float = 0.0 # width of the ligand drawing alone
|
|
123
|
+
estimated: bool = False # True when no layout was run: sizes are lower bounds
|
|
124
|
+
link_hits: int = 0 # interaction lines passing through another residue
|
|
125
|
+
ligand_height: float = 0.0 # height of the ligand drawing alone
|
|
126
|
+
#: Boxes on a plane: are they, as drawn, still a faithful picture of where the residues lie
|
|
127
|
+
#: (:attr:`bindview.plane.Fidelity.ok`)? Always true of every other figure.
|
|
128
|
+
faithful: bool = True
|
|
129
|
+
|
|
130
|
+
@property
|
|
131
|
+
def valid(self) -> bool:
|
|
132
|
+
"""Does nothing overlap, and was every residue placed?"""
|
|
133
|
+
return self.overlaps == 0 and self.unplaced == 0 and self.link_hits == 0 and self.faithful
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
@dataclass
|
|
137
|
+
class RenderResult:
|
|
138
|
+
status: str
|
|
139
|
+
svg: str | None
|
|
140
|
+
figure: str # diagram | empty | summary | none
|
|
141
|
+
warnings: list[str] = field(default_factory=list)
|
|
142
|
+
quality: Quality | None = None
|
|
143
|
+
path: Path | None = None
|
|
144
|
+
style: str = ""
|
|
145
|
+
theme: str = ""
|
|
146
|
+
scene: Scene | None = field(default=None, repr=False)
|
|
147
|
+
#: Page coordinates of every ligand atom, keyed by structure-file atom name
|
|
148
|
+
#: (only for atom-level figures). This is the map the library exists for:
|
|
149
|
+
#: overlays and hit regions on a web page can be positioned from it.
|
|
150
|
+
atoms: dict[str, tuple[float, float]] = field(default_factory=dict, repr=False)
|
|
151
|
+
#: Figure-level confidence that was drawn (ipTM, pocket and ligand pLDDT, the
|
|
152
|
+
#: caller's flag), or ``None`` when the model carries none or it was switched off.
|
|
153
|
+
confidence: dict[str, Any] | None = None
|
|
154
|
+
#: What the figure says beside its drawing, as plain data. Of a diagram: how a ligand with a chain of
|
|
155
|
+
#: residues is drawn (``ligand``), what an interface says of itself (``interface``), the predicted
|
|
156
|
+
#: waters (``solvent_sites``), the residues another protein lacks (``absent``) and what the atoms drawn
|
|
157
|
+
#: of a residue stand at (``plddt_basis``), each where it applies. Of a comparison view: the alignment
|
|
158
|
+
#: decision, the shared / only-A / only-B classification or the consensus rows.
|
|
159
|
+
data: dict[str, Any] = field(default_factory=dict, repr=False)
|
|
160
|
+
#: The figure as nodes, contacts and rigid groups (see :mod:`bindview.graph`): what was laid out,
|
|
161
|
+
#: before it became ink. ``None`` when no node-level figure was drawn (empty, summary, none).
|
|
162
|
+
graph: Graph | None = field(default=None, repr=False)
|
|
163
|
+
#: The ligand's solvent-accessible surface free and in the complex (square angstrom) and the
|
|
164
|
+
#: buried fraction, with whether it fell below the calibrated cut. ``None`` without a structure.
|
|
165
|
+
burial: dict[str, Any] | None = None
|
|
166
|
+
#: The words the figure has around its drawing, in their order: the line of confidence numbers under
|
|
167
|
+
#: the title, a warning above the drawing, the notes under the key. Whether they are drawn or were left
|
|
168
|
+
#: off (``bare=True``, ``caption=False``): a figure without them takes them into its caption.
|
|
169
|
+
notes: list[str] = field(default_factory=list)
|
|
170
|
+
#: The style sheet that the figure goes with, where it was asked for apart (``stylesheet="external"``): for
|
|
171
|
+
#: the page, once for all its figures (:func:`bindview.stylesheet`).
|
|
172
|
+
css: str | None = field(default=None, repr=False)
|
|
173
|
+
|
|
174
|
+
@property
|
|
175
|
+
def ok(self) -> bool:
|
|
176
|
+
"""Is it the diagram that was asked for, with nothing left out or assumed (status ``ok``)? Not so where the
|
|
177
|
+
figure is drawn and says that something is missing, nor where another figure or none was drawn."""
|
|
178
|
+
return self.status == "ok"
|
|
179
|
+
|
|
180
|
+
@property
|
|
181
|
+
def is_empty(self) -> bool:
|
|
182
|
+
"""Is it the figure of a complex in which no contact was found?"""
|
|
183
|
+
return self.status == "empty"
|
|
184
|
+
|
|
185
|
+
def __str__(self) -> str:
|
|
186
|
+
return f"<RenderResult {self.status}: {self.figure}, {len(self.warnings)} warning(s)>"
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
@dataclass
|
|
190
|
+
class _Composed:
|
|
191
|
+
scene: Scene
|
|
192
|
+
layout: LayoutResult
|
|
193
|
+
quality: Quality
|
|
194
|
+
notes: list[str]
|
|
195
|
+
atoms: dict[str, tuple[float, float]] = field(default_factory=dict)
|
|
196
|
+
graph: Graph | None = None
|
|
197
|
+
#: Where atoms of residues are drawn at a level of detail that was asked for and the model has
|
|
198
|
+
#: confidence: what each of them is drawn at, ``"atom"`` (its own value) or ``"residue"``.
|
|
199
|
+
basis: "str | None" = None
|
|
200
|
+
#: Does a contact stand on a glow for its predicted aligned error?
|
|
201
|
+
glows: bool = False
|
|
202
|
+
#: What a figure that answers the pointer has beside (:mod:`bindview.styles.closeup`): made when it is
|
|
203
|
+
#: first asked for, from what the figure was drawn from.
|
|
204
|
+
parts: "tuple[Any, ...] | None" = field(default=None, repr=False)
|
|
205
|
+
over: "list[Group] | None" = field(default=None, repr=False)
|
|
206
|
+
|
|
207
|
+
def beside(self) -> list[Group]:
|
|
208
|
+
if self.over is None:
|
|
209
|
+
self.over = []
|
|
210
|
+
if self.parts is not None:
|
|
211
|
+
style_obj, ctx, bodies, poses, fld, params, content, box = self.parts
|
|
212
|
+
made = closeups(ctx, bodies, poses, fld, params, style_obj.settings, box) + atom_hits(ctx)
|
|
213
|
+
for g in made:
|
|
214
|
+
g.translate = content.translate
|
|
215
|
+
self.over = made
|
|
216
|
+
return self.over
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
class _Same:
|
|
220
|
+
"""An object for what it is and not for what it says: how the key of a kept figure names what a diagram holds as
|
|
221
|
+
one thing and has no value to compare by (its ligand, its structure, the confidence of its model)."""
|
|
222
|
+
|
|
223
|
+
__slots__ = ("it",)
|
|
224
|
+
|
|
225
|
+
def __init__(self, it: Any) -> None:
|
|
226
|
+
self.it = it
|
|
227
|
+
|
|
228
|
+
def __eq__(self, other: object) -> bool:
|
|
229
|
+
return isinstance(other, _Same) and other.it is self.it
|
|
230
|
+
|
|
231
|
+
def __hash__(self) -> int:
|
|
232
|
+
return id(self.it)
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
#: What ``interactions`` can be in the place of a table: make one from the positions of the heavy atoms.
|
|
236
|
+
DISTANCES = "distances"
|
|
237
|
+
|
|
238
|
+
#: How the sentence on the drawn model of an ensemble ends (:meth:`bindview.ensemble.Ensemble.diagram`).
|
|
239
|
+
_WHOSE_DISTANCES = " Distances are that model's."
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
class Diagram:
|
|
243
|
+
"""A ligand, its named atoms, and the interactions resolved onto them."""
|
|
244
|
+
|
|
245
|
+
def __init__(self, ligand: Ligand, interactions: Sequence[ResolvedInteraction], *,
|
|
246
|
+
structure: Structure | None = None, ligand_key: ResidueKey | None = None,
|
|
247
|
+
name: str | None = None, source: str = "supplied",
|
|
248
|
+
warnings: Sequence[str] = (), confidence: Confidence | None = None,
|
|
249
|
+
ensemble: str | None = None, ligand_as: str = "auto",
|
|
250
|
+
detail: "str | Mapping[str, str | None] | None" = None) -> None:
|
|
251
|
+
self.ligand = ligand
|
|
252
|
+
#: How the ligand is drawn -- as atoms or as a chain of residues -- and why
|
|
253
|
+
#: (:mod:`bindview.backends`). ``ligand_as`` is ``"auto"``, ``"atoms"`` or ``"chain"``.
|
|
254
|
+
self.backend: "SmallMolecule | Polymer" = choose_backend(ligand, ligand_as)
|
|
255
|
+
#: How much of a residue is drawn where it is drawn with atoms, on either side: of the
|
|
256
|
+
#: ``"ligand"`` (where it is drawn as a chain) and of the ``"protein"`` around it. ``None`` asks
|
|
257
|
+
#: for no level: a residue of the ligand is its box, and one of the protein is drawn as the style
|
|
258
|
+
#: draws it. Otherwise one of :data:`bindview.fragments.DETAILS`. It is not ``ligand_as``, which
|
|
259
|
+
#: says how the ligand is read.
|
|
260
|
+
self.detail: dict[str, "str | None"] = _details(detail)
|
|
261
|
+
#: Set by an interface: the level of each chain around its column (a participant's own).
|
|
262
|
+
self.detail_by_chain: dict[str, "str | None"] = {}
|
|
263
|
+
if isinstance(self.backend, Polymer) and self.detail["ligand"] is not None:
|
|
264
|
+
self.backend.peptide = replace(self.backend.peptide, detail=self.detail["ligand"])
|
|
265
|
+
self.interactions = list(interactions)
|
|
266
|
+
self.structure = structure
|
|
267
|
+
self.ligand_key = ligand_key
|
|
268
|
+
self.name = name
|
|
269
|
+
self.source = source
|
|
270
|
+
self.warnings = list(warnings)
|
|
271
|
+
#: Per-atom / per-residue pLDDT and model-level evidence, when it may be drawn.
|
|
272
|
+
self.confidence = confidence
|
|
273
|
+
#: What the records' ``occupancy`` is a share of ("1,000 frames of a 100 ns trajectory",
|
|
274
|
+
#: "the 10 ligands of the set"). Printed in the legend; the numbers do not say.
|
|
275
|
+
self.ensemble = ensemble
|
|
276
|
+
#: Sentences the figure prints under itself, after its own: what the one who built the diagram
|
|
277
|
+
#: has to say about it and the figure cannot know. Empty for every diagram but one that stands
|
|
278
|
+
#: for several models (:meth:`bindview.ensemble.Ensemble.diagram`), which says here which model it
|
|
279
|
+
#: is and which contacts of the others it does not make. Not a note that ``notes=False`` drops:
|
|
280
|
+
#: without it such a figure reads as the whole ensemble.
|
|
281
|
+
self.remarks: list[str] = []
|
|
282
|
+
#: Contacts that this structure does not make and other models of its ensemble do, where the
|
|
283
|
+
#: ensemble was asked to have them drawn (``Ensemble.diagram(absent="faint")``): each is drawn
|
|
284
|
+
#: faint, with its share where a distance would stand. They are not among ``interactions``:
|
|
285
|
+
#: not counted, not in a fingerprint, and a diagram without a contact of its own stays empty.
|
|
286
|
+
self.elsewhere: list[ResolvedInteraction] = []
|
|
287
|
+
#: What a figure says of them: where it draws them, and where it cannot (a summary table).
|
|
288
|
+
self.elsewhere_said: tuple[str, str] = ("", "")
|
|
289
|
+
#: A diagram of all the models of an ensemble (:meth:`bindview.ensemble.Ensemble.consensus`): for every
|
|
290
|
+
#: residue the models that contact it, which is what its ring shows, and how each is drawn unless
|
|
291
|
+
#: ``residues=`` says otherwise. Empty for every other diagram.
|
|
292
|
+
self.shares: "Mapping[tuple[str, int, str], ResidueShare]" = {}
|
|
293
|
+
self.forms: "Mapping[str, str]" = {}
|
|
294
|
+
self._exposure: np.ndarray | None = None
|
|
295
|
+
self._burial: Burial | None = None
|
|
296
|
+
self._sites: list[SolventSite] | None = None
|
|
297
|
+
#: The matrix of predicted aligned errors the contacts' values are from, where one was given.
|
|
298
|
+
self.pae: "Pae | PaeDraws | None" = None
|
|
299
|
+
#: What was drawn, each figure under its options and what the diagram was when it was drawn
|
|
300
|
+
#: (:meth:`_drawn_from`), and under keys of their own the layouts it was drawn from (:meth:`_laid_out`).
|
|
301
|
+
self._composed: dict[tuple, Any] = {}
|
|
302
|
+
|
|
303
|
+
# ------------------------------------------------------------------ build
|
|
304
|
+
@classmethod
|
|
305
|
+
def from_structure(cls, structure: "str | Path | Structure", ligand: "str | tuple[str, int] | ResidueKey",
|
|
306
|
+
smiles: str | None = None,
|
|
307
|
+
interactions: "Iterable[Interaction | Mapping[str, Any]] | str | Path | None" = None, *,
|
|
308
|
+
name: str | None = None, ionize_acids: bool = True,
|
|
309
|
+
plddt: "str | bool | Confidence | None" = "auto",
|
|
310
|
+
model_confidence: "str | Path | Mapping[str, Any] | ModelConfidence | None" = "auto",
|
|
311
|
+
trusted: bool | None = None, flag: str | None = None,
|
|
312
|
+
ensemble: str | None = None, ligand_as: str = "auto",
|
|
313
|
+
detail: "str | Mapping[str, str | None] | None" = None, covalent: bool = False,
|
|
314
|
+
pae: Any = None, ions: bool = False) -> "Diagram":
|
|
315
|
+
"""Build a diagram from a structure file.
|
|
316
|
+
|
|
317
|
+
Parameters
|
|
318
|
+
----------
|
|
319
|
+
structure:
|
|
320
|
+
Path to an mmCIF or PDB file, or an already parsed :class:`Structure`.
|
|
321
|
+
ligand:
|
|
322
|
+
Which residue is the ligand: a residue name (``"LIG_B"``),
|
|
323
|
+
``"chain:number"``, or a ``(chain, number)`` tuple. A peptide
|
|
324
|
+
ligand that is a polymer chain of its own, as in a deposited
|
|
325
|
+
structure, is named by its chain: ``"P"`` or ``"chain:P"``
|
|
326
|
+
(:meth:`bindview.structure.Structure.resolve_ligand`). Its residues,
|
|
327
|
+
their names and their numbers are then those of the file.
|
|
328
|
+
smiles:
|
|
329
|
+
The ligand's SMILES. Optional but strongly recommended: bond orders
|
|
330
|
+
cannot be recovered reliably from coordinates alone. When omitted,
|
|
331
|
+
``_chem_comp.pdbx_smiles`` from the file is used if present.
|
|
332
|
+
interactions:
|
|
333
|
+
The contacts: a list of :class:`Interaction` (or dict-like rows), or the path of a table
|
|
334
|
+
(:func:`bindview.load_interactions`). ``"distances"`` makes the table from the positions of the
|
|
335
|
+
heavy atoms (:mod:`bindview.distance_table`), which needs nothing installed and is cruder than a
|
|
336
|
+
detector. ``None`` means *detect them*, which needs the optional PLIP extra. An empty list means
|
|
337
|
+
"analysed, nothing found" and yields an ``empty`` result.
|
|
338
|
+
plddt:
|
|
339
|
+
Where per-atom confidence comes from. ``"auto"`` (default) reads the
|
|
340
|
+
B-factor column **only if the file declares it to be a pLDDT**
|
|
341
|
+
(``_ma_qa_metric``, as AlphaFold-style models do) and otherwise draws
|
|
342
|
+
no confidence at all: in a crystal structure that column is a
|
|
343
|
+
temperature factor, and the value range is never used to guess.
|
|
344
|
+
``"bfactor"`` is the caller's assertion that the column is pLDDT on
|
|
345
|
+
the 0-100 scale (AlphaFold 2 / ColabFold PDB files, which cannot
|
|
346
|
+
declare it), ``"bfactor01"`` that it is pLDDT on the 0-1 scale. The
|
|
347
|
+
scale is never guessed: a column in which nothing exceeds 1 is
|
|
348
|
+
refused as 0-100, one in which something does as 0-1. A
|
|
349
|
+
:class:`~bindview.confidence.Confidence` supplies values explicitly;
|
|
350
|
+
``None`` switches confidence off.
|
|
351
|
+
model_confidence:
|
|
352
|
+
Model-level numbers to display (ipTM, pTM, ranking score): a
|
|
353
|
+
:class:`~bindview.confidence.ModelConfidence`, a mapping, or the path
|
|
354
|
+
of an AlphaFold 3 ``summary_confidences.json``. ``"auto"`` picks up
|
|
355
|
+
that file when it sits next to the model under its standard name.
|
|
356
|
+
trusted, flag:
|
|
357
|
+
The caller's verdict. ``trusted=False`` marks the figure as coming
|
|
358
|
+
from a model that should not be read as a result; ``flag`` is the
|
|
359
|
+
verdict in the caller's words (``"grade C"``). bindview never decides
|
|
360
|
+
this itself.
|
|
361
|
+
ensemble:
|
|
362
|
+
What the ``occupancy`` of the interaction records is a share of, in
|
|
363
|
+
words for the legend: ``"1,000 frames of a 100 ns trajectory"``.
|
|
364
|
+
Occupancy itself comes with the records; nothing here reads a
|
|
365
|
+
trajectory.
|
|
366
|
+
ligand_as:
|
|
367
|
+
How the ligand is drawn. ``"auto"`` (default) decides by what the
|
|
368
|
+
molecule is: a ligand with a chain of at least eight amino-acid
|
|
369
|
+
residues is drawn as that chain, every other ligand as atoms,
|
|
370
|
+
whatever its size (:func:`bindview.peptide.decide`). ``"atoms"`` and
|
|
371
|
+
``"chain"`` overrule it.
|
|
372
|
+
detail:
|
|
373
|
+
How much of a residue is drawn where it is drawn with atoms: ``"box"``
|
|
374
|
+
(no atoms: its name), ``"backbone"``, ``"sidechain"`` or ``"atoms"``.
|
|
375
|
+
One level for both sides, or a mapping with one for the ``"ligand"``
|
|
376
|
+
(where it is drawn as a chain) and one for the ``"protein"``. Only a
|
|
377
|
+
residue that makes a directional contact is drawn with atoms: the
|
|
378
|
+
part that makes the contact, and what the level adds to it. ``None``
|
|
379
|
+
(default) asks for no level: a residue of a ligand drawn as a chain
|
|
380
|
+
is its box, and a residue of the protein is drawn as the style draws
|
|
381
|
+
it. Not ``ligand_as``, which says how the ligand is read.
|
|
382
|
+
covalent:
|
|
383
|
+
Look for covalent bonds between the ligand and a residue, as the file declares them and by
|
|
384
|
+
distance, and draw them (:mod:`bindview.covalent`). Off unless asked for; a row of the kind
|
|
385
|
+
``"covalent"`` in ``interactions`` is drawn either way.
|
|
386
|
+
pae:
|
|
387
|
+
The model's matrix of predicted aligned errors (:mod:`bindview.pae`), as an
|
|
388
|
+
:class:`~bindview.interface.Interface` takes it: AlphaFold 3's ``confidences.json``, Boltz's
|
|
389
|
+
``pae_*.npz``, or several. Each contact then has the PAE between its residue and the atoms of the
|
|
390
|
+
ligand that make it (of a ligand that is a chain, the residue of it), drawn as a glow behind its
|
|
391
|
+
line (``render(pae_colors=...)``).
|
|
392
|
+
ions:
|
|
393
|
+
Draw an ion that the model has between the ligand and the protein as the bridge it is, with the
|
|
394
|
+
atoms of either that hold it (:mod:`bindview.ions`). Off unless asked for; where the model has
|
|
395
|
+
none, none is predicted.
|
|
396
|
+
"""
|
|
397
|
+
st = structure if isinstance(structure, Structure) else read_structure(structure)
|
|
398
|
+
# A polymer chain can be the ligand: it then becomes one residue of the structure, like the
|
|
399
|
+
# single component a co-folding model writes, and ``given`` keeps what the file said of its residues.
|
|
400
|
+
whole = st
|
|
401
|
+
st, key, given, notes = st.resolve_ligand(ligand)
|
|
402
|
+
source = None
|
|
403
|
+
if isinstance(interactions, (str, Path)):
|
|
404
|
+
if str(interactions) == DISTANCES:
|
|
405
|
+
from .distance_table import contact_table, ligand_contacts
|
|
406
|
+
|
|
407
|
+
interactions = contact_table(whole, key.chain) if given else ligand_contacts(whole, ligand, smiles)
|
|
408
|
+
source = DISTANCES
|
|
409
|
+
else:
|
|
410
|
+
interactions, source = load_interactions(interactions), "supplied"
|
|
411
|
+
if interactions is None and given:
|
|
412
|
+
# A chain of its own as ligand: PLIP takes it in its peptide mode, from the file as it was.
|
|
413
|
+
from .detect import detect_interface
|
|
414
|
+
|
|
415
|
+
others = sorted({a.chain for a in whole.atoms} - {key.chain})
|
|
416
|
+
interactions = [c.as_interaction() for c in detect_interface(whole, [key.chain], others)]
|
|
417
|
+
source = "detected"
|
|
418
|
+
return cls._assemble(st, key, given, notes, smiles, interactions, name=name, ionize_acids=ionize_acids,
|
|
419
|
+
plddt=plddt, model_confidence=model_confidence, trusted=trusted, flag=flag,
|
|
420
|
+
ensemble=ensemble, ligand_as=ligand_as, source=source, detail=detail, covalent=covalent,
|
|
421
|
+
pae=read_pae(pae, whole), ions=ions)
|
|
422
|
+
|
|
423
|
+
@classmethod
|
|
424
|
+
def _assemble(cls, st: Structure, key: ResidueKey, given: tuple, notes: "Sequence[str]", smiles: "str | None",
|
|
425
|
+
interactions: "Iterable[Interaction | Mapping[str, Any]] | None", *, name: "str | None" = None,
|
|
426
|
+
ionize_acids: bool = True, plddt: Any = "auto", model_confidence: Any = "auto",
|
|
427
|
+
trusted: "bool | None" = None, flag: "str | None" = None, ensemble: "str | None" = None,
|
|
428
|
+
ligand_as: str = "auto", source: "str | None" = None,
|
|
429
|
+
detail: "str | Mapping[str, str | None] | None" = None, covalent: bool = False,
|
|
430
|
+
pae: "Pae | PaeDraws | None" = None, ions: bool = False) -> "Diagram":
|
|
431
|
+
"""The second half of :meth:`from_structure`: from a structure in which the ligand is one
|
|
432
|
+
residue (``key``), whether the file had it so or a chain, or the residues of one side of an
|
|
433
|
+
interface, were merged into one (``given`` then holds what the file said of them)."""
|
|
434
|
+
warnings: list[str] = list(notes)
|
|
435
|
+
confidence = _confidence_for(st, key, plddt, model_confidence, trusted, flag)
|
|
436
|
+
if given and not smiles:
|
|
437
|
+
from .chains import chain_smiles
|
|
438
|
+
|
|
439
|
+
smiles, unknown = chain_smiles(st.residue_atoms(key), given)
|
|
440
|
+
warnings.extend(unknown)
|
|
441
|
+
elif not smiles:
|
|
442
|
+
smiles = st.chem_comp_smiles.get(st.residue_name(key))
|
|
443
|
+
if smiles is None:
|
|
444
|
+
warnings.append("no SMILES was given and the structure file carries none")
|
|
445
|
+
found_ions = bridges(st, key) if ions else []
|
|
446
|
+
holding = holders(st, key) if ions else []
|
|
447
|
+
whole = st
|
|
448
|
+
if found_ions:
|
|
449
|
+
st, smiles = with_ions(st, key, smiles, found_ions)
|
|
450
|
+
warnings.extend(f"ion bridge: {b}" for b in found_ions)
|
|
451
|
+
elif ions and not holding:
|
|
452
|
+
warnings.append("ions were asked for, and the model has none between the ligand and the protein")
|
|
453
|
+
lig = build_ligand(st.residue_atoms(key), smiles, ionize_acids=ionize_acids)
|
|
454
|
+
if found_ions:
|
|
455
|
+
seat(lig, found_ions)
|
|
456
|
+
if given:
|
|
457
|
+
lig.given, lig.chain = given, key.chain
|
|
458
|
+
warnings.extend(lig.diagnostics)
|
|
459
|
+
if interactions is None:
|
|
460
|
+
from .detect import detect_interactions
|
|
461
|
+
|
|
462
|
+
records = detect_interactions(whole, key)
|
|
463
|
+
source = "detected"
|
|
464
|
+
else:
|
|
465
|
+
records = coerce_interactions(interactions)
|
|
466
|
+
source = source or "supplied"
|
|
467
|
+
check_confidence_scale(r.confidence for r in records)
|
|
468
|
+
if found_ions or holding:
|
|
469
|
+
records, dropped = without_the_bridge(list(records), found_ions, holding)
|
|
470
|
+
records += [r for b in found_ions for r in b.records()]
|
|
471
|
+
if dropped:
|
|
472
|
+
warnings.append(f"{dropped} hydrogen bond{'s' if dropped != 1 else ''} of the table with an atom that holds "
|
|
473
|
+
f"an ion {'are' if dropped != 1 else 'is'} left out")
|
|
474
|
+
if covalent:
|
|
475
|
+
brought = {(r.residue_id, r.protein_atom) for r in records if r.type is InteractionType.COVALENT}
|
|
476
|
+
found = [b for b in covalent_bonds(st, key)
|
|
477
|
+
if ((b.residue.chain, b.residue.number, b.residue.icode), b.atom) not in brought]
|
|
478
|
+
records = list(records) + [b.as_interaction() for b in found]
|
|
479
|
+
warnings.extend(f"covalent bond: {b}" for b in found)
|
|
480
|
+
if not found and not brought:
|
|
481
|
+
warnings.append("covalent bonds were asked for, and the model has none between the ligand and a residue")
|
|
482
|
+
resolved = resolve_interactions(records, lig, st)
|
|
483
|
+
if any(r.type is InteractionType.COVALENT for r in records):
|
|
484
|
+
for r in resolved:
|
|
485
|
+
if r.type is InteractionType.COVALENT and r.ligand is not None and r.ligand.kind == "atom":
|
|
486
|
+
said = as_bound(lig, r.ligand.atom)
|
|
487
|
+
if said:
|
|
488
|
+
warnings.append(said)
|
|
489
|
+
resolved, bonded = drop_bonded(resolved, lig, st)
|
|
490
|
+
if bonded:
|
|
491
|
+
warnings.append(f"{len(bonded)} contact{'s' if len(bonded) != 1 else ''} between atoms that the covalent bond "
|
|
492
|
+
f"joins {'are' if len(bonded) != 1 else 'is'} left out: "
|
|
493
|
+
+ ", ".join(f"{r.record.residue_label} {r.type.label.lower()}" for r in bonded))
|
|
494
|
+
if pae is not None:
|
|
495
|
+
_give_pae(resolved, pae, lig, st, key)
|
|
496
|
+
out = cls(lig, resolved, structure=st, ligand_key=key, name=name, source=source, warnings=warnings,
|
|
497
|
+
confidence=confidence, ensemble=ensemble, ligand_as=ligand_as, detail=detail)
|
|
498
|
+
out.pae = pae
|
|
499
|
+
return out
|
|
500
|
+
|
|
501
|
+
# ------------------------------------------------------------------ queries
|
|
502
|
+
@property
|
|
503
|
+
def n_interactions(self) -> int:
|
|
504
|
+
"""How many contacts the diagram has."""
|
|
505
|
+
return len(self.interactions)
|
|
506
|
+
|
|
507
|
+
def fingerprint(self, name: str | None = None) -> "Fingerprint":
|
|
508
|
+
"""The per-(residue, interaction type) fingerprint of this complex (see :mod:`bindview.fingerprint`)."""
|
|
509
|
+
from .fingerprint import Fingerprint
|
|
510
|
+
|
|
511
|
+
return Fingerprint.from_diagram(self, name)
|
|
512
|
+
|
|
513
|
+
@property
|
|
514
|
+
def unresolved(self) -> list[ResolvedInteraction]:
|
|
515
|
+
"""The contacts that could not be attached to the ligand: they are not drawn, and the result says so."""
|
|
516
|
+
return [r for r in self.interactions if r.ligand is None]
|
|
517
|
+
|
|
518
|
+
def ligand_exposure(self) -> np.ndarray | None:
|
|
519
|
+
"""Relative solvent exposure (0..1) of every ligand atom, or ``None`` without a structure."""
|
|
520
|
+
if self.structure is None or self.ligand_key is None:
|
|
521
|
+
return None
|
|
522
|
+
if self._exposure is None:
|
|
523
|
+
from .exposure import relative_exposure
|
|
524
|
+
|
|
525
|
+
st = self.structure
|
|
526
|
+
env = [a for a in st.atoms if a.residue != self.ligand_key and a.element not in ("H", "D")]
|
|
527
|
+
env_xyz = np.array([a.xyz for a in env], dtype=float).reshape(-1, 3)
|
|
528
|
+
self._exposure = relative_exposure(self.ligand.coords3d,
|
|
529
|
+
[self.ligand.element(i) for i in range(self.ligand.n_atoms)],
|
|
530
|
+
env_xyz, [a.element for a in env])
|
|
531
|
+
return self._exposure
|
|
532
|
+
|
|
533
|
+
def burial(self) -> Burial | None:
|
|
534
|
+
"""How much of the ligand's surface the rest of the model covers.
|
|
535
|
+
|
|
536
|
+
The ligand's solvent-accessible surface alone and in the complex, and
|
|
537
|
+
from the two the buried fraction (see :mod:`bindview.exposure`). Waters
|
|
538
|
+
are not counted as cover; everything else in the model is. ``None``
|
|
539
|
+
without a structure.
|
|
540
|
+
"""
|
|
541
|
+
if self.structure is None or self.ligand_key is None:
|
|
542
|
+
return None
|
|
543
|
+
if self._burial is None:
|
|
544
|
+
self._burial = structure_burial(self.structure, self.ligand_key)
|
|
545
|
+
return self._burial
|
|
546
|
+
|
|
547
|
+
def solvent_sites(self) -> list[SolventSite]:
|
|
548
|
+
"""Predicted solvent sites that could bridge ligand and protein, best first.
|
|
549
|
+
|
|
550
|
+
Empty without a structure, and empty for a structure that has waters
|
|
551
|
+
of its own: observed waters take precedence over guessed ones, always.
|
|
552
|
+
See :mod:`bindview.solvent` for what the prediction is and is not.
|
|
553
|
+
"""
|
|
554
|
+
if self.structure is None or self.ligand_key is None or has_waters(self.structure):
|
|
555
|
+
return []
|
|
556
|
+
if self._sites is None:
|
|
557
|
+
self._sites = predict_solvent_sites(self.structure, self.ligand_key)
|
|
558
|
+
return self._sites
|
|
559
|
+
|
|
560
|
+
def _predicted_bridges(self) -> tuple[list[ResolvedInteraction], str]:
|
|
561
|
+
"""Predicted sites as water-bridge records marked ``predicted``, and a note saying what was done."""
|
|
562
|
+
if self.structure is None or self.ligand_key is None:
|
|
563
|
+
return [], "solvent sites were asked for, but there is no structure to predict them in"
|
|
564
|
+
if has_waters(self.structure):
|
|
565
|
+
n = len({a.residue for a in self.structure.atoms if a.resname.upper() in WATER_NAMES})
|
|
566
|
+
return [], (f"no solvent site was predicted: the structure has {n} water molecule"
|
|
567
|
+
f"{'s' if n != 1 else ''} of its own, and observed waters take precedence over guessed ones")
|
|
568
|
+
sites = self.solvent_sites()
|
|
569
|
+
if not sites:
|
|
570
|
+
return [], "no solvent site was predicted between ligand and protein"
|
|
571
|
+
# A water between two atoms that already touch is not a bridge: a site is drawn only
|
|
572
|
+
# towards a residue that the ligand atom does not already contact directionally.
|
|
573
|
+
direct = {(r.record.residue_id, self.ligand.names[i]) for r in self.interactions
|
|
574
|
+
if r.ligand is not None and r.type is not InteractionType.HYDROPHOBIC for i in r.ligand.atoms}
|
|
575
|
+
records = []
|
|
576
|
+
for k, site in enumerate(sites):
|
|
577
|
+
atom_name = site.ligand[0][0] # the nearest ligand partner
|
|
578
|
+
for chain, number, icode, resname, atom, _ in site.protein: # nearest protein partner first
|
|
579
|
+
if ((chain, number, icode), atom_name) not in direct:
|
|
580
|
+
records.append(Interaction(type=InteractionType.WATER_BRIDGE, residue_number=number,
|
|
581
|
+
residue_name=resname, chain=chain, insertion_code=icode,
|
|
582
|
+
protein_atom=atom, ligand_atom=atom_name, water=f"predicted:{k}",
|
|
583
|
+
predicted=True))
|
|
584
|
+
break
|
|
585
|
+
resolved = [r for r in resolve_interactions(records, self.ligand, self.structure) if r.ligand is not None]
|
|
586
|
+
for k, r in enumerate(resolved):
|
|
587
|
+
r.index = len(self.interactions) + len(self.elsewhere) + k
|
|
588
|
+
if not resolved:
|
|
589
|
+
return [], (f"{len(sites)} solvent site{'s were' if len(sites) != 1 else ' was'} predicted, none of them "
|
|
590
|
+
"between partners that are not already in direct contact: nothing was drawn")
|
|
591
|
+
skipped = len(sites) - len(resolved)
|
|
592
|
+
return resolved, (f"{len(resolved)} predicted water site{'s are' if len(resolved) != 1 else ' is'} drawn"
|
|
593
|
+
+ (f" ({skipped} more lie between partners already in direct contact)" if skipped else "")
|
|
594
|
+
+ ": geometric guesses for a model without solvent, not observations")
|
|
595
|
+
|
|
596
|
+
@property
|
|
597
|
+
def _interface(self) -> Any:
|
|
598
|
+
"""What an interface figure says about itself; ``None`` for every other figure."""
|
|
599
|
+
return self.backend.interface if isinstance(self.backend, Polymer) else None
|
|
600
|
+
|
|
601
|
+
@property
|
|
602
|
+
def _burial_cut_applies(self) -> bool:
|
|
603
|
+
"""Is the calibrated cut of :data:`~bindview.exposure.BURIAL_WARNING_BELOW` this ligand's?
|
|
604
|
+
|
|
605
|
+
It was calibrated on small molecules, none of them a chain of residues. A ligand that is
|
|
606
|
+
one -- a peptide, a strand of a nucleic acid, by what it is and however it is drawn --
|
|
607
|
+
lies along a surface and leaves more of itself open than a molecule in a pocket: its buried
|
|
608
|
+
fraction is measured and printed, and no warning is drawn from it.
|
|
609
|
+
"""
|
|
610
|
+
return self._interface is None and not self.backend.decision.is_chain and not self.shares
|
|
611
|
+
|
|
612
|
+
def _burial_warning(self) -> str | None:
|
|
613
|
+
return burial_warning(self.burial()) if self._burial_cut_applies else None
|
|
614
|
+
|
|
615
|
+
def _burial_report(self) -> dict[str, Any] | None:
|
|
616
|
+
# A buried fraction is a ligand's number, with a cut calibrated on ligands. The column of an
|
|
617
|
+
# interface is a piece of a chain: nothing is reported, warned of or printed for it. Nor for a
|
|
618
|
+
# figure of several models, each of which buries its ligand otherwise.
|
|
619
|
+
burial = self.burial() if self._interface is None and not self.shares else None
|
|
620
|
+
if burial is None:
|
|
621
|
+
return None
|
|
622
|
+
cut = self._burial_cut_applies
|
|
623
|
+
return {**burial.as_dict(), "warn_below": BURIAL_WARNING_BELOW if cut else None,
|
|
624
|
+
"warning": cut and burial_warning(burial) is not None}
|
|
625
|
+
|
|
626
|
+
def proximal_residues(self, cutoff: float = 4.5) -> list[str]:
|
|
627
|
+
"""Labels of residues with a heavy atom within ``cutoff`` angstrom of the ligand."""
|
|
628
|
+
keys = self.pocket_residues(cutoff)
|
|
629
|
+
if not keys or self.structure is None:
|
|
630
|
+
return []
|
|
631
|
+
chains = {k.chain for k in keys}
|
|
632
|
+
return [format_residue_label(self.structure.residue_name(k), k.number, k.icode,
|
|
633
|
+
k.chain if len(chains) > 1 else None) for k in keys]
|
|
634
|
+
|
|
635
|
+
def pocket_residues(self, cutoff: float = 4.5) -> list[ResidueKey]:
|
|
636
|
+
"""Residues with a heavy atom within ``cutoff`` angstrom of the ligand, in chain/number order."""
|
|
637
|
+
if self.structure is None or self.ligand_key is None:
|
|
638
|
+
return []
|
|
639
|
+
return list(pocket_atoms(self.structure, self.ligand_key, cutoff))
|
|
640
|
+
|
|
641
|
+
def _shown_confidence(self, opts: RenderOptions) -> Confidence | None:
|
|
642
|
+
return self.confidence if opts.confidence else None
|
|
643
|
+
|
|
644
|
+
# ------------------------------------------------------------------ render
|
|
645
|
+
def render(self, style: str = "detailed", theme: "str | Palette" = "light", *,
|
|
646
|
+
metrics: Metrics | None = None, graph: Graph | None = None, **options: Any) -> RenderResult:
|
|
647
|
+
"""Lay out and draw the diagram.
|
|
648
|
+
|
|
649
|
+
Parameters
|
|
650
|
+
----------
|
|
651
|
+
style:
|
|
652
|
+
``"detailed"`` (the atoms that make the contacts) or ``"schematic"`` (residues as bubbles).
|
|
653
|
+
theme:
|
|
654
|
+
``"light"``, ``"dark"``, ``"auto"`` (one file that follows the reader's setting), or a
|
|
655
|
+
:class:`~bindview.Palette` of your own (``LIGHT.with_(hbond="#123456")``).
|
|
656
|
+
graph:
|
|
657
|
+
A layout to draw from (below).
|
|
658
|
+
metrics:
|
|
659
|
+
The dimensions of a figure (fonts, widths, margins), as a :class:`~bindview.Metrics`.
|
|
660
|
+
options:
|
|
661
|
+
Everything else: ``bindview.options()`` lists them, with a line on each, and
|
|
662
|
+
``help(bindview.styles.base.RenderOptions)`` does the same. Often used: ``residues``, ``title``,
|
|
663
|
+
``bare``, ``plddt_colors``, ``solvent_sites``, ``interactive``, ``figure_width_mm``, ``on_unreadable``.
|
|
664
|
+
|
|
665
|
+
Returns a :class:`RenderResult`: ``svg``, ``status`` (``"ok"``, ``"empty"``, ``"degraded"``,
|
|
666
|
+
``"unreadable"``), ``warnings`` in words, ``quality``, ``graph``, and what the figure says as data.
|
|
667
|
+
|
|
668
|
+
With ``graph`` nothing is laid out: the figure is drawn from the node
|
|
669
|
+
positions the graph holds -- one returned by an earlier render
|
|
670
|
+
(``result.graph``), read back from JSON, or edited by moving nodes.
|
|
671
|
+
An untouched graph gives the identical figure. An edited one is held to
|
|
672
|
+
the same audit as an engine layout, so a node dragged onto another
|
|
673
|
+
makes the result ``unreadable`` unless ``on_unreadable="render"``.
|
|
674
|
+
"""
|
|
675
|
+
opts = RenderOptions(**options)
|
|
676
|
+
_check_sizes(opts)
|
|
677
|
+
asked_for_water = opts.solvent_sites
|
|
678
|
+
if self.shares:
|
|
679
|
+
# All the models of an ensemble: what belongs to one of them is not drawn unless it is asked for.
|
|
680
|
+
opts = replace(opts, burial=False, solvent_sites=False,
|
|
681
|
+
residues=dict(self.forms) if opts.residues is None else opts.residues,
|
|
682
|
+
lining="none" if opts.lining is None else opts.lining,
|
|
683
|
+
exposure=False if opts.exposure is None else opts.exposure)
|
|
684
|
+
if graph is not None and graph.view != style:
|
|
685
|
+
raise GraphError(f"the graph was laid out for the {graph.view!r} style, not {style!r}")
|
|
686
|
+
if graph is not None:
|
|
687
|
+
graph.validate() # (it may have been changed since it was read)
|
|
688
|
+
if graph.bond_length > _BOND_LENGTH_MAX:
|
|
689
|
+
raise GraphError(f"the bond_length of the graph is {graph.bond_length:g}: a figure is drawn with one "
|
|
690
|
+
f"of at most {_BOND_LENGTH_MAX:g}")
|
|
691
|
+
css_vars = isinstance(theme, str) and theme.lower() == "auto"
|
|
692
|
+
light, dark = scheme(opts.colors)
|
|
693
|
+
palette = light if css_vars else get_palette(theme, opts.colors)
|
|
694
|
+
# (The theme, whatever the colour scheme: the name of a palette is the theme only where the caller passed one.)
|
|
695
|
+
theme_name = "auto" if css_vars else palette.name if isinstance(theme, Palette) else str(theme).lower()
|
|
696
|
+
base = metrics or Metrics()
|
|
697
|
+
warnings = list(self.warnings)
|
|
698
|
+
conf = self._shown_confidence(opts)
|
|
699
|
+
if conf is not None and conf.marked:
|
|
700
|
+
verdict = f" ({conf.model.flag})" if conf.model is not None and conf.model.flag else ""
|
|
701
|
+
warnings.append(f"the model is flagged as not trustworthy{verdict}; the figure is marked accordingly")
|
|
702
|
+
if asked_for_water and not opts.solvent_sites:
|
|
703
|
+
warnings.append("solvent_sites was asked for, and this is a figure of several models: predicted waters "
|
|
704
|
+
"are those of one")
|
|
705
|
+
if opts.plddt_colors and conf is None:
|
|
706
|
+
# An option that was asked for and changes nothing is said, so that a figure without colour
|
|
707
|
+
# is not read as a model without doubt.
|
|
708
|
+
warnings.append("plddt_colors was asked for, and this figure has no pLDDT to colour by: "
|
|
709
|
+
+ ("confidence is switched off (confidence=False)" if not opts.confidence else
|
|
710
|
+
"none is read from this model (it declares none, or plddt is off)"))
|
|
711
|
+
if graph is not None and opts.bond_length is not None and abs(opts.bond_length - graph.bond_length) > 1e-9:
|
|
712
|
+
# An option that was asked for and changes nothing is said.
|
|
713
|
+
warnings.append(f"bond_length={opts.bond_length:g} was asked for with a graph, which has its own scale: the "
|
|
714
|
+
f"figure is drawn at {graph.bond_length:g}")
|
|
715
|
+
if graph is not None and opts.coords != "auto":
|
|
716
|
+
warnings.append(f"coords={opts.coords!r} was asked for with a graph, which has the atoms of the ligand where "
|
|
717
|
+
"they are drawn: it changes nothing")
|
|
718
|
+
exposed = self._burial_warning()
|
|
719
|
+
if exposed is not None:
|
|
720
|
+
warnings.append(exposed)
|
|
721
|
+
for r in self.interactions:
|
|
722
|
+
where = f"{r.record.type.value} {r.record.residue_label}"
|
|
723
|
+
if r.ligand is None:
|
|
724
|
+
warnings.append(f"{where} was not drawn: " + ("; ".join(r.notes) or "it could not be attached"))
|
|
725
|
+
elif r.method in ("approximate", "nearest"):
|
|
726
|
+
warnings.append(f"{where} attached by {r.method} match: " + "; ".join(r.notes))
|
|
727
|
+
else:
|
|
728
|
+
warnings.extend(f"{where}: {n}" for n in r.notes)
|
|
729
|
+
drawable = [r for r in self.interactions if r.ligand is not None]
|
|
730
|
+
if self.interactions: # never on a figure that says "nothing was found"
|
|
731
|
+
drawable = drawable + [r for r in self.elsewhere if r.ligand is not None]
|
|
732
|
+
extra_data: dict[str, Any] = {}
|
|
733
|
+
if self.backend.decision.longest_run >= 2:
|
|
734
|
+
# There is a chain of amino-acid residues in the ligand: say how it is drawn, and why.
|
|
735
|
+
extra_data["ligand"] = describe_backend(self.backend)
|
|
736
|
+
if isinstance(self.backend, Polymer) and self.backend.interface is not None:
|
|
737
|
+
extra_data["interface"] = self.backend.interface.meta_for(None)
|
|
738
|
+
if isinstance(self.backend, Polymer):
|
|
739
|
+
unknown = [f"{r.code3}{r.position}" for r in self.backend.peptide.residues if not r.known]
|
|
740
|
+
if unknown:
|
|
741
|
+
warnings.append(f"{len(unknown)} residue{'s' if len(unknown) != 1 else ''} of the ligand's chain "
|
|
742
|
+
f"{'were' if len(unknown) != 1 else 'was'} not recognised and "
|
|
743
|
+
f"{'are' if len(unknown) != 1 else 'is'} shown as Xaa (position "
|
|
744
|
+
f"{', '.join(str(r.position) for r in self.backend.peptide.residues if not r.known)})")
|
|
745
|
+
if opts.solvent_sites:
|
|
746
|
+
bridges, said = self._predicted_bridges()
|
|
747
|
+
warnings.append(said)
|
|
748
|
+
extra_data["solvent_sites"] = [s.as_dict() for s in self.solvent_sites()]
|
|
749
|
+
if self.interactions: # never on a figure that says "nothing was found"
|
|
750
|
+
drawable = drawable + bridges
|
|
751
|
+
|
|
752
|
+
def finish(scene: Scene | None, status: str, figure: str, quality: Quality | None,
|
|
753
|
+
extra: Sequence[str] = (), atoms: dict[str, tuple[float, float]] | None = None,
|
|
754
|
+
laid_out: Graph | None = None, composed: "_Composed | None" = None) -> RenderResult:
|
|
755
|
+
svg = css = None
|
|
756
|
+
if scene is not None:
|
|
757
|
+
over = composed.beside() if opts.interactive and composed is not None else ()
|
|
758
|
+
svg, css = svg_and_css(scene, palette, background=opts.background, css_vars=css_vars,
|
|
759
|
+
dark_palette=dark if css_vars else None, interactive=opts.interactive, over=over,
|
|
760
|
+
stylesheet=opts.stylesheet)
|
|
761
|
+
if opts.interactive and ROOT_CLASS not in svg.split(">", 1)[0]:
|
|
762
|
+
# An option that was asked for and changes nothing is said.
|
|
763
|
+
extra = list(extra) + [NOTHING_TO_POINT_AT]
|
|
764
|
+
return RenderResult(status=status, svg=svg, figure=figure, warnings=_dedupe(warnings + list(extra)),
|
|
765
|
+
quality=quality, style=style, theme=theme_name,
|
|
766
|
+
# (A copy, like the graph below: the scene of a figure is kept for the next one.)
|
|
767
|
+
scene=None if scene is None else scene.copy(),
|
|
768
|
+
atoms=dict(atoms or {}),
|
|
769
|
+
confidence=self._confidence_report(conf, extra_data.get("plddt_basis"))
|
|
770
|
+
if conf is not None else None,
|
|
771
|
+
burial=self._burial_report(), data=dict(extra_data),
|
|
772
|
+
notes=list(scene.notes) if scene is not None else [], css=css,
|
|
773
|
+
# A copy: layouts are cached, and a graph is made to be edited.
|
|
774
|
+
graph=None if laid_out is None else copy.deepcopy(laid_out))
|
|
775
|
+
|
|
776
|
+
if not self.interactions:
|
|
777
|
+
scene = self._empty_scene(palette, base, opts)
|
|
778
|
+
return finish(scene, "empty", "empty", None)
|
|
779
|
+
|
|
780
|
+
style_obj = style_for(style, opts)
|
|
781
|
+
strangers = unknown_residues(opts, group_residues(drawable, opts.show_chain))
|
|
782
|
+
if strangers:
|
|
783
|
+
# An option that was asked for and changes nothing is said.
|
|
784
|
+
warnings.append(f"residues names {', '.join(strangers)}, which no residue of this figure is called")
|
|
785
|
+
if opts.absent is not None:
|
|
786
|
+
everyone = group_residues(drawable, opts.show_chain)
|
|
787
|
+
mark_groups(everyone, opts)
|
|
788
|
+
extra_data["absent"] = Absence(everyone, opts.absent_label).as_dict()
|
|
789
|
+
best: _Composed | None = None
|
|
790
|
+
queue: list[float] = [opts.bond_length] if opts.bond_length else list(_BOND_LENGTHS)
|
|
791
|
+
if graph is not None:
|
|
792
|
+
queue = [graph.bond_length] # the layout is given, and with it its scale
|
|
793
|
+
chain = isinstance(self.backend, Polymer) and graph is None
|
|
794
|
+
plane = isinstance(self.backend, Polymer) and self.backend.arrangement is not None
|
|
795
|
+
pitches = list(_CHAIN_PITCHES) if chain else [base.chain_pitch]
|
|
796
|
+
pitch = pitches[0]
|
|
797
|
+
attempts = 0
|
|
798
|
+
given_up: _Composed | None = None
|
|
799
|
+
hasty = (opts.effort == "quick" and chain and self._interface is None and opts.on_unreadable != "render")
|
|
800
|
+
if graph is None and opts.on_unreadable != "render" and not opts.bond_length:
|
|
801
|
+
hopeless = self._hopeless(base, opts, drawable)
|
|
802
|
+
if hopeless is not None:
|
|
803
|
+
q, reason = hopeless
|
|
804
|
+
message = (f"{self._what()} is not readable: {self._size()}, "
|
|
805
|
+
f"{q.n_residues} residues, {q.n_interactions} interactions; {reason}")
|
|
806
|
+
if opts.on_unreadable == "none":
|
|
807
|
+
return finish(None, "unreadable", "none", q, [message])
|
|
808
|
+
scene = self._summary_scene(base, opts, drawable, q, reason)
|
|
809
|
+
return finish(scene, "unreadable", "summary", q,
|
|
810
|
+
[message + "; a per-residue summary was drawn instead"])
|
|
811
|
+
while queue:
|
|
812
|
+
bl = queue.pop(0)
|
|
813
|
+
scaled = _scaled(base, bl).with_(chain_pitch=pitch) if chain else _scaled(base, bl)
|
|
814
|
+
if hasty:
|
|
815
|
+
given_up = self._looks_hopeless(style_obj, palette, scaled, opts, drawable, pitches)
|
|
816
|
+
hasty = False
|
|
817
|
+
if given_up is not None:
|
|
818
|
+
best = given_up
|
|
819
|
+
break
|
|
820
|
+
comp = self._compose(style_obj, palette, scaled, opts, drawable, graph)
|
|
821
|
+
if best is None or _better(comp.quality, best.quality):
|
|
822
|
+
best = comp
|
|
823
|
+
if comp.quality.valid and comp.quality.readable:
|
|
824
|
+
best = comp
|
|
825
|
+
break
|
|
826
|
+
attempts += 1
|
|
827
|
+
if chain and attempts >= _CHAIN_ATTEMPTS:
|
|
828
|
+
break # a crowded chain costs several seconds each time
|
|
829
|
+
if chain and not comp.quality.valid:
|
|
830
|
+
# Too crowded along the chain: the same scale again, with more room from residue to
|
|
831
|
+
# residue -- as long as the chain then still fits the page at a legible size.
|
|
832
|
+
wider = [p for p in pitches if p > pitch and self._chain_fits(comp.quality, scaled, opts, p)]
|
|
833
|
+
if wider:
|
|
834
|
+
assert isinstance(self.backend, Polymer)
|
|
835
|
+
want = _ROOM_PER_RESIDUE * comp.quality.n_residues / max(1, len(self.backend.peptide.residues))
|
|
836
|
+
if plane:
|
|
837
|
+
# Boxes on a plane are spread in both directions at once: every step makes room.
|
|
838
|
+
pitch = wider[0]
|
|
839
|
+
elif attempts == 1 and want > 1.55:
|
|
840
|
+
pitch = next((p for p in wider if p >= want), wider[-1])
|
|
841
|
+
elif attempts >= 3 and len(wider) > 1:
|
|
842
|
+
# Three layouts were too crowded: small steps are not what is missing. Every
|
|
843
|
+
# second step from here, so that the wide ones are reached before the tries run out.
|
|
844
|
+
pitch = wider[1]
|
|
845
|
+
else:
|
|
846
|
+
pitch = wider[0]
|
|
847
|
+
queue.insert(0, bl)
|
|
848
|
+
continue
|
|
849
|
+
if queue and comp.quality.valid:
|
|
850
|
+
# A full layout is expensive: skip bond lengths that cannot fit either.
|
|
851
|
+
# The ligand shrinks in proportion, what surrounds it only partly.
|
|
852
|
+
q = comp.quality
|
|
853
|
+
limit = q.width * q.min_font_pt / opts.min_font_pt
|
|
854
|
+
lig_w = q.ligand_width
|
|
855
|
+
|
|
856
|
+
def estimate(b: float) -> float:
|
|
857
|
+
return lig_w * b / bl + (q.width - lig_w) * (0.55 + 0.45 * b / bl)
|
|
858
|
+
fitting = [b for b in queue if estimate(b) <= limit * 1.04]
|
|
859
|
+
queue = fitting if fitting else queue[-1:]
|
|
860
|
+
assert best is not None
|
|
861
|
+
q = best.quality
|
|
862
|
+
warnings.extend(best.notes)
|
|
863
|
+
if best.graph is not None and "interface" in best.graph.meta:
|
|
864
|
+
extra_data["interface"] = dict(best.graph.meta["interface"]) # as it was drawn
|
|
865
|
+
if best.basis is not None:
|
|
866
|
+
extra_data["plddt_basis"] = best.basis
|
|
867
|
+
if opts.absent_style == "marked" and extra_data.get("absent", {}).get("absent") and (
|
|
868
|
+
(opts.plddt_colors and conf is not None) or best.glows):
|
|
869
|
+
warnings.append("the marker under what is absent is yellow, and so is one of the colours that the "
|
|
870
|
+
"confidence is drawn in here; absent_style='faint' tells the two apart")
|
|
871
|
+
if q.valid and q.readable:
|
|
872
|
+
degraded = bool(self.unresolved) or self.ligand.bond_source == "connectivity"
|
|
873
|
+
return finish(best.scene, "degraded" if degraded else "ok", "diagram", q, atoms=best.atoms,
|
|
874
|
+
laid_out=best.graph, composed=best)
|
|
875
|
+
|
|
876
|
+
if not q.valid:
|
|
877
|
+
problems = []
|
|
878
|
+
if q.unplaced or q.overlaps or q.link_hits or q.faithful:
|
|
879
|
+
problems.append(f"{q.unplaced} residue(s) could not be placed, {q.overlaps} pair(s) overlap and "
|
|
880
|
+
f"{q.link_hits} interaction line(s) cross another residue")
|
|
881
|
+
if not q.faithful:
|
|
882
|
+
found: dict[str, Any] = (extra_data.get("interface") or {}).get("plane") or {}
|
|
883
|
+
covered = found.get("boxes_covering_each_other", 0)
|
|
884
|
+
problems.append(
|
|
885
|
+
"the boxes as they stand are not a faithful picture of where the residues lie "
|
|
886
|
+
f"({100.0 * found.get('neighbours_kept', 0.0):.0f} % of neighbour relations kept, distances off "
|
|
887
|
+
f"by {100.0 * found.get('distance_error', 0.0):.0f} %; at least {100.0 * KEPT_MIN:.0f} % and at "
|
|
888
|
+
f"most {100.0 * ERROR_MAX:.0f} % are required"
|
|
889
|
+
+ (f"; {covered} pair{'s' if covered != 1 else ''} of boxes lie on top of each other"
|
|
890
|
+
if covered else "") + ")")
|
|
891
|
+
reason = "; ".join(problems)
|
|
892
|
+
if given_up is not None:
|
|
893
|
+
reason += " (effort='quick': with the most room that the page allows, and not tried any further)"
|
|
894
|
+
else:
|
|
895
|
+
reason = beyond_any_page(_smallest_text_pt(base), opts) or too_small_on_page(
|
|
896
|
+
q.min_font_pt, q.required_width_mm, q.width, q.height, opts)
|
|
897
|
+
message = (f"{self._what()} is not readable: {self._size()}, "
|
|
898
|
+
f"{q.n_residues} residues, {q.n_interactions} interactions; {reason}")
|
|
899
|
+
if opts.on_unreadable == "render":
|
|
900
|
+
return finish(best.scene, "unreadable", "diagram", q, [message + "; rendered anyway on request"],
|
|
901
|
+
atoms=best.atoms, laid_out=best.graph, composed=best)
|
|
902
|
+
if opts.on_unreadable == "none":
|
|
903
|
+
return finish(None, "unreadable", "none", q, [message])
|
|
904
|
+
scene = self._summary_scene(base, opts, drawable, q, reason)
|
|
905
|
+
return finish(scene, "unreadable", "summary", q, [message + "; a per-residue summary was drawn instead"])
|
|
906
|
+
|
|
907
|
+
def _looks_hopeless(self, style_obj: Any, palette: Palette, m: Metrics, opts: RenderOptions,
|
|
908
|
+
drawable: Sequence[ResolvedInteraction], pitches: Sequence[float]) -> "_Composed | None":
|
|
909
|
+
"""The roomiest figure of a chain that the page allows, if that is too crowded: then none is tried further.
|
|
910
|
+
|
|
911
|
+
Looked at where the first layout, the closest one, has no place for several residues; both are left as they
|
|
912
|
+
are as soon as that is known of them. What is drawn is never drawn in haste: where this gives no reason to
|
|
913
|
+
give the figure up, it is laid out as ever, from the first.
|
|
914
|
+
"""
|
|
915
|
+
first = self._compose(style_obj, palette, m, opts, drawable, haste=1)
|
|
916
|
+
n = len(first.layout.poses) + len(first.layout.unplaced)
|
|
917
|
+
if first.layout.left < _crowded(n):
|
|
918
|
+
return None
|
|
919
|
+
wider = [p for p in pitches if p > m.chain_pitch and self._chain_fits(first.quality, m, opts, p)]
|
|
920
|
+
roomy = first if not wider else self._compose(style_obj, palette, m.with_(chain_pitch=wider[-1]), opts, drawable,
|
|
921
|
+
haste=2)
|
|
922
|
+
return roomy if roomy.layout.left >= _hopeless(n) else None
|
|
923
|
+
|
|
924
|
+
def _what(self) -> str:
|
|
925
|
+
"""What kind of diagram this is, for a message that it could not be made readable."""
|
|
926
|
+
if isinstance(self.backend, Polymer):
|
|
927
|
+
return "an interface diagram" if self.backend.interface is not None else "a chain diagram"
|
|
928
|
+
return "an atom-level diagram"
|
|
929
|
+
|
|
930
|
+
def _size(self) -> str:
|
|
931
|
+
if isinstance(self.backend, Polymer):
|
|
932
|
+
# An interface has no ligand: the residues in question are those of its column.
|
|
933
|
+
whose = ("ligand residues" if self.backend.interface is None else
|
|
934
|
+
"residues on the plane" if self.backend.arrangement is not None else "residues in the column")
|
|
935
|
+
return f"{len(self.backend.peptide)} {whose} ({self.ligand.n_atoms} atoms)"
|
|
936
|
+
return f"{self.ligand.n_atoms} ligand atoms"
|
|
937
|
+
|
|
938
|
+
def _hopeless(self, base: Metrics, opts: RenderOptions, drawable: Sequence[ResolvedInteraction]
|
|
939
|
+
) -> tuple[Quality, str] | None:
|
|
940
|
+
"""A lower bound on the figure size, without laying anything out.
|
|
941
|
+
|
|
942
|
+
If the ligand drawn at the smallest bond length, with nothing but a
|
|
943
|
+
margin around it, is already too large to print legibly at the figure
|
|
944
|
+
size, no arrangement of residues can rescue it and the (expensive)
|
|
945
|
+
layout is skipped.
|
|
946
|
+
"""
|
|
947
|
+
m = _scaled(base, _BOND_LENGTHS[-1])
|
|
948
|
+
# (A chain with the atoms that these contacts put beside its boxes, not with those of the last figure.)
|
|
949
|
+
self._set_beside(drawable)
|
|
950
|
+
dep = self._depicted(m, replace(opts, atom_labels="names")) # (as it is laid out, whatever is written)
|
|
951
|
+
box = dep.bounds()
|
|
952
|
+
ring = 2.0 * (m.margin + 1.6 * m.bond_length) if drawable else 2.0 * m.margin
|
|
953
|
+
width, height = box[2] - box[0] + ring, box[3] - box[1] + ring
|
|
954
|
+
natural = _smallest_text_pt(m)
|
|
955
|
+
fit = min(opts.figure_width_mm * _PX_PER_MM / width, opts.figure_height_mm * _PX_PER_MM / height, 1.0)
|
|
956
|
+
font_pt = natural * fit
|
|
957
|
+
if font_pt >= opts.min_font_pt - 1e-9:
|
|
958
|
+
return None
|
|
959
|
+
# (A minimum above the text's own size is beyond every page, not beyond this one.)
|
|
960
|
+
never = beyond_any_page(natural, opts)
|
|
961
|
+
required = math.inf if never else width * opts.min_font_pt / natural / _PX_PER_MM
|
|
962
|
+
groups = group_residues(drawable, opts.show_chain)
|
|
963
|
+
q = Quality(width=width, height=height, bond_length=m.bond_length, n_residues=len(groups),
|
|
964
|
+
n_interactions=len(drawable), overlaps=0, unplaced=0, line_crossings=0, bond_crossings=0,
|
|
965
|
+
max_stretch=0.0, min_font_pt=font_pt, required_width_mm=required, readable=False,
|
|
966
|
+
ligand_width=box[2] - box[0], estimated=True, ligand_height=box[3] - box[1])
|
|
967
|
+
if never:
|
|
968
|
+
return q, never
|
|
969
|
+
mm, word, asked = page_that_would_do(required, width, height, opts)
|
|
970
|
+
return q, (f"the ligand alone, at the smallest bond length, needs a figure at least {mm} mm {word} "
|
|
971
|
+
f"for {opts.min_font_pt:g} pt text (requested: {asked:g} mm)")
|
|
972
|
+
|
|
973
|
+
def _chain_fits(self, q: Quality, m: Metrics, opts: RenderOptions, pitch: float) -> bool:
|
|
974
|
+
"""Would this chain figure, laid out again with ``pitch`` bond lengths from residue to
|
|
975
|
+
residue, still be legible on the page? An estimate from the figure as it is: a wider pitch
|
|
976
|
+
makes it taller by that much for every residue, and nothing else changes."""
|
|
977
|
+
assert isinstance(self.backend, Polymer)
|
|
978
|
+
n = len(self.backend.peptide.residues)
|
|
979
|
+
page_w, page_h = opts.figure_width_mm * _PX_PER_MM, opts.figure_height_mm * _PX_PER_MM
|
|
980
|
+
unscaled = q.min_font_pt / min(page_w / q.width, page_h / q.height, 1.0)
|
|
981
|
+
now = max(POLYMER_MIN_PITCH, m.chain_pitch * m.bond_length)
|
|
982
|
+
if self.backend.arrangement is not None:
|
|
983
|
+
# Boxes on a plane: the drawing of the boxes grows in both directions with the pitch, and
|
|
984
|
+
# what is around it stays as it is.
|
|
985
|
+
grow = max(POLYMER_MIN_PITCH, pitch * m.bond_length) / now
|
|
986
|
+
width = q.width + q.ligand_width * (grow - 1.0)
|
|
987
|
+
height = q.height + q.ligand_height * (grow - 1.0)
|
|
988
|
+
return unscaled * min(page_w / width, page_h / height, 1.0) >= opts.min_font_pt * 1.003
|
|
989
|
+
height = q.height + (n - 1) * (max(POLYMER_MIN_PITCH, pitch * m.bond_length) - now)
|
|
990
|
+
return unscaled * min(page_w / q.width, page_h / height, 1.0) >= opts.min_font_pt * 1.003
|
|
991
|
+
|
|
992
|
+
def render_svg(self, path: "str | Path | None" = None, style: str = "detailed",
|
|
993
|
+
theme: "str | Palette" = "light", **options: Any) -> RenderResult:
|
|
994
|
+
"""Render and, when ``path`` is given and there is a figure, write it."""
|
|
995
|
+
result = self.render(style=style, theme=theme, **options)
|
|
996
|
+
if path is not None and result.svg is not None:
|
|
997
|
+
p = Path(path)
|
|
998
|
+
try:
|
|
999
|
+
p.write_text(result.svg, encoding="utf-8")
|
|
1000
|
+
except OSError as exc:
|
|
1001
|
+
raise RenderError(f"cannot write {p}: {exc}") from exc
|
|
1002
|
+
result.path = p
|
|
1003
|
+
return result
|
|
1004
|
+
|
|
1005
|
+
# ------------------------------------------------------------------ pieces
|
|
1006
|
+
def arrange(self, path: "str | Path | None" = None, style: str = "detailed", *, title: "str | None" = None,
|
|
1007
|
+
port: int = 0, browser: bool = True, **options: Any) -> "Graph | Path | None":
|
|
1008
|
+
"""Arrange the figure by hand, in a browser (:mod:`bindview.arrange`).
|
|
1009
|
+
|
|
1010
|
+
Residues and the key are dragged, turned and flipped; bindview draws the figure again whenever one is let
|
|
1011
|
+
go. Returns the layout when the page is done, for ``render(graph=...)`` (None if it is stopped with Ctrl-C).
|
|
1012
|
+
With ``path`` the page is written there as one file instead, with a preview and without bindview behind it,
|
|
1013
|
+
and the path is returned. ``options`` are those of :meth:`render`.
|
|
1014
|
+
"""
|
|
1015
|
+
from . import arrange
|
|
1016
|
+
|
|
1017
|
+
options = {"style": style, **options}
|
|
1018
|
+
if path is not None:
|
|
1019
|
+
return arrange.page(self, path, title, **options)
|
|
1020
|
+
return arrange.serve(self, title, port=port, browser=browser, **options)
|
|
1021
|
+
|
|
1022
|
+
def _compose(self, style_obj: Any, palette: Palette, m: Metrics, opts: RenderOptions,
|
|
1023
|
+
drawable: Sequence[ResolvedInteraction], given: Graph | None = None, haste: int = 0) -> _Composed:
|
|
1024
|
+
if given is not None:
|
|
1025
|
+
return self._compose_uncached(style_obj, palette, m, opts, drawable, given)
|
|
1026
|
+
# A scene holds colour *tokens*, so it is the same for every palette that
|
|
1027
|
+
# defines the same elements: themes share one layout. Whether the file answers the pointer is
|
|
1028
|
+
# decided where the scene is written, so a figure and its interactive copy share one too.
|
|
1029
|
+
# Nor does a mask of absent residues move anything: with and without it a figure has one layout.
|
|
1030
|
+
key = (style_obj.name, m, replace(opts, interactive=False, stylesheet="inline", effort="full"),
|
|
1031
|
+
frozenset(palette.elements), haste, self._drawn_from())
|
|
1032
|
+
hit = self._kept(key)
|
|
1033
|
+
if hit is None:
|
|
1034
|
+
hit = self._keep(key, self._compose_uncached(style_obj, palette, m, opts, drawable, haste=haste))
|
|
1035
|
+
return hit
|
|
1036
|
+
|
|
1037
|
+
def _kept(self, key: tuple) -> Any:
|
|
1038
|
+
"""What is kept under ``key``, or ``None``. It was used now, and is so the last of its kind to go."""
|
|
1039
|
+
hit = self._composed.pop(key, None)
|
|
1040
|
+
if hit is not None:
|
|
1041
|
+
self._composed[key] = hit
|
|
1042
|
+
return hit
|
|
1043
|
+
|
|
1044
|
+
def _keep(self, key: tuple, value: Any) -> Any:
|
|
1045
|
+
"""Keep ``value`` under ``key``; where there are then more of its kind than are kept
|
|
1046
|
+
(:data:`_KEPT_AT_MOST`), those that were used longest ago go."""
|
|
1047
|
+
self._composed[key] = value
|
|
1048
|
+
kind = _kind(key)
|
|
1049
|
+
same = [k for k in self._composed if _kind(k) == kind]
|
|
1050
|
+
for old in same[:max(0, len(same) - _KEPT_AT_MOST[kind])]:
|
|
1051
|
+
del self._composed[old]
|
|
1052
|
+
return value
|
|
1053
|
+
|
|
1054
|
+
def _drawn_from(self) -> tuple:
|
|
1055
|
+
"""What a figure is drawn from beside its options, for the key of one that is kept.
|
|
1056
|
+
|
|
1057
|
+
The contacts by what they say, the name, the remarks and the levels of detail by their value; the ligand,
|
|
1058
|
+
the structure, the confidence and what else the diagram holds as one thing by which object it is. A
|
|
1059
|
+
diagram that was given other contacts or another name after a figure of it was drawn, or a copy of it
|
|
1060
|
+
that was, is so drawn again, and one that was left as it is, is not.
|
|
1061
|
+
"""
|
|
1062
|
+
def rows(contacts: Sequence[ResolvedInteraction]) -> tuple:
|
|
1063
|
+
return tuple((r.record, r.index, r.residue, r.ligand, r.protein, r.method, r.delta, r.computed_distance,
|
|
1064
|
+
tuple(r.notes), r.absent) for r in contacts)
|
|
1065
|
+
|
|
1066
|
+
backend = self.backend
|
|
1067
|
+
held = (self.ligand, self.structure, self.confidence, self.pae, self.shares, backend,
|
|
1068
|
+
getattr(backend, "peptide", None), getattr(backend, "interface", None),
|
|
1069
|
+
getattr(backend, "arrangement", None))
|
|
1070
|
+
return (rows(self.interactions), rows(self.elsewhere), self.name, self.ensemble, self.ligand_key,
|
|
1071
|
+
tuple(self.remarks), tuple(self.elsewhere_said), tuple(self.detail.items()),
|
|
1072
|
+
tuple(self.detail_by_chain.items()), *(_Same(it) for it in held))
|
|
1073
|
+
|
|
1074
|
+
def _depicted(self, m: Metrics, opts: RenderOptions, given: Graph | None = None) -> Depiction:
|
|
1075
|
+
"""The ligand as it is drawn, or where a graph has it."""
|
|
1076
|
+
if isinstance(self.backend, Polymer):
|
|
1077
|
+
self.backend.atom_labels = opts.atom_labels
|
|
1078
|
+
return self.backend.depict(m, opts.coords) if given is None else self.backend.depict_from(m, given)
|
|
1079
|
+
|
|
1080
|
+
def _field(self, dep: Depiction, m: Metrics, params: LayoutParams, style_obj: Any, ctx: Context) -> LigandField:
|
|
1081
|
+
fld = LigandField(dep, reach=(params.reach + 3.0) * m.bond_length, step=max(2.0, m.bond_length / 10.0),
|
|
1082
|
+
extra=list(style_obj.ligand_obstacles(ctx)) + self.backend.obstacles(dep))
|
|
1083
|
+
# (One that was made before is as good, and knows its distances.)
|
|
1084
|
+
key = ("field", fld.key)
|
|
1085
|
+
hit = self._kept(key)
|
|
1086
|
+
return hit if hit is not None else self._keep(key, fld)
|
|
1087
|
+
|
|
1088
|
+
def _laid_out(self, fld: LigandField, bodies: Sequence[Any], params: LayoutParams) -> LayoutResult:
|
|
1089
|
+
"""The placement of the residues, kept for the next figure that differs in what moves nothing."""
|
|
1090
|
+
key: tuple = ("layout", layout_key(fld, bodies, replace(params, give_up=0)))
|
|
1091
|
+
hit = self._kept(key)
|
|
1092
|
+
if hit is None or 0 < params.give_up <= hit.left:
|
|
1093
|
+
# (One that was left as it was is kept apart: it is not what a figure that takes its time is drawn from,
|
|
1094
|
+
# and what a hasty one says does not depend on which of the two was drawn first.)
|
|
1095
|
+
hasty = (*key, params.give_up)
|
|
1096
|
+
hit = self._kept(hasty)
|
|
1097
|
+
if hit is None:
|
|
1098
|
+
hit = self._keep(hasty if (hit := layout_bodies(fld, bodies, params)).abandoned else key, hit)
|
|
1099
|
+
return hit
|
|
1100
|
+
|
|
1101
|
+
def _compose_uncached(self, style_obj: Any, palette: Palette, m: Metrics, opts: RenderOptions,
|
|
1102
|
+
drawable: Sequence[ResolvedInteraction], given: Graph | None = None, haste: int = 0) -> _Composed:
|
|
1103
|
+
self._set_beside(drawable)
|
|
1104
|
+
dep = self._depicted(m, opts, given)
|
|
1105
|
+
groups = split_along_chain(group_residues(drawable, opts.show_chain), dep)
|
|
1106
|
+
mark_groups(groups, opts)
|
|
1107
|
+
twice = list(dict.fromkeys(g.label for g in groups if g.parts > 1))
|
|
1108
|
+
conf = self._shown_confidence(opts)
|
|
1109
|
+
ctx = Context(self.ligand, dep, groups, m, palette, opts, confidence=conf, ensemble=self.ensemble,
|
|
1110
|
+
solvent_sites=tuple(self.solvent_sites()) if opts.solvent_sites else (),
|
|
1111
|
+
detail={"*": self.detail["protein"], **self.detail_by_chain}, pae=self.pae is not None,
|
|
1112
|
+
shares=self.shares)
|
|
1113
|
+
if style_obj.settings.exposure:
|
|
1114
|
+
ctx.exposure = self.ligand_exposure()
|
|
1115
|
+
bodies = style_obj.bodies(ctx)
|
|
1116
|
+
_set_fans(bodies)
|
|
1117
|
+
params = LayoutParams(unit=m.bond_length, give_up=(0, _crowded(len(bodies)), _hopeless(len(bodies)))[haste])
|
|
1118
|
+
# What is written on an atom moves nothing: the figure is laid out with the atoms' names whatever is written.
|
|
1119
|
+
laid, laid_dep = bodies, dep
|
|
1120
|
+
if given is None and opts.atom_labels != "names":
|
|
1121
|
+
plain = replace(opts, atom_labels="names")
|
|
1122
|
+
laid_dep = self._depicted(m, plain)
|
|
1123
|
+
laid = style_obj.bodies(replace(ctx, dep=laid_dep, options=plain, notes=[]))
|
|
1124
|
+
_set_fans(laid)
|
|
1125
|
+
fld = self._field(dep, m, params, style_obj, ctx)
|
|
1126
|
+
if given is None:
|
|
1127
|
+
layout = self._laid_out(fld if laid_dep is dep else self._field(laid_dep, m, params, style_obj, ctx), laid,
|
|
1128
|
+
params)
|
|
1129
|
+
else:
|
|
1130
|
+
layout = audit_layout(fld, bodies, *poses_from(given, bodies), params) # placed elsewhere: measure only
|
|
1131
|
+
ctx.field = fld
|
|
1132
|
+
# The engine's result becomes the graph, and the renderer draws from the graph: it is the
|
|
1133
|
+
# one description of where things are, whether it was made just now or handed in.
|
|
1134
|
+
graph = diagram_graph(style_obj.name, ctx, bodies, layout, params, name=self.name or "",
|
|
1135
|
+
exposure=ctx.exposure)
|
|
1136
|
+
poses, label_t = poses_from(graph, bodies)
|
|
1137
|
+
drawing = style_obj.draw(ctx, bodies, poses, label_t)
|
|
1138
|
+
notes = list(dep.notes) + list(drawing.notes)
|
|
1139
|
+
|
|
1140
|
+
by_colour = ctx.by_colour
|
|
1141
|
+
ligand_group, ligand_levels = self.backend.draw(dep, palette, m, conf, by_colour=by_colour, by_bond=ctx.by_bond)
|
|
1142
|
+
levels = set(drawing.levels) | ligand_levels
|
|
1143
|
+
legend = list(drawing.legend)
|
|
1144
|
+
if dep.units:
|
|
1145
|
+
assert isinstance(self.backend, Polymer)
|
|
1146
|
+
legend.append(LegendEntry(self.backend.legend_text(), "unit"))
|
|
1147
|
+
if dep.plane is not None:
|
|
1148
|
+
# Boxes on a plane are drawn to scale, and a reader will measure: the scale they are drawn at.
|
|
1149
|
+
legend.append(LegendEntry(f"{SCALE_BAR:g} \u00c5 between the centres of two boxes", "scale",
|
|
1150
|
+
length=SCALE_BAR * dep.plane.scale))
|
|
1151
|
+
if self.backend.interface is not None and not ctx.glows:
|
|
1152
|
+
# The key of a PAE tag is a tag as this figure writes them: plain, bold, or one of each.
|
|
1153
|
+
legend.extend(LegendEntry(text, "tag", marks=pae_key(drawing.tags))
|
|
1154
|
+
for text in self.backend.interface.legend_extra)
|
|
1155
|
+
if not any(e.label == "Confidence:" for e in legend):
|
|
1156
|
+
legend.extend(confidence_legend(levels)) # only the ligand is below full strength
|
|
1157
|
+
under = None
|
|
1158
|
+
if by_colour:
|
|
1159
|
+
assert conf is not None
|
|
1160
|
+
from .styles.ligand_draw import plddt_underlay
|
|
1161
|
+
|
|
1162
|
+
legend.extend(plddt_legend())
|
|
1163
|
+
# The ligand's atoms, on colour. (Where the bonds have it, that is for the atoms outside a chain's boxes.)
|
|
1164
|
+
under = plddt_underlay(dep, self.backend.bands(dep, conf)) if not ctx.by_bond or dep.units else None
|
|
1165
|
+
content = Group("diagram")
|
|
1166
|
+
for name in ("backdrop", "halos", "interactions"):
|
|
1167
|
+
if drawing.layers.get(name):
|
|
1168
|
+
content.add(Group(name, list(drawing.layers[name])))
|
|
1169
|
+
if name == "backdrop" and under is not None:
|
|
1170
|
+
content.add(under)
|
|
1171
|
+
content.add(ligand_group)
|
|
1172
|
+
for name in ("contacts", "residues"):
|
|
1173
|
+
if drawing.layers.get(name):
|
|
1174
|
+
content.add(Group(name, list(drawing.layers[name])))
|
|
1175
|
+
offset = given.legend_offset() if given is not None else (0.0, 0.0)
|
|
1176
|
+
# Atoms of residues drawn at a level that was asked for carry confidence of their own: the
|
|
1177
|
+
# figure says whether that is each atom's value or its residue's, which depends on the model.
|
|
1178
|
+
basis = None
|
|
1179
|
+
if conf is not None and (drawing.atoms_at_level or drawing.atoms_by_own or any(u.beside for u in dep.units)):
|
|
1180
|
+
basis = "atom" if conf.per_atom else "residue"
|
|
1181
|
+
lost = absence(groups, opts)
|
|
1182
|
+
foot = self._footnotes(opts, drawing.has_distances, levels, drawing.occupancy, drawing.predicted,
|
|
1183
|
+
polymer=bool(dep.units), twice=twice, dep=dep, basis=basis, by_colour=by_colour,
|
|
1184
|
+
glows=drawing.glows, lost=lost)
|
|
1185
|
+
scene = self._frame(content, m, opts, legend=legend,
|
|
1186
|
+
footnotes=foot if opts.caption else (), unsaid=() if opts.caption else foot,
|
|
1187
|
+
legend_offset=offset,
|
|
1188
|
+
strip_data={"plddt-basis": basis} if basis is not None else None)
|
|
1189
|
+
if dep.plane is not None and self._interface is not None:
|
|
1190
|
+
# What was measured of the boxes belongs in what is read out of the figure, too.
|
|
1191
|
+
scene.description = " ".join(t for t in (scene.description, self._interface.described(dep)) if t)
|
|
1192
|
+
lig_box = laid_dep.bounds()
|
|
1193
|
+
quality = self._quality(scene, m, opts, layout, len({g.key for g in groups}), len(drawable),
|
|
1194
|
+
lig_box[2] - lig_box[0], lig_box[3] - lig_box[1],
|
|
1195
|
+
faithful=dep.plane is None or dep.plane.ok)
|
|
1196
|
+
dx, dy = content.translate or (0.0, 0.0)
|
|
1197
|
+
atoms = {a.name: (a.x + dx, a.y + dy) for a in dep.atoms if a.name}
|
|
1198
|
+
graph.origin = (dx, dy)
|
|
1199
|
+
graph.size = (scene.width, scene.height)
|
|
1200
|
+
graph.meta = {"ligand": self.name or "", "n_interactions": len([r for r in drawable if not r.absent])}
|
|
1201
|
+
if any(v is not None for v in self.detail.values()) and not (
|
|
1202
|
+
isinstance(self.backend, Polymer) and self.backend.interface is not None):
|
|
1203
|
+
# Said only where a level was asked for (an interface says it by participant, in its own part).
|
|
1204
|
+
graph.meta["detail"] = dict(self.detail)
|
|
1205
|
+
if basis is not None:
|
|
1206
|
+
graph.meta["plddt_basis"] = basis
|
|
1207
|
+
if isinstance(self.backend, Polymer):
|
|
1208
|
+
graph.meta["chain"] = describe_backend(self.backend)
|
|
1209
|
+
if self.backend.interface is not None:
|
|
1210
|
+
graph.meta["interface"] = self.backend.interface.meta_for(dep)
|
|
1211
|
+
report = self._burial_report()
|
|
1212
|
+
if report is not None:
|
|
1213
|
+
graph.meta["burial"] = report
|
|
1214
|
+
for item in scene.items:
|
|
1215
|
+
if isinstance(item, Group) and item.cls == "legend":
|
|
1216
|
+
# The legend is a node too: it has a place and can be moved, by an offset from
|
|
1217
|
+
# where the page puts it.
|
|
1218
|
+
box = items_bounds(item.items) or (0.0, 0.0, 0.0, 0.0)
|
|
1219
|
+
tx, ty = item.translate or (0.0, 0.0)
|
|
1220
|
+
graph.nodes.append(Node(id="legend", kind="legend", label="Legend", x=tx - dx, y=ty - dy,
|
|
1221
|
+
attrs={"width": round(box[2] - box[0], 3), "height": round(box[3] - box[1], 3),
|
|
1222
|
+
"offset": [offset[0], offset[1]]}))
|
|
1223
|
+
box = items_bounds(content.items) or (0.0, 0.0, 1.0, 1.0)
|
|
1224
|
+
if opts.pae_colors and not drawing.glows:
|
|
1225
|
+
# An option that was asked for and changes nothing is said.
|
|
1226
|
+
notes.append("pae_colors was asked for, and no contact of this figure has a predicted aligned error")
|
|
1227
|
+
return _Composed(scene, layout, quality, notes, atoms, graph, basis, drawing.glows,
|
|
1228
|
+
parts=(style_obj, ctx, bodies, poses, fld, params, content, box))
|
|
1229
|
+
|
|
1230
|
+
def _set_beside(self, drawable: Sequence[ResolvedInteraction]) -> None:
|
|
1231
|
+
"""Tell a chain which atoms of which residue stand beside its box, and on which side.
|
|
1232
|
+
|
|
1233
|
+
Decided by the contacts that are drawn and by the chain's level of detail: a residue with a
|
|
1234
|
+
directional contact is drawn with the part that makes it and what the level adds
|
|
1235
|
+
(:func:`bindview.polymer.shown_atoms`); two such residues that share a partner stand on one
|
|
1236
|
+
side (:func:`bindview.polymer.piece_sides`). A column only: boxes on a plane stay boxes.
|
|
1237
|
+
"""
|
|
1238
|
+
if not isinstance(self.backend, Polymer):
|
|
1239
|
+
return
|
|
1240
|
+
pep = self.backend.peptide
|
|
1241
|
+
shown: dict[int, tuple[int, ...]] = {}
|
|
1242
|
+
sides: dict[int, int] = {}
|
|
1243
|
+
if pep.detail not in (None, "box") and self.backend.arrangement is None:
|
|
1244
|
+
involved: dict[int, set[int]] = {}
|
|
1245
|
+
directional = [r for r in drawable if r.ligand is not None and r.type is not InteractionType.HYDROPHOBIC]
|
|
1246
|
+
for r in directional:
|
|
1247
|
+
assert r.ligand is not None
|
|
1248
|
+
for i in r.ligand.atoms:
|
|
1249
|
+
res = pep.residue_of(i)
|
|
1250
|
+
if res is not None:
|
|
1251
|
+
involved.setdefault(res.position, set()).add(i)
|
|
1252
|
+
shown = shown_atoms(pep, involved)
|
|
1253
|
+
partners: dict[int, set[tuple]] = {}
|
|
1254
|
+
for r in directional:
|
|
1255
|
+
assert r.ligand is not None
|
|
1256
|
+
for i in r.ligand.atoms:
|
|
1257
|
+
res = pep.residue_of(i)
|
|
1258
|
+
if res is not None and i in shown.get(res.position, ()):
|
|
1259
|
+
partners.setdefault(res.position, set()).add(
|
|
1260
|
+
(r.record.chain, r.record.residue_number, r.record.insertion_code))
|
|
1261
|
+
sides = piece_sides([res.position for res in pep.residues if res.position in shown], partners)
|
|
1262
|
+
self.backend.shown, self.backend.sides = shown, sides
|
|
1263
|
+
|
|
1264
|
+
def _confidence_report(self, conf: Confidence, basis: "str | None" = None) -> dict[str, Any]:
|
|
1265
|
+
"""Figure-level confidence as plain data, plus how the contacts fall into bands, each by the
|
|
1266
|
+
number it is drawn at (the one its record carries, else the lower of its two ends); and, where
|
|
1267
|
+
atoms of residues were drawn at a level that was asked for, what each was drawn at (``basis``)."""
|
|
1268
|
+
report = conf.summary()
|
|
1269
|
+
if basis is not None:
|
|
1270
|
+
report["drawn_atoms_at"] = ("each atom's own pLDDT" if basis == "atom" else
|
|
1271
|
+
"their residue's pLDDT: the model gives one value for a residue")
|
|
1272
|
+
bands: dict[str, int] = {}
|
|
1273
|
+
values = []
|
|
1274
|
+
for r in self.interactions:
|
|
1275
|
+
v: "float | None"
|
|
1276
|
+
if r.record.confidence is not None: # as the drawing has it (styles.base.contact_plddt)
|
|
1277
|
+
v = r.record.confidence
|
|
1278
|
+
elif r.ligand is None:
|
|
1279
|
+
continue
|
|
1280
|
+
else:
|
|
1281
|
+
v = conf.contact(r.residue if r.residue is not None else r.record.residue_id,
|
|
1282
|
+
[self.ligand.names[i] for i in r.ligand.atoms])
|
|
1283
|
+
if v is not None:
|
|
1284
|
+
values.append(v)
|
|
1285
|
+
band = look_of(v).band or ""
|
|
1286
|
+
bands[band] = bands.get(band, 0) + 1
|
|
1287
|
+
report["contacts_by_band"] = {k: bands[k] for k in ("very_high", "confident", "low", "very_low") if k in bands}
|
|
1288
|
+
report["contact_plddt_range"] = [round(min(values), 1), round(max(values), 1)] if values else None
|
|
1289
|
+
return report
|
|
1290
|
+
|
|
1291
|
+
def _footnotes(self, opts: RenderOptions, has_distances: bool, levels: "set[int] | None" = None,
|
|
1292
|
+
occupancy: bool = False, predicted: bool = False, polymer: bool = False,
|
|
1293
|
+
twice: Sequence[str] = (), dep: "Depiction | None" = None,
|
|
1294
|
+
basis: "str | None" = None, by_colour: bool = False, glows: bool = False,
|
|
1295
|
+
lost: "Absence | None" = None) -> list[str]:
|
|
1296
|
+
out = []
|
|
1297
|
+
if lost is not None:
|
|
1298
|
+
# First: it is what the figure is for.
|
|
1299
|
+
out.append(lost.sentence)
|
|
1300
|
+
if has_distances:
|
|
1301
|
+
out.append("Distances in \u00c5.")
|
|
1302
|
+
if glows:
|
|
1303
|
+
ends = ("the two residues" if isinstance(self.backend, Polymer) else "the residue and the ligand")
|
|
1304
|
+
out.append(f"A contact stands on a glow in the colour of its PAE (predicted aligned error): how far off, in "
|
|
1305
|
+
f"\u00e5ngstr\u00f6m, the model expects {ends} to be placed against each other. It is not pLDDT.")
|
|
1306
|
+
if by_colour:
|
|
1307
|
+
# What is coloured depends on what the figure is of: an interface has no ligand.
|
|
1308
|
+
what = ("a residue has the colour of its own value, on either side"
|
|
1309
|
+
if isinstance(self.backend, Polymer) and self.backend.interface is not None else
|
|
1310
|
+
"a residue has the colour of its own value, and so has every residue of the ligand"
|
|
1311
|
+
if isinstance(self.backend, Polymer) else
|
|
1312
|
+
"a residue has the colour of its own value, and so has every atom of the ligand")
|
|
1313
|
+
out.append(f"Colour follows the model's pLDDT, in AlphaFold's four bands: {what}. No line is drawn "
|
|
1314
|
+
"weaker for it: a contact is as sure as the less sure of its two ends.")
|
|
1315
|
+
if levels and any(lv > 0 for lv in levels):
|
|
1316
|
+
# An interface has no ligand: there the two ends are the neighbour residue and, on the
|
|
1317
|
+
# column's side, the atoms that make the contact.
|
|
1318
|
+
ends = ("two ends' values" if isinstance(self.backend, Polymer) and self.backend.interface is not None
|
|
1319
|
+
else "ligand-atom and residue values")
|
|
1320
|
+
out.append("Stroke weight and opacity follow the model's pLDDT: a contact is drawn at the lower of its "
|
|
1321
|
+
f"{ends}, a residue at its own. {MARK} marks pLDDT below 50.")
|
|
1322
|
+
if basis == "atom":
|
|
1323
|
+
# Said whether or not anything is drawn weaker: what a drawn atom stands at is a claim either way.
|
|
1324
|
+
out.append("The atoms that are drawn of a residue are each at their own pLDDT: the model gives one "
|
|
1325
|
+
"for every atom.")
|
|
1326
|
+
elif basis == "residue":
|
|
1327
|
+
out.append("The atoms that are drawn of a residue are all at their residue's pLDDT: this model gives "
|
|
1328
|
+
"one value for a residue, not one for each of its atoms.")
|
|
1329
|
+
if occupancy and opts.occupancy_style == "steps":
|
|
1330
|
+
out.append("Stroke weight and opacity follow occupancy, the share of "
|
|
1331
|
+
f"{self.ensemble or 'the ensemble'} in which a contact is made, in three steps (90 % and "
|
|
1332
|
+
"more, 50 to 90 %, less than 50 %); the share is written on "
|
|
1333
|
+
+ ("the line, or under the name of a residue that has none." if opts.occupancy_labels == "all" else
|
|
1334
|
+
"the line of a contact that is not made in all."))
|
|
1335
|
+
elif occupancy:
|
|
1336
|
+
out.append("Stroke weight and opacity follow occupancy: the share of "
|
|
1337
|
+
f"{self.ensemble or 'the ensemble'} in which a contact is made.")
|
|
1338
|
+
# (A figure without a distance on it has nothing to say of whose they are.)
|
|
1339
|
+
out.extend(r if has_distances else r.replace(_WHOSE_DISTANCES, "") for r in self.remarks)
|
|
1340
|
+
if self.elsewhere and self.elsewhere_said[0]:
|
|
1341
|
+
out.append(self.elsewhere_said[0])
|
|
1342
|
+
if predicted:
|
|
1343
|
+
out.append("Predicted water sites are geometric guesses for a model that has no solvent, "
|
|
1344
|
+
f"not observations. {VALIDATION}")
|
|
1345
|
+
if opts.notes:
|
|
1346
|
+
lig = self.ligand
|
|
1347
|
+
if lig.stereo_mismatches and isinstance(self.backend, Polymer):
|
|
1348
|
+
n = len(lig.stereo_mismatches)
|
|
1349
|
+
out.append(f"D and L are those of the reference SMILES; in the model {n} "
|
|
1350
|
+
f"stereocentre{'s' if n != 1 else ''} differ{'' if n != 1 else 's'} from it.")
|
|
1351
|
+
elif lig.stereo_mismatches:
|
|
1352
|
+
n = len(lig.stereo_mismatches)
|
|
1353
|
+
out.append(f"Stereo is drawn as modelled; {n} stereocentre{'s' if n != 1 else ''} "
|
|
1354
|
+
f"differ{'' if n != 1 else 's'} from the reference SMILES.")
|
|
1355
|
+
if lig.artefact_bonds and not self.shares: # of one model, and nothing of its geometry is drawn
|
|
1356
|
+
n = len(lig.artefact_bonds)
|
|
1357
|
+
out.append(f"The model has {n} unbonded ligand atom pair{'s' if n != 1 else ''} at bonding distance.")
|
|
1358
|
+
if not isinstance(self.backend, Polymer): # a chain's gaps are drawn, and said, as gaps
|
|
1359
|
+
out.extend(apart_note(lig, *part) for part in lig.apart())
|
|
1360
|
+
if lig.bond_source == "geometry":
|
|
1361
|
+
out.append("Bond orders inferred from geometry (no SMILES).")
|
|
1362
|
+
elif lig.bond_source == "connectivity":
|
|
1363
|
+
out.append("Bond orders unknown (no SMILES): only connectivity is drawn.")
|
|
1364
|
+
n_un = len(self.unresolved)
|
|
1365
|
+
if n_un:
|
|
1366
|
+
out.append(f"{n_un} reported interaction{'s' if n_un != 1 else ''} could not be attached "
|
|
1367
|
+
f"and {'are' if n_un != 1 else 'is'} not shown.")
|
|
1368
|
+
if polymer:
|
|
1369
|
+
# (Not a note that can be switched off: it says what a number means. A figure that draws the PAE as a
|
|
1370
|
+
# glow has no number on a line.)
|
|
1371
|
+
tags = self._interface.tag_notes if glows and self._interface is not None else ()
|
|
1372
|
+
out.extend(t for t in self.backend.footnotes(dep) if t not in tags)
|
|
1373
|
+
if twice:
|
|
1374
|
+
# Nor is this one: without it two drawings of one residue read as two residues.
|
|
1375
|
+
out.append("Drawn more than once, each time beside the stretch of the "
|
|
1376
|
+
+ ("chain" if getattr(self.backend, "interface", None) is not None else "ligand")
|
|
1377
|
+
+ " it touches there: "
|
|
1378
|
+
+ ", ".join(twice) + ".")
|
|
1379
|
+
return out
|
|
1380
|
+
|
|
1381
|
+
def _frame(self, content: Group, m: Metrics, opts: RenderOptions, *, legend: Sequence[LegendEntry] = (),
|
|
1382
|
+
footnotes: Sequence[str] = (),
|
|
1383
|
+
extra_blocks: Sequence[tuple[Group, float, float]] = (),
|
|
1384
|
+
legend_offset: tuple[float, float] = (0.0, 0.0),
|
|
1385
|
+
strip_data: "Mapping[str, str] | None" = None, unsaid: Sequence[str] = ()) -> Scene:
|
|
1386
|
+
"""Put title, content, legend and footnotes on a page sized to fit them.
|
|
1387
|
+
|
|
1388
|
+
The words around the drawing (the line under the title, a warning above it, the footnotes, and
|
|
1389
|
+
``unsaid``: notes that are not drawn) are kept on the scene as ``notes``; ``bare`` draws none of
|
|
1390
|
+
them."""
|
|
1391
|
+
said: list[str] = []
|
|
1392
|
+
bare = opts.bare
|
|
1393
|
+
box = items_bounds([content]) or (0.0, 0.0, 1.0, 1.0)
|
|
1394
|
+
cw, ch = box[2] - box[0], box[3] - box[1]
|
|
1395
|
+
pad = m.margin
|
|
1396
|
+
inner = max(cw, 150.0)
|
|
1397
|
+
conf = self._shown_confidence(opts)
|
|
1398
|
+
|
|
1399
|
+
top: list[Item] = []
|
|
1400
|
+
y = pad
|
|
1401
|
+
title_w = 0.0
|
|
1402
|
+
banner: list[str] = []
|
|
1403
|
+
if conf is not None and conf.marked:
|
|
1404
|
+
# The caller says this model is not to be trusted: say so in words, at the
|
|
1405
|
+
# top, and frame the whole figure. Faint drawing alone would not be a mark.
|
|
1406
|
+
verdict = f" ({conf.model.flag})" if conf.model is not None and conf.model.flag else ""
|
|
1407
|
+
banner = wrap_text(f"Model flagged as not trustworthy{verdict} \u2014 shown for inspection, "
|
|
1408
|
+
"not as a result.", m.title_font, max(inner, 330.0), bold=True)
|
|
1409
|
+
title_w = max(text_width(line, m.title_font, bold=True) for line in banner)
|
|
1410
|
+
y += len(banner) * m.title_font * 1.45 + pad * 0.9
|
|
1411
|
+
if opts.title:
|
|
1412
|
+
top.append(Text.plain(pad, y + CAP_HEIGHT * m.title_font, opts.title, m.title_font, "text",
|
|
1413
|
+
anchor="start", bold=True))
|
|
1414
|
+
title_w = text_width(opts.title, m.title_font, bold=True)
|
|
1415
|
+
y += m.title_font * 1.5
|
|
1416
|
+
if opts.subtitle:
|
|
1417
|
+
top.append(Text.plain(pad, y + CAP_HEIGHT * m.caption_font, opts.subtitle, m.caption_font,
|
|
1418
|
+
"text_muted", anchor="start"))
|
|
1419
|
+
title_w = max(title_w, text_width(opts.subtitle, m.caption_font))
|
|
1420
|
+
y += m.caption_font * 1.6
|
|
1421
|
+
shown = self.burial() if opts.burial and self._interface is None else None
|
|
1422
|
+
# An interface has neither pocket nor ligand: the column, and the residues around it.
|
|
1423
|
+
spine = isinstance(self.backend, Polymer) and self.backend.interface is not None
|
|
1424
|
+
more = (tuple(self.backend.interface.strip)
|
|
1425
|
+
if isinstance(self.backend, Polymer) and self.backend.interface is not None else ())
|
|
1426
|
+
strip = (_confidence_strip(conf, m.caption_font + 1.0, shown,
|
|
1427
|
+
names=(("residues around", "boxes" if self._interface.shape == "plane" else "column")
|
|
1428
|
+
if spine else ("pocket", "ligand")), more=more,
|
|
1429
|
+
more_data=self._interface.strip_data if self._interface is not None else None)
|
|
1430
|
+
if (conf is not None or shown is not None or more) else None)
|
|
1431
|
+
if strip is not None:
|
|
1432
|
+
said.append(" ".join("".join(s.text for s in strip[0]).split()))
|
|
1433
|
+
if strip is not None and not bare:
|
|
1434
|
+
top.append(Group("confidence", [Text(pad, y + CAP_HEIGHT * strip[1], strip[0], strip[1], "text_muted",
|
|
1435
|
+
anchor="start")],
|
|
1436
|
+
data={k: str(v) for k, v in {**strip[3], **(strip_data or {})}.items()}))
|
|
1437
|
+
title_w = max(title_w, strip[2])
|
|
1438
|
+
y += strip[1] * 1.7
|
|
1439
|
+
warn = shown is not None and self._burial_warning() is not None
|
|
1440
|
+
if warn:
|
|
1441
|
+
said.append(_BURIAL_LINE)
|
|
1442
|
+
if warn and shown is not None and not bare:
|
|
1443
|
+
# Below the calibrated cut the figure says what the number may mean, in words.
|
|
1444
|
+
lines = wrap_text(_BURIAL_LINE, m.caption_font, max(inner, title_w, 330.0))
|
|
1445
|
+
items, height = text_block(lines, pad, y - 2.0, m.caption_font, "warning")
|
|
1446
|
+
top.append(Group("burial-warning", items, data={"buried-fraction": f"{shown.buried_fraction:.3f}"}))
|
|
1447
|
+
title_w = max([title_w] + [text_width(line, m.caption_font) for line in lines])
|
|
1448
|
+
y += height
|
|
1449
|
+
for warned in (self._interface.warnings if self._interface is not None else ()):
|
|
1450
|
+
said.append(warned)
|
|
1451
|
+
if bare:
|
|
1452
|
+
continue
|
|
1453
|
+
# The same place and the same colour for what an interface has to be told about as a whole:
|
|
1454
|
+
# that none of its contacts is placed by the model. The tags on the lines say it one by one.
|
|
1455
|
+
lines = wrap_text(warned, m.caption_font, max(inner, title_w, 330.0))
|
|
1456
|
+
items, height = text_block(lines, pad, y - 2.0, m.caption_font, "warning")
|
|
1457
|
+
top.append(Group("pae-warning", items))
|
|
1458
|
+
title_w = max([title_w] + [text_width(line, m.caption_font) for line in lines])
|
|
1459
|
+
y += height
|
|
1460
|
+
if top:
|
|
1461
|
+
y += 4.0
|
|
1462
|
+
inner = max(inner, title_w)
|
|
1463
|
+
content_top = y
|
|
1464
|
+
y += ch
|
|
1465
|
+
|
|
1466
|
+
blocks: list[tuple[Group, float, float]] = list(extra_blocks)
|
|
1467
|
+
if opts.legend and legend:
|
|
1468
|
+
lg, lw, lh = legend_group(legend, m, max(inner, 300.0))
|
|
1469
|
+
if lh > 0:
|
|
1470
|
+
blocks.append((lg, lw, lh))
|
|
1471
|
+
said.extend(footnotes)
|
|
1472
|
+
said.extend(unsaid)
|
|
1473
|
+
foot_lines: list[str] = []
|
|
1474
|
+
for note in (() if bare else footnotes):
|
|
1475
|
+
foot_lines.extend(wrap_text(note, m.caption_font, max(inner, 300.0)))
|
|
1476
|
+
inner = max([inner] + [bw for _, bw, _ in blocks] +
|
|
1477
|
+
[text_width(line, m.caption_font) for line in foot_lines])
|
|
1478
|
+
|
|
1479
|
+
bottom: list[Item] = []
|
|
1480
|
+
for grp, _bw, bh in blocks:
|
|
1481
|
+
y += 10.0
|
|
1482
|
+
if grp.cls == "legend":
|
|
1483
|
+
grp.translate = (pad + legend_offset[0], y + legend_offset[1])
|
|
1484
|
+
else:
|
|
1485
|
+
grp.translate = (pad, y)
|
|
1486
|
+
bottom.append(grp)
|
|
1487
|
+
y += bh
|
|
1488
|
+
if foot_lines:
|
|
1489
|
+
y += 6.0
|
|
1490
|
+
items, fh = text_block(foot_lines, pad, y, m.caption_font, "text_muted")
|
|
1491
|
+
bottom.append(Group("footnotes", items))
|
|
1492
|
+
y += fh
|
|
1493
|
+
width = inner + 2.0 * pad
|
|
1494
|
+
height = y + pad
|
|
1495
|
+
content.translate = (pad + (inner - cw) / 2.0 - box[0], content_top - box[1])
|
|
1496
|
+
if opts.break_lines:
|
|
1497
|
+
keep_lines_off_words(content)
|
|
1498
|
+
scene = Scene(width, height, title=opts.title or self.name or "Ligand interaction diagram", notes=said)
|
|
1499
|
+
scene.items = top + [content] + bottom
|
|
1500
|
+
if banner:
|
|
1501
|
+
bh = len(banner) * m.title_font * 1.45 + pad * 0.5
|
|
1502
|
+
items, _ = text_block(banner, pad, pad * 0.35, m.title_font, "background", bold=True)
|
|
1503
|
+
flag = Group("model-flag", [Rect(0.0, 0.0, width, bh, Paint(fill="warning"))] + items,
|
|
1504
|
+
data={"trusted": "false"})
|
|
1505
|
+
frame = Rect(1.5, 1.5, width - 3.0, height - 3.0, Paint(stroke="warning", width=3.0, join="miter"))
|
|
1506
|
+
scene.items = [flag] + scene.items + [Group("model-flag-frame", [frame])]
|
|
1507
|
+
interface = self.backend.interface if isinstance(self.backend, Polymer) else None
|
|
1508
|
+
if conf is not None or (interface is not None and interface.strip):
|
|
1509
|
+
scene.description = _confidence_sentence(conf, interface)
|
|
1510
|
+
return scene
|
|
1511
|
+
|
|
1512
|
+
def _quality(self, scene: Scene, m: Metrics, opts: RenderOptions, layout: LayoutResult,
|
|
1513
|
+
n_residues: int, n_interactions: int, ligand_width: float = 0.0, ligand_height: float = 0.0,
|
|
1514
|
+
faithful: bool = True) -> Quality:
|
|
1515
|
+
natural = _smallest_text_pt(m)
|
|
1516
|
+
fit = min(opts.figure_width_mm * _PX_PER_MM / scene.width,
|
|
1517
|
+
opts.figure_height_mm * _PX_PER_MM / scene.height, 1.0)
|
|
1518
|
+
font_pt = natural * fit
|
|
1519
|
+
required = (math.inf if beyond_any_page(natural, opts) else
|
|
1520
|
+
scene.width * (opts.min_font_pt / natural) / _PX_PER_MM)
|
|
1521
|
+
return Quality(
|
|
1522
|
+
width=scene.width, height=scene.height, bond_length=m.bond_length, n_residues=n_residues,
|
|
1523
|
+
n_interactions=n_interactions, overlaps=layout.overlaps, unplaced=len(layout.unplaced),
|
|
1524
|
+
line_crossings=layout.line_crossings, bond_crossings=layout.bond_crossings,
|
|
1525
|
+
max_stretch=layout.max_stretch, min_font_pt=font_pt, required_width_mm=required,
|
|
1526
|
+
readable=font_pt >= opts.min_font_pt - 1e-9, ligand_width=ligand_width, link_hits=layout.link_hits,
|
|
1527
|
+
ligand_height=ligand_height, faithful=faithful)
|
|
1528
|
+
|
|
1529
|
+
def _ligand_only(self, palette: Palette, m: Metrics, opts: RenderOptions) -> Group:
|
|
1530
|
+
dep = self.backend.depict(m, opts.coords)
|
|
1531
|
+
return Group("diagram", [self.backend.draw(dep, palette, m)[0]])
|
|
1532
|
+
|
|
1533
|
+
def _empty_scene(self, palette: Palette, m: Metrics, opts: RenderOptions) -> Scene:
|
|
1534
|
+
content = self._ligand_only(palette, m, opts)
|
|
1535
|
+
headline = "No interactions detected" if self.source == "detected" else "No interactions in the supplied set"
|
|
1536
|
+
near = self.proximal_residues()
|
|
1537
|
+
if self.source == "detected":
|
|
1538
|
+
body = "Detection ran on this complex and no contact met the criteria for a typed interaction."
|
|
1539
|
+
else:
|
|
1540
|
+
body = "The interaction list supplied for this ligand is empty: it was analysed and nothing was found."
|
|
1541
|
+
if near:
|
|
1542
|
+
body += (f" {len(near)} residue{'s' if len(near) != 1 else ''} "
|
|
1543
|
+
f"{'lie' if len(near) != 1 else 'lies'} within 4.5 Å of the ligand "
|
|
1544
|
+
f"({', '.join(near)}).")
|
|
1545
|
+
elif self.structure is not None:
|
|
1546
|
+
body += " No residue lies within 4.5 Å of the ligand."
|
|
1547
|
+
if self.remarks:
|
|
1548
|
+
body += " " + " ".join(self.remarks + [s for s in self.elsewhere_said[1:] if s])
|
|
1549
|
+
wrap = 330.0
|
|
1550
|
+
head_items, hh = text_block([headline], 0.0, 0.0, m.title_font, "text", bold=True)
|
|
1551
|
+
body_items, bh = text_block(wrap_text(body, m.caption_font, wrap), 0.0, hh + 3.0, m.caption_font, "text_muted")
|
|
1552
|
+
block = Group("empty-state", head_items + body_items)
|
|
1553
|
+
block.translate = None
|
|
1554
|
+
spacer = Group("spacer")
|
|
1555
|
+
return self._frame(content, m, opts, extra_blocks=[(spacer, 0.0, 2.0), (block, wrap, hh + 3.0 + bh)])
|
|
1556
|
+
|
|
1557
|
+
def _summary_scene(self, m: Metrics, opts: RenderOptions, drawable: Sequence[ResolvedInteraction], q: Quality,
|
|
1558
|
+
reason: str) -> Scene:
|
|
1559
|
+
# A table of this structure's contacts: what only other models make is not one of them.
|
|
1560
|
+
groups = group_residues([r for r in drawable if not r.absent], opts.show_chain)
|
|
1561
|
+
mark_groups(groups, opts)
|
|
1562
|
+
max_w = opts.figure_width_mm * _PX_PER_MM - 2.0 * m.margin
|
|
1563
|
+
conf = self._shown_confidence(opts)
|
|
1564
|
+
plddt = {}
|
|
1565
|
+
if conf is not None:
|
|
1566
|
+
for g in groups:
|
|
1567
|
+
first = g.interactions[0]
|
|
1568
|
+
value = conf.residue(first.residue if first.residue is not None else g.key)
|
|
1569
|
+
if value is not None:
|
|
1570
|
+
plddt[g.key] = value
|
|
1571
|
+
table, tw, _ = summary_table(groups, m, max_w, plddt or None)
|
|
1572
|
+
headline = "Residue-level summary"
|
|
1573
|
+
why = (f"{self._what().capitalize()} of this complex is not readable at {opts.figure_width_mm:g} mm "
|
|
1574
|
+
f"({self._size()}, {q.n_residues} residues, {q.n_interactions} interactions): "
|
|
1575
|
+
f"{reason}. Contacts are listed per residue instead.")
|
|
1576
|
+
head_items, hh = text_block([headline], 0.0, 0.0, m.title_font, "text", bold=True)
|
|
1577
|
+
why_items, wh = text_block(wrap_text(why, m.caption_font, max(tw, 360.0)), 0.0, hh + 3.0,
|
|
1578
|
+
m.caption_font, "warning")
|
|
1579
|
+
table.translate = (0.0, hh + wh + 14.0)
|
|
1580
|
+
content = Group("diagram", head_items + why_items + [table])
|
|
1581
|
+
foot = ["Dots mark interaction types; ×n gives the count. 'closest' is the shortest reported distance."]
|
|
1582
|
+
if plddt:
|
|
1583
|
+
foot.append(f"pLDDT is the residue's own (mean over its atoms); {MARK} marks values below 50.")
|
|
1584
|
+
if any(g.beyond for g in groups):
|
|
1585
|
+
foot.append("† outside the supplied contact set")
|
|
1586
|
+
lost = absence(groups, opts)
|
|
1587
|
+
if lost is not None:
|
|
1588
|
+
how = "In italics" if opts.absent_style == "faint" else "Marked"
|
|
1589
|
+
foot.append((f"{how}: absent from {from_whom(opts.absent_label)}. " if lost.absent else "") + lost.sentence)
|
|
1590
|
+
foot.extend(self.remarks + [s for s in self.elsewhere_said[1:] if s])
|
|
1591
|
+
if isinstance(self.backend, Polymer) and self.backend.interface is not None:
|
|
1592
|
+
# No line is left to carry a predicted aligned error: what it is, and the warning, stay.
|
|
1593
|
+
foot.extend(self.backend.interface.summary_notes)
|
|
1594
|
+
return self._frame(content, m, RenderOptions(**{**opts.__dict__, "legend": False}), footnotes=foot)
|
|
1595
|
+
|
|
1596
|
+
|
|
1597
|
+
_SUB = str.maketrans("0123456789", "₀₁₂₃₄₅₆₇₈₉")
|
|
1598
|
+
_SUP = str.maketrans("0123456789", "⁰¹²³⁴⁵⁶⁷⁸⁹")
|
|
1599
|
+
|
|
1600
|
+
|
|
1601
|
+
def _give_pae(resolved: "Sequence[ResolvedInteraction]", pae: "Pae | PaeDraws", lig: Ligand, st: Structure,
|
|
1602
|
+
key: ResidueKey) -> None:
|
|
1603
|
+
"""Give every contact that has none of its own the predicted aligned error between its two ends: the residue,
|
|
1604
|
+
and the atoms of the ligand that make it (or, of a ligand that is a chain, the residue of it they are of)."""
|
|
1605
|
+
heavy = [a.name for a in st.residue_atoms(key) if a.element not in ("H", "D")]
|
|
1606
|
+
unit = {} # an atom of a chain ligand: the residue it is of
|
|
1607
|
+
for r in lig.given:
|
|
1608
|
+
digits = r.number.rstrip("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz")
|
|
1609
|
+
for name in r.atoms:
|
|
1610
|
+
unit[name] = ResidueKey(lig.chain or key.chain, int(digits), r.number[len(digits):])
|
|
1611
|
+
found = False
|
|
1612
|
+
for r in resolved:
|
|
1613
|
+
if r.ligand is None or r.residue is None or r.record.pae is not None:
|
|
1614
|
+
found = found or r.record.pae is not None
|
|
1615
|
+
continue
|
|
1616
|
+
names = [lig.names[i] for i in r.ligand.atoms]
|
|
1617
|
+
values: list[Any] = []
|
|
1618
|
+
if unit:
|
|
1619
|
+
for end in dict.fromkeys(unit[n] for n in names if n in unit):
|
|
1620
|
+
values.append((pae.between(r.residue, end), pae.each(r.residue, end) if isinstance(pae, PaeDraws) else ()))
|
|
1621
|
+
else:
|
|
1622
|
+
atoms = ([heavy.index(n) for n in names if n in heavy], len(heavy))
|
|
1623
|
+
values.append((pae.between(r.residue, key, atoms),
|
|
1624
|
+
pae.each(r.residue, key, atoms) if isinstance(pae, PaeDraws) else ()))
|
|
1625
|
+
known = [v for v in values if v[0] is not None]
|
|
1626
|
+
if known:
|
|
1627
|
+
value, draws = min(known, key=lambda v: v[0])
|
|
1628
|
+
found = True
|
|
1629
|
+
r.record = r.record.with_(pae=value, pae_draws=tuple(v for v in draws if v is not None)
|
|
1630
|
+
if all(v is not None for v in draws) else ())
|
|
1631
|
+
if resolved and not found:
|
|
1632
|
+
raise RenderError(f"{pae.source or 'the PAE matrix'} has no value for any contact of this ligand: its rows are of "
|
|
1633
|
+
f"chains {', '.join(repr(n) for n in sorted(set(pae.chains)))}, residue numbers "
|
|
1634
|
+
f"{min(pae.numbers)} to {max(pae.numbers)}")
|
|
1635
|
+
|
|
1636
|
+
|
|
1637
|
+
def apart_note(lig: Ligand, part: "tuple[int, ...]", metal: "tuple[int, float] | None",
|
|
1638
|
+
nearest: "tuple[int, float]") -> str:
|
|
1639
|
+
"""The note on a part of the ligand that the model binds to nothing else of it (:meth:`Ligand.apart`).
|
|
1640
|
+
|
|
1641
|
+
It is drawn beside the rest, as it is in the model; without a word a reader takes it for a part the
|
|
1642
|
+
drawing lost, or one that sits where chemistry says (a hydroxide on its cobalt)."""
|
|
1643
|
+
if len(part) == 1:
|
|
1644
|
+
a = lig.mol.GetAtomWithIdx(part[0])
|
|
1645
|
+
h, q = a.GetTotalNumHs(), a.GetFormalCharge()
|
|
1646
|
+
formula = a.GetSymbol() + ("H" + (str(h) if h > 1 else "") if h else "").translate(_SUB)
|
|
1647
|
+
if q:
|
|
1648
|
+
formula += (str(abs(q)) if abs(q) > 1 else "").translate(_SUP) + ("⁺" if q > 0 else "⁻")
|
|
1649
|
+
what = f"{lig.names[part[0]]} ({formula})" if formula != a.GetSymbol() else lig.names[part[0]]
|
|
1650
|
+
else:
|
|
1651
|
+
names = [lig.names[i] for i in part]
|
|
1652
|
+
what = ("the part " + ", ".join(names[:-1]) + " and " + names[-1]) if len(names) <= 4 \
|
|
1653
|
+
else f"a part of {len(names)} atoms ({', '.join(names[:3])}, ...)"
|
|
1654
|
+
where = [f"{nearest[1]:.1f} Å from {lig.names[nearest[0]]}, the nearest atom"]
|
|
1655
|
+
if metal is not None and metal[0] != nearest[0]:
|
|
1656
|
+
where.insert(0, f"{metal[1]:.1f} Å from the metal {lig.names[metal[0]]}")
|
|
1657
|
+
elif metal is not None:
|
|
1658
|
+
where = [f"{nearest[1]:.1f} Å from the metal {lig.names[metal[0]]}, the nearest atom"]
|
|
1659
|
+
return (f"In the model {what} is bound to no other atom of the ligand, and is drawn apart: "
|
|
1660
|
+
+ " and ".join(where) + ".")
|
|
1661
|
+
|
|
1662
|
+
|
|
1663
|
+
def _details(detail: "str | Mapping[str, str | None] | None") -> dict[str, "str | None"]:
|
|
1664
|
+
"""``detail`` as it was given, for the two sides of a diagram: one level for both, or one for each
|
|
1665
|
+
under ``"ligand"`` and ``"protein"``."""
|
|
1666
|
+
if detail is None or isinstance(detail, str):
|
|
1667
|
+
level = check_detail(detail)
|
|
1668
|
+
return {"ligand": level, "protein": level}
|
|
1669
|
+
unknown = [k for k in detail if k not in ("ligand", "protein")]
|
|
1670
|
+
if unknown:
|
|
1671
|
+
raise ValueError(f"detail is a level, or one for each of 'ligand' and 'protein'; not for {unknown[0]!r}")
|
|
1672
|
+
return {side: check_detail(detail.get(side), f"detail of the {side}") for side in ("ligand", "protein")}
|
|
1673
|
+
|
|
1674
|
+
|
|
1675
|
+
def _confidence_for(st: Structure, key: ResidueKey, plddt: Any, model_confidence: Any,
|
|
1676
|
+
trusted: bool | None, flag: str | None) -> Confidence | None:
|
|
1677
|
+
"""Decide whether, and from where, confidence may be read. The guard lives here.
|
|
1678
|
+
|
|
1679
|
+
The B-factor column is read as pLDDT only if the file declares it
|
|
1680
|
+
(``plddt="auto"``) or the caller asserts it (``"bfactor"``); never because
|
|
1681
|
+
the numbers happen to look like one.
|
|
1682
|
+
"""
|
|
1683
|
+
conf: Confidence | None
|
|
1684
|
+
if isinstance(plddt, Confidence):
|
|
1685
|
+
conf = plddt
|
|
1686
|
+
elif plddt is None or plddt is False or (isinstance(plddt, str) and plddt.lower() in ("off", "none")):
|
|
1687
|
+
conf = None
|
|
1688
|
+
elif plddt is True or (isinstance(plddt, str) and plddt.lower() == "auto"):
|
|
1689
|
+
conf = Confidence.from_structure(st, key, scale=st.plddt_scale or 1.0, origin="declared") \
|
|
1690
|
+
if st.declares_plddt else None
|
|
1691
|
+
elif isinstance(plddt, str) and plddt.lower() in ("bfactor", "bfactor01"):
|
|
1692
|
+
# The caller's assertion, and with it the scale: 0-100, or 0-1 ("bfactor01"). A column that
|
|
1693
|
+
# cannot be on the scale asserted is refused there (Confidence.from_structure), not rescaled.
|
|
1694
|
+
conf = Confidence.from_structure(st, key, scale=100.0 if plddt.lower() == "bfactor01" else 1.0,
|
|
1695
|
+
origin="asserted")
|
|
1696
|
+
if conf is None:
|
|
1697
|
+
raise ValueError(f"plddt={plddt!r} was asked for, but {st.source or 'the structure'} has no B-factor "
|
|
1698
|
+
f"column")
|
|
1699
|
+
else:
|
|
1700
|
+
raise ValueError(f"plddt must be 'auto', 'bfactor', 'bfactor01', None or a Confidence, not {plddt!r}")
|
|
1701
|
+
|
|
1702
|
+
model: ModelConfidence | None
|
|
1703
|
+
if isinstance(model_confidence, str) and model_confidence.lower() == "auto":
|
|
1704
|
+
# A sidecar is only looked for next to a file that is a predicted model.
|
|
1705
|
+
beside = ModelConfidence.beside(st.source) if (st.source and conf is not None) else None
|
|
1706
|
+
model = ModelConfidence.from_json(beside) if beside is not None else (conf.model if conf else None)
|
|
1707
|
+
else:
|
|
1708
|
+
model = ModelConfidence.coerce(model_confidence)
|
|
1709
|
+
if trusted is not None or flag is not None:
|
|
1710
|
+
base = model or ModelConfidence()
|
|
1711
|
+
model = ModelConfidence(base.iptm, base.ptm, base.ranking_score,
|
|
1712
|
+
trusted=base.trusted if trusted is None else bool(trusted),
|
|
1713
|
+
flag=flag if flag is not None else base.flag)
|
|
1714
|
+
if model is None:
|
|
1715
|
+
return conf
|
|
1716
|
+
if conf is None:
|
|
1717
|
+
# Model-level evidence without per-atom values: still worth displaying.
|
|
1718
|
+
return Confidence({}, {}, origin="supplied", model=model)
|
|
1719
|
+
return conf.with_model(model)
|
|
1720
|
+
|
|
1721
|
+
|
|
1722
|
+
#: What the figure says, when asked to show burial, about a ligand below the calibrated cut.
|
|
1723
|
+
_BURIAL_LINE = ("Most of the ligand's surface is open to solvent in this model: the site may be incomplete here "
|
|
1724
|
+
"(one chain of an oligomer, a missing cofactor), or the ligand may not sit in a pocket.")
|
|
1725
|
+
|
|
1726
|
+
|
|
1727
|
+
def _confidence_strip(conf: "Confidence | None", size: float, burial: "Burial | None" = None,
|
|
1728
|
+
names: tuple[str, str] = ("pocket", "ligand"), more: "Sequence[tuple[str, str]]" = (),
|
|
1729
|
+
more_data: "Mapping[str, str] | None" = None
|
|
1730
|
+
) -> "tuple[tuple[Span, ...], float, float, dict[str, Any]] | None":
|
|
1731
|
+
"""The figure-level line of provenance numbers: ipTM, mean pocket pLDDT, mean ligand pLDDT,
|
|
1732
|
+
and -- when ``burial`` is given -- the ligand's buried fraction beside them.
|
|
1733
|
+
|
|
1734
|
+
Returns ``(spans, font size, width, data attributes)``, or ``None`` when
|
|
1735
|
+
there is nothing to say.
|
|
1736
|
+
"""
|
|
1737
|
+
parts: list[tuple[str, str]] = []
|
|
1738
|
+
data: dict[str, Any] = {}
|
|
1739
|
+
m = conf.model if conf is not None else None
|
|
1740
|
+
if m is not None and m.iptm is not None:
|
|
1741
|
+
parts.append(("ipTM", f"{m.iptm:.2f}"))
|
|
1742
|
+
data["iptm"] = f"{m.iptm:.2f}"
|
|
1743
|
+
if conf is not None and conf.pocket_plddt is not None:
|
|
1744
|
+
parts.append((f"{names[0]} pLDDT", f"{conf.pocket_plddt:.0f}"))
|
|
1745
|
+
data["pocket-plddt"] = f"{conf.pocket_plddt:.1f}"
|
|
1746
|
+
if conf is not None and conf.ligand_plddt is not None:
|
|
1747
|
+
parts.append((f"{names[1]} pLDDT", f"{conf.ligand_plddt:.0f}"))
|
|
1748
|
+
data["ligand-plddt"] = f"{conf.ligand_plddt:.1f}"
|
|
1749
|
+
for label, value in more:
|
|
1750
|
+
# Not pLDDT: a number of its own, named (the predicted aligned error of an interface's contacts).
|
|
1751
|
+
parts.append((label, value))
|
|
1752
|
+
data.update(more_data or {})
|
|
1753
|
+
if m is not None and m.flag and m.trusted:
|
|
1754
|
+
parts.append(("", m.flag))
|
|
1755
|
+
head = "Model confidence " if parts else ""
|
|
1756
|
+
if burial is not None and burial.sasa_free > 0.0:
|
|
1757
|
+
# Not a confidence, but the same kind of number: what stands behind the picture.
|
|
1758
|
+
parts.append(("ligand buried" if parts else "Ligand buried", f"{100.0 * burial.buried_fraction:.0f} %"))
|
|
1759
|
+
data["buried-fraction"] = f"{burial.buried_fraction:.3f}"
|
|
1760
|
+
if not parts:
|
|
1761
|
+
return None
|
|
1762
|
+
spans: list[Span] = [Span(head)] if head else []
|
|
1763
|
+
width = text_width(head, size) if head else 0.0
|
|
1764
|
+
for k, (label, value) in enumerate(parts):
|
|
1765
|
+
lead = (" \u00b7 " if k else "") + (label + " " if label else "")
|
|
1766
|
+
spans.append(Span(lead))
|
|
1767
|
+
spans.append(Span(value, fill="text", bold=True))
|
|
1768
|
+
width += text_width(lead, size) + text_width(value, size, bold=True)
|
|
1769
|
+
return tuple(spans), size, width, data
|
|
1770
|
+
|
|
1771
|
+
|
|
1772
|
+
def _confidence_sentence(conf: "Confidence | None", interface: Any = None) -> str:
|
|
1773
|
+
"""The same evidence as one plain sentence, for the SVG description.
|
|
1774
|
+
|
|
1775
|
+
``interface`` is what an interface figure says about itself: it has
|
|
1776
|
+
neither pocket nor ligand, and its predicted aligned error and what that
|
|
1777
|
+
means for the figure belong in the sentence as much as under the title.
|
|
1778
|
+
"""
|
|
1779
|
+
bits = []
|
|
1780
|
+
m = conf.model if conf is not None else None
|
|
1781
|
+
whole = "the boxes" if getattr(interface, "shape", "column") == "plane" else "the column"
|
|
1782
|
+
if m is not None and m.iptm is not None:
|
|
1783
|
+
bits.append(f"ipTM {m.iptm:.2f}")
|
|
1784
|
+
if conf is not None and conf.pocket_plddt is not None:
|
|
1785
|
+
bits.append(f"mean pocket pLDDT {conf.pocket_plddt:.0f}" if interface is None
|
|
1786
|
+
else f"mean pLDDT {conf.pocket_plddt:.0f} of the residues around {whole}")
|
|
1787
|
+
if conf is not None and conf.ligand_plddt is not None:
|
|
1788
|
+
bits.append(f"mean ligand pLDDT {conf.ligand_plddt:.0f}" if interface is None
|
|
1789
|
+
else f"mean pLDDT {conf.ligand_plddt:.0f} of {whole}")
|
|
1790
|
+
if interface is not None:
|
|
1791
|
+
bits.extend(f"{label} {value}" for label, value in interface.strip)
|
|
1792
|
+
text = "Predicted model: " + ", ".join(bits) + "." if bits else ""
|
|
1793
|
+
if conf is not None and conf.marked:
|
|
1794
|
+
verdict = f" ({m.flag})" if m is not None and m.flag else ""
|
|
1795
|
+
text = (text + " " if text else "") + f"Flagged as not trustworthy{verdict}."
|
|
1796
|
+
if interface is not None:
|
|
1797
|
+
for said in interface.warnings:
|
|
1798
|
+
text = (text + " " if text else "") + said[:1].upper() + said[1:]
|
|
1799
|
+
return text
|
|
1800
|
+
|
|
1801
|
+
|
|
1802
|
+
def _check_sizes(opts: RenderOptions) -> None:
|
|
1803
|
+
"""Refuse a page, a size of text or a scale that is none, before anything is drawn for it: a
|
|
1804
|
+
:class:`~bindview.errors.RenderError`, which the command line and the page for arranging report in words."""
|
|
1805
|
+
def number(value: Any) -> bool:
|
|
1806
|
+
return isinstance(value, numbers.Real) and not isinstance(value, bool) and math.isfinite(value)
|
|
1807
|
+
|
|
1808
|
+
for name, side in (("figure_width_mm", "width"), ("figure_height_mm", "height")):
|
|
1809
|
+
value = getattr(opts, name)
|
|
1810
|
+
if not number(value) or value <= 0:
|
|
1811
|
+
raise RenderError(f"{name} is the {side} of the page in millimetres, a positive number, not {value!r}")
|
|
1812
|
+
if not number(opts.min_font_pt) or opts.min_font_pt < 0:
|
|
1813
|
+
raise RenderError("min_font_pt is the smallest text that counts as legible, in points: a number that is not "
|
|
1814
|
+
f"negative, not {opts.min_font_pt!r}")
|
|
1815
|
+
scale = opts.bond_length
|
|
1816
|
+
if scale is not None and (not number(scale) or not 0 < scale <= _BOND_LENGTH_MAX):
|
|
1817
|
+
raise RenderError(f"bond_length is the length of a bond in page units, a positive number of at most "
|
|
1818
|
+
f"{_BOND_LENGTH_MAX:g} (or None: the largest that fits the page), not {scale!r}")
|
|
1819
|
+
|
|
1820
|
+
|
|
1821
|
+
def _kind(key: tuple) -> str:
|
|
1822
|
+
"""Which kind of thing a diagram keeps under ``key`` (:data:`_KEPT_AT_MOST`)."""
|
|
1823
|
+
return key[0] if key[0] in ("field", "layout") else "figure"
|
|
1824
|
+
|
|
1825
|
+
|
|
1826
|
+
def _crowded(n: int) -> int:
|
|
1827
|
+
"""With this many of ``n`` residues without a place after the first round of exchanges the first layout of a chain is so
|
|
1828
|
+
crowded that ``effort="quick"`` looks at the roomiest (docs/reference.md has the numbers) ..."""
|
|
1829
|
+
return max(4, math.ceil(n / 10.0))
|
|
1830
|
+
|
|
1831
|
+
|
|
1832
|
+
def _hopeless(n: int) -> int:
|
|
1833
|
+
"""... and with this many that one is."""
|
|
1834
|
+
return max(3, math.ceil(n / 15.0))
|
|
1835
|
+
|
|
1836
|
+
|
|
1837
|
+
def _set_fans(bodies: Sequence[Any]) -> None:
|
|
1838
|
+
"""Tell links that share a ligand site how far apart they should like to be.
|
|
1839
|
+
|
|
1840
|
+
``n`` links into one atom, ring or group ideally split the circle evenly;
|
|
1841
|
+
asking for 80 % of that (capped at a right angle) leaves room for the site's
|
|
1842
|
+
own bonds while still making the partners surround it.
|
|
1843
|
+
"""
|
|
1844
|
+
count: dict[tuple[float, float], int] = {}
|
|
1845
|
+
for body in bodies:
|
|
1846
|
+
for port in body.ports:
|
|
1847
|
+
if port.drawn:
|
|
1848
|
+
key = (round(port.target[0], 2), round(port.target[1], 2))
|
|
1849
|
+
count[key] = count.get(key, 0) + 1
|
|
1850
|
+
for body in bodies:
|
|
1851
|
+
changed = False
|
|
1852
|
+
for port in body.ports:
|
|
1853
|
+
n = count.get((round(port.target[0], 2), round(port.target[1], 2)), 0)
|
|
1854
|
+
if port.drawn and n >= 2:
|
|
1855
|
+
port.fan = min(math.pi / 2.0, 0.8 * 2.0 * math.pi / n)
|
|
1856
|
+
changed = True
|
|
1857
|
+
if changed:
|
|
1858
|
+
body.__post_init__()
|
|
1859
|
+
|
|
1860
|
+
|
|
1861
|
+
def _smallest_text_pt(m: Metrics) -> float:
|
|
1862
|
+
"""The smallest text of a diagram at full size, in points: what a page can at most leave of it."""
|
|
1863
|
+
return _PT_PER_PX * min(m.distance_font, m.protein_atom_font, m.sub_font, m.charge_font, m.legend_font,
|
|
1864
|
+
m.caption_font)
|
|
1865
|
+
|
|
1866
|
+
|
|
1867
|
+
def _scaled(base: Metrics, bond_length: float) -> Metrics:
|
|
1868
|
+
"""Metrics for a different bond length: geometry scales, text does not."""
|
|
1869
|
+
k = bond_length / base.bond_length
|
|
1870
|
+
if abs(k - 1.0) < 1e-9:
|
|
1871
|
+
return base
|
|
1872
|
+
return base.with_(bond_length=bond_length, bond_width=max(1.2, base.bond_width * (0.55 + 0.45 * k)),
|
|
1873
|
+
double_offset=max(3.0, base.double_offset * k), wedge_width=max(4.4, base.wedge_width * k),
|
|
1874
|
+
hash_spacing=max(2.2, base.hash_spacing * k))
|
|
1875
|
+
|
|
1876
|
+
|
|
1877
|
+
def _better(a: Quality, b: Quality) -> bool:
|
|
1878
|
+
"""Is layout ``a`` preferable to ``b`` when neither is fully acceptable?"""
|
|
1879
|
+
if a.valid != b.valid:
|
|
1880
|
+
return a.valid
|
|
1881
|
+
return a.min_font_pt > b.min_font_pt + 1e-9
|
|
1882
|
+
|
|
1883
|
+
|
|
1884
|
+
def _dedupe(items: Sequence[str]) -> list[str]:
|
|
1885
|
+
seen: set[str] = set()
|
|
1886
|
+
out = []
|
|
1887
|
+
for it in items:
|
|
1888
|
+
if it not in seen:
|
|
1889
|
+
seen.add(it)
|
|
1890
|
+
out.append(it)
|
|
1891
|
+
return out
|