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
8 changes: 7 additions & 1 deletion autofit/aggregator/summary/aggregate_csv/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,18 +16,23 @@


class AggregateCSV:
def __init__(self, aggregator: Aggregator):
def __init__(self, aggregator: Aggregator, strict: bool = False):
"""
Summarise results from the aggregator as a CSV.

Parameters
----------
aggregator
strict
If True an argument matching neither the samples_summary nor the
latent_summary raises a KeyError. If False (the default) a warning
is logged once for each such column and its values are left empty.
"""
if len(aggregator) == 0:
raise ValueError("The aggregator is empty.")

self._aggregator = aggregator
self._strict = strict
self._columns = []

def add_variable(
Expand Down Expand Up @@ -56,6 +61,7 @@ def add_variable(
argument,
name=name,
value_types=value_types,
strict=self._strict,
)
)

Expand Down
40 changes: 40 additions & 0 deletions autofit/aggregator/summary/aggregate_csv/column.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import logging
from abc import ABC, abstractmethod
from enum import Enum
from typing import Optional, Callable

logger = logging.getLogger(__name__)


class AbstractColumn(ABC):
def __init__(self, name: str):
Expand Down Expand Up @@ -37,6 +40,7 @@ def __init__(
argument: str,
name: Optional[str] = None,
value_types: list[ValueType] = (ValueType.Median,),
strict: bool = False,
):
"""
A column in the summary table.
Expand All @@ -49,6 +53,10 @@ def __init__(
An optional name for the column
value_types
Value types to include. See ValueType.
strict
If True an argument matching neither the samples_summary nor the
latent_summary raises a KeyError. If False (the default) a warning
is logged once for the column and the values are left empty.
"""
super().__init__(
name
Expand All @@ -59,8 +67,40 @@ def __init__(
)
self.argument = argument
self.value_types = value_types
self.strict = strict
self._has_warned = False

def _check_argument(self, row: "Row"):
"""
Check that the argument matches the samples_summary or latent_summary
of a row.

If it matches neither then a KeyError is raised when strict, else a
warning is logged once for the column.

Parameters
----------
row
A row in the summary table
"""
if self.path in row.known_paths:
return

available = sorted(".".join(path) for path in row.known_paths)
message = (
f"Argument '{self.argument}' matches no value in the samples "
f"summary or latent summary. Available arguments include: "
f"{', '.join(available[:10])}"
)
if self.strict:
raise KeyError(message)
if not self._has_warned:
self._has_warned = True
logger.warning(message)

def value(self, row: "Row"):
self._check_argument(row)

result = {}

if ValueType.Median in self.value_types:
Expand Down
44 changes: 35 additions & 9 deletions autofit/aggregator/summary/aggregate_csv/row.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,30 +41,43 @@ def _add_paths(self, kwargs):
def _latent_summary(self):
return self.result.value("latent.latent_summary")

def _sample_kwargs(self, sample) -> dict:
"""
The arguments of a sample keyed by every path to each prior, or an
empty dict when the summary holds no such sample (e.g. a search
without a PDF has no median_pdf_sample).
"""
if sample is None:
return {}
return self._add_paths(sample.kwargs)

@cached_property
def median_pdf_sample_kwargs(self) -> dict:
"""
The median_pdf_sample arguments for the search from the samples_summary and latent_summary.
"""
samples_summary = self.result.samples_summary
kwargs = self._add_paths(samples_summary.median_pdf_sample.kwargs)
kwargs = self._sample_kwargs(samples_summary.median_pdf_sample)

latent_summary = self._latent_summary
if latent_summary is not None:
if latent_summary is not None and latent_summary.median_pdf_sample is not None:
kwargs.update(latent_summary.median_pdf_sample.kwargs)

return kwargs

@cached_property
def max_likelihood_kwargs(self):
"""
The median_pdf_sample arguments for the search from the samples_summary and latent_summary.
The max_log_likelihood_sample arguments for the search from the samples_summary and latent_summary.
"""
samples_summary = self.result.samples_summary
kwargs = self._add_paths(samples_summary.median_pdf_sample.kwargs)
kwargs = self._sample_kwargs(samples_summary.max_log_likelihood_sample)

latent_summary = self._latent_summary
if latent_summary is not None:
if (
latent_summary is not None
and latent_summary.max_log_likelihood_sample is not None
):
kwargs.update(latent_summary.max_log_likelihood_sample.kwargs)

return kwargs
Expand All @@ -74,14 +87,14 @@ def values_at_sigma_1_kwargs(self) -> dict:
"""
The values_at_sigma_1 arguments for the search from the samples_summary.
"""
kwargs = self._add_paths(self.result.samples_summary.values_at_sigma_1)
kwargs = self._add_paths(self.result.samples_summary.values_at_sigma_1 or {})

latent_summary = self._latent_summary
if latent_summary is not None:
kwargs.update(
{
tuple(key.split(".")): value
for key, value in latent_summary.values_at_sigma_1.items()
for key, value in (latent_summary.values_at_sigma_1 or {}).items()
}
)

Expand All @@ -92,19 +105,32 @@ def values_at_sigma_3_kwargs(self) -> dict:
"""
The values_at_sigma_3 arguments for the search from the samples_summary.
"""
kwargs = self._add_paths(self.result.samples_summary.values_at_sigma_3)
kwargs = self._add_paths(self.result.samples_summary.values_at_sigma_3 or {})

latent_summary = self._latent_summary
if latent_summary is not None:
kwargs.update(
{
tuple(key.split(".")): value
for key, value in latent_summary.values_at_sigma_1.items()
for key, value in (latent_summary.values_at_sigma_3 or {}).items()
}
)

return kwargs

@cached_property
def known_paths(self) -> set:
"""
Every argument path that can be resolved for this row, from the
samples_summary and the latent_summary.
"""
return (
set(self.median_pdf_sample_kwargs)
| set(self.max_likelihood_kwargs)
| set(self.values_at_sigma_1_kwargs)
| set(self.values_at_sigma_3_kwargs)
)

def dict(self) -> dict:
"""
The row as a dictionary including an id and one entry for each column.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
"kwargs": {
"type": "dict",
"arguments": {
"galaxies.lens.bulge.centre.centre_0": -1.0,
"galaxies.lens.bulge.centre.centre_0": -1.5,
"galaxies.lens.bulge.centre.centre_1": -2.0
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
"kwargs": {
"type": "dict",
"arguments": {
"galaxies.lens.bulge.centre.centre_0": -5.0,
"galaxies.lens.bulge.centre.centre_0": -5.5,
"galaxies.lens.bulge.centre.centre_1": -6.0
}
}
Expand Down
Loading
Loading