From 677d28163f448c2a4b512db0b7a70433483c0951 Mon Sep 17 00:00:00 2001 From: Cail Daley Date: Sat, 21 Nov 2026 19:43:04 -0700 Subject: [PATCH 1/3] feat(psfex_interp): render PSFEx models as native-pixel stamps (#989) interpsfex reads PSF_SAMP and resamples the basis-combined model onto the native pixel grid with PSFEx's own model-to-vignet mapping (separable Lanczos-3, unit-sum weights, model centre n//2 on stamp centre), so validation HSM, the galaxy_psf store and ngmix receive native-pixel effective-PSF stamps at any PSF_SAMPLING. At unit sampling with centred stamps the raw grid is returned unchanged. STAMP_PHASE (psfex_interp option, default False) renders each PSF at the sub-pixel phase of the stamp it is compared with: the star's SExtractor VIGNET in validation (centred on the rounded X_IMAGE pixel, measured on SExtractor 2.25), each epoch's vignetmaker stamp (OFFSET) on the multi-epoch path. New ASTRA decision star_selection_psf.psf_stamp_rendering, committed option centred. Co-Authored-By: Claude Opus 5.5 --- astra.yaml | 32 ++- .../psfex_interp_package/psfex_interp.py | 183 +++++++++++++++++- src/shapepipe/modules/psfex_interp_runner.py | 6 + tests/module/test_psfex_interp.py | 180 +++++++++++++++++ universes/committed.yaml | 1 + workflow/config/cfis/config_exp_psfex.ini | 6 + .../config/cfis/config_tile_PiViVi_psfex.ini | 6 + 7 files changed, 407 insertions(+), 7 deletions(-) diff --git a/astra.yaml b/astra.yaml index e336ef639..ab7ca16b9 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_acceptance_thresholds, + psf_stamp_rendering] decisions: star_selection_box: label: Stellar-locus selection, magnitude window and FWHM window scaled to the locus @@ -1253,6 +1254,35 @@ analyses: excluded: true excluded_reason: >- CFIS CCDs are smaller than DECam's; the floor is survey-specific. + psf_stamp_rendering: + label: PSF models rendered as native-pixel stamps, centred or at the compared stamp's phase + rationale: >- + psfex_interp resamples the PSFEx model onto the native pixel grid + with PSFEx's own model-to-vignet mapping (separable Lanczos-3, + unit-sum weights), so validation HSM, the galaxy_psf store and + ngmix receive native-pixel effective-PSF stamps whatever + PSF_SAMPLING is; at unit sampling with centred stamps the model grid + is passed through unchanged. Each stamp is either centred or drawn + at the sub-pixel phase of the stamp it is compared with: the star's + SExtractor VIGNET (cut around the rounded X_IMAGE pixel) in + validation, each epoch's galaxy stamp (the vignetmaker OFFSET) on + the multi-epoch path. On a 0.50 arcsec exposure (shapepipe#989) + phase matching moves the validation star-minus-PSF g1 residual from + -4.0e-3 to between -1.0e-3 and -2.7e-3 at native sampling, and from + -1.3e-3 to consistent with zero with a 0.5-sampled model. On the + galaxy path, a phase-matched PSF makes metacal deconvolution exact + for compact galaxies and leaves the deconvolved galaxy at the stamp + centre, a sub-pixel offset from the ngmix centroid prior (sigma + 1 px); its effect on shear is unmeasured. + Values: + config_exp_psfex.ini#PSFEX_INTERP_RUNNER.STAMP_PHASE = False; + config_tile_PiViVi_psfex.ini#PSFEX_INTERP_RUNNER.STAMP_PHASE = False. + default: centred + options: + centred: + label: PSF centred on the native stamp + stamp_phase: + label: PSF at the sub-pixel phase of the star VIGNET or galaxy stamp prior_insights: des_psf_blacklist_local: claim: >- diff --git a/src/shapepipe/modules/psfex_interp_package/psfex_interp.py b/src/shapepipe/modules/psfex_interp_package/psfex_interp.py index 5e7877c9c..2e0fa8870 100644 --- a/src/shapepipe/modules/psfex_interp_package/psfex_interp.py +++ b/src/shapepipe/modules/psfex_interp_package/psfex_interp.py @@ -32,6 +32,117 @@ FILE_NOT_FOUND = "File_not_found" +def _lanczos3(x): + """Lanczos-3 kernel, as PSFEx's ``INTERPF`` (``vignet.h``).""" + return np.where(np.abs(x) < 3, np.sinc(x) * np.sinc(x / 3), 0.0) + + +def _resample_matrix(n_model, n_native, sampling, offset): + """Separable Lanczos-3 resampling matrix, native rows x model columns. + + Native pixel ``j`` sits at model coordinate + ``n_model // 2 + (j - n_native // 2 - offset) / sampling``; each row holds + the Lanczos-3 weights of the model pixels around it, normalised to unit + sum as PSFEx's ``vignet_resample`` does. + """ + native = np.arange(n_native) - n_native // 2 - offset + model_pos = n_model // 2 + native / sampling + weights = _lanczos3(model_pos[:, None] - np.arange(n_model)[None, :]) + return weights / weights.sum(axis=1, keepdims=True) + + +def native_psf_stamps(psfs, sampling, offsets=None): + """Native-Pixel PSF Stamps. + + Render PSFEx model stamps on the native pixel grid. + + @sc [decision:star_selection_psf.psf_stamp_rendering] + A PSFEx model (``PSF_MASK`` combined over its basis) is a grid of the + effective (pixel-convolved) PSF, ``sampling`` native pixels apart, + centred on grid index ``n // 2``, with values in native-pixel units: the + grid sums to about ``1 / sampling**2``. PSFEx fits that grid by resampling + it onto each training star's vignet (``psf_refine``, ``vignet_resample``), + so the image of a star the model predicts is that resampling. This + function applies it with PSFEx's kernel and conventions: separable + Lanczos-3, weights normalised to unit sum per output pixel, the model + centre ``n_model // 2`` placed on the native stamp centre + ``n_native // 2`` shifted by ``offset``. A native stamp therefore carries + the model's flux in native pixels (about 1), and no pixel response is + applied: the model already is the effective PSF. + + The native stamp is ``n_native x n_native`` with ``n_native`` the odd + integer ``int(n_model * sampling) | 1``: 51 for a 51-pixel model at unit + sampling and for a 101-pixel model at sampling 0.5. + + At ``sampling == 1`` with no offsets the model grid already is the native + stamp and is returned unchanged. + + Parameters + ---------- + psfs : numpy.ndarray + Model-grid stamps, ``(N, n_model, n_model)``. + sampling : float + Model pixel size in native pixels (the ``.psf`` ``PSF_SAMP``). + offsets : numpy.ndarray, optional + ``(N, 2)`` sub-pixel ``(dx, dy)`` of each PSF centre from the native + stamp centre, in native pixels. ``None`` centres every stamp. + + Returns + ------- + numpy.ndarray + Native stamps, ``(N, n_native, n_native)``. + + """ + if sampling == 1 and offsets is None: + return psfs + + n_model = psfs.shape[-1] + n_native = int(n_model * sampling) | 1 + if offsets is None: + offsets = np.zeros((len(psfs), 2)) + + stamps = np.empty((len(psfs), n_native, n_native)) + for idx, (psf, (dx, dy)) in enumerate(zip(psfs, offsets)): + kx = _resample_matrix(n_model, n_native, sampling, dx) + ky = _resample_matrix(n_model, n_native, sampling, dy) + stamps[idx] = ky @ psf @ kx.T + return stamps + + +def sextractor_vignet_offsets(pos, barycentre): + """SExtractor VIGNET Offsets. + + Sub-pixel offset of each position from the centre of its SExtractor + ``VIGNET``. + + SExtractor cuts ``VIGNET`` around the 0-indexed pixel + ``int(mx + 0.49999)``, where ``mx = X_IMAGE - 1`` is the isophotal + barycentre, and places that pixel at stamp index ``w // 2``. The + windowed centroid ``XWIN_IMAGE`` can round to a different pixel than + ``X_IMAGE``, so the offset is measured from the ``X_IMAGE`` pixel. + Measured on SExtractor 2.25 VIGNETs (shapepipe#989): this convention + places the HSM centroid of 268 bright stars within 0.03 px of + ``XWIN_IMAGE``, while rounding ``XWIN_IMAGE`` misplaces 28 of them by a + whole pixel. + + Parameters + ---------- + pos : numpy.ndarray + ``(N, 2)`` 1-indexed image positions the PSF is evaluated at + (``XWIN_IMAGE``, ``YWIN_IMAGE``). + barycentre : numpy.ndarray + ``(N, 2)`` 1-indexed ``X_IMAGE``, ``Y_IMAGE``. + + Returns + ------- + numpy.ndarray + ``(N, 2)`` ``(dx, dy)`` offsets in pixels. + + """ + centre_pixel = np.floor(barycentre - 1 + 0.49999) + return pos - 1 - centre_pixel + + def local_wcs_list(wcs, positions): """Local WCS List. @@ -263,6 +374,10 @@ class PSFExInterpolator(object): Threshold of stars under which the PSF is not interpolated thresh_chi2 : int Threshold for chi squared + stamp_phase : bool + If ``True``, render each PSF at the sub-pixel phase of the stamp it is + compared with or fitted against, rather than centred; see + :meth:`_stamp_offsets` and :meth:`process_me` """ @@ -277,6 +392,7 @@ def __init__( get_shapes=True, star_thresh=20, chi2_thresh=2, + stamp_phase=False, ): # Path to PSFEx output file @@ -303,6 +419,8 @@ def __init__( self._chi2_thresh = chi2_thresh + self._stamp_phase = stamp_phase + # Logging self._w_log = w_log @@ -408,10 +526,12 @@ def _get_galaxy_positions(self): raise KeyError(pos_param_err) galcat.close() - def interpsfex(self, dotpsfpath, pos): + def interpsfex(self, dotpsfpath, pos, offsets=None): """Interpolate PSFEx. - Use PSFEx generated model to perform spatial PSF interpolation. + Use PSFEx generated model to perform spatial PSF interpolation, and + return the PSFs as native-pixel stamps whatever the model's sampling + (``PSF_SAMP``); see :func:`native_psf_stamps`. @sc [decision:star_selection_psf.psf_acceptance_thresholds,label:gate] psf-gate-path-specific-output Validation logs a rejected gate and skips writing validation output; @@ -424,12 +544,14 @@ def interpsfex(self, dotpsfpath, pos): Path to ``.psf`` file (PSFEx output) pos : numpy.ndarray Positions where the PSF model should be evaluated + offsets : numpy.ndarray, optional + ``(N, 2)`` sub-pixel ``(dx, dy)`` of each PSF centre from its + stamp centre; ``None`` centres every stamp Returns ------- numpy.ndarray - Array of PSFs, each row is the PSF image at the corresponding position - requested + Array of native-pixel PSF stamps, one per requested position """ if not os.path.exists(dotpsfpath): @@ -454,11 +576,13 @@ def interpsfex(self, dotpsfpath, pos): return BAD_CHI2 PSF_basis = np.array(PSF_model.data)[0][0] + sampling = PSF_model.header["PSF_SAMP"] try: deg = PSF_model.header["POLDEG1"] except KeyError: # constant PSF model - return PSF_basis[0, :, :] + PSFs = np.repeat(PSF_basis[:1], len(pos), axis=0) + return native_psf_stamps(PSFs, sampling, offsets) # scale coordinates x_interp, x_scale = ( @@ -505,7 +629,7 @@ def interpsfex(self, dotpsfpath, pos): ] ) - return PSFs + return native_psf_stamps(PSFs, sampling, offsets) def _interpolate(self): """Interpolate. @@ -517,8 +641,35 @@ def _interpolate(self): self.interp_PSFs = self.interpsfex( self._dotpsf_path, self.gal_pos, + self._stamp_offsets() if self._stamp_phase else None, ) + def _stamp_offsets(self): + """Stamp Offsets. + + Sub-pixel offsets of the catalogue positions from the centres of the + catalogue's SExtractor ``VIGNET`` stamps, which are what the PSF is + compared with on the single-exposure paths: validation measures star + ``VIGNET`` and PSF with HSM side by side, each with the local WCS at + the star's ``XWIN_IMAGE``. Rendered at that offset, the PSF stamp is + the model's image of the star as sampled in its ``VIGNET``, which is + also how PSFEx maps its model onto a training star. The positions must + be 1-indexed image coordinates (``XWIN_IMAGE``, ``YWIN_IMAGE``); see + :func:`sextractor_vignet_offsets`. + + Returns + ------- + numpy.ndarray + ``(N, 2)`` ``(dx, dy)`` offsets in pixels. + + """ + galcat = file_io.FITSCatalogue(self._galcat_path, SEx_catalogue=True) + galcat.open() + data = galcat.get_data() + barycentre = np.column_stack((data["X_IMAGE"], data["Y_IMAGE"])) + galcat.close() + return sextractor_vignet_offsets(self.gal_pos, barycentre) + def _get_psfshapes(self, wcs_list=None): """Get PSF Shapes. @@ -802,6 +953,25 @@ def process_me(self, dot_psf_dirs, dot_psf_pattern, f_wcs_path): Process multi-epoc PSF interpolation. + With ``stamp_phase``, each epoch's PSF is rendered at the sub-pixel + offset of the object from the centre of that epoch's galaxy stamp. + The vignetmaker cuts the stamp around ``numpy.round`` of the object's + 0-indexed exposure position, projected from the same + ``POSITION_PARAMS`` through the same exposure WCS + (:func:`shapepipe.modules.vignetmaker_package.vignetmaker.get_stamps`), + so the offset is ``gal_pos - round(gal_pos)``: the vignette's + ``OFFSET``, in ``(x, y)`` order. The PSF stamp is then the model's + image of a point source at the object's centroid, sampled on the + galaxy stamp's pixel grid. ngmix metacal turns both stamps into + ``InterpolatedImage`` profiles centred on their stamp centres and + divides one by the other, so for a point-like galaxy the + deconvolution is exact at every sampling and the deconvolved galaxy + sits at the stamp centre, a sub-pixel distance from the ngmix + centroid prior, which is placed at the ``OFFSET`` + (``centroid_source="wcs"``). With centred PSFs the deconvolved galaxy + sits at the ``OFFSET``, and the aliased high frequencies of an + undersampled PSF do not match the galaxy's. + Parameters ---------- dot_psf_dirs : list @@ -951,6 +1121,7 @@ def _interpolate_me(self): self.interp_PSFs = self.interpsfex( dot_psf_path, gal_pos, + gal_pos - np.round(gal_pos) if self._stamp_phase else None, ) if ( diff --git a/src/shapepipe/modules/psfex_interp_runner.py b/src/shapepipe/modules/psfex_interp_runner.py index 5627d5d20..1104bcced 100644 --- a/src/shapepipe/modules/psfex_interp_runner.py +++ b/src/shapepipe/modules/psfex_interp_runner.py @@ -35,6 +35,9 @@ 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") + stamp_phase = config.has_option( + module_config_sec, "STAMP_PHASE" + ) and config.getboolean(module_config_sec, "STAMP_PHASE") # Run in CLASSIC mode if mode == "CLASSIC": @@ -53,6 +56,7 @@ def psfex_interp_runner( get_shapes, star_thresh, chi2_thresh, + stamp_phase, ) # Process inputs @@ -104,6 +108,7 @@ def psfex_interp_runner( get_shapes, star_thresh, chi2_thresh, + stamp_phase, ) # Process inputs multi-epoch @@ -126,6 +131,7 @@ def psfex_interp_runner( get_shapes, star_thresh, chi2_thresh, + stamp_phase, ) # Process inputs validation diff --git a/tests/module/test_psfex_interp.py b/tests/module/test_psfex_interp.py index afde409e8..fc236adc4 100644 --- a/tests/module/test_psfex_interp.py +++ b/tests/module/test_psfex_interp.py @@ -13,6 +13,8 @@ from shapepipe.pipeline import file_io from shapepipe.modules.psfex_interp_package.psfex_interp import ( PSFExInterpolator, + native_psf_stamps, + sextractor_vignet_offsets, ) @@ -206,3 +208,181 @@ def _capture(self, data=None, **kwargs): # ... and the size column is T = 2 sigma^2 (sigma_to_T), not raw sigma. npt.assert_allclose(data["HSM_T_PSF"], 2.0 * interp.psf_shapes[:, 2] ** 2) assert not np.allclose(data["HSM_T_PSF"], interp.psf_shapes[:, 2]) + + +# --- Native-pixel rendering of PSFEx models (shapepipe#989) ---------------- + +# An undersampled effective PSF: a sheared Gaussian of sigma 1.1 px (FWHM +# 2.6 px, about 0.48 arcsec on MegaCam) convolved with the native pixel. +_EPSF = galsim.Convolve( + galsim.Gaussian(sigma=1.1).shear(g1=0.06, g2=-0.03), galsim.Pixel(1.0) +) + + +def _native_epsf(offset=(0.0, 0.0), n=51): + """The effective PSF sampled at native pixel centres: the analytic stamp.""" + return _EPSF.drawImage( + nx=n, ny=n, scale=1.0, method="no_pixel", offset=offset + ).array + + +def _model_grid(sampling, n_model): + """A PSFEx-style model grid: point samples of the effective PSF. + + Samples are ``sampling`` native pixels apart, centred on index + ``n_model // 2``, in native-pixel units (a unit-flux star's value per + native pixel), so the grid sums to about ``1 / sampling**2``. + """ + return ( + _EPSF.drawImage( + nx=n_model, ny=n_model, scale=sampling, method="no_pixel" + ).array + / sampling**2 + ) + + +def _write_dotpsf(path, basis, sampling): + """Write a minimal degree-2 PSFEx ``.psf`` file with the given basis.""" + nbasis, ny, nx = basis.shape + table = fits.BinTableHDU.from_columns( + [ + fits.Column( + name="PSF_MASK", + format=f"{basis.size}E", + dim=f"({nx}, {ny}, {nbasis})", + array=basis[None].astype(np.float32), + ) + ] + ) + header = table.header + header["POLNAME1"] = "XWIN_IMAGE" + header["POLNAME2"] = "YWIN_IMAGE" + header["POLZERO1"], header["POLSCAL1"] = 1000.0, 2000.0 + header["POLZERO2"], header["POLSCAL2"] = 2000.0, 4000.0 + header["POLDEG1"] = 2 + header["PSF_SAMP"] = sampling + header["ACCEPTED"] = 100 + header["CHI2"] = 1.0 + fits.HDUList([fits.PrimaryHDU(), table]).writeto(path) + + +def _interpolator(tmp_path): + cat_path = tmp_path / "galaxies.fits" + _write_galaxy_catalogue(cat_path, XWIN_IMAGE=[1.0], YWIN_IMAGE=[1.0]) + return PSFExInterpolator( + dotpsf_path=None, + galcat_path=str(cat_path), + output_path=str(tmp_path), + img_number="001", + w_log=SimpleNamespace(info=lambda message: None), + pos_params=["XWIN_IMAGE", "YWIN_IMAGE"], + ) + + +def _hsm(stamp): + return galsim.hsm.FindAdaptiveMom(galsim.Image(stamp, scale=1.0)) + + +@pytest.mark.decision("star_selection_psf.psf_stamp_rendering") +def test_unit_sampling_centred_returns_raw_grid(tmp_path): + """At PSF_SAMP = 1 with centred stamps, interpsfex returns the raw grid. + + Bit for bit: the basis combination is the native stamp, untouched. + """ + rng = np.random.default_rng(1) + basis = rng.normal(size=(6, 51, 51)).astype(np.float32) + dotpsf = tmp_path / "unit.psf" + _write_dotpsf(dotpsf, basis, 1.0) + pos = np.array([[100.0, 200.0], [1500.5, 3000.25]]) + + psfs = _interpolator(tmp_path).interpsfex(str(dotpsf), pos) + + xs = (pos[:, 0] - 1000.0) / 2000.0 + ys = (pos[:, 1] - 2000.0) / 4000.0 + coeffs = np.column_stack( + [np.ones_like(xs), xs, xs**2, ys, xs * ys, ys**2] + ) + raw = np.array( + [np.sum([c * b for c, b in zip(row, basis)], axis=0) for row in coeffs] + ) + assert psfs.shape == (2, 51, 51) + assert np.array_equal(psfs, raw) + assert native_psf_stamps(raw, 1.0) is raw + + +@pytest.mark.decision("star_selection_psf.psf_stamp_rendering") +@pytest.mark.parametrize("sampling, n_model", [(0.5, 101), (1.0, 51)]) +@pytest.mark.parametrize("offset", [(0.0, 0.0), (0.3, -0.45)]) +def test_native_stamp_matches_analytic_rendering( + tmp_path, sampling, n_model, offset +): + """The native stamp of a model matches the effective PSF drawn natively. + + The model grid goes through a ``.psf`` file and ``interpsfex``; its + native stamp keeps the native-pixel normalisation and matches the + analytic native rendering at the same offset in HSM size, shape and + centroid. Centred, the match is exact to 3e-5. Off-centre, Lanczos-3 + interpolation of point samples errs by up to 4e-3 in size and 2e-3 in + shape (0.6e-2 px in centroid); a PSFEx model carries no such error, + since PSFEx fits its grid through this same resampling. + """ + basis = np.zeros((6, n_model, n_model)) + basis[0] = _model_grid(sampling, n_model) + dotpsf = tmp_path / "model.psf" + _write_dotpsf(dotpsf, basis, sampling) + + stamp = _interpolator(tmp_path).interpsfex( + str(dotpsf), np.array([[1000.0, 2000.0]]), np.array([offset]) + )[0] + truth = _native_epsf(offset) + + assert stamp.shape == (51, 51) + npt.assert_allclose(stamp.sum(), truth.sum(), rtol=1e-3) + tol = 5e-5 if offset == (0.0, 0.0) else 5e-3 + got, want = _hsm(stamp), _hsm(truth) + npt.assert_allclose( + got.moments_sigma, want.moments_sigma, rtol=tol + ) + npt.assert_allclose( + [got.observed_shape.g1, got.observed_shape.g2], + [want.observed_shape.g1, want.observed_shape.g2], + atol=tol / 2, + ) + npt.assert_allclose( + [got.moments_centroid.x, got.moments_centroid.y], + [want.moments_centroid.x, want.moments_centroid.y], + atol=2 * tol, + ) + + +@pytest.mark.decision("star_selection_psf.psf_stamp_rendering") +@pytest.mark.parametrize("sampling, n_model", [(0.5, 101), (1.0, 51)]) +def test_phase_moves_centroid_by_offset(sampling, n_model): + """A phase offset moves the stamp centroid by that offset. + + To the Lanczos-3 interpolation error (under 1e-2 px); a sign or + convention error would be off by up to a pixel. + """ + model = _model_grid(sampling, n_model)[None] + offsets = np.array([[0.0, 0.0], [0.4, -0.25], [-0.5, 0.5]]) + stamps = native_psf_stamps( + np.repeat(model, len(offsets), axis=0), sampling, offsets + ) + centre = _hsm(stamps[0]).moments_centroid + for stamp, (dx, dy) in zip(stamps[1:], offsets[1:]): + shift = _hsm(stamp).moments_centroid - centre + npt.assert_allclose([shift.x, shift.y], [dx, dy], atol=1e-2) + + +def test_sextractor_vignet_offsets_round_the_barycentre(): + """The VIGNET centre pixel comes from X_IMAGE, not XWIN_IMAGE. + + X_IMAGE = 10.49 rounds (0-indexed, ``int(mx + 0.49999)``) to pixel 9; + XWIN_IMAGE = 10.52 would round to 10. The offset of XWIN from the + VIGNET centre is therefore 10.52 - 1 - 9 = 0.52 px. + """ + pos = np.array([[10.52, 20.0]]) + barycentre = np.array([[10.49, 20.2]]) + npt.assert_allclose( + sextractor_vignet_offsets(pos, barycentre), [[0.52, 0.0]] + ) diff --git a/universes/committed.yaml b/universes/committed.yaml index 13b5e3503..39d56d8e5 100644 --- a/universes/committed.yaml +++ b/universes/committed.yaml @@ -42,6 +42,7 @@ analyses: psf_modelling_software: psfex psf_model_complexity: pixel_basis_deg2_per_ccd psf_acceptance_thresholds: stars22_chi2_2 + psf_stamp_rendering: centred shape_measurement: decisions: ngmix_seed_mode: position_seed diff --git a/workflow/config/cfis/config_exp_psfex.ini b/workflow/config/cfis/config_exp_psfex.ini index 05382bb16..f7632a1a4 100644 --- a/workflow/config/cfis/config_exp_psfex.ini +++ b/workflow/config/cfis/config_exp_psfex.ini @@ -232,3 +232,9 @@ STAR_THRESH = 22 # Maximum chi^2 for PSF model to be computed on CCD # @sc [decision:star_selection_psf.psf_acceptance_thresholds] CHI2_THRESH = 2 + +# PSFs are native-pixel stamps whatever the model's PSF_SAMPLING. If True, +# each is rendered at the sub-pixel phase of the star's SExtractor VIGNET +# (validation); if False, centred. +# @sc [decision:star_selection_psf.psf_stamp_rendering] +STAMP_PHASE = False diff --git a/workflow/config/cfis/config_tile_PiViVi_psfex.ini b/workflow/config/cfis/config_tile_PiViVi_psfex.ini index 66cc25507..0b6b29a71 100644 --- a/workflow/config/cfis/config_tile_PiViVi_psfex.ini +++ b/workflow/config/cfis/config_tile_PiViVi_psfex.ini @@ -108,6 +108,12 @@ STAR_THRESH = 22 # @sc [decision:star_selection_psf.psf_acceptance_thresholds] CHI2_THRESH = 2 +# PSFs are native-pixel stamps whatever the model's PSF_SAMPLING. If True, +# each is rendered at the sub-pixel phase of each epoch's galaxy stamp +# (the vignetmaker OFFSET); if False, centred. +# @sc [decision:star_selection_psf.psf_stamp_rendering] +STAMP_PHASE = False + # Multi-epoch mode parameters # Root of per-exposure work directories. Discover psfex_runner/output/ dirs From a136edae6d7bf99741f1e32e515017f6db9babb9 Mon Sep 17 00:00:00 2001 From: Cail Daley Date: Mon, 23 Nov 2026 20:24:39 -0700 Subject: [PATCH 2/3] config(psfex): 0.7-pixel PSFEx sampling (73x73) with validation phase rendering (#989) --- astra.yaml | 31 ++++++++++++----------- tests/module/test_psfex_interp.py | 6 ++--- universes/committed.yaml | 2 +- workflow/config/cfis/config_exp_psfex.ini | 2 +- workflow/config/cfis/default.psfex | 4 +-- 5 files changed, 23 insertions(+), 22 deletions(-) diff --git a/astra.yaml b/astra.yaml index ab7ca16b9..77364c724 100644 --- a/astra.yaml +++ b/astra.yaml @@ -134,7 +134,7 @@ decisions: default_noimaflags.param#VIGNET = 51; default.param#VIGNET = 51; VIGNETMAKER_RUNNER.STAMP_SIZE = 51; - PSF_SIZE = 51. + PSF_SIZE = 73. default: px_51 options: px_51: @@ -1184,24 +1184,23 @@ 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 with degree-2 spatial variation per CCD at 0.7-pixel sampling 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. + at 0.7-pixel sampling (PSF_SAMPLING = 0.7, PSF_SIZE = 73,73, spanning + the same 51-pixel native stamp). Unit sampling leaves a -0.66% mean + size residual and a -4e-3 g1 residual below 0.5" seeing (shapepipe#989), + while exact 0.5-pixel sampling decouples into four subgrids that + overfit sparse high-latitude CCDs (22-45 stars/CCD). Non-commensurate + 0.7-pixel sampling couples adjacent model pixels through Lanczos-3, + eliminating the Nyquist checkerboard mode while removing the size and + sharp-seeing residuals. Values: BASIS_TYPE = PIXEL; PSF_ACCURACY = 0.01; BASIS_NUMBER = 20; PSFVAR_DEGREES = 2; - PSF_SAMPLING = 1; + PSF_SAMPLING = 0.7; PSFVAR_KEYS = XWIN_IMAGE,YWIN_IMAGE; PSFVAR_GROUPS = 1,1; MEF_TYPE = INDEPENDENT. @@ -1275,12 +1274,14 @@ analyses: centre, a sub-pixel offset from the ngmix centroid prior (sigma 1 px); its effect on shear is unmeasured. Values: - config_exp_psfex.ini#PSFEX_INTERP_RUNNER.STAMP_PHASE = False; + config_exp_psfex.ini#PSFEX_INTERP_RUNNER.STAMP_PHASE = True; config_tile_PiViVi_psfex.ini#PSFEX_INTERP_RUNNER.STAMP_PHASE = False. - default: centred + default: validation_phase_galaxy_centred options: centred: - label: PSF centred on the native stamp + label: PSF centred on the native stamp on both paths + validation_phase_galaxy_centred: + label: Validation PSFs at star VIGNET phase; galaxy PSFs centred for multi-epoch ngmix registration stamp_phase: label: PSF at the sub-pixel phase of the star VIGNET or galaxy stamp prior_insights: diff --git a/tests/module/test_psfex_interp.py b/tests/module/test_psfex_interp.py index fc236adc4..d14afd187 100644 --- a/tests/module/test_psfex_interp.py +++ b/tests/module/test_psfex_interp.py @@ -311,7 +311,7 @@ def test_unit_sampling_centred_returns_raw_grid(tmp_path): @pytest.mark.decision("star_selection_psf.psf_stamp_rendering") -@pytest.mark.parametrize("sampling, n_model", [(0.5, 101), (1.0, 51)]) +@pytest.mark.parametrize("sampling, n_model", [(0.5, 101), (0.7, 73), (1.0, 51)]) @pytest.mark.parametrize("offset", [(0.0, 0.0), (0.3, -0.45)]) def test_native_stamp_matches_analytic_rendering( tmp_path, sampling, n_model, offset @@ -338,7 +338,7 @@ def test_native_stamp_matches_analytic_rendering( assert stamp.shape == (51, 51) npt.assert_allclose(stamp.sum(), truth.sum(), rtol=1e-3) - tol = 5e-5 if offset == (0.0, 0.0) else 5e-3 + tol = 5e-5 if (offset == (0.0, 0.0) and sampling in (0.5, 1.0)) else 5e-3 got, want = _hsm(stamp), _hsm(truth) npt.assert_allclose( got.moments_sigma, want.moments_sigma, rtol=tol @@ -356,7 +356,7 @@ def test_native_stamp_matches_analytic_rendering( @pytest.mark.decision("star_selection_psf.psf_stamp_rendering") -@pytest.mark.parametrize("sampling, n_model", [(0.5, 101), (1.0, 51)]) +@pytest.mark.parametrize("sampling, n_model", [(0.5, 101), (0.7, 73), (1.0, 51)]) def test_phase_moves_centroid_by_offset(sampling, n_model): """A phase offset moves the stamp centroid by that offset. diff --git a/universes/committed.yaml b/universes/committed.yaml index 39d56d8e5..45b359f78 100644 --- a/universes/committed.yaml +++ b/universes/committed.yaml @@ -42,7 +42,7 @@ analyses: psf_modelling_software: psfex psf_model_complexity: pixel_basis_deg2_per_ccd psf_acceptance_thresholds: stars22_chi2_2 - psf_stamp_rendering: centred + psf_stamp_rendering: validation_phase_galaxy_centred shape_measurement: decisions: ngmix_seed_mode: position_seed diff --git a/workflow/config/cfis/config_exp_psfex.ini b/workflow/config/cfis/config_exp_psfex.ini index f7632a1a4..737589bf1 100644 --- a/workflow/config/cfis/config_exp_psfex.ini +++ b/workflow/config/cfis/config_exp_psfex.ini @@ -237,4 +237,4 @@ CHI2_THRESH = 2 # each is rendered at the sub-pixel phase of the star's SExtractor VIGNET # (validation); if False, centred. # @sc [decision:star_selection_psf.psf_stamp_rendering] -STAMP_PHASE = False +STAMP_PHASE = True diff --git a/workflow/config/cfis/default.psfex b/workflow/config/cfis/default.psfex index 840f1ddfd..4be49ca86 100644 --- a/workflow/config/cfis/default.psfex +++ b/workflow/config/cfis/default.psfex @@ -14,13 +14,13 @@ NEWBASIS_TYPE NONE # Create new basis: NONE, PCA_INDEPENDENT # or PCA_COMMON NEWBASIS_NUMBER 8 # Number of new basis vectors # @sc [decision:star_selection_psf.psf_model_complexity] -PSF_SAMPLING 1. # Sampling step in pixel units (0.0 = auto) +PSF_SAMPLING 0.7 # Sampling step in pixel units (0.0 = auto) PSF_PIXELSIZE 1.0 # Effective pixel size in pixel step units # @sc [decision:star_selection_psf.psf_model_complexity] PSF_ACCURACY 0.01 # Accuracy to expect from PSF "pixel" values # @sc [decision:postage_stamp_size] -PSF_SIZE 51,51 # Image size of the PSF model +PSF_SIZE 73,73 # Image size of the PSF model # @sc [decision:star_selection_psf.psfex_candidate_vetting] PSF_RECENTER N # Allow recentering of PSF-candidates Y/N ? # @sc [decision:star_selection_psf.psf_model_complexity] From ab967ef08d17e47576f81ecdab6bca23bf6c6b96 Mon Sep 17 00:00:00 2001 From: Cail Daley Date: Mon, 23 Nov 2026 23:16:16 -0700 Subject: [PATCH 3/3] Keep Run 1 defaults reproducible; add named default_0p7.psfex and psfex_config switch --- astra.yaml | 33 +++---- tests/module/test_psfex_interp.py | 44 +++++++++ universes/committed.yaml | 2 +- workflow/Snakefile | 24 +++-- workflow/config.yaml | 5 ++ workflow/config/cfis/config_exp_psfex.ini | 14 +-- workflow/config/cfis/default.psfex | 4 +- workflow/config/cfis/default_0p7.psfex | 105 ++++++++++++++++++++++ workflow/rules/exposure.smk | 6 +- 9 files changed, 203 insertions(+), 34 deletions(-) create mode 100644 workflow/config/cfis/default_0p7.psfex diff --git a/astra.yaml b/astra.yaml index 77364c724..dcfec48f3 100644 --- a/astra.yaml +++ b/astra.yaml @@ -134,7 +134,7 @@ decisions: default_noimaflags.param#VIGNET = 51; default.param#VIGNET = 51; VIGNETMAKER_RUNNER.STAMP_SIZE = 51; - PSF_SIZE = 73. + PSF_SIZE = 51. default: px_51 options: px_51: @@ -1184,23 +1184,24 @@ 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 at 0.7-pixel sampling + label: PSFEx pixel basis with degree-2 spatial variation per CCD (1.0 default, 0.7 named Run-2 config) rationale: >- - A pixel basis with polynomial variation in XWIN/YWIN, fit per CCD - at 0.7-pixel sampling (PSF_SAMPLING = 0.7, PSF_SIZE = 73,73, spanning - the same 51-pixel native stamp). Unit sampling leaves a -0.66% mean - size residual and a -4e-3 g1 residual below 0.5" seeing (shapepipe#989), - while exact 0.5-pixel sampling decouples into four subgrids that - overfit sparse high-latitude CCDs (22-45 stars/CCD). Non-commensurate - 0.7-pixel sampling couples adjacent model pixels through Lanczos-3, - eliminating the Nyquist checkerboard mode while removing the size and - sharp-seeing residuals. + A pixel basis with polynomial variation in XWIN/YWIN, fit per CCD. + The committed default (default.psfex: PSF_SAMPLING = 1, PSF_SIZE = 51) + preserves Run 1 reproducibility; a named Run-2 config + (default_0p7.psfex: PSF_SAMPLING = 0.7, PSF_SIZE = 73, selected via + psfex_config in the workflow run config) oversamples the model while + spanning the same 51-pixel native stamp. Unit sampling leaves a -0.77% + centred size bias at 0.55-0.65" seeing and a -3.9e-3 g1 residual below + 0.5" seeing (shapepipe#989); 0.5-pixel sampling degrades PSF recovery + on sparse high-latitude CCDs; 0.7 sits at an empirical zero-crossing + of the centred-render size bias across seeings and star counts. Values: BASIS_TYPE = PIXEL; PSF_ACCURACY = 0.01; BASIS_NUMBER = 20; PSFVAR_DEGREES = 2; - PSF_SAMPLING = 0.7; + PSF_SAMPLING = 1 (default.psfex) or 0.7 (default_0p7.psfex); PSFVAR_KEYS = XWIN_IMAGE,YWIN_IMAGE; PSFVAR_GROUPS = 1,1; MEF_TYPE = INDEPENDENT. @@ -1274,14 +1275,14 @@ analyses: centre, a sub-pixel offset from the ngmix centroid prior (sigma 1 px); its effect on shear is unmeasured. Values: - config_exp_psfex.ini#PSFEX_INTERP_RUNNER.STAMP_PHASE = True; + config_exp_psfex.ini#PSFEX_INTERP_RUNNER.STAMP_PHASE = False; config_tile_PiViVi_psfex.ini#PSFEX_INTERP_RUNNER.STAMP_PHASE = False. - default: validation_phase_galaxy_centred + default: centred options: centred: - label: PSF centred on the native stamp on both paths + label: PSF centred on the native stamp on both paths (validates the exact galaxy-path PSF) validation_phase_galaxy_centred: - label: Validation PSFs at star VIGNET phase; galaxy PSFs centred for multi-epoch ngmix registration + label: Validation PSFs at star VIGNET phase (PSFEx diagnostic); galaxy PSFs centred stamp_phase: label: PSF at the sub-pixel phase of the star VIGNET or galaxy stamp prior_insights: diff --git a/tests/module/test_psfex_interp.py b/tests/module/test_psfex_interp.py index d14afd187..3189b9f03 100644 --- a/tests/module/test_psfex_interp.py +++ b/tests/module/test_psfex_interp.py @@ -386,3 +386,47 @@ def test_sextractor_vignet_offsets_round_the_barycentre(): npt.assert_allclose( sextractor_vignet_offsets(pos, barycentre), [[0.52, 0.0]] ) + + +def test_psfex_config_switch_preserves_run1_default_and_exposes_0p7(monkeypatch): + """Default config reproduces Run 1 (default.psfex, centred validation); + SP_PSFEX_CONFIG selects default_0p7.psfex for Run 2.""" + from pathlib import Path + from shapepipe.pipeline.config import CustomParser + + config_dir = ( + Path(__file__).resolve().parents[2] / "workflow" / "config" / "cfis" + ) + assert (config_dir / "default.psfex").is_file() + assert (config_dir / "default_0p7.psfex").is_file() + + def _psfex_kv(path): + out = {} + for line in path.read_text().splitlines(): + line = line.split("#", 1)[0].strip() + if line: + k, *v = line.split() + if v: + out[k] = v[0] + return out + + kv_run1 = _psfex_kv(config_dir / "default.psfex") + kv_run2 = _psfex_kv(config_dir / "default_0p7.psfex") + assert float(kv_run1["PSF_SAMPLING"]) == 1.0 + assert kv_run1["PSF_SIZE"] == "51,51" + assert float(kv_run2["PSF_SAMPLING"]) == 0.7 + assert kv_run2["PSF_SIZE"] == "73,73" + + parser = CustomParser() + parser.read(config_dir / "config_exp_psfex.ini") + monkeypatch.setenv("SP_CONFIG", str(config_dir)) + monkeypatch.delenv("SP_PSFEX_CONFIG", raising=False) + assert parser.getexpanded("PSFEX_RUNNER", "DOT_PSFEX_FILE") == str( + config_dir / "default.psfex" + ) + assert parser.getboolean("PSFEX_INTERP_RUNNER", "STAMP_PHASE") is False + + monkeypatch.setenv("SP_PSFEX_CONFIG", "default_0p7.psfex") + assert parser.getexpanded("PSFEX_RUNNER", "DOT_PSFEX_FILE") == str( + config_dir / "default_0p7.psfex" + ) diff --git a/universes/committed.yaml b/universes/committed.yaml index 45b359f78..39d56d8e5 100644 --- a/universes/committed.yaml +++ b/universes/committed.yaml @@ -42,7 +42,7 @@ analyses: psf_modelling_software: psfex psf_model_complexity: pixel_basis_deg2_per_ccd psf_acceptance_thresholds: stars22_chi2_2 - psf_stamp_rendering: validation_phase_galaxy_centred + psf_stamp_rendering: centred shape_measurement: decisions: ngmix_seed_mode: position_seed diff --git a/workflow/Snakefile b/workflow/Snakefile index bb7c32933..b2744f1c2 100644 --- a/workflow/Snakefile +++ b/workflow/Snakefile @@ -191,15 +191,23 @@ if BLEND_HANDLING not in run_config.BLEND_HANDLINGS: f"Invalid blend_handling={BLEND_HANDLING!r}; expected one of " f"{sorted(run_config.BLEND_HANDLINGS)}.") -# The committed inis read SP_SEG_VIGNET and SP_BLEND_HANDLING with the modules' -# own defaults, and only tile.smk's blend_env exports them (SP_BLEND_HANDLING -# under uberseg, the workflow's default). Drop any copy the -# launching shell carries, bare or as the APPTAINERENV_/SINGULARITYENV_ forms -# that survive --cleanenv, so a job inherits none: the slurm executor submits -# with --export=ALL from this process's environment, and each job re-parses -# this file before its shell runs. +# PSFEx config file under CONFIG_DIR (default.psfex = Run 1 unit sampling; +# default_0p7.psfex = Run 2 0.7-pixel sampling). Exported to exp_psf as +# SP_PSFEX_CONFIG only when non-default so Run-1 params stay unchanged. +PSFEX_CONFIG = config.get("psfex_config") or "default.psfex" +if PSF_MODEL == "psfex" and not (CONFIG_DIR / PSFEX_CONFIG).is_file(): + raise WorkflowError( + f"Invalid psfex_config={PSFEX_CONFIG!r}: " + f"{CONFIG_DIR / PSFEX_CONFIG} does not exist.") + +# The committed inis read SP_SEG_VIGNET, SP_BLEND_HANDLING and SP_PSFEX_CONFIG +# with the modules' own defaults, and only the owning rules export them. Drop +# any copy the launching shell carries, bare or as the +# APPTAINERENV_/SINGULARITYENV_ forms that survive --cleanenv, so a job +# inherits none: the slurm executor submits with --export=ALL from this +# process's environment, and each job re-parses this file before its shell runs. for _prefix in ("", "APPTAINERENV_", "SINGULARITYENV_"): - for _name in ("SP_SEG_VIGNET", "SP_BLEND_HANDLING"): + for _name in ("SP_SEG_VIGNET", "SP_BLEND_HANDLING", "SP_PSFEX_CONFIG"): os.environ.pop(_prefix + _name, None) # SP_PHASE is set by bin/sp and NOWHERE else: `prepare`/`compute` on the two diff --git a/workflow/config.yaml b/workflow/config.yaml index d8fa2ac45..6f1209936 100644 --- a/workflow/config.yaml +++ b/workflow/config.yaml @@ -225,6 +225,11 @@ ngmix_chunks: 8 # interpolate. # defect_fill: noise +# PSFEx configuration file under workflow/config// (exp_psf). +# Unset: default.psfex (Run 1: PSF_SAMPLING 1.0, PSF_SIZE 51,51). +# Set default_0p7.psfex for Run 2 (PSF_SAMPLING 0.7, PSF_SIZE 73,73). +# psfex_config: default_0p7.psfex + # Tile store (vignets, WCS). Unset: the profile's /local/scratch bind (nibi # node NVMe; candide a shared NFS directory, see profiles/candide/config.yaml). # tile_store_root: /n23data1//shapepipe/tilestore diff --git a/workflow/config/cfis/config_exp_psfex.ini b/workflow/config/cfis/config_exp_psfex.ini index 737589bf1..e4e165abe 100644 --- a/workflow/config/cfis/config_exp_psfex.ini +++ b/workflow/config/cfis/config_exp_psfex.ini @@ -199,8 +199,9 @@ NUMBERING_SCHEME = -0000000-0 # Path to executable for the PSF model (optional) EXEC_PATH = psfex -# Default psfex configuration file -DOT_PSFEX_FILE = $SP_CONFIG/default.psfex +# PSFEx configuration file (workflow sets SP_PSFEX_CONFIG from `psfex_config`; +# unset takes default.psfex for Run 1, set default_0p7.psfex for Run 2). +DOT_PSFEX_FILE = $SP_CONFIG/${SP_PSFEX_CONFIG:-default.psfex} [PSFEX_INTERP_RUNNER] @@ -233,8 +234,9 @@ STAR_THRESH = 22 # @sc [decision:star_selection_psf.psf_acceptance_thresholds] CHI2_THRESH = 2 -# PSFs are native-pixel stamps whatever the model's PSF_SAMPLING. If True, -# each is rendered at the sub-pixel phase of the star's SExtractor VIGNET -# (validation); if False, centred. +# PSFs are native-pixel stamps whatever the model's PSF_SAMPLING. False +# (centred) matches the PSF stamp handed to ngmix on the galaxy path so +# full_starcat rho/tau and xi_sys measure the galaxy-path PSF error; True +# renders at the star's SExtractor VIGNET phase for PSFEx model diagnostics. # @sc [decision:star_selection_psf.psf_stamp_rendering] -STAMP_PHASE = True +STAMP_PHASE = False diff --git a/workflow/config/cfis/default.psfex b/workflow/config/cfis/default.psfex index 4be49ca86..840f1ddfd 100644 --- a/workflow/config/cfis/default.psfex +++ b/workflow/config/cfis/default.psfex @@ -14,13 +14,13 @@ NEWBASIS_TYPE NONE # Create new basis: NONE, PCA_INDEPENDENT # or PCA_COMMON NEWBASIS_NUMBER 8 # Number of new basis vectors # @sc [decision:star_selection_psf.psf_model_complexity] -PSF_SAMPLING 0.7 # Sampling step in pixel units (0.0 = auto) +PSF_SAMPLING 1. # Sampling step in pixel units (0.0 = auto) PSF_PIXELSIZE 1.0 # Effective pixel size in pixel step units # @sc [decision:star_selection_psf.psf_model_complexity] PSF_ACCURACY 0.01 # Accuracy to expect from PSF "pixel" values # @sc [decision:postage_stamp_size] -PSF_SIZE 73,73 # Image size of the PSF model +PSF_SIZE 51,51 # Image size of the PSF model # @sc [decision:star_selection_psf.psfex_candidate_vetting] PSF_RECENTER N # Allow recentering of PSF-candidates Y/N ? # @sc [decision:star_selection_psf.psf_model_complexity] diff --git a/workflow/config/cfis/default_0p7.psfex b/workflow/config/cfis/default_0p7.psfex new file mode 100644 index 000000000..b0581fa02 --- /dev/null +++ b/workflow/config/cfis/default_0p7.psfex @@ -0,0 +1,105 @@ +# PSFEx 3.17.1 configuration for 0.7-pixel oversampled PSF models (Run 2). +# Identical to default.psfex except PSF_SAMPLING (0.7) and PSF_SIZE (73,73), +# spanning the same 51-pixel native stamp (floor(73 * 0.7) = 51). +# Select in a campaign run config with: psfex_config: default_0p7.psfex +# + +#-------------------------------- PSF model ---------------------------------- + +# @sc [decision:star_selection_psf.psf_model_complexity] +BASIS_TYPE PIXEL # NONE, PIXEL, GAUSS-LAGUERRE or FILE +BASIS_NUMBER 20 # Basis number or parameter + +BASIS_NAME basis.fits # Basis filename (FITS data-cube) +BASIS_SCALE 1.0 # Gauss-Laguerre beta parameter +NEWBASIS_TYPE NONE # Create new basis: NONE, PCA_INDEPENDENT + # or PCA_COMMON +NEWBASIS_NUMBER 8 # Number of new basis vectors +# @sc [decision:star_selection_psf.psf_model_complexity] +PSF_SAMPLING 0.7 # Sampling step in pixel units (0.0 = auto) + +PSF_PIXELSIZE 1.0 # Effective pixel size in pixel step units +# @sc [decision:star_selection_psf.psf_model_complexity] +PSF_ACCURACY 0.01 # Accuracy to expect from PSF "pixel" values +# @sc [decision:postage_stamp_size] +PSF_SIZE 73,73 # Image size of the PSF model +# @sc [decision:star_selection_psf.psfex_candidate_vetting] +PSF_RECENTER N # Allow recentering of PSF-candidates Y/N ? +# @sc [decision:star_selection_psf.psf_model_complexity] +MEF_TYPE INDEPENDENT # INDEPENDENT or COMMON + +#------------------------- Point source measurements ------------------------- + +# @sc [decision:preparation.object_position_columns] +CENTER_KEYS XWIN_IMAGE,YWIN_IMAGE # Catalogue parameters for source pre-centering +# @sc [decision:detection.photometry_parameters] +PHOTFLUX_KEY FLUX_AUTO # Catalogue parameter for photometric norm. +# @sc [decision:detection.photometry_parameters] +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 +# @sc [decision:star_selection_psf.psf_model_complexity] +PSFVAR_GROUPS 1,1 # Group tag for each context key +# @sc [decision:star_selection_psf.psf_model_complexity] +PSFVAR_DEGREES 2 # Polynom degree for each group + +PSFVAR_NSNAP 9 # Number of PSF snapshots per axis +HIDDENMEF_TYPE COMMON # INDEPENDENT or COMMON +STABILITY_TYPE EXPOSURE # EXPOSURE or SEQUENCE + +#----------------------------- Sample selection ------------------------------ + +# @sc [decision:star_selection_psf.star_selection_box,decision:star_selection_psf.psfex_candidate_vetting] +SAMPLE_AUTOSELECT N # Automatically select the FWHM (Y/N) ? + +# @sc [decision:star_selection_psf.psfex_candidate_vetting] +BADPIXEL_FILTER N # Filter bad-pixels in samples (Y/N) ? + +BADPIXEL_NMAX 0 # Maximum number of bad pixels allowed + +#----------------------- PSF homogeneisation kernel -------------------------- + +HOMOBASIS_TYPE NONE # NONE or GAUSS-LAGUERRE +HOMOBASIS_NUMBER 10 # Kernel basis number or parameter +HOMOBASIS_SCALE 1.0 # GAUSS-LAGUERRE beta parameter +HOMOPSF_PARAMS 2.0, 3.0 # Moffat parameters of the idealised PSF +HOMOKERNEL_DIR # Where to write kernels (empty=same as input) +HOMOKERNEL_SUFFIX .homo.fits # Filename extension for homogenisation kernels + +#----------------------------- Output catalogs ------------------------------- + +OUTCAT_TYPE FITS_LDAC # NONE, ASCII_HEAD, ASCII, FITS_LDAC + +#------------------------------- Check-plots ---------------------------------- + +CHECKPLOT_DEV NULL # NULL, XWIN, TK, PS, PSC, XFIG, PNG, + # JPEG, AQT, PDF or SVG +CHECKPLOT_RES 0 # Check-plot resolution (0 = default) +CHECKPLOT_ANTIALIAS Y # Anti-aliasing using convert (Y/N) ? +CHECKPLOT_TYPE NONE # FWHM,ELLIPTICITY,COUNTS, COUNT_FRACTION, CHI2, RESIDUALS +CHECKPLOT_TYPE FWHM,ELLIPTICITY,COUNTS, COUNT_FRACTION, CHI2, RESIDUALS + # or NONE +CHECKPLOT_NAME fwhm, ellipticity, counts, countfrac, chi2, resi + +#------------------------------ Check-Images --------------------------------- + +# Note: Check-image types can be set the ShapePipe config file, psfex_runner section +####### +CHECKIMAGE_TYPE NONE # CHI,PROTOTYPES,SAMPLES,RESIDUALS,SNAPSHOTS + # or MOFFAT,-MOFFAT,-SYMMETRICAL +#CHECKIMAGE_NAME chi.fits,proto.fits,samp.fits,resi.fits,snap.fits + # Check-image filenames +#CHECKIMAGE_CUBE N # Save check-images as datacubes (Y/N) ? + +#----------------------------- Miscellaneous --------------------------------- + +PSF_SUFFIX .psf # Filename extension for output PSF filename +VERBOSE_TYPE NORMAL # can be QUIET,NORMAL,LOG or FULL +WRITE_XML N # Write XML file (Y/N)? + +NTHREADS 1 # Number of simultaneous threads for + # the SMP version of PSFEx + # 0 = automatic diff --git a/workflow/rules/exposure.smk b/workflow/rules/exposure.smk index f07b1ecff..baa2b993c 100644 --- a/workflow/rules/exposure.smk +++ b/workflow/rules/exposure.smk @@ -87,7 +87,11 @@ rule exp_psf: log: f"{EXP_DIR}/logs/exp_psf.json" params: - pre = lambda wc: unit_pre("exp_psf", wc.exp), + pre = lambda wc: unit_pre( + "exp_psf", wc.exp, + env=({"SP_PSFEX_CONFIG": PSFEX_CONFIG} + if PSF_MODEL == "psfex" and PSFEX_CONFIG != "default.psfex" + else None)), script_hash = SCRIPT_HASH threads: 2 if PSF_MODEL == "mccd" else 8 retries: 2