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/geometry.py
ADDED
|
@@ -0,0 +1,482 @@
|
|
|
1
|
+
"""Pure 2D geometry. No chemistry, no drawing, no state -- unit-tested on its own.
|
|
2
|
+
|
|
3
|
+
Scalars and small tuples are used for one-off computations; the layout engine's
|
|
4
|
+
hot loops use the NumPy variants at the bottom of the file.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import math
|
|
10
|
+
from typing import Iterable, Sequence
|
|
11
|
+
|
|
12
|
+
import numpy as np
|
|
13
|
+
|
|
14
|
+
__all__ = [
|
|
15
|
+
"Point", "Box", "dist", "sub", "add", "mul", "dot", "cross", "norm", "unit", "perp", "lerp", "rotate",
|
|
16
|
+
"angle_of", "angle_diff", "box_of", "box_union", "box_expand", "boxes_overlap", "point_in_box",
|
|
17
|
+
"point_segment_distance", "segment_segment_distance", "segments_intersect",
|
|
18
|
+
"segment_box_entry", "largest_angular_gap", "free_direction",
|
|
19
|
+
"capsule_gaps", "segments_distance", "points_segments_distance", "marching_squares", "polyline_length", "resample_closed",
|
|
20
|
+
"spread_on_circle", "spread_on_line", "polygon_area",
|
|
21
|
+
]
|
|
22
|
+
|
|
23
|
+
Point = tuple[float, float]
|
|
24
|
+
Box = tuple[float, float, float, float] # x0, y0, x1, y1 with x0 <= x1, y0 <= y1
|
|
25
|
+
|
|
26
|
+
_EPS = 1e-12
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
# -- vectors ---------------------------------------------------------------
|
|
30
|
+
|
|
31
|
+
def add(a: Point, b: Point) -> Point:
|
|
32
|
+
return (a[0] + b[0], a[1] + b[1])
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def sub(a: Point, b: Point) -> Point:
|
|
36
|
+
return (a[0] - b[0], a[1] - b[1])
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def mul(a: Point, k: float) -> Point:
|
|
40
|
+
return (a[0] * k, a[1] * k)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def dot(a: Point, b: Point) -> float:
|
|
44
|
+
return a[0] * b[0] + a[1] * b[1]
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def cross(a: Point, b: Point) -> float:
|
|
48
|
+
return a[0] * b[1] - a[1] * b[0]
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def norm(a: Point) -> float:
|
|
52
|
+
return math.hypot(a[0], a[1])
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def dist(a: Point, b: Point) -> float:
|
|
56
|
+
return math.hypot(a[0] - b[0], a[1] - b[1])
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def unit(a: Point, fallback: Point = (1.0, 0.0)) -> Point:
|
|
60
|
+
n = math.hypot(a[0], a[1])
|
|
61
|
+
if n < _EPS:
|
|
62
|
+
return fallback
|
|
63
|
+
return (a[0] / n, a[1] / n)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def perp(a: Point) -> Point:
|
|
67
|
+
"""Rotate by +90 degrees (counter-clockwise in a y-up frame)."""
|
|
68
|
+
return (-a[1], a[0])
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def lerp(a: Point, b: Point, t: float) -> Point:
|
|
72
|
+
return (a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def rotate(a: Point, angle: float) -> Point:
|
|
76
|
+
c, s = math.cos(angle), math.sin(angle)
|
|
77
|
+
return (a[0] * c - a[1] * s, a[0] * s + a[1] * c)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def angle_of(a: Point) -> float:
|
|
81
|
+
return math.atan2(a[1], a[0])
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def angle_diff(a: float, b: float) -> float:
|
|
85
|
+
"""Smallest signed difference ``a - b`` wrapped to (-pi, pi]."""
|
|
86
|
+
d = (a - b) % (2.0 * math.pi)
|
|
87
|
+
if d > math.pi:
|
|
88
|
+
d -= 2.0 * math.pi
|
|
89
|
+
return d
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
# -- boxes -----------------------------------------------------------------
|
|
93
|
+
|
|
94
|
+
def box_of(points: Iterable[Point]) -> Box:
|
|
95
|
+
xs, ys = zip(*points)
|
|
96
|
+
return (min(xs), min(ys), max(xs), max(ys))
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def box_union(boxes: Iterable[Box]) -> Box:
|
|
100
|
+
bs = list(boxes)
|
|
101
|
+
return (min(b[0] for b in bs), min(b[1] for b in bs), max(b[2] for b in bs), max(b[3] for b in bs))
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def box_expand(b: Box, pad: float) -> Box:
|
|
105
|
+
return (b[0] - pad, b[1] - pad, b[2] + pad, b[3] + pad)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def boxes_overlap(a: Box, b: Box, pad: float = 0.0) -> bool:
|
|
109
|
+
return a[0] < b[2] + pad and b[0] < a[2] + pad and a[1] < b[3] + pad and b[1] < a[3] + pad
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def point_in_box(p: Point, b: Box) -> bool:
|
|
113
|
+
return b[0] <= p[0] <= b[2] and b[1] <= p[1] <= b[3]
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
# -- segments --------------------------------------------------------------
|
|
117
|
+
|
|
118
|
+
def point_segment_distance(p: Point, a: Point, b: Point) -> float:
|
|
119
|
+
ab = sub(b, a)
|
|
120
|
+
l2 = dot(ab, ab)
|
|
121
|
+
if l2 < _EPS:
|
|
122
|
+
return dist(p, a)
|
|
123
|
+
t = max(0.0, min(1.0, dot(sub(p, a), ab) / l2))
|
|
124
|
+
return dist(p, (a[0] + ab[0] * t, a[1] + ab[1] * t))
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def segments_intersect(a: Point, b: Point, c: Point, d: Point) -> bool:
|
|
128
|
+
"""Proper intersection: the open segments cross at a single interior point."""
|
|
129
|
+
d1 = cross(sub(b, a), sub(c, a))
|
|
130
|
+
d2 = cross(sub(b, a), sub(d, a))
|
|
131
|
+
d3 = cross(sub(d, c), sub(a, c))
|
|
132
|
+
d4 = cross(sub(d, c), sub(b, c))
|
|
133
|
+
return ((d1 > 0) != (d2 > 0)) and ((d3 > 0) != (d4 > 0)) and \
|
|
134
|
+
abs(d1) > _EPS and abs(d2) > _EPS and abs(d3) > _EPS and abs(d4) > _EPS
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def segment_segment_distance(a: Point, b: Point, c: Point, d: Point) -> float:
|
|
138
|
+
if segments_intersect(a, b, c, d):
|
|
139
|
+
return 0.0
|
|
140
|
+
return min(point_segment_distance(a, c, d), point_segment_distance(b, c, d),
|
|
141
|
+
point_segment_distance(c, a, b), point_segment_distance(d, a, b))
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def segment_box_entry(outside: Point, inside: Point, box: Box) -> Point:
|
|
145
|
+
"""Walking from ``outside`` toward ``inside`` (a point in ``box``), the point
|
|
146
|
+
where the segment first meets the box. Returns ``outside`` if it already
|
|
147
|
+
lies in the box, ``inside`` if the segment never meets it."""
|
|
148
|
+
if point_in_box(outside, box):
|
|
149
|
+
return outside
|
|
150
|
+
dx, dy = inside[0] - outside[0], inside[1] - outside[1]
|
|
151
|
+
t0, t1 = 0.0, 1.0
|
|
152
|
+
for p, q in ((-dx, outside[0] - box[0]), (dx, box[2] - outside[0]),
|
|
153
|
+
(-dy, outside[1] - box[1]), (dy, box[3] - outside[1])):
|
|
154
|
+
if abs(p) < _EPS:
|
|
155
|
+
if q < 0:
|
|
156
|
+
return inside
|
|
157
|
+
continue
|
|
158
|
+
r = q / p
|
|
159
|
+
if p < 0:
|
|
160
|
+
if r > t1:
|
|
161
|
+
return inside
|
|
162
|
+
t0 = max(t0, r)
|
|
163
|
+
else:
|
|
164
|
+
if r < t0:
|
|
165
|
+
return inside
|
|
166
|
+
t1 = min(t1, r)
|
|
167
|
+
return (outside[0] + dx * t0, outside[1] + dy * t0)
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
# -- directions around a point ---------------------------------------------
|
|
171
|
+
|
|
172
|
+
def largest_angular_gap(angles: Sequence[float]) -> tuple[float, float]:
|
|
173
|
+
"""``(mid_angle, width)`` of the widest gap between the given directions."""
|
|
174
|
+
if not angles:
|
|
175
|
+
return (0.0, 2.0 * math.pi)
|
|
176
|
+
srt = sorted(a % (2.0 * math.pi) for a in angles)
|
|
177
|
+
best_w, best_mid = -1.0, 0.0
|
|
178
|
+
for i, a in enumerate(srt):
|
|
179
|
+
b = srt[(i + 1) % len(srt)]
|
|
180
|
+
w = (b - a) % (2.0 * math.pi)
|
|
181
|
+
if len(srt) == 1:
|
|
182
|
+
w = 2.0 * math.pi
|
|
183
|
+
if w > best_w + 1e-9:
|
|
184
|
+
best_w, best_mid = w, a + w / 2.0
|
|
185
|
+
return (best_mid % (2.0 * math.pi), best_w)
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def free_direction(centre: Point, neighbours: Sequence[Point]) -> Point:
|
|
189
|
+
"""Unit vector pointing into the widest gap between ``neighbours`` as seen from ``centre``."""
|
|
190
|
+
angles = [angle_of(sub(n, centre)) for n in neighbours if dist(n, centre) > _EPS]
|
|
191
|
+
mid, _ = largest_angular_gap(angles)
|
|
192
|
+
return (math.cos(mid), math.sin(mid))
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
# -- NumPy kernels ---------------------------------------------------------
|
|
196
|
+
|
|
197
|
+
# (The kernels below work on x and y apart. The layout engine spends most of its time in them, and a trailing
|
|
198
|
+
# axis of two costs several times what the arithmetic does. Every sum is of two terms, so the numbers are the
|
|
199
|
+
# same to the last bit as with ``(v * w).sum(-1)``; ``tests/test_layout.py`` holds them to that.)
|
|
200
|
+
|
|
201
|
+
def points_segments_distance(points: np.ndarray, a: np.ndarray, b: np.ndarray) -> np.ndarray:
|
|
202
|
+
"""Distance from each of ``points`` ``(P, 2)`` to each segment ``a[i]->b[i]`` ``(S, 2)``: ``(P, S)``."""
|
|
203
|
+
ax, ay = a[:, 0], a[:, 1]
|
|
204
|
+
abx, aby = b[:, 0] - ax, b[:, 1] - ay # (S,)
|
|
205
|
+
l2 = np.maximum(abx * abx + aby * aby, _EPS)
|
|
206
|
+
px, py = points[:, 0][:, None], points[:, 1][:, None] # (P, 1)
|
|
207
|
+
t = ((px - ax) * abx + (py - ay) * aby) / l2
|
|
208
|
+
np.clip(t, 0.0, 1.0, out=t)
|
|
209
|
+
dx, dy = px - (ax + abx * t), py - (ay + aby * t)
|
|
210
|
+
return np.sqrt(dx * dx + dy * dy)
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def _seg_seg_dist_arrays(p1: np.ndarray, q1: np.ndarray, p2: np.ndarray, q2: np.ndarray) -> np.ndarray:
|
|
214
|
+
"""Pairwise segment-segment distance, broadcast over leading dimensions.
|
|
215
|
+
|
|
216
|
+
Closest-points formulation (Ericson, *Real-Time Collision Detection*, 5.1.9)
|
|
217
|
+
with every degenerate case handled explicitly: either segment, or both, may
|
|
218
|
+
have zero length -- a disc is a capsule whose segment is a point.
|
|
219
|
+
"""
|
|
220
|
+
p1x, p1y, p2x, p2y = p1[..., 0], p1[..., 1], p2[..., 0], p2[..., 1]
|
|
221
|
+
d1x, d1y = q1[..., 0] - p1x, q1[..., 1] - p1y
|
|
222
|
+
d2x, d2y = q2[..., 0] - p2x, q2[..., 1] - p2y
|
|
223
|
+
rx, ry = p1x - p2x, p1y - p2y
|
|
224
|
+
a = d1x * d1x + d1y * d1y # squared length of segment 1
|
|
225
|
+
e = d2x * d2x + d2y * d2y # squared length of segment 2
|
|
226
|
+
f = d2x * rx + d2y * ry
|
|
227
|
+
c = d1x * rx + d1y * ry
|
|
228
|
+
b = d1x * d2x + d1y * d2y
|
|
229
|
+
a_ok = a > _EPS
|
|
230
|
+
e_ok = e > _EPS
|
|
231
|
+
safe_a = np.where(a_ok, a, 1.0)
|
|
232
|
+
safe_e = np.where(e_ok, e, 1.0)
|
|
233
|
+
denom = a * e - b * b
|
|
234
|
+
# General case: closest point on line 1 to line 2, clamped to segment 1.
|
|
235
|
+
s = np.where(denom > _EPS, np.clip((b * f - c * e) / np.where(denom > _EPS, denom, 1.0), 0.0, 1.0), 0.0)
|
|
236
|
+
# Segment 2 is a point: the answer is the closest point of segment 1 to it.
|
|
237
|
+
s = np.where(e_ok, s, np.clip(-c / safe_a, 0.0, 1.0))
|
|
238
|
+
t = np.where(e_ok, (b * s + f) / safe_e, 0.0)
|
|
239
|
+
# Where t leaves [0, 1], clamp it and recompute s for the clamped end point.
|
|
240
|
+
s = np.where(t < 0.0, np.clip(-c / safe_a, 0.0, 1.0), s)
|
|
241
|
+
s = np.where(t > 1.0, np.clip((b - c) / safe_a, 0.0, 1.0), s)
|
|
242
|
+
t = np.clip(t, 0.0, 1.0)
|
|
243
|
+
# Segment 1 is a point: s is irrelevant, t is the closest point of segment 2 to it.
|
|
244
|
+
s = np.where(a_ok, s, 0.0)
|
|
245
|
+
t = np.where(a_ok, t, np.where(e_ok, np.clip(f / safe_e, 0.0, 1.0), 0.0))
|
|
246
|
+
dx, dy = (p1x + d1x * s) - (p2x + d2x * t), (p1y + d1y * s) - (p2y + d2y * t)
|
|
247
|
+
return np.sqrt(dx * dx + dy * dy)
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def segments_distance(p1: np.ndarray, q1: np.ndarray, p2: np.ndarray, q2: np.ndarray) -> np.ndarray:
|
|
251
|
+
"""Segment-to-segment distance, broadcasting over leading dimensions."""
|
|
252
|
+
return _seg_seg_dist_arrays(p1, q1, p2, q2)
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def capsule_gaps(a0: np.ndarray, a1: np.ndarray, ra: np.ndarray,
|
|
256
|
+
b0: np.ndarray, b1: np.ndarray, rb: np.ndarray) -> np.ndarray:
|
|
257
|
+
"""Clearance between every capsule of set A and every capsule of set B.
|
|
258
|
+
|
|
259
|
+
A capsule is a segment ``p0->p1`` swept by a disc of radius ``r`` (a disc is
|
|
260
|
+
a capsule with ``p0 == p1``). Returns ``(len(A), len(B))``; negative values
|
|
261
|
+
are penetration depths.
|
|
262
|
+
"""
|
|
263
|
+
if len(a0) == 0 or len(b0) == 0:
|
|
264
|
+
return np.zeros((len(a0), len(b0)))
|
|
265
|
+
d = _seg_seg_dist_arrays(a0[:, None, :], a1[:, None, :], b0[None, :, :], b1[None, :, :])
|
|
266
|
+
return d - ra[:, None] - rb[None, :]
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
# -- contours --------------------------------------------------------------
|
|
270
|
+
|
|
271
|
+
def polyline_length(points: np.ndarray, closed: bool = False) -> float:
|
|
272
|
+
if len(points) < 2:
|
|
273
|
+
return 0.0
|
|
274
|
+
seg = np.diff(points, axis=0)
|
|
275
|
+
total = float(np.linalg.norm(seg, axis=1).sum())
|
|
276
|
+
if closed:
|
|
277
|
+
total += float(np.linalg.norm(points[0] - points[-1]))
|
|
278
|
+
return total
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def polygon_area(points: np.ndarray) -> float:
|
|
282
|
+
"""Signed area (positive when counter-clockwise in a y-up frame)."""
|
|
283
|
+
x, y = points[:, 0], points[:, 1]
|
|
284
|
+
return 0.5 * float(np.sum(x * np.roll(y, -1) - np.roll(x, -1) * y))
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def resample_closed(points: np.ndarray, spacing: float) -> np.ndarray:
|
|
288
|
+
"""Resample a closed polyline at (approximately) uniform arc-length ``spacing``."""
|
|
289
|
+
pts = np.vstack([points, points[:1]])
|
|
290
|
+
seg = np.linalg.norm(np.diff(pts, axis=0), axis=1)
|
|
291
|
+
cum = np.concatenate([[0.0], np.cumsum(seg)])
|
|
292
|
+
total = cum[-1]
|
|
293
|
+
n = max(8, int(round(total / spacing)))
|
|
294
|
+
targets = np.linspace(0.0, total, n, endpoint=False)
|
|
295
|
+
x = np.interp(targets, cum, pts[:, 0])
|
|
296
|
+
y = np.interp(targets, cum, pts[:, 1])
|
|
297
|
+
return np.column_stack([x, y])
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def marching_squares(field: np.ndarray, level: float, x0: float, y0: float, step: float) -> list[np.ndarray]:
|
|
301
|
+
"""Closed iso-contours of ``field`` (indexed ``[iy, ix]``) at ``level``.
|
|
302
|
+
|
|
303
|
+
Grid node ``(ix, iy)`` sits at ``(x0 + ix*step, y0 + iy*step)``. Contours
|
|
304
|
+
that would leave the grid are dropped: callers pad the grid so the level
|
|
305
|
+
set of interest closes inside it. Returned loops are ``(n, 2)`` arrays,
|
|
306
|
+
ordered longest first, deterministic for a given field.
|
|
307
|
+
"""
|
|
308
|
+
ny, nx = field.shape
|
|
309
|
+
inside = field < level
|
|
310
|
+
edges: dict[tuple[int, int, int], tuple[float, float]] = {}
|
|
311
|
+
|
|
312
|
+
def crossing(ix: int, iy: int, horizontal: bool) -> tuple[float, float]:
|
|
313
|
+
# Edge from node (ix, iy) to its +x (horizontal) or +y neighbour.
|
|
314
|
+
key = (ix, iy, 0 if horizontal else 1)
|
|
315
|
+
hit = edges.get(key)
|
|
316
|
+
if hit is None:
|
|
317
|
+
v0 = field[iy, ix]
|
|
318
|
+
v1 = field[iy, ix + 1] if horizontal else field[iy + 1, ix]
|
|
319
|
+
t = 0.5 if abs(v1 - v0) < _EPS else float((level - v0) / (v1 - v0))
|
|
320
|
+
t = min(1.0, max(0.0, t))
|
|
321
|
+
hit = (x0 + (ix + (t if horizontal else 0.0)) * step, y0 + (iy + (0.0 if horizontal else t)) * step)
|
|
322
|
+
edges[key] = hit
|
|
323
|
+
return hit
|
|
324
|
+
|
|
325
|
+
# Each cell contributes 0, 1 or 2 directed segments between edge crossings.
|
|
326
|
+
# Edge ids within a cell: 0 bottom, 1 right, 2 top, 3 left.
|
|
327
|
+
table = {
|
|
328
|
+
1: ((3, 0),), 2: ((0, 1),), 3: ((3, 1),), 4: ((1, 2),), 6: ((0, 2),), 7: ((3, 2),),
|
|
329
|
+
8: ((2, 3),), 9: ((2, 0),), 11: ((2, 1),), 12: ((1, 3),), 13: ((1, 0),), 14: ((0, 3),),
|
|
330
|
+
}
|
|
331
|
+
nxt: dict[tuple[int, int, int], tuple[int, int, int]] = {}
|
|
332
|
+
|
|
333
|
+
def edge_key(ix: int, iy: int, e: int) -> tuple[int, int, int]:
|
|
334
|
+
if e == 0:
|
|
335
|
+
return (ix, iy, 0)
|
|
336
|
+
if e == 1:
|
|
337
|
+
return (ix + 1, iy, 1)
|
|
338
|
+
if e == 2:
|
|
339
|
+
return (ix, iy + 1, 0)
|
|
340
|
+
return (ix, iy, 1)
|
|
341
|
+
|
|
342
|
+
for iy in range(ny - 1):
|
|
343
|
+
row0, row1 = inside[iy], inside[iy + 1]
|
|
344
|
+
for ix in range(nx - 1):
|
|
345
|
+
code = (1 if row0[ix] else 0) | (2 if row0[ix + 1] else 0) | (4 if row1[ix + 1] else 0) | (8 if row1[ix] else 0)
|
|
346
|
+
if code == 0 or code == 15:
|
|
347
|
+
continue
|
|
348
|
+
segs: tuple[tuple[int, int], ...]
|
|
349
|
+
if code == 5 or code == 10:
|
|
350
|
+
centre = 0.25 * (field[iy, ix] + field[iy, ix + 1] + field[iy + 1, ix] + field[iy + 1, ix + 1])
|
|
351
|
+
joined = centre < level
|
|
352
|
+
if code == 5:
|
|
353
|
+
segs = ((3, 2), (1, 0)) if joined else ((3, 0), (1, 2))
|
|
354
|
+
else:
|
|
355
|
+
segs = ((0, 3), (2, 1)) if joined else ((0, 1), (2, 3))
|
|
356
|
+
else:
|
|
357
|
+
segs = table[code]
|
|
358
|
+
for e_from, e_to in segs:
|
|
359
|
+
nxt[edge_key(ix, iy, e_from)] = edge_key(ix, iy, e_to)
|
|
360
|
+
|
|
361
|
+
loops: list[np.ndarray] = []
|
|
362
|
+
visited: set[tuple[int, int, int]] = set()
|
|
363
|
+
for start in sorted(nxt):
|
|
364
|
+
if start in visited:
|
|
365
|
+
continue
|
|
366
|
+
chain = [start]
|
|
367
|
+
visited.add(start)
|
|
368
|
+
cur = nxt[start]
|
|
369
|
+
closed = False
|
|
370
|
+
while True:
|
|
371
|
+
if cur == start:
|
|
372
|
+
closed = True
|
|
373
|
+
break
|
|
374
|
+
if cur in visited or cur not in nxt:
|
|
375
|
+
break
|
|
376
|
+
visited.add(cur)
|
|
377
|
+
chain.append(cur)
|
|
378
|
+
cur = nxt[cur]
|
|
379
|
+
if closed and len(chain) >= 4:
|
|
380
|
+
loops.append(np.array([crossing(k[0], k[1], k[2] == 0) for k in chain], dtype=float))
|
|
381
|
+
loops.sort(key=lambda p: (-polyline_length(p, closed=True), float(p[0, 0]), float(p[0, 1])))
|
|
382
|
+
return loops
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
# -- one-dimensional spreading ----------------------------------------------
|
|
386
|
+
|
|
387
|
+
def _pava(values: Sequence[float], weights: Sequence[float]) -> list[float]:
|
|
388
|
+
"""Weighted isotonic regression (non-decreasing) by pooling adjacent violators."""
|
|
389
|
+
blocks: list[list[float]] = [] # [weighted sum, weight, count]
|
|
390
|
+
for v, w in zip(values, weights):
|
|
391
|
+
blocks.append([v * w, w, 1])
|
|
392
|
+
while len(blocks) > 1 and blocks[-2][0] / blocks[-2][1] > blocks[-1][0] / blocks[-1][1] + 1e-15:
|
|
393
|
+
s, w2, c = blocks.pop()
|
|
394
|
+
blocks[-1][0] += s
|
|
395
|
+
blocks[-1][1] += w2
|
|
396
|
+
blocks[-1][2] += c
|
|
397
|
+
out: list[float] = []
|
|
398
|
+
for s, w, c in blocks:
|
|
399
|
+
out.extend([s / w] * int(c))
|
|
400
|
+
return out
|
|
401
|
+
|
|
402
|
+
|
|
403
|
+
def spread_on_line(targets: Sequence[float], widths: Sequence[float],
|
|
404
|
+
weights: Sequence[float] | None = None) -> list[float]:
|
|
405
|
+
"""Centres for intervals on a line, in the given order, without overlap.
|
|
406
|
+
|
|
407
|
+
Exact minimiser of the weighted squared displacement from ``targets``
|
|
408
|
+
subject to ``x[i+1] - x[i] >= (widths[i] + widths[i+1]) / 2``.
|
|
409
|
+
"""
|
|
410
|
+
n = len(targets)
|
|
411
|
+
if n == 0:
|
|
412
|
+
return []
|
|
413
|
+
w = list(weights) if weights is not None else [1.0] * n
|
|
414
|
+
offs = [0.0]
|
|
415
|
+
for i in range(1, n):
|
|
416
|
+
offs.append(offs[-1] + (widths[i - 1] + widths[i]) / 2.0)
|
|
417
|
+
y = _pava([t - o for t, o in zip(targets, offs)], w)
|
|
418
|
+
return [yi + o for yi, o in zip(y, offs)]
|
|
419
|
+
|
|
420
|
+
|
|
421
|
+
def spread_on_circle(targets: Sequence[float], widths: Sequence[float], period: float,
|
|
422
|
+
weights: Sequence[float] | None = None) -> list[float]:
|
|
423
|
+
"""Place intervals on a circle of circumference ``period`` without overlap.
|
|
424
|
+
|
|
425
|
+
Interval ``i`` has width ``widths[i]`` and would like its centre at
|
|
426
|
+
``targets[i]``. The cyclic order of the targets is preserved. The circle is
|
|
427
|
+
cut at each of the ``n`` possible places, the resulting line problem is
|
|
428
|
+
solved exactly, and the cheapest solution that also clears the cut is
|
|
429
|
+
returned. If the intervals cannot fit they are packed evenly in order.
|
|
430
|
+
"""
|
|
431
|
+
n = len(targets)
|
|
432
|
+
if n == 0:
|
|
433
|
+
return []
|
|
434
|
+
if n == 1:
|
|
435
|
+
return [targets[0] % period]
|
|
436
|
+
w = [max(v, 1e-9) for v in (weights if weights is not None else [1.0] * n)]
|
|
437
|
+
order = sorted(range(n), key=lambda i: (targets[i] % period, i))
|
|
438
|
+
t = [targets[i] % period for i in order]
|
|
439
|
+
wd = [widths[i] for i in order]
|
|
440
|
+
wt = [w[i] for i in order]
|
|
441
|
+
out = [0.0] * n
|
|
442
|
+
if sum(wd) >= period - 1e-9:
|
|
443
|
+
scale = period / sum(wd)
|
|
444
|
+
pos, acc = [], 0.0
|
|
445
|
+
for width in wd:
|
|
446
|
+
pos.append(acc + width * scale / 2.0)
|
|
447
|
+
acc += width * scale
|
|
448
|
+
shift = sum(angle_diff_period(ti, pi, period) * wi for ti, pi, wi in zip(t, pos, wt)) / sum(wt)
|
|
449
|
+
for k, i in enumerate(order):
|
|
450
|
+
out[i] = (pos[k] + shift) % period
|
|
451
|
+
return out
|
|
452
|
+
best: tuple[float, list[float], int] | None = None
|
|
453
|
+
for cut in range(n):
|
|
454
|
+
idx = list(range(cut, n)) + list(range(cut))
|
|
455
|
+
tt = [t[i] + (period if i < cut else 0.0) for i in idx]
|
|
456
|
+
xs = spread_on_line(tt, [wd[i] for i in idx], [wt[i] for i in idx])
|
|
457
|
+
if xs[0] + period - xs[-1] < (wd[idx[0]] + wd[idx[-1]]) / 2.0 - 1e-9:
|
|
458
|
+
continue
|
|
459
|
+
cost = sum(wt[i] * (x - ti) ** 2 for i, x, ti in zip(idx, xs, tt))
|
|
460
|
+
if best is None or cost < best[0] - 1e-12:
|
|
461
|
+
best = (cost, xs, cut)
|
|
462
|
+
if best is None:
|
|
463
|
+
# Fits in total but every cut is blocked: tighten from the least bad cut.
|
|
464
|
+
cut = 0
|
|
465
|
+
idx = list(range(n))
|
|
466
|
+
xs = spread_on_line(t, wd, wt)
|
|
467
|
+
over = (wd[0] + wd[-1]) / 2.0 - (xs[0] + period - xs[-1])
|
|
468
|
+
xs = [x - over * (k / (n - 1) - 0.5) for k, x in enumerate(xs)]
|
|
469
|
+
xs = spread_on_line(xs, wd, wt)
|
|
470
|
+
best = (0.0, xs, cut)
|
|
471
|
+
_, xs, cut = best
|
|
472
|
+
idx = list(range(cut, n)) + list(range(cut))
|
|
473
|
+
for k, x in zip(idx, xs):
|
|
474
|
+
out[order[k]] = x % period
|
|
475
|
+
return out
|
|
476
|
+
|
|
477
|
+
|
|
478
|
+
def angle_diff_period(a: float, b: float, period: float) -> float:
|
|
479
|
+
d = (a - b) % period
|
|
480
|
+
if d > period / 2.0:
|
|
481
|
+
d -= period
|
|
482
|
+
return d
|