From 80abfcdca0e92c292b3874b48091c54ebe342f6f Mon Sep 17 00:00:00 2001 From: Cail Daley Date: Sat, 21 Nov 2026 21:38:23 -0500 Subject: [PATCH 1/3] feat(psf): colour-dependent PSFEx model with colour-purified stars The r-band PSF is chromatic: at fixed magnitude, star size falls by 0.69% per magnitude of g-i, and the achromatic per-CCD PSFEx model cannot follow it. This fits PSFEx linear in g-i (PSFVAR_KEYS XWIN_IMAGE,YWIN_IMAGE,GI_COLOR; groups 1,1,2; degrees 2,1; 12 terms), the form DES Y6 fits with Piff. - star_colour_runner (new, between setools and psfex): matches each PSF star to an external per-object catalogue ($SP_STAR_COLOURS: RA, DEC, GI, REMOVE) within 0.5", drops training stars the purity verdict rejects, and adds GI_COLOR to the training and reserve splits (CCD median where no colour). The reserve is kept whole so it stays comparable with an achromatic run. - psfex_interp: the coefficient build enumerates PSFEx's terms for any context (psfex_monomials), so it reads 2-D and 3-D models alike. Objects are evaluated at their GI_COLOR when the catalogue has one (reserve stars), else at DEFAULT_COLOUR (galaxies; 1.1, DES Y6's median galaxy colour). - astra.yaml: psf_model_complexity selects the colour model; new decision psf_colour_purification. --- astra.yaml | 69 +++++++++--- .../psfex_interp_package/psfex_interp.py | 105 ++++++++++++------ src/shapepipe/modules/psfex_interp_runner.py | 10 ++ .../modules/star_colour_package/__init__.py | 10 ++ .../star_colour_package/star_colour.py | 77 +++++++++++++ src/shapepipe/modules/star_colour_runner.py | 51 +++++++++ universes/committed.yaml | 3 +- workflow/config/cfis/config_exp_psfex.ini | 27 ++++- .../config/cfis/config_tile_PiViVi_psfex.ini | 5 + workflow/config/cfis/default.psfex | 6 +- workflow/scripts/completeness.py | 1 + 11 files changed, 311 insertions(+), 53 deletions(-) create mode 100644 src/shapepipe/modules/star_colour_package/__init__.py create mode 100644 src/shapepipe/modules/star_colour_package/star_colour.py create mode 100644 src/shapepipe/modules/star_colour_runner.py diff --git a/astra.yaml b/astra.yaml index e336ef639..84b85f925 100644 --- a/astra.yaml +++ b/astra.yaml @@ -1005,7 +1005,8 @@ analyses: decisions: [star_selection_box, psf_train_validation_split, psfex_candidate_vetting, psf_modelling_software, - psf_model_complexity, psf_acceptance_thresholds] + psf_model_complexity, psf_colour_purification, + psf_acceptance_thresholds] decisions: star_selection_box: label: Stellar-locus selection, magnitude window and FWHM window scaled to the locus @@ -1183,35 +1184,69 @@ analyses: persistence and star-catalogue merging read MCCD products. insights: [farrens22_two_psf_methods] psf_model_complexity: - label: PSFEx pixel basis with degree-2 spatial variation per CCD + label: PSFEx pixel basis, degree 2 in position times linear in g−i, per CCD rationale: >- - A pixel basis with polynomial variation in XWIN/YWIN, fit per CCD - at native sampling. PSF_ACCURACY is the fractional accuracy PSFEx - assumes for PSF pixel values; per the PSFEx documentation it enters - the fit weights, and so how closely the model follows bright stars. - Model flexibility trades overfitting against PSF leakage, the - dominant additive systematic in cosmic shear. A more flexible model - must be supported by the surviving training stars and checked on - held-out residuals under the acceptance gate; successful optimisation - alone does not establish a usable PSF. - Stock values; no rationale recorded. + A pixel basis with polynomial variation in XWIN/YWIN and in the + star's g−i, fit per CCD at native sampling: PSFEx multiplies the + degree-2 position polynomial by a degree-1 colour polynomial (12 + terms), the form DES Y6 fits with Piff (Schutt et al. 2025). The + r-band PSF is chromatic: at fixed magnitude, star size falls by + 0.69% per magnitude of g−i, and an achromatic model cannot follow + it (pando unions/star-selection-as-close-to-des). Training stars + carry GI_COLOR from star_colour_runner; galaxies are evaluated at + the default colour of psf_colour_purification. + PSF_ACCURACY is the fractional accuracy PSFEx assumes for PSF pixel + values; per the PSFEx documentation it enters the fit weights, and + so how closely the model follows bright stars. Model flexibility + trades overfitting against PSF leakage, the dominant additive + systematic in cosmic shear. A more flexible model must be supported + by the surviving training stars and checked on held-out residuals + under the acceptance gate; successful optimisation alone does not + establish a usable PSF. Values: BASIS_TYPE = PIXEL; PSF_ACCURACY = 0.01; BASIS_NUMBER = 20; - PSFVAR_DEGREES = 2; + PSFVAR_DEGREES = 2,1; PSF_SAMPLING = 1; - PSFVAR_KEYS = XWIN_IMAGE,YWIN_IMAGE; - PSFVAR_GROUPS = 1,1; + PSFVAR_KEYS = XWIN_IMAGE,YWIN_IMAGE,GI_COLOR; + PSFVAR_GROUPS = 1,1,2; MEF_TYPE = INDEPENDENT. - default: pixel_basis_deg2_per_ccd + default: pixel_basis_deg2_gi1_per_ccd options: + pixel_basis_deg2_gi1_per_ccd: + label: PIXEL basis, degree 2 in position times degree 1 in g−i, per CCD pixel_basis_deg2_per_ccd: - label: PIXEL basis, degree 2, per CCD + label: PIXEL basis, degree 2, per CCD, achromatic insights: [guinot22_psf_no_oversampling] deg3: label: Degree-3 spatial variation description: Needs more stars per CCD than the acceptance gate guarantees. + psf_colour_purification: + label: External g−i and purity verdict for PSF stars; galaxies at g−i = 1.1 + rationale: >- + Each PSF star is matched within MATCH_RADIUS to an external + per-object catalogue (SP_STAR_COLOURS: dereddened PhotoPipe GAaP + g−i and a purity verdict from a Gaia-seeded stellar locus with + unWISE W1). Training stars the verdict rejects (off the locus in + i−W1, Gaia-extended, or g−i outside [0, 3.5]) are dropped, as DES + Y6 drops non-stellar Gaia matches; the 20% reserve is kept whole so + its residuals compare with an achromatic run. Stars without g−i get + their CCD's median. Galaxies are evaluated at DEFAULT_COLOUR, DES + Y6's median galaxy colour, which its image simulations show costs + Δm = (0.04 ± 2.0)×10⁻³ against per-galaxy colours (Yamamoto et al. + 2025). + Values: + config_exp_psfex.ini#STAR_COLOUR_RUNNER.MATCH_RADIUS = 0.5; + config_exp_psfex.ini#PSFEX_INTERP_RUNNER.DEFAULT_COLOUR = 1.1; + config_tile_PiViVi_psfex.ini#PSFEX_INTERP_RUNNER.DEFAULT_COLOUR = 1.1. + default: purify_and_colour + options: + purify_and_colour: + label: Drop rejected training stars, colour every star, galaxies at 1.1 + per_galaxy_colour: + label: Evaluate each galaxy at its own g−i + description: Needs PhotoPipe colours in the tile chain; DES found no measurable gain. psf_acceptance_thresholds: label: Per-CCD PSF-model quality gate rationale: >- diff --git a/src/shapepipe/modules/psfex_interp_package/psfex_interp.py b/src/shapepipe/modules/psfex_interp_package/psfex_interp.py index 5e7877c9c..05138d694 100644 --- a/src/shapepipe/modules/psfex_interp_package/psfex_interp.py +++ b/src/shapepipe/modules/psfex_interp_package/psfex_interp.py @@ -235,6 +235,44 @@ def _hsm_columns(shapes, obj): return out +def psfex_monomials(groups, degrees): + """Exponents of PSFEx's polynomial terms, in its basis order. + + PSFEx enumerates terms as an odometer over the context dimensions in + ``PSFVAR_KEYS`` order: the first dimension's exponent is raised while its + group's degree budget allows, otherwise it is reset to zero and the next + dimension is raised. For one group of (x, y) at degree 2 this is + 1, x, x², y, xy, y². + + Parameters + ---------- + groups : list of int + 1-based group of each context dimension (``POLGRPn``) + degrees : list of int + Degree of each group (``POLDEGn``) + + Returns + ------- + numpy.ndarray + ``(n_terms, n_dim)`` exponents + + """ + budget = list(degrees) + expo = [0] * len(groups) + terms = [tuple(expo)] + while True: + for dim, grp in enumerate(groups): + if budget[grp - 1] > 0: + expo[dim] += 1 + budget[grp - 1] -= 1 + break + budget[grp - 1] += expo[dim] + expo[dim] = 0 + else: + return np.array(terms) + terms.append(tuple(expo)) + + class PSFExInterpolator(object): """The PSFEx Interpolator Class. @@ -277,6 +315,7 @@ def __init__( get_shapes=True, star_thresh=20, chi2_thresh=2, + default_colour=None, ): # Path to PSFEx output file @@ -303,6 +342,10 @@ def __init__( self._chi2_thresh = chi2_thresh + # Colour at which a colour-dependent model is evaluated for objects + # whose catalogue carries no GI_COLOR (galaxies) + self._default_colour = default_colour + # Logging self._w_log = w_log @@ -318,6 +361,7 @@ def __init__( else: self._pos_params = None self.gal_pos = None + self.gal_colour = None self.interp_PSFs = None self._img_number = img_number @@ -392,6 +436,8 @@ def _get_galaxy_positions(self): ) ] ) + if "GI_COLOR" in galcat.get_data().dtype.names: + self.gal_colour = np.array(galcat.get_data()["GI_COLOR"]) self._w_log.info( f"Read {self.gal_pos.shape[0]} positions from galaxy catalog" ) @@ -408,7 +454,7 @@ def _get_galaxy_positions(self): raise KeyError(pos_param_err) galcat.close() - def interpsfex(self, dotpsfpath, pos): + def interpsfex(self, dotpsfpath, pos, colour=None): """Interpolate PSFEx. Use PSFEx generated model to perform spatial PSF interpolation. @@ -424,6 +470,9 @@ def interpsfex(self, dotpsfpath, pos): Path to ``.psf`` file (PSFEx output) pos : numpy.ndarray Positions where the PSF model should be evaluated + colour : numpy.ndarray, optional + Colour of each object, for a model with a colour context + (``PSFVAR_KEYS`` beyond position); defaults to ``default_colour`` Returns ------- @@ -454,42 +503,35 @@ def interpsfex(self, dotpsfpath, pos): return BAD_CHI2 PSF_basis = np.array(PSF_model.data)[0][0] - try: - deg = PSF_model.header["POLDEG1"] - except KeyError: + hdr = PSF_model.header + n_dim = hdr.get("POLNAXIS", 0) + if n_dim == 0: # constant PSF model return PSF_basis[0, :, :] - # scale coordinates - x_interp, x_scale = ( - PSF_model.header["POLZERO1"], - PSF_model.header["POLSCAL1"], - ) - y_interp, y_scale = ( - PSF_model.header["POLZERO2"], - PSF_model.header["POLSCAL2"], - ) - xs, ys = (pos[:, 0] - x_interp) / x_scale, ( - pos[:, 1] - y_interp - ) / y_scale - - # compute polynomial coefficients - coeffs = np.array([[x**idx for idx in range(deg + 1)] for x in xs]) - cross_coeffs = np.array( + # context per object: position, then any further PSFVAR_KEYS (a + # colour is evaluated at each object's value, or at the configured + # default colour where the catalogue has none) + context = [pos[:, 0], pos[:, 1]] + for idx in range(2, n_dim): + if colour is None: + if self._default_colour is None: + raise ValueError( + f"{dotpsfpath} has a colour context; set DEFAULT_COLOUR" + ) + colour = np.full(len(pos), self._default_colour) + context.append(np.asarray(colour, dtype=float)) + context = np.column_stack( [ - np.concatenate( - [ - [ - (x**idx_j) * (y**idx_i) - for idx_j in range(deg - idx_i + 1) - ] - for idx_i in range(1, deg + 1) - ] - ) - for x, y in zip(xs, ys) + (context[idx] - hdr[f"POLZERO{idx + 1}"]) / hdr[f"POLSCAL{idx + 1}"] + for idx in range(n_dim) ] ) - coeffs = np.hstack((coeffs, cross_coeffs)) + expo = psfex_monomials( + [hdr[f"POLGRP{idx + 1}"] for idx in range(n_dim)], + [hdr[f"POLDEG{grp + 1}"] for grp in range(hdr["POLNGRP"])], + ) + coeffs = np.prod(context[:, None, :] ** expo[None], axis=2) # compute interpolated PSF PSFs = np.array( @@ -517,6 +559,7 @@ def _interpolate(self): self.interp_PSFs = self.interpsfex( self._dotpsf_path, self.gal_pos, + self.gal_colour, ) def _get_psfshapes(self, wcs_list=None): diff --git a/src/shapepipe/modules/psfex_interp_runner.py b/src/shapepipe/modules/psfex_interp_runner.py index 5627d5d20..01d902964 100644 --- a/src/shapepipe/modules/psfex_interp_runner.py +++ b/src/shapepipe/modules/psfex_interp_runner.py @@ -35,6 +35,13 @@ def psfex_interp_runner( get_shapes = config.getboolean(module_config_sec, "GET_SHAPES") star_thresh = config.getint(module_config_sec, "STAR_THRESH") chi2_thresh = config.getint(module_config_sec, "CHI2_THRESH") + # Colour at which a colour-dependent PSF model is evaluated for objects + # without their own (galaxies); needed only for such a model + default_colour = ( + config.getfloat(module_config_sec, "DEFAULT_COLOUR") + if config.has_option(module_config_sec, "DEFAULT_COLOUR") + else None + ) # Run in CLASSIC mode if mode == "CLASSIC": @@ -53,6 +60,7 @@ def psfex_interp_runner( get_shapes, star_thresh, chi2_thresh, + default_colour, ) # Process inputs @@ -104,6 +112,7 @@ def psfex_interp_runner( get_shapes, star_thresh, chi2_thresh, + default_colour, ) # Process inputs multi-epoch @@ -126,6 +135,7 @@ def psfex_interp_runner( get_shapes, star_thresh, chi2_thresh, + default_colour, ) # Process inputs validation diff --git a/src/shapepipe/modules/star_colour_package/__init__.py b/src/shapepipe/modules/star_colour_package/__init__.py new file mode 100644 index 000000000..89c7c09c2 --- /dev/null +++ b/src/shapepipe/modules/star_colour_package/__init__.py @@ -0,0 +1,10 @@ +"""STAR COLOUR PACKAGE. + +Attach an external colour to PSF stars and drop the ones an external purity +verdict rejects, before the PSF fit. + +:Author: Claude (Opus 5.5) for Cail Daley + +""" + +__all__ = ["star_colour"] diff --git a/src/shapepipe/modules/star_colour_package/star_colour.py b/src/shapepipe/modules/star_colour_package/star_colour.py new file mode 100644 index 000000000..ddcc8fc55 --- /dev/null +++ b/src/shapepipe/modules/star_colour_package/star_colour.py @@ -0,0 +1,77 @@ +"""STAR COLOUR. + +Attach an external colour to each PSF star and drop stars an external purity +verdict rejects, between star selection and the PSF fit. + +The external catalogue is a FITS table with one row per object: world +coordinates, a colour (g−i), and a boolean rejection flag. Each star in the +training and reserve splits is matched to its nearest catalogue object within +the match radius. Training stars whose match is flagged are dropped; the +reserve is kept whole so that it stays comparable with an uncoloured run. Every +star gets a ``GI_COLOR`` column for the PSF model's context: its matched colour, +or, for a star without one, the median over the CCD's kept training stars. + +""" + +import numpy as np +from astropy.io import fits +from scipy.spatial import cKDTree + + +def _xyz(ra, dec): + ra, dec = np.radians(ra), np.radians(dec) + return np.c_[np.cos(dec) * np.cos(ra), np.cos(dec) * np.sin(ra), np.sin(dec)] + + +class StarColour: + """Match PSF stars to an external colour catalogue. + + @sc [decision:star_selection_psf.psf_colour_purification] + + Parameters + ---------- + catalogue_path : str + FITS table with ``RA``, ``DEC`` (deg), the colour column and the + rejection column + colour_col, reject_col : str + Column names in the catalogue + radius_arcsec : float + Match radius + """ + + def __init__(self, catalogue_path, colour_col="GI", reject_col="REMOVE", radius_arcsec=0.5): + cat = fits.getdata(catalogue_path, 1) + self._colour = np.asarray(cat[colour_col], dtype=float) + self._reject = np.asarray(cat[reject_col], dtype=bool) + self._tree = cKDTree(_xyz(cat["RA"], cat["DEC"])) + self._radius = np.radians(radius_arcsec / 3600) + + def match(self, ra, dec): + """Return colour (NaN if unmatched or colourless) and rejection flag.""" + d, i = self._tree.query(_xyz(ra, dec), distance_upper_bound=self._radius) + ok = np.isfinite(d) + j = np.where(ok, i, 0) + return np.where(ok, self._colour[j], np.nan), ok & self._reject[j] + + @staticmethod + def _write(src, dst, keep, colour): + h = fits.open(src) + data = h[2].data[keep] + cols = [fits.Column(name=c.name, format=c.format, unit=c.unit, dim=c.dim, array=np.asarray(data[c.name])) + for c in h[2].columns] + cols.append(fits.Column(name="GI_COLOR", format="1E", array=colour[keep].astype(np.float32))) + fits.HDUList([h[0], h[1], fits.BinTableHDU.from_columns(cols, name="LDAC_OBJECTS")]).writeto(dst, overwrite=True) + + def process(self, train_path, reserve_path, train_out, reserve_out, w_log): + """Write the purified, coloured training split and the coloured reserve.""" + tr = fits.getdata(train_path, 2) + c_tr, rej = self.match(tr["XWIN_WORLD"], tr["YWIN_WORLD"]) + have = np.isfinite(c_tr) & ~rej + fill = float(np.median(c_tr[have])) if have.any() else 1.3 + self._write(train_path, train_out, ~rej, np.where(np.isfinite(c_tr), c_tr, fill)) + + rs = fits.getdata(reserve_path, 2) + c_rs, _ = self.match(rs["XWIN_WORLD"], rs["YWIN_WORLD"]) + self._write(reserve_path, reserve_out, np.ones(len(rs), bool), np.where(np.isfinite(c_rs), c_rs, fill)) + w_log.info(f"star_colour: {rej.sum()} of {len(tr)} training stars rejected; " + f"{(~np.isfinite(c_tr)).sum()} without colour given {fill:.3f}") diff --git a/src/shapepipe/modules/star_colour_runner.py b/src/shapepipe/modules/star_colour_runner.py new file mode 100644 index 000000000..48f63885a --- /dev/null +++ b/src/shapepipe/modules/star_colour_runner.py @@ -0,0 +1,51 @@ +"""STAR COLOUR RUNNER. + +Module runner for ``star_colour``: between ``setools_runner`` and +``psfex_runner``, drop training stars an external purity verdict rejects and +give every star a ``GI_COLOR`` for a colour-dependent PSF model. + +Config ([STAR_COLOUR_RUNNER]): + COLOUR_CATALOGUE FITS table with RA, DEC, the colour and the rejection flag + COLOUR_COLUMN colour column name (default GI) + REJECT_COLUMN rejection column name (default REMOVE) + MATCH_RADIUS arcsec (default 0.5) + +:Author: Claude (Opus 5.5) for Cail Daley + +""" + +import os + +from shapepipe.modules.module_decorator import module_runner +from shapepipe.modules.star_colour_package.star_colour import StarColour + + +@module_runner( + input_module="setools_runner", + version="1.0", + file_pattern=["star_split_ratio_80", "star_split_ratio_20"], + file_ext=[".fits", ".fits"], + depends=["numpy", "astropy", "scipy"], +) +def star_colour_runner( + input_file_list, + run_dirs, + file_number_string, + config, + module_config_sec, + w_log, +): + """Define The Star Colour Runner.""" + def opt(key, default): + return config.getexpanded(module_config_sec, key) if config.has_option(module_config_sec, key) else default + + sc = StarColour( + config.getexpanded(module_config_sec, "COLOUR_CATALOGUE"), + colour_col=opt("COLOUR_COLUMN", "GI"), + reject_col=opt("REJECT_COLUMN", "REMOVE"), + radius_arcsec=float(opt("MATCH_RADIUS", 0.5)), + ) + train, reserve = input_file_list + out = run_dirs["output"] + sc.process(train, reserve, f"{out}/{os.path.basename(train)}", f"{out}/{os.path.basename(reserve)}", w_log) + return None, None diff --git a/universes/committed.yaml b/universes/committed.yaml index 13b5e3503..afc02d9a2 100644 --- a/universes/committed.yaml +++ b/universes/committed.yaml @@ -40,7 +40,8 @@ analyses: psf_train_validation_split: split_80_20_seeded psfex_candidate_vetting: builtin_defaults psf_modelling_software: psfex - psf_model_complexity: pixel_basis_deg2_per_ccd + psf_model_complexity: pixel_basis_deg2_gi1_per_ccd + psf_colour_purification: purify_and_colour psf_acceptance_thresholds: stars22_chi2_2 shape_measurement: decisions: diff --git a/workflow/config/cfis/config_exp_psfex.ini b/workflow/config/cfis/config_exp_psfex.ini index 05382bb16..0c3de6607 100644 --- a/workflow/config/cfis/config_exp_psfex.ini +++ b/workflow/config/cfis/config_exp_psfex.ini @@ -23,7 +23,7 @@ RUN_DATETIME = False # Module name, single string or comma-separated list of valid module runner names # @sc [decision:star_selection_psf.psf_modelling_software] -MODULE = sextractor_runner, mask_query_runner, setools_runner, psfex_runner, psfex_interp_runner +MODULE = sextractor_runner, mask_query_runner, setools_runner, star_colour_runner, psfex_runner, psfex_interp_runner # Run mode, SMP or MPI MODE = SMP @@ -188,8 +188,26 @@ NUMBERING_SCHEME = -0000000-0 SETOOLS_CONFIG_PATH = $SP_CONFIG/star_selection.setools +[STAR_COLOUR_RUNNER] + +# Colour-purify the PSF stars and give each its g−i (star_colour_package). +# The catalogue is one row per object with RA, DEC, GI (dereddened GAaP g−i) +# and REMOVE (off the stellar locus in i−W1, Gaia-extended, or g−i outside +# [0, 3.5]); its path comes from the environment. +INPUT_DIR = $SP_RUN/output/run_sp_exp_SxSePsf/setools_runner/output/rand_split, $SP_RUN/output/run_sp_exp_SxSePsf/setools_runner/output/rand_split + +NUMBERING_SCHEME = -0000000-0 + +# @sc [decision:star_selection_psf.psf_colour_purification] +COLOUR_CATALOGUE = $SP_STAR_COLOURS +# @sc [decision:star_selection_psf.psf_colour_purification] +MATCH_RADIUS = 0.5 + + [PSFEX_RUNNER] +INPUT_DIR = $SP_RUN/output/run_sp_exp_SxSePsf/star_colour_runner/output + # Use 80% sample for PSF model # @sc [decision:star_selection_psf.psf_train_validation_split] FILE_PATTERN = star_split_ratio_80 @@ -210,6 +228,13 @@ FILE_PATTERN = star_split_ratio_80, star_split_ratio_20, psfex_cat FILE_EXT = .psf, .fits, .cat +INPUT_DIR = $SP_RUN/output/run_sp_exp_SxSePsf/psfex_runner/output, $SP_RUN/output/run_sp_exp_SxSePsf/star_colour_runner/output, $SP_RUN/output/run_sp_exp_SxSePsf/psfex_runner/output + +# Reserve stars are evaluated at their own GI_COLOR; this is for objects +# without one +# @sc [decision:star_selection_psf.psf_colour_purification] +DEFAULT_COLOUR = 1.1 + NUMBERING_SCHEME = -0000000-0 # Run mode for psfex interpolation: diff --git a/workflow/config/cfis/config_tile_PiViVi_psfex.ini b/workflow/config/cfis/config_tile_PiViVi_psfex.ini index 66cc25507..b57f2a3bb 100644 --- a/workflow/config/cfis/config_tile_PiViVi_psfex.ini +++ b/workflow/config/cfis/config_tile_PiViVi_psfex.ini @@ -108,6 +108,11 @@ STAR_THRESH = 22 # @sc [decision:star_selection_psf.psf_acceptance_thresholds] CHI2_THRESH = 2 +# g−i at which a colour-dependent PSF model is evaluated for galaxies: DES Y6's +# median galaxy colour (Yamamoto et al. 2025) +# @sc [decision:star_selection_psf.psf_colour_purification] +DEFAULT_COLOUR = 1.1 + # Multi-epoch mode parameters # Root of per-exposure work directories. Discover psfex_runner/output/ dirs diff --git a/workflow/config/cfis/default.psfex b/workflow/config/cfis/default.psfex index 840f1ddfd..e3e8dc80b 100644 --- a/workflow/config/cfis/default.psfex +++ b/workflow/config/cfis/default.psfex @@ -38,11 +38,11 @@ PHOTFLUXERR_KEY FLUXERR_AUTO # Catalogue parameter for photometric error #----------------------------- PSF variability ------------------------------- # @sc [decision:preparation.object_position_columns,decision:star_selection_psf.psf_model_complexity] -PSFVAR_KEYS XWIN_IMAGE,YWIN_IMAGE # Catalogue or FITS (preceded by :) params +PSFVAR_KEYS XWIN_IMAGE,YWIN_IMAGE,GI_COLOR # Catalogue or FITS (preceded by :) params # @sc [decision:star_selection_psf.psf_model_complexity] -PSFVAR_GROUPS 1,1 # Group tag for each context key +PSFVAR_GROUPS 1,1,2 # Group tag for each context key # @sc [decision:star_selection_psf.psf_model_complexity] -PSFVAR_DEGREES 2 # Polynom degree for each group +PSFVAR_DEGREES 2,1 # Polynom degree for each group PSFVAR_NSNAP 9 # Number of PSF snapshots per axis HIDDENMEF_TYPE COMMON # INDEPENDENT or COMMON diff --git a/workflow/scripts/completeness.py b/workflow/scripts/completeness.py index 84955a37a..58fb5bd50 100644 --- a/workflow/scripts/completeness.py +++ b/workflow/scripts/completeness.py @@ -94,6 +94,7 @@ "sextractor_runner": dict(expect=120), "mask_query_runner": dict(expect=40), "setools_runner": dict(expect=80, subpath="rand_split"), + "star_colour_runner": dict(expect=80), "psfex_runner": dict(expect=80), "psfex_interp_runner": dict(expect=40, warn=True), }, From a545e577b92a22dbf8d1f4496853dfe275d71e8b Mon Sep 17 00:00:00 2001 From: Cail Daley Date: Mon, 23 Nov 2026 22:45:19 -0500 Subject: [PATCH 2/3] feat(psf): purify PSF stars by colour, keep the achromatic PSFEx model On 80 exposures stratified in seeing, the per-CCD g-i term over-corrects the colour slope (-0.69 to +0.08 %/mag), leaves the model 0.38% too large at g-i = 1.1, and raises reserve ellipticity residual scatter by 6%. Colour purification of the training stars alone moves the reserve residual at g-i = 1.1 from -0.13% to -0.05%. This keeps star_colour_runner and the N-D psfex_interp context, and restores the 2-D default.psfex. --- astra.yaml | 55 +++++++++++++++++------------- universes/committed.yaml | 2 +- workflow/config/cfis/default.psfex | 6 ++-- 3 files changed, 35 insertions(+), 28 deletions(-) diff --git a/astra.yaml b/astra.yaml index 84b85f925..27d9c71ea 100644 --- a/astra.yaml +++ b/astra.yaml @@ -1184,41 +1184,44 @@ analyses: persistence and star-catalogue merging read MCCD products. insights: [farrens22_two_psf_methods] psf_model_complexity: - label: PSFEx pixel basis, degree 2 in position times linear in g−i, per CCD + label: PSFEx pixel basis with degree-2 spatial variation per CCD rationale: >- - A pixel basis with polynomial variation in XWIN/YWIN and in the - star's g−i, fit per CCD at native sampling: PSFEx multiplies the - degree-2 position polynomial by a degree-1 colour polynomial (12 - terms), the form DES Y6 fits with Piff (Schutt et al. 2025). The - r-band PSF is chromatic: at fixed magnitude, star size falls by - 0.69% per magnitude of g−i, and an achromatic model cannot follow - it (pando unions/star-selection-as-close-to-des). Training stars - carry GI_COLOR from star_colour_runner; galaxies are evaluated at - the default colour of psf_colour_purification. - PSF_ACCURACY is the fractional accuracy PSFEx assumes for PSF pixel - values; per the PSFEx documentation it enters the fit weights, and - so how closely the model follows bright stars. Model flexibility - trades overfitting against PSF leakage, the dominant additive - systematic in cosmic shear. A more flexible model must be supported - by the surviving training stars and checked on held-out residuals - under the acceptance gate; successful optimisation alone does not - establish a usable PSF. + A pixel basis with polynomial variation in XWIN/YWIN, fit per CCD + at native sampling. PSF_ACCURACY is the fractional accuracy PSFEx + assumes for PSF pixel values; per the PSFEx documentation it enters + the fit weights, and so how closely the model follows bright stars. + Model flexibility trades overfitting against PSF leakage, the + dominant additive systematic in cosmic shear. A more flexible model + must be supported by the surviving training stars and checked on + held-out residuals under the acceptance gate; successful optimisation + alone does not establish a usable PSF. + The model is achromatic although the r-band PSF is not (star size + falls 0.69% per magnitude of g−i at fixed magnitude). A per-CCD + colour term (PSFVAR_KEYS XWIN_IMAGE,YWIN_IMAGE,GI_COLOR, groups + 1,1,2, degrees 2,1) was tested on 80 exposures: it over-corrects the + slope (to +0.08 %/mag), leaves the model 0.38% too large at + g−i = 1.1 against 0.05% achromatic, and raises the reserve + ellipticity residual scatter by 6% (pando + unions/star-selection-as-close-to-des). Values: BASIS_TYPE = PIXEL; PSF_ACCURACY = 0.01; BASIS_NUMBER = 20; - PSFVAR_DEGREES = 2,1; + PSFVAR_DEGREES = 2; PSF_SAMPLING = 1; - PSFVAR_KEYS = XWIN_IMAGE,YWIN_IMAGE,GI_COLOR; - PSFVAR_GROUPS = 1,1,2; + PSFVAR_KEYS = XWIN_IMAGE,YWIN_IMAGE; + PSFVAR_GROUPS = 1,1; MEF_TYPE = INDEPENDENT. - default: pixel_basis_deg2_gi1_per_ccd + default: pixel_basis_deg2_per_ccd options: - pixel_basis_deg2_gi1_per_ccd: - label: PIXEL basis, degree 2 in position times degree 1 in g−i, per CCD pixel_basis_deg2_per_ccd: label: PIXEL basis, degree 2, per CCD, achromatic insights: [guinot22_psf_no_oversampling] + pixel_basis_deg2_gi1_per_ccd: + label: PIXEL basis, degree 2 in position times degree 1 in g−i, per CCD + description: >- + Branch feat/psfex-colour-term. Over-corrects the colour slope and + adds model noise on 80 test exposures. deg3: label: Degree-3 spatial variation description: Needs more stars per CCD than the acceptance gate guarantees. @@ -1236,6 +1239,10 @@ analyses: Y6's median galaxy colour, which its image simulations show costs Δm = (0.04 ± 2.0)×10⁻³ against per-galaxy colours (Yamamoto et al. 2025). + With the achromatic model, GI_COLOR is carried but unused, and + DEFAULT_COLOUR matters only for a colour-dependent model. On 80 + exposures purification moves the reserve residual at g−i = 1.1 from + −0.13% to −0.05% (0.08–0.10% in every seeing quartile). Values: config_exp_psfex.ini#STAR_COLOUR_RUNNER.MATCH_RADIUS = 0.5; config_exp_psfex.ini#PSFEX_INTERP_RUNNER.DEFAULT_COLOUR = 1.1; diff --git a/universes/committed.yaml b/universes/committed.yaml index afc02d9a2..84379a27c 100644 --- a/universes/committed.yaml +++ b/universes/committed.yaml @@ -40,7 +40,7 @@ analyses: psf_train_validation_split: split_80_20_seeded psfex_candidate_vetting: builtin_defaults psf_modelling_software: psfex - psf_model_complexity: pixel_basis_deg2_gi1_per_ccd + psf_model_complexity: pixel_basis_deg2_per_ccd psf_colour_purification: purify_and_colour psf_acceptance_thresholds: stars22_chi2_2 shape_measurement: diff --git a/workflow/config/cfis/default.psfex b/workflow/config/cfis/default.psfex index e3e8dc80b..840f1ddfd 100644 --- a/workflow/config/cfis/default.psfex +++ b/workflow/config/cfis/default.psfex @@ -38,11 +38,11 @@ PHOTFLUXERR_KEY FLUXERR_AUTO # Catalogue parameter for photometric error #----------------------------- PSF variability ------------------------------- # @sc [decision:preparation.object_position_columns,decision:star_selection_psf.psf_model_complexity] -PSFVAR_KEYS XWIN_IMAGE,YWIN_IMAGE,GI_COLOR # Catalogue or FITS (preceded by :) params +PSFVAR_KEYS XWIN_IMAGE,YWIN_IMAGE # Catalogue or FITS (preceded by :) params # @sc [decision:star_selection_psf.psf_model_complexity] -PSFVAR_GROUPS 1,1,2 # Group tag for each context key +PSFVAR_GROUPS 1,1 # Group tag for each context key # @sc [decision:star_selection_psf.psf_model_complexity] -PSFVAR_DEGREES 2,1 # Polynom degree for each group +PSFVAR_DEGREES 2 # Polynom degree for each group PSFVAR_NSNAP 9 # Number of PSF snapshots per axis HIDDENMEF_TYPE COMMON # INDEPENDENT or COMMON From 545cad8e7bfc35fe2f145317f8c4263db5573d44 Mon Sep 17 00:00:00 2001 From: Cail Daley Date: Mon, 23 Nov 2026 23:00:53 -0500 Subject: [PATCH 3/3] fix(workflow): star_colours as an opt-in run input; persist setools' star splits - inputs.star_colours (run config) is exported as SP_STAR_COLOURS by every unit prologue; apptainer's --cleanenv kept a caller's variable from reaching the jobs. Unset, star_colour_runner passes the star splits through unchanged (checked on one exposure: all 40 PSFEx models bit-identical to run 1's). - star_train/star_test persist globs name setools' rand_split copies: star_colour_runner rewrites the splits under the same names, which collided in the flat tar. The property test matches member names against the glob's filename part and sources against the whole glob. --- src/shapepipe/modules/star_colour_runner.py | 17 +++++++++++++---- tests/unit/test_persist_exp_props.py | 8 +++++++- workflow/Snakefile | 3 +++ workflow/config.yaml | 4 ++++ workflow/config/cfis/config_exp_psfex.ini | 3 ++- workflow/scripts/persist_exp.py | 10 ++++++---- 6 files changed, 35 insertions(+), 10 deletions(-) diff --git a/src/shapepipe/modules/star_colour_runner.py b/src/shapepipe/modules/star_colour_runner.py index 48f63885a..44fbd64da 100644 --- a/src/shapepipe/modules/star_colour_runner.py +++ b/src/shapepipe/modules/star_colour_runner.py @@ -5,7 +5,8 @@ give every star a ``GI_COLOR`` for a colour-dependent PSF model. Config ([STAR_COLOUR_RUNNER]): - COLOUR_CATALOGUE FITS table with RA, DEC, the colour and the rejection flag + COLOUR_CATALOGUE FITS table with RA, DEC, the colour and the rejection flag; + empty, the module passes the splits through unchanged COLOUR_COLUMN colour column name (default GI) REJECT_COLUMN rejection column name (default REMOVE) MATCH_RADIUS arcsec (default 0.5) @@ -15,6 +16,7 @@ """ import os +import shutil from shapepipe.modules.module_decorator import module_runner from shapepipe.modules.star_colour_package.star_colour import StarColour @@ -39,13 +41,20 @@ def star_colour_runner( def opt(key, default): return config.getexpanded(module_config_sec, key) if config.has_option(module_config_sec, key) else default + train, reserve = input_file_list + out = run_dirs["output"] + catalogue = opt("COLOUR_CATALOGUE", "") + if not catalogue: + for path in (train, reserve): + shutil.copy(path, f"{out}/{os.path.basename(path)}") + w_log.info("star_colour: no COLOUR_CATALOGUE, splits passed through") + return None, None + sc = StarColour( - config.getexpanded(module_config_sec, "COLOUR_CATALOGUE"), + catalogue, colour_col=opt("COLOUR_COLUMN", "GI"), reject_col=opt("REJECT_COLUMN", "REMOVE"), radius_arcsec=float(opt("MATCH_RADIUS", 0.5)), ) - train, reserve = input_file_list - out = run_dirs["output"] sc.process(train, reserve, f"{out}/{os.path.basename(train)}", f"{out}/{os.path.basename(reserve)}", w_log) return None, None diff --git a/tests/unit/test_persist_exp_props.py b/tests/unit/test_persist_exp_props.py index 97d58d72c..143447cef 100644 --- a/tests/unit/test_persist_exp_props.py +++ b/tests/unit/test_persist_exp_props.py @@ -242,8 +242,14 @@ def _pack_and_check(self, keep): continue assert f["product"] in entries, ( f"{f['name']} labelled {f['product']!r}, not in the keep list") - assert fnmatch.fnmatch(f["name"], persist.resolve(f["product"])), ( + # tar members are flat; a glob may name a subdirectory + # (rand_split/...), so the member matches its filename part and + # the source path matches the whole glob + glob = persist.resolve(f["product"]) + assert fnmatch.fnmatch(f["name"], Path(glob).name), ( f"{f['name']} does not match {f['product']!r}'s glob") + assert Path(f["src"]).match(glob), ( + f"{f['src']} does not match {f['product']!r}'s glob") assert Path(f["src"]).exists() assert f["bytes"] == Path(f["src"]).stat().st_size diff --git a/workflow/Snakefile b/workflow/Snakefile index bb7c32933..e94af2523 100644 --- a/workflow/Snakefile +++ b/workflow/Snakefile @@ -1075,6 +1075,9 @@ def unit_pre(stage, unit, *, exp_name=None, forest=None, env=None, lines.append(f"export PSF_DICT='{PSF_DICT}'") if INPUT_TYPE == "data": lines.append(f"export SP_INPUT_MASKS='{INPUTS['masks']}'") + # PSF-star colours and purity verdict (star_colour_runner); empty, the + # runner passes the star splits through unchanged + lines.append(f"export SP_STAR_COLOURS='{INPUTS.get('star_colours') or ''}'") if forest: lines.append(f"export SP_EXP='{forest}'") for k, v in (env or {}).items(): diff --git a/workflow/config.yaml b/workflow/config.yaml index d8fa2ac45..cd564bcc9 100644 --- a/workflow/config.yaml +++ b/workflow/config.yaml @@ -66,6 +66,10 @@ input_types: # True = masked), queried per object by make_cat -- never rasterized. # Consumed by MASK_EXT_PATHS in config/cfis/config_tile_Mc.ini, which # carries the bit table. Required for input_type: data. +# - inputs.star_colours (optional): FITS table of RA, DEC, GI (dereddened +# g−i) and REMOVE (PSF-star purity verdict), one row per object, read by +# star_colour_runner to drop impure PSF training stars and give each star +# GI_COLOR. Unset, the star splits pass through unchanged. # - inputs.catalogues: UNIONS per-tile catalogues, a local directory # (symlinked in) or a vos: URL (tile_detection: unions_catalogue) # - psf_dict: simulation PSF stamps (psf_model: fake) diff --git a/workflow/config/cfis/config_exp_psfex.ini b/workflow/config/cfis/config_exp_psfex.ini index 0c3de6607..c7ca0328f 100644 --- a/workflow/config/cfis/config_exp_psfex.ini +++ b/workflow/config/cfis/config_exp_psfex.ini @@ -193,7 +193,8 @@ SETOOLS_CONFIG_PATH = $SP_CONFIG/star_selection.setools # Colour-purify the PSF stars and give each its g−i (star_colour_package). # The catalogue is one row per object with RA, DEC, GI (dereddened GAaP g−i) # and REMOVE (off the stellar locus in i−W1, Gaia-extended, or g−i outside -# [0, 3.5]); its path comes from the environment. +# [0, 3.5]); its path is the run config's inputs.star_colours. Empty, the +# module passes the splits through unchanged. INPUT_DIR = $SP_RUN/output/run_sp_exp_SxSePsf/setools_runner/output/rand_split, $SP_RUN/output/run_sp_exp_SxSePsf/setools_runner/output/rand_split NUMBERING_SCHEME = -0000000-0 diff --git a/workflow/scripts/persist_exp.py b/workflow/scripts/persist_exp.py index 849242c06..3617fb901 100644 --- a/workflow/scripts/persist_exp.py +++ b/workflow/scripts/persist_exp.py @@ -70,11 +70,13 @@ "the selection cuts rejected and why; the split samples have already " "lost the rejects."), "star_train": ( - "star_split_ratio_80-*.fits", 19_900_000, - "the 80% TRAINING sample, the stars PSFEx actually fitted. Rows " - "duplicate star_selection."), + "rand_split/star_split_ratio_80-*.fits", 19_900_000, + "setools' 80% TRAINING sample. PSFEx fits it less the stars the " + "star_colour verdict rejects (star_colour_runner rewrites it under the " + "same name, so the pattern names setools' copy). Rows duplicate " + "star_selection."), "star_test": ( - "star_split_ratio_20-*.fits", 7_100_000, + "rand_split/star_split_ratio_20-*.fits", 7_100_000, "the 20% VALIDATION sample — the positions psf_validation's rows " "correspond to. Rows duplicate star_selection."), "star_stats": (