diff --git a/GALLERY.md b/GALLERY.md index 7a49c2b..7fa3216 100644 --- a/GALLERY.md +++ b/GALLERY.md @@ -2,7 +2,7 @@ -Rendered with PyAutoLens `2026.8.17.1` · 97 figures. +Rendered with PyAutoLens `2026.8.17.1` · 106 figures. Most figures are outputs that the PyAutoLens visualizers (`VisualizerImaging`, `VisualizerInterferometer`, `VisualizerPoint`, `VisualizerWeak`) write to a model-fit's `image/` folder. Pandora shows 24 observed images across seven families with source-plane diagnostics from a fixed starting model. For the Simple cluster, the first point source is offset by 0.003 arcsec in y. See [README.md](README.md) for how to improve one. @@ -13,6 +13,9 @@ Most figures are outputs that the PyAutoLens visualizers (`VisualizerImaging`, ` - [top level](#cluster--visualization--top-level) - [point_0/](#cluster--visualization--point_0) - [point_1/](#cluster--visualization--point_1) +- [cluster_macs_j0416](#cluster_macs_j0416) + - [visualization](#cluster_macs_j0416--visualization) (9 figures) + - [top level](#cluster_macs_j0416--visualization--top-level) - [cluster_pandora](#cluster_pandora) - [visualization](#cluster_pandora--visualization) (11 figures) - [top level](#cluster_pandora--visualization--top-level) @@ -141,6 +144,48 @@ Most figures are outputs that the PyAutoLens visualizers (`VisualizerImaging`, ` ![point_solver](scripts/cluster/images/visualization/point_1/point_solver.png) +## cluster_macs_j0416 + +### cluster_macs_j0416 / visualization + +#### cluster_macs_j0416 / visualization / top level + +##### 210.4c_zoom + +![210.4c_zoom](scripts/cluster_macs_j0416/images/visualization/210.4c_zoom.png) + +##### all_back_traced_images + +![all_back_traced_images](scripts/cluster_macs_j0416/images/visualization/all_back_traced_images.png) + +##### overview + +![overview](scripts/cluster_macs_j0416/images/visualization/overview.png) + +##### published_101 + +![published_101](scripts/cluster_macs_j0416/images/visualization/published_101.png) + +##### published_14.1 + +![published_14.1](scripts/cluster_macs_j0416/images/visualization/published_14.1.png) + +##### ranking + +![ranking](scripts/cluster_macs_j0416/images/visualization/ranking.png) + +##### source_101 + +![source_101](scripts/cluster_macs_j0416/images/visualization/source_101.png) + +##### source_14.1 + +![source_14.1](scripts/cluster_macs_j0416/images/visualization/source_14.1.png) + +##### source_210.4 + +![source_210.4](scripts/cluster_macs_j0416/images/visualization/source_210.4.png) + ## cluster_pandora ### cluster_pandora / visualization diff --git a/README.md b/README.md index 48e4d1c..1752141 100644 --- a/README.md +++ b/README.md @@ -36,6 +36,7 @@ mirroring `autolens_workspace` (a variant gets its own folder): | `group` | `visualization.py` | `dataset.png` + `fit.png` | | `cluster` | `visualization.py` | Combined cluster figures and per-source figures, including `fit.png` (source-plane family fit), `fit_image_plane.png` and `point_solver.png` | | `cluster_pandora` | `visualization.py` | Four cluster overviews and seven source-plane family fits on the registered [Abell 2744 HST cutout](dataset/cluster/a2744/README.md) | +| `cluster_macs_j0416` | `visualization.py` | Nine [MACS J0416 family diagnostics](scripts/cluster_macs_j0416/README.md), including catalogue-labelled source-plane fits and published image-plane offsets | | `multi_dataset` | `visualization.py` | `dataset.png` + `fit.png` per band | | `weak` | `visualization.py` | `dataset.png` + `fit.png` | diff --git a/gallery/viz_manifest.yaml b/gallery/viz_manifest.yaml index c759376..0c4ae73 100644 --- a/gallery/viz_manifest.yaml +++ b/gallery/viz_manifest.yaml @@ -2,13 +2,13 @@ # the PyAutoEyes dashboard. Do not edit by hand: rerun # `bash gallery/gallery_run.sh --all` (or `python gallery/gallery_build.py`). schema: 1 -generated: '2026-11-24' +generated: '2026-11-25' rendered_with: autolens: 2026.8.17.1 autogalaxy: 2026.8.17.1 autoarray: 2026.8.17.1 autofit: 2026.8.17.1 -figure_count: 97 +figure_count: 106 figures: - file: scripts/cluster/images/visualization/dataset.png producer: scripts/cluster/visualization.py @@ -118,6 +118,60 @@ figures: source: point_1 bytes: 499370 sha256: 482ad6ee947511074f0573140c502557c615964c4b6651b8c27d9f8a1f2edc76 +- file: scripts/cluster_macs_j0416/images/visualization/210.4c_zoom.png + producer: scripts/cluster_macs_j0416/visualization.py + domain: cluster_macs_j0416 + source: '' + bytes: 35145 + sha256: e7d541f87ae5dd576bef4c376f3aacfbbef9dae9a3cbda92f2716ae900f4f36e +- file: scripts/cluster_macs_j0416/images/visualization/all_back_traced_images.png + producer: scripts/cluster_macs_j0416/visualization.py + domain: cluster_macs_j0416 + source: '' + bytes: 28212 + sha256: 54ea940b55b2757441377b8a53f3da11cd91a0ce6b9906d8f32188ac2244cbfc +- file: scripts/cluster_macs_j0416/images/visualization/overview.png + producer: scripts/cluster_macs_j0416/visualization.py + domain: cluster_macs_j0416 + source: '' + bytes: 383908 + sha256: 2a4ca482bff330f617764781da829ce4bf351b68b7b27614ffd95c98d6f58def +- file: scripts/cluster_macs_j0416/images/visualization/published_101.png + producer: scripts/cluster_macs_j0416/visualization.py + domain: cluster_macs_j0416 + source: '' + bytes: 368352 + sha256: e6aa1a688132b34d95417e23102af8c563cf2e72ea67435f2e1e5b50ae651011 +- file: scripts/cluster_macs_j0416/images/visualization/published_14.1.png + producer: scripts/cluster_macs_j0416/visualization.py + domain: cluster_macs_j0416 + source: '' + bytes: 422099 + sha256: 48f5510b1d14041e4ef2e036492d58eb6f527c59cb2c0fe56dab8c65e72d11a3 +- file: scripts/cluster_macs_j0416/images/visualization/ranking.png + producer: scripts/cluster_macs_j0416/visualization.py + domain: cluster_macs_j0416 + source: '' + bytes: 23285 + sha256: 6565c51e7a54552c8937f44f67f65e69e1c2e1e17853c2e9bda5aecffd453c45 +- file: scripts/cluster_macs_j0416/images/visualization/source_101.png + producer: scripts/cluster_macs_j0416/visualization.py + domain: cluster_macs_j0416 + source: '' + bytes: 331982 + sha256: 454049bc4e2f3a3dece25ccaf13fc24c5b5161ffa458a08ff58661335acf5ef7 +- file: scripts/cluster_macs_j0416/images/visualization/source_14.1.png + producer: scripts/cluster_macs_j0416/visualization.py + domain: cluster_macs_j0416 + source: '' + bytes: 448924 + sha256: dfa644d221ddbd0f8a7606813dd06ed7ccc5aa2a39ee3bd8f6403f0be67fbc55 +- file: scripts/cluster_macs_j0416/images/visualization/source_210.4.png + producer: scripts/cluster_macs_j0416/visualization.py + domain: cluster_macs_j0416 + source: '' + bytes: 319794 + sha256: 0ef32202e8f9b0d73b249771195cd683e0b4c07a0d4cc33b8f9dc490c8d3b5d5 - file: scripts/cluster_pandora/images/visualization/dataset.png producer: scripts/cluster_pandora/visualization.py domain: cluster_pandora diff --git a/scripts/cluster_macs_j0416/README.md b/scripts/cluster_macs_j0416/README.md new file mode 100644 index 0000000..fafffec --- /dev/null +++ b/scripts/cluster_macs_j0416/README.md @@ -0,0 +1,8 @@ +# MACS J0416 family fits + +Run `bash gallery/gallery_run.sh cluster_macs_j0416` from the gallery root. On first use the producer downloads the expanded mass model, multiple-image catalogue, residual table and HST F160W mosaic. It verifies their SHA-256 digests before rendering and caches the inputs in `output/macs_j0416_inputs/`. The source URLs and digests are recorded in [inputs.py](inputs.py). + +The field contains 237 observed images from 88 knot families. The model holds the 222 published dPIE mass components fixed and solves a source centre for each selected family. The catalogue uses arcsecond offsets increasing west and north from RA 64.038142°, Dec −24.067472°. Each HST cutout is sampled through the mosaic’s sky WCS. [Bergamini et al. (2023)](https://arxiv.org/abs/2208.14020) · [Published model](https://www.fe.infn.it/astro/lensing/M0416_Bergamini22/) · [Hubble Frontier Fields F160W, epoch 2](https://archive.stsci.edu/pub/hlsp/frontier/macs0416/images/hst/v1.0-epoch2/) + +- The three source-plane subplots follow the two images of family 210.4, the three images of 101, and the six images of 14.1. For 210.4 the overview, contribution ranking, 210.4c zoom and all back-traced images are also available individually. Image 210.4c contributes 9.49 of the family’s 11.70 source-plane χ². +- The two published-offset figures use the image matches and rounded residuals in `chires.dat`. The bars show separations in arcseconds. For family 101, image 101c has a 1.75″ offset and the family RMS is 1.08″. The lower-right panel shows the observed images back-traced by the fixed PyAutoLens model. Family 14.1 uses the same comparison for all six images. diff --git a/scripts/cluster_macs_j0416/images/visualization/210.4c_zoom.png b/scripts/cluster_macs_j0416/images/visualization/210.4c_zoom.png new file mode 100644 index 0000000..3a9cdff Binary files /dev/null and b/scripts/cluster_macs_j0416/images/visualization/210.4c_zoom.png differ diff --git a/scripts/cluster_macs_j0416/images/visualization/all_back_traced_images.png b/scripts/cluster_macs_j0416/images/visualization/all_back_traced_images.png new file mode 100644 index 0000000..a2631a0 Binary files /dev/null and b/scripts/cluster_macs_j0416/images/visualization/all_back_traced_images.png differ diff --git a/scripts/cluster_macs_j0416/images/visualization/overview.png b/scripts/cluster_macs_j0416/images/visualization/overview.png new file mode 100644 index 0000000..c501cbd Binary files /dev/null and b/scripts/cluster_macs_j0416/images/visualization/overview.png differ diff --git a/scripts/cluster_macs_j0416/images/visualization/published_101.png b/scripts/cluster_macs_j0416/images/visualization/published_101.png new file mode 100644 index 0000000..ef78efe Binary files /dev/null and b/scripts/cluster_macs_j0416/images/visualization/published_101.png differ diff --git a/scripts/cluster_macs_j0416/images/visualization/published_14.1.png b/scripts/cluster_macs_j0416/images/visualization/published_14.1.png new file mode 100644 index 0000000..d3e1339 Binary files /dev/null and b/scripts/cluster_macs_j0416/images/visualization/published_14.1.png differ diff --git a/scripts/cluster_macs_j0416/images/visualization/ranking.png b/scripts/cluster_macs_j0416/images/visualization/ranking.png new file mode 100644 index 0000000..a95a4f4 Binary files /dev/null and b/scripts/cluster_macs_j0416/images/visualization/ranking.png differ diff --git a/scripts/cluster_macs_j0416/images/visualization/source_101.png b/scripts/cluster_macs_j0416/images/visualization/source_101.png new file mode 100644 index 0000000..7ae675b Binary files /dev/null and b/scripts/cluster_macs_j0416/images/visualization/source_101.png differ diff --git a/scripts/cluster_macs_j0416/images/visualization/source_14.1.png b/scripts/cluster_macs_j0416/images/visualization/source_14.1.png new file mode 100644 index 0000000..064f05a Binary files /dev/null and b/scripts/cluster_macs_j0416/images/visualization/source_14.1.png differ diff --git a/scripts/cluster_macs_j0416/images/visualization/source_210.4.png b/scripts/cluster_macs_j0416/images/visualization/source_210.4.png new file mode 100644 index 0000000..ebdeed9 Binary files /dev/null and b/scripts/cluster_macs_j0416/images/visualization/source_210.4.png differ diff --git a/scripts/cluster_macs_j0416/inputs.py b/scripts/cluster_macs_j0416/inputs.py new file mode 100644 index 0000000..805cce1 --- /dev/null +++ b/scripts/cluster_macs_j0416/inputs.py @@ -0,0 +1,149 @@ +"""Pinned Lenstool catalogue and mass model, and HFF F160W sky registration.""" + +import hashlib +import re +import shutil +from collections import defaultdict +from pathlib import Path +from tempfile import NamedTemporaryFile +from urllib.request import urlopen + +import autolens as al +import numpy as np +from astropy.io import fits +from astropy.wcs import WCS +from scipy.ndimage import map_coordinates + +CACHE = Path(__file__).resolve().parents[2] / "output" / "macs_j0416_inputs" +BASE = "https://www.fe.infn.it/astro/lensing/M0416_Bergamini22/" +FITS = "hlsp_frontier_hst_wfc3-60mas_macs0416_f160w_v1.0-epoch2_drz.fits" +SOURCES = { + "best.par": ( + BASE + "best.par", + "16df3edf1ccc5a1edc17205fbdaacd2f36b37f91102124afea2e96b75c98041f", + ), + "obs_arcs.cat": ( + BASE + "obs_arcs.cat", + "bb70861cd29ab1b768755311375a633891d54cf2164207e54b7ad6d79732b60e", + ), + "chires.dat": ( + BASE + "chires.dat", + "0af67a6765ba3af324243886bc32d513cd3d3718e746bcb3728f41f572bb0d53", + ), + FITS: ( + "https://archive.stsci.edu/pub/hlsp/frontier/macs0416/images/hst/v1.0-epoch2/" + FITS, + "5c974843f9e66400000c724401249de0ef42f1a988eb199fd04abf697b3327b1", + ), +} +FIELD = (-52, 63, -77, 38) + + +def verified_input(name): + url, expected = SOURCES[name] + path = CACHE / name + + def verify(candidate): + with candidate.open("rb") as stream: + if hashlib.file_digest(stream, "sha256").hexdigest() != expected: + raise ValueError(f"Checksum mismatch for {name} from {url}") + + if path.exists(): + verify(path) + return path + CACHE.mkdir(exist_ok=True, parents=True) + with NamedTemporaryFile(dir=CACHE, delete=False) as f: + temporary = Path(f.name) + try: + with urlopen(url, timeout=120) as response, temporary.open("wb") as stream: + shutil.copyfileobj(response, stream) + verify(temporary) + temporary.replace(path) + finally: + temporary.unlink(missing_ok=True) + return path + + +def load_model(): + text = verified_input("best.par").read_text() + ra0, dec0 = map(float, re.search(r"reference\s+3\s+([\d.]+)\s+([-\d.]+)", text).groups()) + families = defaultdict(list) + for line in verified_input("obs_arcs.cat").read_text().splitlines(): + if not line.strip() or line.lstrip().startswith("#"): + continue + ident, ra, dec, a, b, _, z, _ = line.split() + m = re.fullmatch(r"(\d+(?:\.\d+)?)[a-z]", ident) + if not m or float(a) != float(b): + raise ValueError(f"Unexpected observed image: {line}") + y = (float(dec) - dec0) * 3600 + x = -(float(ra) - ra0) * np.cos(np.deg2rad(dec0)) * 3600 + families[m[1]].append((ident, y, x, float(a), float(z))) + zmax = max(rows[0][4] for rows in families.values()) + cosmology = dict(H0=70.0, Om0=0.3) + lenses = [] + for block in re.findall(r"potentiel\s+\S+\s*\n(.*?)\bend\b", text, re.S): + v = {row[0]: float(row[1]) for line in block.splitlines() if len(row := line.split()) == 2} + if v["profil"] != 81: + raise ValueError("Expected Lenstool dPIE profile 81") + z = v["z_lens"] + mass = al.mp.dPIEMass( + centre=(v["y_centre"], v["x_centre"]), + ellipticity=v["ellipticite"], + angle_pos=v["angle_pos"], + sigma=v["v_disp"], + r_core=v["core_radius"], + r_cut=v["cut_radius"], + redshift_object=z, + redshift_source=zmax, + **cosmology, + ) + lenses.append(al.Galaxy(redshift=z, mass=mass)) + datasets = {} + sources = [] + for name, rows in families.items(): + ids, y, x, sigma, z = zip(*rows, strict=True) + datasets[name] = al.PointDataset( + name=name, + positions=list(zip(y, x)), + positions_noise_map=list(sigma), + redshift=z[0], + image_ids=list(ids), + ) + sources.append(al.Galaxy(redshift=z[0], **{name: al.ps.PointSolved()})) + offsets = {} + for line in verified_input("chires.dat").read_text().splitlines(): + row = line.split() + if len(row) == 13 and row[0].isdigit() and row[3] == "1": + if row[1] in offsets: + raise ValueError(f"Duplicate residual for {row[1]}") + offsets[row[1]] = (float(row[11]), -float(row[10])) + ids = [i for ds in datasets.values() for i in ds.image_ids] + if (len(lenses), len(sources), len(ids)) != (222, 88, 237) or set(ids) != set(offsets): + raise ValueError("Unexpected coverage in MACS J0416 tables") + return ( + datasets, + al.Tracer(galaxies=lenses + sources, cosmology=al.cosmo.FlatLambdaCDM(**cosmology)), + offsets, + (ra0, dec0), + ) + + +class Mosaic: + def __init__(self, reference): + self.pixels, header = fits.getdata(verified_input(FITS), header=True) + self.wcs = WCS(header).celestial + self.ra, self.dec = reference + + def raster(self, bounds, step): + x0, x1, y0, y1 = bounds + ny, nx = int(np.ceil((y1 - y0) / step)), int(np.ceil((x1 - x0) / step)) + y, x = np.meshgrid( + y0 + (np.arange(ny) + 0.5) * (y1 - y0) / ny, + x0 + (np.arange(nx) + 0.5) * (x1 - x0) / nx, + indexing="ij", + ) + px, py = self.wcs.world_to_pixel_values( + self.ra - x / (3600 * np.cos(np.radians(self.dec))), self.dec + y / 3600 + ) + return map_coordinates( + self.pixels, [py, px], order=1, mode="constant", cval=np.nan, prefilter=False + ) diff --git a/scripts/cluster_macs_j0416/published_offsets.py b/scripts/cluster_macs_j0416/published_offsets.py new file mode 100644 index 0000000..2087f5d --- /dev/null +++ b/scripts/cluster_macs_j0416/published_offsets.py @@ -0,0 +1,293 @@ +"""Compare the released matched predictions with HST and the solved source plane.""" + +import matplotlib.pyplot as plt +import numpy as np +from autolens.point.plot.source_plane_panel import source_plane_data_from +from inputs import FIELD +from matplotlib import patheffects as pe +from matplotlib.lines import Line2D +from matplotlib.patches import Circle, Ellipse +from matplotlib.ticker import FormatStrFormatter, MaxNLocator + +dark = "#172b36" +amber = "#ffbd49" +cyan = "#5ee8fb" +STYLE = { + "font.size": 10, + "axes.titlesize": 12, + "axes.labelsize": 10, + "axes.spines.top": False, + "axes.spines.right": False, + "figure.facecolor": "white", + "savefig.facecolor": "white", + "axes.titleweight": "semibold", + "axes.labelcolor": dark, + "text.color": dark, + "axes.titlecolor": dark, +} + + +def sky_axes(ax): + ax.set_xlabel("x · west (″)") + ax.set_ylabel("y · north (″)") + ax.tick_params(labelsize=9) + + +def ellipse(ax, pos, c, color): + vals, vec = np.linalg.eigh(c[::-1, ::-1]) + direction = vec[:, -1] + ax.add_patch( + Ellipse( + pos[::-1], + width=2 * np.sqrt(vals[-1]), + height=2 * np.sqrt(vals[0]), + angle=np.rad2deg(np.arctan2(direction[1], direction[0])), + facecolor="none", + edgecolor=color, + lw=1, + alpha=0.8, + ) + ) + + +def centre(ax, c): + ax.scatter(c[1], c[0], marker="+", s=100, color="#965f15", lw=1.8, zorder=4) + + +def bounds_at(pos, r): + y, x = pos + return x - r, x + r, y - r, y + r + + +def published_offsets(fit, field_positions, residuals, mosaic, output): + """Use the released image matches and back-trace the observed positions with the fixed model.""" + name = fit.dataset.name + ids = np.asarray(fit.dataset.image_ids) + theta = np.asarray(fit.dataset.positions.array) + offset = np.asarray([residuals[ident] for ident in ids]) + dist = np.linalg.norm(offset, axis=1) + rms = np.sqrt(np.mean(dist**2)) + source_plane = source_plane_data_from(fit.positions) + beta, cov, sigma = source_plane.traced, source_plane.covariances, source_plane.sigma + c = source_plane.centre + base = mosaic.raster(FIELD, 0.09) + good = base[np.isfinite(base) & (base != 0)] + lo, hi = np.percentile(good, [2, 99.8]) + + def image(ax, bounds=FIELD): + pixels = base if bounds == FIELD else mosaic.raster(bounds, 0.06) + stretched = np.arcsinh(np.clip((pixels - lo) / (hi - lo), 0, 1) * 15) / np.arcsinh(15) + ax.imshow( + stretched, + extent=bounds, + origin="lower", + cmap="gray", + vmin=0, + vmax=1, + interpolation="nearest", + ) + ax.set(xlim=bounds[:2], ylim=bounds[2:], aspect="equal") + + markers = ["o", "s", "D", "^", "v", "P"] + count = len(ids) + cols = min(3, count) + rows = (count + cols - 1) // cols + side = 2.70 + tile = {2: 2.00, 3: 1.57}[cols] + gap = 0.31 + left = 0.69 + right = left + side + 0.63 + top_h = max(side, rows * tile + (rows - 1) * 0.42) + bot = 0.54 + summary_y = bot + top_y = bot + side + (0.94 if rows == 2 else 0.69) + top_end = top_y + top_h + width = right + max(cols * tile + (cols - 1) * gap, side + 1.43) + 0.22 + height = top_end + 0.82 + fig = plt.figure(figsize=(width, height)) + + def panel(x, y, w, h): + return fig.add_axes([x / width, y / height, w / width, h / height]) + + def words(x, y, content, **kwargs): + return fig.text(x / width, y / height, content, transform=fig.transFigure, **kwargs) + + words( + left - 0.08, + height - 0.08, + f"MACS J0416 | Family {name} · z = {fit.dataset.redshift:.3f}", + fontsize=17, + weight="semibold", + va="top", + ) + # Use the space beside the field for the image key, zooms and their true sky coordinates. + field = panel(left, top_y + top_h - side, side, side) + image(field) + sky_axes(field) + field.set_title("Cluster field", loc="left", pad=6) + field.scatter( + field_positions[:, 1], + field_positions[:, 0], + s=5, + facecolors="none", + edgecolors="0.77", + lw=0.48, + ) + field.scatter(theta[:, 1], theta[:, 0], s=59, facecolors="none", edgecolors=amber, lw=1.3) + used = [] + for j in range(count): + y, x = theta[j] + # Try nearby label positions before lengthening a leader in crowded families. + candidates = [ + (x + sx * dx, y + sy * dy) + for dx, dy in ((5, 4), (8, 7), (7, 12), (12, 7), (18, 12), (23, 16)) + for sx, sy in ((1, 1), (-1, 1), (1, -1), (-1, -1)) + ] + tx, ty = next( + ( + (u, v) + for u, v in candidates + if FIELD[0] + 8 < u < FIELD[1] - 8 + and FIELD[2] + 4 < v < FIELD[3] - 4 + and all(abs(u - a) > 17 or abs(v - b) > 7 for a, b in used) + and all(np.hypot(u - theta[k, 1], v - theta[k, 0]) > 2.4 for k in range(count)) + ), + candidates[-1], + ) + used.append((tx, ty)) + field.annotate( + str(ids[j]), + (x, y), + (tx, ty), + ha="center", + va="center", + color=amber, + fontsize=9, + bbox=dict(facecolor="#111", alpha=0.75, edgecolor="none", pad=0.5), + arrowprops=dict(arrowstyle="-", color=amber, lw=0.65), + ) + img_half = max(1.45, 1.40 * np.max(np.abs(offset)), 1.5 * sigma.max()) + stack = rows * tile + (rows - 1) * 0.42 + # One row leaves room for a marker key directly above it. + ztop = top_end - (top_h - stack) / 2 - (0.10 if rows == 1 else 0) + ztitle = ztop + 0.28 if rows == 1 else top_end + 0.23 + words(right, ztitle, "Image-plane zooms", fontsize=12, weight="semibold", va="bottom") + for j in range(count): + col = j % cols + row = j // cols + ax = panel(right + col * (tile + gap), ztop - (row + 1) * tile - row * 0.42, tile, tile) + image(ax, bounds_at(theta[j], img_half)) + ax.add_patch(Circle(theta[j, ::-1], sigma[j], fill=False, edgecolor=amber, lw=1.05, ls=":")) + ax.scatter( + theta[j, 1], theta[j, 0], marker="o", s=60, facecolors="none", edgecolors=amber, lw=1.65 + ) + pp = theta[j] + offset[j] + ax.plot( + pp[1], + pp[0], + marker="x", + ls="none", + ms=7, + color=cyan, + mew=1.65, + path_effects=[pe.withStroke(linewidth=3.3, foreground="#20333a")], + ) + ax.set_title(ids[j], fontsize=10, pad=4) + for axis in (ax.xaxis, ax.yaxis): + axis.set_major_locator(MaxNLocator(nbins=3)) + axis.set_major_formatter(FormatStrFormatter("%.1f")) + ax.tick_params(labelsize=8, pad=1) + # A real legend matches the marker colours on the photographic background. + handles = [ + Line2D([], [], marker="o", ls="none", mec=amber, mfc="none", mew=1.5, label="Observed"), + Line2D([], [], marker="x", ls="none", color=cyan, mew=1.6, label="Published prediction"), + Line2D([], [], ls=":", color=amber, label="1σ"), + ] + fig.legend( + handles=handles, + loc="upper center", + bbox_to_anchor=( + (right + (cols * tile + (cols - 1) * gap) / 2) / width, + (ztop - stack - 0.25) / height, + ), + ncol=3, + fontsize=8, + labelcolor="white", + handletextpad=0.4, + columnspacing=1.1, + facecolor="#24343a", + framealpha=1, + edgecolor="none", + ) + ax = panel(left, summary_y, side, side) + values = dist + order = np.argsort(-dist) + ax.barh(np.arange(count), values[order], height=0.53, color="#377e90") + ax.set_yticks(np.arange(count), ids[order]) + ax.invert_yaxis() + ax.tick_params(labelsize=9) + ax.set_xlim(0, values[order[0]] * 1.24) + ax.grid(axis="x", alpha=0.17) + ax.set_axisbelow(True) + for k, j in enumerate(order): + ax.text( + values[j] + 0.018 * values[order[0]], k, f"{values[j]:.2f}", va="center", fontsize=9 + ) + ax.set_xlabel("Observed–predicted separation (″)") + ax.set_title(f"Per-image offsets · RMS {rms:.2f}″", loc="left", fontsize=11, pad=6) + ax = panel(right, summary_y, side, side) + ax.set_facecolor("#f1f5f5") + err = np.sqrt(np.diagonal(cov, axis1=1, axis2=2)) + lows = np.minimum(np.min(beta - err, axis=0), c) + highs = np.maximum(np.max(beta + err, axis=0), c) + b = bounds_at((lows + highs) / 2, max(0.055, np.max(highs - lows) * 0.64)) + ax.set(xlim=b[:2], ylim=b[2:], aspect="equal") + keys = [] + for j in range(count): + ellipse(ax, beta[j], cov[j], "#438698") + (point,) = ax.plot( + beta[j, 1], + beta[j, 0], + marker=markers[j], + ls="none", + ms=6, + mew=0.6, + mec="white", + color="#14667b", + label=ids[j], + ) + keys.append(point) + centre(ax, c) + sky_axes(ax) + ax.set_title("All back-traced images", fontsize=13, loc="left", pad=7) + legend = panel(right + side + 0.08, summary_y + 0.04, width - right - side - 0.14, side - 0.08) + legend.axis("off") + keys.extend( + [ + Line2D( + [], + [], + marker="+", + ls="none", + color="#965f15", + ms=10, + mew=1.6, + label="Solved centre", + ), + Line2D([], [], color="#438698", lw=1, label="1σ ellipse"), + ] + ) + legend.legend( + handles=keys, + title="Source plane", + loc="center left", + frameon=False, + fontsize=9, + title_fontsize=10, + borderaxespad=0, + handlelength=1.3, + handletextpad=0.45, + labelspacing=0.56, + ) + fig.savefig(output, dpi=160, bbox_inches="tight", pad_inches=0.18) + plt.close(fig) diff --git a/scripts/cluster_macs_j0416/visualization.py b/scripts/cluster_macs_j0416/visualization.py new file mode 100644 index 0000000..f564a12 --- /dev/null +++ b/scripts/cluster_macs_j0416/visualization.py @@ -0,0 +1,66 @@ +"""MACS J0416 family fits and the Bergamini et al. published image-plane residuals.""" + +from pathlib import Path +from tempfile import TemporaryDirectory + +import autolens as al +import autolens.plot as aplt +import matplotlib.pyplot as plt +import numpy as np +from inputs import FIELD, Mosaic, load_model +from published_offsets import STYLE, published_offsets + + +def render(output): + datasets, tracer, offsets, reference = load_model() + mosaic = Mosaic(reference) + image = al.Array2D.no_mask( + values=mosaic.raster(FIELD, 0.1)[::-1], pixel_scales=0.1, origin=(-19.5, 5.5) + ) + positions = np.vstack([ds.positions.array for ds in datasets.values()]) + save = dict(output_path=str(output), output_format="png") + for name in ("210.4", "101", "14.1"): + fit = al.FitPointDataset( + dataset=datasets[name], + tracer=tracer, + solver=None, + fit_positions_cls=al.FitPositionsSourceSolved, + ) + aplt.subplot_fit_family( + fit, + image=image, + title_prefix="MACS J0416 | Family", + output_filename=f"source_{name}", + **save, + ) + if name == "210.4": + aplt.plot_family_overview(fit, image=image, output_filename="overview", **save) + aplt.plot_family_contributions(fit, output_filename="ranking", **save) + aplt.plot_family_image_detail( + fit, image_id="210.4c", output_filename="210.4c_zoom", **save + ) + aplt.plot_family_source_plane(fit, output_filename="all_back_traced_images", **save) + else: + with plt.rc_context(STYLE): + published_offsets(fit, positions, offsets, mosaic, output / f"published_{name}.png") + + +def main(): + output = Path(__file__).resolve().parent / "images" / "visualization" + output.mkdir(parents=True, exist_ok=True) + # A failed input download or model evaluation leaves the tracked figures intact. + with TemporaryDirectory(dir=output.parent) as temporary: + staging = Path(temporary) + render(staging) + figures = list(staging.glob("*.png")) + if len(figures) != 9: + raise RuntimeError(f"Expected nine MACS J0416 figures, rendered {len(figures)}") + stale = set(output.glob("*.png")) - {output / figure.name for figure in figures} + for figure in figures: + figure.replace(output / figure.name) + for figure in stale: + figure.unlink() + + +if __name__ == "__main__": + main()