File size: 11,378 Bytes
8750b11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
"""
Self-contained module for checking if ideal polyhedron volume exceeds threshold.

Given complex vertices (including 0, 1, ∞, and k other points), determines
whether the volume of the associated ideal hyperbolic polyhedron is greater
than a specified threshold.

This module is completely self-contained and does not depend on other files
in the toolkit.

Usage:
    from ideal_poly_volume_toolkit.volume_threshold import volume_exceeds_threshold

    vertices = [0+0j, 1+0j, 0.5+0.5j]  # 0, 1, ∞ implicit
    result = volume_exceeds_threshold(vertices, threshold=1.0)
    # Returns: True if volume > threshold, False otherwise
"""

import numpy as np
from scipy.spatial import ConvexHull, Delaunay


# ============================================================================
# Stereographic projection utilities
# ============================================================================

def lift_to_sphere_with_inf(W: np.ndarray) -> np.ndarray:
    """
    Lift complex points to the unit sphere via inverse stereographic projection.

    Maps C βˆͺ {∞} β†’ SΒ² where:
    - Finite points w β†’ (2Re(w)/(|w|Β²+1), 2Im(w)/(|w|Β²+1), (|w|Β²-1)/(|w|Β²+1))
    - ∞ β†’ (0, 0, 1) (north pole)

    Args:
        W: Complex numpy array of vertices

    Returns:
        N x 3 array of points on unit sphere
    """
    P = np.zeros((W.shape[0], 3), dtype=np.float64)
    is_inf = ~np.isfinite(W.real) | ~np.isfinite(W.imag)
    F = ~is_inf
    w = W[F]
    r2 = (w.real**2 + w.imag**2)
    denom = r2 + 1.0
    P[F, 0] = 2.0 * w.real / denom
    P[F, 1] = 2.0 * w.imag / denom
    P[F, 2] = (r2 - 1.0) / denom
    P[is_inf] = np.array([0.0, 0.0, 1.0])
    return P


def inverse_stereographic_from_sphere_pts(X: np.ndarray) -> np.ndarray:
    """
    Project points from sphere back to complex plane via stereographic projection.

    Maps SΒ² β†’ C via w = (x + iy)/(1 - z)

    Args:
        X: N x 3 array of points on sphere

    Returns:
        Complex numpy array
    """
    x, y, z = X[:, 0], X[:, 1], X[:, 2]
    denom = (1.0 - z)
    return (x / denom) + 1j * (y / denom)


# ============================================================================
# Triangulation methods
# ============================================================================

def hull_tris_projected_back(W: np.ndarray, index_inf: int = 0) -> list:
    """
    Compute triangulation by lifting to sphere, taking convex hull, projecting back.

    This handles vertices including ∞ by working on the sphere where all points
    are finite. Triangles containing ∞ are excluded from the result.

    Args:
        W: Complex array of all vertices (including ∞)
        index_inf: Index of the vertex at infinity

    Returns:
        List of triangles, each a tuple of 3 complex numbers
    """
    P3 = lift_to_sphere_with_inf(W)
    hull = ConvexHull(P3)
    tris = []
    for f in hull.simplices:
        if index_inf in f:
            continue
        X = P3[np.asarray(f)]
        tri = tuple(inverse_stereographic_from_sphere_pts(X))
        tris.append(tri)
    return tris


def delaunay_triangulation_indices(z_finite: np.ndarray) -> np.ndarray:
    """
    Compute Delaunay triangulation of finite complex points.

    Args:
        z_finite: Complex array of finite vertices (no ∞)

    Returns:
        M x 3 array of triangle vertex indices
    """
    pts = np.column_stack([z_finite.real, z_finite.imag])
    tri = Delaunay(pts)
    return tri.simplices.astype(np.int64)


# ============================================================================
# Lobachevsky function (Ξ›) and triangle volume
# ============================================================================

