Skip to content

fix: Preserve Sibson coordinates across internal edges #610

Closed

Description

@Jammy2211

Overview

Audit #603 found incorrect internal-edge Sibson coordinates and near-edge cancellation that can return weights summing above one without a diagnostic flag. This follow-up is filed separately; the audit retains strict expected-failure witnesses.

Plan

  • Reproduce independent square-symmetry, partition and both-sided continuity failures.
  • Preserve natural-neighbor support on internal edges and distinguish hull-edge limits.
  • Handle area cancellation before normalization and positive filtering.
  • Validate eager/JIT behavior and promote audit regressions after repair.
Detailed implementation plan

Affected repositories: PyAutoArray (primary), autolens_workspace_test. Suggested branch: feature/sibson-internal-edge-continuity.

Inspect autoarray/inversion/mesh/interpolator/sibson.py:_sibson_single_from_tables, especially normalization/positive filtering and the unconditional on-edge barycentric fallback. Establish independent symmetric and asymmetric reference coordinates before choosing an algorithmic repair. Test internal versus hull edges, exact/nextafter/finite offsets, nonnegative partition and affine precision, diagnostic flags and eager/JIT parity. Run focused interpolation tests, full library tests and downstream source-recovery smoke. Queue behind audit #603; no implementation or new worktree begins during filing.

Current shared worktrees are on feature/mesh-interpolator-numerics-audit with audit-only tests/scripts uncommitted. User explicitly authorized separate filing of bugs found by the audit.

Original Prompt

Audit finding and authorized follow-up

Fix Sibson interpolation at internal edges

Type: bug
Target: PyAutoArray
Repos:

  • PyAutoArray
  • autolens_workspace_test
    Difficulty: large
    Autonomy: supervised
    Priority: high
    Status: formalised
    Consequence: glance
    Witness: Square-symmetry center weights are 1/4 each; near-edge weights remain nonnegative, sum to one, and agree continuously from both sides under eager/JIT execution.
    Review-minutes: 15
    Unattended: ready

Fix Sibson interpolation at internal edges

Type: bug
Target: autoarray
Repos:

  • PyAutoArray
  • autolens_workspace_test
    Difficulty: large
    Autonomy: supervised
    Priority: high
    Witness: Square-symmetry center weights are 1/4 each; near-edge weights remain nonnegative, sum to one, and agree continuously from both sides under eager/JIT execution.
    Review-minutes: 15

Found during approved audit PyAutoArray#603. Original user instruction: "Any bug found is filed separately; this task is the audit, not the fixes."

In autoarray/inversion/mesh/interpolator/sibson.py:_sibson_single_from_tables, every on-edge query is replaced with seed-triangle barycentric weights, including internal edges where off-edge natural neighbors contribute. For square points [(-1,-1),(-1,1),(1,-1),(1,1)], query(0,0), independent symmetry requires four weights0.25 and interpolated y*x=0. Actual weights0.5 for opposite diagonal nodes yield1. Lattice mesh boundary sweep found jumps up to0.02680921 at +/-1e-8 around internal edge midpoints.

Near the square center at (+/-1e-8,0), cancellation yields returned positive weights summing1.123877166 and interpolated yx=-1.123877166, with no overflow/degenerate flag. Code normalizes signed contributions before discarding negative weights. At epsilon0.01 weights sum1 and yx is near0; error worsens at1e-6 and1e-8.

Plan a separate algorithmic repair preserving full natural-neighbor cavities at internal edges, using a hull-edge limiting rule only where appropriate, and robustly handling area cancellation before normalization/filtering. Validate independent symmetric and asymmetric reference fixtures, both-sided finite and nextafter edge probes, affine precision, partition/nonnegative support, eager/JIT parity and source recovery. Promote audit strict xfails after repair. No production fix is part of audit#603; shared worktrees remain claimed by the audit until shipping.

