xy_zernike_least_squares#

pyzernike.xy_zernike_least_squares(x: ndarray, y: ndarray, values: ndarray, order: Integral, parameters: str | Sequence[str] = ('x0', 'y0', 'Rx', 'Ry'), *, fit_coefficients: bool = False, coefficients: Sequence[float] | ndarray | None = None, Rx: Real | None = 1.0, Ry: Real | None = 1.0, x0: Real | None = 0.0, y0: Real | None = 0.0, alpha: Real | None = 0.0, h: Real | None = 0.0, weights: ndarray | None = None, normalize: bool = False, use_recursive: bool = False, extrapolate: bool = True) → Tuple[Callable[[ndarray], ndarray], Callable[[ndarray], ndarray]][source]#

Build the residual and the Jacobian functions of the least squares fit of a sampled function with Zernike polynomials on an elliptic annulus whose parameters are also unknown, to be given to any least squares solver.

../_images/elliptic_annulus_domain.png

The parameters of the elliptic annulus domain.#

The function \(f\) sampled at the points \((x_k, y_k)\) is modeled by:

\[W(x, y; c, p) = \sum_{j=0}^{P-1} c_j Zxy_j(x, y; p)\]

where \(Zxy_j(\cdot; p)\) is the Zernike polynomial of OSA/ANSI index \(j\) on the elliptic annulus of parameters \(p\) (see pyzernike.xy_zernike_polynomial()) and \(P = \frac{(N+1)(N+2)}{2}\). The unknowns are gathered in the vector:

\[q = (p_1, \dots, p_Q) \quad \text{(or } q = (c_0, \dots, c_{P-1}, p_1, \dots, p_Q) \text{ if ``fit_coefficients=True``)}\]

where \(p_1, \dots, p_Q\) are the free parameters of the annulus given by parameters, in this order. The other parameters keep the values given by Rx, Ry, x0, y0, alpha and h. The returned functions compute the weighted residuals and their Jacobian:

\[r_k(q) = \sqrt{w_k} \left( W(x_k, y_k; q) - f_k \right) \quad \text{and} \quad J_{ki}(q) = \frac{\partial r_k}{\partial q_i}\]

with \(\frac{\partial W}{\partial c_j} = Zxy_j\) and \(\frac{\partial W}{\partial p_i} = \sum_j c_j \frac{\partial Zxy_j}{\partial p_i}\) (exact, see pyzernike.xy_zernike_parameter_derivative()). Any solver of non-linear least squares problems can then minimize \(\frac{1}{2} \| r(q) \|^2\): scipy.optimize.least_squares(residual, q0, jac=jacobian), a Gauss-Newton or Levenberg-Marquardt algorithm, pysolve-gn, …

Samples. The residuals are computed at the valid samples only, i.e. where x, y, values and weights are finite and the weight is strictly positive, in the order of the flattened arrays: the residual vector has the length \(K\) of x[mask] (mask the boolean array of the valid samples) for all \(q\).

Identifiability. A shift, a scaling or a rotation of the pupil transforms a polynomial of degree \(N\) into another polynomial of degree \(N\): for a full ellipse (\(h = 0\)), a change of the parameters \((x_0, y_0, R_x, R_y, \alpha)\) is exactly compensated by a change of the coefficients (see pyzernike.zernike_coefficients_transform()). These parameters can therefore be estimated from the values of the function only if the coefficients are known (fit_coefficients=False, e.g. the known aberrations of a reference optics). Fitting them jointly with the coefficients gives a singular Jacobian for \(h = 0\) (a RuntimeWarning is emitted), and a poorly conditioned problem for \(h > 0\). The position and the size of the pupil are then better measured from its boundary (e.g. on an intensity image). See the page Fitting for the details.

Points outside the annulus. The set of the points inside the annulus changes with \(p\), which is not differentiable. With extrapolate=True (recommended), the polynomials are evaluated with their polynomial expression at all the samples, also slightly outside the current annulus, so that \(r(q)\) is a smooth function of \(q\) and all the samples always contribute. With extrapolate=False, the residuals and the rows of the Jacobian of the samples outside the current annulus are set to zero: the cost can then decrease by shrinking the annulus, so this option should only be used with a good initial guess.

Note

The functions raise a ValueError if \(q\) gives an invalid annulus (\(R_x \leq 0\), \(R_y \leq 0\) or \(h\) outside \([0, 1)\)). With scipy.optimize.least_squares, use the bounds argument to keep the parameters in their domain. The last evaluation is cached: calling the Jacobian after the residuals at the same \(q\) does not compute the polynomials again.

See also

Parameters:
  • x (numpy.ndarray) – The x Cartesian coordinates of the samples, with any shape (...).

  • y (numpy.ndarray) – The y Cartesian coordinates of the samples, with the same shape as x.

  • values (numpy.ndarray) – The sampled values \(f_k\), with the same shape as x.

  • order (Integral) – The maximum radial order \(N \geq 0\) of the model.

  • parameters (Union[str, Sequence[str]], optional) – The free parameter(s) of the annulus, among "x0", "y0", "Rx", "Ry", "alpha" and "h", without duplicates, in the order of the vector of unknowns. An empty sequence means that the annulus is fixed. Default is ("x0", "y0", "Rx", "Ry").

  • fit_coefficients (bool, optional) – If False, the coefficients are fixed to coefficients. If True, the coefficients are unknowns, placed before the parameters of the annulus in \(q\) (see the identifiability above). Default is False.

  • coefficients (Optional[Union[Sequence[float], numpy.ndarray]], optional) – The fixed coefficients in the OSA/ANSI ordering, as a 1D array of \(P = \frac{(N+1)(N+2)}{2}\) finite real numbers. Required if fit_coefficients is False (default), and must be None otherwise. Default is None.

  • Rx (Optional[Real], optional) – The semi-axis \(R_x\) of the ellipse along its x axis (fixed value, or ignored if free). Default is 1.0.

  • Ry (Optional[Real], optional) – The semi-axis \(R_y\) of the ellipse along its y axis (fixed value, or ignored if free). Default is 1.0.

  • x0 (Optional[Real], optional) – The x coordinate \(x_0\) of the center of the ellipse (fixed value, or ignored if free). Default is 0.0.

  • y0 (Optional[Real], optional) – The y coordinate \(y_0\) of the center of the ellipse (fixed value, or ignored if free). Default is 0.0.

  • alpha (Optional[Real], optional) – The rotation angle \(\alpha\) of the ellipse in radians (fixed value, or ignored if free). Default is 0.0.

  • h (Optional[Real], optional) – The ratio \(h\) of the inner to the outer semi-axes, in \([0, 1)\) (fixed value, or ignored if free). Default is 0.0 (full ellipse).

  • weights (Optional[numpy.ndarray], optional) – The weights \(w_k \geq 0\) of the samples, with the same shape as x. Default is None (all the weights are equal to 1).

  • normalize (bool, optional) – If True, the coefficients are those of the polynomials normalized by the factors of Noll \(N_{n}^{m} = \sqrt{(2 - \delta_{m0})(n + 1)}\). Default is False.

  • use_recursive (bool, optional) – If True, the polynomials are computed with the recurrence relation (recommended for high orders). Default is False.

  • extrapolate (bool, optional) – If True, the model is extrapolated outside the current annulus. If False, the samples outside the current annulus are ignored (zero residuals and zero rows of the Jacobian). Default is True.

  • ellipse (None is accepted for all the parameters of the)

  • value. (and means the default)

Returns:

  • residual (Callable[[numpy.ndarray], numpy.ndarray]) – The function \(q \mapsto r(q)\), returning a new array of shape \((K,)\).

  • jacobian (Callable[[numpy.ndarray], numpy.ndarray]) – The function \(q \mapsto J(q)\), returning a new array of shape \((K, \dim q)\) with \(\dim q = Q\) (or \(P + Q\) if fit_coefficients is True).

Warns:

RuntimeWarning – If fit_coefficients is True, \(h = 0\) is fixed and a parameter among \(x_0, y_0, R_x, R_y, \alpha\) is free: the problem is not identifiable (singular Jacobian).

Raises:
  • TypeError – If x, y, values, weights or coefficients can not be converted to a floating point array, if order is not an integer, if parameters is not a string or a sequence of strings, if a parameter of the ellipse is not a real number, or if fit_coefficients, normalize, use_recursive or extrapolate is not a boolean.

  • ValueError – If the arrays do not have the same shape, if order is negative, if parameters contains an unknown name or a duplicate, if there is no unknown, if coefficients is given with fit_coefficients=True or missing with fit_coefficients=False, if its length is not \(P\), if a parameter of the ellipse is not valid, if a weight is negative, or if there is no valid sample. The returned functions raise a ValueError if \(q\) does not have the shape \((\dim q,)\), is not finite, or gives an invalid annulus.

Examples

Estimate the position, the size and the orientation of a pupil from a wavefront measured through a reference optics with known aberrations known_coefficients (OSA/ANSI, order 4), with scipy.optimize.least_squares:

import numpy
import scipy.optimize
from pyzernike import xy_zernike_least_squares

parameters = ("x0", "y0", "Rx", "Ry", "alpha")
residual, jacobian = xy_zernike_least_squares(X, Y, measured, order=4, parameters=parameters, coefficients=known_coefficients)

q0 = numpy.array([0.0, 0.0, 1.0, 1.0, 0.0])  # x0, y0, Rx, Ry, alpha
bounds = ([-numpy.inf, -numpy.inf, 1e-6, 1e-6, -numpy.inf], numpy.inf)
result = scipy.optimize.least_squares(residual, q0, jac=jacobian, bounds=bounds)
x0, y0, Rx, Ry, alpha = result.x

Estimate only the center of the pupil with a hand-written Gauss-Newton algorithm:

residual, jacobian = xy_zernike_least_squares(X, Y, measured, order=4, parameters=("x0", "y0"), coefficients=known_coefficients)
q = numpy.array([0.0, 0.0])
for _ in range(10):
    q -= numpy.linalg.lstsq(jacobian(q), residual(q), rcond=None)[0]