diff --git a/autolens/point/dataset.py b/autolens/point/dataset.py index 6db80075b..a10c8f87c 100644 --- a/autolens/point/dataset.py +++ b/autolens/point/dataset.py @@ -47,6 +47,7 @@ def __init__( Union[float, aa.ArrayIrregular, List[float]] ] = None, redshift: Optional[float] = None, + image_ids: Optional[List[str]] = None, ): """ A collection of the data component that can be used for point-source model-fitting, for example fitting the @@ -85,6 +86,9 @@ def __init__( redshift The redshift of the source. Optional; when provided it is carried through CSV round-trips alongside the positions so cluster-scale workflows can encode per-source redshifts in a single spreadsheet. + image_ids + Catalogue identifiers in observed position order, unique within this family. Family fit + figures use these labels when supplied. The optional CSV column is ``image_id``. """ self.name = name @@ -96,6 +100,18 @@ def __init__( else aa.Grid2DIrregular(values=positions) ) + if image_ids is not None: + if isinstance(image_ids, str): + raise ValueError("Supply image_ids as a sequence of catalogue strings.") + image_ids = list(image_ids) + if len(image_ids) != len(self.positions) or not all( + isinstance(value, str) and value.strip() for value in image_ids + ): + raise ValueError("Supply one non-empty catalogue ID per observed position.") + if len(set(image_ids)) != len(image_ids): + raise ValueError("Catalogue image IDs must be unique within a family.") + self.image_ids = image_ids + # Ensure positions_noise_map is an ArrayIrregular if isinstance(positions_noise_map, float): positions_noise_map = [positions_noise_map] * len(self.positions) @@ -217,7 +233,7 @@ def output_to_csv(datasets: List[PointDataset], file_path: str): image. The base columns (``name, y, x, positions_noise``) are always written. The - optional ``flux``/``flux_noise``, ``time_delay``/``time_delay_noise`` and + optional ``image_id``, ``flux``/``flux_noise``, ``time_delay``/``time_delay_noise`` and ``redshift`` columns are included when *any* dataset in ``datasets`` carries those values; datasets that do not carry them leave those cells blank. @@ -233,6 +249,9 @@ def output_to_csv(datasets: List[PointDataset], file_path: str): include_redshift = any(d.redshift is not None for d in datasets) headers = list(_BASE_HEADERS) + include_ids = any(d.image_ids is not None for d in datasets) + if include_ids: + headers.append("image_id") if include_flux: headers += _FLUX_HEADERS if include_time_delay: @@ -256,6 +275,8 @@ def output_to_csv(datasets: List[PointDataset], file_path: str): "x": float(positions[i][1]), "positions_noise": positions_noise[i], } + if include_ids: + row["image_id"] = dataset.image_ids[i] if dataset.image_ids is not None else "" if include_flux: row["flux"] = "" if fluxes is None else fluxes[i] row["flux_noise"] = ( @@ -328,7 +349,7 @@ def list_from_csv(file_path: str) -> List[PointDataset]: Rows are grouped by their ``name`` column — one ``PointDataset`` per distinct name, preserving the order of first appearance. Optional per-image columns - (``flux``/``flux_noise``, ``time_delay``/``time_delay_noise``) are carried through + (``image_id``, ``flux``/``flux_noise``, ``time_delay``/``time_delay_noise``) are carried through per-group: if every row in a group populates the column the values are loaded, if every row leaves it blank the corresponding attribute is set to ``None``, and any partial-population is rejected with a ``ValueError``. @@ -394,6 +415,7 @@ def list_from_csv(file_path: str) -> List[PointDataset]: else None ) + ids = [row.get("image_id", "") for row in group_rows] datasets.append( PointDataset( name=name, @@ -404,6 +426,7 @@ def list_from_csv(file_path: str) -> List[PointDataset]: time_delays=time_delays, time_delays_noise_map=time_delays_noise_map, redshift=redshift, + image_ids=ids if any(ids) else None, ) ) diff --git a/autolens/point/plot/family_fit_plots.py b/autolens/point/plot/family_fit_plots.py index f8e548daf..a91bd9032 100644 --- a/autolens/point/plot/family_fit_plots.py +++ b/autolens/point/plot/family_fit_plots.py @@ -76,6 +76,16 @@ def from_record(cls, record, by_redshift=False): ), ) + @property + def labels(self): + ids = self.record.fit.dataset.image_ids + return self.record.numbers if ids is None else np.asarray(ids) + + def image_title(self, index): + if self.record.fit.dataset.image_ids is None: + return f"Image {self.record.numbers[index]}" + return self.record.fit.dataset.image_ids[index] + @property def ranked(self): return np.lexsort((self.record.numbers, -self.terms)) @@ -103,8 +113,16 @@ def _numbers(ax, positions, numbers, colors): width, height, scale = pp._panel_size_points(ax, extent) markers = (positions[:, ::-1] - [extent[0], extent[2]]) * scale labels = [str(n) for n in numbers] + # Longer catalogue IDs may need a leader in a crowded cluster core. + placements = pp.NUMBER_PLACEMENTS + if numbers.dtype.kind in ("U", "O"): + placements += tuple( + (dx * radius, dy * radius, ha, va) + for radius in (2, 3, 4) + for dx, dy, ha, va in pp.NUMBER_PLACEMENTS + ) offsets = pp.adjacent_number_placements_from( - markers, labels, width, height, fontsize=9 + markers, labels, width, height, fontsize=9, placements_to_try=placements ) for (y, x), number, color, (dx, dy, ha, va) in zip( positions, labels, colors, offsets @@ -114,6 +132,11 @@ def _numbers(ax, positions, numbers, colors): (x, y), xytext=(dx, dy), textcoords="offset points", + arrowprops=( + dict(arrowstyle="-", color=color, lw=0.7, shrinkB=4) + if (dx, dy, ha, va) not in pp.NUMBER_PLACEMENTS + else None + ), ha=ha, va=va, color=color, @@ -160,7 +183,7 @@ def _overview(ax, families, family, image, indices): if other is family: colors = np.full(len(y), "#9ba5ae", dtype=object) colors[indices] = color - _numbers(ax, record.observed, record.numbers, colors) + _numbers(ax, record.observed, family.labels, colors) ax.set_title("Cluster fit overview", weight="bold") ax.legend( loc="best", @@ -174,7 +197,7 @@ def _overview(ax, families, family, image, indices): def _ranking(ax, family, highlight): order = family.ranked values = family.terms[order].tolist() - labels = [f"Image {family.record.numbers[i]}" for i in order] + labels = [family.image_title(i) for i in order] colors = [family.ink if i in highlight else "#c4cfd6" for i in order] if family.penalty: values.append(family.penalty) @@ -235,8 +258,8 @@ def _source_plane(ax, family, highlight): colors[highlight] = family.ink ax.scatter(*source.traced.T[::-1], c=colors, s=28) ax.scatter(*source.centre[::-1], marker="+", s=96, color="#172f49") - _numbers(ax, source.traced, rec.numbers, colors) - ax.set_title("All images in the source plane", weight="bold") + _numbers(ax, source.traced, family.labels, colors) + ax.set_title("All back-traced images", weight="bold") def _zoom_half_width(family): @@ -253,20 +276,19 @@ def _zoom_half_width(family): def _image_detail(ax, family, i, half): - rec = family.record if not np.isfinite(family.data[i]).all(): ax.set_axis_off() ax.text( 0.5, 0.5, - f"Image {rec.numbers[i]}\nPosition unavailable", + f"{family.image_title(i)}\nPosition unavailable", transform=ax.transAxes, ha="center", ) return angular_axes(ax, family.data[i], half, small=True) _detail(ax, family, i) - ax.set_title(f"Image {rec.numbers[i]}", size=10, weight="bold") + ax.set_title(family.image_title(i), size=10, weight="bold") def _detail_key(family): @@ -322,7 +344,7 @@ def _shared_detail(ax, family, indices): s=36, label="Unpaired model", ) - _numbers(ax, family.data, rec.numbers, [family.ink] * len(indices)) + _numbers(ax, family.data, family.labels, [family.ink] * len(indices)) ax.set_title( ( "Source-plane detail" @@ -340,8 +362,10 @@ def _page(families, family, image, indices, page, pages, shared, title_prefix): source = family.source plane = "Source" if source.presentation.is_source_plane else "Image" # More ranking rows need extra space, including on subsequent pages. - height = 11.2 + max(0, len(rec.numbers) - 8) * 0.25 - fig = plt.figure(figsize=(16.2, height)) + height = (8.1 if len(rec.numbers) <= 3 else 10.0) + max( + 0, len(rec.numbers) - 8 + ) * 0.25 + fig = plt.figure(figsize=(14.0, height)) title = f"{rec.name} / {plane}-plane fit" fig.text( 0.08, @@ -366,6 +390,7 @@ def _page(families, family, image, indices, page, pages, shared, title_prefix): fig.text(0.55, 0.025, "+ fitted source centre", fontsize=10) half = _zoom_half_width(family) + legend_y = 0.383 if shared: ax = fig.add_axes([0.55, 0.475, 0.383, 0.36]) _shared_detail(ax, family, indices) @@ -381,19 +406,29 @@ def _page(families, family, image, indices, page, pages, shared, title_prefix): right=0.96, bottom=0.475, top=0.837, - wspace=0.5, - hspace=0.74, + wspace=0.22, + hspace=0.42, ) - fig.text(0.54, 0.881, f"{plane}-plane detail by image", size=14, weight="bold") + tiles = [] for slot, i in enumerate(indices): ax = fig.add_subplot(grid[slot // columns, slot % columns]) _image_detail(ax, family, i, half) + tiles.append(ax.get_position()) + # Anchor the heading and key to the square tiles even when the grid has spare height. + fig.text( + tiles[0].x0, + tiles[0].y1 + 0.37 / height, + f"{plane}-plane detail by image", + size=14, + weight="bold", + ) + legend_y = min(tile.y0 for tile in tiles) - 0.42 / height keys, labels = _detail_key(family) fig.legend( keys, labels, - loc="lower center", - bbox_to_anchor=(0.745, 0.383), + loc="upper center" if not shared else "lower center", + bbox_to_anchor=(0.745, legend_y), ncol=3, frameon=False, fontsize=9, @@ -453,7 +488,11 @@ def _subplot( output_format, title_prefix, ): - order = np.argsort(family.record.numbers) + order = ( + np.argsort(family.record.numbers) + if family.record.fit.dataset.image_ids is None + else np.arange(len(family.record.numbers)) + ) pages = ( [order] if single_panel or len(order) <= 6 @@ -553,6 +592,7 @@ def plot_family_image_detail( fit, image_number=None, *, + image_id=None, fits=None, ax=None, output_path=None, @@ -564,11 +604,18 @@ def plot_family_image_detail( For a source-plane fit compare the back-traced position and source centre. For an image-plane fit compare the observed and predicted positions. Each numbered zoom uses the same angular scale as the others in this family. - Omit image_number to show all images and predictions on shared axes. + Pass image_id to select by catalogue identifier, or omit both selectors for shared axes. Optional fits preserves the cluster's colours. Supply ax to compose a figure. """ family, _ = _select_family(fit, fits) numbers = family.record.numbers + if image_id is not None: + if image_number is not None: + raise ValueError("Choose either image_id or image_number.") + ids = fit.dataset.image_ids + if ids is None or image_id not in ids: + raise ValueError(f"Unknown image ID {image_id!r} for {fit.dataset.name}.") + image_number = numbers[ids.index(image_id)] if image_number is not None: matches = np.flatnonzero(numbers == image_number) if len(matches) != 1: @@ -597,7 +644,7 @@ def plot_family_source_plane( ): """Show every observed image of one family back-traced to its source plane. - Works for both source- and image-plane positions likelihoods. Numbers match + Works for both source- and image-plane positions likelihoods. Image labels match the overview and contributions. The plus marks the fitted source centre. Optional fits preserves the cluster's colours. Supply ax to compose a figure. """ diff --git a/autolens/point/plot/positions_panel.py b/autolens/point/plot/positions_panel.py index 4c8b1b80b..c25fe80d0 100644 --- a/autolens/point/plot/positions_panel.py +++ b/autolens/point/plot/positions_panel.py @@ -475,13 +475,15 @@ def adjacent_number_placements_from( width: float, height: float, fontsize: float, + *, + placements_to_try=NUMBER_PLACEMENTS, ) -> List[Tuple[float, float, str, str]]: """ Returns, for each of the first ``len(labels)`` markers, the ``(dx, dy, ha, va)`` offset (points) of its label. Each label sits a few points off its own marker (one of ``NUMBER_PLACEMENTS``): the first placement which stays inside the panel and overlaps neither another marker nor an already-placed label, else the one overlapping - least. A label is therefore never moved away from its marker to find space. + least. Catalogue plots can supply further offsets for crowded labels. Parameters ---------- @@ -502,7 +504,7 @@ def adjacent_number_placements_from( text_height = fontsize + 2.0 others = np.delete(markers, index, axis=0) best, best_score, best_box = NUMBER_PLACEMENTS[0], np.inf, None - for dx, dy, ha, va in NUMBER_PLACEMENTS: + for dx, dy, ha, va in placements_to_try: x0 = x + dx - (text_width if ha == "right" else 0.0) y0 = y + dy - (text_height if va == "top" else 0.0) box = (x0, y0, x0 + text_width, y0 + text_height) diff --git a/test_autolens/point/plot/test_multi_source_plots.py b/test_autolens/point/plot/test_multi_source_plots.py index 1c31eb59e..3d69db242 100644 --- a/test_autolens/point/plot/test_multi_source_plots.py +++ b/test_autolens/point/plot/test_multi_source_plots.py @@ -617,7 +617,7 @@ def test__plot_family_fits__one_shared_detail_panel( axes = {ax.get_title(): ax for ax in fig.axes} assert "Cluster fit overview" in axes ranking = axes["Per-image contribution"].get_window_extent() - source_plane = axes["All images in the source plane"].get_window_extent() + source_plane = axes["All back-traced images"].get_window_extent() assert (ranking.width, ranking.height) == pytest.approx( (source_plane.width, source_plane.height) ) @@ -793,3 +793,28 @@ def test__family_panels_use_tracer_redshifts_for_older_datasets(cluster, monkeyp selected, _ = _select_family(high_z, fits) combined, _ = _select_family(high_z, fits, overview=True) assert selected.ink == combined.ink + + +@pytest.mark.parametrize("likelihood", ["FitPositionsSource", "FitPositionsImagePair"]) +def test__catalogue_ids_follow_positions_across_all_panels( + cluster, family_figures, tmp_path, monkeypatch, likelihood +): + import autolens.plot as aplt + + fit = cluster.fits[likelihood][0] + ids = [f"101{chr(97+i)}" for i in range(len(fit.dataset.positions))] + monkeypatch.setattr(fit.dataset, "image_ids", ids) + output = dict(output_path=tmp_path, output_format="png") + aplt.subplot_fit_family(fit, **output) + axes = {ax.get_title(): ax for ax in family_figures[tmp_path / "fit_family.png"].axes} + for name in ["Cluster fit overview", "All back-traced images"]: + assert [t.get_text() for t in axes[name].texts] == ids + assert {t.get_text() for t in axes["Per-image contribution"].get_yticklabels()} >= set(ids) + assert set(ids) <= axes.keys() + + aplt.plot_family_image_detail(fit, image_id=ids[-1], **output) + zoom = family_figures[tmp_path / "family_image_detail.png"].axes[0] + assert zoom.get_title() == ids[-1] + np.testing.assert_allclose(zoom.get_xlim(), axes[ids[-1]].get_xlim()) + with pytest.raises(ValueError, match="Unknown image ID"): + aplt.plot_family_image_detail(fit, image_id="missing") diff --git a/test_autolens/point/test_dataset.py b/test_autolens/point/test_dataset.py index cf3ab24bd..d43096a1f 100644 --- a/test_autolens/point/test_dataset.py +++ b/test_autolens/point/test_dataset.py @@ -222,3 +222,17 @@ def test__from_csv__multiple_groups_requires_name(tmp_path): picked = al.PointDataset.from_csv(file_path, name="source_1") assert picked.name == "source_1" + + +def test__catalogue_image_ids_round_trip_with_unlabelled_family(tmp_path): + positions = [(0, 1), (2, 3)] + named = al.PointDataset("A", positions, 0.1, image_ids=["001b", "001a"]) + plain = al.PointDataset("B", positions, 0.1) + path = tmp_path / "positions.csv" + al.output_to_csv([named, plain], path) + a, b = al.list_from_csv(path) + assert a.image_ids == ["001b", "001a"] + assert b.image_ids is None + for ids in [["001a"], ["001a", ""], ["001a", "001a"]]: + with pytest.raises(ValueError): + al.PointDataset("A", positions, 0.1, image_ids=ids)