Skip to content
Merged
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
37 changes: 37 additions & 0 deletions autogalaxy/profiles/mass/abstract/abstract.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,14 +49,51 @@ def radial_deflection_from(r, params, xp):
"(jnightingale2211@gmail.com) or open a GitHub issue."
)

# The radial parameters (everything after the centre) put into a masked-out slot of
# `vmapped_deflections_from` before it is evaluated. They must lie inside the domain of
# `radial_deflection_from`, so that a masked slot's deflection and its gradient are both
# finite (and then exactly zero). `None` uses ones; a profile for which ones are not a
# valid parameter set overrides this.
vmapped_padding_params = None

@classmethod
def vmapped_deflections_from(cls, grid, params_batch, mask, xp=None):
"""
Returns the summed deflections of a batch of spherical profiles of this class, for the
JAX ray-tracing scan of the line-of-sight and subhalo substructure code.

Parameters
----------
grid
The (y,x) coordinates, shape ``(n_grid, 2)``.
params_batch
The parameters of each slot, shape ``(n_slots, 2 + n_radial)``: the centre followed
by the parameters ``radial_deflection_from`` takes.
mask
Which slots hold a real profile, shape ``(n_slots,)``. A masked-out slot contributes
exactly zero to the deflections and to their gradients, whatever its parameters
(callers pad such slots with zeros). Its parameters are swapped for
``vmapped_padding_params`` before evaluation, because a zero scale radius would give a
NaN gradient that ``where`` alone does not stop: the masked branch's cotangent is zero,
but zero times an infinite partial derivative is NaN.
"""
import jax
import jax.numpy as jnp

if xp is None:
xp = jnp

n_radial = params_batch.shape[-1] - 2
padding_radial = (
xp.ones(n_radial)
if cls.vmapped_padding_params is None
else xp.asarray(cls.vmapped_padding_params, dtype=params_batch.dtype)
)
padding = xp.concatenate(
[xp.zeros(2, dtype=params_batch.dtype), padding_radial.astype(params_batch.dtype)]
)
params_batch = xp.where(mask[:, None], params_batch, padding[None, :])

def single(params):
centred = grid - params[:2]
r_squared = centred[:, 0] ** 2 + centred[:, 1] ** 2
Expand Down
114 changes: 64 additions & 50 deletions autogalaxy/profiles/mass/dark/cnfw.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,69 +10,79 @@


def F_func_from(theta, radius, xp=np):
F = theta * 0.0
"""
The cNFW projected-mass function ``F(theta; radius)`` of Shajib (2019) used by the cNFW
deflections, for ``theta > 0``.

The inner (``theta < radius``) and outer (``theta > radius``) closed forms are each
evaluated on a ``theta`` inside their own domain (the other branch's points are swapped for
a safe value first), and ``theta == radius`` uses their common limit. Evaluating a branch
outside its domain gives NaN there, and although ``where`` discards that value, its NaN
gradient still reaches JAX's ``grad``.
"""
is_inner = (theta > 0) & (theta < radius)
is_edge = theta == radius
is_outer = theta > radius

mask1 = (theta > 0) & (theta <= radius)
mask2 = theta > radius

F = xp.where(
mask1,
(
radius / 2 * xp.log(2 * radius / theta)
- xp.sqrt(radius**2 - theta**2)
* xp.arctanh(xp.sqrt((radius - theta) / (radius + theta)))
),
F,
)
theta_inner = xp.where(is_inner, theta, 0.5 * radius)
theta_outer = xp.where(is_outer, theta, 2.0 * radius)
theta_edge = xp.where(is_edge, theta, radius)

F = xp.where(
mask2,
(
radius / 2 * xp.log(2 * radius / theta)
+ xp.sqrt(theta**2 - radius**2)
* xp.arctan(xp.sqrt((theta - radius) / (theta + radius)))
),
F,
)
F_inner = radius / 2 * xp.log(2 * radius / theta_inner) - xp.sqrt(
radius**2 - theta_inner**2
) * xp.arctanh(xp.sqrt((radius - theta_inner) / (radius + theta_inner)))

F_outer = radius / 2 * xp.log(2 * radius / theta_outer) + xp.sqrt(
theta_outer**2 - radius**2
) * xp.arctan(xp.sqrt((theta_outer - radius) / (theta_outer + radius)))

# Both closed forms meet at radius / 2 * ln(2) with slope 1 / 2 in theta; the added
# (theta - radius) is zero in value and gives the edge branch that slope.
F_edge = radius / 2 * xp.log(2 * radius / theta_edge) + (theta_edge - radius)

F = theta * 0.0
F = xp.where(is_inner, F_inner, F)
F = xp.where(is_edge, F_edge, F)
F = xp.where(is_outer, F_outer, F)

return 2 * radius * F


