WritingScientific computing

From measured points to Zernike coefficients

How I turn native corneal samples into maps and Zernike descriptors in CorneaForge, with explicit reference surfaces, coordinates and units.

Updated

In this article

I built CorneaForge’s geometry engine to turn measured corneal points into maps physicians can inspect in OphtaFlow AI and numerical descriptors of surface shape. I implemented two paths: interpolation for the maps, and direct fitting of Zernike coefficients for the descriptors. Both start from the same measured points on a polar grid.

The elevation-fitting path extracts valid coordinates, forms residuals against a conic reference surface, and solves a least-squares problem on those points. It returns coefficients in micrometers and a fit residual. The rendering path evaluates an interpolant on a pixel grid. This gives me both a view of the measured surface and a compact numerical description for analysis.

Here is how those calculations work, using a small constructed surface that makes each step visible.

First locate the observations

Suppose an instrument samples a surface on concentric rings. Each observation contains a radius r, an angle θ, and a value z.

To place the observation on a Cartesian diagram, use:

x = r cos(θ)
y = r sin(θ)

For r = 2 and θ = π/2, the location is approximately (0, 2). Its measured value travels with it.

From these coordinates, I take two paths. Rendering evaluates values on a regular pixel grid suitable for visualization or an image model. Zernike fitting uses the original point coordinates directly, so each retained instrument sample contributes once to the fitting objective.

Build a map from neighboring measurements

Consider two measurements on a line: 10 at the left endpoint and 20 at the right. Linear interpolation fills the interval with a straight line, giving 15 at the midpoint. The rendering algorithm uses this rule to estimate values between measured locations.

In two dimensions, a triangle provides an equally simple construction. Let its vertices be:

Vertex Position Value
A (0, 0) 10
B (1, 0) 20
C (0, 1) 40

At q = (0.25, 0.25), the barycentric weights are 0.5, 0.25, and 0.25. These numbers express the position itself:

q = 0.5 A + 0.25 B + 0.25 C

Use the same weights for the values:

z(q) = 0.5 × 10 + 0.25 × 20 + 0.25 × 40 = 20

Inside the triangle, the weights are nonnegative and sum to one. Along an edge, one weight becomes zero. At a vertex, its weight is one and the others are zero. These are useful checks on an implementation before examining a complicated map.

With many source points, a triangulation defines which triples provide the local interpolation. A Delaunay triangulation uses the source positions; the measured values are supplied afterwards. Its empty-circumcircle condition says that a triangle’s circumcircle contains no other source point strictly inside it. The selected triangulation then fixes the triangles used by the interpolator.

SciPy’s LinearNDInterpolator implements this piecewise linear construction and accepts a precomputed Delaunay triangulation. Its handling of queries outside the convex hull is explicit: the default fill value is NaN.

Missing measurements change the triangles, sometimes creating wider spans across gaps. In CorneaForge, that dependency also shapes the interpolation cache: the positions of valid samples are part of the identity of the reusable operator.

Describe a surface with a few shapes

A basis expansion describes the surface as a weighted combination of chosen shapes. The weights are its coefficients.

Zernike polynomials form a family of functions on a disk, widely used in optics. In this constructed example, values use arbitrary units and three real, unnormalized modes. Normalize the radius as ρ = r/R, where R is the analysis radius:

Z₀ = 1
Z₁ = 2ρ² − 1
Z₂ = ρ² cos(2θ)

The first adds a constant height. The second changes the surface radially. The third adds an oriented variation. We can construct a surface by choosing their coefficients:

z(ρ, θ) = 0.2 Z₀ + 0.4 Z₁ − 0.3 Z₂

At the center, ρ = 0, so the value is 0.2 − 0.4 = −0.2. At the right edge, ρ = 1, θ = 0, it becomes 0.2 + 0.4 − 0.3 = 0.3. At the upper edge, θ = π/2, the cosine changes sign and the value becomes 0.9.