def _lob_value_series(theta: float, n: int = 64) -> float:
    """
    Compute Lobachevsky function Ξ›(ΞΈ) via series expansion.

    Ξ›(ΞΈ) = -βˆ«β‚€^ΞΈ log|2sin(t)| dt = (1/2) Ξ£β‚–β‚Œβ‚^∞ sin(2kΞΈ)/kΒ²

    Args:
        theta: Angle in radians
        n: Number of terms in series (default 64 for good accuracy)

    Returns:
        Ξ›(ΞΈ) value
    """
    total = 0.0
    for k in range(1, n + 1):
        total += np.sin(2 * k * theta) / (k * k)
    return 0.5 * total


def _angles_for_triangle(z1, z2, z3):
    """
    Compute the three interior angles of a Euclidean triangle.

    Args:
        z1, z2, z3: Complex coordinates of triangle vertices

    Returns:
        Tuple of three angles (a1, a2, a3) in radians
    """
    def angle_at(a, b, c):
        u = np.array([(b - a).real, (b - a).imag])
        v = np.array([(c - a).real, (c - a).imag])
        dot = (u * v).sum()
        cross = u[0] * v[1] - u[1] * v[0]
        return np.arctan2(abs(cross), dot)

    return (angle_at(z1, z2, z3),
            angle_at(z2, z3, z1),
            angle_at(z3, z1, z2))


def triangle_volume(z1, z2, z3, series_terms=64):
    """
    Compute volume of ideal hyperbolic tetrahedron from base triangle.

    For a triangle with vertices z1, z2, z3 in the complex plane, the volume
    of the ideal tetrahedron with base vertices at z1, z2, z3 and apex at ∞
    is given by the sum of Lobachevsky functions at the three interior angles:

    V = Ξ›(α₁) + Ξ›(Ξ±β‚‚) + Ξ›(α₃)

    Args:
        z1, z2, z3: Complex coordinates of triangle vertices
        series_terms: Number of terms in Lobachevsky series (default 64)

    Returns:
        Volume of the ideal tetrahedron
    """
    a1, a2, a3 = _angles_for_triangle(z1, z2, z3)
    return (_lob_value_series(a1, series_terms) +
            _lob_value_series(a2, series_terms) +
            _lob_value_series(a3, series_terms))


# ============================================================================
# Volume computation strategies
# ============================================================================

def compute_volume_hull_method(vertices: np.ndarray, index_inf: int = None) -> float:
    """
    Compute polyhedron volume using convex hull method.

    This method:
    1. Lifts all vertices to sphere (including ∞ β†’ north pole)
    2. Computes convex hull on sphere
    3. Projects triangles back to complex plane (excluding those containing ∞)
    4. Sums volumes of all triangles

    Args:
        vertices: Complex array of all vertices
        index_inf: Index of vertex at infinity (if None, searches for inf)

    Returns:
        Total volume
    """
    if index_inf is None:
        # Find infinity vertex
        is_inf = ~np.isfinite(vertices.real) | ~np.isfinite(vertices.imag)
        if not np.any(is_inf):
            raise ValueError("No vertex at infinity found")
        index_inf = np.where(is_inf)[0][0]

    tris = hull_tris_projected_back(vertices, index_inf=index_inf)
    total = 0.0
    for (z1, z2, z3) in tris:
        total += triangle_volume(z1, z2, z3)
    return total


def compute_volume_delaunay_method(vertices: np.ndarray) -> float:
    """
    Compute polyhedron volume using Delaunay triangulation.

    This method:
    1. Takes only finite vertices
    2. Computes Delaunay triangulation in the plane
    3. Sums volumes of all triangles (implicitly with ∞ as apex)

    Note: This assumes ∞ is one of the vertices. All finite vertices
    are triangulated and each triangle forms a tetrahedron with ∞.

    Args:
        vertices: Complex array of all vertices (including ∞)

    Returns:
        Total volume
    """
    # Filter out infinity
    is_finite = np.isfinite(vertices.real) & np.isfinite(vertices.imag)
    z_finite = vertices[is_finite]

    if len(z_finite) < 3:
        raise ValueError("Need at least 3 finite vertices for triangulation")

    idx_tris = delaunay_triangulation_indices(z_finite)
    total = 0.0
    for (i, j, k) in idx_tris:
        z1, z2, z3 = z_finite[i], z_finite[j], z_finite[k]
        total += triangle_volume(z1, z2, z3)
    return total


