bindview 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. bindview/__init__.py +88 -0
  2. bindview/__main__.py +6 -0
  3. bindview/align.py +493 -0
  4. bindview/arrange.js +347 -0
  5. bindview/arrange.py +248 -0
  6. bindview/backends.py +290 -0
  7. bindview/basepairs.py +1711 -0
  8. bindview/chains.py +264 -0
  9. bindview/chem.py +57 -0
  10. bindview/clearance.py +123 -0
  11. bindview/cli.py +990 -0
  12. bindview/compare.py +1854 -0
  13. bindview/confidence.py +531 -0
  14. bindview/consensus.py +303 -0
  15. bindview/covalent.py +220 -0
  16. bindview/depict.py +790 -0
  17. bindview/detect.py +378 -0
  18. bindview/diagram.py +1891 -0
  19. bindview/distance_table.py +589 -0
  20. bindview/ensemble.py +787 -0
  21. bindview/errors.py +47 -0
  22. bindview/exposure.py +207 -0
  23. bindview/features.py +179 -0
  24. bindview/fingerprint.py +469 -0
  25. bindview/fragments.py +304 -0
  26. bindview/geometry.py +482 -0
  27. bindview/graph.py +611 -0
  28. bindview/graphbuild.py +431 -0
  29. bindview/interactions.py +418 -0
  30. bindview/interactive.py +334 -0
  31. bindview/interface.py +1329 -0
  32. bindview/ions.py +155 -0
  33. bindview/layout/__init__.py +15 -0
  34. bindview/layout/body.py +421 -0
  35. bindview/layout/engine.py +1084 -0
  36. bindview/layout/field.py +261 -0
  37. bindview/ligand.py +583 -0
  38. bindview/near.py +67 -0
  39. bindview/options.py +92 -0
  40. bindview/pae.py +991 -0
  41. bindview/peptide.py +610 -0
  42. bindview/plane.py +320 -0
  43. bindview/polymer.py +678 -0
  44. bindview/py.typed +0 -0
  45. bindview/report.py +1407 -0
  46. bindview/residues.py +296 -0
  47. bindview/resolve.py +493 -0
  48. bindview/scene.py +239 -0
  49. bindview/solvent.py +254 -0
  50. bindview/structure.py +1145 -0
  51. bindview/styles/__init__.py +2 -0
  52. bindview/styles/absence.py +180 -0
  53. bindview/styles/base.py +2128 -0
  54. bindview/styles/closeup.py +146 -0
  55. bindview/styles/detailed.py +690 -0
  56. bindview/styles/ligand_draw.py +289 -0
  57. bindview/styles/mixed.py +70 -0
  58. bindview/styles/polymer_draw.py +354 -0
  59. bindview/styles/rings.py +75 -0
  60. bindview/styles/schematic.py +311 -0
  61. bindview/styles/summary.py +147 -0
  62. bindview/svg.py +310 -0
  63. bindview/textmetrics.py +64 -0
  64. bindview/theme.py +317 -0
  65. bindview-0.1.0.dist-info/METADATA +270 -0
  66. bindview-0.1.0.dist-info/RECORD +70 -0
  67. bindview-0.1.0.dist-info/WHEEL +4 -0
  68. bindview-0.1.0.dist-info/entry_points.txt +2 -0
  69. bindview-0.1.0.dist-info/licenses/LICENSE +21 -0
  70. bindview-0.1.0.dist-info/licenses/NOTICE +48 -0
