QDpy
Loading...
Searching...
No Matches
_archive_geometry.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
4
5"""Geometry shared by static archive plots and animation frames."""
6
7from functools import lru_cache
8from itertools import combinations
9
10import numpy as np
11from scipy.spatial import Delaunay, QhullError, SphericalVoronoi, geometric_slerp
12
13
14def _clip_polygon(polygon, normal, offset):
15 margins = polygon @ normal - offset
16 inside = margins <= 0
17 vertices = []
18 for i in range(len(polygon)):
19 previous = i - 1
20 if inside[previous] != inside[i]:
21 fraction = margins[previous] / (margins[previous] - margins[i])
22 vertices.append(polygon[previous] + fraction * (polygon[i] - polygon[previous]))
23 if inside[i]:
24 vertices.append(polygon[i])
25 return np.asarray(vertices).reshape(-1, 2)
26
27
28def _neighbours(points):
29 """Use Delaunay edges for planar cells when all sites are represented."""
30 try:
31 simplices = Delaunay(points).simplices
32 except QhullError:
33 return None
34 neighbours = [set() for _ in points]
35 for simplex in simplices:
36 for i, j in combinations(simplex, 2):
37 neighbours[i].add(j)
38 neighbours[j].add(i)
39 return neighbours if all(neighbours) else None
40
41
42@lru_cache(maxsize=24)
43def _bounded_cells(centroids, limits, dimensions, section):
44 """Return original cell indices and polygon vertices in a descriptor plane."""
45 scale = max(np.max(np.abs(centroids)), np.max(np.abs(limits)), *(abs(x) for x in section), 1e-300)
46 sites = np.asarray(centroids) / scale
47 (xlo, xhi), (ylo, yhi) = np.asarray(limits) / scale
48 box = np.array([[xlo, ylo], [xhi, ylo], [xhi, yhi], [xlo, yhi]])
49 visible = sites[:, dimensions]
50 hidden = [i for i in range(sites.shape[1]) if i not in dimensions]
51 fixed = np.asarray(section) / scale
52 _, unique = np.unique(sites, axis=0, return_index=True)
53 unique = sorted(unique)
54 neighbours = _neighbours(visible[unique]) if not hidden and len(unique) >= 3 else None
55 result = []
56 for position, i in enumerate(unique):
57 polygon = box
58 rivals = unique if neighbours is None else [unique[j] for j in sorted(neighbours[position])]
59 for j in rivals:
60 if i == j:
61 continue
62 delta = sites[j] - sites[i]
63 normal = delta[list(dimensions)]
64 # Compare the full squared distances on the specified plane.
65 offset = delta @ sites[i] + (delta @ delta) / 2 - delta[hidden] @ fixed
66 if not np.any(normal):
67 if offset < 0 or (offset == 0 and j < i):
68 polygon = ()
69 break
70 continue
71 polygon = _clip_polygon(polygon, normal, offset)
72 if len(polygon) < 3:
73 break
74 if len(polygon) >= 3:
75 result.append((i, polygon * scale))
76 return result
77
78
79@lru_cache(maxsize=12)
80def _sphere_cells(centroids, bounds, centre):
81 """Tessellate a common-radius CVT on its sphere in raw descriptor space."""
82 sites = np.asarray(centroids) - centre
83 radii = np.linalg.norm(sites, axis=1)
84 radius = radii[0]
85 margin = radius * 1e-12
86 if (len(sites) < 4 or not np.isfinite(radius) or not radius
87 or not np.allclose(radii, radius, rtol=1e-7, atol=0)
88 or any(origin - radius < lo - margin or origin + radius > hi + margin
89 for (lo, hi), origin in zip(bounds, centre))):
90 return (), ()
91 unit = sites / radii[:, None]
92 try:
93 tessellation = SphericalVoronoi(unit)
94 tessellation.sort_vertices_of_regions()
95 except (ValueError, QhullError):
96 return (), ()
97 faces, edges = [], []
98 for cell, region in enumerate(tessellation.regions):
99 vertices = tessellation.vertices[region]
100 for a, b in zip(vertices, np.roll(vertices, -1, axis=0)):
101 edge = geometric_slerp(a, b, np.linspace(0, 1, 9))
102 edges.append(edge)
103 for start, stop in zip(edge, edge[1:]):
104 faces.append((cell, np.array([unit[cell], start, stop])))
105 return faces, edges