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
64 changes: 61 additions & 3 deletions autoarray/inversion/inversion/abstract.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import warnings

import numpy as np
from typing import Dict, List, Optional, Type, Union
from typing import Dict, List, Optional, Tuple, Type, Union

from autonerves import cached_property, is_test_mode

Expand Down Expand Up @@ -1253,10 +1253,68 @@ def log_det_regularization_matrix_term(self) -> float:
if all(term is not None for term in term_list):
return sum(term_list)

return self._log_det_symmetric_from(
self.regularization_matrix_reduced, sparse=self._xp is np
grounded_indexes, log_block_sizes = self._intrinsic_regularization_blocks

if len(grounded_indexes) == 0:
return self._log_det_symmetric_from(
self.regularization_matrix_reduced, sparse=self._xp is np
)

# Pseudo-determinant of each intrinsic block (PyAutoArray#682). For a symmetric block `H_b` whose null
# vector is the constant `1 / sqrt(P_b)`, `pdet(H_b) = P_b * det(H_b with one row and column deleted)`:
# deleting ("grounding") one pixel removes the constant mode exactly, so the term no longer contains the
# `log` of the ~1e-8 diagonal jitter that otherwise holds that mode up, nor the rounding noise of order
# `eps * ||H|| / 1e-8` that came with it. The grounded matrix keeps `H`'s sparsity and its indices are
# static, so the sparse NumPy route and `jax.jit` are both unchanged.
matrix = self.regularization_matrix_reduced
keep = np.setdiff1d(np.arange(matrix.shape[0]), grounded_indexes)

if keep.shape[0] == 0:
return log_block_sizes

return log_block_sizes + self._log_det_symmetric_from(
matrix[keep][:, keep], sparse=self._xp is np
)

@property
def _intrinsic_regularization_blocks(self) -> Tuple[np.ndarray, float]:
"""
The blocks of `regularization_matrix_reduced` whose regularization has an exact constant null mode
(`AbstractRegularization.has_constant_null_mode`), as the index of the first parameter of every such block
in `regularization_matrix_reduced` coordinates, and the sum of `log(P_b)` over their sizes `P_b`.

`regularization_matrix_reduced` is the block diagonal of every linear object's regularization matrix when
every linear object is regularized, and otherwise the restriction of that to the mapper parameters
(`mapper_indices`). In both cases each regularized block is contiguous, so its first index is the running
sum of the sizes of the blocks before it.
"""
if self.all_linear_obj_have_regularization:
linear_obj_list = self.linear_obj_list
else:
linear_obj_list = self.cls_list_from(cls=Mapper)

if not any(
getattr(linear_obj.regularization, "has_constant_null_mode", False)
for linear_obj in linear_obj_list
):
return np.asarray([], dtype=int), 0.0

grounded_indexes = []
log_block_sizes = 0.0
offset = 0

for linear_obj in linear_obj_list:
params = int(linear_obj.params)
regularization = linear_obj.regularization

if regularization is not None and regularization.has_constant_null_mode:
grounded_indexes.append(offset)
log_block_sizes += float(np.log(params))

offset += params

return np.asarray(grounded_indexes, dtype=int), log_block_sizes

@property
def reconstruction_covariance_matrix(self) -> np.ndarray:
"""
Expand Down
17 changes: 17 additions & 0 deletions autoarray/inversion/regularization/abstract.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,23 @@ class AbstractRegularization:
combinations at construction.
"""

has_constant_null_mode = False
"""
Whether this scheme's regularization matrix ``H`` has the constant vector as an exact null mode by
construction, i.e. it is the precision matrix of an *intrinsic* Gaussian prior that penalizes only differences
between pixels and leaves the overall level of the reconstruction unconstrained.

This holds for the smoothness schemes whose every row of ``B`` sums to zero (``Constant``, ``ConstantSplit``,
``Adapt``, ``AdaptPower``, ``AdaptSplit``, ``AdaptSplitPower``); their ``H`` is singular except for the small
diagonal jitter added for numerical stability. It does not hold for schemes with a zeroth-order term or a
kernel covariance, whose ``H`` is positive-definite in its own right.

When ``True`` the Bayesian evidence normalises the prior with the **pseudo-determinant** of ``H`` (the product of
its non-zero eigenvalues) rather than its determinant, which would be set by the arbitrary jitter and carry its
rounding noise (PyAutoArray#682): see ``AbstractInversion.log_det_regularization_matrix_term``. A unit test pins
this flag to the measured spectrum of every scheme, so it must only be set where the null mode is exact.
"""

def __init__(self):
"""
Abstract base class for a regularization-scheme, which is applied to a pixelization to enforce a \
Expand Down
3 changes: 3 additions & 0 deletions autoarray/inversion/regularization/adapt.py
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,9 @@ def weighted_regularization_matrix_single_scatter_from(


class Adapt(AbstractRegularization):
# The rows of B sum to zero, so H's constant vector is an exact null mode (PyAutoArray#682).
has_constant_null_mode = True

def __init__(
self,
inner_coefficient: float = 1.0,
Expand Down
3 changes: 3 additions & 0 deletions autoarray/inversion/regularization/adapt_split_zeroth.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@


class AdaptSplitZeroth(Adapt):
# Inherits from `Adapt` but adds a zeroth-order term, so H is positive-definite in its own right.
has_constant_null_mode = False

is_split_regularization = True

def __init__(
Expand Down
3 changes: 3 additions & 0 deletions autoarray/inversion/regularization/constant.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,9 @@ class in the module `autoarray.inversion.regularization`.


class Constant(AbstractRegularization):
# The rows of B sum to zero, so H's constant vector is an exact null mode (PyAutoArray#682).
has_constant_null_mode = True

def __init__(self, coefficient: float = 1.0):
"""
Regularization which uses the neighbors of the mesh (e.g. shared Delaunay vertexes) and
Expand Down
179 changes: 179 additions & 0 deletions test_autoarray/inversion/inversion/test_intrinsic_log_det.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
"""
PyAutoArray#682: the evidence's ``log det H`` term for intrinsic regularization schemes.

The smoothness schemes build an ``H`` whose constant vector is an exact null mode, held up only by the 1e-8
diagonal jitter. The evidence therefore normalises them with the pseudo-determinant (the product of the
non-zero eigenvalues), and ``AbstractRegularization.has_constant_null_mode`` says which schemes those are.
"""

import numpy as np
import pytest

import autoarray as aa
from autoarray import fixtures


def _mappers():
return {
"delaunay": fixtures.make_delaunay_mapper_9_3x3(),
"rectangular": fixtures.make_rectangular_mapper_7x7_3x3(),
}


SCHEMES = [
aa.reg.Constant(coefficient=3.0),
aa.reg.ConstantSplit(coefficient=3.0),
aa.reg.Adapt(inner_coefficient=0.1, outer_coefficient=10.0),
aa.reg.AdaptPower(inner_coefficient=0.1, outer_coefficient=10.0),
aa.reg.AdaptSplit(inner_coefficient=0.1, outer_coefficient=10.0),
aa.reg.AdaptSplitPower(inner_coefficient=0.1, outer_coefficient=10.0),
aa.reg.Zeroth(coefficient=3.0),
aa.reg.ConstantZeroth(coefficient_neighbor=3.0, coefficient_zeroth=1.0),
aa.reg.AdaptSplitZeroth(inner_coefficient=0.1, outer_coefficient=10.0),
aa.reg.AdaptSplitZerothPower(inner_coefficient=0.1, outer_coefficient=10.0),
aa.reg.GaussianKernel(coefficient=3.0, scale=0.5),
aa.reg.ExponentialKernel(coefficient=3.0, scale=0.5),
]


def _cases(schemes):
"""
Every (scheme, mesh) pair the scheme applies to: split schemes need an adaptive mesh's split tables,
which the rectangular mesh does not provide, so they are paired with the Delaunay mesh only.
"""
return [
pytest.param(scheme, mesh, id=f"{type(scheme).__name__}-{mesh}")
for scheme in schemes
for mesh in ("delaunay", "rectangular")
if mesh == "delaunay" or not scheme.is_split_regularization
]


def _matrix_from(regularization, mapper):
return np.asarray(regularization.regularization_matrix_from(linear_obj=mapper))


@pytest.mark.parametrize("regularization, mesh", _cases(SCHEMES))
def test__has_constant_null_mode__matches_measured_spectrum(regularization, mesh):
"""
The flag must describe the matrix: an intrinsic scheme's smallest eigenvalue is the jitter with the
constant vector as its eigenvector and an O(1) gap above it; every other scheme is positive-definite
without the jitter.
"""
matrix = _matrix_from(regularization, _mappers()[mesh])

eigenvalues, eigenvectors = np.linalg.eigh(matrix)
pixels = matrix.shape[0]
overlap = abs(eigenvectors[:, 0] @ np.ones(pixels) / np.sqrt(pixels))

intrinsic = eigenvalues[0] < 1.0e-6 and overlap > 1.0 - 1.0e-9

assert regularization.has_constant_null_mode == intrinsic

if intrinsic:
assert eigenvalues[1] > 1.0e-3


def _inversion_from(mapper_list):
return aa.m.MockInversion(
linear_obj_list=mapper_list,
regularization_matrix=__import__("scipy.linalg").linalg.block_diag(
*[np.asarray(mapper.regularization_matrix) for mapper in mapper_list]
),
)


def _mapper_with(regularization, mesh):
mapper = _mappers()[mesh]
return type(mapper)(
interpolator=mapper.interpolator,
regularization=regularization,
image_plane_mesh_grid=mapper.image_plane_mesh_grid,
)


@pytest.mark.parametrize(
"regularization, mesh",
_cases([scheme for scheme in SCHEMES if scheme.has_constant_null_mode]),
)
def test__log_det_regularization_matrix_term__intrinsic__is_pseudo_determinant(
regularization, mesh
):
"""
The term equals an independent eigenvalue pseudo-determinant (log of the non-zero eigenvalues), not the
full determinant, which differs from it by the log of the ~1e-8 jitter.
"""
mapper = _mapper_with(regularization, mesh)
matrix = np.asarray(mapper.regularization_matrix)

eigenvalues = np.linalg.eigvalsh(matrix)

log_det = _inversion_from([mapper]).log_det_regularization_matrix_term

assert log_det == pytest.approx(np.sum(np.log(eigenvalues[1:])), abs=1.0e-7)

# The full determinant differs by the log of the constant-mode eigenvalue: the 1e-8 jitter plus round-off
# of order eps * ||H||. That round-off is what the pseudo-determinant removes; at `Adapt` outer=10 it is
# ~2e-4 in the log here, hence the loose tolerance on this illustrative gap only.
assert np.sum(np.log(eigenvalues)) - log_det == pytest.approx(
np.log(1.0e-8), abs=1.0e-3
)


@pytest.mark.parametrize("mesh", ["delaunay", "rectangular"])
def test__log_det_regularization_matrix_term__intrinsic__independent_of_constant_mode(
mesh,
):
"""
The pseudo-determinant does not see the constant mode at all: moving that mode's eigenvalue from the
jitter to 1e-5 leaves the term unchanged, where the full determinant would shift by ``log(1e3)``.
"""
mapper = _mapper_with(
aa.reg.Adapt(inner_coefficient=0.1, outer_coefficient=10.0), mesh
)
matrix = np.asarray(mapper.regularization_matrix)
pixels = matrix.shape[0]

lifted = matrix + 1.0e-5 * np.ones((pixels, pixels)) / pixels

log_det = aa.m.MockInversion(
linear_obj_list=[mapper], regularization_matrix=matrix
).log_det_regularization_matrix_term
log_det_lifted = aa.m.MockInversion(
linear_obj_list=[mapper], regularization_matrix=lifted
).log_det_regularization_matrix_term

assert log_det_lifted == pytest.approx(log_det, abs=1.0e-6)


def test__log_det_regularization_matrix_term__non_intrinsic__unchanged():
"""A positive-definite scheme keeps the full determinant."""
mapper = _mapper_with(aa.reg.Zeroth(coefficient=3.0), "delaunay")
matrix = np.asarray(mapper.regularization_matrix)

log_det = _inversion_from([mapper]).log_det_regularization_matrix_term

assert log_det == pytest.approx(np.linalg.slogdet(matrix)[1], rel=1.0e-12)


def test__log_det_regularization_matrix_term__multiple_mappers__sum_of_blocks():
"""
Each regularized mapper is its own block: an intrinsic block contributes its pseudo-determinant and a
positive-definite block its determinant, so the term is the sum of the per-mapper terms.
"""
mapper_0 = _mapper_with(aa.reg.Constant(coefficient=3.0), "delaunay")
mapper_1 = _mapper_with(aa.reg.Zeroth(coefficient=2.0), "rectangular")
mapper_2 = _mapper_with(
aa.reg.Adapt(inner_coefficient=0.1, outer_coefficient=10.0), "rectangular"
)

combined = _inversion_from([mapper_0, mapper_1, mapper_2])

separate = sum(
_inversion_from([mapper]).log_det_regularization_matrix_term
for mapper in (mapper_0, mapper_1, mapper_2)
)

assert combined.log_det_regularization_matrix_term == pytest.approx(
separate, rel=1.0e-12
)
Loading
Loading