sht

hrtfpykit.hrtf.sht(hrtf, sh_order, ear='left', epsilon=1e-06)

Compute a spherical-harmonic decomposition of HRTF magnitudes.

The function projects linear HRTF magnitudes from the source grid into a real-valued spherical-harmonic basis. It accepts an HRTF object and uses the current HRTF source grid to evaluate the basis. The complex transfer functions stored in hrtf.TF.values are decomposed by magnitude.

The source coordinates are read as spherical positions in radians. The implementation maps SOFA-style azimuth/elevation to spherical-harmonic angles where phi is the azimuth and theta is pi / 2 minus elevation before evaluating scipy.special.sph_harm_y. Coefficients are solved with Tikhonov regularization.

Parameters:
  • hrtf (HRTF) – HRTF object used for the decomposition. hrtf.TF.values must have shape (positions, ears, frequency_bins) and contain at least two ear channels. hrtf.TF.frequency_bins must match the final TF axis.

  • sh_order (int) – Non-negative spherical-harmonic order. The coefficient count is (sh_order + 1) ** 2.

  • ear ({left, right, both}, default=``left``) – Ear channel used for the decomposition. left and right produce a two-dimensional coefficient matrix. both preserves a two-ear axis in the coefficient matrix.

  • epsilon (float, default=1e-6) – Positive Tikhonov regularization factor added to the normal matrix. Larger values stabilize ill-conditioned source grids more strongly but increase regularization bias.

Returns:

SH-domain container with C shaped (n_coefficients, n_frequencies) for one ear or (n_coefficients, 2, n_frequencies) for both ears, and Y shaped (N, n_coefficients).

Return type:

SH

Raises:

ValueError – If hrtf is not an HRTF object, TF values or frequency bins are missing, TF shape is incompatible, the source grid does not match the TF position axis, ear is invalid, sh_order is not a non-negative integer, or epsilon is not finite and positive.

Examples

Compute a low-order spherical-harmonic representation from a SOFA-backed HRTF and keep both ears in the coefficient tensor:

>>> from hrtfpykit.hrtf import load_hrtf, sht
>>> hrtf = load_hrtf("P0001_FreeFieldComp_44kHz.sofa")
>>> sh = sht(hrtf, sh_order=3, ear="both")
>>> sh.get_coefficients().shape
(16, 2, 129)