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/styles/base.py
ADDED
|
@@ -0,0 +1,2128 @@
|
|
|
1
|
+
"""Pieces every style needs: grouping interactions by residue, finding where a
|
|
2
|
+
link lands on the ligand, drawing link lines, eyelashes, spokes and the legend.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import math
|
|
8
|
+
from dataclasses import dataclass, field, replace
|
|
9
|
+
from typing import TYPE_CHECKING, Any, Mapping, Sequence
|
|
10
|
+
|
|
11
|
+
import numpy as np
|
|
12
|
+
|
|
13
|
+
from ..confidence import (LOOKS, MARK, OCCUPANCY_SAMPLES, OCCUPANCY_STEPS, PLAIN, SHARE_WRITTEN_BELOW, Confidence,
|
|
14
|
+
Look, look_of, occupancy_factors)
|
|
15
|
+
from ..depict import Depiction
|
|
16
|
+
from ..pae import PAE_BANDS, pae_band, pae_tag
|
|
17
|
+
from ..geometry import (Point, add, angle_diff, dist, lerp, mul, perp, polygon_area, resample_closed, sub, unit)
|
|
18
|
+
from ..layout.body import SPRINGS, Port
|
|
19
|
+
from ..layout.field import LigandField
|
|
20
|
+
from ..interactions import InteractionType
|
|
21
|
+
from ..interactive import NUMBER
|
|
22
|
+
from ..ligand import Ligand
|
|
23
|
+
from ..residues import ATOM_LABELS, can_donate, charged_groups, format_residue_label, is_backbone_atom, is_nucleotide, residue_class
|
|
24
|
+
from ..resolve import Anchor, ResolvedInteraction
|
|
25
|
+
from ..scene import Circle, Group, Item, Line, Paint, Polygon, Polyline, Rect, Text
|
|
26
|
+
from ..textmetrics import CAP_HEIGHT, text_width
|
|
27
|
+
from ..theme import Metrics, Palette
|
|
28
|
+
from . import absence as other_protein
|
|
29
|
+
from .rings import ring_sample
|
|
30
|
+
|
|
31
|
+
if TYPE_CHECKING:
|
|
32
|
+
from ..consensus import ResidueShare
|
|
33
|
+
|
|
34
|
+
__all__ = [
|
|
35
|
+
"link_legend",
|
|
36
|
+
"ResidueGroup", "group_residues", "Target", "ligand_target", "LinkStyle", "LINK_STYLES",
|
|
37
|
+
"link_items", "eyelash_items", "eyelash_mark", "spoke_items", "legend_group", "Context", "RenderOptions",
|
|
38
|
+
"hbond_direction", "halo_items", "LABELLED_BY_DEFAULT", "interaction_title", "spoke_reach", "halo_radius",
|
|
39
|
+
"group_skeleton", "PortInfo", "port_infos", "make_ports", "label_size", "LegendEntry", "StyleDrawing",
|
|
40
|
+
"VISIBLE_LENGTH", "interaction_data", "contact_plddt", "residue_plddt", "confidence_legend", "charge_legend",
|
|
41
|
+
"marked_label", "residue_occupancy", "occupancy_legend", "absent_legend", "ABSENT_OPACITY", "share_label",
|
|
42
|
+
"PREDICTED_LABEL", "predicted_style",
|
|
43
|
+
"predicted_items", "predicted_legend", "CHAIN_CONTACT", "CHAIN_CONTACT_LENGTH", "set_lanes", "tag_slack",
|
|
44
|
+
"split_along_chain", "chain_index", "SPLIT_GAP", "beyond_any_page",
|
|
45
|
+
"page_that_would_do", "too_small_on_page",
|
|
46
|
+
"RESIDUE_FORMS", "LININGS", "LINES", "LineSet", "Settings", "STYLE_SETTINGS", "residue_names", "Drawn",
|
|
47
|
+
"finish_drawing", "LiningClaim", "lining_claims", "lining_items", "contact_face", "EXPOSED_FROM",
|
|
48
|
+
]
|
|
49
|
+
|
|
50
|
+
#: What a predicted solvent site is called on the figure, on the line where a water would be.
|
|
51
|
+
PREDICTED_LABEL = "pred. H\u2082O"
|
|
52
|
+
|
|
53
|
+
T = InteractionType
|
|
54
|
+
|
|
55
|
+
#: Interaction types whose distance is printed on the line unless asked otherwise.
|
|
56
|
+
#: Atom-to-atom distances are; centre-to-centre ones (rings, charge centres) are
|
|
57
|
+
#: carried in the SVG as data and tooltips but would only clutter the drawing.
|
|
58
|
+
LABELLED_BY_DEFAULT = frozenset({T.HBOND, T.HALOGEN, T.METAL, T.WATER_BRIDGE})
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
#: How a residue beside the ligand can be drawn (``RenderOptions.residues``).
|
|
62
|
+
RESIDUE_FORMS = ("atoms", "bubbles", "names")
|
|
63
|
+
#: What the lining of the pocket can follow (``RenderOptions.lining``).
|
|
64
|
+
LININGS = ("contacts", "nearest", "none")
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _residues_option(value: Any) -> Any:
|
|
68
|
+
"""``residues`` as it is kept: None, one form, or the pairs of a mapping in a fixed order."""
|
|
69
|
+
if value is None or isinstance(value, str):
|
|
70
|
+
if value is not None and value not in RESIDUE_FORMS:
|
|
71
|
+
raise ValueError(f"residues is one of {', '.join(map(repr, RESIDUE_FORMS))}, or a mapping from a "
|
|
72
|
+
f"residue to one of them, not {value!r}")
|
|
73
|
+
return value
|
|
74
|
+
pairs = tuple(sorted((str(k), str(v)) for k, v in dict(value).items()))
|
|
75
|
+
for name, form in pairs:
|
|
76
|
+
if form not in RESIDUE_FORMS:
|
|
77
|
+
raise ValueError(f"residues: {name} is to be drawn as one of {', '.join(map(repr, RESIDUE_FORMS))}, "
|
|
78
|
+
f"not {form!r}")
|
|
79
|
+
return pairs
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
#: Where ``plddt_colors`` puts the colour, and how a predicted water stands on its line.
|
|
83
|
+
PLDDT_PLACES = ("behind", "bonds")
|
|
84
|
+
SOLVENT_MARKS = ("glow", "filled", "outline")
|
|
85
|
+
#: The words of the options that are one word of a few and have no list elsewhere.
|
|
86
|
+
_WORDS = {"distance_labels": ("auto", "all", "none"), "show_chain": ("auto", "always", "never"),
|
|
87
|
+
"on_unreadable": ("summary", "render", "none"), "coords": ("auto", "coordgen", "rdkit")}
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
@dataclass(frozen=True)
|
|
91
|
+
class RenderOptions:
|
|
92
|
+
title: str | None = None
|
|
93
|
+
subtitle: str | None = None
|
|
94
|
+
legend: bool = True
|
|
95
|
+
caption: bool = True
|
|
96
|
+
notes: bool = True
|
|
97
|
+
distance_labels: str = "auto" # auto | all | none
|
|
98
|
+
show_chain: str = "auto" # auto | always | never
|
|
99
|
+
figure_width_mm: float = 180.0
|
|
100
|
+
figure_height_mm: float = 240.0
|
|
101
|
+
min_font_pt: float = 5.0
|
|
102
|
+
bond_length: float | None = None # None = pick the largest readable one
|
|
103
|
+
on_unreadable: str = "summary" # summary | render | none
|
|
104
|
+
#: How long to try with a ligand that is drawn as a chain of residues, whose figure is tried with more and
|
|
105
|
+
#: more room along the chain while it is too crowded: ``"full"``, until it is legible or six layouts were
|
|
106
|
+
#: not; or ``"quick"``, which, when the first layout is very crowded, looks at the roomiest one that the
|
|
107
|
+
#: page allows and tries no further when that has no place for several residues either. A figure that is
|
|
108
|
+
#: drawn is the same file either way; one that is given up says so. With ``on_unreadable="render"``, and
|
|
109
|
+
#: for anything but a ligand drawn as a chain, it changes nothing.
|
|
110
|
+
effort: str = "full"
|
|
111
|
+
background: bool = True
|
|
112
|
+
coords: str = "auto" # auto | coordgen | rdkit: how the ligand is laid out
|
|
113
|
+
#: Draw the model's confidence when the diagram has it (see :mod:`bindview.confidence`).
|
|
114
|
+
confidence: bool = True
|
|
115
|
+
#: Print the ligand's buried fraction with the other provenance numbers under the title
|
|
116
|
+
#: (and, below the calibrated cut, a line saying what that may mean). It is always reported
|
|
117
|
+
#: in the result; this only decides whether it is also in the figure: ``True`` prints it there,
|
|
118
|
+
#: ``False`` leaves it out. An interface has no buried fraction, on or off.
|
|
119
|
+
burial: bool = True
|
|
120
|
+
#: Predict solvent sites that could bridge ligand and protein, and draw them -- marked as
|
|
121
|
+
#: predicted. Off unless asked for, and never done for a structure that has waters of its own.
|
|
122
|
+
solvent_sites: bool = False
|
|
123
|
+
#: The colour scheme: ``"standard"``, or ``"contrast"``, whose residue classes are further apart
|
|
124
|
+
#: (:data:`bindview.theme.SCHEMES`). The theme picks its light or its dark palette.
|
|
125
|
+
colors: str = "standard"
|
|
126
|
+
#: Show the model's pLDDT by AlphaFold's four colours and not by stroke weight: residues and the
|
|
127
|
+
#: atoms of the ligand are coloured by their band, and every line is drawn at full strength.
|
|
128
|
+
#: ``True`` or ``"behind"``: the atoms stand on the colour. ``"bonds"``: the bonds are drawn in it, half
|
|
129
|
+
#: by half, those of the ligand and those that are drawn of a residue.
|
|
130
|
+
#: Off unless asked for; without a pLDDT to draw it changes nothing, and the result says so.
|
|
131
|
+
plddt_colors: "bool | str" = False
|
|
132
|
+
#: Show the predicted aligned error of a contact (:mod:`bindview.pae`) as a glow behind its line, in the four
|
|
133
|
+
#: colours of pLDDT (blue: the two ends are placed against each other; orange: they are not). ``None``, the
|
|
134
|
+
#: default, does so in the diagram of a ligand that was given a ``pae``, and writes the value on the line in
|
|
135
|
+
#: the figure of an interface; ``True`` draws the glow there too, ``False`` in neither.
|
|
136
|
+
pae_colors: "bool | None" = None
|
|
137
|
+
#: Draw each atom that the detailed style draws of a residue (the fragment of one that makes a
|
|
138
|
+
#: directional contact) at its own pLDDT, where the model gives the atoms of a residue values of their
|
|
139
|
+
#: own (AlphaFold 3 does), and say so in a footnote; a model with one value for a residue is the same
|
|
140
|
+
#: figure either way. ``False`` draws a fragment at its residue's value. At a level of ``detail`` the
|
|
141
|
+
#: atoms are at their own values either way.
|
|
142
|
+
plddt_by_atom: bool = True
|
|
143
|
+
#: How a contact's occupancy (the share of an ensemble that makes it) is drawn: ``"steps"``, a line in
|
|
144
|
+
#: three steps of weight and opacity (90 % and more, 50 to 90 %, below 50 %) with the share written on
|
|
145
|
+
#: every line made in fewer than all, in the place of its distance; or ``"continuous"``, weight and
|
|
146
|
+
#: opacity in proportion to the share and nothing written. A figure without occupancy is the same file
|
|
147
|
+
#: either way.
|
|
148
|
+
occupancy_style: str = "steps"
|
|
149
|
+
|
|
150
|
+
def __post_init__(self) -> None:
|
|
151
|
+
for name, words in _WORDS.items():
|
|
152
|
+
if not isinstance(getattr(self, name), str) or getattr(self, name) not in words:
|
|
153
|
+
raise ValueError(f"{name} is one of {', '.join(map(repr, words))}, not {getattr(self, name)!r}")
|
|
154
|
+
if self.occupancy_style not in ("steps", "continuous"):
|
|
155
|
+
raise ValueError(f"occupancy_style is 'steps' or 'continuous', not {self.occupancy_style!r}")
|
|
156
|
+
if self.occupancy_labels not in ("all", "partial"):
|
|
157
|
+
raise ValueError(f"occupancy_labels is 'all' or 'partial', not {self.occupancy_labels!r}")
|
|
158
|
+
if self.plddt_colors not in (True, False, *PLDDT_PLACES):
|
|
159
|
+
raise ValueError(f"plddt_colors is True, False or one of {', '.join(map(repr, PLDDT_PLACES))}, "
|
|
160
|
+
f"not {self.plddt_colors!r}")
|
|
161
|
+
if self.lines is not None and self.lines not in LINES:
|
|
162
|
+
raise ValueError(f"lines is one of {', '.join(map(repr, LINES))} (or None, the style's), "
|
|
163
|
+
f"not {self.lines!r}")
|
|
164
|
+
if self.lining not in (None, True, False, *LININGS):
|
|
165
|
+
raise ValueError(f"lining is one of {', '.join(map(repr, LININGS))} (or None, the style's), "
|
|
166
|
+
f"not {self.lining!r}")
|
|
167
|
+
if self.stylesheet not in ("inline", "scoped", "external"):
|
|
168
|
+
raise ValueError(f"stylesheet is 'inline', 'scoped' or 'external', not {self.stylesheet!r}")
|
|
169
|
+
if self.absent_style not in other_protein.ABSENT_STYLES:
|
|
170
|
+
raise ValueError(f"absent_style is one of {', '.join(map(repr, other_protein.ABSENT_STYLES))}, "
|
|
171
|
+
f"not {self.absent_style!r}")
|
|
172
|
+
if self.effort not in ("full", "quick"):
|
|
173
|
+
raise ValueError(f"effort is 'full' or 'quick', not {self.effort!r}")
|
|
174
|
+
if self.atom_labels not in ATOM_LABELS:
|
|
175
|
+
raise ValueError(f"atom_labels is one of {', '.join(map(repr, ATOM_LABELS))}, not {self.atom_labels!r}")
|
|
176
|
+
if self.solvent_mark not in SOLVENT_MARKS:
|
|
177
|
+
raise ValueError(f"solvent_mark is one of {', '.join(map(repr, SOLVENT_MARKS))}, not {self.solvent_mark!r}")
|
|
178
|
+
# (Held as a tuple: options are the key of a layout that is kept.)
|
|
179
|
+
object.__setattr__(self, "residues", _residues_option(self.residues))
|
|
180
|
+
object.__setattr__(self, "absent", other_protein.absent_option(self.absent))
|
|
181
|
+
#: The figure answers the pointer (:mod:`bindview.interactive`): pointing at a residue, or at one of
|
|
182
|
+
#: its contacts, keeps it with its contacts and what they reach, draws those contacts heavier and steps
|
|
183
|
+
#: the other residues and contacts far back; a click keeps that until a click elsewhere. A style sheet in the file does it and
|
|
184
|
+
#: no script, and nothing that is drawn changes: where the file is not shown by a browser as a
|
|
185
|
+
#: document or as part of a page (an image, a PDF, a drawing program) it is the figure it would be
|
|
186
|
+
#: without this. Off unless asked for; for a figure with no residue to point at it changes nothing,
|
|
187
|
+
#: and the result says so.
|
|
188
|
+
interactive: bool = False
|
|
189
|
+
#: Break a contact's line where it runs over a word that is not its own (:mod:`bindview.clearance`): the
|
|
190
|
+
#: letter of a ligand atom that lies on its way to a ring centre, the name of a residue, the distance
|
|
191
|
+
#: written on another line. The line is broken around the word as it is around its own distance.
|
|
192
|
+
#: ``False`` draws every line whole; a figure in which no line runs over a word is the same file either
|
|
193
|
+
#: way.
|
|
194
|
+
break_lines: bool = True
|
|
195
|
+
#: Shade the charged group that a salt bridge or a pi-cation contact is made with, in the colour of the
|
|
196
|
+
#: contact: such a contact is with the group and not with one of its atoms. ``True`` draws the shading and
|
|
197
|
+
#: ``False`` none: the line points at the group, and ends where the shading would begin, either way;
|
|
198
|
+
#: nothing else in the figure moves.
|
|
199
|
+
charge_halos: bool = False
|
|
200
|
+
#: Name that shading, where it is drawn, in the key: "Charged group", a soft disc in the colour of the
|
|
201
|
+
#: contact (one for each kind of contact that shades a group, where both do). On unless ``False`` is
|
|
202
|
+
#: passed, which leaves the entry out.
|
|
203
|
+
charge_key: bool = True
|
|
204
|
+
#: The drawing and its key, and no words around them: no line of confidence numbers under the title, no
|
|
205
|
+
#: warning above the drawing and no notes under the key. For a figure that goes into a paper or a slide
|
|
206
|
+
#: with a caption of its own. The words that are left off are what the figure needs to be read (what a
|
|
207
|
+
#: ``?`` marks, the unit of a distance, what a PAE is): they are in ``RenderResult.notes``, for that
|
|
208
|
+
#: caption. A title or subtitle that is asked for is drawn, and so is the mark of a model the caller
|
|
209
|
+
#: flagged as not to be trusted. Off unless asked for.
|
|
210
|
+
bare: bool = False
|
|
211
|
+
#: How the residues are drawn, in either style: ``"atoms"`` (the part that makes a directional contact,
|
|
212
|
+
#: and an eyelash for a residue that makes none), ``"bubbles"``, or ``"names"``; or a mapping, residue
|
|
213
|
+
#: by residue (``{"Gln712": "atoms", "*": "bubbles"}``; a residue is named as the figure names it, with
|
|
214
|
+
#: or without its chain). ``None``: the style's own (:data:`STYLE_SETTINGS`), as for the next three.
|
|
215
|
+
residues: Any = None
|
|
216
|
+
#: The colours and dashes of the contact lines: ``"detailed"`` or ``"schematic"``, in either style.
|
|
217
|
+
lines: str | None = None
|
|
218
|
+
#: Grey halos behind the ligand's atoms that are open to solvent, in either style.
|
|
219
|
+
exposure: bool | None = None
|
|
220
|
+
#: The wall of the pocket around the ligand, in either style: ``"contacts"``, a stretch for each contact
|
|
221
|
+
#: in the colour of what makes it (hydrophobic, polar, charged), which is what the schematic style draws
|
|
222
|
+
#: unless told otherwise; ``"nearest"``, a band in the class of the nearest residue, open where none is
|
|
223
|
+
#: near; ``"none"`` (docs/reference.md). ``True`` is ``"contacts"`` and ``False`` is ``"none"``.
|
|
224
|
+
lining: "str | bool | None" = None
|
|
225
|
+
#: What is written on an atom that is drawn of a residue: the letter of its element (``"elements"``: N, O), as in a
|
|
226
|
+
#: chemical formula, or its name in the structure file (``"names"``: NZ, OE1, O4'), by which it is found in the file
|
|
227
|
+
#: and in a table of contacts; that is in the tooltip of the contact either way. Nothing moves with it. A name
|
|
228
|
+
#: is centred on its atom, so a bond that comes from the right ends at its last letter, and NZ can read as a Z.
|
|
229
|
+
atom_labels: str = "elements"
|
|
230
|
+
#: How a predicted water stands on its line: on a glow (``"glow"``), in a filled box with a heavy broken
|
|
231
|
+
#: border (``"filled"``), or in a thin broken outline (``"outline"``).
|
|
232
|
+
solvent_mark: str = "glow"
|
|
233
|
+
#: On which contacts the share of an ensemble is written (``occupancy_style="steps"``): on every line, and
|
|
234
|
+
#: beside the name of a residue that has hydrophobic contacts only and no line (``"all"``); or on the line of
|
|
235
|
+
#: a contact that is made in fewer than all (``"partial"``), where one made in all has its distance. With
|
|
236
|
+
#: ``distance_labels="all"`` a contact made in all keeps its distance either way.
|
|
237
|
+
occupancy_labels: str = "all"
|
|
238
|
+
#: Residues that another protein does not have (:mod:`bindview.styles.absence`): numbers (``702``, ``"60A"``) or
|
|
239
|
+
#: names (``"Leu702"``, ``"A:702"``), any of which the figure may not have. Those that touch the ligand are
|
|
240
|
+
#: marked with their contacts, and the figure says how many of the contact residues they are. ``None``: there
|
|
241
|
+
#: is no other protein; an empty list: there is one, and none is absent from it, which the figure says too.
|
|
242
|
+
absent: Any = None
|
|
243
|
+
#: The other protein's name, for the key and the sentence under it.
|
|
244
|
+
absent_label: str | None = None
|
|
245
|
+
#: What becomes of them: ``"marked"``, a stroke of a marker pen under them; ``"faint"``, set back.
|
|
246
|
+
absent_style: str = "marked"
|
|
247
|
+
#: Where the figure's style sheet is, for a page that has several figures in it: ``"inline"``, in the figure,
|
|
248
|
+
#: where it declares the colours for every figure of the page; ``"scoped"``, in the figure and for figures in
|
|
249
|
+
#: the same colours alone; ``"external"``, in ``result.css`` and not in the figure, for the page to have once
|
|
250
|
+
#: (:func:`bindview.stylesheet`). Where a figure has no style sheet it changes nothing.
|
|
251
|
+
stylesheet: str = "inline"
|
|
252
|
+
|
|
253
|
+
def labelled(self, kind: InteractionType) -> bool:
|
|
254
|
+
if self.distance_labels == "none":
|
|
255
|
+
return False
|
|
256
|
+
if self.distance_labels == "all":
|
|
257
|
+
return kind is not T.HYDROPHOBIC
|
|
258
|
+
return kind in LABELLED_BY_DEFAULT
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def beyond_any_page(natural_pt: float, options: RenderOptions, fixed: bool = False) -> "str | None":
|
|
262
|
+
"""Why no page can make a figure legible, where that is so; ``None`` where a page of some size can.
|
|
263
|
+
|
|
264
|
+
A figure is fitted to its page by making it smaller, never larger. So its smallest text is at most
|
|
265
|
+
what it is at full size (``natural_pt``, in points), and a ``min_font_pt`` above that is met by no
|
|
266
|
+
width or height. A message that named a width to try would send the caller after a page that does
|
|
267
|
+
not exist: this is the reason to give in its place, and it names what does help. ``fixed``: the
|
|
268
|
+
text of this kind of figure has one size, which no ``Metrics`` changes.
|
|
269
|
+
"""
|
|
270
|
+
if options.min_font_pt <= natural_pt + 1e-9:
|
|
271
|
+
return None
|
|
272
|
+
# (Both sizes are cut off, not rounded: rounded up, 6.375 pt would be said as "is 6.4 pt" to a caller
|
|
273
|
+
# who asked for 6.4 pt and is told that no page gives it.)
|
|
274
|
+
is_ = math.floor(natural_pt * 100.0 + 1e-9) / 100.0
|
|
275
|
+
most = math.floor(natural_pt * 10.0 + 1e-9) / 10.0
|
|
276
|
+
return (f"its smallest text is {is_:g} pt at full size, and a figure is fitted to a page by making "
|
|
277
|
+
f"it smaller, never larger: no page gives it the {options.min_font_pt:g} pt that min_font_pt asks "
|
|
278
|
+
f"for. Ask for {most:g} pt or less"
|
|
279
|
+
+ (": the text of this view has one size" if fixed else ", or hand in larger fonts (metrics=)"))
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def page_that_would_do(required_width_mm: float, width: float, height: float,
|
|
283
|
+
options: RenderOptions) -> "tuple[str, str, float]":
|
|
284
|
+
"""The page a figure needs for its text, as the words name it: millimetres, ``"wide"`` or ``"high"``,
|
|
285
|
+
and what was asked for in that direction.
|
|
286
|
+
|
|
287
|
+
``required_width_mm`` is the width at which the smallest text reaches ``min_font_pt``; ``width`` and
|
|
288
|
+
``height`` are the figure's own. The width is named, in whole millimetres, wherever that is more than
|
|
289
|
+
the width asked for. Two cases read wrong that way and are said differently:
|
|
290
|
+
|
|
291
|
+
* rounded, the number is the width that was asked for (90.3 mm of a page of 90 mm): it is then
|
|
292
|
+
rounded up to a tenth, so the page named is one that would do;
|
|
293
|
+
* the width asked for would do, and the page's height is what makes the text small: the height is
|
|
294
|
+
named, and a caller is not sent after a width they already have.
|
|
295
|
+
"""
|
|
296
|
+
needed, asked, word = required_width_mm, options.figure_width_mm, "wide"
|
|
297
|
+
if required_width_mm <= options.figure_width_mm + 1e-9:
|
|
298
|
+
needed, asked, word = required_width_mm * height / width, options.figure_height_mm, "high"
|
|
299
|
+
said = f"{needed:.0f}"
|
|
300
|
+
if float(said) <= asked:
|
|
301
|
+
said = f"{math.ceil(needed * 10.0 - 1e-9) / 10.0:g}"
|
|
302
|
+
return said, word, asked
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def too_small_on_page(printed_pt: float, required_width_mm: float, width: float, height: float,
|
|
306
|
+
options: RenderOptions) -> str:
|
|
307
|
+
"""What to say of a figure whose text the page asked for makes too small (``printed_pt``), with the
|
|
308
|
+
page that would do. The size is cut off where rounding would write the minimum itself: 4.98 pt is
|
|
309
|
+
not "5.0 pt (minimum 5 pt)"."""
|
|
310
|
+
size = f"{printed_pt:.1f}"
|
|
311
|
+
if float(size) >= options.min_font_pt:
|
|
312
|
+
size = f"{math.floor(printed_pt * 100.0) / 100.0:.2f}"
|
|
313
|
+
mm, word, asked = page_that_would_do(required_width_mm, width, height, options)
|
|
314
|
+
where = f"at {asked:g} mm" if word == "wide" else f"on a page {asked:g} mm high"
|
|
315
|
+
return (f"{where} the smallest text would print at {size} pt "
|
|
316
|
+
f"(minimum {options.min_font_pt:g} pt); it needs a figure about {mm} mm {word}")
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
@dataclass
|
|
320
|
+
class ResidueGroup:
|
|
321
|
+
"""All drawable interactions of one residue."""
|
|
322
|
+
|
|
323
|
+
key: tuple[str, int, str]
|
|
324
|
+
resname: str
|
|
325
|
+
label: str
|
|
326
|
+
interactions: list[ResolvedInteraction]
|
|
327
|
+
#: Beside a chain ligand a residue whose contacts lie far apart along the chain is drawn once for
|
|
328
|
+
#: each stretch (:func:`split_along_chain`): which of its drawings this is, and how many there are.
|
|
329
|
+
part: int = 0
|
|
330
|
+
parts: int = 1
|
|
331
|
+
#: Does the protein that the figure is compared with lack this residue (``RenderOptions.absent``), and is it
|
|
332
|
+
#: set back for that?
|
|
333
|
+
lost: bool = False
|
|
334
|
+
faint: bool = False
|
|
335
|
+
|
|
336
|
+
@property
|
|
337
|
+
def uid(self) -> tuple:
|
|
338
|
+
"""What tells this drawing from every other: the residue, and which of its drawings it is."""
|
|
339
|
+
return self.key if self.parts == 1 else (*self.key, self.part)
|
|
340
|
+
|
|
341
|
+
@property
|
|
342
|
+
def node_ident(self) -> str:
|
|
343
|
+
"""The identifier of this drawing: the residue's, numbered where the residue is drawn more than once."""
|
|
344
|
+
return self.ident if self.parts == 1 else f"{self.ident}~{self.part + 1}"
|
|
345
|
+
|
|
346
|
+
@property
|
|
347
|
+
def beyond(self) -> bool:
|
|
348
|
+
return any(r.record.beyond_contact_set for r in self.interactions)
|
|
349
|
+
|
|
350
|
+
@property
|
|
351
|
+
def absent(self) -> bool:
|
|
352
|
+
"""Does the structure that is shown make none of this residue's contacts (other models do)?"""
|
|
353
|
+
return bool(self.interactions) and all(r.absent for r in self.interactions)
|
|
354
|
+
|
|
355
|
+
@property
|
|
356
|
+
def types(self) -> list[InteractionType]:
|
|
357
|
+
seen: list[InteractionType] = []
|
|
358
|
+
for r in self.interactions:
|
|
359
|
+
if r.type not in seen:
|
|
360
|
+
seen.append(r.type)
|
|
361
|
+
return seen
|
|
362
|
+
|
|
363
|
+
@property
|
|
364
|
+
def only_hydrophobic(self) -> bool:
|
|
365
|
+
return all(r.type is T.HYDROPHOBIC for r in self.interactions)
|
|
366
|
+
|
|
367
|
+
@property
|
|
368
|
+
def residue_class(self) -> str:
|
|
369
|
+
return residue_class(self.resname)
|
|
370
|
+
|
|
371
|
+
@property
|
|
372
|
+
def ident(self) -> str:
|
|
373
|
+
chain, number, icode = self.key
|
|
374
|
+
return f"{chain}:{self.resname}{number}{icode}" if chain else f"{self.resname}{number}{icode}"
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
@property
|
|
378
|
+
def numbered(self) -> str:
|
|
379
|
+
"""The residue's number, with its insertion code."""
|
|
380
|
+
return f"{self.key[1]}{self.key[2]}"
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
def group_residues(resolved: Sequence[ResolvedInteraction], show_chain: str = "auto") -> list[ResidueGroup]:
|
|
384
|
+
"""Group resolved, drawable interactions by residue, in chain/number order."""
|
|
385
|
+
table: dict[tuple[str, int, str], list[ResolvedInteraction]] = {}
|
|
386
|
+
for r in resolved:
|
|
387
|
+
if r.ligand is None:
|
|
388
|
+
continue
|
|
389
|
+
table.setdefault(r.record.residue_id, []).append(r)
|
|
390
|
+
chains = {k[0] for k in table}
|
|
391
|
+
with_chain = show_chain == "always" or (show_chain == "auto" and len(chains) > 1)
|
|
392
|
+
out = []
|
|
393
|
+
for key in sorted(table):
|
|
394
|
+
rs = table[key]
|
|
395
|
+
rec = rs[0].record
|
|
396
|
+
label = format_residue_label(rec.residue_name, rec.residue_number, rec.insertion_code,
|
|
397
|
+
key[0] if with_chain and key[0] else None)
|
|
398
|
+
out.append(ResidueGroup(key, rec.residue_name, label, rs))
|
|
399
|
+
return out
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
#: How far apart along a chain ligand, in residues of the ligand, the contacts of one residue of the
|
|
403
|
+
#: protein may lie for it still to be drawn once.
|
|
404
|
+
SPLIT_GAP = 8
|
|
405
|
+
|
|
406
|
+
|
|
407
|
+
def chain_index(dep: Depiction, atoms: Sequence[int]) -> int | None:
|
|
408
|
+
"""Where along a chain ligand these atoms are: the index of their residue, and for atoms outside
|
|
409
|
+
the chain that of the residue which carries them."""
|
|
410
|
+
for a in atoms:
|
|
411
|
+
res = dep.home_of(a)
|
|
412
|
+
if res is not None:
|
|
413
|
+
return res.index
|
|
414
|
+
seen, queue = set(atoms), list(atoms)
|
|
415
|
+
while queue:
|
|
416
|
+
for j in dep.neighbours(queue.pop(0), False):
|
|
417
|
+
res = dep.unit_of(j)
|
|
418
|
+
if res is not None:
|
|
419
|
+
return res.index
|
|
420
|
+
if j not in seen:
|
|
421
|
+
seen.add(j)
|
|
422
|
+
queue.append(j)
|
|
423
|
+
return None
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
def split_along_chain(groups: Sequence[ResidueGroup], dep: Depiction) -> list[ResidueGroup]:
|
|
427
|
+
"""Beside a chain ligand: one drawing of a residue for each stretch of the chain it touches.
|
|
428
|
+
|
|
429
|
+
A chain is drawn as a straight column whatever its path in space. A residue
|
|
430
|
+
of the protein that touches both ends of a folded peptide would have to
|
|
431
|
+
stand beside two places at once; drawn in one of them, its other contact is
|
|
432
|
+
a line across the whole figure, or cannot be drawn at all. Where the
|
|
433
|
+
contacts of a residue lie more than :data:`SPLIT_GAP` residues apart, it is
|
|
434
|
+
therefore drawn once for each stretch, with the contacts it makes there --
|
|
435
|
+
and the figure says so in a footnote.
|
|
436
|
+
"""
|
|
437
|
+
if not dep.units or dep.arranged == "plane":
|
|
438
|
+
# On a plane the boxes are where the residues are: what one residue touches lies together.
|
|
439
|
+
return list(groups)
|
|
440
|
+
out: list[ResidueGroup] = []
|
|
441
|
+
for grp in groups:
|
|
442
|
+
places = []
|
|
443
|
+
for r in grp.interactions:
|
|
444
|
+
assert r.ligand is not None
|
|
445
|
+
where = chain_index(dep, r.ligand.atoms)
|
|
446
|
+
places.append(0 if where is None else where)
|
|
447
|
+
order = sorted(range(len(places)), key=lambda i: (places[i], i))
|
|
448
|
+
stretch = [0] * len(places)
|
|
449
|
+
for before, i in zip(order, order[1:]):
|
|
450
|
+
stretch[i] = stretch[before] + (1 if places[i] - places[before] > SPLIT_GAP else 0)
|
|
451
|
+
n = max(stretch) + 1
|
|
452
|
+
if n == 1:
|
|
453
|
+
out.append(grp)
|
|
454
|
+
continue
|
|
455
|
+
for k in range(n):
|
|
456
|
+
out.append(ResidueGroup(grp.key, grp.resname, grp.label,
|
|
457
|
+
[r for r, s in zip(grp.interactions, stretch) if s == k], part=k, parts=n))
|
|
458
|
+
return out
|
|
459
|
+
|
|
460
|
+
|
|
461
|
+
@dataclass
|
|
462
|
+
class Context:
|
|
463
|
+
ligand: Ligand
|
|
464
|
+
dep: Depiction
|
|
465
|
+
groups: list[ResidueGroup]
|
|
466
|
+
metrics: Metrics
|
|
467
|
+
palette: Palette
|
|
468
|
+
options: RenderOptions
|
|
469
|
+
notes: list[str] = field(default_factory=list)
|
|
470
|
+
exposure: "np.ndarray | None" = None # relative solvent exposure per ligand atom
|
|
471
|
+
field: "LigandField | None" = None # the ligand distance field, once built
|
|
472
|
+
confidence: "Confidence | None" = None # per-atom / per-residue pLDDT, when it may be drawn
|
|
473
|
+
ensemble: str | None = None # what the records' occupancy is a share of (legend text)
|
|
474
|
+
solvent_sites: tuple = () # the predicted sites behind any predicted water bridge
|
|
475
|
+
#: How much of a residue beside the ligand is drawn where it is drawn with atoms: by chain, and
|
|
476
|
+
#: under ``"*"`` for every chain that is not named (:data:`bindview.fragments.DETAILS`). None: as always.
|
|
477
|
+
detail: "dict[str, str | None] | None" = None
|
|
478
|
+
#: Was the diagram given a matrix of predicted aligned errors of its own (``from_structure(pae=...)``)?
|
|
479
|
+
pae: bool = False
|
|
480
|
+
#: A figure of all the models of an ensemble: the models that contact each residue, which its ring shows.
|
|
481
|
+
shares: "Mapping[tuple[str, int, str], ResidueShare] | None" = None
|
|
482
|
+
|
|
483
|
+
def share_of(self, grp: "ResidueGroup") -> "ResidueShare | None":
|
|
484
|
+
"""The models that contact a residue, where the figure is of several and the residue stands in a ring."""
|
|
485
|
+
return self.shares.get(grp.key) if self.shares else None
|
|
486
|
+
|
|
487
|
+
@property
|
|
488
|
+
def glows(self) -> bool:
|
|
489
|
+
"""Is the predicted aligned error of a contact a glow behind its line (``pae_colors``)?"""
|
|
490
|
+
return self.pae if self.options.pae_colors is None else self.options.pae_colors
|
|
491
|
+
|
|
492
|
+
def detail_of(self, grp: "ResidueGroup") -> "str | None":
|
|
493
|
+
"""The level of detail of a residue beside the ligand: its chain's, or the figure's."""
|
|
494
|
+
if not self.detail:
|
|
495
|
+
return None
|
|
496
|
+
return self.detail.get(grp.key[0], self.detail.get("*"))
|
|
497
|
+
|
|
498
|
+
@property
|
|
499
|
+
def by_colour(self) -> bool:
|
|
500
|
+
"""Does this figure show pLDDT by AlphaFold's colours (``plddt_colors``) and not by weight?"""
|
|
501
|
+
return bool(self.options.plddt_colors) and self.confidence is not None
|
|
502
|
+
|
|
503
|
+
@property
|
|
504
|
+
def by_bond(self) -> bool:
|
|
505
|
+
"""... and is it the bonds that have the colour?"""
|
|
506
|
+
return self.by_colour and self.options.plddt_colors == "bonds"
|
|
507
|
+
|
|
508
|
+
@property
|
|
509
|
+
def shares_written(self) -> bool:
|
|
510
|
+
"""Is the share of an ensemble written on every contact that has one (``occupancy_labels``)?"""
|
|
511
|
+
return self.options.occupancy_style == "steps" and self.options.occupancy_labels == "all"
|
|
512
|
+
|
|
513
|
+
def look(self, value: "float | None") -> Look:
|
|
514
|
+
"""The look of a pLDDT value in this figure (:func:`bindview.confidence.look_of`)."""
|
|
515
|
+
return look_of(value, by_colour=self.by_colour)
|
|
516
|
+
|
|
517
|
+
def fill_of(self, look: Look, otherwise: str) -> str:
|
|
518
|
+
"""The fill of something that has a pLDDT band: the band's colour where the figure colours by
|
|
519
|
+
pLDDT and the thing has a value, and ``otherwise`` (its own token) in every other case."""
|
|
520
|
+
return f"plddt_{look.band}" if self.by_colour and look.band is not None else otherwise
|
|
521
|
+
|
|
522
|
+
def text_on(self, look: Look, otherwise: str) -> str:
|
|
523
|
+
"""The colour of a name that stands on :meth:`fill_of`."""
|
|
524
|
+
return f"plddt_text_{look.band}" if self.by_colour and look.band is not None else otherwise
|
|
525
|
+
|
|
526
|
+
|
|
527
|
+
# ---------------------------------------------------------------------------
|
|
528
|
+
# Confidence: what a contact and a residue are drawn with
|
|
529
|
+
# ---------------------------------------------------------------------------
|
|
530
|
+
|
|
531
|
+
def contact_plddt(ctx: Context, r: ResolvedInteraction) -> float | None:
|
|
532
|
+
"""Confidence of one contact: the number the record carries, and otherwise the lower of the
|
|
533
|
+
residue's pLDDT and the ligand site's."""
|
|
534
|
+
if not ctx.options.confidence:
|
|
535
|
+
return None
|
|
536
|
+
if r.record.confidence is not None:
|
|
537
|
+
return r.record.confidence
|
|
538
|
+
if ctx.confidence is None or r.ligand is None:
|
|
539
|
+
return None
|
|
540
|
+
names = [ctx.ligand.names[i] for i in r.ligand.atoms]
|
|
541
|
+
return ctx.confidence.contact(r.residue if r.residue is not None else r.record.residue_id, names)
|
|
542
|
+
|
|
543
|
+
|
|
544
|
+
def residue_plddt(ctx: Context, grp: "ResidueGroup") -> float | None:
|
|
545
|
+
"""pLDDT of the residue itself (mean over its atoms)."""
|
|
546
|
+
if ctx.confidence is None:
|
|
547
|
+
return None
|
|
548
|
+
first = grp.interactions[0]
|
|
549
|
+
return ctx.confidence.residue(first.residue if first.residue is not None else grp.key)
|
|
550
|
+
|
|
551
|
+
|
|
552
|
+
def residue_occupancy(grp: "ResidueGroup") -> float | None:
|
|
553
|
+
"""Occupancy a residue node is drawn at: that of its most persistent contact.
|
|
554
|
+
|
|
555
|
+
This is a drawing level, not a reported number: the share of the ensemble
|
|
556
|
+
in which the residue makes *any* contact is at least this, and cannot be
|
|
557
|
+
known from per-contact occupancies alone.
|
|
558
|
+
"""
|
|
559
|
+
values = [r.record.occupancy for r in grp.interactions if r.record.occupancy is not None]
|
|
560
|
+
return max(values) if values else None
|
|
561
|
+
|
|
562
|
+
|
|
563
|
+
def marked_label(text: str, look: Look) -> str:
|
|
564
|
+
"""``text`` with the lowest band's mark appended."""
|
|
565
|
+
return f"{text}{MARK}" if look.mark else text
|
|
566
|
+
|
|
567
|
+
|
|
568
|
+
# ---------------------------------------------------------------------------
|
|
569
|
+
# Where a link lands on the ligand
|
|
570
|
+
# ---------------------------------------------------------------------------
|
|
571
|
+
|
|
572
|
+
@dataclass(frozen=True)
|
|
573
|
+
class Target:
|
|
574
|
+
point: Point
|
|
575
|
+
radius: float
|
|
576
|
+
caps: tuple[np.ndarray, np.ndarray, np.ndarray] | None
|
|
577
|
+
kind: str # atom | ring | group
|
|
578
|
+
atoms: tuple[int, ...]
|
|
579
|
+
extent: float = 3.0 # how far the atom / ring / group reaches from ``point``
|
|
580
|
+
unit: int | None = None # in a chain ligand: the residue these atoms belong to (index of the unit)
|
|
581
|
+
|
|
582
|
+
@property
|
|
583
|
+
def key(self) -> tuple:
|
|
584
|
+
"""What tells two targets apart: the residue of a chain ligand, or else the kind and the atoms."""
|
|
585
|
+
return ("unit", self.unit) if self.unit is not None else (self.kind, self.atoms)
|
|
586
|
+
|
|
587
|
+
|
|
588
|
+
def _box_capsule(box: tuple[float, float, float, float], pad: float) -> tuple[Point, Point, float]:
|
|
589
|
+
w, h = box[2] - box[0], box[3] - box[1]
|
|
590
|
+
cx, cy = (box[0] + box[2]) / 2.0, (box[1] + box[3]) / 2.0
|
|
591
|
+
r = min(w, h) / 2.0
|
|
592
|
+
if w >= h:
|
|
593
|
+
return (box[0] + r, cy), (box[2] - r, cy), r + pad
|
|
594
|
+
return (cx, box[1] + r), (cx, box[3] - r), r + pad
|
|
595
|
+
|
|
596
|
+
|
|
597
|
+
def halo_radius(metrics: Metrics) -> float:
|
|
598
|
+
return 0.33 * metrics.bond_length
|
|
599
|
+
|
|
600
|
+
|
|
601
|
+
def spoke_reach(dep: Depiction, atom: int, metrics: Metrics) -> float:
|
|
602
|
+
"""Outer radius of the contact spokes drawn on a ligand atom."""
|
|
603
|
+
r0 = metrics.spoke_inner
|
|
604
|
+
label = dep.atoms[atom].label
|
|
605
|
+
if label is not None:
|
|
606
|
+
r0 = max(r0, math.hypot(label.box[2] - label.box[0], label.box[3] - label.box[1]) / 2.0 + 1.5)
|
|
607
|
+
return r0 + (metrics.spoke_outer - metrics.spoke_inner)
|
|
608
|
+
|
|
609
|
+
|
|
610
|
+
def group_skeleton(dep: Depiction, atoms: Sequence[int]) -> list[tuple[Point, Point]]:
|
|
611
|
+
"""Bond segments among ``atoms`` (the backbone a group halo is drawn along)."""
|
|
612
|
+
members = set(atoms)
|
|
613
|
+
segs = [(dep.pos(b.a), dep.pos(b.b)) for b in dep.bonds
|
|
614
|
+
if b.kind == "covalent" and b.a in members and b.b in members]
|
|
615
|
+
if not segs:
|
|
616
|
+
segs = [(dep.pos(i), dep.pos(i)) for i in atoms]
|
|
617
|
+
return segs
|
|
618
|
+
|
|
619
|
+
|
|
620
|
+
def ligand_target(dep: Depiction, anchor: Anchor, metrics: Metrics, whole: bool = False) -> Target:
|
|
621
|
+
"""The point a link aims at, and the ink that stops it short of that point.
|
|
622
|
+
|
|
623
|
+
``whole``: a contact without a direction, which is one with the residue of a chain as a whole. It
|
|
624
|
+
lands on the residue's box even where atoms of the residue are drawn beside it; a directional
|
|
625
|
+
contact lands on its atom there.
|
|
626
|
+
"""
|
|
627
|
+
res = dep.unit_for(anchor.atoms, whole) if dep.units else None
|
|
628
|
+
if res is None and dep.units:
|
|
629
|
+
own = dep.landing(anchor.atoms)
|
|
630
|
+
if own != tuple(anchor.atoms):
|
|
631
|
+
# Some of its atoms are drawn and some are in the box: it lands on those that are drawn.
|
|
632
|
+
anchor = Anchor("atom" if len(own) == 1 else anchor.kind, own, anchor.group_kind)
|
|
633
|
+
if res is not None:
|
|
634
|
+
# A residue of a chain ligand: the link stops at its box, whichever of its atoms makes the contact.
|
|
635
|
+
c0, c1, cr = _box_capsule(res.box, metrics.label_gap + 0.5)
|
|
636
|
+
caps = (np.array([c0], dtype=float), np.array([c1], dtype=float), np.array([cr], dtype=float))
|
|
637
|
+
return Target(res.pos, 8.0, caps, "atom", anchor.atoms, extent=8.0, unit=res.index)
|
|
638
|
+
if anchor.kind in ("ring", "group"):
|
|
639
|
+
centre = dep.centroid(anchor.atoms)
|
|
640
|
+
spread = max(dist(centre, dep.pos(i)) for i in anchor.atoms)
|
|
641
|
+
if anchor.kind == "ring":
|
|
642
|
+
return Target(centre, 3.6, None, "ring", anchor.atoms, extent=spread)
|
|
643
|
+
hr = halo_radius(metrics)
|
|
644
|
+
segs = group_skeleton(dep, anchor.atoms)
|
|
645
|
+
p0 = np.array([s[0] for s in segs], dtype=float)
|
|
646
|
+
p1 = np.array([s[1] for s in segs], dtype=float)
|
|
647
|
+
caps = (p0, p1, np.full(len(segs), hr + 1.0))
|
|
648
|
+
return Target(centre, hr, caps, "group", anchor.atoms, extent=spread + hr)
|
|
649
|
+
atom = dep.atoms[anchor.atom]
|
|
650
|
+
if atom.label is None:
|
|
651
|
+
return Target(atom.pos, 3.0, None, "atom", anchor.atoms, extent=3.0)
|
|
652
|
+
caps_l = [_box_capsule(box, metrics.label_gap + 0.5) for box in atom.label.boxes]
|
|
653
|
+
caps = (np.array([c[0] for c in caps_l], dtype=float), np.array([c[1] for c in caps_l], dtype=float),
|
|
654
|
+
np.array([c[2] for c in caps_l], dtype=float))
|
|
655
|
+
return Target(atom.pos, 8.0, caps, "atom", anchor.atoms, extent=8.0)
|
|
656
|
+
|
|
657
|
+
|
|
658
|
+
# ---------------------------------------------------------------------------
|
|
659
|
+
# Link lines
|
|
660
|
+
# ---------------------------------------------------------------------------
|
|
661
|
+
|
|
662
|
+
@dataclass(frozen=True)
|
|
663
|
+
class LinkStyle:
|
|
664
|
+
token: str
|
|
665
|
+
dash: tuple[float, ...]
|
|
666
|
+
width: float = 1.0
|
|
667
|
+
cap: str = "butt"
|
|
668
|
+
end_dots: bool = False # dot at a ring-centroid end
|
|
669
|
+
|
|
670
|
+
|
|
671
|
+
LINK_STYLES: dict[InteractionType, LinkStyle] = {
|
|
672
|
+
T.HBOND: LinkStyle("hbond", (4.2, 2.8)),
|
|
673
|
+
T.SALTBRIDGE: LinkStyle("saltbridge", (0.01, 3.7), width=1.75, cap="round"),
|
|
674
|
+
T.PI_STACKING: LinkStyle("pi_stacking", (6.5, 2.4, 1.3, 2.4), end_dots=True),
|
|
675
|
+
T.PI_CATION: LinkStyle("pi_cation", (8.0, 3.0), end_dots=True),
|
|
676
|
+
T.HALOGEN: LinkStyle("halogen", (6.5, 2.2, 1.3, 2.2, 1.3, 2.2)),
|
|
677
|
+
T.METAL: LinkStyle("metal", ()),
|
|
678
|
+
T.WATER_BRIDGE: LinkStyle("water_bridge", (2.2, 2.2)),
|
|
679
|
+
T.HYDROPHOBIC: LinkStyle("hydrophobic", (1.0, 3.0)),
|
|
680
|
+
# A bond like those of the ligand, on a highlight (link_items).
|
|
681
|
+
T.COVALENT: LinkStyle("ligand_bond", (), width=1.35, cap="round"),
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
_ARROW_LEN = 6.4
|
|
685
|
+
_ARROW_HALF = 2.5
|
|
686
|
+
#: The highlight a covalent bond stands on: its colour, and its width in widths of a contact's line.
|
|
687
|
+
HIGHLIGHT = "warning"
|
|
688
|
+
COVALENT_GLOW = 6.5
|
|
689
|
+
#: The glow of a contact's predicted aligned error: its width in widths of a contact's line, and its opacity.
|
|
690
|
+
GLOW = 6.0
|
|
691
|
+
GLOW_OPACITY = 0.5
|
|
692
|
+
#: ... of the darkest of its colours, so that a distance is legible on it.
|
|
693
|
+
_GLOW_OPACITIES = {"plddt_very_high": 0.34}
|
|
694
|
+
|
|
695
|
+
#: ... and of the line a hydrophobic contact gets on a chain ligand, in the detailed style: in the colour of
|
|
696
|
+
#: the arc it leaves, and finer than any other.
|
|
697
|
+
CHAIN_CONTACT = LinkStyle("hydrophobic", (), width=0.6)
|
|
698
|
+
|
|
699
|
+
#: The lines of the schematic style.
|
|
700
|
+
SCHEMATIC_LINKS: dict[InteractionType, LinkStyle] = {
|
|
701
|
+
T.HBOND: LinkStyle("sch_hbond", ()),
|
|
702
|
+
T.SALTBRIDGE: LinkStyle("sch_saltbridge", (0.01, 3.7), width=1.75, cap="round"),
|
|
703
|
+
T.PI_STACKING: LinkStyle("sch_pi_stacking", (), end_dots=True),
|
|
704
|
+
T.PI_CATION: LinkStyle("sch_pi_cation", (), end_dots=True),
|
|
705
|
+
T.HALOGEN: LinkStyle("sch_halogen", (6.5, 2.2, 1.3, 2.2)),
|
|
706
|
+
T.METAL: LinkStyle("sch_metal", ()),
|
|
707
|
+
T.WATER_BRIDGE: LinkStyle("sch_water_bridge", (2.2, 2.2)),
|
|
708
|
+
# Only on a chain ligand, where a contact without a line cannot be told from its neighbour's.
|
|
709
|
+
T.HYDROPHOBIC: LinkStyle("bubble_line", (), width=0.6),
|
|
710
|
+
T.COVALENT: LinkStyle("ligand_bond", (), width=1.35, cap="round"),
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
SCHEMATIC_SIDECHAIN = LinkStyle("sch_hbond", (4.2, 2.6))
|
|
714
|
+
|
|
715
|
+
|
|
716
|
+
@dataclass(frozen=True)
|
|
717
|
+
class LineSet:
|
|
718
|
+
"""How the contacts of a figure are drawn: a line style for each kind of contact, and one for a hydrogen
|
|
719
|
+
bond of a side chain or a base where it is told from one of the backbone (``sidechain``)."""
|
|
720
|
+
|
|
721
|
+
name: str
|
|
722
|
+
styles: Mapping[InteractionType, LinkStyle]
|
|
723
|
+
sidechain: LinkStyle | None = None
|
|
724
|
+
|
|
725
|
+
def hbond(self, info: "PortInfo", grp: "ResidueGroup") -> tuple[LinkStyle, str]:
|
|
726
|
+
"""The line of a hydrogen bond, and what it is called in the key: ``backbone``, ``sidechain``,
|
|
727
|
+
``base``, or nothing in particular."""
|
|
728
|
+
if self.sidechain is None:
|
|
729
|
+
return self.styles[T.HBOND], ""
|
|
730
|
+
if info.site_kind == "atom" and not is_backbone_atom(grp.resname, info.site_atoms[0]):
|
|
731
|
+
return self.sidechain, "base" if is_nucleotide(grp.resname) else "sidechain"
|
|
732
|
+
return self.styles[T.HBOND], "backbone"
|
|
733
|
+
|
|
734
|
+
|
|
735
|
+
#: The line sets there are, by name (``RenderOptions.lines``).
|
|
736
|
+
LINES: dict[str, LineSet] = {
|
|
737
|
+
"detailed": LineSet("detailed", {**LINK_STYLES, T.HYDROPHOBIC: CHAIN_CONTACT}),
|
|
738
|
+
"schematic": LineSet("schematic", SCHEMATIC_LINKS, SCHEMATIC_SIDECHAIN),
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
|
|
742
|
+
@dataclass(frozen=True)
|
|
743
|
+
class Settings:
|
|
744
|
+
"""The settings of a style: how the residues are drawn, the lines, solvent exposure, the lining of the
|
|
745
|
+
pocket, and whether a distance is written without being asked for (``distances``)."""
|
|
746
|
+
|
|
747
|
+
residues: Any
|
|
748
|
+
lines: LineSet
|
|
749
|
+
exposure: bool
|
|
750
|
+
lining: str
|
|
751
|
+
distances: bool
|
|
752
|
+
|
|
753
|
+
def with_options(self, options: "RenderOptions") -> "Settings":
|
|
754
|
+
"""These settings with what the options set by hand in their place."""
|
|
755
|
+
asked = options.lining
|
|
756
|
+
lining = (self.lining if asked is None else asked if isinstance(asked, str) else
|
|
757
|
+
"contacts" if asked else "none")
|
|
758
|
+
return Settings(self.residues if options.residues is None else options.residues,
|
|
759
|
+
self.lines if options.lines is None else LINES[options.lines],
|
|
760
|
+
self.exposure if options.exposure is None else bool(options.exposure),
|
|
761
|
+
lining, self.distances)
|
|
762
|
+
|
|
763
|
+
def labelled(self, options: "RenderOptions"):
|
|
764
|
+
"""``labelled(kind)`` for :func:`port_infos`: is the distance of this kind of contact written?"""
|
|
765
|
+
if self.distances:
|
|
766
|
+
return options.labelled
|
|
767
|
+
# Maestro prints no distances; they are available on request.
|
|
768
|
+
return lambda kind: options.distance_labels == "all" and kind is not T.HYDROPHOBIC
|
|
769
|
+
|
|
770
|
+
def form_of(self, grp: "ResidueGroup") -> str:
|
|
771
|
+
"""How this residue is drawn: one of :data:`RESIDUE_FORMS`."""
|
|
772
|
+
if isinstance(self.residues, str):
|
|
773
|
+
return self.residues
|
|
774
|
+
table = dict(self.residues)
|
|
775
|
+
for name in residue_names(grp):
|
|
776
|
+
if name in table:
|
|
777
|
+
return table[name]
|
|
778
|
+
lowered = {k.lower(): v for k, v in table.items()}
|
|
779
|
+
for name in residue_names(grp):
|
|
780
|
+
if name.lower() in lowered:
|
|
781
|
+
return lowered[name.lower()]
|
|
782
|
+
return table.get("*", "")
|
|
783
|
+
|
|
784
|
+
|
|
785
|
+
def residue_names(grp: "ResidueGroup") -> list[str]:
|
|
786
|
+
"""What a residue can be called in ``residues=``: as the figure names it, with its chain, by its number."""
|
|
787
|
+
chain, number, icode = grp.key
|
|
788
|
+
plain = f"{grp.resname}{number}{icode}"
|
|
789
|
+
out = [grp.label, grp.ident, plain, f"{number}{icode}"]
|
|
790
|
+
if chain:
|
|
791
|
+
out += [f"{chain}:{plain}", f"{chain}:{number}{icode}"]
|
|
792
|
+
return out
|
|
793
|
+
|
|
794
|
+
|
|
795
|
+
#: What each style is: its settings. Every one of them can be set by hand (:class:`RenderOptions`).
|
|
796
|
+
STYLE_SETTINGS: dict[str, Settings] = {
|
|
797
|
+
"detailed": Settings("atoms", LINES["detailed"], False, "none", True),
|
|
798
|
+
"schematic": Settings("bubbles", LINES["schematic"], True, "contacts", False),
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
|
|
802
|
+
def _cut_by_box(a: Point, b: Point, box: tuple[float, float, float, float]) -> list[tuple[Point, Point]]:
|
|
803
|
+
"""Segment ``a->b`` with the part inside ``box`` removed."""
|
|
804
|
+
dx, dy = b[0] - a[0], b[1] - a[1]
|
|
805
|
+
t0, t1 = 0.0, 1.0
|
|
806
|
+
for p, q in ((-dx, a[0] - box[0]), (dx, box[2] - a[0]), (-dy, a[1] - box[1]), (dy, box[3] - a[1])):
|
|
807
|
+
if abs(p) < 1e-12:
|
|
808
|
+
if q < 0:
|
|
809
|
+
return [(a, b)]
|
|
810
|
+
continue
|
|
811
|
+
r = q / p
|
|
812
|
+
if p < 0:
|
|
813
|
+
t0 = max(t0, r)
|
|
814
|
+
else:
|
|
815
|
+
t1 = min(t1, r)
|
|
816
|
+
if t0 >= t1:
|
|
817
|
+
return [(a, b)]
|
|
818
|
+
out = []
|
|
819
|
+
if t0 > 1e-6:
|
|
820
|
+
out.append((a, lerp(a, b, t0)))
|
|
821
|
+
if t1 < 1.0 - 1e-6:
|
|
822
|
+
out.append((lerp(a, b, t1), b))
|
|
823
|
+
return out
|
|
824
|
+
|
|
825
|
+
|
|
826
|
+
def link_items(a: Point, b: Point, kind: InteractionType, metrics: Metrics, *, label: str | None = None,
|
|
827
|
+
arrow: str | None = None, opacity: float = 1.0, label_at: float = 0.5,
|
|
828
|
+
style: "LinkStyle | None" = None, weight: float = 1.0,
|
|
829
|
+
tag: "tuple[str, bool] | None" = None, glow: "str | None" = None) -> list[Item]:
|
|
830
|
+
"""A link from ``a`` (protein end) to ``b`` (ligand end).
|
|
831
|
+
|
|
832
|
+
``arrow`` is ``"a"`` or ``"b"``: put an arrowhead at that end (the acceptor
|
|
833
|
+
of an H-bond). ``label`` is printed at the midpoint with the line broken
|
|
834
|
+
around it, so no background patch is needed and the figure works on any
|
|
835
|
+
backdrop. ``weight`` scales the stroke width (confidence; see
|
|
836
|
+
:class:`~bindview.confidence.Look`).
|
|
837
|
+
"""
|
|
838
|
+
style = style or LINK_STYLES[kind]
|
|
839
|
+
paint = Paint(stroke=style.token, width=metrics.interaction_width * style.width * weight, dash=style.dash,
|
|
840
|
+
cap=style.cap, opacity=opacity)
|
|
841
|
+
out: list[Item] = []
|
|
842
|
+
length = dist(a, b)
|
|
843
|
+
if length < 1e-6:
|
|
844
|
+
return out
|
|
845
|
+
u = unit(sub(b, a))
|
|
846
|
+
start, end = a, b
|
|
847
|
+
if glow is not None:
|
|
848
|
+
out.append(Line(a[0], a[1], b[0], b[1],
|
|
849
|
+
Paint(stroke=glow, width=GLOW * metrics.interaction_width, cap="round",
|
|
850
|
+
opacity=_GLOW_OPACITIES.get(glow, GLOW_OPACITY))))
|
|
851
|
+
if kind is T.COVALENT:
|
|
852
|
+
# A bond to the target is what a reader looks for first: it stands on a highlight.
|
|
853
|
+
out.append(Line(a[0], a[1], b[0], b[1],
|
|
854
|
+
Paint(stroke=HIGHLIGHT, width=COVALENT_GLOW * metrics.interaction_width, cap="round",
|
|
855
|
+
opacity=0.4 * opacity)))
|
|
856
|
+
if arrow in ("a", "b") and length > 2.5 * _ARROW_LEN:
|
|
857
|
+
tip = a if arrow == "a" else b
|
|
858
|
+
back = add(tip, mul(u, _ARROW_LEN if arrow == "a" else -_ARROW_LEN))
|
|
859
|
+
n = perp(u)
|
|
860
|
+
half = _ARROW_HALF * (0.55 + 0.45 * weight)
|
|
861
|
+
out.append(Polygon((tip, add(back, mul(n, half)), add(back, mul(n, -half))),
|
|
862
|
+
Paint(fill=style.token, opacity=opacity)))
|
|
863
|
+
if arrow == "a":
|
|
864
|
+
start = lerp(tip, back, 0.85)
|
|
865
|
+
else:
|
|
866
|
+
end = lerp(tip, back, 0.85)
|
|
867
|
+
pieces = [(start, end)]
|
|
868
|
+
if label and not tag:
|
|
869
|
+
mid = lerp(a, b, label_at)
|
|
870
|
+
w = text_width(label, metrics.distance_font) + 3.0
|
|
871
|
+
h = CAP_HEIGHT * metrics.distance_font + 3.4
|
|
872
|
+
pieces = _cut_by_box(start, end, (mid[0] - w / 2.0, mid[1] - h / 2.0, mid[0] + w / 2.0, mid[1] + h / 2.0))
|
|
873
|
+
out.append(Text.plain(mid[0], mid[1] + CAP_HEIGHT * metrics.distance_font / 2.0, label,
|
|
874
|
+
metrics.distance_font, style.token, opacity=opacity))
|
|
875
|
+
elif tag:
|
|
876
|
+
# The predicted aligned error of the contact, written out: in the colour of the figure's text and at
|
|
877
|
+
# full strength whatever the line's, because it is not a property of the line. What pLDDT does to the
|
|
878
|
+
# stroke it does not do to this.
|
|
879
|
+
mid = lerp(a, b, label_at)
|
|
880
|
+
words, bold = tag
|
|
881
|
+
lead = (label + " ") if label else ""
|
|
882
|
+
w = text_width(lead, metrics.distance_font) + text_width(words, metrics.distance_font, bold=bold) + 3.0
|
|
883
|
+
h = CAP_HEIGHT * metrics.distance_font + 3.4
|
|
884
|
+
pieces = _cut_by_box(start, end, (mid[0] - w / 2.0, mid[1] - h / 2.0, mid[0] + w / 2.0, mid[1] + h / 2.0))
|
|
885
|
+
left = mid[0] - (w - 3.0) / 2.0
|
|
886
|
+
baseline = mid[1] + CAP_HEIGHT * metrics.distance_font / 2.0
|
|
887
|
+
if label:
|
|
888
|
+
out.append(Text.plain(left, baseline, label, metrics.distance_font, style.token, anchor="start",
|
|
889
|
+
opacity=opacity))
|
|
890
|
+
out.append(Text.plain(left + text_width(lead, metrics.distance_font), baseline, words, metrics.distance_font,
|
|
891
|
+
"text", anchor="start", bold=bold))
|
|
892
|
+
for p, q in pieces:
|
|
893
|
+
if dist(p, q) > 0.4:
|
|
894
|
+
out.append(Line(p[0], p[1], q[0], q[1], paint))
|
|
895
|
+
return out
|
|
896
|
+
|
|
897
|
+
|
|
898
|
+
def hbond_direction(r: ResolvedInteraction, dep: Depiction) -> tuple[str | None, str | None]:
|
|
899
|
+
"""``(arrow_end, note)`` for an H-bond-like interaction.
|
|
900
|
+
|
|
901
|
+
The arrowhead goes at the acceptor: ``"a"`` (protein end) when the ligand
|
|
902
|
+
donates, ``"b"`` (ligand end) when the protein does. No arrowhead is drawn
|
|
903
|
+
when the direction is unknown, or when the reported donor cannot donate in
|
|
904
|
+
the protonation state that is actually depicted -- the line is kept, the
|
|
905
|
+
impossible claim is not made.
|
|
906
|
+
"""
|
|
907
|
+
donor = r.record.ligand_is_donor
|
|
908
|
+
if donor is None or r.ligand is None:
|
|
909
|
+
return None, None
|
|
910
|
+
if donor:
|
|
911
|
+
if r.ligand.kind == "atom" and dep.atoms[r.ligand.atom].hcount == 0:
|
|
912
|
+
name = dep.atoms[r.ligand.atom].name
|
|
913
|
+
return None, (f"{r.record.residue_label}–{name}: reported with the ligand as donor, but {name} "
|
|
914
|
+
f"carries no hydrogen in the depicted protonation state; drawn without direction")
|
|
915
|
+
return "a", None
|
|
916
|
+
if r.protein.kind == "atom":
|
|
917
|
+
ok = can_donate(r.record.residue_name, r.protein.atoms[0])
|
|
918
|
+
if ok is False:
|
|
919
|
+
return None, (f"{r.record.residue_label} {r.protein.atoms[0]}: reported as donor, but that atom "
|
|
920
|
+
f"carries no hydrogen in the standard protonation state; drawn without direction")
|
|
921
|
+
return "b", None
|
|
922
|
+
|
|
923
|
+
|
|
924
|
+
def interaction_title(r: ResolvedInteraction, lig: Ligand, plddt: float | None = None,
|
|
925
|
+
dep: Depiction | None = None) -> str:
|
|
926
|
+
"""Tooltip text: what interacts with what, at what distance (and how confidently).
|
|
927
|
+
|
|
928
|
+
With the depiction of a chain ligand, the ligand's end names the residue
|
|
929
|
+
that makes the contact, its atoms, and whether they are backbone or side
|
|
930
|
+
chain: what the line itself does not show.
|
|
931
|
+
"""
|
|
932
|
+
rec = r.record
|
|
933
|
+
prot = rec.residue_label
|
|
934
|
+
if r.protein.kind == "atom":
|
|
935
|
+
prot += f" {r.protein.atoms[0]}"
|
|
936
|
+
elif r.protein.kind == "ring":
|
|
937
|
+
prot += " ring"
|
|
938
|
+
elif r.protein.kind == "group":
|
|
939
|
+
prot += " " + ("(+)" if r.protein.charge > 0 else "(−)" if r.protein.charge < 0 else "group")
|
|
940
|
+
res = dep.unit_for(r.ligand.atoms, True) if (dep is not None and dep.units and r.ligand is not None) else None
|
|
941
|
+
if r.ligand is None:
|
|
942
|
+
lg = "?"
|
|
943
|
+
elif res is not None:
|
|
944
|
+
part = res.part(r.ligand.atoms)
|
|
945
|
+
lg = (f"{res.text} {res.number or res.position} of {dep.called if dep is not None else 'the ligand'} "
|
|
946
|
+
f"({part}: "
|
|
947
|
+
f"{', '.join(lig.names[i] for i in r.ligand.atoms)})")
|
|
948
|
+
elif r.ligand.kind == "atom":
|
|
949
|
+
lg = lig.names[r.ligand.atom]
|
|
950
|
+
elif r.ligand.kind == "ring":
|
|
951
|
+
lg = "ring " + "-".join(lig.names[i] for i in r.ligand.atoms)
|
|
952
|
+
else:
|
|
953
|
+
lg = f"{r.ligand.group_kind or 'group'} " + "-".join(lig.names[i] for i in r.ligand.atoms)
|
|
954
|
+
text = f"{rec.type.label}: {prot} – {lg}"
|
|
955
|
+
if rec.predicted:
|
|
956
|
+
text = f"Predicted water site, not observed: {prot} – {lg}"
|
|
957
|
+
if r.absent:
|
|
958
|
+
text = f"{rec.type.label}, made by other models and not by the one shown: {prot} – {lg}"
|
|
959
|
+
if rec.distance is not None:
|
|
960
|
+
text += f", {rec.distance:.2f} Å"
|
|
961
|
+
if plddt is not None:
|
|
962
|
+
text += f", contact pLDDT {plddt:.0f}"
|
|
963
|
+
if rec.pae is not None:
|
|
964
|
+
text += f", PAE {rec.pae:.1f} \u00c5"
|
|
965
|
+
if len(rec.pae_draws) > 1:
|
|
966
|
+
text += (f" (median of {len(rec.pae_draws)} draws, {min(rec.pae_draws):.1f} to "
|
|
967
|
+
f"{max(rec.pae_draws):.1f})")
|
|
968
|
+
if rec.occupancy is not None:
|
|
969
|
+
text += f", occupancy {100.0 * rec.occupancy:.0f} %"
|
|
970
|
+
return text
|
|
971
|
+
|
|
972
|
+
|
|
973
|
+
# ---------------------------------------------------------------------------
|
|
974
|
+
# Hydrophobic contacts: eyelashes and spokes
|
|
975
|
+
# ---------------------------------------------------------------------------
|
|
976
|
+
|
|
977
|
+
def _arc_points(centre: Point, radius: float, a0: float, a1: float) -> tuple[Point, ...]:
|
|
978
|
+
n = max(6, int(math.ceil(abs(a1 - a0) * radius / 3.0)))
|
|
979
|
+
return tuple((centre[0] + radius * math.cos(a0 + (a1 - a0) * k / n),
|
|
980
|
+
centre[1] + radius * math.sin(a0 + (a1 - a0) * k / n)) for k in range(n + 1))
|
|
981
|
+
|
|
982
|
+
|
|
983
|
+
def _direction_clusters(centre: Point, targets: Sequence[Point]) -> list[tuple[float, float]]:
|
|
984
|
+
"""``[(mid_angle, half_width)]`` arcs facing ``targets`` as seen from ``centre``."""
|
|
985
|
+
angles = sorted(math.atan2(t[1] - centre[1], t[0] - centre[0]) % (2 * math.pi) for t in targets)
|
|
986
|
+
if not angles:
|
|
987
|
+
return []
|
|
988
|
+
if len(angles) == 1:
|
|
989
|
+
return [(angles[0], math.radians(56.0))]
|
|
990
|
+
gaps = [((angles[(i + 1) % len(angles)] - angles[i]) % (2 * math.pi), i) for i in range(len(angles))]
|
|
991
|
+
big, at = max(gaps)
|
|
992
|
+
spread = 2 * math.pi - big
|
|
993
|
+
start = angles[(at + 1) % len(angles)]
|
|
994
|
+
if spread <= math.radians(110.0):
|
|
995
|
+
return [(start + spread / 2.0, math.radians(56.0))]
|
|
996
|
+
# Two faces: split the run at its own widest internal gap.
|
|
997
|
+
run = [(a - start) % (2 * math.pi) for a in angles]
|
|
998
|
+
run.sort()
|
|
999
|
+
inner = [(run[i + 1] - run[i], i) for i in range(len(run) - 1)]
|
|
1000
|
+
_, cut = max(inner)
|
|
1001
|
+
out = []
|
|
1002
|
+
for part in (run[:cut + 1], run[cut + 1:]):
|
|
1003
|
+
mid = start + (part[0] + part[-1]) / 2.0
|
|
1004
|
+
out.append((mid, math.radians(40.0)))
|
|
1005
|
+
return out
|
|
1006
|
+
|
|
1007
|
+
|
|
1008
|
+
def eyelash_items(centre: Point, radius: float, targets: Sequence[Point], metrics: Metrics,
|
|
1009
|
+
opacity: float = 1.0, weight: float = 1.0) -> list[Item]:
|
|
1010
|
+
"""Arc(s) with lashes, bulging toward the ligand atoms in contact."""
|
|
1011
|
+
paint = Paint(stroke="hydrophobic", width=1.25 * weight, opacity=opacity)
|
|
1012
|
+
out: list[Item] = []
|
|
1013
|
+
for mid, half in _direction_clusters(centre, targets):
|
|
1014
|
+
out.append(Polyline(_arc_points(centre, radius, mid - half, mid + half), paint))
|
|
1015
|
+
n = 7 if half > math.radians(50.0) else 5
|
|
1016
|
+
for k in range(n):
|
|
1017
|
+
ang = mid - half + 2 * half * (k + 0.5) / n
|
|
1018
|
+
c, s = math.cos(ang), math.sin(ang)
|
|
1019
|
+
out.append(Line(centre[0] + radius * c, centre[1] + radius * s,
|
|
1020
|
+
centre[0] + (radius + metrics.lash_length) * c,
|
|
1021
|
+
centre[1] + (radius + metrics.lash_length) * s, paint))
|
|
1022
|
+
return out
|
|
1023
|
+
|
|
1024
|
+
|
|
1025
|
+
def eyelash_mark(centre: Point, radius: float, targets: Sequence[Point], metrics: Metrics) -> list[Item]:
|
|
1026
|
+
"""The marker pen under the arcs of :func:`eyelash_items`, lashes and all."""
|
|
1027
|
+
reach = metrics.lash_length
|
|
1028
|
+
return [other_protein.stroke(_arc_points(centre, radius + reach / 2.0, mid - half, mid + half), reach + 4.0, 1.0)
|
|
1029
|
+
for mid, half in _direction_clusters(centre, targets)]
|
|
1030
|
+
|
|
1031
|
+
|
|
1032
|
+
def spoke_items(dep: Depiction, atom: int, toward: Point, metrics: Metrics, opacity: float = 1.0,
|
|
1033
|
+
weight: float = 1.0) -> list[Item]:
|
|
1034
|
+
"""Short ticks on a ligand atom, fanned toward the residue it contacts.
|
|
1035
|
+
|
|
1036
|
+
Ticks are only drawn in the free sectors between the atom's bonds, so they
|
|
1037
|
+
never lie on top of the skeleton.
|
|
1038
|
+
"""
|
|
1039
|
+
p = dep.pos(atom)
|
|
1040
|
+
want = math.atan2(toward[1] - p[1], toward[0] - p[0])
|
|
1041
|
+
bonds = [math.atan2(q[1] - p[1], q[0] - p[0]) for q in (dep.pos(j) for j in dep.neighbours(atom, False))]
|
|
1042
|
+
keep_off = math.radians(21.0)
|
|
1043
|
+
|
|
1044
|
+
def free(ang: float) -> bool:
|
|
1045
|
+
return all(abs(angle_diff(ang, b)) >= keep_off for b in bonds)
|
|
1046
|
+
|
|
1047
|
+
centre = want
|
|
1048
|
+
if not free(centre):
|
|
1049
|
+
# Slide to the nearest free direction.
|
|
1050
|
+
best = None
|
|
1051
|
+
for step in range(1, 61):
|
|
1052
|
+
for sgn in (1.0, -1.0):
|
|
1053
|
+
cand = want + sgn * math.radians(3.0 * step)
|
|
1054
|
+
if free(cand):
|
|
1055
|
+
best = cand
|
|
1056
|
+
break
|
|
1057
|
+
if best is not None:
|
|
1058
|
+
break
|
|
1059
|
+
if best is None:
|
|
1060
|
+
return []
|
|
1061
|
+
centre = best
|
|
1062
|
+
r1 = spoke_reach(dep, atom, metrics)
|
|
1063
|
+
r0 = r1 - (metrics.spoke_outer - metrics.spoke_inner)
|
|
1064
|
+
paint = Paint(stroke="hydrophobic", width=1.1 * weight, opacity=opacity)
|
|
1065
|
+
out: list[Item] = []
|
|
1066
|
+
for off in (-0.42, 0.0, 0.42):
|
|
1067
|
+
ang = centre + off
|
|
1068
|
+
if not free(ang):
|
|
1069
|
+
continue
|
|
1070
|
+
c, s = math.cos(ang), math.sin(ang)
|
|
1071
|
+
out.append(Line(p[0] + r0 * c, p[1] + r0 * s, p[0] + r1 * c, p[1] + r1 * s, paint))
|
|
1072
|
+
return out
|
|
1073
|
+
|
|
1074
|
+
|
|
1075
|
+
def halo_items(segments: Sequence[tuple[Point, Point]], radius: float, token: str) -> list[Item]:
|
|
1076
|
+
"""A soft highlight along a charged group: the thing a salt bridge attaches to."""
|
|
1077
|
+
paint = Paint(stroke=token, width=2.0 * radius, opacity=0.17, cap="round")
|
|
1078
|
+
return [Line(p[0], p[1], q[0] + (0.01 if p == q else 0.0), q[1], paint) for p, q in segments]
|
|
1079
|
+
|
|
1080
|
+
|
|
1081
|
+
# ---------------------------------------------------------------------------
|
|
1082
|
+
# Ports shared by the styles
|
|
1083
|
+
# ---------------------------------------------------------------------------
|
|
1084
|
+
|
|
1085
|
+
# Length of the *visible* part of a link, in bond lengths: (ideal, minimum). What
|
|
1086
|
+
# the atoms, rings and groups at either end take up is added on top.
|
|
1087
|
+
VISIBLE_LENGTH = {
|
|
1088
|
+
T.HBOND: (1.45, 1.1), T.HALOGEN: (1.45, 1.1), T.METAL: (1.35, 1.05), T.WATER_BRIDGE: (1.5, 1.15),
|
|
1089
|
+
T.SALTBRIDGE: (1.3, 0.75), T.PI_STACKING: (1.3, 0.75), T.PI_CATION: (1.3, 0.75), T.HYDROPHOBIC: (1.9, 0.0),
|
|
1090
|
+
T.COVALENT: (0.85, 0.6),
|
|
1091
|
+
}
|
|
1092
|
+
#: ... and of the line a hydrophobic contact gets on a chain ligand.
|
|
1093
|
+
CHAIN_CONTACT_LENGTH = (0.9, 0.3)
|
|
1094
|
+
_PRIMARY_ORDER = {T.COVALENT: -1, T.METAL: 0, T.HBOND: 1, T.HALOGEN: 2, T.WATER_BRIDGE: 3, T.SALTBRIDGE: 4,
|
|
1095
|
+
T.PI_STACKING: 5, T.PI_CATION: 6, T.HYDROPHOBIC: 9}
|
|
1096
|
+
|
|
1097
|
+
|
|
1098
|
+
@dataclass
|
|
1099
|
+
class PortInfo:
|
|
1100
|
+
"""One link of a residue: which interactions it stands for and where it lands."""
|
|
1101
|
+
|
|
1102
|
+
interactions: list[ResolvedInteraction]
|
|
1103
|
+
kind: InteractionType
|
|
1104
|
+
site_kind: str # atom | ring | group | residue
|
|
1105
|
+
site_atoms: tuple[str, ...]
|
|
1106
|
+
target: Target
|
|
1107
|
+
drawn: bool
|
|
1108
|
+
label: str | None
|
|
1109
|
+
plddt: float | None = None # contact confidence: the lower of its two ends
|
|
1110
|
+
look: Look = PLAIN
|
|
1111
|
+
occupancy: float | None = None # share of the ensemble in which the contact is made
|
|
1112
|
+
#: Predicted aligned error between the two residues of the contact, where the caller gave one.
|
|
1113
|
+
#: It is never drawn by the stroke (that is pLDDT's): it is written on the line (:attr:`tag`),
|
|
1114
|
+
#: in the figure of an interface, which is the one that explains the tag (``written``).
|
|
1115
|
+
pae: float | None = None
|
|
1116
|
+
#: ... and, where that is the median over several draws of the model, the value of each draw.
|
|
1117
|
+
pae_draws: tuple[float, ...] = ()
|
|
1118
|
+
written: bool = False
|
|
1119
|
+
#: A residue of a chain ligand is one place. When a residue of the protein has several links to
|
|
1120
|
+
#: it (an H-bond and a salt bridge), each gets a lane: a shift across the line, so that they run
|
|
1121
|
+
#: side by side instead of on top of each other. Zero everywhere else.
|
|
1122
|
+
lane: float = 0.0
|
|
1123
|
+
#: Is occupancy drawn in steps (``RenderOptions.occupancy_style``)?
|
|
1124
|
+
steps: bool = False
|
|
1125
|
+
#: Is the PAE drawn as a glow (``RenderOptions.pae_colors``)?
|
|
1126
|
+
glowing: bool = False
|
|
1127
|
+
#: Is the residue set back because another protein lacks it (``absent_style="faint"``)?
|
|
1128
|
+
faint: bool = False
|
|
1129
|
+
|
|
1130
|
+
@property
|
|
1131
|
+
def glow(self) -> str | None:
|
|
1132
|
+
"""The colour a contact's line stands on for its PAE, where that is drawn."""
|
|
1133
|
+
if not self.glowing or not self.drawn or self.pae is None:
|
|
1134
|
+
return None
|
|
1135
|
+
return f"plddt_{pae_band(self.pae)}"
|
|
1136
|
+
|
|
1137
|
+
@property
|
|
1138
|
+
def beyond(self) -> bool:
|
|
1139
|
+
return all(r.record.beyond_contact_set for r in self.interactions)
|
|
1140
|
+
|
|
1141
|
+
@property
|
|
1142
|
+
def absent(self) -> bool:
|
|
1143
|
+
"""Is this a contact that the structure shown does not make, and other models of its ensemble do?"""
|
|
1144
|
+
return all(r.absent for r in self.interactions)
|
|
1145
|
+
|
|
1146
|
+
@property
|
|
1147
|
+
def tag(self) -> "tuple[str, bool] | None":
|
|
1148
|
+
"""``("PAE 11", bold)`` for a drawn contact whose PAE is worth saying (:func:`bindview.pae.pae_tag`)."""
|
|
1149
|
+
return pae_tag(self.pae) if (self.drawn and self.written) else None
|
|
1150
|
+
|
|
1151
|
+
@property
|
|
1152
|
+
def shown(self) -> str | None:
|
|
1153
|
+
"""Everything that is printed on the line: the label and the tag, for the room they need."""
|
|
1154
|
+
parts = [t for t in (self.label, self.tag[0] if self.tag else None) if t]
|
|
1155
|
+
return " ".join(parts) if parts else None
|
|
1156
|
+
|
|
1157
|
+
@property
|
|
1158
|
+
def predicted(self) -> bool:
|
|
1159
|
+
"""Is this a contact through a predicted solvent site (not observed, not detected)?"""
|
|
1160
|
+
return all(r.record.predicted for r in self.interactions)
|
|
1161
|
+
|
|
1162
|
+
@property
|
|
1163
|
+
def weight(self) -> float:
|
|
1164
|
+
"""Stroke-width factor: confidence and occupancy, each scaling the line."""
|
|
1165
|
+
return self.look.width * occupancy_factors(self.occupancy, self.steps)[0]
|
|
1166
|
+
|
|
1167
|
+
@property
|
|
1168
|
+
def opacity(self) -> float:
|
|
1169
|
+
"""Stroke opacity: confidence, occupancy, and the fading of contacts outside the contact set."""
|
|
1170
|
+
return min(self.look.opacity * occupancy_factors(self.occupancy, self.steps)[1], 0.5 if self.beyond else 1.0,
|
|
1171
|
+
ABSENT_OPACITY if self.absent or self.faint else 1.0)
|
|
1172
|
+
|
|
1173
|
+
def absorb(self, other: "PortInfo | ResolvedInteraction") -> None:
|
|
1174
|
+
"""Let this link also stand for further records. Its occupancy is then that of the most
|
|
1175
|
+
persistent of them: the link is there whenever any of them is, so this is a lower bound."""
|
|
1176
|
+
records = other.interactions if isinstance(other, PortInfo) else [other]
|
|
1177
|
+
self.interactions.extend(records)
|
|
1178
|
+
values = [v for v in [self.occupancy] + [r.record.occupancy for r in records] if v is not None]
|
|
1179
|
+
self.occupancy = max(values) if values else None
|
|
1180
|
+
for r in records:
|
|
1181
|
+
# The smallest value stands for the link, and brings its own draws with it.
|
|
1182
|
+
if r.record.pae is not None and (self.pae is None or r.record.pae < self.pae):
|
|
1183
|
+
self.pae, self.pae_draws = r.record.pae, r.record.pae_draws
|
|
1184
|
+
|
|
1185
|
+
|
|
1186
|
+
def _ring_systems(rings: "Sequence[frozenset]") -> "dict[frozenset, frozenset]":
|
|
1187
|
+
"""Each ring's fused system: all the atoms of the rings joined to it by a shared bond, and so on."""
|
|
1188
|
+
parent = list(range(len(rings)))
|
|
1189
|
+
|
|
1190
|
+
def root(i: int) -> int:
|
|
1191
|
+
while parent[i] != i:
|
|
1192
|
+
i = parent[i]
|
|
1193
|
+
return i
|
|
1194
|
+
|
|
1195
|
+
for i in range(len(rings)):
|
|
1196
|
+
for j in range(i + 1, len(rings)):
|
|
1197
|
+
if len(rings[i] & rings[j]) >= 2 and root(i) != root(j):
|
|
1198
|
+
parent[root(i)] = root(j)
|
|
1199
|
+
members: dict[int, set] = {}
|
|
1200
|
+
for i, ring in enumerate(rings):
|
|
1201
|
+
members.setdefault(root(i), set()).update(ring)
|
|
1202
|
+
return {ring: frozenset(members[root(i)]) for i, ring in enumerate(rings)}
|
|
1203
|
+
|
|
1204
|
+
|
|
1205
|
+
def _stacked_pairs(ctx: Context, records: "Sequence[ResolvedInteraction]"
|
|
1206
|
+
) -> "tuple[list[ResolvedInteraction], dict[int, tuple]]":
|
|
1207
|
+
"""One stacked pair, one line.
|
|
1208
|
+
|
|
1209
|
+
A π-stack is found ring by ring: an indole over a pteridine is up to four pairs of rings, and would be
|
|
1210
|
+
four lines from one residue into one place. Where one fused ring system of a residue stacks on one
|
|
1211
|
+
fused ring system of the ligand (or on one residue of a chain ligand) with more than one pair of rings,
|
|
1212
|
+
those records are one link, drawn at the shortest of them; the others stand in its title. Returns the
|
|
1213
|
+
records, the stacking ones among them in order of distance where they are merged, and the key of the
|
|
1214
|
+
link each merged record belongs to. A stack made by one pair of rings is left as it was."""
|
|
1215
|
+
stacks = [k for k, r in enumerate(records) if r.type is T.PI_STACKING and r.ligand is not None
|
|
1216
|
+
and r.protein.kind == "ring" and r.ligand.kind == "ring"]
|
|
1217
|
+
if len(stacks) < 2:
|
|
1218
|
+
return list(records), {}
|
|
1219
|
+
protein = _ring_systems(list(dict.fromkeys(frozenset(records[k].protein.atoms) for k in stacks)))
|
|
1220
|
+
ligand = _ring_systems(list(dict.fromkeys([*(frozenset(r) for r in ctx.dep.rings),
|
|
1221
|
+
*(frozenset(records[k].ligand.atoms) # type: ignore[union-attr]
|
|
1222
|
+
for k in stacks)])))
|
|
1223
|
+
by_pair: dict[tuple, list[int]] = {}
|
|
1224
|
+
for k in stacks:
|
|
1225
|
+
r = records[k]
|
|
1226
|
+
assert r.ligand is not None
|
|
1227
|
+
res = ctx.dep.unit_for(r.ligand.atoms, False) if ctx.dep.units else None
|
|
1228
|
+
place = ("unit", res.index) if res is not None else ("ring", ligand[frozenset(r.ligand.atoms)])
|
|
1229
|
+
by_pair.setdefault((T.PI_STACKING, "ring", protein[frozenset(r.protein.atoms)], *place), []).append(k)
|
|
1230
|
+
out, keys = list(records), {}
|
|
1231
|
+
for key, ks in by_pair.items():
|
|
1232
|
+
if len({(records[k].protein.atoms, records[k].ligand.atoms) for k in ks}) < 2: # type: ignore[union-attr]
|
|
1233
|
+
continue
|
|
1234
|
+
nearest = sorted((records[k] for k in ks),
|
|
1235
|
+
key=lambda r: r.record.distance if r.record.distance is not None else 99.0)
|
|
1236
|
+
for k, r in zip(ks, nearest):
|
|
1237
|
+
out[k] = r
|
|
1238
|
+
keys[id(r)] = key
|
|
1239
|
+
return out, keys
|
|
1240
|
+
|
|
1241
|
+
|
|
1242
|
+
def port_infos(ctx: Context, grp: ResidueGroup, labelled) -> list[PortInfo]:
|
|
1243
|
+
"""One port per distinct (protein site, ligand anchor, type); primary first.
|
|
1244
|
+
|
|
1245
|
+
``labelled(kind)`` says whether that type's distance is printed.
|
|
1246
|
+
"""
|
|
1247
|
+
table: dict[tuple, PortInfo] = {}
|
|
1248
|
+
records = grp.interactions
|
|
1249
|
+
if ctx.dep.pairwise:
|
|
1250
|
+
# One line per pair of residues and kind: the closest pair of atoms speaks for all of them.
|
|
1251
|
+
records = sorted(records, key=lambda r: r.record.distance if r.record.distance is not None else 99.0)
|
|
1252
|
+
records, stacked = _stacked_pairs(ctx, records)
|
|
1253
|
+
for r in records:
|
|
1254
|
+
assert r.ligand is not None
|
|
1255
|
+
site = r.protein
|
|
1256
|
+
# A contact without a direction is one with the residue, whatever is drawn of the residue.
|
|
1257
|
+
whole = r.type is T.HYDROPHOBIC
|
|
1258
|
+
res = ctx.dep.unit_for(r.ligand.atoms, whole) if ctx.dep.units else None
|
|
1259
|
+
# In a chain ligand the residue is what a contact lands on: two atoms of one residue are one place.
|
|
1260
|
+
where = ("unit", res.index) if res is not None else (r.ligand.kind, r.ligand.atoms)
|
|
1261
|
+
key = (r.type, site.kind, site.atoms, *where, r.record.predicted, r.absent)
|
|
1262
|
+
if id(r) in stacked:
|
|
1263
|
+
key = (*stacked[id(r)], r.record.predicted, r.absent)
|
|
1264
|
+
if res is not None and (r.type is T.HYDROPHOBIC or ctx.dep.pairwise):
|
|
1265
|
+
# ... and a hydrophobic contact is one between two residues, whichever of their atoms are close.
|
|
1266
|
+
# In the figure of an interface every contact is: a column of residues on one side leaves
|
|
1267
|
+
# no room, and no use, for three lines from three atoms of one residue into one box.
|
|
1268
|
+
key = (r.type, *where, r.record.predicted, r.absent)
|
|
1269
|
+
info = table.get(key)
|
|
1270
|
+
if info is not None:
|
|
1271
|
+
info.absorb(r)
|
|
1272
|
+
continue
|
|
1273
|
+
# A hydrophobic contact has no line: it is read off by proximity, spokes facing spokes. Beside a
|
|
1274
|
+
# column of residue boxes that does not work -- there is not room for everything beside its own
|
|
1275
|
+
# box, and a contact drawn two boxes away is read as a contact with the wrong residue. On a
|
|
1276
|
+
# chain ligand it therefore gets a line as well, a fine one without a label.
|
|
1277
|
+
drawn = r.type is not T.HYDROPHOBIC or res is not None
|
|
1278
|
+
label = None
|
|
1279
|
+
if r.type is T.WATER_BRIDGE:
|
|
1280
|
+
# The bridging water sits on the link, where a distance would -- and says so if it is a guess.
|
|
1281
|
+
label = PREDICTED_LABEL if r.record.predicted else "H\u2082O"
|
|
1282
|
+
elif r.type is T.HYDROPHOBIC:
|
|
1283
|
+
pass
|
|
1284
|
+
elif drawn and labelled(r.type) and r.record.distance is not None:
|
|
1285
|
+
label = f"{r.record.distance:.2f}"
|
|
1286
|
+
if r.absent and drawn:
|
|
1287
|
+
# No distance: the structure shown has none for it. The share of the models that make it
|
|
1288
|
+
# stands where a distance would.
|
|
1289
|
+
label = share_label(r.record.occupancy, label)
|
|
1290
|
+
plddt = contact_plddt(ctx, r)
|
|
1291
|
+
look = ctx.look(plddt)
|
|
1292
|
+
if drawn and look.mark and not r.record.predicted and r.type is not T.HYDROPHOBIC:
|
|
1293
|
+
# The lowest band carries a visible mark; it sits where a distance would,
|
|
1294
|
+
# so the layout reserves room for it like for any other label.
|
|
1295
|
+
label = f"{label} {MARK}" if label else MARK
|
|
1296
|
+
table[key] = PortInfo([r], r.type, site.kind, site.atoms,
|
|
1297
|
+
ligand_target(ctx.dep, r.ligand, ctx.metrics, whole),
|
|
1298
|
+
drawn, label, plddt, look, r.record.occupancy, pae=r.record.pae,
|
|
1299
|
+
pae_draws=r.record.pae_draws, written=ctx.dep.pairwise and not ctx.glows,
|
|
1300
|
+
glowing=ctx.glows, faint=grp.faint,
|
|
1301
|
+
steps=ctx.options.occupancy_style == "steps")
|
|
1302
|
+
if ctx.options.occupancy_style == "steps":
|
|
1303
|
+
# The share of a contact made in fewer than all the models stands on its line, where a distance would.
|
|
1304
|
+
# Written once the links are merged: a link is drawn at the share of its most persistent record.
|
|
1305
|
+
for info in table.values():
|
|
1306
|
+
if info.occupancy is None or not info.drawn or info.absent or info.kind is T.HYDROPHOBIC:
|
|
1307
|
+
continue
|
|
1308
|
+
in_all = info.occupancy >= SHARE_WRITTEN_BELOW
|
|
1309
|
+
if not in_all or (ctx.shares_written and not (info.label and ctx.options.distance_labels == "all")):
|
|
1310
|
+
water = (PREDICTED_LABEL if info.predicted else "H\u2082O") if info.kind is T.WATER_BRIDGE else None
|
|
1311
|
+
text = share_label(info.occupancy, water)
|
|
1312
|
+
info.label = f"{text} {MARK}" if text and info.look.mark and not info.predicted else text
|
|
1313
|
+
|
|
1314
|
+
def order(info: PortInfo) -> tuple:
|
|
1315
|
+
d = info.interactions[0].record.distance
|
|
1316
|
+
return (0 if info.drawn else 1, _PRIMARY_ORDER[info.kind], d if d is not None else 99.0,
|
|
1317
|
+
info.site_atoms, info.target.atoms)
|
|
1318
|
+
set_lanes(sorted((i for i in table.values() if i.drawn and i.target.unit is not None), key=order))
|
|
1319
|
+
return sorted(table.values(), key=order)
|
|
1320
|
+
|
|
1321
|
+
|
|
1322
|
+
#: Distance between two links of one residue to one residue of a chain ligand, and the room there is for them.
|
|
1323
|
+
_LANE = 8.0
|
|
1324
|
+
_LANES_SPAN = 12.0
|
|
1325
|
+
|
|
1326
|
+
|
|
1327
|
+
def set_lanes(infos: "Sequence[PortInfo]") -> None:
|
|
1328
|
+
"""Give every drawn link its lane where several of them end on the same residue of a chain ligand."""
|
|
1329
|
+
by_unit: dict[int, list[PortInfo]] = {}
|
|
1330
|
+
for info in infos:
|
|
1331
|
+
assert info.target.unit is not None
|
|
1332
|
+
by_unit.setdefault(info.target.unit, []).append(info)
|
|
1333
|
+
for same in by_unit.values():
|
|
1334
|
+
if len(same) < 2:
|
|
1335
|
+
for info in same: # alone after all (its companions were merged into it): back to the middle
|
|
1336
|
+
x, y = info.target.point
|
|
1337
|
+
info.target = replace(info.target, point=(x, y - info.lane))
|
|
1338
|
+
info.lane = 0.0
|
|
1339
|
+
continue
|
|
1340
|
+
step = min(_LANE, _LANES_SPAN / (len(same) - 1))
|
|
1341
|
+
for k, info in enumerate(same):
|
|
1342
|
+
lane = (k - (len(same) - 1) / 2.0) * step
|
|
1343
|
+
x, y = info.target.point
|
|
1344
|
+
info.target = replace(info.target, point=(x, y + lane - info.lane))
|
|
1345
|
+
info.lane = lane
|
|
1346
|
+
|
|
1347
|
+
|
|
1348
|
+
def tag_slack(dep: Depiction, info: "PortInfo") -> float:
|
|
1349
|
+
"""Extra length a line with a tag on it needs where it ends on a residue box of a chain.
|
|
1350
|
+
|
|
1351
|
+
A line into a box is reckoned to end a fixed distance from the box's centre, which is right from
|
|
1352
|
+
above or below and too little from the side, where the box is widest. A distance label has always
|
|
1353
|
+
had room to spare; a tag is long enough to cover what is left of a short line. With this much more
|
|
1354
|
+
a piece of the line is seen on either side of it from any direction.
|
|
1355
|
+
"""
|
|
1356
|
+
if info.tag is None or info.target.unit is None:
|
|
1357
|
+
return 0.0
|
|
1358
|
+
box = dep.units[info.target.unit].box
|
|
1359
|
+
return max(0.0, (box[2] - box[0]) / 2.0 - info.target.extent)
|
|
1360
|
+
|
|
1361
|
+
|
|
1362
|
+
def label_size(text: str, font: float) -> tuple[float, float]:
|
|
1363
|
+
return (text_width(text, font) + 2.0, CAP_HEIGHT * font + 2.4)
|
|
1364
|
+
|
|
1365
|
+
|
|
1366
|
+
def make_ports(ctx: Context, infos: Sequence[PortInfo], locate) -> list[Port]:
|
|
1367
|
+
"""Engine ports for a residue. ``locate(info)`` gives, for the protein end of
|
|
1368
|
+
a link, ``(local point, ink radius, upright index, extent, clip)``."""
|
|
1369
|
+
m = ctx.metrics
|
|
1370
|
+
bl = m.bond_length
|
|
1371
|
+
ports = []
|
|
1372
|
+
n_sight = sum(1 for i in infos if not i.drawn) or 1
|
|
1373
|
+
for info in infos:
|
|
1374
|
+
local, port_radius, upright, extent, clip = locate(info)
|
|
1375
|
+
ideal, minimum = CHAIN_CONTACT_LENGTH if (info.kind is T.HYDROPHOBIC and info.drawn) \
|
|
1376
|
+
else VISIBLE_LENGTH[info.kind]
|
|
1377
|
+
label = label_size(info.shown, m.distance_font) if info.shown else None
|
|
1378
|
+
if label is not None and info.predicted:
|
|
1379
|
+
label = (label[0] + 8.0, label[1] + 4.0) # room for the outline drawn around a predicted site
|
|
1380
|
+
ideal_px, min_px = ideal * bl, minimum * bl
|
|
1381
|
+
if label is not None:
|
|
1382
|
+
# A printed distance needs room whatever the bond length.
|
|
1383
|
+
ideal_px = max(ideal_px, label[0] + 24.0)
|
|
1384
|
+
min_px = max(min_px, label[0] + 13.0)
|
|
1385
|
+
ends = info.target.extent + extent + tag_slack(ctx.dep, info)
|
|
1386
|
+
ports.append(Port(
|
|
1387
|
+
local=local, target=info.target.point, ideal=ideal_px + ends,
|
|
1388
|
+
min_length=min_px + ends if info.drawn else 0.0,
|
|
1389
|
+
weight=SPRINGS["link"] if info.drawn else SPRINGS["sightline"] / n_sight, drawn=info.drawn,
|
|
1390
|
+
port_radius=port_radius, target_radius=info.target.radius, target_reach=info.target.extent,
|
|
1391
|
+
label_size=label,
|
|
1392
|
+
target_caps=info.target.caps, port_upright=upright,
|
|
1393
|
+
port_caps=clip[0] if clip else None, port_uprights=clip[1] if clip else ()))
|
|
1394
|
+
return ports
|
|
1395
|
+
|
|
1396
|
+
|
|
1397
|
+
def interaction_data(ctx: Context, grp: ResidueGroup, info: PortInfo) -> dict[str, str]:
|
|
1398
|
+
"""``data-*`` attributes that make an interaction addressable from a web page."""
|
|
1399
|
+
rec = info.interactions[0].record
|
|
1400
|
+
data = {"residue": grp.ident, NUMBER: grp.numbered, "type": info.kind.value,
|
|
1401
|
+
"ligand-atoms": ",".join(ctx.ligand.names[i] for i in info.target.atoms)}
|
|
1402
|
+
if info.target.unit is not None:
|
|
1403
|
+
# A residue of a chain ligand makes it: name the residue, and every atom of it that takes part.
|
|
1404
|
+
res = ctx.dep.units[info.target.unit]
|
|
1405
|
+
atoms = list(dict.fromkeys(a for r in info.interactions if r.ligand is not None for a in r.ligand.atoms))
|
|
1406
|
+
data["ligand-atoms"] = ",".join(ctx.ligand.names[i] for i in atoms)
|
|
1407
|
+
data["ligand-residue"] = f"{res.text}{res.number or res.position}"
|
|
1408
|
+
data["ligand-part"] = res.part(atoms).replace(" ", "-")
|
|
1409
|
+
if info.pae is not None:
|
|
1410
|
+
data["pae"] = f"{info.pae:.1f}"
|
|
1411
|
+
if len(info.pae_draws) > 1:
|
|
1412
|
+
data["pae-draws"] = " ".join(f"{v:.1f}" for v in info.pae_draws)
|
|
1413
|
+
if info.site_atoms:
|
|
1414
|
+
data["protein-atoms"] = ",".join(info.site_atoms)
|
|
1415
|
+
if rec.distance is not None:
|
|
1416
|
+
data["distance"] = f"{rec.distance:.2f}"
|
|
1417
|
+
if info.beyond:
|
|
1418
|
+
data["beyond"] = "true"
|
|
1419
|
+
if info.plddt is not None and info.look.band is not None:
|
|
1420
|
+
data["plddt"] = f"{info.plddt:.1f}"
|
|
1421
|
+
data["confidence"] = info.look.band
|
|
1422
|
+
if info.occupancy is not None:
|
|
1423
|
+
data["occupancy"] = f"{info.occupancy:.3f}"
|
|
1424
|
+
if info.predicted:
|
|
1425
|
+
data["predicted"] = "true"
|
|
1426
|
+
if info.absent:
|
|
1427
|
+
data["absent"] = "true"
|
|
1428
|
+
if grp.lost:
|
|
1429
|
+
data[other_protein.FROM] = other_protein.said_of(ctx.options)
|
|
1430
|
+
return data
|
|
1431
|
+
|
|
1432
|
+
|
|
1433
|
+
# ---------------------------------------------------------------------------
|
|
1434
|
+
# Legend
|
|
1435
|
+
# ---------------------------------------------------------------------------
|
|
1436
|
+
|
|
1437
|
+
@dataclass(frozen=True)
|
|
1438
|
+
class LegendEntry:
|
|
1439
|
+
"""One legend entry: ``sample`` says what is drawn in front of the text.
|
|
1440
|
+
|
|
1441
|
+
``link``: a line in ``style`` (with an arrowhead if ``arrow``); ``eyelash``;
|
|
1442
|
+
``swatch``: a filled disc in ``token``; ``halo``: a soft disc in ``token``;
|
|
1443
|
+
``scale``: a bar ``length`` page units long, for a figure in which a length means something;
|
|
1444
|
+
``tag``: words that are written on lines of the figure (``marks``), as they are written there;
|
|
1445
|
+
``lining``: a piece of the pocket's lining in ``token``; ``site``: a predicted water on its line;
|
|
1446
|
+
``glow``: a piece of the glow of a contact's predicted aligned error in ``token``;
|
|
1447
|
+
``ring``: the ring of a residue (:mod:`bindview.styles.rings`);
|
|
1448
|
+
``marker``: a line on a stroke of the marker pen (:mod:`bindview.styles.absence`);
|
|
1449
|
+
``text``: no sample at all.
|
|
1450
|
+
"""
|
|
1451
|
+
|
|
1452
|
+
label: str
|
|
1453
|
+
sample: str = "text"
|
|
1454
|
+
kind: InteractionType | None = None
|
|
1455
|
+
style: LinkStyle | None = None
|
|
1456
|
+
token: str | None = None
|
|
1457
|
+
arrow: bool = False
|
|
1458
|
+
stroke: str | None = None
|
|
1459
|
+
weight: float = 1.0 # ``weight`` sample: stroke width factor ...
|
|
1460
|
+
opacity: float = 1.0 # ... and opacity of a confidence band
|
|
1461
|
+
mark: str = "" # ... and the mark printed on it
|
|
1462
|
+
dash: tuple[float, ...] = () # ``node`` sample: outline dash (``weight`` is its width)
|
|
1463
|
+
length: float = 0.0 # ``scale`` sample: the length of the bar
|
|
1464
|
+
#: ``tag`` sample: words that are written on lines of the figure, each with whether it is bold there.
|
|
1465
|
+
marks: "tuple[tuple[str, bool], ...]" = ()
|
|
1466
|
+
|
|
1467
|
+
|
|
1468
|
+
@dataclass
|
|
1469
|
+
class StyleDrawing:
|
|
1470
|
+
"""What a style hands back: items by layer (bottom first) and bookkeeping."""
|
|
1471
|
+
|
|
1472
|
+
layers: dict[str, list[Item]]
|
|
1473
|
+
legend: list[LegendEntry]
|
|
1474
|
+
notes: list[str] = field(default_factory=list)
|
|
1475
|
+
has_distances: bool = False
|
|
1476
|
+
levels: set[int] = field(default_factory=set) # confidence levels that occur (0 = unqualified)
|
|
1477
|
+
occupancy: bool = False # some contact carries an occupancy
|
|
1478
|
+
predicted: bool = False # some contact runs through a predicted solvent site
|
|
1479
|
+
#: For every PAE tag that was written on a line: is it bold? What the legend's key of a tag follows.
|
|
1480
|
+
tags: list[bool] = field(default_factory=list)
|
|
1481
|
+
#: Was a residue beside the ligand drawn with atoms at a level of detail that was asked for? Then
|
|
1482
|
+
#: its atoms carry confidence of their own, and the figure has to say on what basis.
|
|
1483
|
+
atoms_at_level: bool = False
|
|
1484
|
+
#: Was the fragment of a residue drawn with every atom at its own pLDDT without a level of detail
|
|
1485
|
+
#: (``plddt_by_atom``)? The figure then says so, as it does for a level.
|
|
1486
|
+
atoms_by_own: bool = False
|
|
1487
|
+
#: Does a contact stand on a glow for its predicted aligned error?
|
|
1488
|
+
glows: bool = False
|
|
1489
|
+
|
|
1490
|
+
|
|
1491
|
+
@dataclass
|
|
1492
|
+
class Drawn:
|
|
1493
|
+
"""What drawing the residues of a figure gathers: the items, and what the key has to name."""
|
|
1494
|
+
|
|
1495
|
+
layers: dict[str, list[Item]]
|
|
1496
|
+
kinds: list[InteractionType] = field(default_factory=list)
|
|
1497
|
+
notes: list[str] = field(default_factory=list)
|
|
1498
|
+
classes: list[str] = field(default_factory=list) # residue classes that colour a bubble
|
|
1499
|
+
halo_done: set[tuple] = field(default_factory=set)
|
|
1500
|
+
dots_done: set[tuple] = field(default_factory=set)
|
|
1501
|
+
hbonds: set[str] = field(default_factory=set) # backbone | sidechain | base, where they are told apart
|
|
1502
|
+
lashes: bool = False # a hydrophobic contact is an eyelash or a spoke
|
|
1503
|
+
whole: bool = False # ... or a line into a residue of a chain ligand
|
|
1504
|
+
has_distances: bool = False
|
|
1505
|
+
beyond: bool = False
|
|
1506
|
+
occupancy: bool = False
|
|
1507
|
+
predicted: bool = False
|
|
1508
|
+
absent: bool = False
|
|
1509
|
+
lost: bool = False # a residue that the protein compared with does not have
|
|
1510
|
+
levels: set[int] = field(default_factory=set)
|
|
1511
|
+
tags: list[bool] = field(default_factory=list)
|
|
1512
|
+
glows: bool = False # a contact stands on a glow for its PAE
|
|
1513
|
+
atoms_at_level: bool = False
|
|
1514
|
+
atoms_by_own: bool = False
|
|
1515
|
+
claims: "list[LiningClaim]" = field(default_factory=list)
|
|
1516
|
+
rings: bool = False # a residue stands in a ring (``Context.shares``)
|
|
1517
|
+
#: Where bubbles stand, with their radius and the colour they are filled with (``lining="nearest"``).
|
|
1518
|
+
placed: list[tuple[Point, float, str]] = field(default_factory=list)
|
|
1519
|
+
|
|
1520
|
+
|
|
1521
|
+
_CLASS_LABEL = {
|
|
1522
|
+
"hydrophobic": "Hydrophobic", "polar": "Polar", "positive": "Charged (+)", "negative": "Charged (−)",
|
|
1523
|
+
"glycine": "Glycine", "nucleotide": "Nucleotide", "metal": "Metal", "water": "Water", "other": "Other",
|
|
1524
|
+
}
|
|
1525
|
+
_CLASS_ORDER = ["hydrophobic", "polar", "positive", "negative", "glycine", "nucleotide", "metal", "water", "other"]
|
|
1526
|
+
|
|
1527
|
+
|
|
1528
|
+
def finish_drawing(ctx: Context, settings: "Settings", d: Drawn) -> StyleDrawing:
|
|
1529
|
+
"""What every style does once its residues are drawn: the backdrop (exposure, lining) and the key."""
|
|
1530
|
+
back: list[Item] = []
|
|
1531
|
+
if settings.exposure:
|
|
1532
|
+
back.extend(exposure_items(ctx))
|
|
1533
|
+
faces: set[str] = set()
|
|
1534
|
+
if settings.lining == "contacts":
|
|
1535
|
+
items, faces = lining_items(ctx, d.claims)
|
|
1536
|
+
back.extend(items)
|
|
1537
|
+
elif settings.lining == "nearest":
|
|
1538
|
+
back.extend(ribbon_items(ctx, d.placed))
|
|
1539
|
+
if back:
|
|
1540
|
+
d.layers["backdrop"] = back + d.layers.get("backdrop", [])
|
|
1541
|
+
styles = settings.lines.styles
|
|
1542
|
+
legend = [LegendEntry(_CLASS_LABEL[c], "swatch", token=f"class_{c}", stroke="bubble_line")
|
|
1543
|
+
for c in _CLASS_ORDER if c in d.classes]
|
|
1544
|
+
if d.rings:
|
|
1545
|
+
legend.append(LegendEntry(f"Ring: share of {ctx.ensemble or 'the models'} that contact the residue", "ring"))
|
|
1546
|
+
kinds = list(d.kinds)
|
|
1547
|
+
if settings.lines.sidechain is not None:
|
|
1548
|
+
if "backbone" in d.hbonds:
|
|
1549
|
+
legend.append(LegendEntry("H-bond (backbone)", "link", kind=T.HBOND, style=styles[T.HBOND], arrow=True))
|
|
1550
|
+
if d.hbonds & {"sidechain", "base"}:
|
|
1551
|
+
words = ("side chain" if "base" not in d.hbonds else "base" if "sidechain" not in d.hbonds
|
|
1552
|
+
else "side chain or base")
|
|
1553
|
+
legend.append(LegendEntry(f"H-bond ({words})", "link", kind=T.HBOND, style=settings.lines.sidechain,
|
|
1554
|
+
arrow=True))
|
|
1555
|
+
kinds = [k for k in kinds if k is not T.HBOND]
|
|
1556
|
+
legend.extend(link_legend(kinds, styles))
|
|
1557
|
+
if d.whole:
|
|
1558
|
+
legend.append(LegendEntry(T.HYDROPHOBIC.label, "link", kind=T.HYDROPHOBIC, style=styles[T.HYDROPHOBIC]))
|
|
1559
|
+
if d.lashes:
|
|
1560
|
+
legend.append(LegendEntry(T.HYDROPHOBIC.label, "eyelash"))
|
|
1561
|
+
if ctx.options.charge_key:
|
|
1562
|
+
legend.extend(charge_legend({key[1] for key in d.halo_done}, styles))
|
|
1563
|
+
if settings.exposure and ctx.exposure is not None and any(e >= EXPOSED_FROM for e in ctx.exposure):
|
|
1564
|
+
legend.append(LegendEntry("Solvent exposure", "halo", token="exposure"))
|
|
1565
|
+
legend.extend(lining_legend(faces, "Lining:" if ctx.dep.pairwise else "Pocket lining:"))
|
|
1566
|
+
if d.beyond:
|
|
1567
|
+
legend.append(LegendEntry("† outside the supplied contact set"))
|
|
1568
|
+
legend.extend(predicted_legend(d.predicted, styles, ctx.options.solvent_mark))
|
|
1569
|
+
legend.extend(confidence_legend(d.levels))
|
|
1570
|
+
legend.extend(pae_legend(d.glows))
|
|
1571
|
+
legend.extend(occupancy_legend(ctx.ensemble, d.occupancy, ctx.options.occupancy_style == "steps"))
|
|
1572
|
+
legend.extend(absent_legend(d.absent))
|
|
1573
|
+
if d.lost:
|
|
1574
|
+
words = other_protein.legend_text(ctx.options)
|
|
1575
|
+
legend.append(LegendEntry(words, "weight", opacity=ABSENT_OPACITY)
|
|
1576
|
+
if ctx.options.absent_style == "faint" else LegendEntry(words, "marker"))
|
|
1577
|
+
return StyleDrawing(d.layers, legend, d.notes, d.has_distances, d.levels, d.occupancy, d.predicted, d.tags,
|
|
1578
|
+
d.atoms_at_level, atoms_by_own=d.atoms_by_own, glows=d.glows)
|
|
1579
|
+
|
|
1580
|
+
|
|
1581
|
+
# ---------------------------------------------------------------------------
|
|
1582
|
+
# Behind the ligand: solvent exposure and the lining of the pocket
|
|
1583
|
+
# ---------------------------------------------------------------------------
|
|
1584
|
+
|
|
1585
|
+
#: An atom of the ligand that is open to solvent by this share or more has a halo.
|
|
1586
|
+
EXPOSED_FROM = 0.25
|
|
1587
|
+
|
|
1588
|
+
|
|
1589
|
+
def exposure_items(ctx: Context) -> list[Item]:
|
|
1590
|
+
"""Grey halos behind ligand atoms that are open to solvent."""
|
|
1591
|
+
if ctx.exposure is None:
|
|
1592
|
+
return []
|
|
1593
|
+
out: list[Item] = []
|
|
1594
|
+
bl = ctx.metrics.bond_length
|
|
1595
|
+
for i, e in enumerate(ctx.exposure[: ctx.dep.n_heavy]):
|
|
1596
|
+
if e < EXPOSED_FROM or (ctx.dep.units and ctx.dep.home_of(i) is not None):
|
|
1597
|
+
continue
|
|
1598
|
+
x, y = ctx.dep.pos(i)
|
|
1599
|
+
out.append(Circle(x, y, (0.30 + 0.30 * min(1.0, float(e))) * bl, Paint(fill="exposure", opacity=0.55)))
|
|
1600
|
+
for res in ctx.dep.units:
|
|
1601
|
+
# A residue of a chain ligand: one halo behind its box, as wide as its atoms are exposed on average.
|
|
1602
|
+
values = [float(ctx.exposure[a]) for a in res.atoms if a < len(ctx.exposure)]
|
|
1603
|
+
e = sum(values) / len(values) if values else 0.0
|
|
1604
|
+
if e < EXPOSED_FROM:
|
|
1605
|
+
continue
|
|
1606
|
+
pad = (0.08 + 0.12 * min(1.0, e)) * bl
|
|
1607
|
+
x0, y0, x1, y1 = res.box
|
|
1608
|
+
out.append(Rect(x0 - pad, y0 - pad, x1 - x0 + 2.0 * pad, y1 - y0 + 2.0 * pad,
|
|
1609
|
+
Paint(fill="exposure", opacity=0.55), rx=5.0 + pad))
|
|
1610
|
+
return out
|
|
1611
|
+
|
|
1612
|
+
|
|
1613
|
+
#: How far from the ligand's ink the lining runs, and how far along it a contact's stretch reaches to either
|
|
1614
|
+
#: side (in bond lengths); how near the middles of two stretches of different colours may be; and its line.
|
|
1615
|
+
LINING_OFF, LINING_HALF, LINING_APART = 0.62, 0.7, 0.5
|
|
1616
|
+
LINING_WIDTH, LINING_OPACITY = 4.4, 0.62
|
|
1617
|
+
_LINING_STEP = 3.0
|
|
1618
|
+
|
|
1619
|
+
|
|
1620
|
+
@dataclass(frozen=True)
|
|
1621
|
+
class LiningClaim:
|
|
1622
|
+
"""One contact's stretch of the lining: from where (the ligand's end) to where (the residue's) it lies,
|
|
1623
|
+
the colour of what makes it, and who makes it."""
|
|
1624
|
+
|
|
1625
|
+
point: Point
|
|
1626
|
+
toward: Point
|
|
1627
|
+
token: str
|
|
1628
|
+
residue: str
|
|
1629
|
+
label: str
|
|
1630
|
+
|
|
1631
|
+
|
|
1632
|
+
def contact_face(r: ResolvedInteraction) -> str:
|
|
1633
|
+
"""What part of the residue makes a contact, as a class of surface: ``hydrophobic`` (a carbon, the face of
|
|
1634
|
+
a ring), ``polar`` (a nitrogen, oxygen or sulphur), ``positive`` or ``negative`` (a charged group),
|
|
1635
|
+
``metal`` or ``water``; the class of the residue where the record does not say which part."""
|
|
1636
|
+
name, site = r.record.residue_name, r.protein
|
|
1637
|
+
cls = residue_class(name)
|
|
1638
|
+
if cls in ("metal", "water"):
|
|
1639
|
+
return cls
|
|
1640
|
+
if r.type is T.HYDROPHOBIC or site.kind == "ring":
|
|
1641
|
+
return "hydrophobic"
|
|
1642
|
+
signs = {sign for sign, _ in charged_groups(name)}
|
|
1643
|
+
if site.kind == "group" or r.type is T.SALTBRIDGE:
|
|
1644
|
+
sign = site.charge or (signs.pop() if len(signs) == 1 else 0)
|
|
1645
|
+
return "positive" if sign > 0 else "negative" if sign < 0 else cls
|
|
1646
|
+
if site.kind == "atom" and site.atoms:
|
|
1647
|
+
atom = site.atoms[0]
|
|
1648
|
+
element = atom.lstrip("0123456789")[:1].upper()
|
|
1649
|
+
if element == "C":
|
|
1650
|
+
return "hydrophobic"
|
|
1651
|
+
if cls in ("positive", "negative") and not is_backbone_atom(name, atom):
|
|
1652
|
+
return cls
|
|
1653
|
+
if is_nucleotide(name) and atom.upper() in ("OP1", "OP2", "O1P", "O2P"):
|
|
1654
|
+
return "negative"
|
|
1655
|
+
return "polar"
|
|
1656
|
+
return cls
|
|
1657
|
+
|
|
1658
|
+
|
|
1659
|
+
def lining_claims(ctx: Context, grp: "ResidueGroup", look: Look, infos: "Sequence[PortInfo]",
|
|
1660
|
+
ends: Sequence[Point]) -> list[LiningClaim]:
|
|
1661
|
+
"""The stretches of the lining that a residue's contacts ask for (``ends``: where each leaves it)."""
|
|
1662
|
+
out: list[LiningClaim] = []
|
|
1663
|
+
for info, end in zip(infos, ends):
|
|
1664
|
+
if info.predicted or info.absent or info.faint or info.kind is T.COVALENT:
|
|
1665
|
+
continue # a guess, a contact that is not there or is set back, and a bond, which is no wall
|
|
1666
|
+
for face in dict.fromkeys(contact_face(r) for r in info.interactions):
|
|
1667
|
+
token = ctx.fill_of(look, f"class_{face}")
|
|
1668
|
+
out.append(LiningClaim(info.target.point, end, token, grp.ident, grp.label))
|
|
1669
|
+
return out
|
|
1670
|
+
|
|
1671
|
+
|
|
1672
|
+
def _outline(ctx: Context) -> list[np.ndarray]:
|
|
1673
|
+
"""The outline of the ligand that the lining runs along: closed curves, smooth, in even steps."""
|
|
1674
|
+
assert ctx.field is not None
|
|
1675
|
+
loops = ctx.field.contours(LINING_OFF * ctx.metrics.bond_length)
|
|
1676
|
+
if not loops:
|
|
1677
|
+
return []
|
|
1678
|
+
sign = polygon_area(loops[0]) >= 0
|
|
1679
|
+
out = []
|
|
1680
|
+
for loop in loops:
|
|
1681
|
+
if (polygon_area(loop) >= 0) != sign or len(loop) < 12:
|
|
1682
|
+
continue # holes (the inside of a macrocycle) carry none
|
|
1683
|
+
pts = resample_closed(loop, _LINING_STEP)
|
|
1684
|
+
for _ in range(3): # take the staircase out of the grid contour
|
|
1685
|
+
pts = (np.roll(pts, 1, axis=0) + pts + np.roll(pts, -1, axis=0)) / 3.0
|
|
1686
|
+
out.append(pts)
|
|
1687
|
+
return out
|
|
1688
|
+
|
|
1689
|
+
|
|
1690
|
+
def _leaves_at(loops: Sequence[np.ndarray], a: Point, b: Point) -> tuple[int, float]:
|
|
1691
|
+
"""Where the line from ``a`` (in the ligand) to ``b`` leaves the outline: which curve, and where on it.
|
|
1692
|
+
The first crossing from ``a``; where it crosses none, the place of the outline nearest to the line."""
|
|
1693
|
+
A, d = np.array(a, dtype=float), np.array(b, dtype=float) - np.array(a, dtype=float)
|
|
1694
|
+
best: tuple[float, int, float] | None = None
|
|
1695
|
+
for k, pts in enumerate(loops):
|
|
1696
|
+
e = np.roll(pts, -1, axis=0) - pts
|
|
1697
|
+
den = d[0] * e[:, 1] - d[1] * e[:, 0]
|
|
1698
|
+
ok = np.abs(den) > 1e-9
|
|
1699
|
+
w = pts - A
|
|
1700
|
+
safe = np.where(ok, den, 1.0)
|
|
1701
|
+
t = (w[:, 0] * e[:, 1] - w[:, 1] * e[:, 0]) / safe
|
|
1702
|
+
u = (w[:, 0] * d[1] - w[:, 1] * d[0]) / safe
|
|
1703
|
+
hit = np.nonzero(ok & (t >= 0.0) & (t <= 1.0) & (u >= 0.0) & (u < 1.0))[0]
|
|
1704
|
+
if len(hit):
|
|
1705
|
+
i = int(hit[np.argmin(t[hit])])
|
|
1706
|
+
found = (float(t[i]), k, i + float(u[i]))
|
|
1707
|
+
if best is None or found < best:
|
|
1708
|
+
best = found
|
|
1709
|
+
if best is not None:
|
|
1710
|
+
return best[1], best[2]
|
|
1711
|
+
near: tuple[float, float, int, int] | None = None
|
|
1712
|
+
for k, pts in enumerate(loops):
|
|
1713
|
+
w = pts - A
|
|
1714
|
+
along = np.clip((w @ d) / max(float(d @ d), 1e-9), 0.0, 1.0)
|
|
1715
|
+
off = np.linalg.norm(w - along[:, None] * d, axis=1)
|
|
1716
|
+
i = int(np.argmin(np.round(off, 6) + 1e-7 * np.linalg.norm(w, axis=1)))
|
|
1717
|
+
cand = (round(float(off[i]), 6), float(np.linalg.norm(w[i])), k, i)
|
|
1718
|
+
if near is None or cand < near:
|
|
1719
|
+
near = cand
|
|
1720
|
+
assert near is not None
|
|
1721
|
+
return near[2], float(near[3])
|
|
1722
|
+
|
|
1723
|
+
|
|
1724
|
+
def lining_items(ctx: Context, claims: Sequence[LiningClaim]) -> tuple[list[Item], set[str]]:
|
|
1725
|
+
"""The lining of the pocket from the contacts (docs/reference.md): a stretch of the ligand's outline for each,
|
|
1726
|
+
where the line to the residue crosses it, in the colour of what makes it. Returns the items, and the
|
|
1727
|
+
colours that are drawn."""
|
|
1728
|
+
if ctx.field is None or not claims or ctx.dep.arranged == "plane":
|
|
1729
|
+
return [], set() # boxes where residues lie have no outline: there is no pocket round them
|
|
1730
|
+
loops = _outline(ctx)
|
|
1731
|
+
if not loops:
|
|
1732
|
+
return [], set()
|
|
1733
|
+
bl = ctx.metrics.bond_length
|
|
1734
|
+
half, apart = LINING_HALF * bl, LINING_APART * bl
|
|
1735
|
+
at: dict[int, list[tuple[float, LiningClaim]]] = {}
|
|
1736
|
+
for claim in claims:
|
|
1737
|
+
k, where = _leaves_at(loops, claim.point, claim.toward)
|
|
1738
|
+
at.setdefault(k, []).append((where, claim))
|
|
1739
|
+
out: list[Item] = []
|
|
1740
|
+
drawn: set[str] = set()
|
|
1741
|
+
for loop in sorted(at):
|
|
1742
|
+
pts = loops[loop]
|
|
1743
|
+
n = len(pts)
|
|
1744
|
+
step = float(np.linalg.norm(np.roll(pts, -1, axis=0) - pts, axis=1).sum()) / n
|
|
1745
|
+
places = sorted(at[loop], key=lambda c: (c[0], c[1].residue, c[1].token))
|
|
1746
|
+
mids = np.array([c[0] for c in places])
|
|
1747
|
+
for _ in range(4): # two colours in one place: moved apart, so that each is seen
|
|
1748
|
+
for i in range(len(places) if len(places) > 2 else len(places) - 1):
|
|
1749
|
+
j = (i + 1) % len(places)
|
|
1750
|
+
if places[i][1].token == places[j][1].token:
|
|
1751
|
+
continue
|
|
1752
|
+
gap = float(mids[j] - mids[i]) + (n if j < i else 0.0)
|
|
1753
|
+
short = apart / step - gap
|
|
1754
|
+
if short > 0.0:
|
|
1755
|
+
mids[i] -= short / 2.0
|
|
1756
|
+
mids[j] += short / 2.0
|
|
1757
|
+
steps = np.arange(n)[:, None]
|
|
1758
|
+
off = np.abs(steps - mids[None, :]) % n
|
|
1759
|
+
off = np.minimum(off, n - off) * step
|
|
1760
|
+
nearest = np.argmin(off, axis=1)
|
|
1761
|
+
held = off[np.arange(n), nearest] <= half
|
|
1762
|
+
label = [places[j][1].token if h else "" for j, h in zip(nearest, held)]
|
|
1763
|
+
start = next((i for i in range(n) if label[i] != label[i - 1]), 0)
|
|
1764
|
+
i = 0
|
|
1765
|
+
while i < n:
|
|
1766
|
+
token = label[(start + i) % n]
|
|
1767
|
+
run = [(start + i) % n]
|
|
1768
|
+
i += 1
|
|
1769
|
+
while i < n and label[(start + i) % n] == token:
|
|
1770
|
+
run.append((start + i) % n)
|
|
1771
|
+
i += 1
|
|
1772
|
+
if not token or len(run) < 2:
|
|
1773
|
+
continue
|
|
1774
|
+
whose = list(dict.fromkeys(places[nearest[q]][1] for q in run))
|
|
1775
|
+
if len(run) == n:
|
|
1776
|
+
run.append(run[0]) # one colour all the way round: close the curve
|
|
1777
|
+
drawn.add(token)
|
|
1778
|
+
face = token.removeprefix("class_")
|
|
1779
|
+
names = list(dict.fromkeys(c.label for c in whose))
|
|
1780
|
+
g = Group("lining", data={"surface": face,
|
|
1781
|
+
"residues": " ".join(dict.fromkeys(c.residue for c in whose))},
|
|
1782
|
+
title=("Lining" + (f", {_LINING_LABEL.get(face, face)}" if token.startswith("class_") else "")
|
|
1783
|
+
+ ": " + ", ".join(names)))
|
|
1784
|
+
g.add(Polyline(tuple((float(pts[q, 0]), float(pts[q, 1])) for q in run),
|
|
1785
|
+
Paint(stroke=token, width=LINING_WIDTH, opacity=LINING_OPACITY, cap="round")))
|
|
1786
|
+
out.append(g)
|
|
1787
|
+
return out, drawn
|
|
1788
|
+
|
|
1789
|
+
|
|
1790
|
+
_LINING_LABEL = {"hydrophobic": "hydrophobic", "polar": "polar", "positive": "charged (+)",
|
|
1791
|
+
"negative": "charged (−)", "metal": "metal", "water": "water", "nucleotide": "nucleotide",
|
|
1792
|
+
"glycine": "glycine", "other": "other"}
|
|
1793
|
+
|
|
1794
|
+
|
|
1795
|
+
def lining_legend(faces: "set[str]", heading: str = "Pocket lining:") -> list[LegendEntry]:
|
|
1796
|
+
"""The key of the lining: what each colour that is drawn says of the part of the pocket that is there.
|
|
1797
|
+
(Where the figure colours by pLDDT the lining does too, and that key is the figure's.)"""
|
|
1798
|
+
named = [c for c in _CLASS_ORDER if f"class_{c}" in faces]
|
|
1799
|
+
if not named:
|
|
1800
|
+
return []
|
|
1801
|
+
return [LegendEntry(heading)] + [LegendEntry(_LINING_LABEL[c], "lining", token=f"class_{c}")
|
|
1802
|
+
for c in named]
|
|
1803
|
+
|
|
1804
|
+
|
|
1805
|
+
def ribbon_items(ctx: Context, placed: Sequence[tuple[Point, float, str]]) -> list[Item]:
|
|
1806
|
+
"""The lining that follows the nearest residue (``lining="nearest"``): each stretch in the colour of the
|
|
1807
|
+
residue nearest to it (``placed`` holds that colour as its token) and left open where none is near."""
|
|
1808
|
+
if ctx.field is None or not placed:
|
|
1809
|
+
return []
|
|
1810
|
+
if ctx.dep.arranged == "plane":
|
|
1811
|
+
return [] # boxes where residues lie have no outline: there is no pocket round them
|
|
1812
|
+
m = ctx.metrics
|
|
1813
|
+
centres = np.array([p[0] for p in placed], dtype=float)
|
|
1814
|
+
radii = np.array([p[1] for p in placed], dtype=float)
|
|
1815
|
+
out: list[Item] = []
|
|
1816
|
+
for pts in _outline(ctx):
|
|
1817
|
+
d = np.linalg.norm(pts[:, None, :] - centres[None, :, :], axis=2) - radii[None, :]
|
|
1818
|
+
nearest = np.argmin(d, axis=1)
|
|
1819
|
+
near = d[np.arange(len(pts)), nearest] <= 1.25 * m.bond_length
|
|
1820
|
+
label = np.where(near, nearest, -1)
|
|
1821
|
+
cls = [placed[j][2] if j >= 0 else "" for j in label]
|
|
1822
|
+
cls = _despeckle(cls, 5)
|
|
1823
|
+
n = len(pts)
|
|
1824
|
+
# Walk the closed loop in runs of equal class, starting at a class boundary.
|
|
1825
|
+
start = next((k for k in range(n) if cls[k] != cls[k - 1]), 0)
|
|
1826
|
+
k = 0
|
|
1827
|
+
while k < n:
|
|
1828
|
+
i0 = (start + k) % n
|
|
1829
|
+
c = cls[i0]
|
|
1830
|
+
run = [i0]
|
|
1831
|
+
k += 1
|
|
1832
|
+
while k < n and cls[(start + k) % n] == c:
|
|
1833
|
+
run.append((start + k) % n)
|
|
1834
|
+
k += 1
|
|
1835
|
+
if not c or len(run) < 2:
|
|
1836
|
+
continue
|
|
1837
|
+
if len(run) == n:
|
|
1838
|
+
run.append(run[0]) # one class all the way round: close the loop
|
|
1839
|
+
out.append(Polyline(tuple((float(pts[i, 0]), float(pts[i, 1])) for i in run),
|
|
1840
|
+
Paint(stroke=c, width=LINING_WIDTH, opacity=LINING_OPACITY, cap="round")))
|
|
1841
|
+
return out
|
|
1842
|
+
|
|
1843
|
+
|
|
1844
|
+
def _despeckle(values: list[str], min_run: int) -> list[str]:
|
|
1845
|
+
"""Absorb runs shorter than ``min_run`` (on a closed loop) into the preceding run."""
|
|
1846
|
+
n = len(values)
|
|
1847
|
+
if n == 0:
|
|
1848
|
+
return values
|
|
1849
|
+
out = list(values)
|
|
1850
|
+
for _ in range(2):
|
|
1851
|
+
start = next((k for k in range(n) if out[k] != out[k - 1]), None)
|
|
1852
|
+
if start is None:
|
|
1853
|
+
return out
|
|
1854
|
+
k = 0
|
|
1855
|
+
while k < n:
|
|
1856
|
+
i0 = (start + k) % n
|
|
1857
|
+
j = k
|
|
1858
|
+
while j < n and out[(start + j) % n] == out[i0]:
|
|
1859
|
+
j += 1
|
|
1860
|
+
if j - k < min_run:
|
|
1861
|
+
prev = out[(i0 - 1) % n]
|
|
1862
|
+
for t in range(k, j):
|
|
1863
|
+
out[(start + t) % n] = prev
|
|
1864
|
+
k = j
|
|
1865
|
+
return out
|
|
1866
|
+
|
|
1867
|
+
|
|
1868
|
+
_LEGEND_ORDER = [T.COVALENT, T.HBOND, T.SALTBRIDGE, T.PI_STACKING, T.PI_CATION, T.HALOGEN, T.METAL, T.WATER_BRIDGE]
|
|
1869
|
+
|
|
1870
|
+
|
|
1871
|
+
def link_legend(kinds: Sequence[InteractionType], styles: "Mapping[InteractionType, LinkStyle]"
|
|
1872
|
+
) -> list[LegendEntry]:
|
|
1873
|
+
return [LegendEntry(k.label, "link", kind=k, style=styles[k], arrow=k is T.HBOND)
|
|
1874
|
+
for k in _LEGEND_ORDER if k in kinds]
|
|
1875
|
+
|
|
1876
|
+
|
|
1877
|
+
def charge_legend(shaded: "set[str]", styles: "Mapping[InteractionType, LinkStyle]") -> list[LegendEntry]:
|
|
1878
|
+
"""The key of the shading of a charged group (``charge_halos``): one entry for each kind of contact
|
|
1879
|
+
whose colour shades a group in the figure (``shaded``: the tokens drawn), named by the kind where
|
|
1880
|
+
there are two."""
|
|
1881
|
+
kinds = [k for k in (T.SALTBRIDGE, T.PI_CATION) if k in styles and styles[k].token in shaded]
|
|
1882
|
+
return [LegendEntry("Charged group" if len(kinds) == 1 else f"Charged group ({k.label.lower()})", "halo",
|
|
1883
|
+
token=styles[k].token) for k in kinds]
|
|
1884
|
+
|
|
1885
|
+
|
|
1886
|
+
def confidence_legend(levels: "set[int]") -> list[LegendEntry]:
|
|
1887
|
+
"""Legend samples for the confidence bands, when anything is drawn below full strength."""
|
|
1888
|
+
if not any(lv > 0 for lv in levels):
|
|
1889
|
+
return []
|
|
1890
|
+
out = [LegendEntry("Confidence:")]
|
|
1891
|
+
for band, text in (("confident", "pLDDT \u2265 70"), ("low", "50\u201370"), ("very_low", "< 50")):
|
|
1892
|
+
look = LOOKS[band]
|
|
1893
|
+
out.append(LegendEntry(text, "weight", weight=look.width, opacity=look.opacity,
|
|
1894
|
+
mark=MARK if look.mark else ""))
|
|
1895
|
+
return out
|
|
1896
|
+
|
|
1897
|
+
|
|
1898
|
+
def pae_legend(present: bool) -> list[LegendEntry]:
|
|
1899
|
+
"""The key of the glow of a contact's predicted aligned error: its four bands, all of them."""
|
|
1900
|
+
if not present:
|
|
1901
|
+
return []
|
|
1902
|
+
out = [LegendEntry("PAE of the contact:")]
|
|
1903
|
+
bounds = [least for _, least in PAE_BANDS]
|
|
1904
|
+
for k, (band, least) in enumerate(PAE_BANDS):
|
|
1905
|
+
text = (f"< {bounds[1]:g} \u00c5" if k == 0 else f"\u2265 {least:g} \u00c5" if k == len(PAE_BANDS) - 1 else
|
|
1906
|
+
f"{least:g}\u2013{bounds[k + 1]:g} \u00c5")
|
|
1907
|
+
out.append(LegendEntry(text, "glow", token=f"plddt_{band}"))
|
|
1908
|
+
return out
|
|
1909
|
+
|
|
1910
|
+
|
|
1911
|
+
def plddt_legend() -> list[LegendEntry]:
|
|
1912
|
+
"""The key of a figure that colours by pLDDT: AlphaFold's four bands, all of them, so that the
|
|
1913
|
+
key is the same on every figure."""
|
|
1914
|
+
out = [LegendEntry("pLDDT:")]
|
|
1915
|
+
for band, text in (("very_high", "\u2265 90"), ("confident", "70\u201390"), ("low", "50\u201370"),
|
|
1916
|
+
("very_low", "< 50")):
|
|
1917
|
+
out.append(LegendEntry(text, "swatch", token=f"plddt_{band}", stroke="bubble_line"))
|
|
1918
|
+
return out
|
|
1919
|
+
|
|
1920
|
+
|
|
1921
|
+
def predicted_style(base: LinkStyle) -> LinkStyle:
|
|
1922
|
+
"""How a line through a predicted solvent site is drawn: fine round dots, in the water colour
|
|
1923
|
+
of the style. A different kind of line from an observed water bridge, not a paler one."""
|
|
1924
|
+
return LinkStyle(base.token, (0.01, 3.4), width=1.25, cap="round")
|
|
1925
|
+
|
|
1926
|
+
|
|
1927
|
+
def _predicted_box(a: Point, b: Point, label: str, label_at: float, metrics: Metrics
|
|
1928
|
+
) -> tuple[float, float, float, float]:
|
|
1929
|
+
mid = lerp(a, b, label_at)
|
|
1930
|
+
w = text_width(label, metrics.distance_font) + 9.0
|
|
1931
|
+
h = CAP_HEIGHT * metrics.distance_font + 7.0
|
|
1932
|
+
return mid[0] - w / 2.0, mid[1] - h / 2.0, w, h
|
|
1933
|
+
|
|
1934
|
+
|
|
1935
|
+
def predicted_items(a: Point, b: Point, info: "PortInfo", label_at: float, metrics: Metrics, style: LinkStyle,
|
|
1936
|
+
opacity: float, mark: str) -> list[Item]:
|
|
1937
|
+
"""The line through a predicted site, with its label set off as a node of its own, the way LigPlot sets a
|
|
1938
|
+
water between ligand and residue, and unlike anything an observed water gets: on a glow (``mark="glow"``), in a
|
|
1939
|
+
filled box with a heavy broken border (``"filled"``), or in a thin broken outline (``"outline"``)."""
|
|
1940
|
+
label = info.label or ""
|
|
1941
|
+
line = link_items(a, b, info.kind, metrics, label=info.label, opacity=opacity, label_at=label_at,
|
|
1942
|
+
weight=info.weight, style=style)
|
|
1943
|
+
x, y, w, h = _predicted_box(a, b, label, label_at, metrics)
|
|
1944
|
+
if mark == "outline":
|
|
1945
|
+
return line + [Rect(x, y, w, h, Paint(stroke=style.token, width=0.85, dash=(2.2, 1.7), opacity=opacity),
|
|
1946
|
+
rx=h / 2.0)]
|
|
1947
|
+
if mark == "glow":
|
|
1948
|
+
return water_glow(x, y, w, h, style.token, opacity) + line
|
|
1949
|
+
# The fill lies under the words, the border over the line.
|
|
1950
|
+
return [Rect(x, y, w, h, Paint(fill=style.token, opacity=0.24 * opacity), rx=h / 2.0)] + line + [
|
|
1951
|
+
Rect(x, y, w, h, Paint(stroke=style.token, width=1.9, dash=(4.0, 1.8), opacity=opacity), rx=h / 2.0)]
|
|
1952
|
+
|
|
1953
|
+
|
|
1954
|
+
#: The glow of a predicted water, from the outside in: how far each layer reaches beyond its words, and how strong
|
|
1955
|
+
#: it is. (Soft edges without a filter, which not every reader of an SVG has.)
|
|
1956
|
+
_WATER_GLOW = ((6.4, 0.07), (4.3, 0.09), (2.2, 0.12), (0.0, 0.16))
|
|
1957
|
+
|
|
1958
|
+
|
|
1959
|
+
def water_glow(x: float, y: float, w: float, h: float, token: str, opacity: float = 1.0) -> list[Item]:
|
|
1960
|
+
return [Rect(x - g, y - g, w + 2.0 * g, h + 2.0 * g, Paint(fill=token, opacity=o * opacity), rx=h / 2.0 + g)
|
|
1961
|
+
for g, o in _WATER_GLOW]
|
|
1962
|
+
|
|
1963
|
+
|
|
1964
|
+
def predicted_legend(present: bool, styles: "Mapping[InteractionType, LinkStyle]", mark: str
|
|
1965
|
+
) -> list[LegendEntry]:
|
|
1966
|
+
if not present:
|
|
1967
|
+
return []
|
|
1968
|
+
return [LegendEntry("Predicted water site (not observed)", {"outline": "link", "glow": "site-glow"}.get(mark, "site"),
|
|
1969
|
+
kind=T.WATER_BRIDGE, style=predicted_style(styles[T.WATER_BRIDGE]))]
|
|
1970
|
+
|
|
1971
|
+
|
|
1972
|
+
#: The most a contact is drawn at that the structure shown does not make.
|
|
1973
|
+
ABSENT_OPACITY = 0.45
|
|
1974
|
+
|
|
1975
|
+
|
|
1976
|
+
def is_distance(label: "str | None") -> bool:
|
|
1977
|
+
"""Is what stands on a line a distance (and not a share, the word of a water, a mark)?"""
|
|
1978
|
+
return label is not None and label[:1].isdigit() and "%" not in label
|
|
1979
|
+
|
|
1980
|
+
|
|
1981
|
+
def share_label(occupancy: "float | None", label: "str | None" = None) -> "str | None":
|
|
1982
|
+
"""What stands on the line of a contact that only other models make: the share of the models that
|
|
1983
|
+
make it, after whatever stood there already (the water of a water bridge)."""
|
|
1984
|
+
if occupancy is None:
|
|
1985
|
+
return label
|
|
1986
|
+
share = f"{100.0 * occupancy:.0f} %"
|
|
1987
|
+
return f"{label} {share}" if label else share
|
|
1988
|
+
|
|
1989
|
+
|
|
1990
|
+
def absent_legend(present: bool) -> list[LegendEntry]:
|
|
1991
|
+
"""The key of a contact that other models of the ensemble make and the one shown does not."""
|
|
1992
|
+
if not present:
|
|
1993
|
+
return []
|
|
1994
|
+
return [LegendEntry("Faint, with a share: made by other models, not by the one shown", "weight",
|
|
1995
|
+
weight=occupancy_factors(0.5)[0], opacity=ABSENT_OPACITY)]
|
|
1996
|
+
|
|
1997
|
+
|
|
1998
|
+
def occupancy_legend(ensemble: str | None, present: bool, steps: bool) -> list[LegendEntry]:
|
|
1999
|
+
"""Legend samples for occupancy, naming the ensemble it is a share of: its three steps, where it is drawn
|
|
2000
|
+
in steps (and then the share is written on the line, as the heading says), else three shares."""
|
|
2001
|
+
if not present:
|
|
2002
|
+
return []
|
|
2003
|
+
of = ensemble or "the ensemble"
|
|
2004
|
+
if steps:
|
|
2005
|
+
out = [LegendEntry(f"Occupancy (share of {of}, written on the line):")]
|
|
2006
|
+
bounds = [least for least, _, _ in OCCUPANCY_STEPS]
|
|
2007
|
+
names = [f"{100 * bounds[0]:.0f}\u2013100 %"] + [f"{100 * lo:.0f}\u2013{100 * hi:.0f} %" for lo, hi in
|
|
2008
|
+
zip(bounds[1:-1], bounds[:-2])] + [f"< {100 * bounds[-2]:.0f} %"]
|
|
2009
|
+
for name, (_, width, opacity) in zip(names, OCCUPANCY_STEPS):
|
|
2010
|
+
out.append(LegendEntry(name, "weight", weight=width, opacity=opacity))
|
|
2011
|
+
return out
|
|
2012
|
+
out = [LegendEntry(f"Occupancy (share of {of}):")]
|
|
2013
|
+
for value in OCCUPANCY_SAMPLES:
|
|
2014
|
+
width, opacity = occupancy_factors(value)
|
|
2015
|
+
out.append(LegendEntry(f"{100.0 * value:.0f} %", "weight", weight=width, opacity=opacity))
|
|
2016
|
+
return out
|
|
2017
|
+
|
|
2018
|
+
|
|
2019
|
+
#: Between two samples of one key (a plain tag and a bold one).
|
|
2020
|
+
_KEY_GAP = 6.0
|
|
2021
|
+
|
|
2022
|
+
|
|
2023
|
+
def legend_group(entries: Sequence[LegendEntry], metrics: Metrics, max_width: float) -> tuple[Group, float, float]:
|
|
2024
|
+
"""A wrapped row of legend entries. Returns ``(group, width, height)`` with the
|
|
2025
|
+
group's origin at its top-left corner."""
|
|
2026
|
+
g = Group("legend")
|
|
2027
|
+
font = metrics.legend_font
|
|
2028
|
+
spacing = 18.0
|
|
2029
|
+
line_h = font * 1.75
|
|
2030
|
+
x, y = 0.0, 0.0
|
|
2031
|
+
widest = 0.0
|
|
2032
|
+
|
|
2033
|
+
def size(e: LegendEntry) -> tuple[float, float, float]:
|
|
2034
|
+
"""The width of an entry's sample, of the gap after it, and of the whole entry."""
|
|
2035
|
+
sample = {"link": 26.0, "eyelash": 26.0, "swatch": 11.0, "halo": 13.0, "weight": 26.0,
|
|
2036
|
+
"node": 13.0, "unit": 22.0, "lining": 18.0, "glow": 20.0, "site": 38.0, "site-glow": 38.0,
|
|
2037
|
+
"ring": 15.0, "marker": 26.0}.get(e.sample, 0.0)
|
|
2038
|
+
if e.sample == "tag":
|
|
2039
|
+
# Words that are written in the figure, shown as they are written there: plain, bold, or one of each.
|
|
2040
|
+
sample = sum(text_width(words, metrics.distance_font, bold=bold) for words, bold in e.marks) \
|
|
2041
|
+
+ _KEY_GAP * max(len(e.marks) - 1, 0)
|
|
2042
|
+
if e.sample == "scale":
|
|
2043
|
+
sample = e.length
|
|
2044
|
+
gap = 8.0 if e.sample in ("link", "eyelash", "weight", "scale", "site", "site-glow", "marker") else (5.0 if sample else 0.0)
|
|
2045
|
+
return sample, gap, sample + gap + text_width(e.label, font)
|
|
2046
|
+
|
|
2047
|
+
sizes = [size(e) for e in entries]
|
|
2048
|
+
for k, e in enumerate(entries):
|
|
2049
|
+
sample, gap, w = sizes[k]
|
|
2050
|
+
# A heading ("Confidence:") goes with the first entry after it: it is not left at the end of a row.
|
|
2051
|
+
heading = e.sample == "text" and e.label.endswith(":") and k + 1 < len(entries)
|
|
2052
|
+
need = w + (spacing + sizes[k + 1][2] if heading else 0.0)
|
|
2053
|
+
if x > 0 and x + need > max_width:
|
|
2054
|
+
x, y = 0.0, y + line_h
|
|
2055
|
+
cy = y + line_h / 2.0
|
|
2056
|
+
if e.sample == "eyelash":
|
|
2057
|
+
centre = (x + sample / 2.0, cy + 5.0)
|
|
2058
|
+
g.extend(eyelash_items(centre, 9.0, [(centre[0], centre[1] - 50.0)], metrics.with_(lash_length=4.0)))
|
|
2059
|
+
elif e.sample == "link" and e.kind is not None:
|
|
2060
|
+
a, b = (x, cy), (x + sample, cy)
|
|
2061
|
+
st = e.style or LINK_STYLES[e.kind]
|
|
2062
|
+
g.extend(link_items(a, b, e.kind, metrics, arrow="b" if e.arrow else None, style=st))
|
|
2063
|
+
if st.end_dots:
|
|
2064
|
+
g.add(Circle(b[0], b[1], 2.4, Paint(fill=st.token)))
|
|
2065
|
+
elif e.sample == "lining" and e.token:
|
|
2066
|
+
g.add(Line(x + 2.2, cy, x + sample - 2.2, cy,
|
|
2067
|
+
Paint(stroke=e.token, width=LINING_WIDTH, opacity=LINING_OPACITY, cap="round")))
|
|
2068
|
+
elif e.sample == "glow" and e.token:
|
|
2069
|
+
width = GLOW * metrics.interaction_width
|
|
2070
|
+
g.add(Line(x + width / 2.0, cy, x + sample - width / 2.0, cy,
|
|
2071
|
+
Paint(stroke=e.token, width=width, opacity=_GLOW_OPACITIES.get(e.token, GLOW_OPACITY),
|
|
2072
|
+
cap="round")))
|
|
2073
|
+
elif e.sample == "site-glow" and e.style is not None and e.kind is not None:
|
|
2074
|
+
# A predicted water: its glow on its line, as it stands in the figure.
|
|
2075
|
+
g.extend(water_glow(x + 13.0, cy - 2.6, sample - 26.0, 5.2, e.style.token))
|
|
2076
|
+
g.extend(link_items((x, cy), (x + sample, cy), e.kind, metrics, style=e.style))
|
|
2077
|
+
elif e.sample == "site" and e.style is not None and e.kind is not None:
|
|
2078
|
+
# A predicted water: its box on its line, as it stands in the figure.
|
|
2079
|
+
box = (x + 11.0, cy - 5.0, sample - 22.0, 10.0)
|
|
2080
|
+
g.add(Rect(*box, Paint(fill=e.style.token, opacity=0.24), rx=5.0))
|
|
2081
|
+
g.extend(link_items((x, cy), (x + 11.0, cy), e.kind, metrics, style=e.style))
|
|
2082
|
+
g.extend(link_items((x + sample - 11.0, cy), (x + sample, cy), e.kind, metrics, style=e.style))
|
|
2083
|
+
g.add(Rect(*box, Paint(stroke=e.style.token, width=1.9, dash=(4.0, 1.8)), rx=5.0))
|
|
2084
|
+
elif e.sample == "weight":
|
|
2085
|
+
paint = Paint(stroke="text", width=metrics.interaction_width * 1.3 * e.weight, opacity=e.opacity,
|
|
2086
|
+
cap="butt")
|
|
2087
|
+
if e.mark:
|
|
2088
|
+
mid = x + sample / 2.0
|
|
2089
|
+
mw = text_width(e.mark, metrics.distance_font) / 2.0 + 2.0
|
|
2090
|
+
g.add(Line(x, cy, mid - mw, cy, paint), Line(mid + mw, cy, x + sample, cy, paint))
|
|
2091
|
+
g.add(Text.plain(mid, cy + CAP_HEIGHT * metrics.distance_font / 2.0, e.mark, metrics.distance_font,
|
|
2092
|
+
"text", opacity=e.opacity))
|
|
2093
|
+
else:
|
|
2094
|
+
g.add(Line(x, cy, x + sample, cy, paint))
|
|
2095
|
+
elif e.sample == "marker":
|
|
2096
|
+
g.add(Group("", [other_protein.stroke([(x + 4.0, cy), (x + sample - 4.0, cy)], metrics.interaction_width)],
|
|
2097
|
+
opacity=other_protein.OPACITY))
|
|
2098
|
+
g.add(Line(x, cy, x + sample, cy, Paint(stroke="text", width=metrics.interaction_width, dash=(4.2, 2.6),
|
|
2099
|
+
cap="butt")))
|
|
2100
|
+
elif e.sample == "node":
|
|
2101
|
+
g.add(Circle(x + sample / 2.0, cy, sample / 2.0 - e.weight / 2.0,
|
|
2102
|
+
Paint(fill=e.token, stroke=e.stroke or "bubble_line", width=e.weight, dash=e.dash,
|
|
2103
|
+
opacity=e.opacity)))
|
|
2104
|
+
elif e.sample == "ring":
|
|
2105
|
+
g.extend(ring_sample(x + sample / 2.0, cy, sample / 2.0))
|
|
2106
|
+
elif e.sample == "unit":
|
|
2107
|
+
g.add(Rect(x + 0.6, cy - 5.5, sample - 1.2, 11.0, Paint(fill="background", stroke="ligand_bond", width=1.15),
|
|
2108
|
+
rx=3.5))
|
|
2109
|
+
elif e.sample == "swatch" and e.token:
|
|
2110
|
+
g.add(Circle(x + sample / 2.0, cy, sample / 2.0,
|
|
2111
|
+
Paint(fill=e.token, stroke=e.stroke, width=0.8) if e.stroke else Paint(fill=e.token)))
|
|
2112
|
+
elif e.sample == "halo" and e.token:
|
|
2113
|
+
g.add(Circle(x + sample / 2.0, cy, sample / 2.0, Paint(fill=e.token, opacity=0.6)))
|
|
2114
|
+
elif e.sample == "tag":
|
|
2115
|
+
at = x
|
|
2116
|
+
for words, bold in e.marks:
|
|
2117
|
+
g.add(Text.plain(at, cy + CAP_HEIGHT * metrics.distance_font / 2.0, words, metrics.distance_font,
|
|
2118
|
+
"text", anchor="start", bold=bold))
|
|
2119
|
+
at += text_width(words, metrics.distance_font, bold=bold) + _KEY_GAP
|
|
2120
|
+
elif e.sample == "scale":
|
|
2121
|
+
# A scale bar: a length of the figure, with a tick at either end.
|
|
2122
|
+
paint = Paint(stroke="text_muted", width=1.1, cap="butt")
|
|
2123
|
+
g.add(Line(x, cy, x + sample, cy, paint), Line(x, cy - 3.5, x, cy + 3.5, paint),
|
|
2124
|
+
Line(x + sample, cy - 3.5, x + sample, cy + 3.5, paint))
|
|
2125
|
+
g.add(Text.plain(x + sample + gap, cy + CAP_HEIGHT * font / 2.0, e.label, font, "text_muted", anchor="start"))
|
|
2126
|
+
x += w + spacing
|
|
2127
|
+
widest = max(widest, x - spacing)
|
|
2128
|
+
return g, widest, (y + line_h if entries else 0.0)
|