bindview/plane.py ADDED
@@ -0,0 +1,320 @@
1
+ """Where the residues of one side of an interface lie: a plane through them, and how true its picture is.
2
+
3
+ The column of an interface figure (:mod:`bindview.interface`) orders a line. That
4
+ is the right picture of a peptide and the wrong one of a paratope: three loops
5
+ that are far apart in the sequence and side by side in space have no order in
6
+ which neighbours in the column are neighbours in space. For such an interface
7
+ the residues are drawn **where they lie**: projected onto the plane through
8
+ them, at one scale, seen from the partner's side.
9
+
10
+ A picture that looks like the arrangement in space is measured by its reader.
11
+ So the arrangement is not assumed to be faithful, it is measured
12
+ (:func:`fidelity`), the figure says what was found, and an interface that is
13
+ too curved for any plane is not drawn this way at all (:data:`KEPT_MIN`,
14
+ :data:`ERROR_MAX`).
15
+
16
+ Nothing here needs more than NumPy.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ from dataclasses import dataclass
22
+ from typing import Any, Sequence
23
+
24
+ import numpy as np
25
+
26
+ from .geometry import Point
27
+
28
+ __all__ = ["NEAR", "APART", "KEPT_MIN", "ERROR_MAX", "STRETCH_GAP", "MIN_RESIDUES", "Fidelity", "Projection",
29
+ "Arrangement", "Placed", "stretches", "project", "fidelity", "separate", "overlapping", "passes_through",
30
+ "SCALE_BAR"]
31
+
32
+ #: Two residues are neighbours when their centres are this close (ångström): the customary distance
33
+ #: for a contact between two residues ...
34
+ NEAR = 8.0
35
+ #: ... and apart when they are further than this. Between the two a pair is neither: a pair at 8.1 Å
36
+ #: that is drawn at 7.9 Å is not an error of the picture.
37
+ APART = 10.0
38
+ #: A projection is drawn only if it keeps this share of the neighbour relations ...
39
+ KEPT_MIN = 0.90
40
+ #: ... and its distances are off by no more than this (stress; 0.05 is customarily "good", 0.10 "fair", 0.20 "poor").
41
+ ERROR_MAX = 0.10
42
+ #: Residues of the chain that are not at the interface and may lie between two that are, for the two
43
+ #: still to be one stretch: one turn of a helix, so that one face of a helix is one stretch.
44
+ STRETCH_GAP = 3
45
+ #: A plane needs three points.
46
+ MIN_RESIDUES = 3
47
+ #: The median distance between a box and its nearest neighbour, in units of the pitch of a column:
48
+ #: what makes room between the boxes for the residues that touch them.
49
+ ROOM = 2.2
50
+ #: ... and the least that distance is taken to be (ångström) when the scale is set.
51
+ MIN_SPACING = 2.5
52
+ #: Clear space kept between two boxes that had to be pushed apart.
53
+ BOX_GAP = 5.0
54
+ #: The length, in ångström, of the scale bar a figure with boxes on a plane carries.
55
+ SCALE_BAR = 5.0
56
+
57
+
58
+ def stretches(places: Sequence[int], gap: int = STRETCH_GAP) -> list[tuple[int, int]]:
59
+ """Runs of residues that are close in the chain, as ``(first, last)`` indices into ``places``.
60
+
61
+ ``places`` are the positions of residues in their chain, ascending. Two
62
+ consecutive ones are in one stretch when no more than ``gap`` residues lie
63
+ between them.
64
+ """
65
+ out: list[tuple[int, int]] = []
66
+ start = 0
67
+ for k in range(1, len(places) + 1):
68
+ if k == len(places) or places[k] - places[k - 1] - 1 > gap:
69
+ out.append((start, k - 1))
70
+ start = k
71
+ return out
72
+
73
+
74
+ @dataclass(frozen=True)
75
+ class Fidelity:
76
+ """How faithfully positions in a figure reproduce positions in space.
77
+
78
+ ``kept`` is the share of neighbour relations the figure has right, of the
79
+ ``pairs`` that are neighbours (within :data:`NEAR`) in the figure or in
80
+ space: a ``false`` neighbour is drawn within :data:`NEAR` and lies more
81
+ than :data:`APART` away, a ``lost`` one the other way round. ``error`` is
82
+ the root-mean-square deviation of all distances in the figure from those
83
+ in space, relative to the root-mean-square distance (stress).
84
+ """
85
+
86
+ kept: float
87
+ false: int
88
+ lost: int
89
+ pairs: int
90
+ error: float
91
+
92
+ @property
93
+ def ok(self) -> bool:
94
+ return self.kept >= KEPT_MIN and self.error <= ERROR_MAX
95
+
96
+ def as_dict(self) -> dict[str, Any]:
97
+ return {"neighbours_kept": round(self.kept, 3), "false_neighbours": self.false,
98
+ "lost_neighbours": self.lost, "neighbour_pairs": self.pairs, "distance_error": round(self.error, 3)}
99
+
100
+
101
+ def _pairs(points: np.ndarray) -> np.ndarray:
102
+ d = np.linalg.norm(points[:, None, :] - points[None, :, :], axis=2)
103
+ return d[np.triu_indices(len(points), 1)]
104
+
105
+
106
+ def fidelity(space: np.ndarray, figure: np.ndarray, near: float = NEAR, apart: float = APART) -> Fidelity:
107
+ """Compare positions in a figure with positions in space.
108
+
109
+ ``space`` is ``(n, 3)`` in ångström; ``figure`` is ``(n, 2)`` **in
110
+ ångström too**: page coordinates divided by the scale of the figure. The
111
+ scale is the figure's own and is not fitted: a reader has one scale.
112
+ """
113
+ space = np.asarray(space, dtype=float).reshape(-1, 3)
114
+ figure = np.asarray(figure, dtype=float).reshape(-1, 2)
115
+ if len(space) != len(figure):
116
+ raise ValueError("as many positions in the figure as in space")
117
+ if len(space) < 2:
118
+ return Fidelity(1.0, 0, 0, 0, 0.0)
119
+ a, b = _pairs(space), _pairs(figure)
120
+ pairs = int(((a <= near) | (b <= near)).sum())
121
+ false = int(((b <= near) & (a > apart)).sum())
122
+ lost = int(((a <= near) & (b > apart)).sum())
123
+ total = float((a * a).sum())
124
+ error = float(np.sqrt(((b - a) ** 2).sum() / total)) if total > 0.0 else 0.0
125
+ return Fidelity(1.0 - (false + lost) / pairs if pairs else 1.0, false, lost, pairs, error)
126
+
127
+
128
+ @dataclass(frozen=True)
129
+ class Projection:
130
+ """Points projected onto the plane through them.
131
+
132
+ ``xy`` are figure coordinates in ångström (x to the right, y **down**, as
133
+ on a page), seen from the side the ``normal`` points to. ``rms`` is the
134
+ root-mean-square distance of the points from the plane; ``tilt`` the angle
135
+ (degrees) between the normal and the direction the plane was oriented by,
136
+ ``None`` when there was none.
137
+ """
138
+
139
+ xy: np.ndarray
140
+ normal: np.ndarray
141
+ rms: float
142
+ tilt: float | None
143
+
144
+
145
+ def project(points: np.ndarray, toward: "np.ndarray | None" = None) -> Projection:
146
+ """Project ``points`` (``(n, 3)``, at least three) onto their least-squares plane.
147
+
148
+ Of all planes this is the one whose projection keeps the most of the
149
+ squared distances between the points. ``toward`` is a direction from the
150
+ points to whoever looks at them (the partner at an interface): the plane
151
+ is seen from that side, so the picture is not a mirror image. In the plane
152
+ the long axis of the points is upright, with the first point nearer the
153
+ top than the last.
154
+ """
155
+ pts = np.asarray(points, dtype=float).reshape(-1, 3)
156
+ if len(pts) < MIN_RESIDUES:
157
+ raise ValueError(f"a plane needs {MIN_RESIDUES} points, not {len(pts)}")
158
+ centre = pts.mean(axis=0)
159
+ rel = pts - centre
160
+ _, _, axes = np.linalg.svd(rel, full_matrices=True)
161
+ long_axis, normal = axes[0], axes[2]
162
+ tilt = None
163
+ if toward is not None and float(np.linalg.norm(toward)) > 1e-9:
164
+ look = np.asarray(toward, dtype=float) / float(np.linalg.norm(toward))
165
+ if float(normal @ look) < 0.0:
166
+ normal = -normal
167
+ tilt = float(np.degrees(np.arccos(np.clip(float(normal @ look), -1.0, 1.0))))
168
+ if float(rel[0] @ long_axis) < float(rel[-1] @ long_axis):
169
+ long_axis = -long_axis # the first point nearer the top
170
+ right = np.cross(long_axis, normal) # right x up = normal: what is seen from the normal's side
171
+ xy = np.column_stack([rel @ right, -(rel @ long_axis)])
172
+ return Projection(xy, normal, float(np.sqrt(((rel @ normal) ** 2).mean())), tilt)
173
+
174
+
175
+ def overlapping(centres: np.ndarray, half_w: float, half_h: float, gap: float = 0.0) -> int:
176
+ """How many pairs of equal boxes at ``centres`` overlap (or come closer than ``gap``)."""
177
+ at = np.asarray(centres, dtype=float).reshape(-1, 2)
178
+ if len(at) < 2:
179
+ return 0
180
+ d = np.abs(at[:, None, :] - at[None, :, :])
181
+ close = (d[..., 0] < 2.0 * half_w + gap - 1e-6) & (d[..., 1] < 2.0 * half_h + gap - 1e-6)
182
+ return int(np.triu(close, 1).sum())
183
+
184
+
185
+ def separate(centres: np.ndarray, half_w: float, half_h: float, gap: float = BOX_GAP,
186
+ sweeps: int = 5000) -> np.ndarray:
187
+ """Push equal boxes apart until no two overlap, each pair by the least it takes.
188
+
189
+ Two boxes that overlap are moved apart along the axis on which that takes
190
+ less, half the way each. Pairs are taken in a fixed order, so the result
191
+ is the same every time. A handful of sweeps settles boxes at the spacing a
192
+ figure has; thirty boxes thrown on one spot take a few thousand, which is
193
+ what ``sweeps`` allows. Whether any still overlap is for the caller to
194
+ ask (:func:`overlapping`): a figure never takes it on trust.
195
+ """
196
+ out = np.array(centres, dtype=float).reshape(-1, 2).copy()
197
+ need = np.array([2.0 * half_w + gap, 2.0 * half_h + gap])
198
+ n = len(out)
199
+ for _ in range(sweeps):
200
+ moved = False
201
+ for i in range(n):
202
+ for j in range(i + 1, n):
203
+ d = out[j] - out[i]
204
+ inside = need - np.abs(d)
205
+ if inside[0] <= 1e-9 or inside[1] <= 1e-9:
206
+ continue
207
+ axis = 0 if inside[0] < inside[1] else 1
208
+ way = 1.0 if d[axis] > 0.0 or (d[axis] == 0.0) else -1.0
209
+ out[i, axis] -= way * inside[axis] / 2.0
210
+ out[j, axis] += way * inside[axis] / 2.0
211
+ moved = True
212
+ if not moved:
213
+ break
214
+ return out
215
+
216
+
217
+ def passes_through(a: Point, b: Point, box: "tuple[float, float, float, float]", margin: float = 1.0) -> bool:
218
+ """Does the segment from ``a`` to ``b`` run through ``box`` (grown by ``margin``)?"""
219
+ lo, hi = 0.0, 1.0
220
+ for start, end, b0, b1 in ((a[0], b[0], box[0] - margin, box[2] + margin),
221
+ (a[1], b[1], box[1] - margin, box[3] + margin)):
222
+ d = end - start
223
+ if abs(d) < 1e-12:
224
+ if start < b0 or start > b1:
225
+ return False
226
+ continue
227
+ t0, t1 = (b0 - start) / d, (b1 - start) / d
228
+ lo, hi = max(lo, min(t0, t1)), min(hi, max(t0, t1))
229
+ return hi > lo
230
+
231
+
232
+ @dataclass(frozen=True)
233
+ class Placed:
234
+ """The boxes of an arrangement on a page: what a figure says about its own truth."""
235
+
236
+ scale: float # page units per ångström
237
+ fidelity: Fidelity # of the boxes as they are drawn
238
+ bare: Fidelity # of the projection itself, before any box was moved
239
+ rms: float # of the residue centres from the plane, ångström
240
+ tilt: float | None
241
+ moved: int # boxes that had to be pushed off their place
242
+ covered: int = 0 # pairs of boxes that lie on top of each other as drawn
243
+
244
+ @property
245
+ def ok(self) -> bool:
246
+ """Is this a figure to draw: faithful, and no box on top of another?"""
247
+ return self.fidelity.ok and self.covered == 0
248
+
249
+ def as_dict(self) -> dict[str, Any]:
250
+ # The scale in full: a figure drawn again from its graph is measured with it.
251
+ out = {**self.fidelity.as_dict(), "px_per_angstrom": round(self.scale, 6),
252
+ "out_of_plane_rms": round(self.rms, 2), "boxes_moved": self.moved,
253
+ **({"boxes_covering_each_other": self.covered} if self.covered else {}),
254
+ "projection": self.bare.as_dict(),
255
+ "thresholds": {"neighbours_kept_min": KEPT_MIN, "distance_error_max": ERROR_MAX,
256
+ "neighbour_within": NEAR, "apart_beyond": APART}}
257
+ if self.tilt is not None:
258
+ out["partner_off_normal_deg"] = round(self.tilt, 1)
259
+ return out
260
+
261
+
262
+ @dataclass(frozen=True)
263
+ class Arrangement:
264
+ """The residues of a chain where they lie on the plane through them.
265
+
266
+ ``xy`` (figure coordinates in ångström) and ``space`` (their centres in
267
+ space) are one per residue, in the order of the chain. ``joins`` are the
268
+ positions (counted from 1) after which a dotted line joins two boxes: the
269
+ two are in one stretch, with residues between them that are not drawn.
270
+ """
271
+
272
+ xy: tuple[Point, ...]
273
+ space: tuple[tuple[float, float, float], ...]
274
+ joins: frozenset[int]
275
+ rms: float
276
+ tilt: float | None
277
+ bare: Fidelity
278
+
279
+ @classmethod
280
+ def of(cls, centres: np.ndarray, toward: "np.ndarray | None", joins: Sequence[int] = ()) -> "Arrangement":
281
+ proj = project(centres, toward)
282
+ space = np.asarray(centres, dtype=float).reshape(-1, 3)
283
+ return cls(tuple((float(x), float(y)) for x, y in proj.xy),
284
+ tuple((float(p[0]), float(p[1]), float(p[2])) for p in space),
285
+ frozenset(joins), proj.rms, proj.tilt, fidelity(space, proj.xy))
286
+
287
+ @property
288
+ def spacing(self) -> float:
289
+ """The median distance between a residue and its nearest neighbour on the plane, ångström."""
290
+ xy = np.array(self.xy, dtype=float)
291
+ d = np.linalg.norm(xy[:, None, :] - xy[None, :, :], axis=2) + np.eye(len(xy)) * 1e9
292
+ return float(np.median(d.min(axis=1)))
293
+
294
+ def scale(self, pitch: float) -> float:
295
+ """Page units per ångström at a column pitch of ``pitch`` page units.
296
+
297
+ The median distance from a residue to its nearest neighbour on the plane becomes
298
+ :data:`ROOM` pitches. Residues that lie one above the other fall on one spot; where that is
299
+ the usual case the spacing is taken as :data:`MIN_SPACING`, or the figure would have no end.
300
+ """
301
+ return pitch * ROOM / max(self.spacing, MIN_SPACING)
302
+
303
+ def place(self, pitch: float, half_w: float, half_h: float) -> tuple[list[Point], Placed]:
304
+ """Box centres on the page, and what became of the arrangement on the way."""
305
+ scale = self.scale(pitch)
306
+ ideal = np.array(self.xy, dtype=float) * scale
307
+ final = separate(ideal, half_w, half_h)
308
+ return [(float(x), float(y)) for x, y in final], self.measure(final, scale, ideal, half_w, half_h)
309
+
310
+ def measure(self, centres: "np.ndarray | Sequence[Point]", scale: float, ideal: "np.ndarray | None" = None,
311
+ half_w: float = 0.0, half_h: float = 0.0) -> Placed:
312
+ """What the boxes at ``centres`` (page units, any origin) say about the arrangement. With the
313
+ half width and height of a box, whether two of them lie on top of each other is counted too."""
314
+ final = np.array(centres, dtype=float).reshape(-1, 2)
315
+ if ideal is None:
316
+ ideal = np.array(self.xy, dtype=float) * scale
317
+ ideal = ideal + (final.mean(axis=0) - ideal.mean(axis=0))
318
+ moved = int((np.linalg.norm(final - ideal, axis=1) > 0.5).sum())
319
+ return Placed(scale, fidelity(np.array(self.space, dtype=float), final / scale), self.bare, self.rms,
320
+ self.tilt, moved, overlapping(final, half_w, half_h) if half_w and half_h else 0)