# ============================================================================
# Main API
# ============================================================================

def compute_volume(vertices, method="auto", series_terms=64):
    """
    Compute volume of ideal hyperbolic polyhedron from vertex coordinates.

    The polyhedron is determined by vertices in C βˆͺ {∞}. The volume is
    computed by triangulating the finite vertices and summing the volumes
    of the resulting ideal tetrahedra.

    Args:
        vertices: Array-like of complex numbers and/or np.inf
                 Can include 0, 1, ∞, and additional points
        method: "auto", "hull", or "delaunay"
               - "auto": Use Delaunay if ∞ present, else hull
               - "hull": Lift to sphere, convex hull, project back
               - "delaunay": Delaunay triangulation of finite vertices
        series_terms: Number of terms in Lobachevsky series (default 64)

    Returns:
        Volume of the ideal polyhedron

    Examples:
        >>> # Tetrahedron with vertices at 0, 1, i, ∞
        >>> vertices = [0+0j, 1+0j, 1j, np.inf]
        >>> vol = compute_volume(vertices)

        >>> # Polyhedron with 7 vertices (0, 1, i, ∞ + 3 random)
        >>> vertices = [0+0j, 1+0j, 1j, np.inf, 0.5+0.3j, -0.2+0.7j, 0.8-0.1j]
        >>> vol = compute_volume(vertices)
    """
    # Convert to numpy array
    vertices = np.asarray(vertices, dtype=complex)

    # Check if infinity is present
    has_inf = np.any(~np.isfinite(vertices.real) | ~np.isfinite(vertices.imag))

    # Choose method
    if method == "auto":
        method = "delaunay" if has_inf else "hull"

    if method == "delaunay":
        if not has_inf:
            raise ValueError("Delaunay method requires vertex at infinity")
        return compute_volume_delaunay_method(vertices)
    elif method == "hull":
        if not has_inf:
            # Add infinity if not present
            vertices = np.append(vertices, np.inf)
        return compute_volume_hull_method(vertices)
    else:
        raise ValueError(f"Unknown method: {method}")


def volume_exceeds_threshold(vertices, threshold):
    """
    Check if ideal polyhedron volume exceeds a threshold.

    This is the main API function. Given vertices (which implicitly or
    explicitly include 0, 1, and ∞), compute the volume and check if
    it exceeds the given threshold.

    Args:
        vertices: Array-like of complex numbers (and optionally np.inf)
                 Should include or implicitly represent 0, 1, ∞
        threshold: Real number to compare against

    Returns:
        True if volume > threshold, False otherwise

    Examples:
        >>> # Check if tetrahedron volume > 1.0
        >>> vertices = [0+0j, 1+0j, 1j, np.inf]
        >>> result = volume_exceeds_threshold(vertices, 1.0)
        >>> print(result)  # True or False

        >>> # With additional vertices
        >>> vertices = [0+0j, 1+0j, 1j, np.inf, 0.5+0.5j, -0.3+0.8j]
        >>> result = volume_exceeds_threshold(vertices, 2.5)
    """
    volume = compute_volume(vertices)
    return volume > threshold


def get_volume(vertices):
    """
    Convenience function to get the exact volume value.

    Args:
        vertices: Array-like of complex numbers (and optionally np.inf)

    Returns:
        Volume as a float

    Examples:
        >>> vertices = [0+0j, 1+0j, 1j, np.inf]
        >>> vol = get_volume(vertices)
        >>> print(f"Volume: {vol:.6f}")
    """
    return compute_volume(vertices)