Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 66 additions & 0 deletions rework_summaries/tb-07-moffat-kernel-tests_changes.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
# tb-07-moffat-kernel-tests

Tests only. No production code changes.

## Why the scope is narrower than expected

The Tier B entry asked to "detach the kernel maths from `_apply_convolution`'s
FOV-header rewriting". Checking against the upstream baseline changed the
picture: `MoffatPSF`, `AOEnhanceablePSF`, `moffat_cell_integrals`,
`fwhm2gamma` and `_legendre_rule` **do not exist upstream at all** —
`scopesim/effects/psfs/analytical.py` ends at `_sigma2gauss` there — and
`psfs/psf_base.py` is byte-identical to upstream.

So there is nothing to detach for upstreaming purposes and no flag to add. The
class is already opt-in by virtue of being named in a YAML. What was actually
missing is that the kernel mathematics had **no direct test anywhere**. It was
exercised only through `MoffatPSF.get_kernel`, so an error in the closed-form
integral could surface only as a slightly wrong PSF — the hardest kind of
error to notice in this codebase.

`_apply_convolution`'s in-place rewriting of the FOV's `NAXIS`/`CDELT`/`CRPIX`/
`CRVAL` and its nulling of `_volume` and `pixel_area` is left untouched. That
is a layering problem, not a maths problem, and belongs with the `observe()`
dispatch rework.

## What is now tested

`moffat_cell_integrals` evaluates the x-marginal of the 2D Moffat in closed
form, integrates the conditional y-distribution exactly as a Student-t with
`2*alpha - 1` degrees of freedom via `scipy.special.stdtr`, and finishes the
remaining x-integral with Gauss-Legendre quadrature. The wavelength averaging
happens *inside* this function (`integral/len(gammas)`), not in `get_kernel`.

- **Against numerical quadrature.** Single cells at three positions compared
with `scipy.integrate.dblquad` on the analytic profile. They agree to
machine precision (relative error 0 and 3.3e-16).
- **Normalisation.** Summing the cell integrals over a wide grid gives 1 to
1e-5.
- **A profile far narrower than the cell** still integrates to unity. This is
the case the analytic integral exists to handle and the one that point
sampling of the kernel gets wrong.
- **Wavelength averaging** equals the mean of the single-width results exactly.
- **Symmetry** about both axes.

`fwhm2gamma` implements FWHM = 2*gamma*sqrt(2^(1/alpha) - 1):

- the profile is half its peak at half the FWHM, across four alphas and three
FWHMs
- gamma scales linearly with FWHM
- the returned quantity keeps the input angular unit (checked with marcsec,
since the callers mix arcsec and other units)

## Recorded, not fixed

`MoffatPSF._apply_convolution` widens the base signature —
`PSF._apply_convolution(self, obj)` versus
`(self, obj, spatial_shifts=())` — and the `super()` fallback drops
`spatial_shifts` silently. It is currently unreachable with non-empty shifts,
because `defer_render` in `observe()` requires a `FieldOfView3D` and the
fallback only runs when the object is not one. Worth an assertion rather than a
fix, and worth remembering if that dispatch is ever relaxed.

## Verification

`scopesim/tests`: 4 failed, 1397 passed. Same four pre-existing failures as on
`main`; 21 new tests pass.
82 changes: 82 additions & 0 deletions scopesim/tests/tests_effects/test_moffat_cell_integrals.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
"""Direct tests for the Moffat kernel mathematics.

These were previously exercised only through MoffatPSF.get_kernel, so an error
in the closed-form integral could only show up as a slightly wrong PSF.
"""

import numpy as np
import pytest
from astropy import units as u
from scipy.integrate import dblquad

from scopesim.effects.psfs.analytical import moffat_cell_integrals, MoffatPSF

ALPHA = 4.765
FWHM = .7


def _gamma(fwhm=FWHM, alpha=ALPHA):
return MoffatPSF.fwhm2gamma(fwhm*u.arcsec, alpha).to_value(u.arcsec)


def _moffat(x, y, gamma, alpha):
"""Normalised 2D Moffat surface brightness."""
return (alpha - 1)/(np.pi*gamma**2) * (1 + (x**2 + y**2)/gamma**2)**(-alpha)


class TestFwhm2Gamma:
@pytest.mark.parametrize("alpha", [1.5, 2.5, 4.765, 10.])
@pytest.mark.parametrize("fwhm", [.2, .7, 1.3])
def test_profile_is_half_its_peak_at_half_the_fwhm(self, fwhm, alpha):
gamma = _gamma(fwhm, alpha)
assert (1 + ((fwhm/2)/gamma)**2)**(-alpha) == pytest.approx(.5)

def test_gamma_scales_linearly_with_fwhm(self):
assert _gamma(1.4)/_gamma(.7) == pytest.approx(2.)

def test_returns_the_input_angular_unit(self):
assert MoffatPSF.fwhm2gamma(700*u.marcsec, ALPHA).unit == u.marcsec


class TestMoffatCellIntegrals:
@pytest.mark.parametrize("centre", [(0., 0.), (.35, -.2), (1.1, .9)])
def test_matches_numerical_quadrature_over_one_cell(self, centre):
gamma, (cx, cy), step = _gamma(), centre, .1
analytic = moffat_cell_integrals(np.array([cx]), np.array([cy]), step, step,
np.array([gamma]), ALPHA)[0]
numeric, _ = dblquad(lambda y, x: _moffat(x, y, gamma, ALPHA),
cx - step/2, cx + step/2, cy - step/2, cy + step/2,
epsabs=1e-13)
assert analytic == pytest.approx(numeric, rel=1e-9)

def test_integrates_to_unity_over_a_wide_grid(self):
step, half = .1, 100
centres = (np.arange(2*half + 1) - half)*step
xx, yy = np.meshgrid(centres, centres, indexing="ij")
total = moffat_cell_integrals(xx, yy, step, step, np.array([_gamma()]), ALPHA).sum()
assert total == pytest.approx(1., rel=1e-5)

def test_wavelength_averaging_is_the_mean_of_the_single_widths(self):
# The kernel averages over sampled wavelengths inside this function.
gammas = np.array([.3, .5])
centres = (np.arange(81) - 40)*.1
xx, yy = np.meshgrid(centres, centres, indexing="ij")
averaged = moffat_cell_integrals(xx, yy, .1, .1, gammas, ALPHA)
singles = [moffat_cell_integrals(xx, yy, .1, .1, gammas[[i]], ALPHA) for i in (0, 1)]
np.testing.assert_allclose(averaged, sum(singles)/2, rtol=1e-12)

def test_narrow_profile_is_resolved_without_oversampling(self):
# A profile far narrower than the cell must still integrate to unity;
# this is the case point sampling of the kernel would get wrong.
step, half = 1., 60
centres = (np.arange(2*half + 1) - half)*step
xx, yy = np.meshgrid(centres, centres, indexing="ij")
total = moffat_cell_integrals(xx, yy, step, step, np.array([.05]), ALPHA).sum()
assert total == pytest.approx(1., rel=1e-4)

def test_is_symmetric_about_the_origin(self):
centres = (np.arange(21) - 10)*.1
xx, yy = np.meshgrid(centres, centres, indexing="ij")
cells = moffat_cell_integrals(xx, yy, .1, .1, np.array([_gamma()]), ALPHA)
np.testing.assert_allclose(cells, cells[::-1, :], rtol=1e-12)
np.testing.assert_allclose(cells, cells[:, ::-1], rtol=1e-12)
Loading