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/arrange.js ADDED
@@ -0,0 +1,347 @@
1
+ // The page in which a figure is arranged by hand (bindview/arrange.py). It knows the figure by what bindview writes into it:
2
+ // groups of residues and contacts with data-residue, and the graph of the figure, whose nodes have the places.
3
+ (function () {
4
+ "use strict";
5
+ var given = JSON.parse(document.getElementById("graph").textContent), exact = window.EXACT || null;
6
+ var orig = given.graph, bonds = given.bonds, now = copy(orig), svg = null, items = {}, byId = {}, STEP = 15;
7
+ var picked = null, drag = null, past = [], busy = false, again = false;
8
+ function copy(x) { return JSON.parse(JSON.stringify(x)); }
9
+ function $(id) { return document.getElementById(id); }
10
+ function say(words) { $("said").textContent = words; }
11
+
12
+ // ------------------------------------------------------------ reading a figure
13
+ function read() {
14
+ svg = document.querySelector("#figure svg"); items = {}; byId = {};
15
+ now.nodes.forEach(function (n) { byId[n.id] = n; });
16
+ svg.querySelectorAll("g.residue[data-residue]").forEach(function (g) {
17
+ var id = "R:" + g.getAttribute("data-residue"), n = byId[id];
18
+ if (!n || n.x === null || n.x === undefined) { return; }
19
+ var it = items[id] = items[id] || { id: id, n: n, parts: [], links: [], spokes: [], lining: [], dx: 0, dy: 0, turn: 0, flip: false };
20
+ it.parts = it.parts.concat(leaves(g)); it.group = g;
21
+ it.targets = now.contacts.filter(function (c) { return c.residue === id && c.ligand; })
22
+ .map(function (c) { return byId[c.ligand]; }).filter(Boolean)
23
+ .map(function (t) { return [t.x, t.y]; });
24
+ g.style.cursor = "grab";
25
+ g.addEventListener("pointerdown", function (e) { begin(e, id); });
26
+ g.addEventListener("dblclick", function () { back(id); });
27
+ });
28
+ svg.querySelectorAll("g.interaction[data-residue]").forEach(function (g) {
29
+ var it = items["R:" + g.getAttribute("data-residue")]; if (it) { it.links.push(link(g, it)); }
30
+ });
31
+ svg.querySelectorAll("g.contact[data-residue]").forEach(function (g) {
32
+ var it = items["R:" + g.getAttribute("data-residue")]; if (it) { it.spokes.push(g); }
33
+ });
34
+ svg.querySelectorAll("g.lining[data-residues]").forEach(function (g) {
35
+ g.getAttribute("data-residues").split(" ").forEach(function (r) { if (items["R:" + r]) { items["R:" + r].lining.push(g); } });
36
+ });
37
+ Object.keys(items).forEach(function (id) { shape(items[id]); });
38
+ var key = svg.querySelector("g.legend");
39
+ if (key && byId.legend) {
40
+ items.legend = { id: "legend", n: byId.legend, key: key, home: key.getAttribute("transform") || "", dx: 0, dy: 0, turn: 0,
41
+ flip: false, parts: [], links: [], spokes: [], lining: [] };
42
+ key.style.cursor = "grab";
43
+ key.addEventListener("pointerdown", function (e) { begin(e, "legend"); });
44
+ }
45
+ svg.addEventListener("pointermove", function (e) {
46
+ if (!drag) { return; }
47
+ var p = place(e), it = items[drag.id]; it.dx = p.x - drag.x; it.dy = p.y - drag.y; show(it);
48
+ });
49
+ svg.addEventListener("pointerup", function () { if (drag) { drag = null; done(); } });
50
+ svg.addEventListener("pointerdown", function (e) { if (!e.target.closest("g.residue, g.legend")) { pick(null); } });
51
+ svg.addEventListener("wheel", function (e) {
52
+ if (!picked || !items[picked] || items[picked].key) { return; }
53
+ e.preventDefault(); turn((e.deltaY > 0 ? 1 : -1) * 5); later();
54
+ }, { passive: false });
55
+ if (picked && items[picked]) { pick(picked); }
56
+ write();
57
+ }
58
+ function leaves(g) {
59
+ var out = [];
60
+ (function walk(el) {
61
+ Array.prototype.forEach.call(el.children, function (c) {
62
+ if (c.tagName === "g") { walk(c); } else if (c.tagName !== "title") {
63
+ out.push({ el: c, text: c.tagName === "text", x: +c.getAttribute("x"), y: +c.getAttribute("y"),
64
+ size: +(c.getAttribute("font-size") || 10) });
65
+ }
66
+ });
67
+ })(g);
68
+ return out;
69
+ }
70
+ function ends(g) {
71
+ var pts = [];
72
+ g.querySelectorAll("line").forEach(function (l) {
73
+ pts.push([+l.getAttribute("x1"), +l.getAttribute("y1")], [+l.getAttribute("x2"), +l.getAttribute("y2")]);
74
+ });
75
+ return pts;
76
+ }
77
+ function link(g, it) { // a contact's line: its end at the residue, its end at the ligand
78
+ var pts = ends(g), best = [pts[0] || [0, 0], pts[1] || pts[0] || [0, 0]], far = -1, n = it.n;
79
+ pts.forEach(function (p) { pts.forEach(function (q) {
80
+ var d = Math.hypot(p[0] - q[0], p[1] - q[1]); if (d > far) { far = d; best = [p, q]; }
81
+ }); });
82
+ var near = Math.hypot(best[0][0] - n.x, best[0][1] - n.y) <= Math.hypot(best[1][0] - n.x, best[1][1] - n.y) ? 0 : 1;
83
+ return { a: best[near], b: best[1 - near], all: leaves(g) };
84
+ }
85
+ function shape(it) { // what faces the ligand by itself: an eyelash, the tip of a bubble
86
+ var n = it.n;
87
+ if (n.form === "eyelash") {
88
+ it.arcs = it.parts.filter(function (l) { return l.el.tagName === "polyline"; });
89
+ it.lashes = it.parts.filter(function (l) { return l.el.tagName === "line"; });
90
+ if (!it.arcs.length) { it.arcs = null; return; }
91
+ var p = it.arcs[0].el.getAttribute("points").trim().split(/\s+/)[0].split(",");
92
+ it.radius = Math.hypot(+p[0] - n.x, +p[1] - n.y);
93
+ var l = it.lashes[0] && it.lashes[0].el;
94
+ it.lash = l ? Math.hypot(+l.getAttribute("x2") - n.x, +l.getAttribute("y2") - n.y) - it.radius : 5;
95
+ } else if (n.form === "bubble") {
96
+ it.drop = it.parts.filter(function (l) { return l.el.tagName === "path" && / A /.test(" " + l.el.getAttribute("d").replace(/A/g, " A ")); });
97
+ it.drop.forEach(function (l) {
98
+ var m = l.el.getAttribute("d").match(/A\s*([\d.]+)/); l.radius = m ? +m[1] : 15;
99
+ });
100
+ }
101
+ }
102
+
103
+ // ------------------------------------------------------------ drawing the preview
104
+ function moved(it, p) {
105
+ var n = it.n, x = p[0] - n.x, y = p[1] - n.y, a0 = n.angle || 0, c, s, u, v;
106
+ if (it.flip) {
107
+ c = Math.cos(-a0); s = Math.sin(-a0); u = x * c - y * s; v = -(x * s + y * c);
108
+ c = Math.cos(a0); s = Math.sin(a0); x = u * c - v * s; y = u * s + v * c;
109
+ }
110
+ c = Math.cos(it.turn); s = Math.sin(it.turn);
111
+ return [x * c - y * s + n.x + it.dx, x * s + y * c + n.y + it.dy];
112
+ }
113
+ function matrix(it) {
114
+ var o = moved(it, [0, 0]), e = moved(it, [1, 0]), f = moved(it, [0, 1]);
115
+ return "matrix(" + [e[0] - o[0], e[1] - o[1], f[0] - o[0], f[1] - o[1], o[0], o[1]].join(" ") + ")";
116
+ }
117
+ function clusters(c, targets) {
118
+ var full = 2 * Math.PI, deg = Math.PI / 180;
119
+ var ang = targets.map(function (t) { return ((Math.atan2(t[1] - c[1], t[0] - c[0]) % full) + full) % full; })
120
+ .sort(function (a, b) { return a - b; });
121
+ if (!ang.length) { return []; }
122
+ if (ang.length === 1) { return [[ang[0], 56 * deg]]; }
123
+ var big = -1, at = 0;
124
+ ang.forEach(function (a, i) { var g = ((ang[(i + 1) % ang.length] - a) % full + full) % full; if (g >= big) { big = g; at = i; } });
125
+ var spread = full - big, start = ang[(at + 1) % ang.length];
126
+ if (spread <= 110 * deg) { return [[start + spread / 2, 56 * deg]]; }
127
+ var run = ang.map(function (a) { return ((a - start) % full + full) % full; }).sort(function (a, b) { return a - b; });
128
+ var cut = 0, gap = -1;
129
+ for (var i = 0; i + 1 < run.length; i++) { if (run[i + 1] - run[i] >= gap) { gap = run[i + 1] - run[i]; cut = i; } }
130
+ return [run.slice(0, cut + 1), run.slice(cut + 1)].map(function (p) { return [start + (p[0] + p[p.length - 1]) / 2, 40 * deg]; });
131
+ }
132
+ function eyelash(it) {
133
+ var c = [it.n.x + it.dx, it.n.y + it.dy], parent = it.arcs[0].el.parentNode, like = it.arcs[0].el, lash = it.lashes[0].el;
134
+ it.arcs.concat(it.lashes).forEach(function (l) { l.el.remove(); });
135
+ it.arcs = []; it.lashes = [];
136
+ clusters(c, it.targets).forEach(function (k) {
137
+ var pts = [], i, a, n = k[1] > 50 * Math.PI / 180 ? 7 : 5;
138
+ for (i = 0; i <= 24; i++) { a = k[0] - k[1] + 2 * k[1] * i / 24; pts.push((c[0] + it.radius * Math.cos(a)).toFixed(2) + "," + (c[1] + it.radius * Math.sin(a)).toFixed(2)); }
139
+ var arc = like.cloneNode(false); arc.setAttribute("points", pts.join(" ")); arc.removeAttribute("transform");
140
+ parent.insertBefore(arc, parent.firstChild); it.arcs.push({ el: arc });
141
+ for (i = 0; i < n; i++) {
142
+ a = k[0] - k[1] + 2 * k[1] * (i + 0.5) / n;
143
+ var l = lash.cloneNode(false); l.removeAttribute("transform");
144
+ l.setAttribute("x1", c[0] + it.radius * Math.cos(a)); l.setAttribute("y1", c[1] + it.radius * Math.sin(a));
145
+ l.setAttribute("x2", c[0] + (it.radius + it.lash) * Math.cos(a)); l.setAttribute("y2", c[1] + (it.radius + it.lash) * Math.sin(a));
146
+ parent.insertBefore(l, parent.firstChild); it.lashes.push({ el: l });
147
+ }
148
+ });
149
+ }
150
+ function drop(it, l) {
151
+ var x = it.n.x + it.dx, y = it.n.y + it.dy, r = l.radius, tip = 1.3, phi = Math.acos(1 / tip), tx = 0, ty = 0;
152
+ it.targets.forEach(function (t) { tx += t[0] / it.targets.length; ty += t[1] / it.targets.length; });
153
+ var th = Math.atan2(ty - y, tx - x), f = function (k, a) { return (x + k * r * Math.cos(a)).toFixed(2) + " " + (y + k * r * Math.sin(a)).toFixed(2); };
154
+ l.el.setAttribute("d", "M " + f(tip, th) + " L " + f(1, th + phi) + " A " + r + " " + r + " 0 1 1 " + f(1, th - phi) + " Z");
155
+ }
156
+ // The spokes on the atoms of the ligand: fanned towards the residue, between the atom's bonds.
157
+ function spokes(it) {
158
+ it.spokes.forEach(function (g) {
159
+ var lines = Array.prototype.slice.call(g.querySelectorAll("line")); if (!lines.length) { return; }
160
+ var atoms = (g.getAttribute("data-ligand-atoms") || "").split(",").map(function (a) { return byId["L:" + a]; }).filter(Boolean);
161
+ atoms.forEach(function (n) {
162
+ var mine = lines.filter(function (l) { return Math.hypot(+l.getAttribute("x1") - n.x, +l.getAttribute("y1") - n.y) < 26; });
163
+ if (!mine.length) { return; }
164
+ var r0 = Math.hypot(+mine[0].getAttribute("x1") - n.x, +mine[0].getAttribute("y1") - n.y);
165
+ var r1 = Math.hypot(+mine[0].getAttribute("x2") - n.x, +mine[0].getAttribute("y2") - n.y);
166
+ var want = Math.atan2(it.n.y + it.dy - n.y, it.n.x + it.dx - n.x), off = 21 * Math.PI / 180;
167
+ var dirs = (bonds[n.id] || []).map(function (id) { return byId[id]; }).filter(Boolean)
168
+ .map(function (q) { return Math.atan2(q.y - n.y, q.x - n.x); });
169
+ var free = function (a) { return dirs.every(function (b) { return Math.abs(Math.atan2(Math.sin(a - b), Math.cos(a - b))) >= off; }); };
170
+ var mid = null;
171
+ for (var k = 0; k <= 60 && mid === null; k++) {
172
+ [1, -1].forEach(function (sg) { var a = want + sg * 3 * k * Math.PI / 180; if (mid === null && free(a)) { mid = a; } });
173
+ }
174
+ if (mid === null) { return; }
175
+ var like = mine[0]; mine.forEach(function (l) { if (l !== like) { l.remove(); } });
176
+ [-0.42, 0, 0.42].filter(function (d) { return free(mid + d); }).forEach(function (d, i) {
177
+ var l = i ? like.cloneNode(false) : like, a = mid + d;
178
+ l.setAttribute("x1", n.x + r0 * Math.cos(a)); l.setAttribute("y1", n.y + r0 * Math.sin(a));
179
+ l.setAttribute("x2", n.x + r1 * Math.cos(a)); l.setAttribute("y2", n.y + r1 * Math.sin(a));
180
+ if (i) { g.appendChild(l); }
181
+ });
182
+ });
183
+ });
184
+ }
185
+ function shift(l, q, mid) { l.el.setAttribute("transform", "translate(" + (q[0] - mid[0]) + " " + (q[1] - mid[1]) + ")"); }
186
+ function show(it) {
187
+ if (it.key) { it.key.setAttribute("transform", "translate(" + it.dx + " " + it.dy + ") " + it.home); write(); return; }
188
+ var m = matrix(it);
189
+ it.parts.forEach(function (l) {
190
+ if (!l.el.isConnected) { return; }
191
+ var mid = [l.x, l.y - 0.36 * l.size];
192
+ if (l.text) { shift(l, moved(it, mid), mid); }
193
+ else if (it.drop && it.drop.indexOf(l) >= 0) { drop(it, l); }
194
+ else if (!it.arcs) { l.el.setAttribute("transform", m); }
195
+ });
196
+ if (it.arcs) { eyelash(it); }
197
+ spokes(it);
198
+ // The wall of the pocket is bindview's to draw: where the residue has gone, what is on the page is of its old place.
199
+ it.lining.forEach(function (g) { g.setAttribute("opacity", "0.25"); });
200
+ it.links.forEach(function (k) {
201
+ // The end at the ligand stays, the end at the residue goes with it: a turn and a stretch about the former.
202
+ var q = moved(it, k.a), ax = k.a[0] - k.b[0], ay = k.a[1] - k.b[1], bx = q[0] - k.b[0], by = q[1] - k.b[1];
203
+ var d = ax * ax + ay * ay || 1, c = (ax * bx + ay * by) / d, s = (ax * by - ay * bx) / d;
204
+ var mk = "matrix(" + [c, s, -s, c, k.b[0] - c * k.b[0] + s * k.b[1], k.b[1] - s * k.b[0] - c * k.b[1]].join(" ") + ")";
205
+ k.all.forEach(function (l) {
206
+ var mid = [l.x, l.y - 0.36 * l.size], x = mid[0] - k.b[0], y = mid[1] - k.b[1];
207
+ if (l.text) { shift(l, [c * x - s * y + k.b[0], s * x + c * y + k.b[1]], mid); }
208
+ else { l.el.setAttribute("transform", mk); }
209
+ });
210
+ });
211
+ write();
212
+ }
213
+
214
+ // ------------------------------------------------------------ what the hand does
215
+ function place(e) {
216
+ var p = svg.createSVGPoint(); p.x = e.clientX; p.y = e.clientY;
217
+ return p.matrixTransform(svg.getScreenCTM().inverse());
218
+ }
219
+ function begin(e, id) {
220
+ e.preventDefault(); pick(id);
221
+ var p = place(e), it = items[id];
222
+ drag = { id: id, x: p.x - it.dx, y: p.y - it.dy };
223
+ try { svg.setPointerCapture(e.pointerId); } catch (err) { /* a made-up event has no pointer */ }
224
+ }
225
+ function pick(id) {
226
+ picked = id;
227
+ svg.querySelectorAll("g.residue, g.legend").forEach(function (g) {
228
+ var r = g.getAttribute("data-residue");
229
+ g.classList.toggle("picked", !!id && (r ? "R:" + r === id : id === "legend"));
230
+ });
231
+ $("which").textContent = id ? (byId[id].label || id) : "nothing";
232
+ }
233
+ function turnable(it) { return it.n.form === "fragment"; }
234
+ function turn(by) {
235
+ var it = items[picked]; if (!it || it.key) { return; }
236
+ if (!turnable(it)) { say("It is drawn without atoms and faces the ligand by itself: it is moved, not turned."); return; }
237
+ it.turn += by * Math.PI / 180; show(it);
238
+ }
239
+ function flip() {
240
+ var it = items[picked]; if (!it || it.key) { return; }
241
+ if (!turnable(it)) { say("It is drawn without atoms: there is nothing to flip."); return; }
242
+ it.flip = !it.flip; show(it); done();
243
+ }
244
+ function back(id) {
245
+ var o = orig.nodes.filter(function (n) { return n.id === id; })[0], n = byId[id];
246
+ now.nodes[now.nodes.indexOf(n)] = copy(o); past.push(null); redraw(now, true);
247
+ }
248
+ document.addEventListener("keydown", function (e) {
249
+ if (e.target.tagName === "TEXTAREA") { return; }
250
+ if ((e.metaKey || e.ctrlKey) && e.key === "z") { e.preventDefault(); undo(); return; }
251
+ if (!picked || !items[picked]) { return; }
252
+ var it = items[picked], step = e.shiftKey ? 10 : 2, k = e.key;
253
+ if (k === "r" || k === "R") { turn(k === "R" ? -STEP : STEP); later(); }
254
+ else if (k === "f") { flip(); }
255
+ else if (k === "Escape") { pick(null); }
256
+ else if (k.indexOf("Arrow") === 0) {
257
+ it.dx += k === "ArrowLeft" ? -step : k === "ArrowRight" ? step : 0;
258
+ it.dy += k === "ArrowUp" ? -step : k === "ArrowDown" ? step : 0; show(it); later();
259
+ } else { return; }
260
+ e.preventDefault();
261
+ });
262
+ var timer = null;
263
+ function later() { clearTimeout(timer); timer = setTimeout(done, 350); }
264
+ function touched() { return Object.keys(items).some(function (id) { var it = items[id]; return it.dx || it.dy || it.turn || it.flip; }); }
265
+ function edited() {
266
+ var g = copy(now);
267
+ g.nodes.forEach(function (n) {
268
+ var it = items[n.id]; if (!it) { return; }
269
+ if (it.key) { n.offset = [(n.offset || [0, 0])[0] + it.dx, (n.offset || [0, 0])[1] + it.dy]; }
270
+ n.x += it.dx; n.y += it.dy;
271
+ if (it.flip) { if (n.mirror) { delete n.mirror; } else { n.mirror = true; } }
272
+ if (it.turn) { n.angle = (n.angle || 0) + it.turn; }
273
+ });
274
+ return g;
275
+ }
276
+ // Let go: bindview draws the figure from the layout (where it is behind the page), and that is the new figure.
277
+ function done() {
278
+ if (drag || !touched()) { return; }
279
+ past.push(copy(now)); redraw(edited(), false);
280
+ }
281
+ function undo() {
282
+ var g = past.pop(); while (g === null) { g = past.pop(); }
283
+ if (g) { redraw(g, true); }
284
+ }
285
+ function redraw(graph, whole) {
286
+ if (!exact) {
287
+ if (whole) { now = copy(orig); $("figure").innerHTML = given.svg; now = copy(orig); read(); replay(graph); } else { write(); }
288
+ return;
289
+ }
290
+ if (busy) { again = true; return; }
291
+ busy = true; say("drawing …");
292
+ fetch(exact + "render", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(graph) })
293
+ .then(function (r) { return r.json(); }).then(function (a) {
294
+ busy = false;
295
+ if (a.error) { say(a.error); return; }
296
+ $("figure").innerHTML = a.svg; now = a.graph; read(); say(a.said || "");
297
+ if (again) { again = false; done(); }
298
+ }).catch(function (err) { busy = false; say("bindview does not answer: " + err); });
299
+ }
300
+ function replay(graph) { // without bindview: the preview of a layout, from the first figure
301
+ graph.nodes.forEach(function (n) {
302
+ var it = items[n.id], o = byId[n.id]; if (!it || o.x === null) { return; }
303
+ if (it.key) { it.dx = (n.offset || [0, 0])[0] - (o.offset || [0, 0])[0]; it.dy = (n.offset || [0, 0])[1] - (o.offset || [0, 0])[1]; }
304
+ else { it.dx = n.x - o.x; it.dy = n.y - o.y; it.turn = (n.angle || 0) - (o.angle || 0); it.flip = !!n.mirror !== !!o.mirror; }
305
+ if (it.dx || it.dy || it.turn || it.flip) { show(it); }
306
+ });
307
+ }
308
+
309
+ // ------------------------------------------------------------ what comes out
310
+ function num(v) { return (Math.round(v * 10) / 10).toString(); }
311
+ function calls() {
312
+ var g = edited(), was = {}, out = []; orig.nodes.forEach(function (n) { was[n.id] = n; });
313
+ g.nodes.forEach(function (n) {
314
+ var o = was[n.id]; if (!items[n.id] || !o) { return; }
315
+ var name = JSON.stringify(n.id === "legend" ? "legend" : n.label), dx, dy;
316
+ if (n.id === "legend") { dx = (n.offset || [0, 0])[0] - (o.offset || [0, 0])[0]; dy = (n.offset || [0, 0])[1] - (o.offset || [0, 0])[1]; }
317
+ else { dx = n.x - o.x; dy = n.y - o.y; }
318
+ if (!!n.mirror !== !!o.mirror) { out.push("graph.flip(" + name + ")"); }
319
+ var d = Math.round(((n.angle || 0) - (o.angle || 0)) * 180 / Math.PI) % 360;
320
+ if (d) { out.push("graph.rotate(" + name + ", " + d + ")"); }
321
+ if (Math.abs(dx) > 0.05 || Math.abs(dy) > 0.05) { out.push("graph.move(" + name + ", " + num(dx) + ", " + num(dy) + ")"); }
322
+ });
323
+ return out;
324
+ }
325
+ function write() {
326
+ var c = calls();
327
+ $("calls").value = c.length ? ["graph = diagram.render().graph"].concat(c, ["figure = diagram.render(graph=graph)"]).join("\n")
328
+ : "# nothing is moved yet";
329
+ }
330
+ $("save").addEventListener("click", function () {
331
+ var a = document.createElement("a");
332
+ a.href = URL.createObjectURL(new Blob([JSON.stringify(edited(), null, 1) + "\n"], { type: "application/json" }));
333
+ a.download = "layout.json"; a.click(); URL.revokeObjectURL(a.href);
334
+ });
335
+ $("copy").addEventListener("click", function () { navigator.clipboard.writeText($("calls").value).then(function () { say("copied"); }); });
336
+ $("reset").addEventListener("click", function () { past.push(copy(edited())); redraw(copy(orig), true); });
337
+ $("undo").addEventListener("click", undo);
338
+ $("turn").addEventListener("click", function () { turn(STEP); later(); });
339
+ $("back").addEventListener("click", function () { turn(-STEP); later(); });
340
+ $("flip").addEventListener("click", flip);
341
+ if ($("done")) { $("done").addEventListener("click", function () {
342
+ fetch(exact + "done", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(edited()) })
343
+ .then(function () { say("The layout went back to Python. This page can be closed."); });
344
+ }); }
345
+ read();
346
+ window.arrange = { items: function () { return items; }, edited: edited, calls: calls, show: show, pick: pick, turn: turn, flip: flip, done: done, undo: undo };
347
+ })();
bindview/arrange.py ADDED
@@ -0,0 +1,248 @@
1
+ """A figure arranged by hand: residues and the key are dragged, turned and flipped in a browser.
2
+
3
+ ::
4
+
5
+ graph = diagram.arrange() # opens a browser; hands the layout back when the page is done
6
+ figure = diagram.render(graph=graph)
7
+
8
+ diagram.arrange("arrange.html") # the same as one file, to open or to send
9
+
10
+ Drag a residue, or the key, to another place. With a residue picked, the wheel or ``r`` / ``shift``+``r`` turns it, ``f``
11
+ flips it, the arrow keys nudge it, a double click puts it back, and ``cmd``/``ctrl``+``z`` undoes.
12
+
13
+ **What follows.** While a residue is dragged the page shows a preview: the lines of its contacts, the arc of an eyelash,
14
+ the spokes on the atoms of the ligand and the tip of a bubble go with it. When it is let go, bindview draws the figure
15
+ from the moved layout (``render(graph=...)``), so that all that depends on a place is where it belongs: the lining of the
16
+ pocket, the lines broken around words, names and distances, the frame; and the page says where two things overlap. The
17
+ one file has no bindview behind it and stays with the preview.
18
+
19
+ **What comes out** is a layout (:class:`~bindview.Graph`), the same that ``graph.move``, ``graph.rotate`` and
20
+ ``graph.flip`` make in Python. The page writes those calls, to copy, and saves the layout as the JSON that
21
+ ``Graph.from_json`` and ``bindview render --layout`` read.
22
+
23
+ The page is served on 127.0.0.1 only, under an address that cannot be guessed, answers requests of its own page and no
24
+ other, and stops when it is done. Standard library, and nothing from the network.
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import hmac
30
+ import html
31
+ import json
32
+ import math
33
+ import secrets
34
+ import sys
35
+ import threading
36
+ import webbrowser
37
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
38
+ from importlib import resources
39
+ from pathlib import Path
40
+ from typing import TYPE_CHECKING, Any
41
+
42
+ from .errors import BindviewError, GraphError, RenderError
43
+ from .graph import Graph
44
+
45
+ if TYPE_CHECKING:
46
+ from .diagram import Diagram, RenderResult
47
+
48
+ __all__ = ["page", "serve"]
49
+
50
+ #: The most a request of the page may hold: a layout is some tens of kilobytes.
51
+ _LARGEST = 16_000_000
52
+
53
+ _STYLE = """
54
+ body{font:15px/1.5 -apple-system,'Segoe UI',Helvetica,Arial,sans-serif;color:#1f2933;margin:0;background:#f5f7fa}
55
+ main{max-width:1100px;margin:0 auto;padding:20px 20px 60px}h1{font-size:22px;margin:0 0 4px}p{margin:4px 0 10px;max-width:90ch}
56
+ #figure{background:#fff;border:1px solid #d9e2ec;border-radius:8px;padding:10px;touch-action:none;overflow:auto}
57
+ #figure svg{display:block;max-width:100%;height:auto;margin:0 auto;user-select:none;-webkit-user-select:none;overflow:visible}
58
+ .picked{filter:drop-shadow(0 0 3px #f59e0b) drop-shadow(0 0 6px #f59e0b)}
59
+ .bar{display:flex;flex-wrap:wrap;gap:8px;align-items:center;margin:10px 0}button{font:inherit;padding:5px 12px;border:1px solid
60
+ #9aa5b1;border-radius:6px;background:#fff;cursor:pointer}button:hover{background:#eef2f6}#which{font-weight:600}#said{color:#9a3412}
61
+ textarea{width:100%;height:112px;font:13px/1.45 ui-monospace,Menlo,monospace;border:1px solid #d9e2ec;border-radius:6px;padding:8px;
62
+ box-sizing:border-box;background:#fff}kbd{font:12px ui-monospace,Menlo,monospace;border:1px solid #cbd2d9;border-radius:4px;
63
+ padding:0 4px;background:#fff}
64
+ """
65
+
66
+
67
+ def _size(length: "str | None") -> "int | None":
68
+ """The ``Content-Length`` of a request as a size that is read, or None: the digits 0 to 9 (``"\u00b2".isdigit()``
69
+ is true, and ``int`` refuses it), no more of them than the largest size has, and not above that."""
70
+ if not length or not (length.isascii() and length.isdigit()) or len(length) > len(str(_LARGEST)):
71
+ return None
72
+ return int(length) if int(length) <= _LARGEST else None
73
+
74
+
75
+ def _finite(number: str) -> float:
76
+ """A number of a layout as it is read from JSON: ``Infinity``, ``NaN`` and ``1e999`` are none."""
77
+ value = float(number)
78
+ if not math.isfinite(value):
79
+ raise ValueError(f"{number} is no number that a layout has")
80
+ return value
81
+
82
+
83
+ def _bonds(diagram: "Diagram") -> dict[str, list[str]]:
84
+ """For each atom of the ligand those it is bonded to: the spokes of a contact keep clear of the bonds."""
85
+ names = diagram.ligand.names
86
+ return {f"L:{names[a.GetIdx()]}": [f"L:{names[b.GetIdx()]}" for b in a.GetNeighbors() if b.GetAtomicNum() > 1]
87
+ for a in diagram.ligand.mol.GetAtoms() if a.GetAtomicNum() > 1}
88
+
89
+
90
+ def _first(diagram: "Diagram", options: dict[str, Any]) -> "tuple[RenderResult, Graph]":
91
+ """The figure that the page starts from, and its layout."""
92
+ result = diagram.render(**options)
93
+ if result.graph is None or result.svg is None:
94
+ raise RenderError(f"there is nothing to arrange: the figure is {result.status}")
95
+ return result, result.graph
96
+
97
+
98
+ def _html(diagram: "Diagram", title: str, behind: "str | None", options: dict[str, Any],
99
+ first: "tuple[RenderResult, Graph] | None" = None) -> str:
100
+ """The page. ``behind``: the address of the bindview that draws what is let go; None for the one file.
101
+ ``first``: the figure it starts from, where that is drawn already."""
102
+ result, graph = first or _first(diagram, options)
103
+ # (Not one "<" in the block of data: "</script" would end it, and "<!--" with "<script" would keep it open.)
104
+ given = json.dumps({"graph": graph.to_dict(), "bonds": _bonds(diagram),
105
+ "svg": result.svg if behind is None else ""}).replace("<", "\\u003c")
106
+ script = resources.files(__package__).joinpath("arrange.js").read_text(encoding="utf-8")
107
+ how = ("When it is let go, bindview draws the figure from the new layout." if behind else
108
+ "This file shows a preview; bindview draws the figure from the layout that is saved.")
109
+ return f"""<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width">
110
+ <title>{html.escape(title)}</title><style>{_STYLE}</style></head><body><main><h1>{html.escape(title)}</h1>
111
+ <p>Drag a residue or the key. With a residue picked, the wheel or <kbd>r</kbd> / <kbd>shift</kbd>+<kbd>r</kbd> turns it,
112
+ <kbd>f</kbd> flips it, the arrow keys nudge it; a double click puts it back, <kbd>cmd</kbd>/<kbd>ctrl</kbd>+<kbd>z</kbd> undoes.
113
+ {how}</p>
114
+ <div class="bar"><span>Picked: <span id="which">nothing</span></span><button id="back">Turn &#8634;</button>
115
+ <button id="turn">Turn &#8635;</button><button id="flip">Flip</button><button id="undo">Undo</button>
116
+ <button id="reset">Put all back</button><button id="save">Save layout.json</button>{'<button id="done">Done</button>' if behind else ''}
117
+ <span id="said"></span></div>
118
+ <div id="figure">{result.svg}</div>
119
+ <div class="bar"><span>The calls that make it:</span><button id="copy">Copy</button></div><textarea id="calls" readonly></textarea>
120
+ <p>Or from the saved file: <code>diagram.render(graph=Graph.from_json("layout.json"))</code>, or
121
+ <code>bindview render MODEL --ligand LIG --layout layout.json</code>.</p></main>
122
+ <script type="application/json" id="graph">{given}</script>
123
+ <script>window.EXACT = {json.dumps(behind)};</script><script>{script}</script></body></html>
124
+ """
125
+
126
+
127
+ def page(diagram: "Diagram", path: "str | Path", title: "str | None" = None, **options: Any) -> Path:
128
+ """Write the page as one file, with a preview and without bindview behind it. ``options``: those of ``render``."""
129
+ out = Path(path)
130
+ text = _html(diagram, title or _title(diagram), None, options)
131
+ try:
132
+ out.write_text(text, encoding="utf-8")
133
+ except OSError as exc:
134
+ raise RenderError(f"cannot write {out}: {exc}") from exc
135
+ return out
136
+
137
+
138
+ def _title(diagram: "Diagram") -> str:
139
+ return f"Arrange the figure{': ' + diagram.name if diagram.name else ''}"
140
+
141
+
142
+ class Server:
143
+ """The page with bindview behind it, on 127.0.0.1: what :func:`serve` opens and waits for."""
144
+
145
+ def __init__(self, diagram: "Diagram", title: "str | None" = None, port: int = 0, **options: Any) -> None:
146
+ self.diagram, self.title = diagram, title or _title(diagram)
147
+ self.options = {k: v for k, v in options.items() if k != "graph"} # the first figure's; then the page's own
148
+ self.key = secrets.token_urlsafe(18)
149
+ #: The layout as the page had it when it was done.
150
+ self.graph: "Graph | None" = None
151
+ self.over = threading.Event()
152
+ self._drawing = threading.Lock()
153
+ first = _first(diagram, options) # a figure that cannot be arranged says so here
154
+ #: The page moves, turns and flips: a layout that comes back has the bond length of the first figure.
155
+ self._bond_length = first[1].bond_length
156
+ self._page = _html(diagram, self.title, f"/{self.key}/", options, first)
157
+ server = self
158
+
159
+ class Handler(BaseHTTPRequestHandler):
160
+ def log_message(self, format: str, *args: Any) -> None: # noqa: A002 (the name it has there)
161
+ pass
162
+
163
+ def answer(self, code: int, body: str, kind: str) -> None:
164
+ data = body.encode("utf-8")
165
+ self.send_response(code)
166
+ for name, value in (("Content-Type", f"{kind}; charset=utf-8"), ("Content-Length", str(len(data))),
167
+ ("Cache-Control", "no-store"), ("X-Content-Type-Options", "nosniff"),
168
+ ("Referrer-Policy", "no-referrer")):
169
+ self.send_header(name, value)
170
+ self.end_headers()
171
+ self.wfile.write(data)
172
+
173
+ def asked(self) -> "str | None":
174
+ """What is asked of the page by the page: ``""`` for the page itself, else the word after the key
175
+ (the path is ``/KEY/WORD`` and nothing more). None for another host, origin, key or path."""
176
+ host = f"127.0.0.1:{server.port}"
177
+ parts = self.path.split("/")
178
+ if (self.headers.get("Host") != host or self.headers.get("Origin") not in (None, f"http://{host}")
179
+ or len(parts) != 3 or parts[0]
180
+ or not hmac.compare_digest(parts[1].encode("utf-8"), server.key.encode("utf-8"))):
181
+ return None
182
+ return parts[2]
183
+
184
+ def do_GET(self) -> None: # noqa: N802
185
+ if self.asked() == "":
186
+ self.answer(200, server._page, "text/html")
187
+ else:
188
+ self.answer(404, "not here", "text/plain")
189
+
190
+ def do_POST(self) -> None: # noqa: N802
191
+ size = _size(self.headers.get("Content-Length"))
192
+ what = self.asked()
193
+ if what not in ("render", "done") or size is None:
194
+ self.answer(404, "not here", "text/plain")
195
+ return
196
+ body = server.answer(what, self.rfile.read(size))
197
+ self.answer(400 if "error" in body else 200, json.dumps(body), "application/json")
198
+ if what == "done" and "error" not in body:
199
+ server.over.set()
200
+
201
+ self._http = ThreadingHTTPServer(("127.0.0.1", port), Handler)
202
+ self.port = int(self._http.server_address[1])
203
+ self.address = f"http://127.0.0.1:{self.port}/{self.key}/"
204
+ threading.Thread(target=self._http.serve_forever, daemon=True).start()
205
+
206
+ def answer(self, what: str, body: bytes) -> dict[str, Any]:
207
+ """What the page is told: the figure of a layout, or that the layout has been taken; or, as ``error``, why
208
+ the layout is refused. A layout that the page cannot have sent is refused before it is drawn."""
209
+ try:
210
+ graph = Graph.from_dict(json.loads(body, parse_float=_finite, parse_constant=_finite))
211
+ if not math.isclose(graph.bond_length, self._bond_length, rel_tol=1e-9, abs_tol=0.0):
212
+ raise GraphError(f"the layout has a bond length of {graph.bond_length:g}, and the figure on the page "
213
+ f"one of {self._bond_length:g}, which the page does not change")
214
+ if what == "done":
215
+ self.graph = graph
216
+ return {}
217
+ with self._drawing:
218
+ made = self.diagram.render(graph=graph, **{**self.options, "on_unreadable": "render"})
219
+ except RecursionError:
220
+ return {"error": "This cannot be drawn: the layout is nested deeper than a layout is"}
221
+ except (BindviewError, ValueError, TypeError, LookupError, ArithmeticError) as exc:
222
+ return {"error": f"This cannot be drawn: {exc}"}
223
+ q = made.quality
224
+ wrong = [] if q is None else [f"{n} {word}{'s' if n != 1 else ''}" for n, word in (
225
+ (q.overlaps, "overlap"), (q.link_hits, "line across a residue")) if n]
226
+ return {"svg": made.svg, "graph": made.graph.to_dict() if made.graph is not None else None,
227
+ "said": f"Drawn all the same: {', '.join(wrong)}." if wrong else ""}
228
+
229
+ def close(self) -> None:
230
+ self._http.shutdown()
231
+ self._http.server_close()
232
+
233
+
234
+ def serve(diagram: "Diagram", title: "str | None" = None, *, port: int = 0, browser: bool = True, **options: Any
235
+ ) -> "Graph | None":
236
+ """Open the page with bindview behind it, and hand back the layout when it is done (None if it is stopped with
237
+ Ctrl-C). ``options``: those of ``render``."""
238
+ server = Server(diagram, title, port, **options)
239
+ try:
240
+ print(f"arrange the figure at {server.address}", file=sys.stderr, flush=True)
241
+ if browser:
242
+ webbrowser.open(server.address)
243
+ server.over.wait()
244
+ except KeyboardInterrupt:
245
+ pass
246
+ finally:
247
+ server.close()
248
+ return server.graph