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
7 changes: 7 additions & 0 deletions autolens/point/dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,13 @@ def __init__(
be paired with the `Point` model-component which has the name `source_1`. If a dataset component is not
successfully paired with a model-component, an error is raised.

The dataset holds observations only and stores no magnifications, which are model quantities. The
magnification at each observed position is available on any point fit (e.g. `FitFluxes`,
`FitPositionsImagePairAllSolved`) and on a finished model-fit's `ResultPoint`, via
`signed_magnifications_at_positions` (sign = image parity) and `magnifications_at_positions` (|mu|). For
arbitrary (y,x) image-plane coordinates use
`ag.LensCalc.from_tracer(tracer=...).magnification_2d_via_hessian_from(grid=...)`.

Parameters
----------
name
Expand Down
52 changes: 42 additions & 10 deletions autolens/point/fit/abstract.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,16 @@

Concrete subclasses implement ``figure_of_merit`` to compute the chi-squared or
log-likelihood for the specific observable (positions, fluxes, time delays) being fitted.

Magnification at a point: every point fit exposes ``signed_magnifications_at_positions``
(the Hessian magnification at each observed image position, with the image parity
preserved as its sign) and ``magnifications_at_positions`` (its absolute value, which
the flux fits and magnification weighting consume). For multi-plane tracers these use
the plane of the paired point source, not the final plane. The same accessors are
available on a finished model-fit via ``ResultPoint``. For arbitrary (y,x) coordinates
use ``ag.LensCalc.from_tracer(tracer=...).magnification_2d_via_hessian_from(grid=...)``.
"""

from abc import ABC
import numpy as np
from typing import Optional, Tuple
Expand Down Expand Up @@ -108,19 +117,24 @@ def noise_map(self):
return self._noise_map

@property
def magnifications_at_positions(self) -> aa.ArrayIrregular:
def signed_magnifications_at_positions(self) -> aa.ArrayIrregular:
"""
The magnification of every observed position in the image-plane, which is computed from the tracer's deflection
angle map via the Hessian.
The signed magnification of every observed position in the image-plane, computed from the tracer's
deflection angle map via the Hessian, with the image parity preserved.

These magnifications are used for two purposes:
The magnification is mu = 1 / det(A), where A is the lensing Jacobian. Its sign is the physical image
parity observable: positive for images of positive parity (minima, and maxima such as the central image),
negative for saddle-point images of negative parity. This accessor returns the raw signed value; the
unsigned `magnifications_at_positions` is `abs()` of it.

1) For the opt-in `weighting = "magnification"` source-plane chi-squared, the residuals are multiplied by the
magnification to approximate how the noise in the image-plane positions maps to the source-plane (the
default `"jacobian"` weighting uses the full lensing Jacobian instead).
For multi-plane tracers (more than two planes) the magnification is computed with multi-plane lensing up to
the plane containing the paired point-source profile (`plane_j`), not the final plane, so each source in a
cluster gets the magnification appropriate to its own redshift.

2) For fitting the fluxes of point sources, the magnification is used to scale the flux of the point source
in the source-plane to the image-plane, thus computing the model image-plane fluxes.
This property is JAX-traceable and returns an `aa.ArrayIrregular` on both the NumPy and JAX backends.

To compute the magnification at arbitrary (y,x) image-plane coordinates (rather than at the observed
positions of a dataset), use `ag.LensCalc.from_tracer(...).magnification_2d_via_hessian_from(grid=...)`.
"""
use_multi_plane = len(self.tracer.planes) > 2
plane_j = (
Expand All @@ -138,7 +152,25 @@ def magnifications_at_positions(self) -> aa.ArrayIrregular:
)
if self.use_jax:
magnifications = aa.ArrayIrregular(values=magnifications)
return abs(magnifications)
return magnifications

@property
def magnifications_at_positions(self) -> aa.ArrayIrregular:
"""
The (unsigned) magnification of every observed position in the image-plane, which is computed from the
tracer's deflection angle map via the Hessian. This is `abs()` of `signed_magnifications_at_positions`, so the
image parity (sign) is discarded; use `signed_magnifications_at_positions` to read the parity.

These magnifications are used for two purposes, both of which consume |mu| by construction:

1) For the opt-in `weighting = "magnification"` source-plane chi-squared, the residuals are multiplied by the
magnification to approximate how the noise in the image-plane positions maps to the source-plane (the
default `"jacobian"` weighting uses the full lensing Jacobian instead).

2) For fitting the fluxes of point sources, the magnification is used to scale the flux of the point source
in the source-plane to the image-plane, thus computing the model image-plane fluxes.
"""
return abs(self.signed_magnifications_at_positions)

@property
def source_plane_coordinate(self) -> Tuple[float, float]:
Expand Down
43 changes: 43 additions & 0 deletions autolens/point/model/result.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,46 @@ def grid(self):
@property
def max_log_likelihood_fit(self):
return self.analysis.fit_from(instance=self.instance)

def _max_log_likelihood_component_fit(self):
"""
Returns the component fit (positions, flux or time-delay) of the maximum log likelihood `FitPointDataset`
which carries the per-image magnification accessors.

