Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 45 additions & 3 deletions astra.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -1194,7 +1195,14 @@ analyses:
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.
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;
Expand All @@ -1207,11 +1215,45 @@ analyses:
default: pixel_basis_deg2_per_ccd
options:
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]
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.
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).
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;
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: >-
Expand Down
105 changes: 74 additions & 31 deletions src/shapepipe/modules/psfex_interp_package/psfex_interp.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -277,6 +315,7 @@ def __init__(
get_shapes=True,
star_thresh=20,
chi2_thresh=2,
default_colour=None,
):

# Path to PSFEx output file
Expand All @@ -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

Expand All @@ -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
Expand Down Expand Up @@ -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"
)
Expand All @@ -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.
Expand All @@ -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
-------
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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):
Expand Down
10 changes: 10 additions & 0 deletions src/shapepipe/modules/psfex_interp_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -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":
Expand All @@ -53,6 +60,7 @@ def psfex_interp_runner(
get_shapes,
star_thresh,
chi2_thresh,
default_colour,
)

# Process inputs
Expand Down Expand Up @@ -104,6 +112,7 @@ def psfex_interp_runner(
get_shapes,
star_thresh,
chi2_thresh,
default_colour,
)

# Process inputs multi-epoch
Expand All @@ -126,6 +135,7 @@ def psfex_interp_runner(
get_shapes,
star_thresh,
chi2_thresh,
default_colour,
)

# Process inputs validation
Expand Down
10 changes: 10 additions & 0 deletions src/shapepipe/modules/star_colour_package/__init__.py
Original file line number Diff line number Diff line change
@@ -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"]
77 changes: 77 additions & 0 deletions src/shapepipe/modules/star_colour_package/star_colour.py
Original file line number Diff line number Diff line change
@@ -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}")
Loading
Loading