Source code for ktch.harmonic._flip_distances

"""Distances of each specimen's flip candidates to a template."""

# 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 ._canonical_form import _Layout
from ._registration import (
    _TIE_TOL,
    flip_parts,
    proper_sign_patterns,
    residual_patterns,
)
from ._spherical_harmonic_analysis import _sphere_sign_flip_signs


[docs] def flip_distances(estimator, coeffs, template): """Distances from each specimen's flip candidates to a template. Registration leaves each specimen on one of a few equally valid representatives: the elements of the residual group, which ``flip`` names by the signs they put on the codomain axes. For each specimen, this applies every candidate to its registered coefficients, as ``flip`` does, and measures the distance to ``template``. A specimen whose nearest candidate is not the identity is registered in a different orientation from the template. Nothing is decided here: no threshold, no warning, and the coefficients are not changed. 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 the candidates. It does not need to be fitted. coeffs : array-like of shape (n_samples, n_features) Registered coefficients in the layout ``estimator.transform`` returns. The columns appended by ``return_transform=True`` may be present; they are not read. template : array-like of shape (n_features,) The coefficients of the shape the specimens are compared with, in the same layout. SPHARM-PDM calls such a shape a flip template. The constant mode is not read. Returns ------- result : :class:`~sklearn.utils.Bunch` - ``candidates`` : ndarray of shape (n_candidates, n_dim). The codomain signs of each candidate, as ``flip`` takes them; the identity first. ``first_order`` of EFA and DHA in 2D has the identity and the half turn; in 3D also the two that turn the shape over (they reverse the parameterization), whatever ``reversal`` is. SPHARM ``first_order`` and ``moment`` in 3D have the four proper sign patterns, ``moment`` in 2D the identity and ``-I``. - ``distances`` : ndarray of shape (n_samples, n_candidates). ``||h . y - t|| / ||t||`` for each candidate ``h``, specimen ``y`` and template ``t``, over every mode but the constant. - ``nearest`` : ndarray of int, shape (n_samples,). The position in ``candidates`` of the candidate nearest the template; candidates within 1e-10 of the nearest count as tied, and the first of them (the identity, if it is among them) is taken. Raises ------ ValueError If the estimator does not register (``registration=None``), or registers with ``align_parameter=False``. That setting keeps the input's parameterization and leaves no candidates (see :func:`canonical_form_report` for its orientation). Also if ``coeffs`` is not 2-D, if ``template`` does not have the layout of ``coeffs`` or its non-constant modes are zero, or if the coefficients of ``coeffs`` or ``template`` are not all finite (the columns of ``return_transform`` are not read). See Also -------- canonical_form_report : Whether registered coefficients are in canonical form. Notes ----- To move a specimen onto its nearest candidate, register it again with ``flip=candidates[nearest]``. For SPHARM, ``rotate_spharm_coeffs(row, np.diag(candidates[nearest]), domain="coupled")`` does the same to ``first_order`` coefficients. Examples -------- >>> import numpy as np >>> from ktch.harmonic import SphericalHarmonicRegistration, flip_distances >>> rng = np.random.default_rng(0) >>> width = 3 * (3 + 1) ** 2 >>> reg = SphericalHarmonicRegistration(scale=False) >>> template = reg.fit_transform(rng.standard_normal((1, width)))[0] >>> coeffs = reg.fit_transform(rng.standard_normal((5, width))) >>> result = flip_distances(reg, coeffs, template) >>> result.candidates.shape (4, 3) >>> result.distances.shape (5, 4) """ 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], user="flip_distances") if layout.registration is None: raise ValueError( "flip_distances compares registered coefficients; the estimator's " "registration is None." ) if layout.registration == "first_order" and not estimator.align_parameter: raise ValueError( "align_parameter=False keeps the input's parameterization. Its " "output has no flip candidates; canonical_form_report reads its " "orientation." ) template = np.asarray(template, dtype=float) if template.ndim == 2 and template.shape[0] == 1: template = template[0] width = layout.n_dim * layout.n_coeffs if template.ndim != 1 or template.shape[0] not in (width, coeffs.shape[1]): raise ValueError( f"template must be one row of {width} coefficients (or " f"{coeffs.shape[1]} columns, as coeffs); got shape {template.shape}." ) # A NaN would make every distance NaN, and the nearest the first. bad = ~np.isfinite(coeffs[:, :width]).all(axis=1) if bad.any(): raise ValueError( "coeffs has non-finite coefficients in rows " f"{np.flatnonzero(bad).tolist()}." ) if not np.isfinite(template[:width]).all(): raise ValueError("template has non-finite coefficients.") target = layout.modes(template[None])[0] size = np.linalg.norm(target) if size == 0.0: raise ValueError("template has no non-constant modes.") candidates = _candidates(layout) mats = layout._matrices(coeffs) distances = np.stack( [ np.linalg.norm(_act(layout, g, mats)[:, :, 1:] - target, axis=(1, 2)) / size for g in candidates ], axis=1, ) nearest = np.argmax( distances <= distances.min(axis=1, keepdims=True) + _TIE_TOL, axis=1 ) return Bunch(candidates=np.array(candidates), distances=distances, nearest=nearest)
def _candidates(layout): """The proper elements of the residual group, as codomain signs.""" if layout.registration == "moment" or layout.kind == "spharm": return proper_sign_patterns(layout.n_dim) return residual_patterns(layout.n_dim, reversal=True) def _act(layout, signs, mats): """Registered coefficients with the element of ``signs`` applied. The same element as ``flip=signs`` applies after the rule. """ signs = np.asarray(signs, dtype=float) out = signs[None, :, None] * mats if layout.registration == "moment": return out # the codomain only if layout.kind == "spharm": l_max = int(round(layout.n_coeffs**0.5)) - 1 return out * _sphere_sign_flip_signs(l_max, signs)[None, None, :] shift, reverse = flip_parts(signs) if layout.kind == "efa": # Per axis [cos_0..cos_n, sin_0..sin_n]. The start point moved by pi # multiplies harmonic k by (-1)^k; reversal negates the sines. n = layout.n_coeffs // 2 - 1 k = np.concatenate([np.arange(n + 1), np.arange(n + 1)]) factor = np.ones(layout.n_coeffs) if shift: factor *= (-1.0) ** k if reverse: factor[n + 1 :] *= -1.0 return out * factor # DHA: mode (n, m) at n^2 + n + m. The disk turned by pi multiplies the # modes of order m by (-1)^m; reversal negates the m < 0 (sine) modes. n_max = int(round(layout.n_coeffs**0.5)) - 1 m = np.concatenate([np.arange(-d, d + 1) for d in range(n_max + 1)]) factor = np.ones(layout.n_coeffs) if shift: factor *= (-1.0) ** np.abs(m) if reverse: factor[m < 0] *= -1.0 return out * factor