diff --git a/autofit/aggregator/summary/aggregate_csv/__init__.py b/autofit/aggregator/summary/aggregate_csv/__init__.py index 3bd8531d4..30bcef07f 100644 --- a/autofit/aggregator/summary/aggregate_csv/__init__.py +++ b/autofit/aggregator/summary/aggregate_csv/__init__.py @@ -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( @@ -56,6 +61,7 @@ def add_variable( argument, name=name, value_types=value_types, + strict=self._strict, ) ) diff --git a/autofit/aggregator/summary/aggregate_csv/column.py b/autofit/aggregator/summary/aggregate_csv/column.py index 77eedafde..ba7694102 100644 --- a/autofit/aggregator/summary/aggregate_csv/column.py +++ b/autofit/aggregator/summary/aggregate_csv/column.py @@ -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): @@ -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. @@ -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 @@ -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: diff --git a/autofit/aggregator/summary/aggregate_csv/row.py b/autofit/aggregator/summary/aggregate_csv/row.py index b1304b7ae..88f985c60 100644 --- a/autofit/aggregator/summary/aggregate_csv/row.py +++ b/autofit/aggregator/summary/aggregate_csv/row.py @@ -41,16 +41,26 @@ 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 @@ -58,13 +68,16 @@ def median_pdf_sample_kwargs(self) -> dict: @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 @@ -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() } ) @@ -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. diff --git a/test_autofit/aggregator/summary_files/aggregate_summary/fit_1/files/samples_summary.json b/test_autofit/aggregator/summary_files/aggregate_summary/fit_1/files/samples_summary.json index 072379d23..e631daeaf 100644 --- a/test_autofit/aggregator/summary_files/aggregate_summary/fit_1/files/samples_summary.json +++ b/test_autofit/aggregator/summary_files/aggregate_summary/fit_1/files/samples_summary.json @@ -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 } } diff --git a/test_autofit/aggregator/summary_files/aggregate_summary/fit_2/files/samples_summary.json b/test_autofit/aggregator/summary_files/aggregate_summary/fit_2/files/samples_summary.json index c87d60c0c..c8a3c266a 100644 --- a/test_autofit/aggregator/summary_files/aggregate_summary/fit_2/files/samples_summary.json +++ b/test_autofit/aggregator/summary_files/aggregate_summary/fit_2/files/samples_summary.json @@ -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 } } diff --git a/test_autofit/aggregator/summary_files/test_aggregate_csv.py b/test_autofit/aggregator/summary_files/test_aggregate_csv.py index 3be6fbffd..cd98a5b38 100644 --- a/test_autofit/aggregator/summary_files/test_aggregate_csv.py +++ b/test_autofit/aggregator/summary_files/test_aggregate_csv.py @@ -1,8 +1,15 @@ import csv +import logging from pathlib import Path +import autofit as af +from autofit.example.model import Gaussian from autofit.aggregator.summary.aggregate_csv import AggregateCSV, ValueType +from autofit.aggregator.summary.aggregate_csv.column import Column +from autofit.aggregator.summary.aggregate_csv.row import Row +from autofit.non_linear.samples.sample import Sample +from autofit.non_linear.samples.summary import SamplesSummary import pytest @@ -62,8 +69,8 @@ def test_add_column( dicts = load_output() - assert dicts[0]["galaxies_lens_bulge_centre_centre_0"] == "-1.0" or "-5.0" - assert dicts[1]["galaxies_lens_bulge_centre_centre_0"] == "-5.0" or "-1.0" + assert dicts[0]["galaxies_lens_bulge_centre_centre_0"] == "-1.0" + assert dicts[1]["galaxies_lens_bulge_centre_centre_0"] == "-5.0" def test_use_max_log_likelihood( @@ -79,8 +86,8 @@ def test_use_max_log_likelihood( dicts = load_output() - assert dicts[0]["galaxies_lens_bulge_centre_centre_0_max_lh"] == "-1.0" or "-5.0" - assert dicts[1]["galaxies_lens_bulge_centre_centre_0_max_lh"] == "-5.0" or "-1.0" + assert dicts[0]["galaxies_lens_bulge_centre_centre_0_max_lh"] == "-1.5" + assert dicts[1]["galaxies_lens_bulge_centre_centre_0_max_lh"] == "-5.5" def test_add_named_column( @@ -96,8 +103,8 @@ def test_add_named_column( dicts = load_output() - assert dicts[0]["centre_0"] == "-1.0" or "-5.0" - assert dicts[1]["centre_0"] == "-5.0" or "-1.0" + assert dicts[0]["centre_0"] == "-1.0" + assert dicts[1]["centre_0"] == "-5.0" def test_add_latent_column( @@ -107,13 +114,16 @@ def test_add_latent_column( ): summary.add_variable( "latent.value", + value_types=[ValueType.Median, ValueType.MaxLogLikelihood], ) summary.save(output_path) dicts = load_output() - assert dicts[0]["latent_value"] == "1.0" or "2.0" - assert dicts[1]["latent_value"] == "2.0" or "1.0" + assert dicts[0]["latent_value"] == "1.0" + assert dicts[1]["latent_value"] == "2.0" + assert dicts[0]["latent_value_max_lh"] == "2.0" + assert dicts[1]["latent_value_max_lh"] == "3.0" def test_computed_column( @@ -220,3 +230,163 @@ def test_latent_values_at_1_sigma( assert ( first["galaxies_lens_bulge_centre_latent_lower_1_sigma"] == "3.4319440071038327" ) + + +def test_latent_values_at_3_sigma( + output_path, + summary, + load_output, +): + summary.add_variable( + "galaxies.lens.bulge.centre.latent", + value_types=[ValueType.ValuesAt1Sigma, ValueType.ValuesAt3Sigma], + ) + summary.save(output_path) + + dicts = load_output() + + first = dicts[0] + assert ( + first["galaxies_lens_bulge_centre_latent_lower_3_sigma"] == "1.6742483855526449" + ) + assert ( + first["galaxies_lens_bulge_centre_latent_upper_3_sigma"] == "5.93749816282317" + ) + assert ( + first["galaxies_lens_bulge_centre_latent_lower_3_sigma"] + != first["galaxies_lens_bulge_centre_latent_lower_1_sigma"] + ) + + +def test_max_log_likelihood_differs_from_median( + output_path, + summary, + load_output, +): + summary.add_variable( + "galaxies.lens.bulge.centre.centre_0", + value_types=[ValueType.Median, ValueType.MaxLogLikelihood], + ) + summary.save(output_path) + + dicts = load_output() + + assert dicts[0]["galaxies_lens_bulge_centre_centre_0"] == "-1.0" + assert dicts[1]["galaxies_lens_bulge_centre_centre_0"] == "-5.0" + assert dicts[0]["galaxies_lens_bulge_centre_centre_0_max_lh"] == "-1.5" + assert dicts[1]["galaxies_lens_bulge_centre_centre_0_max_lh"] == "-5.5" + + for row in dicts: + assert ( + row["galaxies_lens_bulge_centre_centre_0"] + != row["galaxies_lens_bulge_centre_centre_0_max_lh"] + ) + + +def test_unresolvable_argument_warns( + output_path, + summary, + load_output, + caplog, +): + summary.add_variable("does.not.exist") + + with caplog.at_level( + logging.WARNING, + logger="autofit.aggregator.summary.aggregate_csv.column", + ): + summary.save(output_path) + + records = [ + record for record in caplog.records if "does.not.exist" in record.getMessage() + ] + assert len(records) == 1 + + dicts = load_output() + + assert dicts[0]["does_not_exist"] == "" + assert dicts[1]["does_not_exist"] == "" + + +def test_resolvable_argument_does_not_warn( + output_path, + summary, + load_output, + caplog, +): + summary.add_variable("galaxies.lens.bulge.centre.centre_0") + + with caplog.at_level( + logging.WARNING, + logger="autofit.aggregator.summary.aggregate_csv.column", + ): + summary.save(output_path) + + assert caplog.records == [] + + +def test_unresolvable_argument_strict_raises( + output_path, + aggregator, +): + summary = AggregateCSV(aggregator, strict=True) + summary.add_variable("does.not.exist") + + with pytest.raises(KeyError, match="does.not.exist"): + summary.save(output_path) + + +class _NoPDFResult: + """ + A stand-in search output whose summary holds only a max_log_likelihood_sample, + as produced by a search without a PDF (no median sample, no sigma bounds). + """ + + id = "no_pdf" + + def __init__(self): + self.model = af.Model(Gaussian) + self.samples_summary = SamplesSummary( + model=self.model, + max_log_likelihood_sample=Sample( + log_likelihood=1.0, + log_prior=0.0, + weight=1.0, + kwargs={"centre": 0.5, "normalization": 2.0, "sigma": 3.0}, + ), + ) + + def value(self, name): + return None + + +def test_summary_without_pdf_does_not_raise(caplog): + row = Row(_NoPDFResult(), [], 0) + + assert row.known_paths == {("centre",), ("normalization",), ("sigma",)} + + column = Column( + "centre", + value_types=[ + ValueType.Median, + ValueType.MaxLogLikelihood, + ValueType.ValuesAt1Sigma, + ValueType.ValuesAt3Sigma, + ], + ) + + with caplog.at_level( + logging.WARNING, + logger="autofit.aggregator.summary.aggregate_csv.column", + ): + value = column.value(row) + + assert value == { + "": None, + "max_lh": 0.5, + "lower_1_sigma": None, + "upper_1_sigma": None, + "lower_3_sigma": None, + "upper_3_sigma": None, + } + assert caplog.records == []