diff --git a/autoarray/inversion/mesh/interpolator/_sibson_numba.py b/autoarray/inversion/mesh/interpolator/_sibson_numba.py index 450053a44..1079b52f9 100644 --- a/autoarray/inversion/mesh/interpolator/_sibson_numba.py +++ b/autoarray/inversion/mesh/interpolator/_sibson_numba.py @@ -17,6 +17,9 @@ # compiled code (and the on-disk cache) as literals. EPS = 2.220446049250313e-16 TINY = 2.2250738585072014e-308 +# Same values as ``sibson.SIBSON_ZERO_AREA_TOLERANCE`` / ``SIBSON_NEGATIVE_AREA_TOLERANCE`` (PyAutoArray#610). +ZERO_AREA_TOLERANCE = 1.0e-12 +NEGATIVE_AREA_TOLERANCE = 1.0e-10 @numba.njit(cache=True, nogil=True) @@ -28,84 +31,20 @@ def _np_maximum(a, b): @numba.njit(cache=True, nogil=True) -def _block_sum(values, start, n): - # NumPy ``pairwise_sum`` leaf (n <= 128): plain loop below 8, otherwise - # eight interleaved accumulators combined as a fixed tree. - if n < 8: - result = -0.0 - for i in range(n): - result += values[start + i] - return result - r0 = values[start + 0] - r1 = values[start + 1] - r2 = values[start + 2] - r3 = values[start + 3] - r4 = values[start + 4] - r5 = values[start + 5] - r6 = values[start + 6] - r7 = values[start + 7] - i = 8 - stop = n - (n % 8) - while i < stop: - r0 += values[start + i + 0] - r1 += values[start + i + 1] - r2 += values[start + i + 2] - r3 += values[start + i + 3] - r4 += values[start + i + 4] - r5 += values[start + i + 5] - r6 += values[start + i + 6] - r7 += values[start + i + 7] - i += 8 - result = ((r0 + r1) + (r2 + r3)) + ((r4 + r5) + (r6 + r7)) - while i < n: - result += values[start + i] - i += 1 - return result - - -@numba.njit(cache=True, nogil=True) -def _pairwise_sum(values): - # Explicit-stack form of NumPy's recursive ``pairwise_sum``: blocks - # above 128 split at ``n2 = n // 2 - (n // 2) % 8`` and the two halves - # are added left + right. - node_start = np.empty(64, dtype=np.int64) - node_n = np.empty(64, dtype=np.int64) - node_state = np.empty(64, dtype=np.int64) - partials = np.empty(64, dtype=np.float64) - top = 0 - partial_top = 0 - node_start[0] = 0 - node_n[0] = values.shape[0] - node_state[0] = 0 - top = 1 - while top > 0: - top -= 1 - start = node_start[top] - n = node_n[top] - state = node_state[top] - if n <= 128: - partials[partial_top] = _block_sum(values, start, n) - partial_top += 1 - elif state == 0: - n2 = n // 2 - n2 -= n2 % 8 - node_start[top] = start - node_n[top] = n - node_state[top] = 1 - node_start[top + 1] = start + n2 - node_n[top + 1] = n - n2 - node_state[top + 1] = 0 - node_start[top + 2] = start - node_n[top + 2] = n2 - node_state[top + 2] = 0 - top += 3 - else: - right = partials[partial_top - 1] - left = partials[partial_top - 2] - partial_top -= 2 - partials[partial_top] = left + right - partial_top += 1 - return partials[0] +def _credit(unique_ids, compact_weights, unique_count, vertex, value): + """Add ``value`` to ``vertex``'s entry of the vertex-sorted compact list; return the new count.""" + position = 0 + while position < unique_count and unique_ids[position] < vertex: + position += 1 + if position < unique_count and unique_ids[position] == vertex: + compact_weights[position] += value + return unique_count + for k in range(unique_count, position, -1): + unique_ids[k] = unique_ids[k - 1] + compact_weights[k] = compact_weights[k - 1] + unique_ids[position] = vertex + compact_weights[position] = 0.0 + value + return unique_count + 1 def _sibson_from_tables( @@ -180,18 +119,20 @@ def _sibson_from_tables( cavity[count] = candidate count += 1 - # Watson contributions, grouped by vertex id into a sorted list. + # Natural-neighbour areas from the cavity BOUNDARY, credited per cavity-triangle edge and grouped by + # vertex id into a sorted list (``_sibson_single_from_tables`` documents the decomposition, + # PyAutoArray#610). Slot-major, edges j = 0, 1, 2: the same order as the reference. unique_ids = np.full(compact_length, -1, dtype=np.int64) compact_weights = np.zeros(compact_length, dtype=np.float64) unique_count = 0 - inserted_invalid = False + interior_collinear = False + hull_found = False + hull_a = 0 + hull_b = 0 vx = np.empty(3, dtype=np.float64) vy = np.empty(3, dtype=np.float64) vid = np.empty(3, dtype=np.int64) - rx = np.empty(3, dtype=np.float64) - ry = np.empty(3, dtype=np.float64) - ivalid = np.empty(3, dtype=np.bool_) - contribution = np.empty(3, dtype=np.float64) + vertex_value = np.empty(3, dtype=np.float64) for slot in range(count): triangle_index = cavity[slot] for j in range(3): @@ -201,57 +142,78 @@ def _sibson_from_tables( vid[j] = vertex vx[j] = points[vertex, 0] vy[j] = points[vertex, 1] - ox = circumcentres[triangle_index, 0] - oy = circumcentres[triangle_index, 1] - # Circle j passes through the query and the edge opposite j. - for j in range(3): - ax = vx[(j + 1) % 3] - ay = vy[(j + 1) % 3] - bax = vx[(j + 2) % 3] - ax - bay = vy[(j + 2) % 3] - ay - cax = qx - ax - cay = qy - ay - denominator = 2.0 * (bax * cay - bay * cax) - ba2 = bax * bax + bay * bay - ca2 = cax * cax + cay * cay - scale = _np_maximum(_np_maximum(ba2, ca2), 1.0) - valid = abs(denominator) > 32.0 * EPS * scale - safe_denominator = denominator if valid else 1.0 - offset_x = (ba2 * cay - ca2 * bay) / safe_denominator - offset_y = (bax * ca2 - cax * ba2) / safe_denominator - if valid: - centre_x = ax + offset_x - centre_y = ay + offset_y - else: - centre_x = 0.0 - centre_y = 0.0 - inserted_invalid = True - ivalid[j] = valid - rx[j] = centre_x - ox - ry[j] = centre_y - oy + orientation = (vx[1] - vx[0]) * (vy[2] - vy[0]) - (vy[1] - vy[0]) * ( + vx[2] - vx[0] + ) + sign = -1.0 if orientation < 0.0 else 1.0 + rtx = circumcentres[triangle_index, 0] - qx + rty = circumcentres[triangle_index, 1] - qy + vertex_value[0] = 0.0 + vertex_value[1] = 0.0 + vertex_value[2] = 0.0 for j in range(3): - j1 = (j + 1) % 3 - j2 = (j + 2) % 3 - if ivalid[j1] and ivalid[j2]: - contribution[j] = rx[j1] * ry[j2] - ry[j1] * rx[j2] + ja = (j + 1) % 3 + jb = (j + 2) % 3 + a_vertex = vid[ja] + b_vertex = vid[jb] + other = simplex_neighbors[triangle_index, j] + # The cavity walk's own circumcircle test (see the reference body). + other_in_cavity = False + if other >= 0 and circumcircle_valid[other]: + odx = circumcentres[other, 0] - qx + ody = circumcentres[other, 1] - qy + other_radius_squared = circumradii_squared[other] + other_in_cavity = odx * odx + ody * ody <= other_radius_squared + ( + 64.0 * EPS * _np_maximum(other_radius_squared, 1.0) + ) + value_b = 0.0 + value_a = 0.0 + if other_in_cavity: + if triangle_index < other: + rox = circumcentres[other, 0] - qx + roy = circumcentres[other, 1] - qy + term = 0.5 * (rtx * roy - rty * rox) + value_b = term + value_a = -term else: - contribution[j] = 0.0 + # New circumcentre of (a, b, query), as ``circumcircles_from(a, b, query)``. + ax = vx[ja] + ay = vy[ja] + bax = vx[jb] - ax + bay = vy[jb] - ay + cax = qx - ax + cay = qy - ay + denominator = 2.0 * (bax * cay - bay * cax) + ba2 = bax * bax + bay * bay + ca2 = cax * cax + cay * cay + scale = _np_maximum(_np_maximum(ba2, ca2), 1.0) + if abs(denominator) > 32.0 * EPS * scale: + rnx = ax + (ba2 * cay - ca2 * bay) / denominator - qx + rny = ay + (bax * ca2 - cax * ba2) / denominator - qy + boundary_term = 0.5 * (rtx * rny - rty * rnx) + mbx = 0.5 * (vx[jb] - qx) + mby = 0.5 * (vy[jb] - qy) + max_ = 0.5 * (vx[ja] - qx) + may = 0.5 * (vy[ja] - qy) + closure_b = 0.5 * (rnx * mby - rny * mbx) + closure_a = 0.5 * (max_ * rny - may * rnx) + value_b = boundary_term + closure_b + value_a = -boundary_term + closure_a + elif other < 0: + if not hull_found: + hull_found = True + hull_a = a_vertex + hull_b = b_vertex + else: + interior_collinear = True + vertex_value[jb] += value_b + vertex_value[ja] += value_a for j in range(3): - vertex = vid[j] - position = 0 - while position < unique_count and unique_ids[position] < vertex: - position += 1 - if position < unique_count and unique_ids[position] == vertex: - compact_weights[position] += contribution[j] - else: - for k in range(unique_count, position, -1): - unique_ids[k] = unique_ids[k - 1] - compact_weights[k] = compact_weights[k - 1] - unique_ids[position] = vertex - compact_weights[position] = 0.0 + contribution[j] - unique_count += 1 + unique_count = _credit( + unique_ids, compact_weights, unique_count, vid[j], sign * vertex_value[j] + ) - # On-vertex / on-edge tests against the seed triangle. + # On-vertex test against the seed triangle. s0 = simplices_padded[seed, 0] s1 = simplices_padded[seed, 1] s2 = simplices_padded[seed, 2] @@ -296,25 +258,31 @@ def _sibson_from_tables( vertex_tolerance = 64.0 * EPS * coordinate_scale vertex_tolerance = vertex_tolerance * vertex_tolerance on_vertex = min_distance <= vertex_tolerance + on_hull_edge = (not on_vertex) and hull_found - seed_denominator = (p1x - p0x) * (p2y - p0y) - (p1y - p0y) * (p2x - p0x) - if seed_denominator == 0.0: - seed_denominator = 1.0 - bary0 = (d1x * d2y - d1y * d2x) / seed_denominator - bary1 = (d2x * d0y - d2y * d0x) / seed_denominator - bary2 = (d0x * d1y - d0y * d1x) / seed_denominator - edge_tolerance = 128.0 * EPS - min_bary = _np_maximum(-abs(bary0), -abs(bary1)) - min_bary = -_np_maximum(min_bary, -abs(bary2)) - on_edge = (not on_vertex) and (min_bary <= edge_tolerance) - - weight_sum = _pairwise_sum(compact_weights) + # Snap round-off-sized areas to 0 before normalising; a clearly negative one is degenerate. + # One pass over the live entries only (the rest of the compact list is padding); parity with the + # reference's pairwise sums is to round-off, which the tolerances absorb. + total = 0.0 + for k in range(unique_count): + total += compact_weights[k] + magnitude = abs(total) + significant_negative = False + weight_sum = 0.0 + for k in range(unique_count): + if compact_weights[k] < -NEGATIVE_AREA_TOLERANCE * magnitude: + significant_negative = True + if compact_weights[k] <= ZERO_AREA_TOLERANCE * magnitude: + compact_weights[k] = 0.0 + else: + weight_sum += compact_weights[k] degenerate = ( (not on_vertex) - and (not on_edge) + and (not on_hull_edge) and ( - inserted_invalid - or (not np.isfinite(weight_sum)) + interior_collinear + or significant_negative + or (not np.isfinite(total)) or abs(weight_sum) <= TINY ) ) @@ -324,31 +292,41 @@ def _sibson_from_tables( mappings[q, 0] = local_vertex weights[q, 0] = 1.0 size = 1 - elif on_edge: - # Barycentric row of the containing triangle (third weight 0). + elif on_hull_edge: + # Linear interpolation between the hull edge's endpoints (the Sibson limit on the hull). + ex = points[hull_b, 0] - points[hull_a, 0] + ey = points[hull_b, 1] - points[hull_a, 1] + edge_length_squared = ex * ex + ey * ey + if edge_length_squared <= 0.0: + edge_length_squared = 1.0 + along = ( + (qx - points[hull_a, 0]) * ex + (qy - points[hull_a, 1]) * ey + ) / edge_length_squared + if along < 0.0: + along = 0.0 + if along > 1.0: + along = 1.0 if max_neighbors > 0: - mappings[q, 0] = s0 - weights[q, 0] = bary0 + mappings[q, 0] = hull_a + weights[q, 0] = 1.0 - along if max_neighbors > 1: - mappings[q, 1] = s1 - weights[q, 1] = bary1 - if max_neighbors > 2: - mappings[q, 2] = s2 - weights[q, 2] = bary2 - size = 3 + mappings[q, 1] = hull_b + weights[q, 1] = along + size = 2 else: + # Selected entries are written to the front, in vertex order, with no -1 holes. size = 0 for k in range(max_neighbors): if k >= compact_length or k >= unique_count: break weight = compact_weights[k] / safe_sum if weight > 0.0: - mappings[q, k] = unique_ids[k] - weights[q, k] = weight + mappings[q, size] = unique_ids[k] + weights[q, size] = weight size += 1 neighbor_overflow = ( - (not on_vertex) and (not on_edge) and unique_count > max_neighbors + (not on_vertex) and (not on_hull_edge) and unique_count > max_neighbors ) failed = cavity_overflow or neighbor_overflow or degenerate if failed: diff --git a/autoarray/inversion/mesh/interpolator/sibson.py b/autoarray/inversion/mesh/interpolator/sibson.py index 2f1789af5..5b8fdadb3 100644 --- a/autoarray/inversion/mesh/interpolator/sibson.py +++ b/autoarray/inversion/mesh/interpolator/sibson.py @@ -2,8 +2,8 @@ The Delaunay connectivity still comes from the small qhull callback used by ``delaunay.py``. Everything depending continuously on the mesh and query -coordinates -- circumcircles, cavity traversal, Watson areas, normalization -and stencil compaction -- is array code and therefore differentiable by JAX. +coordinates -- circumcircles, cavity traversal, natural-neighbour areas from the cavity boundary +(PyAutoArray#610), normalization and stencil compaction -- is array code and therefore differentiable by JAX. ``InterpolatorDelaunayNN`` exposes the implementation through the public ``mesh.DelaunayNN`` mesh. Overflow and degeneracy diagnostics remain part of @@ -36,6 +36,13 @@ SIBSON_MAX_CAVITY_TRIANGLES = 32 SIBSON_MAX_NEIGHBORS = 32 +# Natural-neighbour areas within this fraction of the total are round-off around a true zero (e.g. a +# cocircular neighbour): they are snapped to exactly 0 before normalising, so the NumPy, JAX and numba bodies +# (which sum in different orders) select the same support. An area below minus SIBSON_NEGATIVE_AREA_TOLERANCE +# times the total cannot come from round-off and marks the row degenerate (PyAutoArray#610). +SIBSON_ZERO_AREA_TOLERANCE = 1.0e-12 +SIBSON_NEGATIVE_AREA_TOLERANCE = 1.0e-10 + def _positive_int_env(name, raw): """Parse a positive-integer environment override; ``None`` when unset.""" @@ -63,8 +70,8 @@ def _bool_env(name, raw): # ``jax.lax.map`` block size for the JAX Sibson query loop, bound onto the mesh # as ``DelaunayNN.query_chunk``. It is a MEMORY GUARD and nothing else: it # bounds the ``(C, 3, 2)`` per-query intermediates of the cavity -- the -# inserted Watson circumcircle centres and their contributions, of order -# 15-25 kB per query per lane at cap 32 -- so the live footprint stays bounded +# new circumcentres of the cavity-boundary edges and the per-edge area terms, of +# order 15-25 kB per query per lane at cap 32 -- so the live footprint stays bounded # when the likelihood is vmapped over many live points. # # It is emphatically not a speed knob to be kept small. The walk and the two @@ -219,10 +226,15 @@ def _contains_query( circumradii_squared, circumcircle_valid, xp, + elementwise=False, ): + """Whether ``query`` lies inside (or on, to round-off) the circumcircle of ``triangle_index``. + + ``elementwise=True`` accepts an array of triangle indexes and returns one boolean per index. + """ safe_index = xp.maximum(triangle_index, 0) delta = circumcentres[safe_index] - query - distance_squared = xp.sum(delta * delta) + distance_squared = xp.sum(delta * delta, axis=-1) if elementwise else xp.sum(delta * delta) radius_squared = circumradii_squared[safe_index] tolerance = 64.0 * xp.finfo(query.dtype).eps * xp.maximum(radius_squared, 1.0) return ( @@ -375,51 +387,91 @@ def _sibson_single_from_tables( max_cavity_triangles=max_cavity_triangles, ) + # Sibson weights from the Bowyer-Watson cavity BOUNDARY (PyAutoArray#610). + # + # The weight of natural neighbour v is the area of (new Voronoi cell of the query q) intersected with + # (old Voronoi cell of v). That convex region is bounded by segments which each separate two sites, so its + # area is a sum of terms 0.5 * cross(P - q, P' - q), every one local to a single cavity-triangle edge: + # + # * cavity-interior edge (a, b) shared by cavity triangles T and T': the old Voronoi edge c(T) -> c(T') + # (stored circumcentres only), credited +b / -a; + # * cavity-boundary edge (a, b) of T: the a|b Voronoi edge's piece c(T) -> c_new(q, a, b) inside the new + # cell, credited +b / -a, plus the q|b and q|a bisector pieces from c_new(q, a, b) to the bisector + # midpoints m_b = (q + b) / 2 and m_a = (q + a) / 2. Splitting each q|v bisector segment at m_v (which + # lies on it) is exact and keeps every term local to one edge. + # + # (a, b) is the edge opposite vertex j taken counter-clockwise; a clockwise triangle negates all its terms. + # The only circles through q, c_new(q, a, b), are formed on cavity-BOUNDARY edges. q lies strictly inside + # the cavity, so it can be collinear with a boundary edge only when that edge is a convex-hull edge and q + # lies on it. Internal edges through or near q (the square-centre diagonal) are never singular. The old + # Watson decomposition formed a circle through q for every edge of every cavity triangle, including the + # cavity-interior ones whose huge cancelling terms broke continuity and the partition of unity near edges. cavity_valid = cavity >= 0 safe_cavity = cavity.clip(min=0) - triangle_vertices = simplices_padded[safe_cavity].clip(min=0) - vertices = points[triangle_vertices] - - # Circle j passes through the query and the edge opposite triangle vertex j. - edge_a = vertices[:, [1, 2, 0], :] - edge_b = vertices[:, [2, 0, 1], :] - query_for_edges = xp.broadcast_to(query, edge_a.shape) - inserted_centres, _, inserted_valid = circumcircles_from( - edge_a, edge_b, query_for_edges, xp=xp + triangle_vertices = simplices_padded[safe_cavity].clip(min=0) # (C, 3) + vertices = points[triangle_vertices] # (C, 3, 2) + + orientation = _cross(vertices[:, 1] - vertices[:, 0], vertices[:, 2] - vertices[:, 0]) + orientation_sign = xp.where(orientation < 0.0, -1.0, 1.0).astype(points.dtype) + + # Edge j joins a = vertex (j+1) % 3 -> b = vertex (j+2) % 3 and is shared with simplex_neighbors[:, j]. + a_index = triangle_vertices[:, [1, 2, 0]] + b_index = triangle_vertices[:, [2, 0, 1]] + a_points = vertices[:, [1, 2, 0], :] + b_points = vertices[:, [2, 0, 1], :] + other = simplex_neighbors[safe_cavity] # (C, 3) + + # A neighbour of a cavity triangle is in the cavity exactly when the cavity walk's own circumcircle test + # accepts it (the walk examines every neighbour), so re-evaluate that predicate rather than searching the + # cavity list. Only an overflowed cavity can differ, and its row is failed (NaN) either way. + other_in_cavity = _contains_query( + other, query, circumcentres, circumradii_squared, circumcircle_valid, xp, elementwise=True ) + interior = cavity_valid[:, None] & other_in_cavity + count_interior = interior & (safe_cavity[:, None] < other) # each interior edge once + boundary = cavity_valid[:, None] & ~other_in_cavity - original_centres = circumcentres[safe_cavity][:, None, :] - relative = inserted_centres - original_centres - contributions = xp.stack( - [ - _cross(relative[:, 1], relative[:, 2]), - _cross(relative[:, 2], relative[:, 0]), - _cross(relative[:, 0], relative[:, 1]), - ], - axis=1, + relative_centres = circumcentres[safe_cavity] - query # (C, 2) + relative_other_centres = circumcentres[other.clip(min=0)] - query # (C, 3, 2) + interior_term = 0.5 * _cross(relative_centres[:, None, :], relative_other_centres) + + query_for_edges = xp.broadcast_to(query, a_points.shape) + new_centres, _, new_valid = circumcircles_from( + a_points, b_points, query_for_edges, xp=xp ) - contribution_valid = cavity_valid[:, None] & xp.stack( - [ - inserted_valid[:, 1] & inserted_valid[:, 2], - inserted_valid[:, 2] & inserted_valid[:, 0], - inserted_valid[:, 0] & inserted_valid[:, 1], - ], - axis=1, + relative_new = new_centres - query + boundary_term = 0.5 * _cross(relative_centres[:, None, :], relative_new) + closure_b = 0.5 * _cross(relative_new, 0.5 * (b_points - query)) + closure_a = 0.5 * _cross(0.5 * (a_points - query), relative_new) + + usable_boundary = boundary & new_valid + value_b = xp.where(count_interior, interior_term, 0.0) + xp.where( + usable_boundary, boundary_term + closure_b, 0.0 + ) + value_a = xp.where(count_interior, -interior_term, 0.0) + xp.where( + usable_boundary, -boundary_term + closure_a, 0.0 ) - contributions = xp.where(contribution_valid, contributions, 0.0) + value_b = orientation_sign[:, None] * value_b + value_a = orientation_sign[:, None] * value_a + + # A boundary edge without a circle through q: on a hull edge, q lies on that edge (the hull-edge rule + # below); anywhere else it cannot happen for a valid cavity and the row is marked degenerate. + collinear_boundary = boundary & ~new_valid + hull_collinear = collinear_boundary & (other < 0) + interior_collinear = collinear_boundary & (other >= 0) + + # Pre-sum the edge credits per triangle vertex: vertex i is b of edge (i + 1) % 3 and a of edge (i + 2) % 3. + vertex_values = value_b[:, [1, 2, 0]] + value_a[:, [2, 0, 1]] # (C, 3) flat_vertices = triangle_vertices.reshape(-1) - flat_contributions = contributions.reshape(-1) - flat_valid = xp.broadcast_to(cavity_valid[:, None], contributions.shape).reshape(-1) + flat_contributions = vertex_values.reshape(-1) + flat_valid = xp.broadcast_to(cavity_valid[:, None], triangle_vertices.shape).reshape(-1) sentinel = points.shape[0] sortable_vertices = xp.where(flat_valid, flat_vertices, sentinel) sortable_contributions = xp.where(flat_valid, flat_contributions, 0.0) - # Compact the at-most 3*C Watson contributions without allocating an - # N-vertex vector per query. Equal vertex ids become adjacent after the - # small fixed-size sort and are scatter-added into consecutive groups. - # This is substantially cheaper than a global N-way top-k for production - # meshes (N ~= 1200, while 3*C <= 96). + # Compact the at-most 3*C vertex credits without allocating an N-vertex vector per query: equal vertex ids + # become adjacent after the small fixed-size sort and are scatter-added into consecutive groups. order = xp.argsort(sortable_vertices) sorted_vertices = sortable_vertices[order] sorted_contributions = sortable_contributions[order] @@ -468,36 +520,30 @@ def _sibson_single_from_tables( vertex_tolerance = (64.0 * xp.finfo(points.dtype).eps * coordinate_scale) ** 2 on_vertex = inside & (xp.min(seed_distances_squared) <= vertex_tolerance) - seed_denominator = _cross( - seed_points[1] - seed_points[0], seed_points[2] - seed_points[0] - ) - safe_seed_denominator = xp.where(seed_denominator != 0.0, seed_denominator, 1.0) - seed_barycentric = ( - xp.stack( - [ - _cross(seed_points[1] - query, seed_points[2] - query), - _cross(seed_points[2] - query, seed_points[0] - query), - _cross(seed_points[0] - query, seed_points[1] - query), - ] - ) - / safe_seed_denominator - ) - edge_tolerance = 128.0 * xp.finfo(points.dtype).eps - on_edge = ( - inside & (~on_vertex) & (xp.min(xp.abs(seed_barycentric)) <= edge_tolerance) - ) + on_hull_edge = inside & (~on_vertex) & xp.any(hull_collinear) fallback_index = xp.where(on_vertex, local_vertex, outside_fallback_index) use_fallback = (~inside) | on_vertex + # Each neighbour's area is >= 0 in exact arithmetic. Snap round-off-sized values (true zeros, e.g. a + # cocircular neighbour) to exactly 0 BEFORE normalising, so every backend selects the same support; a + # clearly negative area is an inconsistency and marks the row degenerate. + total = xp.sum(compact_weights) + magnitude = xp.abs(total) + significant_negative = xp.any(compact_weights < -SIBSON_NEGATIVE_AREA_TOLERANCE * magnitude) + compact_weights = xp.where( + compact_weights <= SIBSON_ZERO_AREA_TOLERANCE * magnitude, 0.0, compact_weights + ) + weight_sum = xp.sum(compact_weights) degenerate = ( inside & (~on_vertex) - & (~on_edge) + & (~on_hull_edge) & ( - xp.any(cavity_valid[:, None] & ~inserted_valid) - | (~xp.isfinite(weight_sum)) + xp.any(interior_collinear) + | significant_negative + | (~xp.isfinite(total)) | (xp.abs(weight_sum) <= xp.finfo(points.dtype).tiny) ) ) @@ -519,6 +565,15 @@ def _sibson_single_from_tables( mappings = xp.where(selected_valid, mappings, -1).astype(xp.int32) weights = xp.where(selected_valid, weights, 0.0) + # Consumers read only the first `size` entries, so move the selected ones to the front (stably, keeping + # the vertex order): a zero-area neighbour between two selected ones must not leave a -1 hole. + if xp is np: + front = np.argsort(~selected_valid, kind="stable") + else: + front = xp.argsort(~selected_valid, stable=True) + mappings = mappings[front] + weights = weights[front] + fallback_mappings = -xp.ones((max_neighbors,), dtype=xp.int32) fallback_weights = xp.zeros((max_neighbors,), dtype=points.dtype) if xp is np: @@ -531,24 +586,34 @@ def _sibson_single_from_tables( weights = xp.where(use_fallback, fallback_weights, weights) size = xp.where(use_fallback, 1, xp.sum(selected_valid)).astype(xp.int32) - # Inserting a query exactly on an existing edge makes one of the Watson - # circumcircles collinear. Sibson coordinates there are the ordinary - # linear coordinates of the two edge endpoints, which the containing - # triangle's barycentric row represents exactly (the third weight is 0). + # Hull-edge rule. On a convex-hull edge the new Voronoi cell is unbounded and Sibson coordinates reduce to + # linear interpolation between the edge's endpoints, which is also the limit approached from inside (the + # deviation is O(distance)). It applies ONLY on hull edges: on an internal edge the boundary formulation + # above is regular and keeps the off-edge natural neighbours (the square centre gets 1/4 each). + hull_edge = xp.argmax(hull_collinear.reshape(-1)) + hull_a = a_index.reshape(-1)[hull_edge] + hull_b = b_index.reshape(-1)[hull_edge] + hull_a_point = points[hull_a] + edge_vector = points[hull_b] - hull_a_point + edge_length_squared = xp.sum(edge_vector * edge_vector) + safe_edge_length_squared = xp.where(edge_length_squared > 0.0, edge_length_squared, 1.0) + along = xp.clip( + xp.sum((query - hull_a_point) * edge_vector) / safe_edge_length_squared, 0.0, 1.0 + ) edge_mappings = -xp.ones((max_neighbors,), dtype=xp.int32) edge_weights = xp.zeros((max_neighbors,), dtype=points.dtype) if xp is np: - edge_mappings[:3] = seed_vertices - edge_weights[:3] = seed_barycentric + edge_mappings[:2] = (hull_a, hull_b) + edge_weights[:2] = (1.0 - along, along) else: - edge_mappings = edge_mappings.at[:3].set(seed_vertices) - edge_weights = edge_weights.at[:3].set(seed_barycentric) - mappings = xp.where(on_edge, edge_mappings, mappings) - weights = xp.where(on_edge, edge_weights, weights) - size = xp.where(on_edge, 3, size).astype(xp.int32) + edge_mappings = edge_mappings.at[:2].set(xp.stack([hull_a, hull_b]).astype(xp.int32)) + edge_weights = edge_weights.at[:2].set(xp.stack([1.0 - along, along])) + mappings = xp.where(on_hull_edge, edge_mappings, mappings) + weights = xp.where(on_hull_edge, edge_weights, weights) + size = xp.where(on_hull_edge, 2, size).astype(xp.int32) neighbor_overflow = ( - inside & (~on_vertex) & (~on_edge) & (unique_count > max_neighbors) + inside & (~on_vertex) & (~on_hull_edge) & (unique_count > max_neighbors) ) overflow = overflow | neighbor_overflow failed = overflow | degenerate @@ -603,24 +668,22 @@ def sibson_numba_kernel(parallel: bool = True): The kernel is a line-by-line port of :func:`_sibson_single_from_tables` (NumPy branch) with ``prange`` over queries: the same cavity walk and - containment tolerance, the same Watson circumcircle arithmetic in the same - operation order, the same on-vertex / on-edge / outside-mesh fallbacks, + containment tolerance, the same cavity-boundary area terms (PyAutoArray#610) + in the same edge order, the same on-vertex / hull-edge / outside-mesh fallbacks, degeneracy and overflow diagnostics, and the same padding of unused slots. Each query owns its scratch arrays and writes only its own output row, so the parallel loop needs neither a reduction nor a lock. Two details are reproduced deliberately rather than approximated: - * the per-vertex grouping inserts the at-most ``3 * C`` contributions into - a small sorted list (ascending vertex id, contributions summed in cavity + * the per-vertex grouping inserts the at-most ``3 * C`` per-triangle-vertex + credits into a small sorted list (ascending vertex id, summed in cavity order), which is the reference's ``argsort`` + ``np.add.at`` grouping up - to the order equal vertex ids are summed in -- NumPy's argsort is not - stable, so weights agree to rounding (parity tests: <= 1e-12, observed - ~1e-14 near the hull where cavity contributions cancel), not - bit-for-bit; - * the normalising sum replicates NumPy's pairwise summation over the - length ``3 * C`` compact vector, so ``weight_sum`` (and the degeneracy - test on it) sees the same blocking as ``np.sum``. + to the order equal vertex ids are summed in, so weights agree to rounding + (parity tests: <= 1e-12), not bit-for-bit; + * the total and normalising sums run over the live entries only, in one + pass; round-off-sized areas are snapped to zero with the reference's + relative tolerances, so both bodies select the same support. The jitted functions live at module level in ``_sibson_numba``, which is imported only here, so ``import numba`` stays off the library import path @@ -788,7 +851,7 @@ def sibson_mappings_weights_from_tables( Mapper-compatible arrays with at most ``max_neighbors`` unique source vertices per query. cavity_sizes, cavity_overflow, degenerate - Prototype diagnostics. Overflow or a Watson edge degeneracy produces + Prototype diagnostics. Overflow or a degenerate (inconsistent) cavity produces NaN weights rather than silently returning an approximate stencil. """ if circumcircles is None: @@ -894,6 +957,47 @@ def jax_sibson( return (points, simplices_padded) + outputs +def sibson_mappings_weights_from( + points_np, + query_points_np, + max_cavity_triangles=SIBSON_MAX_CAVITY_TRIANGLES, + max_neighbors=SIBSON_MAX_NEIGHBORS, +): + """NumPy Sibson ``(mappings, sizes, weights)`` of arbitrary query points on the Delaunay mesh of ``points_np``. + + Used to integrate the Sibson basis functions for ``MeshGeometryDelaunayNN.areas_for_magnification``. + """ + from scipy.spatial import Delaunay + + triangle = Delaunay(points_np) + points = triangle.points.astype(points_np.dtype) + simplex_count = triangle.simplices.shape[0] + simplices_padded = -np.ones((2 * points.shape[0], 3), dtype=np.int32) + neighbors_padded = -np.ones_like(simplices_padded) + simplices_padded[:simplex_count] = triangle.simplices.astype(np.int32) + neighbors_padded[:simplex_count] = triangle.neighbors.astype(np.int32) + + simplex_indexes = triangle.find_simplex(query_points_np).astype(np.int32) + delaunay_mappings = pix_indexes_for_sub_slim_index_delaunay_from( + data_grid=query_points_np, + simplex_index_for_sub_slim_index=simplex_indexes, + pix_indexes_for_simplex_index=triangle.simplices, + delaunay_points=points, + ) + mappings, sizes, weights, _, _, _ = sibson_mappings_weights_from_tables( + query_points=query_points_np, + points=points, + simplices_padded=simplices_padded, + simplex_neighbors=neighbors_padded, + simplex_indexes=simplex_indexes, + outside_fallback_indexes=delaunay_mappings[:, 0], + max_cavity_triangles=max_cavity_triangles, + max_neighbors=max_neighbors, + xp=np, + ) + return mappings, sizes, weights + + def scipy_delaunay_nn( points_np, query_points_np, @@ -1176,6 +1280,24 @@ def delaunay(self): return DelaunayNNInterface(*outputs, xp=self._xp) + @cached_property + def mesh_geometry(self): + """ + Delaunay vertex geometry whose `areas_for_magnification` integrates this interpolator's own Sibson + basis functions rather than using the barycentric dual areas (see `MeshGeometryDelaunayNN`). + """ + from autoarray.inversion.mesh.mesh_geometry.delaunay import ( + MeshGeometryDelaunayNN, + ) + + return MeshGeometryDelaunayNN( + mesh=self.mesh, + mesh_grid=self.mesh_grid, + data_grid=self.data_grid, + dual_areas=self.dual_areas, + xp=self._xp, + ) + @cached_property def _mappings_sizes_weights(self): return ( diff --git a/autoarray/inversion/mesh/mesh_geometry/delaunay.py b/autoarray/inversion/mesh/mesh_geometry/delaunay.py index ad3786bf3..0d687e33f 100644 --- a/autoarray/inversion/mesh/mesh_geometry/delaunay.py +++ b/autoarray/inversion/mesh/mesh_geometry/delaunay.py @@ -326,19 +326,8 @@ def areas_for_magnification(self) -> np.ndarray: Computed host-side on first access, like the Delaunay dual-area fallback. """ - import scipy.spatial - nodes = np.asarray(self.mesh_grid_xy) - lo = nodes.min(axis=0) - hi = nodes.max(axis=0) - - n = KNN_AREA_QUADRATURE_PIXELS - u = (np.arange(n) + 0.5) / n - grid_0, grid_1 = np.meshgrid( - lo[0] + u * (hi[0] - lo[0]), lo[1] + u * (hi[1] - lo[1]), indexing="ij" - ) - points = np.stack([grid_0.ravel(), grid_1.ravel()], axis=1) - points = points[scipy.spatial.Delaunay(nodes).find_simplex(points) >= 0] + points = basis_quadrature_points_from(nodes) interpolator = self.interpolator_cls( mesh=self.mesh, @@ -348,10 +337,69 @@ def areas_for_magnification(self) -> np.ndarray: ) mappings, _, weights = interpolator._mappings_sizes_weights - areas = np.bincount( - np.asarray(mappings).ravel(), - weights=np.asarray(weights).ravel(), - minlength=nodes.shape[0], + return basis_integral_areas_from(nodes, mappings, weights) + + +def basis_quadrature_points_from(nodes: np.ndarray) -> np.ndarray: + """ + The midpoint-quadrature points for integrating an interpolant's basis functions over the convex hull of + ``nodes``: the centres of a uniform ``KNN_AREA_QUADRATURE_PIXELS``^2 grid over their bounding box, keeping + those inside the hull. + """ + import scipy.spatial + + lo = nodes.min(axis=0) + hi = nodes.max(axis=0) + + n = KNN_AREA_QUADRATURE_PIXELS + u = (np.arange(n) + 0.5) / n + grid_0, grid_1 = np.meshgrid( + lo[0] + u * (hi[0] - lo[0]), lo[1] + u * (hi[1] - lo[1]), indexing="ij" + ) + points = np.stack([grid_0.ravel(), grid_1.ravel()], axis=1) + return points[scipy.spatial.Delaunay(nodes).find_simplex(points) >= 0] + + +def basis_integral_areas_from(nodes, mappings, weights) -> np.ndarray: + """ + Every vertex's basis-function integral from the interpolation ``mappings`` / ``weights`` of the + ``basis_quadrature_points_from`` points: the weights summed per vertex (``-1`` padding ignored), rescaled + so the total is the convex-hull area, which removes the cells straddling the hull edge from the sum. + """ + import scipy.spatial + + mappings = np.asarray(mappings).ravel() + weights = np.asarray(weights).ravel() + valid = mappings >= 0 + + areas = np.bincount( + mappings[valid], weights=weights[valid], minlength=nodes.shape[0] + ) + + return areas * scipy.spatial.ConvexHull(nodes).volume / np.sum(areas) + + +class MeshGeometryDelaunayNN(MeshGeometryDelaunay): + @cached_property + def areas_for_magnification(self) -> np.ndarray: + """ + The integral of every vertex's Sibson (natural-neighbour) basis function over the convex hull of the + mesh, so `sum(reconstruction * areas_for_magnification)` is the integral of the reconstructed source. + + The Delaunay barycentric dual areas are these integrals only for the linear barycentric interpolant. + The Sibson interpolant is not linear on the Delaunay triangles; its dual-area approximation biased the + identity-lens magnification on a regular mesh by -2.65% once the Sibson weights at internal edges + were corrected (PyAutoArray#610), against +0.04% for these integrals. The quadrature is the one the + kNN meshes use (`MeshGeometryKNearestNeighbor`, PyAutoArray#665), evaluated with the Sibson weights. + + Computed host-side on first access, like the Delaunay dual-area fallback. + """ + from autoarray.inversion.mesh.interpolator.sibson import ( + sibson_mappings_weights_from, ) - return areas * scipy.spatial.ConvexHull(nodes).volume / np.sum(areas) + nodes = np.asarray(self.mesh_grid_xy) + points = basis_quadrature_points_from(nodes) + mappings, _, weights = sibson_mappings_weights_from(nodes, points) + + return basis_integral_areas_from(nodes, mappings, weights) diff --git a/test_autoarray/inversion/pixelization/interpolator/test_numerics_audit.py b/test_autoarray/inversion/pixelization/interpolator/test_numerics_audit.py index a671c944a..49769d263 100644 --- a/test_autoarray/inversion/pixelization/interpolator/test_numerics_audit.py +++ b/test_autoarray/inversion/pixelization/interpolator/test_numerics_audit.py @@ -164,14 +164,8 @@ def test_linear_precision_and_pairing_fault(family): ] + [ ("delaunay", None), - pytest.param( - "sibson", - None, - marks=pytest.mark.xfail( - strict=True, - reason="PyAutoArray#610: Sibson interior-edge fallback is discontinuous", - ), - ), + # Was a strict xfail witness for PyAutoArray#610 (interior-edge fallback discontinuous). + ("sibson", None), ], ) def test_exact_nextafter_boundary_continuity_and_locator_fault( @@ -470,10 +464,7 @@ def test_knn_full_block_neighbors_kernel_and_pairing_fault(): ) -@pytest.mark.xfail( - strict=True, - reason="PyAutoArray#610: exact interior edge uses triangle weights instead of Sibson weights", -) +# Was a strict xfail witness for PyAutoArray#610 (exact interior edge used triangle weights); now a regression. def test_sibson_square_center_matches_independent_symmetry_oracle(): nodes = np.array([[-1.0, -1.0], [-1.0, 1.0], [1.0, -1.0], [1.0, 1.0]]) values = nodes[:, 0] * nodes[:, 1] @@ -492,10 +483,7 @@ def test_sibson_square_center_matches_independent_symmetry_oracle(): ) -@pytest.mark.xfail( - strict=True, - reason="PyAutoArray#610: near-edge cancellation clips negative weights after normalization", -) +# Was a strict xfail witness for PyAutoArray#610 (near-edge cancellation clipped after normalization); now a regression. def test_sibson_near_edge_preserves_partition_after_positive_filter(): # A normalize-then-clip mutation reproduces the defect mechanism while # leaving the intended constant-field oracle unchanged. diff --git a/test_autoarray/inversion/pixelization/interpolator/test_sibson_internal_edges.py b/test_autoarray/inversion/pixelization/interpolator/test_sibson_internal_edges.py new file mode 100644 index 000000000..3f497ac7b --- /dev/null +++ b/test_autoarray/inversion/pixelization/interpolator/test_sibson_internal_edges.py @@ -0,0 +1,475 @@ +""" +PyAutoArray#610: Sibson (natural-neighbour) weights at and near internal Delaunay edges. + +The weights are computed from the Bowyer-Watson cavity boundary, so a query on or near an internal edge is +regular. These tests check the three production bodies (the NumPy reference, numba and JAX) against an +independent oracle that builds the Voronoi cells by half-plane clipping and shares no code with production. +""" + +import importlib.util + +import numpy as np +import pytest +from scipy.spatial import Delaunay + +from autoarray.inversion.mesh.interpolator import sibson +from autoarray.inversion.mesh.interpolator import _sibson_numba + +requires_jax = pytest.mark.skipif( + importlib.util.find_spec("jax") is None, reason="JAX path requires jax" +) + + +# --------------------------------------------------------------------------------------------------------------- +# Independent oracle: Voronoi cells by half-plane clipping (Sutherland-Hodgman); no production code. +# --------------------------------------------------------------------------------------------------------------- + + +def _clip(polygon, through, normal): + kept = [] + for i in range(len(polygon)): + p, q = polygon[i], polygon[(i + 1) % len(polygon)] + dp, dq = normal @ (p - through), normal @ (q - through) + if dp <= 0: + kept.append(p) + if dp * dq < 0: + kept.append(p + (q - p) * (dp / (dp - dq))) + return kept + + +def _area(polygon): + if len(polygon) < 3: + return 0.0 + c = polygon[0] + return 0.5 * sum( + (polygon[i] - c)[0] * (polygon[i + 1] - c)[1] + - (polygon[i] - c)[1] * (polygon[i + 1] - c)[0] + for i in range(1, len(polygon) - 1) + ) + + +def oracle_weights(points, query, box=1.0e4): + """Sibson weights: area of (new cell of query) intersected with (old cell of each vertex), normalised.""" + corners = [(-box, -box), (box, -box), (box, box), (-box, box)] + new_cell = [np.array(c, dtype=float) for c in corners] + for p in points: + new_cell = _clip(new_cell, (query + p) / 2, p - query) + areas = {} + for i, v in enumerate(points): + cell = new_cell + for k, p in enumerate(points): + if k != i: + cell = _clip(cell, (v + p) / 2, p - v) + if len(cell) < 3: + break + area = _area(cell) + if area > 0: + areas[i] = area + total = sum(areas.values()) + return {k: a / total for k, a in areas.items()} + + +# --------------------------------------------------------------------------------------------------------------- +# Production backends on explicit tables. +# --------------------------------------------------------------------------------------------------------------- + + +def _neighbors_from(simplices): + """qhull convention: neighbors[t, j] is the triangle across the edge opposite vertex j (-1 on the hull).""" + edge_owner = {} + for t, s in enumerate(simplices): + for j in range(3): + edge = frozenset((int(s[(j + 1) % 3]), int(s[(j + 2) % 3]))) + edge_owner.setdefault(edge, []).append((t, j)) + neighbors = -np.ones_like(simplices) + for owners in edge_owner.values(): + if len(owners) == 2: + (t0, j0), (t1, j1) = owners + neighbors[t0, j0], neighbors[t1, j1] = t1, t0 + return neighbors + + +def _locate(points, simplices, query): + for t, s in enumerate(simplices): + a, b, c = points[s] + m = np.array([b - a, c - a]).T + u, v = np.linalg.solve(m, query - a) + if u >= -1e-12 and v >= -1e-12 and u + v <= 1 + 1e-12: + return t + return -1 + + +def tables(points, query, simplices=None): + if simplices is None: + triangulation = Delaunay(points) + simplices = triangulation.simplices.astype(np.int32) + neighbors = triangulation.neighbors.astype(np.int32) + seeds = triangulation.find_simplex(query).astype(np.int32) + else: + simplices = np.asarray(simplices, dtype=np.int32) + neighbors = _neighbors_from(simplices).astype(np.int32) + seeds = np.array([_locate(points, simplices, q) for q in query], np.int32) + count = simplices.shape[0] + simplices_padded = -np.ones((2 * len(points), 3), np.int32) + neighbors_padded = -np.ones_like(simplices_padded) + simplices_padded[:count] = simplices + neighbors_padded[:count] = neighbors + fallback = np.argmin(((query[:, None] - points[None]) ** 2).sum(-1), axis=1) + return dict( + query_points=query, + points=points, + simplices_padded=simplices_padded, + simplex_neighbors=neighbors_padded, + simplex_indexes=seeds, + outside_fallback_indexes=fallback.astype(np.int32), + ) + + +def run(backend, points, query, simplices=None): + kwargs = tables(np.asarray(points, float), np.asarray(query, float), simplices) + circles = sibson.delaunay_circumcircles_from( + kwargs["points"], kwargs["simplices_padded"], xp=np + ) + caps = dict(max_cavity_triangles=32, max_neighbors=32) + if backend == "numpy": + return sibson._sibson_mappings_weights_numpy_reference( + **kwargs, circumcircles=circles, **caps + ) + if backend == "numba": + return sibson._sibson_mappings_weights_numba( + **kwargs, circumcircles=circles, **caps + ) + import jax + import jax.numpy as jnp + + jax.config.update("jax_enable_x64", True) + jkwargs = {k: jnp.asarray(v) for k, v in kwargs.items()} + outputs = jax.jit( + lambda d: sibson.sibson_mappings_weights_from_tables(**d, **caps, xp=jnp) + )(jkwargs) + return tuple(np.asarray(o) for o in outputs) + + +def rows(outputs): + mappings, sizes, weights = outputs[0], outputs[1], outputs[2] + return [ + {int(mappings[i, k]): float(weights[i, k]) for k in range(sizes[i])} + for i in range(len(sizes)) + ] + + +def max_difference(a, b): + return max(abs(a.get(k, 0.0) - b.get(k, 0.0)) for k in set(a) | set(b)) + + +BACKENDS = ["numpy", "numba", pytest.param("jax", marks=requires_jax)] + +SQUARE = np.array( + [[-1.0, -1.0], [-1.0, 1.0], [1.0, -1.0], [1.0, 1.0]] + + [[-3.0, -3.0], [3.0, -3.0], [3.0, 3.0], [-3.0, 3.0]] +) + + +def _square_simplices(diagonal, clockwise=False): + """The inner square split along one of its two diagonals, plus the outer ring, as explicit triangles.""" + inner = [[0, 3, 1], [0, 2, 3]] if diagonal == "0-3" else [[0, 2, 1], [2, 3, 1]] + ring = [ + [4, 5, 2], + [4, 2, 0], + [5, 6, 3], + [5, 3, 2], + [6, 7, 1], + [6, 1, 3], + [7, 4, 0], + [7, 0, 1], + ] + simplices = np.array(inner + ring) + u = SQUARE[simplices[:, 1]] - SQUARE[simplices[:, 0]] + v = SQUARE[simplices[:, 2]] - SQUARE[simplices[:, 0]] + signed = u[:, 0] * v[:, 1] - u[:, 1] * v[:, 0] + want_negative = clockwise + flip = (signed < 0) != want_negative + simplices[flip] = simplices[flip][:, [0, 2, 1]] + return simplices + + +# --------------------------------------------------------------------------------------------------------------- +# Tests +# --------------------------------------------------------------------------------------------------------------- + + +@pytest.mark.parametrize("backend", BACKENDS) +@pytest.mark.parametrize("diagonal", ["0-3", "1-2"]) +@pytest.mark.parametrize("clockwise", [False, True]) +def test__square_centre__quarter_weights_for_either_diagonal_and_orientation( + backend, diagonal, clockwise +): + """Fourfold symmetry fixes all four weights to 1/4, whichever diagonal the triangulation picked and + whichever way its triangles are wound: the query lies exactly on that internal diagonal. + """ + simplices = _square_simplices(diagonal, clockwise=clockwise) + (row,) = rows(run(backend, SQUARE, [[0.0, 0.0]], simplices)) + + assert set(row) == {0, 1, 2, 3} + for weight in row.values(): + assert weight == pytest.approx(0.25, abs=1.0e-14) + + +@pytest.mark.parametrize("backend", BACKENDS) +def test__regular_hexagon_centre__sixth_weights(backend): + angles = np.arange(6) * np.pi / 3 + points = np.vstack( + [ + np.column_stack([np.cos(angles), np.sin(angles)]), + 4 * np.column_stack([np.cos(angles + 0.3), np.sin(angles + 0.3)]), + ] + ) + (row,) = rows(run(backend, points, [[0.0, 0.0]])) + + assert set(row) == set(range(6)) + for weight in row.values(): + assert weight == pytest.approx(1.0 / 6.0, abs=1.0e-13) + + +def _asymmetric_fixtures(): + rng = np.random.default_rng(610) + random_mesh = np.vstack( + [rng.uniform(-1, 1, (40, 2)), [[-4, -4], [4, -4], [4, 4], [-4, 4]]] + ) + rectangle = np.array( + [[x, y] for x in (-2.0, 0.0, 2.0) for y in (-1.0, 0.0, 1.0)] + + [[-6, -6], [6, -6], [6, 6], [-6, 6]] + ) + kite = np.array( + [ + [0.0, 1.0], + [0.6, 0.0], + [0.0, -2.0], + [-0.6, 0.0], + [-5, -5], + [5, -5], + [5, 5], + [-5, 5], + ] + ) + return { + "random": (random_mesh, rng.uniform(-0.8, 0.8, (25, 2))), + "rectangle_2to1": (rectangle, rng.uniform(-1.8, 1.8, (15, 2)) * [1.0, 0.5]), + "kite": (kite, np.array([[0.05, 0.1], [0.0, 0.0], [-0.2, -0.7], [0.1, -1.2]])), + } + + +@pytest.mark.parametrize("backend", BACKENDS) +@pytest.mark.parametrize("fixture", ["random", "rectangle_2to1", "kite"]) +def test__asymmetric_queries__match_independent_oracle(backend, fixture): + points, query = _asymmetric_fixtures()[fixture] + + for q, row in zip(query, rows(run(backend, points, query))): + assert max_difference(row, oracle_weights(points, q)) < 1.0e-10 + + +def _internal_edge_midpoints(points): + triangulation = Delaunay(points) + seen, midpoints = set(), [] + for t, s in enumerate(triangulation.simplices): + for j in range(3): + if triangulation.neighbors[t, j] < 0: + continue + a, b = s[(j + 1) % 3], s[(j + 2) % 3] + if frozenset((a, b)) in seen: + continue + seen.add(frozenset((a, b))) + pa, pb = points[a], points[b] + normal = np.array([-(pb - pa)[1], (pb - pa)[0]]) + midpoints.append(((pa + pb) / 2, normal / np.linalg.norm(normal))) + return midpoints + + +def _lattice_and_random(): + axis = np.linspace(-1, 1, 5) + lattice = np.array( + [[x, y] for x in axis for y in axis] + ) + 1.0e-3 * np.random.default_rng(1).normal(size=(25, 2)) + rng = np.random.default_rng(611) + return { + "lattice": np.vstack([lattice, [[-4, -4], [4, -4], [4, 4], [-4, 4]]]), + "random": np.vstack( + [rng.uniform(-1, 1, (30, 2)), [[-4, -4], [4, -4], [4, 4], [-4, 4]]] + ), + } + + +@pytest.mark.parametrize("backend", BACKENDS) +@pytest.mark.parametrize("mesh", ["lattice", "random"]) +def test__internal_edges__continuous_from_both_sides(backend, mesh): + """At every internal edge midpoint, finite and nextafter offsets on either side differ from the on-edge + row by at most L * offset: continuity (the former code jumped by up to 0.027 at 1e-8). + """ + points = _lattice_and_random()[mesh] + midpoints = _internal_edge_midpoints(points) + offsets = [1.0e-2, 1.0e-6, 1.0e-8, 1.0e-12] + + queries = [] + for midpoint, normal in midpoints: + queries.append(midpoint) + for offset in offsets: + queries += [midpoint + offset * normal, midpoint - offset * normal] + queries += [ + np.nextafter(midpoint, midpoint + normal), + np.nextafter(midpoint, midpoint - normal), + ] + results = rows(run(backend, points, np.array(queries))) + + stride = 1 + 2 * len(offsets) + 2 + lipschitz = 200.0 + for m in range(len(midpoints)): + on_edge = results[m * stride] + probes = results[m * stride + 1 : (m + 1) * stride] + for i, offset in enumerate(offsets): + for probe in probes[2 * i : 2 * i + 2]: + assert max_difference(probe, on_edge) <= lipschitz * offset + 1.0e-12 + for probe in probes[-2:]: + assert max_difference(probe, on_edge) <= 1.0e-12 + + +@pytest.mark.parametrize("backend", BACKENDS) +def test__affine_precision_partition_and_support(backend): + """Linear precision, partition of unity, non-negativity and natural-neighbour support -- including the + near-edge queries where the former code's weights summed to 1.12.""" + points = _lattice_and_random()["random"] + rng = np.random.default_rng(612) + queries = list(rng.uniform(-0.9, 0.9, (40, 2))) + for midpoint, normal in _internal_edge_midpoints(points)[:15]: + queries += [midpoint, midpoint + 1.0e-8 * normal, midpoint - 1.0e-8 * normal] + queries = np.array(queries) + + for q, row in zip(queries, rows(run(backend, points, queries))): + assert sum(row.values()) == pytest.approx(1.0, abs=1.0e-12) + assert min(row.values()) >= 0.0 + reconstructed = sum(w * points[k] for k, w in row.items()) + np.testing.assert_allclose(reconstructed, q, atol=1.0e-11, rtol=0) + assert set(row) <= set(oracle_weights(points, q)) + + +def _hull_points(): + return np.random.default_rng(613).uniform(-1, 1, (30, 2)) + + +def _hull_edges(points): + triangulation = Delaunay(points) + for t, s in enumerate(triangulation.simplices): + for j in range(3): + if triangulation.neighbors[t, j] < 0: + yield s[(j + 1) % 3], s[(j + 2) % 3], s[j] + + +@pytest.mark.parametrize("backend", BACKENDS) +def test__hull_edges__linear_on_the_edge_and_continuous_from_inside(backend): + """On a convex-hull edge Sibson coordinates are linear between its endpoints; approaching the edge from + inside they converge to that limit at O(distance).""" + points = _hull_points() + distances = [1.0e-4, 1.0e-8, 1.0e-12] + cases, queries = [], [] + for a, b, opposite in _hull_edges(points): + on_edge = points[a] + 0.37 * (points[b] - points[a]) + inward = points[opposite] - on_edge + inward /= np.linalg.norm(inward) + cases.append((a, b)) + queries.append(on_edge) + queries += [on_edge + d * inward for d in distances] + results = rows(run(backend, points, np.array(queries))) + + stride = 1 + len(distances) + for c, (a, b) in enumerate(cases): + linear = {int(a): 0.63, int(b): 0.37} + on_edge = results[c * stride] + assert max_difference(on_edge, linear) <= 1.0e-12 + for d, row in zip(distances, results[c * stride + 1 : (c + 1) * stride]): + assert max_difference(row, linear) <= 200.0 * d + 1.0e-12 + + +@pytest.mark.parametrize("backend", BACKENDS) +def test__outside_hull__nearest_vertex_fallback_unchanged(backend): + points = _hull_points() + query = np.array([[3.0, 0.2], [-2.5, -2.5]]) + nearest = np.argmin(((query[:, None] - points[None]) ** 2).sum(-1), axis=1) + + for n, row in zip(nearest, rows(run(backend, points, query))): + assert row == {int(n): 1.0} + + +def _parity_queries(): + points = _lattice_and_random()["random"] + queries = [q for q, _ in _internal_edge_midpoints(points)] + queries += list(np.random.default_rng(614).uniform(-1.2, 1.2, (40, 2))) + return points, np.array(queries) + + +@requires_jax +def test__numpy_numba_and_jax_jit__agree(): + """One algorithm, three bodies: identical mappings / sizes / flags and weights to 1e-12.""" + points, queries = _parity_queries() + reference = run("numpy", points, queries) + for backend in ("numba", "jax"): + outputs = run(backend, points, queries) + for index in (0, 1, 3, 4, 5): + np.testing.assert_array_equal(np.asarray(outputs[index]), reference[index]) + np.testing.assert_allclose(outputs[2], reference[2], rtol=1.0e-12, atol=1.0e-12) + + +def test__numba_area_tolerances_match_reference_module(): + assert _sibson_numba.ZERO_AREA_TOLERANCE == sibson.SIBSON_ZERO_AREA_TOLERANCE + assert ( + _sibson_numba.NEGATIVE_AREA_TOLERANCE == sibson.SIBSON_NEGATIVE_AREA_TOLERANCE + ) + + +def _exact_lattice(n=9): + axis = np.linspace(-1.0, 1.0, n) + return np.array([[x, y] for x in axis for y in axis]), axis[1] - axis[0] + + +def test__delaunay_nn_magnification_areas__integrate_sibson_basis(): + """ + `MeshGeometryDelaunayNN.areas_for_magnification` integrates the Sibson basis functions. On an exact + lattice (every cell cocircular) symmetry fixes each interior vertex's integral to the cell area h^2 + (which the corrected internal-edge weights now honour), the areas tile the hull, and they integrate a + linear field exactly up to quadrature error. + """ + from autoarray.inversion.mesh.mesh_geometry.delaunay import ( + basis_integral_areas_from, + basis_quadrature_points_from, + ) + + nodes, h = _exact_lattice() + points = basis_quadrature_points_from(nodes) + mappings, _, weights = sibson.sibson_mappings_weights_from(nodes, points) + areas = basis_integral_areas_from(nodes, mappings, weights) + + assert areas.sum() == pytest.approx(4.0, rel=1.0e-12) + + interior = np.all(np.abs(nodes) < 1.0 - 1.5 * h, axis=1) + np.testing.assert_allclose(areas[interior], h * h, rtol=2.0e-3) + + linear = 0.3 + 1.7 * nodes[:, 0] - 0.4 * nodes[:, 1] + assert np.sum(areas * linear) == pytest.approx(4.0 * 0.3, rel=1.0e-3) + + +def test__delaunay_nn_interpolator__uses_sibson_basis_geometry(): + import autoarray as aa + from autoarray.inversion.mesh.mesh_geometry.delaunay import ( + MeshGeometryDelaunayNN, + ) + + nodes, _ = _exact_lattice(5) + mesh_grid = aa.Grid2DIrregular(values=nodes[:, ::-1]) + data_grid = aa.Grid2D.uniform(shape_native=(4, 4), pixel_scales=0.3) + mesh = aa.mesh.DelaunayNN(pixels=nodes.shape[0]) + interpolator = mesh.interpolator_cls( + mesh=mesh, mesh_grid=mesh_grid, data_grid=data_grid + ) + + assert isinstance(interpolator.mesh_geometry, MeshGeometryDelaunayNN) + assert interpolator.mesh_geometry.areas_for_magnification.sum() == pytest.approx( + 4.0, rel=1.0e-12 + ) diff --git a/test_autoarray/inversion/pixelization/interpolator/test_sibson_numba.py b/test_autoarray/inversion/pixelization/interpolator/test_sibson_numba.py index d1c2780d9..27ed19733 100644 --- a/test_autoarray/inversion/pixelization/interpolator/test_sibson_numba.py +++ b/test_autoarray/inversion/pixelization/interpolator/test_sibson_numba.py @@ -114,7 +114,15 @@ def test__cocircular_grid__on_vertex_on_edge_and_collinear_queries(): assert reference[1][0] == 1 and reference[0][0, 0] == 7 -def test__thin_triangle__degenerate_watson_circle_matches_reference(): +def test__thin_triangle__near_internal_edge__regular_and_matches_reference(): + """ + Queries on, or 1e-15 / 1e-12 off, the thin triangle's base edge (0,0)-(1,0) -- an INTERNAL edge, with + (0.5, -100) below it. The former Watson decomposition formed a collinear circle through that edge and + returned NaN (degenerate) rows at 1e-15 and an edge-barycentric row on it that dropped the off-edge + natural neighbours. The boundary formulation (PyAutoArray#610) is regular there: every row is a finite + partition of unity, continuous across the edge, and agrees with an independent Voronoi-clipping oracle + to ~1e-12 (measured when this test was rewritten). + """ points = np.array( [ [0.0, 0.0], @@ -140,8 +148,27 @@ def test__thin_triangle__degenerate_watson_circle_matches_reference(): reference, numba_outputs = _reference_and_numba(points, query) _assert_parity(reference, numba_outputs) - assert reference[5].tolist() == [True, False, False, False, True, False] - assert np.isnan(numba_outputs[2][0]).all() + mappings, sizes, weights, _, overflow, degenerate = reference + assert not degenerate.any() and not overflow.any() + assert np.isfinite(weights).all() + + def row(i): + return {int(mappings[i, k]): weights[i, k] for k in range(sizes[i])} + + for i in range(len(query)): + assert sum(row(i).values()) == pytest.approx(1.0, abs=1.0e-12) + reconstructed = sum(w * points[k] for k, w in row(i).items()) + np.testing.assert_allclose(reconstructed, query[i], atol=1.0e-11, rtol=0) + + # On the edge (row 1) and 1e-15 / 1e-12 above it (rows 0, 5): one continuous row that keeps the + # off-edge natural neighbours (the thin apex 2 and the far vertex 3). + on_edge = row(1) + assert set(on_edge) == {0, 1, 2, 3} + for i in (0, 5): + assert set(row(i)) == set(on_edge) + for k in on_edge: + assert row(i)[k] == pytest.approx(on_edge[k], abs=1.0e-10) + assert on_edge[2] == pytest.approx(0.10498950105, abs=1.0e-9) @pytest.mark.parametrize(