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/ions.py
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
"""An ion between a ligand and its target, drawn as the bridge it is.
|
|
2
|
+
|
|
3
|
+
A zinc that a sulphonamide binds and three histidines hold, a magnesium between two phosphates and an aspartate: a
|
|
4
|
+
table of contacts has the ion's contact with the ligand and nothing of what holds it, and a figure of that table
|
|
5
|
+
shows an ion in the air. ``Diagram.from_structure(ions=True)`` takes an ion that the model has and that touches both
|
|
6
|
+
(:func:`bridges`) into the drawing of the ligand, on the atoms of it that hold it, and gives each residue that holds
|
|
7
|
+
it a contact with it, with its length. A hydrogen bond of the table between two atoms that hold the same ion is not
|
|
8
|
+
one (they are 3 Å apart because the ion is between them) and is left out, and so is one of a histidine's nitrogen
|
|
9
|
+
that holds an ion, be it one between the two or a metal of the ligand itself (a heme's iron): it has neither a
|
|
10
|
+
hydrogen nor a lone pair left.
|
|
11
|
+
|
|
12
|
+
Where the model has no ion, none is made up. Off unless it is asked for.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
from dataclasses import dataclass, replace
|
|
18
|
+
from typing import Sequence
|
|
19
|
+
|
|
20
|
+
import numpy as np
|
|
21
|
+
from rdkit import Chem
|
|
22
|
+
|
|
23
|
+
from .chem import is_metal
|
|
24
|
+
from .exposure import WATER_NAMES
|
|
25
|
+
from .interactions import Interaction, InteractionType
|
|
26
|
+
from .ligand import Ligand
|
|
27
|
+
from .structure import Atom, ResidueKey, Structure
|
|
28
|
+
|
|
29
|
+
__all__ = ["IonBridge", "bridges", "holders", "with_ions", "REACH"]
|
|
30
|
+
|
|
31
|
+
T = InteractionType
|
|
32
|
+
#: How far a donor is from an ion that it holds, at most, in ångström.
|
|
33
|
+
REACH = {"Mg": 2.6, "Mn": 2.7, "Zn": 2.7, "Fe": 2.7, "Co": 2.7, "Ni": 2.7, "Cu": 2.7, "Ca": 2.9, "Na": 2.9, "K": 3.3,
|
|
34
|
+
"Cd": 2.8}
|
|
35
|
+
_REACH = 2.8
|
|
36
|
+
#: The charge of an ion by the name its file gives it (in capitals), and by its element: the alkali metals, silver,
|
|
37
|
+
#: thallium and gold have one, aluminium and its group, chromium and the rare earths three. Any other metal has two.
|
|
38
|
+
_CHARGE = {"FE": 3, "FE2": 2, "CU1": 1, "MN3": 3, "3CO": 3, "AU3": 3, "EU": 2, "YB2": 2,
|
|
39
|
+
"Li": 1, "Na": 1, "K": 1, "Rb": 1, "Cs": 1, "Ag": 1, "Tl": 1, "Au": 1,
|
|
40
|
+
"Al": 3, "Ga": 3, "In": 3, "Bi": 3, "Cr": 3, "Sc": 3, "Y": 3, "La": 3, "Ce": 3, "Pr": 3, "Nd": 3, "Sm": 3,
|
|
41
|
+
"Eu": 3, "Gd": 3, "Tb": 3, "Dy": 3, "Ho": 3, "Er": 3, "Tm": 3, "Yb": 3, "Lu": 3}
|
|
42
|
+
_DONORS = ("N", "O", "S")
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass(frozen=True)
|
|
46
|
+
class IonBridge:
|
|
47
|
+
"""An ion of the model, and what holds it."""
|
|
48
|
+
|
|
49
|
+
ion: Atom
|
|
50
|
+
#: Its name in the drawing of the ligand.
|
|
51
|
+
name: str
|
|
52
|
+
ligand: "tuple[tuple[str, float], ...]" # (atom name, distance), nearest first
|
|
53
|
+
protein: "tuple[tuple[Atom, float], ...]"
|
|
54
|
+
|
|
55
|
+
@property
|
|
56
|
+
def charge(self) -> int:
|
|
57
|
+
return _CHARGE.get(self.ion.resname.upper(), _CHARGE.get(self.ion.element, 2))
|
|
58
|
+
|
|
59
|
+
def records(self) -> list[Interaction]:
|
|
60
|
+
return [Interaction(type=T.METAL, residue_number=a.resnum, residue_name=a.resname, chain=a.chain,
|
|
61
|
+
insertion_code=a.icode, protein_atom=a.name, ligand_atom=self.name, distance=round(d, 2))
|
|
62
|
+
for a, d in self.protein]
|
|
63
|
+
|
|
64
|
+
def __str__(self) -> str:
|
|
65
|
+
held = ", ".join(f"{a.resname.capitalize()}{a.resnum} {a.name}" for a, _ in self.protein)
|
|
66
|
+
return f"{self.ion.element} is between {', '.join(n for n, _ in self.ligand)} of the ligand and {held}"
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def bridges(structure: Structure, ligand: ResidueKey) -> list[IonBridge]:
|
|
70
|
+
"""The ions of the structure that a donor of the ligand and a donor of another residue hold."""
|
|
71
|
+
own = [a for a in structure.residue_atoms(ligand) if a.element in _DONORS]
|
|
72
|
+
others = [a for a in structure.atoms if a.element in _DONORS and a.residue != ligand
|
|
73
|
+
and a.resname.upper() not in WATER_NAMES]
|
|
74
|
+
if not own or not others:
|
|
75
|
+
return []
|
|
76
|
+
taken = {a.name for a in structure.residue_atoms(ligand)}
|
|
77
|
+
mine = np.array([a.xyz for a in own], dtype=float)
|
|
78
|
+
theirs = np.array([a.xyz for a in others], dtype=float)
|
|
79
|
+
out = []
|
|
80
|
+
for ion in structure.atoms:
|
|
81
|
+
if not is_metal(ion.element) or ion.residue == ligand or len(structure.residue_atoms(ion.residue)) != 1:
|
|
82
|
+
continue
|
|
83
|
+
at, reach = np.array(ion.xyz, dtype=float), REACH.get(ion.element, _REACH)
|
|
84
|
+
d, e = np.linalg.norm(mine - at, axis=1), np.linalg.norm(theirs - at, axis=1)
|
|
85
|
+
held = sorted(((own[i].name, float(d[i])) for i in np.nonzero(d <= reach)[0]), key=lambda t: t[1])
|
|
86
|
+
by = sorted(((others[i], float(e[i])) for i in np.nonzero(e <= reach)[0]), key=lambda t: t[1])
|
|
87
|
+
if not held or not by:
|
|
88
|
+
continue
|
|
89
|
+
name, k = ion.element.upper(), 1
|
|
90
|
+
while name in taken:
|
|
91
|
+
k += 1
|
|
92
|
+
name = f"{ion.element.upper()}{k}"
|
|
93
|
+
taken.add(name)
|
|
94
|
+
out.append(IonBridge(ion, name, tuple(held), tuple(by)))
|
|
95
|
+
return out
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def with_ions(structure: Structure, ligand: ResidueKey, smiles: "str | None", found: "Sequence[IonBridge]"
|
|
99
|
+
) -> "tuple[Structure, str | None]":
|
|
100
|
+
"""The structure with the ions of ``found`` as atoms of the ligand, and the SMILES with them."""
|
|
101
|
+
names = {(b.ion.residue, b.ion.name): b.name for b in found}
|
|
102
|
+
resname = structure.residue_name(ligand)
|
|
103
|
+
atoms = [replace(a, name=names[(a.residue, a.name)], resname=resname, chain=ligand.chain, resnum=ligand.number,
|
|
104
|
+
icode=ligand.icode) if (a.residue, a.name) in names else a for a in structure.atoms]
|
|
105
|
+
if smiles:
|
|
106
|
+
smiles = smiles + "".join(f".[{b.ion.element}+{b.charge if b.charge > 1 else ''}]" for b in found)
|
|
107
|
+
return replace(structure, atoms=atoms, _by_residue={}, _coords=None), smiles
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def seat(lig: Ligand, found: "Sequence[IonBridge]") -> None:
|
|
111
|
+
"""Tell the ligand which of its atoms are ions between it and the protein, and what of it holds them."""
|
|
112
|
+
index = {n: i for i, n in enumerate(lig.names)}
|
|
113
|
+
ions = {index[b.name]: b for b in found}
|
|
114
|
+
lig.bridging = sorted(ions)
|
|
115
|
+
lig.coordination = sorted([(m, d) for m, d in lig.coordination if m not in ions]
|
|
116
|
+
+ [(m, index[n]) for m, b in ions.items() for n, _ in b.ligand if n in index])
|
|
117
|
+
loose = [(b.GetBeginAtomIdx(), b.GetEndAtomIdx()) for b in lig.mol.GetBonds()
|
|
118
|
+
if b.GetBeginAtomIdx() in ions or b.GetEndAtomIdx() in ions]
|
|
119
|
+
if loose: # without a template the ion's neighbours were taken for bonds
|
|
120
|
+
mol = Chem.RWMol(lig.mol)
|
|
121
|
+
for i, j in loose:
|
|
122
|
+
mol.RemoveBond(i, j)
|
|
123
|
+
lig.mol = mol.GetMol()
|
|
124
|
+
lig.mol.UpdatePropertyCache(strict=False)
|
|
125
|
+
Chem.FastFindRings(lig.mol)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def holders(structure: Structure, ligand: ResidueKey) -> "list[Atom]":
|
|
129
|
+
"""The atoms of other residues that hold a metal of the ligand itself."""
|
|
130
|
+
metals = [a for a in structure.residue_atoms(ligand) if is_metal(a.element)]
|
|
131
|
+
return [a for a in structure.atoms if a.element in _DONORS and a.residue != ligand
|
|
132
|
+
and a.resname.upper() not in WATER_NAMES
|
|
133
|
+
and any(float(np.linalg.norm(np.array(a.xyz) - np.array(m.xyz))) <= REACH.get(m.element, _REACH)
|
|
134
|
+
for m in metals)]
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def without_the_bridge(records: "Sequence[Interaction]", found: "Sequence[IonBridge]", holding: "Sequence[Atom]" = ()
|
|
138
|
+
) -> "tuple[list[Interaction], int]":
|
|
139
|
+
"""The records of a table without the ions' own (they are drawn with the ligand) and without hydrogen bonds
|
|
140
|
+
between two atoms that hold the same ion, or of a histidine's nitrogen that holds one (``holding``: what holds
|
|
141
|
+
a metal of the ligand itself); and how many of those there were."""
|
|
142
|
+
ions = {(b.ion.chain, b.ion.resnum, b.ion.icode) for b in found}
|
|
143
|
+
pairs = {(n, a.chain, a.resnum, a.icode, a.name) for b in found for n, _ in b.ligand for a, _ in b.protein}
|
|
144
|
+
spent = {(a.chain, a.resnum, a.icode, a.name) for a in [a for b in found for a, _ in b.protein] + list(holding)
|
|
145
|
+
if a.element == "N" and a.resname.upper() in ("HIS", "HID", "HIE", "HIP")}
|
|
146
|
+
out, dropped = [], 0
|
|
147
|
+
for r in records:
|
|
148
|
+
if r.residue_id in ions:
|
|
149
|
+
continue
|
|
150
|
+
end = (*r.residue_id, r.protein_atom)
|
|
151
|
+
if r.type is T.HBOND and (end in spent or (r.ligand_atom, *end) in pairs):
|
|
152
|
+
dropped += 1
|
|
153
|
+
continue
|
|
154
|
+
out.append(r)
|
|
155
|
+
return out, dropped
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""Placing residues around the ligand.
|
|
2
|
+
|
|
3
|
+
The engine is style-agnostic. A style describes each residue as a :class:`Body`
|
|
4
|
+
(collision shapes, a text label, and *ports* that tie it to points on the
|
|
5
|
+
ligand); the engine returns a pose for every body such that nothing overlaps,
|
|
6
|
+
and reports honestly when it could not manage that.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from .body import Body, Port, Pose
|
|
10
|
+
from .body import SPRINGS
|
|
11
|
+
from .engine import LayoutParams, LayoutResult, audit_layout, layout_bodies, layout_key
|
|
12
|
+
from .field import LigandField
|
|
13
|
+
|
|
14
|
+
__all__ = ["Body", "Port", "Pose", "LayoutParams", "LayoutResult", "layout_bodies", "layout_key", "audit_layout", "LigandField",
|
|
15
|
+
"SPRINGS"]
|
bindview/layout/body.py
ADDED
|
@@ -0,0 +1,421 @@
|
|
|
1
|
+
"""Bodies: the rigid things the layout engine places.
|
|
2
|
+
|
|
3
|
+
A body is a set of collision shapes in its own coordinate frame, optionally a
|
|
4
|
+
text label that follows it without rotating, and one or more *ports* -- points
|
|
5
|
+
on the body tied to fixed points on the ligand. All shapes are capsules (a
|
|
6
|
+
segment swept by a disc); a disc is the degenerate case.
|
|
7
|
+
|
|
8
|
+
Every method that maps local geometry to the page is vectorised over a batch of
|
|
9
|
+
candidate poses, because the engine scores thousands of them at a time.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import math
|
|
15
|
+
from dataclasses import dataclass, field
|
|
16
|
+
from typing import Any, Sequence
|
|
17
|
+
|
|
18
|
+
import numpy as np
|
|
19
|
+
|
|
20
|
+
from ..geometry import Point
|
|
21
|
+
|
|
22
|
+
__all__ = ["Port", "Body", "Pose", "LabelSpec", "march_entry", "SPRINGS"]
|
|
23
|
+
|
|
24
|
+
#: Spring constants by class of tie -- the ``weight`` a :class:`Port` gets. A tie pulls its body
|
|
25
|
+
#: towards the length ``ideal`` with a force constant of ``LayoutParams.w_length * weight`` (times
|
|
26
|
+
#: ``w_short`` while it is shorter than ideal); the ligand does not move at all.
|
|
27
|
+
#:
|
|
28
|
+
#: ``link`` an interaction that is drawn as a line.
|
|
29
|
+
#: ``sightline`` the line-less contacts of a residue, together: the constant is shared among them.
|
|
30
|
+
#: ``eyelash`` the same for a residue that makes line-less contacts only and is drawn as an
|
|
31
|
+
#: eyelash: nothing else holds it, so its sightlines together pull like one link.
|
|
32
|
+
SPRINGS: dict[str, float] = {"link": 1.0, "sightline": 0.35, "eyelash": 1.0}
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass(frozen=True)
|
|
36
|
+
class Pose:
|
|
37
|
+
x: float
|
|
38
|
+
y: float
|
|
39
|
+
angle: float = 0.0
|
|
40
|
+
mirror: bool = False
|
|
41
|
+
|
|
42
|
+
def apply(self, p: Point) -> Point:
|
|
43
|
+
lx, ly = p[0], (-p[1] if self.mirror else p[1])
|
|
44
|
+
c, s = np.cos(self.angle), np.sin(self.angle)
|
|
45
|
+
return (float(lx * c - ly * s + self.x), float(lx * s + ly * c + self.y))
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@dataclass
|
|
49
|
+
class Port:
|
|
50
|
+
"""A tie between a point on the body and a point on the ligand.
|
|
51
|
+
|
|
52
|
+
``drawn`` ports become interaction lines and reserve room for themselves
|
|
53
|
+
(and for a distance label, if ``label_size`` is set). Undrawn ports are
|
|
54
|
+
sightlines: they pull the body toward the ligand atom without any ink.
|
|
55
|
+
"""
|
|
56
|
+
|
|
57
|
+
local: Point
|
|
58
|
+
target: Point
|
|
59
|
+
ideal: float
|
|
60
|
+
min_length: float = 0.0
|
|
61
|
+
weight: float = 1.0
|
|
62
|
+
drawn: bool = True
|
|
63
|
+
port_radius: float = 0.0
|
|
64
|
+
target_radius: float = 0.0
|
|
65
|
+
#: How far from the point it aims at the ink is still that of its own target (the atoms of a ring
|
|
66
|
+
#: round its centre, the label of an atom): a link may run across that, and across no other atom
|
|
67
|
+
#: that is drawn beside a residue box of a chain ligand.
|
|
68
|
+
target_reach: float = 0.0
|
|
69
|
+
label_size: tuple[float, float] | None = None
|
|
70
|
+
#: Ink around the target as world-space capsules ``(p0 (H, 2), p1 (H, 2), r (H,))``.
|
|
71
|
+
#: When given, the link stops where it first meets them (an atom label, the
|
|
72
|
+
#: halo of a charged group) instead of at ``target_radius``.
|
|
73
|
+
target_caps: tuple[np.ndarray, np.ndarray, np.ndarray] | None = None
|
|
74
|
+
#: Index into the body's upright boxes: the link stops at that box.
|
|
75
|
+
port_upright: int | None = None
|
|
76
|
+
#: Ink around the port in body-local coordinates (the halo of a charged
|
|
77
|
+
#: group), plus the upright boxes of the atoms in it: the link stops at
|
|
78
|
+
#: whichever it meets first.
|
|
79
|
+
port_caps: tuple[np.ndarray, np.ndarray, np.ndarray] | None = None
|
|
80
|
+
port_uprights: tuple[int, ...] = ()
|
|
81
|
+
#: Preferred minimum angle (radians) between this link and other bodies'
|
|
82
|
+
#: links into the same target, so that they fan out around it; 0 = no preference.
|
|
83
|
+
fan: float = 0.0
|
|
84
|
+
#: Indices into the body's upright boxes that the link may not run through: the names of the
|
|
85
|
+
#: atoms of its own residue that it does not end on. Empty for every body that is not drawn at a
|
|
86
|
+
#: level of detail: there a link across its own body costs, and is not forbidden.
|
|
87
|
+
clear_of: tuple[int, ...] = ()
|
|
88
|
+
#: ... and whether it may not run through the body's own name label either (a link that ends on
|
|
89
|
+
#: an atom of a residue has no business at the residue's name).
|
|
90
|
+
clear_of_name: bool = False
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
@dataclass(frozen=True)
|
|
94
|
+
class LabelSpec:
|
|
95
|
+
"""An upright text box attached to the body.
|
|
96
|
+
|
|
97
|
+
The box is centred ``gap`` beyond ``anchor`` along ``direction`` (both in
|
|
98
|
+
body-local coordinates), far enough that the box clears the anchor whatever
|
|
99
|
+
the body's rotation.
|
|
100
|
+
"""
|
|
101
|
+
|
|
102
|
+
anchor: Point
|
|
103
|
+
direction: Point
|
|
104
|
+
width: float
|
|
105
|
+
height: float
|
|
106
|
+
gap: float = 3.0
|
|
107
|
+
pad: float = 1.0
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
@dataclass
|
|
111
|
+
class Body:
|
|
112
|
+
key: Any
|
|
113
|
+
kind: str # "disc" | "fragment"
|
|
114
|
+
shapes_p0: np.ndarray # (S, 2) local
|
|
115
|
+
shapes_p1: np.ndarray # (S, 2) local
|
|
116
|
+
shapes_r: np.ndarray # (S,)
|
|
117
|
+
ports: list[Port]
|
|
118
|
+
label: LabelSpec | None = None
|
|
119
|
+
rotatable: bool = False
|
|
120
|
+
mirrorable: bool = False
|
|
121
|
+
ligand_clearance: float = 4.0
|
|
122
|
+
axis: Point = (1.0, 0.0) # local direction that should point away from the ligand
|
|
123
|
+
priority: float = 0.0
|
|
124
|
+
payload: Any = None
|
|
125
|
+
#: Text boxes that travel with the body but stay upright (atom-name labels on
|
|
126
|
+
#: a fragment): local centre points ``(U, 2)`` and ``(width, height)`` each.
|
|
127
|
+
upright_pts: np.ndarray = field(default_factory=lambda: np.zeros((0, 2)))
|
|
128
|
+
upright_wh: np.ndarray = field(default_factory=lambda: np.zeros((0, 2)))
|
|
129
|
+
upright_pad: float = 1.5
|
|
130
|
+
_samples: np.ndarray = field(init=False, repr=False)
|
|
131
|
+
_sample_r: np.ndarray = field(init=False, repr=False)
|
|
132
|
+
|
|
133
|
+
def __post_init__(self) -> None:
|
|
134
|
+
self.shapes_p0 = np.asarray(self.shapes_p0, dtype=float).reshape(-1, 2)
|
|
135
|
+
self.shapes_p1 = np.asarray(self.shapes_p1, dtype=float).reshape(-1, 2)
|
|
136
|
+
self.shapes_r = np.asarray(self.shapes_r, dtype=float).reshape(-1)
|
|
137
|
+
self.upright_pts = np.asarray(self.upright_pts, dtype=float).reshape(-1, 2)
|
|
138
|
+
self.upright_wh = np.asarray(self.upright_wh, dtype=float).reshape(-1, 2)
|
|
139
|
+
pts, rr = [], []
|
|
140
|
+
for p0, p1, r in zip(self.shapes_p0, self.shapes_p1, self.shapes_r):
|
|
141
|
+
# (The length by a function that every platform rounds alike, and rounded before it is cut to a whole
|
|
142
|
+
# number of steps: a last bit decides neither.)
|
|
143
|
+
n = max(1, math.ceil(round(math.hypot(float(p1[0] - p0[0]), float(p1[1] - p0[1])) / 7.0, 6)))
|
|
144
|
+
for k in range(n + 1):
|
|
145
|
+
t = k / n if n else 0.0
|
|
146
|
+
pts.append(p0 + (p1 - p0) * t)
|
|
147
|
+
rr.append(r)
|
|
148
|
+
if np.allclose(p0, p1):
|
|
149
|
+
break
|
|
150
|
+
self._samples = np.array(pts, dtype=float).reshape(-1, 2)
|
|
151
|
+
self._sample_r = np.array(rr, dtype=float)
|
|
152
|
+
self._port_local = np.array([p.local for p in self.ports], dtype=float).reshape(-1, 2)
|
|
153
|
+
self._targets = np.array([p.target for p in self.ports], dtype=float).reshape(-1, 2)
|
|
154
|
+
self._reach = np.array([p.target_reach for p in self.ports], dtype=float)
|
|
155
|
+
self._drawn = np.array([p.drawn for p in self.ports], dtype=bool)
|
|
156
|
+
self._ideal = np.array([p.ideal for p in self.ports], dtype=float)
|
|
157
|
+
self._minlen = np.array([p.min_length for p in self.ports], dtype=float)
|
|
158
|
+
self._weight = np.array([p.weight for p in self.ports], dtype=float)
|
|
159
|
+
self._rport = np.array([p.port_radius for p in self.ports], dtype=float)
|
|
160
|
+
self._rtarget = np.array([p.target_radius for p in self.ports], dtype=float)
|
|
161
|
+
self._has_dlabel = np.array([p.label_size is not None for p in self.ports], dtype=bool)
|
|
162
|
+
self._dlabel = np.array([p.label_size or (0.0, 0.0) for p in self.ports], dtype=float).reshape(-1, 2)
|
|
163
|
+
|
|
164
|
+
# -- sizes -------------------------------------------------------------
|
|
165
|
+
@property
|
|
166
|
+
def radius(self) -> float:
|
|
167
|
+
"""Radius of a circle about the local origin containing every rotating shape."""
|
|
168
|
+
best = 0.0
|
|
169
|
+
if len(self.shapes_r):
|
|
170
|
+
d0 = np.linalg.norm(self.shapes_p0, axis=1) + self.shapes_r
|
|
171
|
+
d1 = np.linalg.norm(self.shapes_p1, axis=1) + self.shapes_r
|
|
172
|
+
best = float(max(d0.max(), d1.max()))
|
|
173
|
+
if len(self.upright_pts):
|
|
174
|
+
reach = np.linalg.norm(self.upright_pts, axis=1) + np.hypot(self.upright_wh[:, 0], self.upright_wh[:, 1]) / 2.0
|
|
175
|
+
best = max(best, float(reach.max()))
|
|
176
|
+
return best
|
|
177
|
+
|
|
178
|
+
@property
|
|
179
|
+
def n_ports(self) -> int:
|
|
180
|
+
return len(self.ports)
|
|
181
|
+
|
|
182
|
+
@property
|
|
183
|
+
def n_proper(self) -> int:
|
|
184
|
+
"""Number of solids that are the body itself (shapes, upright boxes, name
|
|
185
|
+
label); the distance labels come after these in :meth:`solids`."""
|
|
186
|
+
return len(self.shapes_r) + len(self.upright_pts) + (1 if self.label is not None else 0)
|
|
187
|
+
|
|
188
|
+
@property
|
|
189
|
+
def proper_radius(self) -> float:
|
|
190
|
+
"""Radius about the local origin that contains the body itself in any pose."""
|
|
191
|
+
best = self.radius
|
|
192
|
+
if self.label is not None:
|
|
193
|
+
lab = self.label
|
|
194
|
+
reach = (math.hypot(*lab.anchor) + lab.gap + max(lab.width, lab.height) / 2.0
|
|
195
|
+
+ math.hypot(lab.width, lab.height) / 2.0 + lab.pad)
|
|
196
|
+
best = max(best, reach)
|
|
197
|
+
return best + self.upright_pad
|
|
198
|
+
|
|
199
|
+
# -- transforms (batched) ----------------------------------------------
|
|
200
|
+
@staticmethod
|
|
201
|
+
def _xf(local: np.ndarray, pos: np.ndarray, ang: np.ndarray, mir: np.ndarray) -> np.ndarray:
|
|
202
|
+
"""Map local points ``(S, 2)`` through ``N`` poses: ``(N, S, 2)``."""
|
|
203
|
+
ly = np.where(mir[:, None], -local[None, :, 1], local[None, :, 1])
|
|
204
|
+
lx = np.broadcast_to(local[None, :, 0], ly.shape)
|
|
205
|
+
c, s = np.cos(ang)[:, None], np.sin(ang)[:, None]
|
|
206
|
+
return np.stack([lx * c - ly * s + pos[:, 0:1], lx * s + ly * c + pos[:, 1:2]], axis=-1)
|
|
207
|
+
|
|
208
|
+
@staticmethod
|
|
209
|
+
def _xd(vec: Sequence[float], ang: np.ndarray, mir: np.ndarray) -> np.ndarray:
|
|
210
|
+
"""Map one local direction through ``N`` poses: ``(N, 2)``."""
|
|
211
|
+
ly = np.where(mir, -vec[1], vec[1])
|
|
212
|
+
c, s = np.cos(ang), np.sin(ang)
|
|
213
|
+
return np.stack([vec[0] * c - ly * s, vec[0] * s + ly * c], axis=-1)
|
|
214
|
+
|
|
215
|
+
def ports_world(self, pos: np.ndarray, ang: np.ndarray, mir: np.ndarray) -> np.ndarray:
|
|
216
|
+
return self._xf(self._port_local, pos, ang, mir)
|
|
217
|
+
|
|
218
|
+
def label_centre(self, pos: np.ndarray, ang: np.ndarray, mir: np.ndarray) -> np.ndarray | None:
|
|
219
|
+
if self.label is None:
|
|
220
|
+
return None
|
|
221
|
+
lab = self.label
|
|
222
|
+
anchor = self._xf(np.array([lab.anchor], dtype=float), pos, ang, mir)[:, 0, :]
|
|
223
|
+
d = self._xd(lab.direction, ang, mir)
|
|
224
|
+
reach = lab.gap + np.abs(d[:, 0]) * lab.width / 2.0 + np.abs(d[:, 1]) * lab.height / 2.0
|
|
225
|
+
return anchor + d * reach[:, None]
|
|
226
|
+
|
|
227
|
+
def upright_capsules(self, pos: np.ndarray, ang: np.ndarray, mir: np.ndarray
|
|
228
|
+
) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
|
|
229
|
+
"""World capsules of the upright boxes: ``(N, U, 2)``, ``(N, U, 2)``, ``(U,)``."""
|
|
230
|
+
c = self._xf(self.upright_pts, pos, ang, mir)
|
|
231
|
+
w, h = self.upright_wh[:, 0], self.upright_wh[:, 1]
|
|
232
|
+
half = np.maximum(0.0, (w - h) / 2.0)
|
|
233
|
+
off = np.stack([half, np.zeros_like(half)], axis=-1)[None, :, :]
|
|
234
|
+
return c - off, c + off, h / 2.0 + self.upright_pad
|
|
235
|
+
|
|
236
|
+
def link_segments(self, pos: np.ndarray, ang: np.ndarray, mir: np.ndarray
|
|
237
|
+
) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
|
|
238
|
+
"""``(port_end, target_end, length)`` for every port: the *visible* part of
|
|
239
|
+
each link (stopped by the ink at both ends) and the full centre-to-centre
|
|
240
|
+
length. Shapes ``(N, K, 2)``, ``(N, K, 2)``, ``(N, K)``."""
|
|
241
|
+
p = self.ports_world(pos, ang, mir)
|
|
242
|
+
t = np.broadcast_to(self._targets[None, :, :], p.shape)
|
|
243
|
+
v = t - p
|
|
244
|
+
length = np.linalg.norm(v, axis=2)
|
|
245
|
+
u = v / np.maximum(length, 1e-9)[:, :, None]
|
|
246
|
+
a = p + u * np.minimum(self._rport[None, :], length * 0.45)[:, :, None]
|
|
247
|
+
b = t - u * np.minimum(self._rtarget[None, :], length * 0.45)[:, :, None]
|
|
248
|
+
up = None
|
|
249
|
+
for k, port in enumerate(self.ports):
|
|
250
|
+
if port.target_caps is not None:
|
|
251
|
+
c0, c1, cr = port.target_caps
|
|
252
|
+
n = len(pos)
|
|
253
|
+
b[:, k, :] = march_entry(p[:, k, :], t[:, k, :],
|
|
254
|
+
np.broadcast_to(c0[None, :, :], (n,) + c0.shape),
|
|
255
|
+
np.broadcast_to(c1[None, :, :], (n,) + c1.shape), cr)
|
|
256
|
+
if port.port_upright is not None:
|
|
257
|
+
if up is None:
|
|
258
|
+
up = self.upright_capsules(pos, ang, mir)
|
|
259
|
+
j = port.port_upright
|
|
260
|
+
a[:, k, :] = march_entry(t[:, k, :], p[:, k, :], up[0][:, j:j + 1, :], up[1][:, j:j + 1, :],
|
|
261
|
+
up[2][j:j + 1])
|
|
262
|
+
elif port.port_caps is not None or port.port_uprights:
|
|
263
|
+
c0s, c1s, crs = [], [], []
|
|
264
|
+
if port.port_caps is not None:
|
|
265
|
+
c0s.append(self._xf(port.port_caps[0], pos, ang, mir))
|
|
266
|
+
c1s.append(self._xf(port.port_caps[1], pos, ang, mir))
|
|
267
|
+
crs.append(port.port_caps[2])
|
|
268
|
+
if port.port_uprights:
|
|
269
|
+
if up is None:
|
|
270
|
+
up = self.upright_capsules(pos, ang, mir)
|
|
271
|
+
sel = list(port.port_uprights)
|
|
272
|
+
c0s.append(up[0][:, sel, :])
|
|
273
|
+
c1s.append(up[1][:, sel, :])
|
|
274
|
+
crs.append(up[2][sel])
|
|
275
|
+
a[:, k, :] = march_entry(t[:, k, :], p[:, k, :], np.concatenate(c0s, axis=1),
|
|
276
|
+
np.concatenate(c1s, axis=1), np.concatenate(crs))
|
|
277
|
+
return a, b, length
|
|
278
|
+
|
|
279
|
+
def dlabel_capsules(self, a: np.ndarray, b: np.ndarray, label_t: np.ndarray | None
|
|
280
|
+
) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
|
|
281
|
+
"""Capsules of the distance labels, given the visible link ends ``a`` / ``b``
|
|
282
|
+
(``(N, K, 2)``) and each label's position along its link ``label_t`` (``(N, K)``,
|
|
283
|
+
0 = protein end, 1 = ligand end; default the midpoint)."""
|
|
284
|
+
idx = np.nonzero(self._has_dlabel)[0]
|
|
285
|
+
if label_t is None:
|
|
286
|
+
t = np.full((len(a), len(idx)), 0.5)
|
|
287
|
+
else:
|
|
288
|
+
t = label_t[:, idx]
|
|
289
|
+
centre = a[:, idx, :] + (b[:, idx, :] - a[:, idx, :]) * t[:, :, None]
|
|
290
|
+
w, h = self._dlabel[idx, 0], self._dlabel[idx, 1]
|
|
291
|
+
half = np.maximum(0.0, (w - h) / 2.0)
|
|
292
|
+
off = np.stack([half, np.zeros_like(half)], axis=-1)[None, :, :]
|
|
293
|
+
return centre - off, centre + off, h / 2.0 + 1.0
|
|
294
|
+
|
|
295
|
+
def solids(self, pos: np.ndarray, ang: np.ndarray, mir: np.ndarray, label_t: np.ndarray | None = None,
|
|
296
|
+
links: tuple[np.ndarray, np.ndarray, np.ndarray] | None = None
|
|
297
|
+
) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
|
|
298
|
+
"""Everything of the body that must not be overlapped: its shapes, its
|
|
299
|
+
upright boxes, its name label and the distance labels on its drawn links.
|
|
300
|
+
|
|
301
|
+
Returns ``(p0, p1, r, is_dlabel)`` with shapes ``(N, S', 2)``,
|
|
302
|
+
``(N, S', 2)``, ``(S',)``, ``(S',)``.
|
|
303
|
+
"""
|
|
304
|
+
n = len(pos)
|
|
305
|
+
p0 = [self._xf(self.shapes_p0, pos, ang, mir)]
|
|
306
|
+
p1 = [self._xf(self.shapes_p1, pos, ang, mir)]
|
|
307
|
+
rr = [self.shapes_r]
|
|
308
|
+
flag = [np.zeros(len(self.shapes_r), dtype=bool)]
|
|
309
|
+
if len(self.upright_pts):
|
|
310
|
+
u0, u1, ur = self.upright_capsules(pos, ang, mir)
|
|
311
|
+
p0.append(u0)
|
|
312
|
+
p1.append(u1)
|
|
313
|
+
rr.append(ur)
|
|
314
|
+
flag.append(np.zeros(len(ur), dtype=bool))
|
|
315
|
+
if self.label is not None:
|
|
316
|
+
c = self.label_centre(pos, ang, mir)
|
|
317
|
+
assert c is not None
|
|
318
|
+
half = max(0.0, (self.label.width - self.label.height) / 2.0)
|
|
319
|
+
off = np.array([half, 0.0])
|
|
320
|
+
p0.append((c - off)[:, None, :])
|
|
321
|
+
p1.append((c + off)[:, None, :])
|
|
322
|
+
rr.append(np.array([self.label.height / 2.0 + self.label.pad]))
|
|
323
|
+
flag.append(np.zeros(1, dtype=bool))
|
|
324
|
+
if self._has_dlabel.any():
|
|
325
|
+
a, b, _ = links if links is not None else self.link_segments(pos, ang, mir)
|
|
326
|
+
d0, d1, dr = self.dlabel_capsules(a, b, label_t)
|
|
327
|
+
p0.append(d0)
|
|
328
|
+
p1.append(d1)
|
|
329
|
+
rr.append(dr)
|
|
330
|
+
flag.append(np.ones(len(dr), dtype=bool))
|
|
331
|
+
if n == 0:
|
|
332
|
+
total = sum(len(r) for r in rr)
|
|
333
|
+
return np.zeros((0, total, 2)), np.zeros((0, total, 2)), np.concatenate(rr), np.concatenate(flag)
|
|
334
|
+
return np.concatenate(p0, axis=1), np.concatenate(p1, axis=1), np.concatenate(rr), np.concatenate(flag)
|
|
335
|
+
|
|
336
|
+
def ligand_samples(self, pos: np.ndarray, ang: np.ndarray, mir: np.ndarray, some: slice = slice(0, None)
|
|
337
|
+
) -> tuple[np.ndarray, np.ndarray]:
|
|
338
|
+
"""Points (with radii) at which the body proper -- shapes, upright boxes
|
|
339
|
+
and name label, not the distance labels -- is tested against the ligand
|
|
340
|
+
field, or ``some`` of them. Returns ``(points (N, Q, 2), radius (Q,))``."""
|
|
341
|
+
pts = [self._xf(self._samples[some], pos, ang, mir)]
|
|
342
|
+
rr = [self._sample_r[some]]
|
|
343
|
+
extra: list[tuple[np.ndarray, np.ndarray, np.ndarray]] = []
|
|
344
|
+
if len(self.upright_pts):
|
|
345
|
+
extra.append(self.upright_capsules(pos, ang, mir))
|
|
346
|
+
if self.label is not None:
|
|
347
|
+
c = self.label_centre(pos, ang, mir)
|
|
348
|
+
assert c is not None
|
|
349
|
+
half = max(0.0, (self.label.width - self.label.height) / 2.0)
|
|
350
|
+
off = np.array([half, 0.0])
|
|
351
|
+
extra.append(((c - off)[:, None, :], (c + off)[:, None, :],
|
|
352
|
+
np.array([self.label.height / 2.0 + self.label.pad])))
|
|
353
|
+
for c0, c1, cr in extra:
|
|
354
|
+
for t in (0.0, 0.5, 1.0) if some == slice(0, None) else (0.5,):
|
|
355
|
+
pts.append(c0 + (c1 - c0) * t)
|
|
356
|
+
rr.append(cr)
|
|
357
|
+
return np.concatenate(pts, axis=1), np.concatenate(rr)
|
|
358
|
+
|
|
359
|
+
def self_clear(self, pos: np.ndarray, ang: np.ndarray, mir: np.ndarray) -> np.ndarray:
|
|
360
|
+
"""``(N,)`` booleans: the name label does not sit on the body's own drawing.
|
|
361
|
+
|
|
362
|
+
The label stays upright while the body turns, so whether it clears the
|
|
363
|
+
body's atoms depends on the pose.
|
|
364
|
+
"""
|
|
365
|
+
n = len(pos)
|
|
366
|
+
if self.label is None or n == 0:
|
|
367
|
+
return np.ones(n, dtype=bool)
|
|
368
|
+
from ..geometry import segments_distance
|
|
369
|
+
|
|
370
|
+
c = self.label_centre(pos, ang, mir)
|
|
371
|
+
assert c is not None
|
|
372
|
+
half = max(0.0, (self.label.width - self.label.height) / 2.0)
|
|
373
|
+
off = np.array([half, 0.0])
|
|
374
|
+
l0, l1 = (c - off)[:, None, :], (c + off)[:, None, :]
|
|
375
|
+
lr = self.label.height / 2.0 + self.label.pad
|
|
376
|
+
ok = np.ones(n, dtype=bool)
|
|
377
|
+
if len(self.upright_pts):
|
|
378
|
+
u0, u1, ur = self.upright_capsules(pos, ang, mir)
|
|
379
|
+
ok &= ((segments_distance(l0, l1, u0, u1) - ur[None, :] - lr) >= 0.5).all(axis=1)
|
|
380
|
+
if len(self.shapes_r):
|
|
381
|
+
s0 = self._xf(self.shapes_p0, pos, ang, mir)
|
|
382
|
+
s1 = self._xf(self.shapes_p1, pos, ang, mir)
|
|
383
|
+
anchor = self._xf(np.array([self.label.anchor], dtype=float), pos, ang, mir)
|
|
384
|
+
# Bonds that end at the anchor atom necessarily come close; judge the rest.
|
|
385
|
+
touches = (segments_distance(anchor, anchor, s0, s1) - self.shapes_r[None, :]) <= 0.5
|
|
386
|
+
gap = segments_distance(l0, l1, s0, s1) - self.shapes_r[None, :] - lr
|
|
387
|
+
ok &= ((gap >= 0.5) | touches).all(axis=1)
|
|
388
|
+
return ok
|
|
389
|
+
|
|
390
|
+
def march_entry(start: np.ndarray, end: np.ndarray, c0: np.ndarray, c1: np.ndarray, cr: np.ndarray,
|
|
391
|
+
steps: int = 28) -> np.ndarray:
|
|
392
|
+
"""Where the segment ``start -> end`` first enters a union of capsules.
|
|
393
|
+
|
|
394
|
+
``start`` / ``end`` are ``(N, 2)``; the capsules are ``c0`` / ``c1`` of shape
|
|
395
|
+
``(N, H, 2)`` with radii ``cr`` ``(H,)``. The segment is sampled and the
|
|
396
|
+
crossing refined by linear interpolation, which is exact enough for drawing
|
|
397
|
+
and fully vectorised. Returns ``end`` where the segment never enters.
|
|
398
|
+
"""
|
|
399
|
+
n = len(start)
|
|
400
|
+
if n == 0:
|
|
401
|
+
return np.zeros((0, 2))
|
|
402
|
+
ts = np.linspace(0.0, 1.0, steps)
|
|
403
|
+
sx, sy = start[:, 0][:, None], start[:, 1][:, None] # (N, 1)
|
|
404
|
+
px, py = sx + (end[:, 0][:, None] - sx) * ts, sy + (end[:, 1][:, None] - sy) * ts # (N, T)
|
|
405
|
+
px, py = px[:, :, None], py[:, :, None] # (N, T, 1)
|
|
406
|
+
cx, cy = c0[:, :, 0][:, None, :], c0[:, :, 1][:, None, :] # (N, 1, H)
|
|
407
|
+
abx, aby = c1[:, :, 0][:, None, :] - cx, c1[:, :, 1][:, None, :] - cy
|
|
408
|
+
l2 = np.maximum(abx * abx + aby * aby, 1e-12)
|
|
409
|
+
tt = ((px - cx) * abx + (py - cy) * aby) / l2 # (N, T, H)
|
|
410
|
+
np.clip(tt, 0.0, 1.0, out=tt)
|
|
411
|
+
dx, dy = px - (cx + abx * tt), py - (cy + aby * tt)
|
|
412
|
+
d = (np.sqrt(dx * dx + dy * dy) - cr[None, None, :]).min(axis=2) # (N, T)
|
|
413
|
+
inside = d <= 0.0
|
|
414
|
+
has = inside.any(axis=1)
|
|
415
|
+
first = np.argmax(inside, axis=1)
|
|
416
|
+
prev = np.maximum(first - 1, 0)
|
|
417
|
+
rows = np.arange(n)
|
|
418
|
+
d0, d1 = d[rows, prev], d[rows, first]
|
|
419
|
+
frac = np.where((d0 > 0.0) & (d0 - d1 > 1e-12), d0 / np.maximum(d0 - d1, 1e-12), 0.0)
|
|
420
|
+
t_hit = np.where(has, (prev + frac * (first - prev)) / (steps - 1), 1.0)
|
|
421
|
+
return start + (end - start) * t_hit[:, None]
|