Every component fit of a `FitPointDataset` is an `AbstractFitPoint` evaluated at the observed positions
of the same `PointDataset` with the same tracer and point-source name, so they all give identical
magnifications; the first present component (positions, then flux, then time delays) is used.
"""
fit = self.max_log_likelihood_fit

for component in ("positions", "flux", "time_delays"):
component_fit = getattr(fit, component, None)
if component_fit is not None and hasattr(
component_fit, "signed_magnifications_at_positions"
):
return component_fit

raise AttributeError(
f"The maximum log likelihood fit of this ResultPoint is of type {type(fit).__name__}, which has no "
f"positions, flux or time-delay component fit carrying `signed_magnifications_at_positions`, so the "
f"per-image magnifications cannot be computed from it."
)

@property
def signed_magnifications_at_positions(self) -> aa.ArrayIrregular:
"""
The signed magnification at every observed image position of the point-source dataset, computed from the
maximum log likelihood tracer via the Hessian. The sign is the physical image parity (negative for
saddle-point images); see `AbstractFitPoint.signed_magnifications_at_positions`.
"""
return (
self._max_log_likelihood_component_fit().signed_magnifications_at_positions
)

@property
def magnifications_at_positions(self) -> aa.ArrayIrregular:
"""
The unsigned magnification |mu| at every observed image position of the point-source dataset, computed from
the maximum log likelihood tracer via the Hessian; see `AbstractFitPoint.magnifications_at_positions`.
"""
return self._max_log_likelihood_component_fit().magnifications_at_positions
82 changes: 82 additions & 0 deletions test_autolens/point/fit/test_abstract.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import numpy as np
import pytest

import autogalaxy as ag
Expand Down Expand Up @@ -44,3 +45,84 @@ def test__magnifications_at_positions__multi_plane_calculation(gal_x1_mp):
assert fit_0.magnifications_at_positions[0] != pytest.approx(
fit_1.magnifications_at_positions.array[0], 1.0e-1
)


def _sie_tracer_and_positions():
lens = al.Galaxy(
redshift=0.5,
mass=al.mp.Isothermal(
centre=(0.0, 0.0), einstein_radius=1.0, ell_comps=(0.0, 0.1)
),
)
source = al.Galaxy(
redshift=1.0, point_0=al.ps.PointFlux(centre=(0.0, 0.0), flux=1.0)
)

tracer = al.Tracer(galaxies=[lens, source])

# Hand-supplied image positions: outside the critical curve (positive parity, minimum) and inside it
# (negative parity, saddle point).
positions = al.Grid2DIrregular([(0.0, 1.8), (0.0, -0.6)])

return tracer, positions


def _assert_mixed_parity(fit):
signed = fit.signed_magnifications_at_positions
unsigned = fit.magnifications_at_positions

assert isinstance(signed, al.ArrayIrregular)
assert isinstance(unsigned, al.ArrayIrregular)

signed = np.asarray(signed.array)
unsigned = np.asarray(unsigned.array)

assert signed[0] > 0.0
assert signed[1] < 0.0
assert signed == pytest.approx(np.array([2.571428571, -1.2]), 1.0e-4)
assert (unsigned == np.abs(signed)).all()


def test__signed_magnifications_at_positions__mixed_parity__numpy():
tracer, positions = _sie_tracer_and_positions()

fit = al.FitFluxes(
name="point_0",
data=al.ArrayIrregular([1.0, 1.0]),
noise_map=al.ArrayIrregular([1.0, 1.0]),
positions=positions,
tracer=tracer,
)

_assert_mixed_parity(fit)


def test__signed_magnifications_at_positions__mixed_parity__jax():
jnp = pytest.importorskip("jax.numpy")

tracer, positions = _sie_tracer_and_positions()

fit = al.FitFluxes(
name="point_0",
data=al.ArrayIrregular([1.0, 1.0]),
noise_map=al.ArrayIrregular([1.0, 1.0]),
positions=positions,
tracer=tracer,
xp=jnp,
)

assert fit.use_jax is True

_assert_mixed_parity(fit)

fit_np = al.FitFluxes(
name="point_0",
data=al.ArrayIrregular([1.0, 1.0]),
noise_map=al.ArrayIrregular([1.0, 1.0]),
positions=positions,
tracer=tracer,
)

assert np.asarray(fit.signed_magnifications_at_positions.array) == pytest.approx(
fit_np.signed_magnifications_at_positions.array, 1.0e-8
)
62 changes: 62 additions & 0 deletions test_autolens/point/fit/test_multi_plane_magnification.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import numpy as np
import pytest

import autogalaxy as ag
import autolens as al


def test__signed_magnifications_at_positions__multi_plane__uses_point_source_plane_not_final_plane():
"""
A three-plane tracer whose point source sits in the middle plane: the fit's magnification must be the
multi-plane magnification up to that plane (`plane_j`), and must differ from the final-plane value, so the
test fails if `plane_j` silently resolves to the final plane.
"""
lens = al.Galaxy(
redshift=0.5,
mass=al.mp.Isothermal(
centre=(0.0, 0.0), einstein_radius=1.0, ell_comps=(0.0, 0.1)
),
)
middle = al.Galaxy(
redshift=1.0,
mass=al.mp.IsothermalSph(centre=(0.1, 0.1), einstein_radius=0.3),
point_0=al.ps.PointFlux(centre=(0.0, 0.0), flux=1.0),
)
final = al.Galaxy(redshift=2.0, mass=al.mp.IsothermalSph(einstein_radius=0.1))

tracer = al.Tracer(galaxies=[lens, middle, final])

assert len(tracer.planes) == 3

plane_j = tracer.extract_plane_index_of_profile(profile_name="point_0")

assert plane_j == 1

positions = al.Grid2DIrregular([(0.0, 1.8), (0.0, -0.6), (1.5, 0.0)])

fit = al.FitFluxes(
name="point_0",
data=al.ArrayIrregular([1.0, 1.0, 1.0]),
noise_map=al.ArrayIrregular([1.0, 1.0, 1.0]),
positions=positions,
tracer=tracer,
)

assert fit.plane_index == plane_j

expected = ag.LensCalc.from_tracer(
tracer, use_multi_plane=True, plane_j=plane_j
).magnification_2d_via_hessian_from(grid=positions)

final_plane = ag.LensCalc.from_tracer(
tracer, use_multi_plane=True, plane_j=-1
).magnification_2d_via_hessian_from(grid=positions)

signed = np.asarray(fit.signed_magnifications_at_positions.array)

assert signed == pytest.approx(np.asarray(expected.array), 1.0e-10)
assert np.asarray(fit.magnifications_at_positions.array) == pytest.approx(
np.abs(np.asarray(expected.array)), 1.0e-10
)

assert not np.allclose(signed, np.asarray(final_plane.array), rtol=1.0e-3)
74 changes: 74 additions & 0 deletions test_autolens/point/model/test_result_point.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import numpy as np
import pytest

import autofit as af
import autolens as al

from autolens.point.model.result import ResultPoint


def _result_point(dataset_name="point_0"):
lens = al.Galaxy(
redshift=0.5,
mass=al.mp.Isothermal(
centre=(0.0, 0.0), einstein_radius=1.0, ell_comps=(0.0, 0.1)
),
)
source = al.Galaxy(
redshift=1.0, point_0=al.ps.PointFlux(centre=(0.0, 0.0), flux=1.0)
)

instance = af.ModelInstance()
instance.galaxies = af.ModelInstance()
instance.galaxies.lens = lens
instance.galaxies.source = source

positions = al.Grid2DIrregular([(0.0, 1.8), (0.0, -0.6)])

dataset = al.PointDataset(
name=dataset_name,
positions=positions,
positions_noise_map=al.ArrayIrregular([0.05, 0.05]),
fluxes=al.ArrayIrregular([1.0, 1.0]),
fluxes_noise_map=al.ArrayIrregular([0.1, 0.1]),
)

solver = al.m.MockPointSolver(model_positions=positions)

analysis = al.AnalysisPoint(dataset=dataset, solver=solver, use_jax=False)

samples_summary = al.m.MockSamplesSummary(max_log_likelihood_instance=instance)

return ResultPoint(samples_summary=samples_summary, analysis=analysis)


def test__magnification_accessors__delegate_to_max_log_likelihood_fit():
result = _result_point()

fit = result.max_log_likelihood_fit

signed = result.signed_magnifications_at_positions
unsigned = result.magnifications_at_positions

assert isinstance(signed, al.ArrayIrregular)
assert isinstance(unsigned, al.ArrayIrregular)

assert signed.array == pytest.approx(
fit.positions.signed_magnifications_at_positions.array, 1.0e-10
)
assert signed.array == pytest.approx(
fit.flux.signed_magnifications_at_positions.array, 1.0e-10
)
assert signed.array[0] > 0.0
assert signed.array[1] < 0.0
assert (np.asarray(unsigned.array) == np.abs(np.asarray(signed.array))).all()


def test__magnification_accessors__no_component_fit__raises_naming_fit_type():
result = _result_point(dataset_name="point_unpaired")

with pytest.raises(AttributeError, match="FitPointDataset"):
result.signed_magnifications_at_positions

with pytest.raises(AttributeError, match="FitPointDataset"):
result.magnifications_at_positions
Loading