def dev_F_func_from(theta, radius, xp=np):
dev_F = theta * 0.0
"""
The derivative of ``F_func_from`` with respect to ``radius``, for ``theta > 0``.

mask1 = (theta > 0) & (theta < radius)
mask2 = theta == radius
mask3 = theta > radius

dev_F = xp.where(
mask1,
(
radius * xp.log(2 * radius / theta)
- (2 * radius**2 - theta**2)
/ xp.sqrt(radius**2 - theta**2)
* xp.arctanh(xp.sqrt((radius - theta) / (radius + theta)))
),
dev_F,
)
Each closed form is evaluated on a ``theta`` inside its own domain, as in ``F_func_from``,
so that its JAX gradient is finite everywhere.
"""
is_inner = (theta > 0) & (theta < radius)
is_edge = theta == radius
is_outer = theta > radius

dev_F = xp.where(
mask2,
radius * (xp.log(2) - 1 / 2),
dev_F,
theta_inner = xp.where(is_inner, theta, 0.5 * radius)
theta_outer = xp.where(is_outer, theta, 2.0 * radius)

dev_F_inner = radius * xp.log(2 * radius / theta_inner) - (
2 * radius**2 - theta_inner**2
) / xp.sqrt(radius**2 - theta_inner**2) * xp.arctanh(
xp.sqrt((radius - theta_inner) / (radius + theta_inner))
)

dev_F = xp.where(
mask3,
(
radius * xp.log(2 * radius / theta)
+ (theta**2 - 2 * radius**2)
/ xp.sqrt(theta**2 - radius**2)
* xp.arctan(xp.sqrt((theta - radius) / (theta + radius)))
),
dev_F,
dev_F_outer = radius * xp.log(2 * radius / theta_outer) + (
theta_outer**2 - 2 * radius**2
) / xp.sqrt(theta_outer**2 - radius**2) * xp.arctan(
xp.sqrt((theta_outer - radius) / (theta_outer + radius))
)

dev_F = theta * 0.0
dev_F = xp.where(is_inner, dev_F_inner, dev_F)
# Both closed forms meet at radius * (ln(2) - 1 / 2) with slope 1 / 3 in theta; the
# added (theta - radius) / 3 is zero in value and gives the edge branch that slope.
theta_edge = xp.where(is_edge, theta, radius)
dev_F_edge = radius * (xp.log(2) - 1 / 2) + (theta_edge - radius) / 3.0
dev_F = xp.where(is_edge, dev_F_edge, dev_F)
dev_F = xp.where(is_outer, dev_F_outer, dev_F)

return 2 * dev_F


Expand Down Expand Up @@ -330,6 +340,10 @@ def F_func(self, theta, radius, xp=np):
def dev_F_func(self, theta, radius, xp=np):
return dev_F_func_from(theta, radius, xp=xp)

# (kappa_s, scale_radius, core_radius) of a masked-out `vmapped_deflections_from` slot;
# the default of ones would put scale_radius == core_radius and divide by zero.
vmapped_padding_params = (0.0, 1.0, 0.1)

@staticmethod
def radial_deflection_from(r, params, xp):
kappa_s, scale_radius, core_radius = params[0], params[1], params[2]
Expand Down
170 changes: 170 additions & 0 deletions test_autogalaxy/profiles/mass/abstract/test_vmapped_deflections.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
"""
Gradients through `MassProfile.vmapped_deflections_from`, the batched hook of the JAX
line-of-sight / subhalo ray-tracing scan.

A masked-out slot (callers pad these with zeros) must contribute exactly zero to the deflections
and to their gradients, and the cNFW deflections must have finite gradients everywhere.
"""

import importlib.util

import numpy as np
import pytest

import autogalaxy as ag

# The `vmapped_deflections_from` path is jax-backed; these tests need jax
# installed to run (it ships via the `[optional]` extras). The NumPy-only
# Python-version matrix has no jax, so skip there rather than fail.
requires_jax = pytest.mark.skipif(
importlib.util.find_spec("jax") is None,
reason="requires jax (installed via the [optional] extras; absent on the NumPy-only matrix env)",
)

PROFILES = [
(
ag.mp.NFWTruncatedSph,
[
[0.3, -0.2, 0.05, 0.8, 3.0],
[-0.5, 0.4, 0.02, 1.3, 2.5],
],
),
(
ag.mp.cNFWSph,
[
[0.3, -0.2, 0.05, 1.0, 0.1],
[-0.5, 0.4, 0.02, 1.5, 0.3],
],
),
]


def _grid():
return np.random.default_rng(1).uniform(-2.0, 2.0, size=(25, 2))


@requires_jax
@pytest.mark.parametrize("profile_cls, real_params", PROFILES)
def test__masked_zero_slots__value_and_gradients_match_no_padding(
profile_cls, real_params
):
import jax
import jax.numpy as jnp

with jax.enable_x64(True):
grid = jnp.array(_grid())
real = jnp.array(real_params)
padded = jnp.concatenate([real, jnp.zeros((3, real.shape[1]))])
mask_padded = jnp.array([True, True, False, False, False])
mask_real = jnp.array([True, True])

def summed(grid, params, mask):
return jnp.sum(profile_cls.vmapped_deflections_from(grid, params, mask))

value_padded = summed(grid, padded, mask_padded)
value_real = summed(grid, real, mask_real)
d_grid_padded, d_params_padded = jax.grad(summed, argnums=(0, 1))(
grid, padded, mask_padded
)
d_grid_real, d_params_real = jax.grad(summed, argnums=(0, 1))(
grid, real, mask_real
)

assert np.isfinite(np.asarray(d_grid_padded)).all()
assert np.isfinite(np.asarray(d_params_padded)).all()
assert float(value_padded) == pytest.approx(float(value_real), abs=1e-12)
np.testing.assert_allclose(d_grid_padded, d_grid_real, rtol=0.0, atol=1e-10)
np.testing.assert_allclose(
d_params_padded[:2], d_params_real, rtol=0.0, atol=1e-10
)
assert np.all(np.asarray(d_params_padded[2:]) == 0.0)


@requires_jax
@pytest.mark.parametrize("profile_cls, real_params", PROFILES)
def test__all_slots_masked__deflections_and_gradients_are_zero(
profile_cls, real_params
):
import jax
import jax.numpy as jnp

with jax.enable_x64(True):
grid = jnp.array(_grid())
params = jnp.zeros((3, len(real_params[0])))
mask = jnp.array([False, False, False])

def summed(grid, params):
return jnp.sum(profile_cls.vmapped_deflections_from(grid, params, mask))

d_grid, d_params = jax.grad(summed, argnums=(0, 1))(grid, params)

assert float(summed(grid, params)) == 0.0
assert np.all(np.asarray(d_grid) == 0.0)
assert np.all(np.asarray(d_params) == 0.0)


@requires_jax
def test__cnfw_sph__vmapped_gradients_finite_and_match_finite_differences():
import jax
import jax.numpy as jnp

params = np.array([[0.1, -0.2, 0.05, 1.0, 0.1]])
# Points inside the core radius, between the core and scale radius, outside the scale
# radius and exactly on the scale radius.
grid = np.array(
[[0.1 + 0.05, -0.2], [0.1 + 0.4, -0.2], [0.1, -0.2 + 2.5], [0.1 + 1.0, -0.2]]
)
mask = jnp.array([True])

def summed(grid, params):
return jnp.sum(ag.mp.cNFWSph.vmapped_deflections_from(grid, params, mask))

with jax.enable_x64(True):
d_grid, d_params = jax.grad(summed, argnums=(0, 1))(
jnp.array(grid), jnp.array(params)
)

# Not smaller: the closed forms lose precision within ~1e-6 of the scale radius,
# which a smaller central difference amplifies.
step = 1.0e-4
d_params_numerical = np.zeros_like(params)
for i in range(params.shape[1]):
up, down = params.copy(), params.copy()
up[0, i] += step
down[0, i] -= step
d_params_numerical[0, i] = (
float(summed(jnp.array(grid), jnp.array(up)))
- float(summed(jnp.array(grid), jnp.array(down)))
) / (2.0 * step)

assert np.isfinite(np.asarray(d_grid)).all()
assert np.isfinite(np.asarray(d_params)).all()
np.testing.assert_allclose(d_params, d_params_numerical, rtol=1e-5, atol=1e-8)


def test__cnfw_f_func__value_and_slope_continuous_at_the_radius():
from autogalaxy.profiles.mass.dark.cnfw import F_func_from

radius = 1.3
step = 1.0e-7
theta = np.array([radius - step, radius, radius + step])

F = F_func_from(theta, radius)

assert F[1] == pytest.approx(radius**2 * np.log(2.0), rel=1e-12)
assert F[0] == pytest.approx(F[1], abs=1e-6)
assert F[2] == pytest.approx(F[1], abs=1e-6)


def test__cnfw_dev_f_func__value_continuous_at_the_radius():
from autogalaxy.profiles.mass.dark.cnfw import dev_F_func_from

radius = 1.3
step = 1.0e-7
theta = np.array([radius - step, radius, radius + step])

dev_F = dev_F_func_from(theta, radius)

assert dev_F[1] == pytest.approx(2.0 * radius * (np.log(2.0) - 0.5), rel=1e-12)
assert dev_F[0] == pytest.approx(dev_F[1], abs=1e-6)
assert dev_F[2] == pytest.approx(dev_F[1], abs=1e-6)
Loading