Build a surface from three modesSynthetic worked example
Surface values are also given in the text below.

z = a + b(2ρ² − 1) + cρ² cos(2θ)

Centre: −0.20. Right edge: 0.30. Top edge: 0.90.

Non-normalized modes, arbitrary units, fixed colour scale from −3 to +3.

Recover the mixture from samples

If we know the sample locations but not the coefficients, we can evaluate each basis function at each location. Arrange those evaluations into a matrix A: one row per sample and one column per mode.

Then A c gives the predicted sample values for a coefficient vector c. Fitting asks for coefficients that make those predictions close to the observed vector z:

choose c to minimize ||A c − z||²

Here is the complete calculation for those three modes:

import numpy as np

rho = np.array([0.0, 1.0, 1.0, 0.5])
theta = np.array([0.0, 0.0, np.pi / 2, np.pi / 4])

A = np.column_stack([
    np.ones_like(rho),
    2 * rho**2 - 1,
    rho**2 * np.cos(2 * theta),
])
coefficients = np.array([0.2, 0.4, -0.3])
observations = A @ coefficients

estimated, _, rank, singular_values = np.linalg.lstsq(
    A, observations, rcond=None
)
residual = observations - A @ estimated

assert rank == 3
assert np.allclose(estimated, coefficients)
assert np.allclose(residual, 0.0)

A has shape (4, 3): four points, three modes. Both coefficient vectors have length three; the observation and residual vectors have length four. The points provide enough independent information to identify the three coefficients, and there is no noise, so the recovery works to numerical precision.

On real data, the residual measures how closely the chosen modes fit the available observations. More modes increase flexibility but can make the coefficients sensitive to noise and incomplete sampling. NumPy’s least-squares documentation describes the returned rank and singular values, which help inspect that numerical stability.

The coordinate convention is part of the result

Even with identical input values, changing the analysis disk changes the fit. A physical point at radius 2 mm has ρ = 0.5 when R = 4 mm and ρ = 1 when R = 2 mm. The basis functions evaluate differently at that point.

Centering sets the origin from which the coordinates are measured. Rotation sets the orientation of angular modes. Removing piston shifts the height reference. These operations act on different parts of the calculation, so I specify center, orientation, analysis radius, mode ordering and normalization together.

Zernike modes are orthogonal over a continuous disk under their defined area measure. In the sampled problem, the locations and weights of the observations determine the relationships between columns of A.

My implementation uses ordinary least squares with equal weight per retained sample. Ring sampling and missing sectors therefore shape the fitting objective. This is a deliberate, inspectable property of the computation: the solver minimizes the summed squared error at the measured points.

The elevation fit I implemented

The elevation path in CorneaForge fits 36 normalized Zernike terms through radial order 7, within a default analysis radius of 4 mm. It uses a conic reference surface, with separate anterior and posterior shape parameters. Sag is the surface height relative to the apex; the fitted residual is reference sag minus measured sag. Preserving that sign convention matters: reversing it reverses the fitted coefficients.

The solver evaluates the basis at the original valid point coordinates and converts its fitted coefficients from millimeters to micrometers. It also returns the root mean square of the remaining residual, in millimeters, so the surface descriptor travels with a measure of fit error.

These coefficients describe residual elevation. A wavefront calculation instead fits optical path differences, incorporating the relevant surfaces, refractive indices and ray geometry. The fitted quantity belongs alongside the coefficient vector, as do the coordinate and basis conventions addressed by the VSIA taskforce’s standards for reporting optical aberrations.

For an ML pipeline, these coefficients offer a compact representation of surface shape. I can compare that representation with image-based features while retaining the reference surface, radius, normalization and units needed to interpret the experiment.

I built the next stages around two questions: how does the reference surface change the residual? And how does the measured shape change the path of light? They lead from this least-squares fit into the three-dimensional geometry and optical engine of CorneaForge.