Source code for luv_finder.utils

"""Shared constants and the analytic ALMA primary beam.

The primary beam follows the ALMA Technical Handbook: the measured FWHM of the 12 m and 7 m antennas is
about 1.13 lambda / D, and CASA models the beam as an Airy pattern scaled so that its FWHM matches.
"""

from __future__ import annotations

from math import factorial

import astropy.constants as const
import jax
import numpy as np
from scipy.optimize import brentq
from scipy.special import j1, jn_zeros

C = const.c.value
ARCSEC = np.deg2rad(1 / 3600)
#: Primary-beam level down to which a pointing is searched, fitted and imaged.
PB_LIMIT = 0.2

#: Arrays processed in blocks stay near this size in memory.
BLOCK_BYTES = 2**31

#: Measured primary-beam FWHM in units of lambda / D (ALMA Technical Handbook).
FWHM_FACTOR = 1.13

#: First zero of J1, the edge of the Airy main lobe.
_X_NULL = jn_zeros(1, 1)[0]


#: Below this ``x`` the Airy pattern is its series ``2 J1(x) / x = sum_k (-x^2/4)^k / (k! (k+1)!)``, to
#: double precision: JAX's ``bessel_jn`` is NaN at ``x <= 1e-6`` and its derivative wrong up to ``x ~ 0.3``
#: (a few arcsec from a pointing centre), which a fit there needs.
_X_SERIES = 0.5
_SERIES = np.array([(-0.25) ** k / (factorial(k) * factorial(k + 1)) for k in range(8)])


def _airy(x, xp=np):
    """Airy power pattern ``(2 J1(x) / x)**2``, equal to 1 at ``x = 0``; ``xp`` is numpy or ``jax.numpy``."""
    bessel = j1 if xp is np else lambda z: jax.scipy.special.bessel_jn(z, v=1)[1]
    small = x < _X_SERIES
    safe, near = xp.where(small, 1.0, x), xp.where(small, x, 0.0)
    series = sum(c * near ** (2 * k) for k, c in enumerate(_SERIES))
    return xp.where(small, series**2, (2 * bessel(safe) / safe) ** 2)


#: Argument at which the Airy pattern drops to one half.
X_HALF = brentq(lambda x: _airy(x) - 0.5, 1.0, _X_NULL)


def primary_beam_fwhm(freq_hz, dish_diameter):
    return FWHM_FACTOR * C / (freq_hz * dish_diameter * ARCSEC)


[docs] def primary_beam(offset_arcsec, freq_hz, dish_diameter, xp=np): """Primary-beam attenuation in [0, 1] at an angular offset from the pointing centre.""" fwhm = primary_beam_fwhm(freq_hz, dish_diameter) return _airy(2 * X_HALF * xp.asarray(offset_arcsec, dtype=float) / fwhm, xp)
[docs] def primary_beam_at(dra, ddec, offset, freq_hz, dish_diameter, xp=np): """:func:`primary_beam` at (``dra``, ``ddec``) arcsec of the pointing centred on ``offset``.""" return primary_beam(xp.hypot(dra - offset[0], ddec - offset[1]), freq_hz, dish_diameter, xp=xp)
[docs] def primary_beam_radius(level, freq_hz, dish_diameter): """Offset in arcsec at which the main lobe falls to ``level`` (``0 < level <= 1``).""" if not 0 < level <= 1: raise ValueError(f"level must be in (0, 1], got {level}") x = 0.0 if level == 1 else brentq(lambda x: _airy(x) - level, 0.0, _X_NULL) return x / (2 * X_HALF) * primary_beam_fwhm(freq_hz, dish_diameter)