Activity

  1. Jammy2211 commented on Nov 9, 2026

    @Jammy2211
    CollaboratorAuthor

    Algorithm plan (2026-11-09): for maintainer approval before any implementation

    Root cause

    _sibson_single_from_tables (and its numba twin _sibson_numba._sibson_from_tables) uses Watson's per-triangle decomposition. For every cavity triangle it forms the circle through the query q and each of that triangle's three edges, including edges interior to the cavity. Those interior terms cancel in exact arithmetic, but when q is on or near an interior edge that circle is (nearly) collinear and its centre runs to infinity. That produces both audit failures:

    • Exactly on an edge, the code avoids the singularity by returning the seed triangle's barycentric row. That's the correct limit only on a hull edge. On an internal edge it drops the off-edge natural neighbours (square centre: 0.5 / 0.5 on the diagonal instead of 0.25 × 4).
    • Near an edge, the huge cancelling terms are normalised and then negatives are clipped (normalise-then-filter), so the partition breaks (Σw = 1.1239 at 1e-8).

    Proposed algorithm: stolen areas from the cavity boundary only (no circle through an interior edge)

    The stolen area of natural neighbour v is |cell_new(q) ∩ cell_old(v)|, a convex polygon. Its boundary decomposes into segments, each separating two sites, so its area is a sum of segment terms ½·cross(P−q, P′−q), measured relative to q and credited (+/−) to the two sites the segment separates:

    1. Cavity-interior edge (a,b) shared by cavity triangles T, T′: the old Voronoi edge c(T) → c(T′), credited +b / −a (for CCW a→b in T). Only stored circumcentres are used here, never a circle through q.
    2. Cavity-boundary edge (a,b) of triangle T: the in-cell piece c(T) → c_new(q,a,b) of the a|b Voronoi edge, credited +b / −a. c_new(q,a,b) is the only circle through q, and it is formed only on boundary edges.
    3. Bisector of q and v: c_new(q,a,v) → c_new(q,v,b), where (a,v) and (v,b) are v's incoming and outgoing boundary edges (exactly one each, since the cavity is a topological disk). Credited to v.

    Since q lies strictly inside the cavity, it is collinear with a boundary edge only if that edge is a hull edge and q is on it. Internal edges through or near q are interior to the cavity and are never singular, so no on-edge special case is needed at internal edges.

    Rules by case:

    • On a vertex: existing vertex fallback (unchanged).
    • Outside the hull: existing outside fallback (unchanged).
    • Exactly collinear with a hull boundary edge (the new circle is undefined): hull-edge limit, linear interpolation between that edge's endpoints. This rule is applied only there.
    • Everything else, including exactly on internal edges: the boundary formulation.

    Area cancellation is handled before normalisation:

    • Every term is bounded by the scale of the new cell; there are no 1/δ terms.
    • Each neighbour's area is ≥ 0 in exact arithmetic. Clamp negatives with |neg| ≤ tol·total to 0 before normalising. A larger negative, or a mismatch between Σ areas and the independently summed new-cell polygon area (the closed loop of step-3 vertices), raises the existing degenerate flag (NaN row; the perf: skip Sibson row padding in adaptive signals and unique mappings (DelaunayNN imaging) #629 empty_failed contract is kept).
    • Normalise last.

    Shapes and caps are unchanged:

    • The neighbour set is the cavity vertex set, which equals the boundary vertex set (a Bowyer–Watson cavity has no interior vertex), so max_neighbors semantics are unchanged.
    • Boundary edges ≤ C + 2, against the 3C Watson circles today, so there are fewer circumcircle evaluations per query.
    • Step-3 pairing is a scatter of c_new into the existing compact neighbour slots (in/out per vertex): static-shape for JAX, a flat loop for numba.

    Prototype evidence (standalone NumPy, brute cavity, independent oracle = half-plane-clipped Voronoi cells)

    case current library (audit) boundary formulation
    square centre, on the internal diagonal 0.5 / 0.5 diagonal, y·x = 1 0.25 × 4, exact; triangulation-independent
    square, x = ±1e-2 / ±1e-6 / ±1e-8 / ±nextafter(0) Σw = 1.1239 at 1e-8 Σw = 1 (to 1e-15), oracle ≤ 7.5e-14, affine ≤ 1.2e-16
    random 44-point mesh, 5 asymmetric interior queries — oracle ≤ 7.5e-14, affine ≤ 7e-16
    all 82 internal-edge midpoints, |w(±δ) − w(on edge)| jumps up to 0.0268 at ±1e-8 (lattice) 2.4e-7 / 2.4e-9 / 2.4e-11 at δ = 1e-8 / 1e-10 / 1e-12: Lipschitz (ratio ≈ 24), no jump
    approaching a hull edge, d = 1e-2 … 1e-14 inside — |w − linear limit| = O(d) (ratio ≈ 40) down to 1e-14; affine ≤ 3e-15; so no near-hull switch tolerance is needed, only exact collinearity

    Implementation surfaces

    • autoarray/inversion/mesh/interpolator/sibson.py: _sibson_single_from_tables, the NumPy and JAX bodies. Keep the BFS cavity (_cavity_triangle_indexes_{numpy,jax}); replace Watson contributions, on-edge override and normalise-then-filter.
    • autoarray/inversion/mesh/interpolator/_sibson_numba.py: _sibson_from_tables, same algorithm in both the prange and serial builds (fix: run numba prange kernels serially in multiprocessing search workers (#676) #677).
    • Interplay with the open Mind draft sibson_serial_kernel_loses_allocation_hoisting (same numba body): land this repair first, then do the hoisting on the new body. Rewriting the per-query scratch twice would be wasted work.

    Validation (as the prompt asks)

    1. Independent symmetric references: square centre (both diagonal choices) gives 1/4 each; regular hexagon centre gives 1/6 each; both with y·x / linear fields exact.
    2. Independent asymmetric references: half-plane Voronoi-clipping oracle (test-local, no production code) on random meshes and on 2:1 rectangle and kite fixtures, to 1e-12.
    3. Both-sided edge probes: every internal-edge midpoint of a lattice and a random mesh at ±1e-2, ±1e-6, ±1e-8 and nextafter normal offsets. Continuity asserted as |w(±δ) − w(0)| ≤ L·δ + 1e-14, with the exactly-on-edge value equal to the limit.
    4. Affine precision: Σ wᵢ pᵢ = q and linear fields exact to 1e-12, including near-edge and near-hull queries.
    5. Partition and support: Σw = 1 to 1e-12, w ≥ 0, support ⊆ natural neighbours; NaN only on declared overflow/degenerate.
    6. Eager / JIT / NumPy / numba parity to 1e-12 on all fixtures, plus the existing test__sibson_serial_kernel_equals_parallel_kernel.
    7. Hull: inside-approach converges to the linear limit; exactly-on-hull equals the linear rule; outside is unchanged.
    8. Promote the audit's strict xfails test_sibson_square_center_matches_independent_symmetry_oracle and test_sibson_near_edge_preserves_partition_after_positive_filter to ordinary tests.
    9. Source recovery and workspace: autolens_workspace_test misc/jax_assertions/{delaunay_nn, delaunay_nn_caps}.py, imaging/mesh_interpolator_source_recovery.py and the DelaunayNN jax_likelihood scripts. Also measure the per-query kernel cost (autolens_profiling delaunay_nn scripts): expected neutral-or-faster with C+2 circles instead of 3C.

    Phasing and consequence (for your decision)

    • Phasing. The Feature Agent suggests splitting into phases. I recommend splitting by repo, not by body: the NumPy/JAX and numba bodies are parity-tested against each other, so changing one without the other leaves main red. That gives PR 1: PyAutoArray, both bodies plus the full test suite above. PR 2: autolens_workspace_test DelaunayNN pins.
    • Consequence. The prompt declares glance. DelaunayNN likelihoods will change wherever data points sit on or near internal edges, which is common: Hilbert image-mesh vertices are data-pixel centres, so traced data points can land exactly on edges. I recommend treating this as judge (human /prm), as with fix: pseudo-determinant for intrinsic regularization log det H #683/fix: KNN neighbour search for a partial final point block #684.

    Implementation waits for approval of: (a) the boundary-formulation algorithm, (b) the PR split, (c) the consequence tier.

    Prototype core (standalone; the oracle and probe drivers are in the session scratch)
    import numpy as np
    from scipy.spatial import Delaunay
    
    def circumcentre(a, b, c):
        ax, ay = a; bx, by = b; cx, cy = c
        d = 2.0 * (ax * (by - cy) + bx * (cy - ay) + cx * (ay - by))
        ux = ((ax*ax + ay*ay) * (by - cy) + (bx*bx + by*by) * (cy - ay) + (cx*cx + cy*cy) * (ay - by)) / d
        uy = ((ax*ax + ay*ay) * (cx - bx) + (bx*bx + by*by) * (ax - cx) + (cx*cx + cy*cy) * (bx - ax)) / d
        return np.array([ux, uy])
    
    def cross(u, v):
        return u[0] * v[1] - u[1] * v[0]
    
    def sibson_boundary(points, tri, q):
        """Unnormalised stolen areas {vertex: area}; normalise after clamping tiny negatives."""
        simp, nbr = tri.simplices, tri.neighbors          # scipy simplices are CCW
        cc = np.array([circumcentre(*points[s]) for s in simp])
        r2 = np.array([np.sum((points[s[0]] - cc[i]) ** 2) for i, s in enumerate(simp)])
        in_cavity = np.sum((cc - q) ** 2, axis=1) < r2     # production: seeded BFS
        w, c_in, c_out = {}, {}, {}
        credit = lambda k, x: w.__setitem__(k, w.get(k, 0.0) + x)
        for t in np.flatnonzero(in_cavity):
            s = simp[t]
            for j in range(3):
                a, b = s[(j + 1) % 3], s[(j + 2) % 3]      # CCW edge a->b opposite vertex j
                other = nbr[t, j]
                if other >= 0 and in_cavity[other]:          # cavity-interior edge: old Voronoi edge
                    if t < other:
                        seg = 0.5 * cross(cc[t] - q, cc[other] - q)
                        credit(b, seg); credit(a, -seg)
                else:                                        # cavity-boundary edge: only circle through q
                    cn = circumcentre(q, points[a], points[b])   # exact collinearity => hull-edge linear rule
                    seg = 0.5 * cross(cc[t] - q, cn - q)
                    credit(b, seg); credit(a, -seg)
                    c_in[b], c_out[a] = cn, cn
        return {v: w[v] + 0.5 * cross(c_in[v] - q, c_out[v] - q) for v in w}

    Generated by Claude Code

  2. Jammy2211 commented on Nov 9, 2026

    @Jammy2211
    CollaboratorAuthor

    Library PR Created: #685 (+ workspace autolens_workspace_test#359)

    The approved plan is implemented, split by repo, tier judge.

    • Algorithm: natural-neighbour areas from the cavity boundary, identical in the NumPy/JAX body and the numba body (parallel + serial). Validated against an independent Voronoi-clipping oracle, the square centre (both diagonals and windings), both-sided edge probes (Lipschitz), the hull limit, and NumPy = numba = JAX-jit parity. The audit's 3 strict xfails are promoted. Full suite 2402 passed / 0 xfailed.
    • Departures from the plan, both forced by measurement:
      1. Hull rule keyed on exact hull collinearity (an invalid boundary circle), not on the seed-barycentric tolerance. The two tolerances could disagree in a sliver and produce NaN rows. No near-hull switch is needed: weights converge to the linear limit at O(d) down to 1e-14.
      2. DelaunayNN magnification areas. Once the weights were corrected, the Delaunay dual-area approximation biased mesh_magnification.py's identity leg by −2.65% (1% tolerance). DelaunayNN now integrates its own Sibson basis (the feat: exact KNN mesh magnification areas + fix partial-block neighbour search (arc phase 4b) #665 kNN quadrature, shared), giving +0.04%, better than main's −0.41%. This affects the magnification diagnostic only, not the likelihood.
    • Performance: the numba serial kernel (every Nautilus worker) is about 20% faster than main at HST size. Parallel is within noise. An initial port was slower; three exact rewrites removed that (details in fix: Sibson weights from the cavity boundary, regular at internal edges #685).
    • Plan validation item 9: an exact-cocircular lattice wasn't covered by my jittered lattice tests. It's now covered, and the implementation matches the oracle there to 5e-12.

    Generated by Claude Code

  3. Jammy2211 commented on Nov 9, 2026

    @Jammy2211
    CollaboratorAuthor

    Library merged: #685 (af80e69), 2026-11-09, via /prm with CI 3/3 green

    This stays open for the workspace half, autolens_workspace_test#359 (documentation only). Its smoke CI is red for reasons outside its diff:

    1. The fix: pseudo-determinant for intrinsic regularization log det H #683 figure-of-merit pins are not yet on workspace main (they're in autolens_workspace_test#358). The three failing scripts are imaging/jax_likelihood/{delaunay,rectangular}.py and interferometer/jax_likelihood/rectangular.py.
    2. The PyAutoHeart smoke-tests.yml warnings NameError.

    In that same run, mesh_magnification.py, mesh_interpolator_source_recovery.py and the DelaunayNN assertions all pass against #685.

    Order to finish: fix PyAutoHeart, then /prm #358, then /prm #359.


    Generated by Claude Code

  4. Jammy2211 commented on Nov 9, 2026

    @Jammy2211
    CollaboratorAuthor

    Shipped — 2026-11-09

    • Library: fix: Sibson weights from the cavity boundary, regular at internal edges #685 (af80e69). Sibson weights now come from the cavity boundary, so they're regular at internal edges. The hull-edge rule applies only on exact hull collinearity, and round-off-sized areas are snapped before normalising. It's the same algorithm in the NumPy/JAX and numba (parallel + serial) bodies. DelaunayNN magnification areas integrate the Sibson basis.
    • Workspace: docs: mesh_magnification — DelaunayNN integrates its Sibson basis autolens_workspace_test#359 (5857d49), documentation for mesh_magnification.py.
    • Witness: square centre 1/4 each (both diagonals and windings); weights stay non-negative, sum to one, and are continuous from both sides of internal edges (Lipschitz to nextafter); NumPy = numba = JAX-jit. The audit's 3 strict xfails are promoted.
    • Pending release: PyAutoArray.
    • Re-measure on the new kernel: the Mind draft sibson_serial_kernel_loses_allocation_hoisting.

    Generated by Claude Code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions