Source code for ktch.harmonic._canonical_form

"""Canonical-form check of registered harmonic coefficients."""

# Copyright 2026 Koji Noshita
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import annotations

import numpy as np
from sklearn.utils import Bunch

from ._disk_harmonic_analysis import DiskHarmonicAnalysis
from ._elliptic_fourier_analysis import EllipticFourierAnalysis
from ._registration import _DEGREE1_RATIO_TOL, infer_l_max
from ._spherical_harmonic_analysis import (
    SphericalHarmonicAnalysis,
    SphericalHarmonicRegistration,
)

_FORMS = ("auto", "first_order", "moment")
_J = np.diag([1.0, -1.0])
_EPS = np.finfo(float).eps


[docs] def canonical_form_report(estimator, coeffs, *, form="auto", tol=1e-10, atol=0.0): r"""Report whether registered coefficients are in a registration's canonical form. A per-specimen correction applied after registration can leave every rendering looking right while breaking the correspondence between specimens: a specimen turned on the codomain alone looks like one in a different pose. This check reads the coefficients and says, per specimen, whether they are in the canonical form of ``first_order`` registration, one coupled operation away from it, or no coupled operation away from it, and, for the sample, whether every specimen was turned by one rotation. It reports what it finds rather than raising on it; it raises only on input it cannot read (see Raises). Parameters ---------- estimator : object The :class:`~ktch.harmonic.EllipticFourierAnalysis`, :class:`~ktch.harmonic.DiskHarmonicAnalysis`, :class:`~ktch.harmonic.SphericalHarmonicAnalysis` or :class:`~ktch.harmonic.SphericalHarmonicRegistration` whose output ``coeffs`` is. Its parameters (``n_dim``, ``n_harmonics``, the registration method) give the layout of ``coeffs`` and, with ``form="auto"``, the canonical form to check against. It does not need to be fitted. coeffs : array-like of shape (n_samples, n_features) Coefficients in the layout ``estimator.transform`` returns. For :class:`EllipticFourierAnalysis` the columns appended by ``return_transform=True`` may be present; they are not read. form : {"auto", "first_order", "moment"}, default="auto" The canonical form to check against. ``"auto"`` follows the estimator's registration (``registration``, or ``method`` for :class:`SphericalHarmonicRegistration`, with ``"auto"`` resolved as the estimator resolves it); unregistered estimators are checked against ``"first_order"``. tol : float, default=1e-10 How far from the canonical form still counts as in it: the tolerance on each quantity below (relative, see Notes). Use it for a departure the coefficients carry, such as the precision of the software that aligned them. atol : float, default=0.0 Absolute uncertainty of each coefficient, such as the rounding of a file (``5e-7`` for six decimals). It decides when a first-order block is too thin to have a frame (``"degenerate"``) and how far rounding can move each quantity, which grows as the block thins (see Notes). ``0`` takes the rounding of the arithmetic only. Returns ------- report : :class:`~sklearn.utils.Bunch` With ``form="first_order"`` (or ``"auto"`` resolving to it): - ``label`` : ndarray of str, shape (n_samples,). ``"canonical"``, ``"coupled"``, ``"uncoupled"`` or ``"degenerate"`` (see Notes). - ``direction`` : ndarray of int, shape (n_samples,). The sign of the determinant of the degree-1 block: in 2D ``1`` for a counter-clockwise and ``-1`` for a clockwise output; for SPHARM ``1`` for a right-handed and ``-1`` for a left-handed block; ``0`` for EFA-3D and DHA-3D, whose block is 3 x 2, and for a block of zero determinant. - ``d_q``, ``d_s``, ``delta_order``, ``sigma_ratio`` : ndarray of float, shape (n_samples,). The quantities the label is read from (see Notes); ``nan`` for degenerate specimens except ``sigma_ratio``. - ``population`` : :class:`~sklearn.utils.Bunch` with ``status`` (``"aligned"``, ``"uniform"``, ``"not_uniform"`` or ``"empty"``), ``side`` (``"codomain"``, ``"parameter"``, ``"either"`` or ``"neither"`` when ``status`` is ``"uniform"``, ``None`` otherwise), ``d_u`` and ``rotation`` (see Notes). - ``form`` : ``"first_order"``; ``tol``, ``atol`` : the tolerances used. With ``form="moment"`` (or ``"auto"`` resolving to it): - ``label`` : ndarray of str, ``"canonical"`` or ``"not_canonical"``. - ``d_offdiag``, ``delta_order`` : ndarray of float (see Notes). - ``population`` : ``None``; ``form`` : ``"moment"``; ``tol``, ``atol``. Raises ------ TypeError If ``estimator`` is not one of the four harmonic estimators. ValueError For an unknown ``form``, a negative ``tol`` or ``atol``, ``coeffs`` that is not 2-D, whose width does not match the estimator or whose coefficients are not finite, an estimator with ``n_dim`` not in ``(2, 3)`` or without degree-1 modes, or ``form="first_order"`` for SPHARM with ``n_dim != 3``. See Also -------- rotate_spharm_coeffs : Rotate SPHARM coefficients on the codomain, the parameter sphere, or both (``domain="coupled"``). Notes ----- **first_order.** Let :math:`M` (:math:`D \times c`) be the degree-1 block of a specimen: the images of the parameter axes, one per column (EFA and DHA: the cosine and the sine vectors of the first harmonic, :math:`c = 2`; SPHARM: the parameter axes :math:`x, y, z`, :math:`c = 3`). Its polar decomposition is :math:`M = Q S`, with :math:`Q` having orthonormal columns and :math:`S = (M^\top M)^{1/2}` symmetric positive definite. A codomain rotation :math:`O` acts as :math:`Q \to O Q` and leaves :math:`S`; a parameter operation acts on degree 1 as :math:`M \to M A` with :math:`A` orthogonal, which gives :math:`Q \to Q A` and :math:`S \to A^\top S A`. Let :math:`E` be the first :math:`c` columns of the identity. A coupled operation applies one rotation to both domains so that :math:`Q = E` is kept (for SPHARM, ``domain="coupled"`` of :func:`rotate_spharm_coeffs`; for EFA, a start-point shift with the codomain turned by the same angle); it keeps the correspondence between specimens. In 2D a clockwise output, one that keeps a clockwise input's running direction, has :math:`\det M < 0`. It is classified from :math:`M \operatorname{diag}(1, -1)`, and its direction is reported in ``direction`` rather than in the label. - ``degenerate``: :math:`\sigma_{\min}` is within the uncertainty of the block (below), or ``sigma_ratio`` :math:`= \sigma_{\min} / \sigma_{\max} \le 10^{-12}`, the cut registration itself uses. The first-order ellipse is a segment (the ellipsoid is flat), and :math:`Q` is not determined. - ``canonical``: :math:`Q = E` and :math:`S` diagonal with descending entries, the form ``first_order`` returns. - ``coupled``: :math:`Q = E` and :math:`S` not diagonal and descending. One coupled operation takes the specimen to the canonical form. The output of ``align_parameter=False`` is of this kind (canonical when the input's parameterization is already aligned to its ellipse). - ``uncoupled``: :math:`Q \ne E`. No coupled operation takes the specimen to the canonical form. This is what a per-specimen codomain-only or parameter-only operation applied after registration gives, and also what every specimen of a sample turned by one common rotation gives; ``population`` tells these apart. A left-handed SPHARM block is always of this kind. The quantities are :math:`d_Q = \|Q - E\|_F`; ``d_s``, the Frobenius norm of the off-diagonal part of :math:`S` over that of :math:`S`; and ``delta_order``, the largest increase between consecutive diagonal entries of :math:`S` over the first one (0 when they descend). :math:`Q = E` means :math:`d_Q \le` ``tol`` plus a floor, and :math:`S` diagonal and descending means ``d_s`` and ``delta_order`` both :math:`\le` ``tol`` plus a floor. The block is known to :math:`\epsilon = \mathrm{atol} \sqrt{D c} + \max(D, c)\, u\, \sigma_{\max}` (:math:`u` the unit roundoff), as the cutoff ``atol + rtol * sigma_max`` of :func:`scipy.linalg.pinv` reads singular values; the floor of :math:`d_Q` is :math:`\epsilon` times the condition number of the polar factor, :math:`1/\sigma_{\min}` for a :math:`3 \times 2` block and :math:`2 / (\sigma_{c-1} + \sigma_c)` for a square one (Higham, *Functions of Matrices*, 2008, Thm. 8.9), and that of ``d_s`` and ``delta_order`` is :math:`2 \epsilon / \sigma_{\max}`. A thin :math:`3 \times 2` block therefore reads :math:`Q` only to :math:`\epsilon / \sigma_{\min}`. ``population`` judges the non-degenerate specimens together. With :math:`\bar Q` the polar factor of the mean of their :math:`Q`, each weighted by the inverse square of its tolerance (``tol`` plus its floor), and ``d_u`` :math:`= \max_i \|Q_i - \bar Q\|_F`, the status is ``"not_uniform"`` when some :math:`\|Q_i - \bar Q\|_F` exceeds its tolerance, ``"aligned"`` when :math:`\bar Q = E`, and ``"uniform"`` otherwise: every specimen carries the same orthogonal transformation, as from a convention change applied to the whole sample. With one usable specimen the status is ``"aligned"`` or ``"uniform"``; with none it is ``"empty"``. For ``"uniform"``, ``side`` says where that transformation acts: ``"codomain"`` when every :math:`S_i` is diagonal and descending, ``"parameter"`` when every :math:`A_0 S_i A_0^\top` is (:math:`A_0 = E^\top \bar Q`), ``"either"`` when both hold (a half turn, a reflection of one axis, or coinciding singular values) and ``"neither"`` otherwise; the parameter side requires :math:`A_0` to be orthogonal, since a parameter operation gives :math:`\bar Q = E A`. ``rotation`` (:math:`D \times D`, orthogonal) is then the matrix :math:`R` with :math:`R \bar Q = E` (in 3D completed by the cross product): left-applied to the coefficient vectors of every specimen, it undoes a common codomain rotation. It is proper except for a SPHARM sample whose specimens are all left-handed (``direction`` -1), which it mirrors back. For a common parameter operation it only expresses that operation on the codomain. In a 2D sample with both directions, a common parameter operation reads as ``"not_uniform"``: folding a clockwise specimen by :math:`\operatorname{diag}(1, -1)` inverts it (a shift :math:`A` becomes :math:`A^{-1}`), while a common codomain rotation still reads as uniform. **moment.** ``moment`` aligns the codomain to the principal axes of the second moment :math:`\sum_k a_k a_k^\top` of the non-constant coefficient vectors, and leaves the parameter domain as it is; its outputs are generally ``uncoupled`` in the sense above. Its canonical form is that second moment diagonal with descending entries, read with ``d_offdiag`` and ``delta_order`` as ``d_s`` and ``delta_order`` are read from :math:`S`, with the floor :math:`2 \epsilon \|A\|_2 / \|M\|_F` (:math:`A` the non-constant coefficient vectors, :math:`M` their second moment, :math:`\epsilon = \mathrm{atol} \sqrt{D m}` for :math:`m` modes, plus the rounding of the arithmetic). The check sees codomain rotations other than sign changes, and not parameter operations, which leave the second moment unchanged. Examples -------- >>> from ktch.datasets import load_outline_mosquito_wings >>> from ktch.harmonic import EllipticFourierAnalysis, canonical_form_report >>> outlines = list(load_outline_mosquito_wings().coords[:5]) >>> efa = EllipticFourierAnalysis(n_harmonics=10) >>> coeffs = efa.fit_transform(outlines) >>> report = canonical_form_report(efa, coeffs) >>> report.label.tolist() ['canonical', 'canonical', 'canonical', 'canonical', 'canonical'] >>> report.population.status 'aligned' """ if form not in _FORMS: raise ValueError(f"form must be one of {_FORMS}, got {form!r}") if not tol >= 0: raise ValueError(f"tol must be non-negative, got {tol!r}") if not atol >= 0: raise ValueError(f"atol must be non-negative, got {atol!r}") coeffs = np.asarray(coeffs, dtype=float) if coeffs.ndim != 2: raise ValueError( f"coeffs must be 2-D (n_samples, n_features); got shape {coeffs.shape}" ) layout = _Layout.of(estimator, coeffs.shape[1]) # The coefficients the report reads must be finite. bad = ~np.isfinite(coeffs[:, : layout.n_dim * layout.n_coeffs]).all(axis=1) if bad.any(): raise ValueError( "coeffs has non-finite coefficients in rows " f"{np.flatnonzero(bad).tolist()}." ) if form == "auto": form = "moment" if layout.registration == "moment" else "first_order" if form == "moment": return _moment_report(layout.modes(coeffs), tol, atol) if layout.sphere and layout.n_dim != 3: raise ValueError( "form='first_order' for SPHARM requires n_dim=3 (the degree-1 " f"block spans a 3D frame); got n_dim={layout.n_dim}." ) return _first_order_report(layout.degree1(coeffs), tol, atol)
class _Layout: """Where the degree-1 block and the non-constant modes sit in ``coeffs``.""" def __init__(self, n_dim, n_coeffs, registration, sphere, kind): self.n_dim = n_dim self.n_coeffs = n_coeffs # per axis self.registration = registration self.sphere = sphere self.kind = kind # "efa", "dha" or "spharm" @classmethod def of(cls, estimator, width, user="canonical_form_report"): supported = ( EllipticFourierAnalysis, DiskHarmonicAnalysis, SphericalHarmonicAnalysis, SphericalHarmonicRegistration, ) if not isinstance(estimator, supported): raise TypeError( "estimator must be an EllipticFourierAnalysis, " "DiskHarmonicAnalysis, SphericalHarmonicAnalysis or " f"SphericalHarmonicRegistration; got {type(estimator).__name__}." ) n_dim = estimator.n_dim if n_dim not in (2, 3): raise ValueError(f"{user} applies to 2D/3D shape data; got n_dim={n_dim}.") if isinstance(estimator, EllipticFourierAnalysis): n_coeffs = 2 * (estimator.n_harmonics + 1) base = n_dim * n_coeffs extras = {2: 2, 3: 5}[n_dim] if width not in (base, base + extras): raise ValueError( f"coeffs has {width} columns; this estimator returns " f"{base} (or {base + extras} with return_transform)." ) registration = estimator._resolve_registration()[0] layout = cls(n_dim, n_coeffs, registration, False, "efa") harmonics = estimator.n_harmonics elif isinstance(estimator, DiskHarmonicAnalysis): n_coeffs = (estimator.n_harmonics + 1) ** 2 _check_width(width, n_dim * n_coeffs) layout = cls(n_dim, n_coeffs, estimator._resolve_method(), False, "dha") harmonics = estimator.n_harmonics elif isinstance(estimator, SphericalHarmonicAnalysis): n_coeffs = (estimator.n_harmonics + 1) ** 2 _check_width(width, n_dim * n_coeffs) registration = estimator._resolve_method() layout = cls(n_dim, n_coeffs, registration, True, "spharm") harmonics = estimator.n_harmonics else: # SphericalHarmonicRegistration harmonics = infer_l_max(width, n_dim) registration = estimator._resolve_method(l_max=harmonics) layout = cls(n_dim, (harmonics + 1) ** 2, registration, True, "spharm") if harmonics < 1: raise ValueError(f"{user} needs the degree-1 modes (n_harmonics >= 1).") return layout def _matrices(self, coeffs): n = coeffs.shape[0] return coeffs[:, : self.n_dim * self.n_coeffs].reshape( n, self.n_dim, self.n_coeffs ) def degree1(self, coeffs): """``(n_samples, n_dim, c)``: the images of the parameter axes.""" mats = self._matrices(coeffs) if self.kind == "efa": # Per axis [cos_0..cos_n, sin_0..sin_n]: harmonic 1 at 1 and n + 2. return mats[:, :, [1, self.n_coeffs // 2 + 1]] if self.kind == "dha": # Modes (n, m) at n^2 + n + m: (1, 1) cosine at 3, (1, -1) sine at 1. return mats[:, :, [3, 1]] # SPHARM (l, m) at l^2 + l + m: x ~ (1, 1), y ~ (1, -1), z ~ (1, 0). return mats[:, :, [3, 1, 2]] def modes(self, coeffs): """``(n_samples, n_dim, n_coeffs - 1)``: the non-constant mode vectors.""" return self._matrices(coeffs)[:, :, 1:] def _check_width(width, expected): if width != expected: raise ValueError( f"coeffs has {width} columns; this estimator returns {expected}." ) def _off_diagonal(mats): """``||A - diag A||_F / ||A||_F`` for each matrix of a stack.""" off = np.array(mats) idx = np.arange(mats.shape[1]) off[:, idx, idx] = 0.0 with np.errstate(divide="ignore", invalid="ignore"): return np.linalg.norm(off, axis=(1, 2)) / np.linalg.norm(mats, axis=(1, 2)) def _order_violation(mats): """The largest increase between consecutive diagonal entries over the first.""" diag = np.einsum("nii->ni", mats) rise = np.max(np.maximum(diag[:, 1:] - diag[:, :-1], 0.0), axis=1) with np.errstate(divide="ignore", invalid="ignore"): return np.where(diag[:, 0] > 0, rise / diag[:, 0], np.inf) def _polar(mats): """``M = Q S`` for each matrix of a stack, with the singular values.""" u, sv, vt = np.linalg.svd(mats, full_matrices=False) q = u @ vt s = np.einsum("nji,nj,njk->nik", vt, sv, vt) return q, s, sv def _first_order_report(m1, tol, atol): n, n_dim, c = m1.shape e = np.eye(n_dim)[:, :c] direction = np.zeros(n, dtype=int) if n_dim == c: direction = np.sign(np.linalg.det(m1)).astype(int) folded = np.array(m1) if n_dim == 2: folded[direction < 0] = folded[direction < 0] @ _J q, s, sv = _polar(folded) # How well the block is known: atol per coefficient, and the rounding of # the arithmetic (as scipy.linalg.pinv's cutoff atol + rtol * sigma_max). noise = atol * np.sqrt(n_dim * c) + max(n_dim, c) * _EPS * sv[:, 0] with np.errstate(divide="ignore", invalid="ignore"): sigma_ratio = np.where(sv[:, 0] > 0, sv[:, -1] / sv[:, 0], 0.0) degenerate = sv[:, -1] <= np.maximum(noise, _DEGREE1_RATIO_TOL * sv[:, 0]) # The floors: the uncertainty times the condition number of the polar # factor (Higham 2008, Thm. 8.9) for d_q, and relative to the block # for d_s and delta_order. if c < n_dim: q_floor = noise / sv[:, -1] else: q_floor = 2 * noise / (sv[:, -2] + sv[:, -1]) s_floor = np.where(sv[:, 0] > 0, 2 * noise / sv[:, 0], np.inf) d_q = np.linalg.norm(q - e, axis=(1, 2)) d_s = _off_diagonal(s) delta_order = _order_violation(s) at_e = d_q <= tol + q_floor diagonal = (d_s <= tol + s_floor) & (delta_order <= tol + s_floor) label = np.where( degenerate, "degenerate", np.where(at_e & diagonal, "canonical", np.where(at_e, "coupled", "uncoupled")), ) for values in (d_q, d_s, delta_order): values[degenerate] = np.nan used = ~degenerate return Bunch( label=label, direction=direction, d_q=d_q, d_s=d_s, delta_order=delta_order, sigma_ratio=sigma_ratio, population=_population( q[used], s[used], e, tol, q_floor[used], np.max(s_floor[used], initial=0.0) ), form="first_order", tol=tol, atol=atol, ) def _population(q, s, e, tol, q_floor, s_floor): """The uniform-rotation judgment of the usable specimens (``first_order`` Notes).""" if len(q) == 0: return Bunch(status="empty", side=None, d_u=np.nan, rotation=None) # The mean frame weights each specimen by the inverse square of its # tolerance: one thin specimen then does not move it. allowed = tol + q_floor w = 1.0 / allowed**2 if allowed.min() > 0 else np.ones(len(q)) w = w / w.sum() q_bar = _polar(np.einsum("n,nij->ij", w, q)[None])[0][0] bar_floor = float(np.sqrt(np.sum((w * q_floor) ** 2))) dist = np.linalg.norm(q - q_bar, axis=(1, 2)) d_u = float(np.max(dist)) if np.any(dist > allowed + bar_floor): return Bunch(status="not_uniform", side=None, d_u=d_u, rotation=None) if np.linalg.norm(q_bar - e) <= tol + bar_floor: return Bunch(status="aligned", side=None, d_u=d_u, rotation=None) a0 = e.T @ q_bar s_tol = tol + float(s_floor) codomain = _all_diagonal(s, s_tol) # A parameter operation gives Q_bar = E A with A orthogonal. parameter = bool( np.linalg.norm(a0 @ a0.T - np.eye(a0.shape[0])) <= tol + bar_floor ) and _all_diagonal(a0 @ s @ a0.T, s_tol) side = { (True, True): "either", (True, False): "codomain", (False, True): "parameter", (False, False): "neither", }[(codomain, parameter)] frame = q_bar if q_bar.shape[1] == 2 and q_bar.shape[0] == 3: frame = np.column_stack([q_bar, np.cross(q_bar[:, 0], q_bar[:, 1])]) return Bunch(status="uniform", side=side, d_u=d_u, rotation=frame.T) def _all_diagonal(s, tol): return bool(np.all((_off_diagonal(s) <= tol) & (_order_violation(s) <= tol))) def _moment_report(modes, tol, atol): m2 = modes @ np.transpose(modes, (0, 2, 1)) d_offdiag = _off_diagonal(m2) delta_order = _order_violation(m2) n_dim, n_modes = modes.shape[1], modes.shape[2] spectral = np.linalg.norm(modes, ord=2, axis=(1, 2)) noise = atol * np.sqrt(n_dim * n_modes) + max(n_dim, n_modes) * _EPS * spectral with np.errstate(divide="ignore", invalid="ignore"): floor = np.where( spectral > 0, 2 * noise * spectral / np.linalg.norm(m2, axis=(1, 2)), np.inf ) canonical = (d_offdiag <= tol + floor) & (delta_order <= tol + floor) return Bunch( label=np.where(canonical, "canonical", "not_canonical"), d_offdiag=d_offdiag, delta_order=delta_order, population=None, form="moment", tol=tol, atol=atol, )