From ea34ff18d3393517b0856667adb941d328b34ed9 Mon Sep 17 00:00:00 2001 From: Cail Daley Date: Thu, 29 Oct 2026 14:36:46 -0400 Subject: [PATCH 1/7] Register tile categories on native exposure stamp grids Sample full-tile labels through the independent WCSs at image INT_POS pixel centres. Store segmentation, neighbours and off-tile maps with each image epoch and consume them before ngmix masks, cuts and diagnostics. Keep native images unchanged and fail on missing categories. Preserve pre-join labels as SEG_LABEL and strip this bookkeeping from final catalogues. Define noisefill neighbours from full foreign segmentation footprints so category coverage does not depend on finite tile VIGNET markers. Cover independent astrometry, categorical sampling, joined labels, tile edges, the retained 188.307 example and a killed flip-only-overlay mutant. Record the convention in ASTRA and the workflow documentation. --- astra.yaml | 83 ++--- docs/source/workflow.md | 26 ++ .../config_tile_PiViVi_canfar_sx.ini | 42 +-- example/cfis_image_sims/config_tile_Sx.ini | 3 + .../validation/masked_pixels/dr6_epochs.py | 44 +-- .../masked_pixels/tile_defect_flags.py | 20 +- .../modules/make_cat_package/make_cat.py | 6 +- src/shapepipe/modules/ngmix_package/ngmix.py | 148 +++----- .../sextractor_package/sextractor_script.py | 13 +- .../vignetmaker_package/vignetmaker.py | 92 ++++- src/shapepipe/modules/vignetmaker_runner.py | 9 +- tests/data/registration_188307.md | 18 + tests/data/registration_188307.npz | Bin 0 -> 15677 bytes tests/module/test_categorical_registration.py | 345 ++++++++++++++++++ tests/module/test_ngmix_defect_fill.py | 36 +- tests/module/test_ngmix_defect_flags.py | 13 +- tests/module/test_ngmix_uberseg.py | 4 +- tests/module/test_sextractor_seg_vignet.py | 7 +- tests/mutations/flip_only_overlay.py | 61 ++++ universes/committed.yaml | 2 +- .../config/cfis/config_tile_PiViVi_mccd.ini | 4 +- .../config/cfis/config_tile_PiViVi_psfex.ini | 4 +- .../config_tile_PiViVi_fake.ini | 4 +- 23 files changed, 748 insertions(+), 236 deletions(-) create mode 100644 tests/data/registration_188307.md create mode 100644 tests/data/registration_188307.npz create mode 100644 tests/module/test_categorical_registration.py create mode 100644 tests/mutations/flip_only_overlay.py diff --git a/astra.yaml b/astra.yaml index d93c2067c..f8be0dcbf 100644 --- a/astra.yaml +++ b/astra.yaml @@ -857,7 +857,7 @@ analyses: decisions: [astrometric_solution_source, ccd_split_extent, epoch_provenance_from_tile_history, object_position_columns, - stamp_positioning_and_padding] + stamp_positioning_and_padding, categorical_registration] decisions: astrometric_solution_source: label: Astrometry taken verbatim from delivered per-CCD headers @@ -942,6 +942,26 @@ analyses: it sits 0.16 px (median) and 1.6 px (p99) from it for 20 < MAG_AUTO < 24.5, and the image simulations measure the windowed one. + categorical_registration: + label: Tile categories sampled on each native exposure grid + rationale: >- + [HARDCODED] Vignetmaker maps exposure-stamp pixel centres through the + independent exposure and tile WCSs, using the image's rounded INT_POS. + The full tile segmentation is sampled nearest-neighbour with + floor(x+0.5), so half-cell ties go to the higher index. This preserves + categorical labels without smoothing or resampling native images. + SEG_LABEL retains pre-join labels; joined NUMBERs label targets and + -1 labels detections absent from the joined catalogue. Off-tile means + the nearest tile cell is outside the full segmentation image. + Noisefill neighbours are all foreign nonzero segmentation pixels, + with full-tile support independent of VIGNET's marker coverage. + UberSeg recomputes its Voronoi partition on the registered labels. + These maps enter ngmix before masks, cuts and footprint diagnostics. + A flip alone cannot register independent pixel grids and centroids. + default: native_grid_nearest + options: + native_grid_nearest: + label: Full tile categories projected to native exposure centres stamp_positioning_and_padding: label: Nearest-pixel stamp extraction with zero padding rationale: >- @@ -1363,7 +1383,7 @@ analyses: [ngmix_seed_mode, galaxy_model, fit_initialisation, fit_priors, metacal_scheme, centroid_source, epoch_flux_rescaling, psf_epoch_averaging, galaxy_pixel_weights, psf_likelihood_noise, - megacam_ccd_flip, defect_fill, blend_handling, + defect_fill, blend_handling, defect_weighting, epoch_masked_fraction_cut, central_defect_veto, defect_flagging] decisions: @@ -1548,24 +1568,12 @@ analyses: options: psf_noise_1em5: label: PSF_NOISE 1e-5 - megacam_ccd_flip: - label: 180-degree rotation of tile vignets for CCDs below 18 and 36-37 - rationale: >- - [HARDCODED] "MegaPipe has CCDs that are upside down": the tile vignet - and segmentation stamp are rotated to register with the epoch stamp. - A wrong flip mis-registers the tile coverage flag against the epoch, - changing flagged pixels and the masked-fraction cut. The docstring - warns it is wrong for THELI CCDs. - default: megapipe_flip - options: - megapipe_flip: - label: Flip CCDs < 18 and 36/37 (MegaPipe orientation) defect_flagging: label: Adaptive exposure defects on tile objects rationale: >- [HARDCODED] We retain every instrument bit by OR'ing exposure flag - pixels on the object's coadd footprint (seg == obj_id), flipped to - each epoch, across epochs kept after the fraction cut and central + pixels on the object's tile footprint (seg == obj_id), sampled on + each exposure grid, across epochs kept after the fraction cut and central veto. NGMIX_IMAFLAGS_ISO invents no bit for unflagged zero-weight or off-tile pixels. NGMIX_N_EPOCH_INTERP_ISO counts kept epochs with an interpolated defect on that footprint, including those @@ -1575,8 +1583,8 @@ analyses: collaboration decision requests adaptive exposure flags propagated to tile objects. Stamp-wide diagnostics count a distant defect equally for small and large objects. The coadd footprint avoids - exposure detection matching; it is not reprojected, consistent with - the existing segmentation overlay. These columns impose no cut + exposure detection matching; labels are projected through both WCSs + before any epoch cut. These columns impose no cut and do not alter the fits. default: footprint_or_and_interp_epochs options: @@ -1703,40 +1711,29 @@ analyses: mask_blend_bias_detection). Noise-filling the neighbour side would instead cut the target's own light along an unsheared boundary, a sharp edge that rings in the FFTs. The alternative, noisefill - (ngmix's own default, and the workflow's blend_handling: - noisefill), gives weight 0 to the pixels marked -1e30 in the tile - VIGNET (about 93% of neighbour-footprint pixels on a simulated - tile), excluding the off-tile rows and columns, which are defects, - and replaces them with noise; unmarked neighbour pixels keep their - weight and light. Under both handlings the neighbours are defined - by the coadd segmentation map: a marker counts only on a footprint - labelled neither 0 nor the target. SExtractor's MASK_TYPE CORRECT - also marks sub-MINAREA sky blobs and fragments CLEAN merged into - the target, which the seg labels as sky or as the target; noise- - filling those removed the target's own light (15% of - NEIGHBOUR_FLAG = 0 objects differed between the arms on 25 tiles). - tile_detect therefore writes SEG_VIGNET under both handlings. - Uberseg reads no marker, so its output is unchanged. It is - the comparison arm, with defect_fill held equal across arms. + (ngmix's own default), gives weight 0 to every foreign nonzero + segmentation footprint sampled on the exposure grid and replaces + its light with noise. Off-tile cells are defects, not neighbours. + Both handlings use the full tile segmentation, independent of the + finite VIGNET marker support. CLEAN-merged own fragments and sky + blobs retain their light because their labels are own or zero. + The workflow selects uberseg, with defect_fill held independently. default: uberseg options: noisefill: label: Noise-fill the marked neighbour pixels (BLEND_HANDLING = noisefill) description: >- - Pixels marked -1e30 in the tile VIGNET get weight 0 and noise. - The fill stops at the marked footprint, so unmarked neighbour - pixels and the neighbour's wings keep their weight and light, - which biases shapes toward neighbours (Jarvis et al. 2016). A - candidate cause of the FLAGS=2 B-modes - investigated in #814. + Foreign nonzero segmentation footprints on the exposure grid + get weight 0 and noise. The neighbour's unsegmented wings retain + their weight and light, leaving residual neighbour contamination + (Jarvis et al. 2016). insights: [mask_uberseg_neighbour_bias] uberseg: label: UberSeg, weight-only description: >- - As in DES Y1/Y3. Needs the coadd segmentation stamp (the tile - catalogue's SEG_VIGNET). DILATE_NEIGHBOUR absorbs the coadd-vs-epoch - overlay offset: ShapePipe reuses one coadd seg stamp for every - epoch where MEDS reprojects it. + As in DES Y1/Y3. Uses the full tile segmentation sampled on each + exposure grid. DILATE_NEIGHBOUR expands the neighbour side after + computing the Voronoi partition on the registered labels. insights: [mask_uberseg_weight_only, mask_uberseg_neighbour_bias, mask_des_y1_uberseg_only, mask_blend_bias_detection] uberseg_fill: label: UberSeg plus noise fill of neighbour-side pixels diff --git a/docs/source/workflow.md b/docs/source/workflow.md index 196aeeb46..58dff754c 100644 --- a/docs/source/workflow.md +++ b/docs/source/workflow.md @@ -50,6 +50,32 @@ recognise passes straight through to snakemake with the right profile and state directory, which is the escape hatch for `sp --unlock`, `sp --dag` or `sp exp_psf ...`. +## Exposure-grid categories + +Tile detection writes `SEG_LABEL`, the segmentation check-image label before the catalogue join, alongside `SEG_VIGNET`. +The join changes `NUMBER` and the tile segmentation stamps but retains `SEG_LABEL`. +The multi-epoch vignetmaker takes `segmentation` as its fourth positional input, after `sexcat`, `log_exp_headers` and `exp_numbers`. +It maps the full segmentation labels to catalogue `NUMBER`s; detections absent from the joined catalogue have label −1 and sky has label 0. + +Each `image_vignet` epoch entry contains three categorical arrays with the image stamp's shape: `SEG_VIGNET` (int32), `NEIGHBOUR` (bool) and `OFF_TILE` (bool). +The native stamp's `INT_POS` defines every exposure pixel centre; `OFFSET` retains the same subpixel centroid remainder as the image extraction. +Vignetmaker maps those zero-based centres through the exposure WCS and the tile WCS, then samples the nearest tile cell with `floor(x + 0.5)` on each axis, including upward half-cell ties. +No image, detector flag, weight, background or RMS stamp is resampled. +A nearest cell outside the full tile rectangle sets `OFF_TILE`; it is not sky or a neighbour. + +Both blend handlings use the full registered segmentation, including cells beyond the original tile VIGNET support. +`NEIGHBOUR` marks every foreign nonzero segmentation label, including −1. +`noisefill` replaces light on that full neighbour footprint, independently of the tile VIGNET's intensity markers. +`uberseg` recomputes the nearest-segment Voronoi partition on the exposure-grid labels before applying its configured dilation. +Ngmix reads these arrays before its defect mask, masked-fraction cut, central veto and footprint diagnostics; it applies no CCD flip to them. +The tile-grid `SEG_VIGNET` still supplies the catalogue-level `neighbour_flag`. +`SEG_LABEL` and both tile stamp columns are omitted from final catalogues when stamp removal is enabled. +There are no additional product files or final-catalogue columns. + +Image vignette stores without registered categories fail with an instruction to rerun vignetmaker. +Detection catalogues without `SEG_LABEL` require tile detection and the join to run with the matching segmentation check image. +Use a single code revision and this input contract across a campaign, including calibration simulations; image and categorical products from different extractions must not be mixed. + ## The two static invocations The exposure job set is *derived from data the run itself produces* — a tile's diff --git a/example/cfis_image_sims/config_tile_PiViVi_canfar_sx.ini b/example/cfis_image_sims/config_tile_PiViVi_canfar_sx.ini index d42a10bdd..b7f45c037 100644 --- a/example/cfis_image_sims/config_tile_PiViVi_canfar_sx.ini +++ b/example/cfis_image_sims/config_tile_PiViVi_canfar_sx.ini @@ -20,7 +20,7 @@ RUN_NAME = run_sp_tile_ViVi # Module name, single string or comma-separated list of valid module runner names -MODULE = vignetmaker_runner, vignetmaker_runner, vignetmaker_runner +MODULE = vignetmaker_runner, vignetmaker_runner # Parallel processing mode, SMP or MPI MODE = SMP @@ -93,9 +93,9 @@ PREFIX = weight INPUT_DIR = run_sp_tile_Sx:sextractor_runner, run_sp_tile_Mh_exp:merge_headers_runner, last:find_exposures_runner -FILE_PATTERN = sexcat, log_exp_headers, exp_numbers +FILE_PATTERN = sexcat, log_exp_headers, exp_numbers, segmentation -FILE_EXT = .fits, .sqlite, .txt +FILE_EXT = .fits, .sqlite, .txt, .fits # NUMBERING_SCHEME (optional) string with numbering pattern for input files NUMBERING_SCHEME = -000-000 @@ -124,39 +124,3 @@ PREFIX = ME_IMAGE_EXP_DIR = $SP_EXP ME_IMAGE_EXP_RUNNERS = split_exp_runner, split_exp_runner, split_exp_runner ME_IMAGE_PATTERN = flag, image, weight - - -[VIGNETMAKER_RUNNER_RUN_3] - -# Cut per-object coadd-frame segmentation stamps from the tile SExtractor -# SEGMENTATION check image (config_tile_Sx.ini: CHECKIMAGE = BACKGROUND, -# SEGMENTATION). Integer labels, no interpolation, zero-padded — CLASSIC mode -# guarantees this. Row-aligned to the tile catalogue on the same XWIN/YWIN -# centres and 51x51 grid as the coadd VIGNET, so ngmix can overlay the seg -# stamp directly for uberseg neighbour masking (shapepipe#776). - -INPUT_DIR = run_sp_tile_Sx:sextractor_runner - -FILE_PATTERN = sexcat, segmentation - -FILE_EXT = .fits, .fits - -# NUMBERING_SCHEME (optional) string with numbering pattern for input files -NUMBERING_SCHEME = -000-000 - -MASKING = False -MASK_VALUE = 0 - -# CLASSIC: cut stamps at object positions in the coadd (tile) frame. -MODE = CLASSIC - -# Coordinate frame type, one in PIX (pixel frame), SPHE (spherical coordinates) -COORD = PIX -POSITION_PARAMS = XWIN_IMAGE,YWIN_IMAGE - -# Vignet size in pixels — MUST equal the coadd VIGNET size (51) so the seg -# stamp overlays the galaxy stamp on an identical grid. -STAMP_SIZE = 51 - -# Output file name prefix, file name is _vignet.fits -PREFIX = seg diff --git a/example/cfis_image_sims/config_tile_Sx.ini b/example/cfis_image_sims/config_tile_Sx.ini index b84cca656..9c8e9c1f7 100644 --- a/example/cfis_image_sims/config_tile_Sx.ini +++ b/example/cfis_image_sims/config_tile_Sx.ini @@ -104,6 +104,9 @@ BKG_FROM_HEADER = False # OBJECTS, -OBJECTS, SEGMENTATION, APERTURES CHECKIMAGE = BACKGROUND, SEGMENTATION +# Retain tile-grid labels and the pre-join label for exposure registration. +SEG_VIGNET = True + # File name suffix for the output sextractor files (optional) SUFFIX = sexcat diff --git a/scripts/validation/masked_pixels/dr6_epochs.py b/scripts/validation/masked_pixels/dr6_epochs.py index 6f1ecb068..ef072cb00 100644 --- a/scripts/validation/masked_pixels/dr6_epochs.py +++ b/scripts/validation/masked_pixels/dr6_epochs.py @@ -4,17 +4,15 @@ Inputs: * one MegaCam exposure with its weight and flag maps (vos:cfis/pitcairn, vos:cfis/weights, vos:cfis/flags), e.g. 2086786p.fits.fz; - * the DR6 tile catalogue with VIGNET (-1e30 neighbour and off-tile - markers) and SEG_VIGNET columns, as read_ext_sexcat writes it from - CFIS..r.cat and CFIS..r.seg.fits.fz - (sexcat--.fits). + * the tile catalogue with SEG_LABEL and its matching full segmentation + check image in the same directory (sexcat--.fits and + segmentation--.fits). The epoch stamps are cut as vignetmaker does: 51x51 around the rounded pixel of the object's (XWIN_WORLD, YWIN_WORLD) in the CCD's own WCS, CCDs -numbered as split_exp names them (HDU index - 1). The tile VIGNET and seg -stamp are MegaCam-flipped onto the epoch and split into neighbour and -off-tile pixels (split_tile_markers); the off-tile pixels get zero weight, -as prepare_postage_stamps gives them. The background is a sigma-clipped +numbered as split_exp names them (HDU index - 1). Full tile categories are +sampled on each native exposure grid with register_categories; off-tile +pixels get zero weight as in prepare_postage_stamps. The background is a sigma-clipped median over the clean pixels of a 257x257 box around the object, and the background RMS is constant over the stamp; the pipeline takes both from SExtractor's maps instead. Only the survey flag and weight maps mark @@ -37,11 +35,10 @@ from scipy.ndimage import find_objects, label from shapepipe.modules.ngmix_package.ngmix import ( - Ngmix, defect_mask, - split_tile_markers, ) -from shapepipe.modules.vignetmaker_package.vignetmaker import get_stamps +from shapepipe.modules.vignetmaker_package.vignetmaker import get_stamps, register_categories +from shapepipe.modules.sextractor_package.match_catalogue import relabel RAD = 25 N = 2 * RAD + 1 @@ -52,9 +49,13 @@ def read_tile(sexcat): with fitsio.FITS(sexcat) as f: hdu = [h for h in f if h.get_extname() == "LDAC_OBJECTS"][0] - return hdu.read(columns=["NUMBER", "XWIN_WORLD", "YWIN_WORLD", - "MAG_AUTO", "FLUX_RADIUS", "VIGNET", - "SEG_VIGNET"]) + data = hdu.read(columns=["NUMBER", "XWIN_WORLD", "YWIN_WORLD", + "MAG_AUTO", "FLUX_RADIUS", "SEG_LABEL"]) + seg_path = sexcat.replace("sexcat-", "segmentation-") + tile = {name: data[name] for name in data.dtype.names} + tile["segmentation"] = relabel(fits.getdata(seg_path), data["SEG_LABEL"], data["NUMBER"]) + tile["wcs"] = WCS(fits.getheader(seg_path)) + return tile def tile_name(sexcat): @@ -75,11 +76,10 @@ def ccd_positions(hdus, ra, dec): return out -def tile_overlay(tile, i, ccd): - tile_vign = Ngmix.MegaCamFlip(np.copy(tile["VIGNET"][i]), ccd) - seg = Ngmix.MegaCamFlip(np.copy(tile["SEG_VIGNET"][i]), ccd) - neighbour, off_tile = split_tile_markers(tile_vign, (N, N)) - return seg.astype(np.int32), neighbour, off_tile +def epoch_categories(tile, i, epoch_wcs, int_pos): + maps = register_categories(tile["segmentation"], tile["wcs"], epoch_wcs, + int_pos, (N, N), tile["NUMBER"][i]) + return maps["SEG_VIGNET"], maps["NEIGHBOUR"], maps["OFF_TILE"] def components(defect, flag, off_tile): @@ -119,7 +119,7 @@ def cut(hdus, ext, pos, tile, i): good = (wgt[box] > 0) & (flg[box] == 0) _, bkg, rms = sigma_clipped_stats(img[box][good], sigma=3.0) stamps["gal"] = stamps["gal"] - bkg - seg, neighbour, off_tile = tile_overlay(tile, i, ccd) + seg, neighbour, off_tile = epoch_categories(tile, i, WCS(hdus[0][ext].header), int_pos[0]) stamps["weight"][off_tile] = 0 stamps.update( bkg_rms=np.full((N, N), rms), seg=seg, neighbour=neighbour, @@ -138,8 +138,8 @@ def scan(hdus, tile): continue wgt = get_stamps(hdus[1][ext].data, pos, RAD)[0] flg = get_stamps(hdus[2][ext].data, pos, RAD)[0].astype(np.int32) - for i, w, f in zip(rows, wgt, flg): - seg, neighbour, off_tile = tile_overlay(tile, i, ext - 1) + for i, w, f, centre in zip(rows, wgt, flg, np.round(pos).astype(int)): + seg, neighbour, off_tile = epoch_categories(tile, i, WCS(hdus[0][ext].header), centre) w[off_tile] = 0 defect = defect_mask(w, f) if not defect.any(): diff --git a/scripts/validation/masked_pixels/tile_defect_flags.py b/scripts/validation/masked_pixels/tile_defect_flags.py index bc76583dc..d65a29637 100644 --- a/scripts/validation/masked_pixels/tile_defect_flags.py +++ b/scripts/validation/masked_pixels/tile_defect_flags.py @@ -11,7 +11,8 @@ --plot scripts/validation/masked_pixels/tile_defect_flags-TILE.png All stores open read-only; nothing is written beneath an input directory. -SEXCAT must carry the committed workflow's SEG_VIGNET column. Omit +SEXCAT must carry SEG_VIGNET and image epochs must carry native-grid +SEG_VIGNET, NEIGHBOUR and OFF_TILE categories. Omit --background only for already background-subtracted images; omit --rms when the run used stamp-estimated RMS. Pass the production blend/fill choices explicitly. The output contains every tile row, including unavailable PSFs, zero-kept- @@ -37,7 +38,7 @@ from sqlitedict import SqliteDict from shapepipe.modules.ngmix_package.ngmix import ( - EPOCH_INTERPOLATED_DEFECT_RADIUS, Ngmix, Tile_cat, centre_distance, + EPOCH_INTERPOLATED_DEFECT_RADIUS, Postage_stamp, Tile_cat, centre_distance, prepare_postage_stamps, ) @@ -102,13 +103,14 @@ def store(path): continue flags = vignet.flag_vign_cat[key] data["n_candidate"][i] = len(psf) - if footprint.any() and not data["footprint_clipped"][i]: - bits = 0 - for name in psf: - own = Ngmix.MegaCamFlip(footprint, int(name.split("-")[1])) - values = np.asarray(flags[name]["VIGNET"])[own] - bits |= int(np.bitwise_or.reduce(values.astype(np.int64))) - data["precut_imaflags_iso"][i] = bits + precut = Postage_stamp() + for name in psf: + epoch_seg = gal[name]["SEG_VIGNET"] + precut.record_footprint_defects( + flags[name]["VIGNET"], np.zeros(epoch_seg.shape, bool), + epoch_seg, obj_id, + ) + data["precut_imaflags_iso"][i] = precut.imaflags_iso # Reuse the fetched flag row when the production preparation reads # it; no second SQLite fetch is needed for the pre-cut comparison. per_object = SimpleNamespace(**(vars(vignet) | { diff --git a/src/shapepipe/modules/make_cat_package/make_cat.py b/src/shapepipe/modules/make_cat_package/make_cat.py index a04d4c52c..8a8aca7e7 100644 --- a/src/shapepipe/modules/make_cat_package/make_cat.py +++ b/src/shapepipe/modules/make_cat_package/make_cat.py @@ -92,8 +92,8 @@ def read_sextractor_data(sexcat_path, remove_vignet=True): sexcat_path : str Path to SExtractor catalogue remove_vignet : bool - If ``True`` will not keep the ``VIGNET`` and ``SEG_VIGNET`` stamp - fields + If ``True``, omit ``VIGNET``, ``SEG_VIGNET`` and the registration + bookkeeping field ``SEG_LABEL``. Returns ------- @@ -110,7 +110,7 @@ def read_sextractor_data(sexcat_path, remove_vignet=True): columns = { name: data[name] for name in data.dtype.names - if not (remove_vignet and name in ("VIGNET", "SEG_VIGNET")) + if not (remove_vignet and name in ("VIGNET", "SEG_VIGNET", "SEG_LABEL")) } tile_name = os.path.basename(sexcat_path) diff --git a/src/shapepipe/modules/ngmix_package/ngmix.py b/src/shapepipe/modules/ngmix_package/ngmix.py index 04009baf5..4010166d1 100644 --- a/src/shapepipe/modules/ngmix_package/ngmix.py +++ b/src/shapepipe/modules/ngmix_package/ngmix.py @@ -592,9 +592,9 @@ class Tile_cat(): ---------- cat_path : str Path to the tile SExtractor catalogue. Its optional ``SEG_VIGNET`` - column, one integer coadd segmentation stamp per object on the grid - of its ``VIGNET``, becomes ``self.seg``, which defines the neighbours - under both blend handlings; without it ``self.seg`` is ``None``. + column becomes ``self.seg`` for the catalogue-level neighbour flag + and centre-label diagnostic. Epoch masks come from the registered + categories in the image vignette store. row_min, row_max : int, optional First and last catalogue row of the chunk (1-based, inclusive; see :func:`chunk_rows`). The default, ``-1``, is unbounded, so the whole @@ -636,10 +636,8 @@ def get_data(self, cat_path): else None ) - # Coadd-frame segmentation stamp (integer labels, the catalogue's - # NUMBER), one per object on the grid of its VIGNET, overlaid - # unchanged on every epoch; it defines the neighbours (shapepipe#776, - # split_tile_markers, uberseg_mask). + # Tile-grid labels supply the catalogue-level neighbour flag. + # Per-epoch registered labels are read from the image vignette store. self.seg = ( ChunkStamps(data['SEG_VIGNET'], self.rows) if 'SEG_VIGNET' in cols @@ -656,33 +654,26 @@ class Postage_stamp(): Parameters ---------- bkg_sub: bool - + Subtract per-epoch backgrounds. megacam_flip: bool - We probably want to put weight and flag options here too + Accepted without effect; categorical maps are on the native grid. """ def __init__( self, bkg_sub=True, - megacam_flip=True - + megacam_flip=True, ): self.gals = [] self.psfs = [] self.weights = [] self.flags = [] - # Neighbour masks, one per epoch: the pixels marked -1e30 in the tile - # VIGNET on other detections' footprints (off-tile markers get zero - # weight instead; see split_tile_markers), MegaCam-flipped to the - # epoch. noisefill zero-weights and noise-fills them, and the epoch - # cuts do not count them (see prepare_ngmix_weights). + # Exposure-grid neighbour masks, projected upstream from tile + # other-footprint markers. Epoch cuts do not count neighbours. self.neighbours = [] self.bkg_rms = [] - # Segmentation stamps, one per epoch, used only by the "uberseg" blend - # handling; empty under the default "noisefill". All epochs carry the - # SAME coadd-frame seg stamp (shapepipe#776: one coadd seg per object, - # no per-epoch reprojection), each MegaCam-flipped to match its galaxy - # stamp so the overlay stays registered. + # Exposure-grid segmentation stamps, sampled upstream from the full + # tile segmentation. UberSeg partitions these native-grid labels. self.segs = [] self.jacobs = [] # Per-epoch sub-pixel [row, col] coadd-centroid offset propagated from @@ -713,7 +704,6 @@ def __init__( self.min_dist_interp = np.inf self.min_dist_noisefill = np.inf self.bkg_sub = bkg_sub - self.megacam_flip = megacam_flip def record_defects(self, defect, interpolated): """Add one kept epoch to the defect diagnostics. @@ -752,9 +742,9 @@ def record_footprint_defects(self, flag, interpolated, seg, obj_id): @sc [decision:shape_measurement.defect_flagging,label:schema] footprint-defect-flags ``imaflags_iso`` is the bitwise OR of all instrument bits in the exposure flag stamp on ``seg == obj_id``, OR'ed across epochs kept - after the masked-fraction cut and central veto. ``seg`` is the coadd - SEG_VIGNET, already MegaCam-flipped to the epoch frame; it is not an - exposure detection or a reprojected isophote. ``n_epoch_interp_iso`` + after the masked-fraction cut and central veto. ``seg`` is the tile + segmentation sampled on the native exposure grid, not an exposure + detection. ``n_epoch_interp_iso`` counts kept epochs with any interpolated defect on that footprint. Zero-weight/off-tile pixels with flag 0 contribute no instrument bit (SExtractor semantics), but count if interpolated. Neither quantity @@ -896,11 +886,9 @@ class Ngmix(object): :func:`make_ngmix_observation`. blend_handling : {"noisefill", "uberseg"}, optional Neighbour treatment. ``"noisefill"`` (default) zero-weights and - noise-fills the pixels marked -1e30 in the tile VIGNET on other - detections' footprints; ``"uberseg"`` ignores those markers and - zeroes the weight of neighbour-side pixels from the coadd - segmentation stamps, the tile catalogue's ``SEG_VIGNET`` column (see - :class:`Tile_cat`), which it requires. Defect pixels are filled + noise-fills foreign nonzero segmentation footprints on the exposure + grid. ``"uberseg"`` zeroes neighbour-side weights using the nearest + segment partition of those registered labels. Defect pixels are filled under both (see :func:`prepare_ngmix_weights`). dilate_neighbour : int, optional Neighbour-mask dilation iterations for ``"uberseg"`` (see @@ -1050,7 +1038,6 @@ def MegaCamFlip(self, vign, ccd_nb): numpy.ndarray The flipped postage stamp - @sc [decision:shape_measurement.megacam_ccd_flip] """ if ccd_nb < 18 or ccd_nb in [36, 37]: # swap x axis so origin is on top-right @@ -1297,17 +1284,15 @@ def _check_central_seg_label(self, seg, obj_id): """Cross-check the seg stamp's centre pixel against the object's NUMBER. The authoritative central label is ``obj_id`` (the SExtractor NUMBER); - this is a diagnostic on the coadd-vs-epoch overlay registration, not a - gate. Two outcomes: + this checks the tile catalogue's label integrity. Two outcomes: * The seg stamp does not contain ``obj_id`` anywhere — the object's own footprint fell outside the cutout (bad centroid / dropped detection), so uberseg has no central object to keep. Raise; the per-object ``try/except`` in :meth:`process` drops it, loud in the log. - * The centre-pixel label is nonzero and ``!= obj_id`` — a few-pixel - registration offset put a neighbour on the centre pixel. Harmless for - the mask (which keys off ``obj_id``), but a signal worth surfacing: - log a warning and proceed. + * The centre-pixel label is nonzero and ``!= obj_id`` — the tile + barycentre lies on a neighbour. Log this diagnostic and proceed; + native-grid masks use the target's NUMBER, not the centre label. Parameters ---------- @@ -1328,9 +1313,8 @@ def _check_central_seg_label(self, seg, obj_id): if centre_label != 0 and centre_label != obj_id: self._w_log.info( f"uberseg: object NUMBER={obj_id} but seg centre pixel carries" - + f" label {centre_label}; a coadd-vs-epoch registration offset" - + " is placing a neighbour on the centre. Proceeding with the" - + " NUMBER (authoritative)." + + f" label {centre_label}; the tile barycentre lies on a" + + " neighbour. Proceeding with the authoritative NUMBER." ) def log_mean_ellipticity(self): @@ -1435,10 +1419,8 @@ def process(self): ) if tile_cat.seg is None and getattr(tile_cat, "vign", None) is not None: self._w_log.warning( - f"{self._tile_cat_path} has no SEG_VIGNET column: every" - + " interior -1e30 marker is taken as a neighbour," - + " including the object's own CLEAN-merged fragments" - + " (neighbours-are-other-footprints)." + f"{self._tile_cat_path} has no SEG_VIGNET column:" + + " catalogue-level neighbour_flag is unknown (written 0)." ) check_wcs_centroid_offset( @@ -1525,11 +1507,8 @@ def process(self): # NUMBER (obj_id): seg labels are the NUMBERs of the same SE run # that produced the tile catalogue, so obj_id is authoritative # and is used for both the uberseg mask and the neighbour flag. - # The centre pixel is only a diagnostic: a few-pixel coadd-vs- - # epoch overlay offset can put a NEIGHBOUR's label there, which - # would invert the mask — so we never trust it to define the - # central object. Cross-check it and warn on a mismatch (a - # registration signal), but proceed with obj_id (shapepipe#776). + # NUMBER defines the target even if its tile-stamp centre + # falls on sky or a neighbour. The central label is diagnostic. if self._blend_handling == "uberseg": self._check_central_seg_label(tile_cat.seg[i_tile], obj_id) res, psf_res, psf_orig_res = do_ngmix_metacal( @@ -1657,6 +1636,9 @@ def prepare_postage_stamps( ): """Gather one object's epoch stamps, dropping epochs its defects spoil. + @sc [decision:preparation.categorical_registration] + Categorical inputs are already on each epoch's native extraction grid. + @sc [decision:shape_measurement.central_defect_veto,decision:shape_measurement.epoch_masked_fraction_cut] epoch-cut-on-defect-mask An epoch is dropped when more than ``EPOCH_MASKED_FRACTION_CUT`` of its stamp lies in :func:`defect_mask`, the set :func:`prepare_ngmix_weights` @@ -1665,10 +1647,9 @@ def prepare_postage_stamps( that ``DEFECT_WEIGHTING`` zero-weights or interpolates are not counted. @sc [decision:shape_measurement.central_defect_veto,decision:shape_measurement.epoch_masked_fraction_cut,decision:shape_measurement.blend_handling] neighbour-markers-are-not-defects - The tile VIGNET's -1e30 markers on other objects' segmentation - footprints (:func:`split_tile_markers`) are the epoch's neighbour mask - (``stamp.neighbours``), not defects: every epoch shares the tile VIGNET, - so counting them would drop every epoch of a blended object. + Foreign nonzero segmentation footprints, sampled upstream on each + exposure grid, are the epoch's neighbour mask (``stamp.neighbours``), + not defects. Counting neighbours would reject blended objects. @sc [decision:shape_measurement.central_defect_veto,decision:shape_measurement.epoch_masked_fraction_cut,decision:shape_measurement.defect_fill] off-tile-pixels-are-defects Beyond the tile's edge the epoch holds the object's own light, cut off by @@ -1751,31 +1732,21 @@ def prepare_postage_stamps( if not sigma_mad(gal_vign_sub_bkg) > 0: continue - tile_vign = ( - np.copy(tile_cat.vign[i_tile]) - if tile_cat.vign is not None - else None - ) - if stamp.megacam_flip and tile_vign is not None: - tile_vign = Ngmix.MegaCamFlip(tile_vign, int(ccd_n)) - - # Coadd-frame segmentation stamp for this object, MegaCam-flipped to - # match the (flipped) galaxy stamp so the overlay stays registered. - # The SAME coadd seg rides every epoch (shapepipe#776: no reprojection). - tile_seg = ( - np.copy(tile_cat.seg[i_tile]) - if getattr(tile_cat, "seg", None) is not None - else None - ) - if stamp.megacam_flip and tile_seg is not None: - tile_seg = Ngmix.MegaCamFlip(tile_seg, int(ccd_n)) - + # All categories share the image stamp's native extraction grid. + # Read them before constructing defects, cuts or footprint diagnostics. + epoch = gal_obj[expccd_name] + required = ("SEG_VIGNET", "NEIGHBOUR", "OFF_TILE") + if any(name not in epoch for name in required): + raise ValueError( + "Exposure-grid categories are missing; rerun vignetmaker with" + " the tile segmentation and current detection catalogue" + ) + tile_seg, neighbour, off_tile = (np.asarray(epoch[name]) for name in required) + if any(array.shape != gal_vign.shape for array in (tile_seg, neighbour, off_tile)): + raise ValueError("Exposure categories must have the image stamp shape") + if neighbour.dtype != bool or off_tile.dtype != bool: + raise ValueError("NEIGHBOUR and OFF_TILE must be boolean maps") flag_vign = flag_obj[expccd_name]['VIGNET'] - # Off-tile pixels are defects (off-tile-pixels-are-defects); the - # other -1e30 markers are neighbours (neighbour-markers-are-not-defects). - neighbour, off_tile = split_tile_markers( - tile_vign, np.shape(gal_vign), tile_seg, obj_id - ) weight_vign = np.where(off_tile, 0, weight_obj[expccd_name]['VIGNET']) bkg_rms_vign = ( bkg_rms_obj[expccd_name]['VIGNET'] @@ -1853,7 +1824,6 @@ def prepare_postage_stamps( def split_tile_markers(tile_vign, shape, seg=None, object_number=None): """Split the tile VIGNET's -1e30 markers into neighbour and off-tile. - @sc [decision:shape_measurement.blend_handling,decision:shape_measurement.defect_fill] off-tile-is-marked-border-rows-and-columns SExtractor writes -1e30 into the tile VIGNET on stamp pixels beyond the tile's edge and, under MASK_TYPE CORRECT, on every above-threshold pixel that is not the object's own pre-CLEAN footprint. A stamp clipped by the @@ -1861,7 +1831,6 @@ def split_tile_markers(tile_vign, shape, seg=None, object_number=None): the off-tile pixels are the union of the runs of entirely -1e30 rows and columns that start at a stamp border. - @sc [decision:shape_measurement.blend_handling] neighbours-are-other-footprints The other markers also fall on pixels no other object owns: detections smaller than DETECT_MINAREA (noise peaks, catalogued nowhere) and fragments CLEAN merged into the object itself, which the segmentation @@ -2071,8 +2040,7 @@ def central_seg_label(seg): (``obj_id``), which is plumbed straight through: segmentation labels ARE the NUMBERs of the same SE run, so ``obj_id`` names the central footprint directly (shapepipe#776). This helper reads the centre pixel only as a - registration cross-check — a few-pixel coadd-vs-epoch overlay offset can - put a NEIGHBOUR's label on the centre pixel, which is exactly why the + label diagnostic: a neighbour can occupy the centre pixel, so the centre pixel must NOT define the central object (trusting it there would invert the uberseg mask). See :meth:`Ngmix._check_central_seg_label`. @@ -2084,7 +2052,7 @@ def central_seg_label(seg): Returns ------- int - Label at the centre pixel — the central object's segmentation id. + Segmentation label at the centre pixel. Raises ------ @@ -2166,14 +2134,13 @@ def uberseg_mask(seg, object_number, dilate_neighbour=0): object_number : int Segmentation label of the central object — its SExtractor ``NUMBER`` (``obj_id``), authoritative because seg labels are the NUMBERs of the - same SE run. Not the centre-pixel label, which a few-pixel coadd-vs- - epoch offset can steal for a neighbour and so invert this mask. + same detection run, including any catalogue join. A neighbour can + occupy the centre pixel, so its label cannot define the target. dilate_neighbour : int, optional Enlarge the mask by this many binary-dilation iterations of the neighbour footprints (4-connected, ~one pixel per iteration) on top of - the Voronoi partition, to absorb the few-pixel coadd-vs-epoch - registration offset the coadd-seg overlay accepts (shapepipe#776, - decision on seg source). ``0`` (the default) is the pure Sheldon + the Voronoi partition on the registered exposure-grid labels. + ``0`` (the default) is the pure Sheldon UberSeg mask. The dilation only ever adds pixels, so over-masking a boundary pixel costs a little central-object S/N but never leaks neighbour flux into the fit. @@ -2428,8 +2395,8 @@ def prepare_ngmix_weights( no raw defect value may reach it. @sc [decision:shape_measurement.blend_handling] noisefill-fills-markers - Under ``"noisefill"`` the ``neighbour`` pixels (the tile VIGNET's -1e30 - neighbour markers) get weight 0 and noise. Their light is gone, so they + Under ``"noisefill"`` the ``neighbour`` pixels (registered foreign nonzero + segmentation footprints) get weight 0 and noise. Their light is gone, so they neither support the interpolant nor receive it. @sc [decision:shape_measurement.blend_handling] uberseg-ignores-markers @@ -2535,8 +2502,7 @@ def prepare_ngmix_weights( raise ValueError( "blend_handling='uberseg' requires a segmentation map and the" + " central object_number; none reached prepare_ngmix_weights." - + " The tile catalogue's SEG_VIGNET column carries the map (see" - + " CosmoStat/shapepipe#776)." + + " The image vignette store must carry registered SEG_VIGNET." ) defect = defect_mask(weight, flag, bkg_rms) diff --git a/src/shapepipe/modules/sextractor_package/sextractor_script.py b/src/shapepipe/modules/sextractor_package/sextractor_script.py index e41ddad57..1f598f424 100644 --- a/src/shapepipe/modules/sextractor_package/sextractor_script.py +++ b/src/shapepipe/modules/sextractor_package/sextractor_script.py @@ -148,9 +148,11 @@ def add_seg_vignet(cat_path, seg_path, w_log=None): ``NUMBER``, is cut on the grid of each object's VIGNET, centred where SExtractor centres VIGNET (:func:`vignet_centre` of ``X_IMAGE_DBL`` / ``Y_IMAGE_DBL``, :func:`cut_stamps`), and written, int32 and 0 off the image, as - ``SEG_VIGNET`` in ``LDAC_OBJECTS``, which ngmix's UberSeg blend handling - reads. The double positions (:func:`seg_vignet_param_file`) are dropped; - every other HDU and column is kept. + ``SEG_VIGNET`` in ``LDAC_OBJECTS`` for tile-level neighbour diagnostics. + The double positions (:func:`seg_vignet_param_file`) are dropped; + ``SEG_LABEL`` retains the check-image label through catalogue joins so + vignetmaker can register the full segmentation, beyond VIGNET's support. + Every other HDU and column is kept. Parameters ---------- @@ -184,7 +186,10 @@ def add_seg_vignet(cat_path, seg_path, w_log=None): kept = [c for c in objects.columns.columns if c.name not in DOUBLE_POSITIONS] new = fits.BinTableHDU.from_columns( - kept + [seg_vignet_column(seg_vignets)], + kept + [ + seg_vignet_column(seg_vignets), + fits.Column(name="SEG_LABEL", format="J", array=data["NUMBER"]), + ], header=objects.header, name="LDAC_OBJECTS", ) diff --git a/src/shapepipe/modules/vignetmaker_package/vignetmaker.py b/src/shapepipe/modules/vignetmaker_package/vignetmaker.py index f0d7d9dd9..228a11408 100644 --- a/src/shapepipe/modules/vignetmaker_package/vignetmaker.py +++ b/src/shapepipe/modules/vignetmaker_package/vignetmaker.py @@ -11,6 +11,7 @@ import numpy as np from astropy.wcs import WCS +from astropy.io import fits from sqlitedict import SqliteDict from shapepipe.pipeline import file_io @@ -85,6 +86,63 @@ def get_stamps(image, positions, rad): return stamps, int_pos, offsets +def register_categories( + segmentation, tile_wcs, epoch_wcs, int_pos, shape, object_number +): + """Sample tile categories at native exposure-stamp pixel centres. + + @sc [decision:preparation.categorical_registration] + WCS coordinates are zero-based pixel centres. + ``int_pos`` is [row, col]. + Nearest-neighbour sampling uses ``floor(x + 0.5)`` (ties go upward). + Segmentation, neighbours and the tile rectangle have full-tile support. + A neighbour is any nonzero label other than ``object_number``, including + -1 for a detection absent from the joined catalogue. + Noisefill uses this full neighbour footprint; UberSeg recomputes its + nearest-segment partition on the registered labels. + Neither images nor detector masks are resampled. + + Parameters + ---------- + segmentation : numpy.ndarray + Full tile segmentation with catalogue NUMBER labels (0 sky, -1 + detections absent from the joined catalogue). + tile_wcs, epoch_wcs : astropy.wcs.WCS + Independent tile and native exposure coordinate systems. + int_pos : array_like + Rounded exposure extraction centre in [row, col] order. + shape : tuple + Exposure stamp shape. + object_number : int + Target's catalogue NUMBER. + + Returns + ------- + dict + Exposure-grid ``SEG_VIGNET``, ``NEIGHBOUR`` and ``OFF_TILE`` maps. + """ + row, col = np.indices(shape, dtype=float) + xy = np.stack( + (col - shape[1] // 2 + int_pos[1], row - shape[0] // 2 + int_pos[0]), + axis=-1, + ) + world = epoch_wcs.all_pix2world(xy.reshape(-1, 2), 0) + tile_xy = tile_wcs.all_world2pix(world, 0).reshape(*shape, 2) + if not np.isfinite(tile_xy).all(): + raise ValueError( + "Non-finite tile coordinates in categorical registration" + ) + x, y = np.floor(tile_xy + 0.5).astype(np.int64).transpose(2, 0, 1) + inside = ( + (x >= 0) & (x < segmentation.shape[1]) + & (y >= 0) & (y < segmentation.shape[0]) + ) + seg = np.zeros(shape, dtype=np.int32) + seg[inside] = segmentation[y[inside], x[inside]] + neighbour = (seg != 0) & (seg != object_number) + return dict(SEG_VIGNET=seg, NEIGHBOUR=neighbour, OFF_TILE=~inside) + + class VignetMaker(object): """Vignet Maker. @@ -319,6 +377,20 @@ def _get_stamp_me(self, image_dirs, image_pattern): all_id = np.copy(cat.get_data()["NUMBER"]) n_epoch = np.copy(cat.get_data()["N_EPOCH"]) + categories = None + if image_pattern == "image": + from shapepipe.modules.sextractor_package.match_catalogue import relabel + + data = cat.get_data() + if "SEG_LABEL" not in data.dtype.names: + raise ValueError("Exposure categories require SEG_LABEL; " + "rerun tile detection") + tile_seg = relabel( + fits.getdata(self._segmentation_path), + data["SEG_LABEL"], data["NUMBER"], + ) + tile_wcs = WCS(fits.getheader(self._segmentation_path)) + categories = {} list_ext_name = cat.get_ext_name() hdu_ind = [ @@ -382,6 +454,14 @@ def _get_stamp_me(self, image_dirs, image_pattern): img_path, pos - 1, self._rad ) + if categories is not None: + for number, centre in zip(obj_id, tmp_int_pos): + maps = register_categories( + tile_seg, tile_wcs, wcs_file, centre, + tmp_vign.shape[1:], int(number), + ) + categories[int(number), f"{exp_name}-{ccd}"] = maps + if array_vign is None: array_vign = np.copy(tmp_vign) else: @@ -456,6 +536,10 @@ def _get_stamp_me(self, image_dirs, image_pattern): output_dict[id_tmp][index]["INT_POS"] = final_list[j][4][ where_res[0] ] + if categories is not None: + output_dict[id_tmp][index].update( + categories[int(id_tmp), index] + ) counter += 1 if counter == 0: @@ -463,7 +547,9 @@ def _get_stamp_me(self, image_dirs, image_pattern): return output_dict - def process_me(self, image_dirs, image_pattern, f_wcs_path, rad): + def process_me( + self, image_dirs, image_pattern, f_wcs_path, rad, segmentation_path + ): """Process Multi-Epoch. Main function to create the stamps in the multi-epoch case. @@ -480,10 +566,14 @@ def process_me(self, image_dirs, image_pattern, f_wcs_path, rad): Path to the log file containing the WCS for each CCDs rad : int Radius of the stamp, must be an odd integer + segmentation_path : str + Full tile segmentation check image with the tile WCS. + Image epoch entries receive native-grid categorical maps. """ self._f_wcs_file = SqliteDict(f_wcs_path) self._rad = rad + self._segmentation_path = segmentation_path for idx in range(len(image_pattern)): diff --git a/src/shapepipe/modules/vignetmaker_runner.py b/src/shapepipe/modules/vignetmaker_runner.py index 85df0cffe..4b51ad260 100644 --- a/src/shapepipe/modules/vignetmaker_runner.py +++ b/src/shapepipe/modules/vignetmaker_runner.py @@ -142,8 +142,13 @@ def vignetmaker_runner( ) f_wcs_path = input_file_list[1] - # Process inputs - vm_inst.process_me(image_dirs, image_pattern, f_wcs_path, radius) + if len(input_file_list) != 4: + raise ValueError( + "MULTI-EPOCH requires the tile segmentation check image as" + " fourth input; append segmentation/.fits to FILE_PATTERN/FILE_EXT" + ) + vm_inst.process_me(image_dirs, image_pattern, f_wcs_path, radius, + input_file_list[3]) else: diff --git a/tests/data/registration_188307.md b/tests/data/registration_188307.md new file mode 100644 index 000000000..940ced044 --- /dev/null +++ b/tests/data/registration_188307.md @@ -0,0 +1,18 @@ +# Retained registration fixture + +`registration_188307.npz` contains tile 188.307, catalogue object 5422, exposure–CCD 2254827-27. +The target's original segmentation check-image label is 5366; its joined catalogue NUMBER is 5422. +Other detections use label −1 and sky uses label 0. + +The source segmentation rectangle is the zero-based full-tile slice `[1420:1510, 640:735]`. +`tile_header` is the tile WCS sliced to that rectangle, including the adjusted reference pixel. +`epoch_header` is the independently retained exposure WCS. +`int_pos`, `offset`, `image`, `weight`, `flag` and `rms` come from the retained epoch stores listed in `/scratch/cdaley/veto-survey/prevalence_checks.json` on Nibi. +The original tile catalogue is `sexcat-188-307.fits` under `defectflag-check/run/188307/work/tiles/18/188.307/output/run_sp_tile_Sx/sextractor_runner/output`. + +`expected_seg` and `old_seg` are the independently measured registered and flip-only classifications in `/scratch/cdaley/registration/example_5422.npz`, with target/foreign labels changed to 5422/−1. +They are not generated by `register_categories`. +Ten target-footprint pixels differ between them. +The native epoch pixel `[25,27]` has weight 0 and instrument flag 3, is sky in `old_seg`, and belongs to the target in `expected_seg`. +Its three-pixel defect strip lies on the registered footprint, giving `imaflags_iso=3` and `n_epoch_interp_iso=1` when the diagnostic is isolated from the central veto. +The production fixed-radius central veto rejects this epoch in both registrations. diff --git a/tests/data/registration_188307.npz b/tests/data/registration_188307.npz new file mode 100644 index 0000000000000000000000000000000000000000..2fa1337e19b6f5d9c7fb36dae6c4bf241a018552 GIT binary patch literal 15677 zcmb_@XH=70yDf@6v#<<`8an~5hO2){1-$~(!|X)BVHX}-zPF5ACA#4 zZg`WhZKBR^pFXjca1i-jC;sPY_`01m!2PVG6gl0jujTS;2={n>GSzFvqHF6w)GSNv zbRBK4fqPrwj?!|OI9sffI&}|PQ^p+zy~Qlm@}Wd6swT#yCP&a6g$`JOim~@;BK6vh zt?f)f&|s>n`UK3cy=x*fkMB)Rhi#XZ`r>RSdIsR7y}?^zyb@vFE2+a3mC9aN{o$EX zdu(lE(5bGw!|{aS`{a=PY3BaSTCZaJ@}P37&6&39{fn@De&-E8{-8Ixb>JR#=xoIw zc1YyMGe|glQM6V!jNywtR6niFvsatcerJcPpBmOkJG6sVuj;&d<|XFiHHfHhO0mL3 zz4khBaNU&m(m6;_@Di&?Q1Cr}TXb=!((_p>c0zRYDKz0vtc2*^SxM&k-=;&%%gcBEOb43t>ELQ@3o){Sn3zMH z|I7xzi^+4|w2A-fHxnl{CS_@Z@~V9(FtzayNaU&04?j46{-*lr=@5g~O;vibmw{I{ z{B*T^LYo}j7kn353dsdDqQVZ4GqJnS)Zc~sS%YF$>@t})CrjAY8ph+~)U!us361o<54 zX>HQ{uC@mYy`};LL0Bsh_a(c$l}Nm;QPlvSL$HulS&abA0%_|y*d%Q{rrprUiSqX;5u>NhE}mCOU)HP*wA%iGiT6SkvL*j~keJlK}oIksJ@9w3RIvb>A9tkG^n>9Vx! z3`;UnTh)#6&e;D!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LLmN4q>qVIS+k_v|E5UA7dK<*!y0Gg$a7UIn6Wus`4X(r_$0 zGwzi4_>RL#v?!=6d3Z`B2gxF1pKMj<_t;aY>@iy%fT=rm+61N8Ymv4>1ohYt@#&@P z3(vB&zbAxhXrmlBb9#@a7@JE5Mu%HJJB-T4CMPxQFDmZU8sSaQS9=t}imfqJAfLJ> zPONrWio(=eoooZMFg(rQ55}Kj-thi8sr{En#lsO|<_a-4I`msZUp}N%Sw2i!tJ`HXnT8$%7=&tpWkxhL*fE%II4A%V1*U+@!I*)AI+^6zw18(x0=oKWDuW6Zq8W`BhSu(AJ>2*(Z_n zHTe-_X?g29WFLZgH>r?6oF3fib5<_@zFs(OQQyPXRgFt4+fH^n6OSrrUBti_eL;+p ze7Le4v8W!XU3E4as98Q_0Mmj*{~ofA;F7{WA-fP`JJ|k*XbDh$ zkiFI6q&GR~P=A^Hqkd*>k(IR-1v2b|vRD?^$qk>`Jud3I_cW+9Ic8*@c-(fEsm8MR z{5Gvz_0-s9XF?+x0VhrS#^{`^0T7sBel zfiW)Q0$XTK@p-gP@M#%O9^4=cG?lxE8hvQM)3S@`wHQBjN_@`B+UdlqUAa4Z z>MAuay93W@yrc7knkUXb?J9ki$Af ze<82`w}Sj%1pF@To`3xx8vK6(FI4gu8u$w!#lIkbz4={we~svWXy*TkyAZQqXw@(D zDCB>`QBs}X@Q<|ppRfyY%Y}610`~XY2{IA=52?#PaTnT>3+>1S?!s97r}efdD-@ABcY}I{!ppWZWP0 g-vwJ0?ieC`?KV%h(2LJ#7 literal 0 HcmV?d00001 diff --git a/tests/module/test_categorical_registration.py b/tests/module/test_categorical_registration.py new file mode 100644 index 000000000..86ecef091 --- /dev/null +++ b/tests/module/test_categorical_registration.py @@ -0,0 +1,345 @@ +"""Native-grid categories from independent tile and exposure astrometry.""" + +from configparser import ConfigParser +from pathlib import Path +from types import SimpleNamespace + +import numpy as np +import numpy.testing as npt +import pytest +from astropy.io import fits +from astropy.wcs import Sip, WCS +from sqlitedict import SqliteDict + +from shapepipe.modules.ngmix_package import ngmix as n +from shapepipe.modules.vignetmaker_package.vignetmaker import ( + VignetMaker, + get_stamps, + register_categories, +) + +pytestmark = pytest.mark.decision("preparation.categorical_registration") + + +def _wcs(crpix=(41.0, 43.0), angle=0.0, distortion=False): + w = WCS(naxis=2) + w.wcs.ctype = ["RA---TAN", "DEC--TAN"] + w.wcs.crval = [188.0, 30.7] + w.wcs.crpix = crpix + theta = np.deg2rad(angle) + w.wcs.cd = ( + 0.18577 + / 3600 + * np.array( + [ + [-np.cos(theta), np.sin(theta)], + [np.sin(theta), np.cos(theta)], + ] + ) + ) + if distortion: + a, b = np.zeros((4, 4)), np.zeros((4, 4)) + a[2, 0], a[1, 1], b[0, 2] = 8e-4, -5e-4, -7e-4 + w.sip = Sip(a, b, None, None, w.wcs.crpix) + w.wcs.ctype = ["RA---TAN-SIP", "DEC--TAN-SIP"] + return w + + +def _segmentation(): + seg = np.zeros((89, 91), np.int32) + # An asymmetric target, a departed detection, and a nearby neighbour. + seg[35:46, 33:38] = 101 + seg[40:44, 38:46] = 101 + seg[45:49, 34:36] = 101 + seg[30:37, 46:50] = -1 + seg[43:52, 48:56] = 205 + return seg + + +def _oracle(seg, tw, ew, centre, shape): + """Scalar high-level WCS oracle; no shared mapping/extraction helper.""" + expected = np.zeros(shape, np.int32) + off = np.zeros(shape, bool) + for row, col in np.ndindex(shape): + sky = ew.pixel_to_world( + col + centre[1] - shape[1] // 2, row + centre[0] - shape[0] // 2 + ) + tx, ty = tw.world_to_pixel(sky) + x, y = int(np.floor(tx + 0.5)), int(np.floor(ty + 0.5)) + off[row, col] = not (0 <= x < seg.shape[1] and 0 <= y < seg.shape[0]) + if not off[row, col]: + expected[row, col] = seg[y, x] + return expected, off + + +@pytest.mark.parametrize( + "crpix,angle,distortion", + [ + ((43.0, 40.0), 0.0, False), # integer translation + ((40.37, 42.61), 0.0, False), # independent subpixel origins + ((41.24, 42.83), 17.0, False), # residual rotation + ((40.81, 43.22), 181.8, True), # upside-down CCD plus distortion + ], +) +def test_independent_wcs_registration(crpix, angle, distortion): + seg, tw, ew = _segmentation(), _wcs(), _wcs(crpix, angle, distortion) + positions = np.array([[41.29, 40.38]]) + image = np.arange(90 * 90).reshape(90, 90) + stamps, ip, offsets = get_stamps(image, positions, 12) + got = register_categories(seg, tw, ew, ip[0], stamps.shape[1:], 101) + expected, off = _oracle(seg, tw, ew, ip[0], stamps.shape[1:]) + npt.assert_array_equal(got["SEG_VIGNET"], expected) + npt.assert_array_equal(got["OFF_TILE"], off) + npt.assert_array_equal( + got["NEIGHBOUR"], (expected != 0) & (expected != 101) + ) + npt.assert_allclose(ip[0] + offsets[0], positions[0]) + assert np.any(expected == 101) and np.any(got["NEIGHBOUR"]) + + +def test_rotated_tile_edge_is_not_a_border_run_heuristic(): + tw, ew = _wcs(), _wcs((42.3, 43.2), 27.0) + seg = _segmentation() + centre = [2, 3] + got = register_categories(seg, tw, ew, centre, (19, 19), 101) + expected, off = _oracle(seg, tw, ew, centre, (19, 19)) + npt.assert_array_equal(got["SEG_VIGNET"], expected) + npt.assert_array_equal(got["OFF_TILE"], off) + assert np.any(off) and np.any(~off) + # At least one off-tile cell has both in-tile row and column companions. + assert np.any( + off & (~off).any(axis=1)[:, None] & (~off).any(axis=0)[None, :] + ) + assert not np.any(got["NEIGHBOUR"] & off) + + +def test_half_pixel_ties_go_upward(): + # An exact coordinate stub isolates floating-point tie semantics from + # spherical WCS round-trip precision, exercised in the tests above. + identity = SimpleNamespace(all_pix2world=lambda xy, origin: xy) + shift = SimpleNamespace(all_world2pix=lambda xy, origin: xy + 0.5) + seg = np.arange(25, dtype=np.int32).reshape(5, 5) + got = register_categories(seg, shift, identity, [2, 2], (3, 3), 12) + npt.assert_array_equal(got["SEG_VIGNET"], seg[2:5, 2:5]) + + +def test_full_source_covers_pixels_beyond_original_vignet(): + # A target shifted 30 px from the tile barycentre still samples real + # labels; a 51-px tile cutout padded with sky cannot represent this. + tw, ew = _wcs(), _wcs((11.0, 43.0)) + seg = _segmentation() + seg[40:46, 65:72] = 101 + got = register_categories(seg, tw, ew, [42, 40], (51, 51), 101) + expected, off = _oracle(seg, tw, ew, [42, 40], (51, 51)) + npt.assert_array_equal(got["SEG_VIGNET"], expected) + npt.assert_array_equal(got["OFF_TILE"], off) + assert got["SEG_VIGNET"][25, 25] == 101 + + +def _prepare(epoch, tw, ew, obj_id, tile_seg, weight=None, flag=None): + shape = epoch["VIGNET"].shape + name = "2254827-27" + per = lambda a: {str(obj_id): {name: {"VIGNET": a}}} + vignet = SimpleNamespace( + bkg_vign_cat=None, + bkg_rms_vign_cat=None, + flag_vign_cat=per(np.zeros(shape) if flag is None else flag), + weight_vign_cat=per(np.ones(shape) if weight is None else weight), + f_wcs_file={ + "2254827": { + 27: { + "WCS": ew, + "header": fits.Header({"FSCALE": 1.0}).tostring(), + } + } + }, + ) + sky = ew.pixel_to_world(epoch["INT_POS"][1], epoch["INT_POS"][0]) + tile = SimpleNamespace( + vign=np.zeros((1, *shape)), + seg=tile_seg[None], + ra=[sky.ra.deg], + dec=[sky.dec.deg], + ) + return n.prepare_postage_stamps( + vignet, + obj_id, + 0, + tile, + bkg_sub=False, + psf_obj={name: {"VIGNET": np.ones(shape)}}, + gal_obj={name: epoch}, + blend_handling="uberseg", + ) + + +def test_ngmix_consumes_registered_maps_without_flipping(monkeypatch): + seg, tw, ew = _segmentation(), _wcs(), _wcs((40.37, 42.61), 181.2, True) + centre, shape = np.array([42, 40]), (51, 51) + epoch = dict( + VIGNET=np.random.default_rng(3).normal(size=shape), + INT_POS=centre, + OFFSET=np.array([0.2, -0.3]), + ) + epoch.update(register_categories(seg, tw, ew, centre, shape, 101)) + expected, _ = _oracle(seg, tw, ew, centre, shape) + monkeypatch.setattr( + n.Ngmix, + "MegaCamFlip", + lambda *a: pytest.fail("native maps must not be flipped"), + ) + stamp = _prepare(epoch, tw, ew, 101, seg[17:68, 15:66]) + assert len(stamp.gals) == 1 + npt.assert_array_equal(stamp.segs[0], expected) + npt.assert_array_equal(stamp.neighbours[0], epoch["NEIGHBOUR"]) + npt.assert_array_equal(stamp.offsets[0], epoch["OFFSET"]) + + +def test_off_tile_reaches_fraction_cut_before_diagnostics(): + tw, ew = _wcs(), _wcs((41.2, 43.4), 12.0) + shape, centre = (51, 51), [1, 2] + epoch = dict( + VIGNET=np.random.default_rng(2).normal(size=shape), INT_POS=centre + ) + epoch.update( + register_categories(_segmentation(), tw, ew, centre, shape, 101) + ) + assert epoch["OFF_TILE"].mean() > 0.1 + stamp = _prepare(epoch, tw, ew, 101, np.zeros(shape, np.int32)) + assert stamp.epoch_cuts["masked_fraction"] == 1 + assert not stamp.gals + assert stamp.n_epoch_interp == 0 + + +def test_retained_188307_object_5422_epoch_2254827_27(monkeypatch): + path = Path(__file__).parents[1] / "data/registration_188307.npz" + with np.load(path) as f: + tw = WCS(fits.Header.fromstring(str(f["tile_header"]))) + ew = WCS(fits.Header.fromstring(str(f["epoch_header"]))) + epoch = dict( + VIGNET=f["image"], INT_POS=f["int_pos"], OFFSET=f["offset"] + ) + epoch.update( + register_categories( + f["segmentation"], tw, ew, f["int_pos"], (51, 51), 5422 + ) + ) + npt.assert_array_equal(epoch["SEG_VIGNET"], f["expected_seg"]) + assert ( + (epoch["SEG_VIGNET"] == 5422) ^ (f["old_seg"] == 5422) + ).sum() == 10 + assert f["old_seg"][25, 27] == 0 + assert epoch["SEG_VIGNET"][25, 27] == 5422 + assert f["weight"][25, 27] == 0 and f["flag"][25, 27] == 3 + # Isolate the footprint diagnostic; production's fixed-radius veto + # rejects this particular epoch in either registration. + monkeypatch.setattr(n, "central_defect_vetoes", lambda *args: False) + stamp = _prepare( + epoch, tw, ew, 5422, f["old_seg"], f["weight"], f["flag"] + ) + assert len(stamp.gals) == 1 + assert stamp.imaflags_iso == 3 + assert stamp.n_epoch_interp_iso == 1 + + +@pytest.mark.parametrize( + "relative", + [ + "workflow/config/cfis/config_tile_PiViVi_psfex.ini", + "workflow/config/cfis/config_tile_PiViVi_mccd.ini", + "workflow/config/cfis_image_sims/config_tile_PiViVi_fake.ini", + "example/cfis_image_sims/config_tile_PiViVi_canfar_sx.ini", + ], +) +def test_multi_epoch_configs_supply_full_segmentation(relative): + config = ConfigParser(interpolation=None) + config.read(Path(__file__).parents[2] / relative) + sections = [ + s + for s in config.sections() + if s.startswith("VIGNETMAKER") + and config.get(s, "MODE") == "MULTI-EPOCH" + ] + assert sections + for section in sections: + assert ( + config.get(section, "FILE_PATTERN").split(",")[-1].strip() + == "segmentation" + ) + assert ( + config.get(section, "FILE_EXT").split(",")[-1].strip() == ".fits" + ) + + +def test_simulation_example_produces_registration_labels(): + root = Path(__file__).parents[2] / "example/cfis_image_sims" + config = ConfigParser(interpolation=None) + config.read(root / "config_tile_Sx.ini") + assert config.getboolean("SEXTRACTOR_RUNNER", "SEG_VIGNET") + assert "SEGMENTATION" in config.get("SEXTRACTOR_RUNNER", "CHECKIMAGE") + + +def test_vignetmaker_writes_joined_categories_with_image_grid(tmp_path): + seg, tw, ew = _segmentation(), _wcs(), _wcs((40.37, 42.61), 1.7, True) + raw = np.where(seg == 101, 7, np.where(seg != 0, 8, 0)).astype(np.int32) + sky = ew.pixel_to_world(40.27, 42.34) + columns = [ + fits.Column(name="NUMBER", format="J", array=[101]), + fits.Column(name="SEG_LABEL", format="J", array=[7]), + fits.Column(name="N_EPOCH", format="J", array=[1]), + fits.Column(name="XWIN_WORLD", format="D", array=[sky.ra.deg]), + fits.Column(name="YWIN_WORLD", format="D", array=[sky.dec.deg]), + ] + cat = tmp_path / "cat.fits" + fits.HDUList( + [ + fits.PrimaryHDU(), + fits.BinTableHDU(), + fits.BinTableHDU.from_columns(columns), + fits.BinTableHDU.from_columns( + [ + fits.Column( + name="EXP_NAME", format="8A", array=["2254827"] + ), + fits.Column(name="CCD_N", format="J", array=[27]), + ], + name="EPOCH_0", + ), + ] + ).writeto(cat) + seg_path, image_path = ( + tmp_path / "segmentation.fits", + tmp_path / "image-2254827-27.fits", + ) + fits.writeto(seg_path, raw, tw.to_header(relax=True)) + image = np.random.default_rng(4).normal(size=(89, 91)) + fits.writeto(image_path, image) + headers = tmp_path / "headers.sqlite" + with SqliteDict(str(headers)) as db: + db["2254827"] = {27: {"WCS": ew}} + db.commit() + maker = VignetMaker( + str(cat), + "SPHE", + ["XWIN_WORLD", "YWIN_WORLD"], + str(tmp_path), + "-188-307", + SimpleNamespace(info=lambda msg: None), + ) + maker.process_me( + [[str(tmp_path)]], ["image"], str(headers), 25, str(seg_path) + ) + with SqliteDict( + str(tmp_path / "image_vignet-188-307.sqlite"), flag="r" + ) as db: + epoch = db["101"]["2254827-27"] + stamps, ip, offset = get_stamps(image, np.array([[42.34, 40.27]]), 25) + npt.assert_array_equal(epoch["VIGNET"], stamps[0]) + npt.assert_array_equal(epoch["INT_POS"], ip[0]) + npt.assert_allclose(epoch["OFFSET"], offset[0], atol=1e-7) + joined = np.where(raw == 7, 101, np.where(raw != 0, -1, 0)) + expected, off = _oracle(joined, tw, ew, ip[0], (51, 51)) + npt.assert_array_equal(epoch["SEG_VIGNET"], expected) + npt.assert_array_equal(epoch["OFF_TILE"], off) + assert np.any(epoch["SEG_VIGNET"] == -1) + npt.assert_array_equal(epoch["NEIGHBOUR"], expected == -1) diff --git a/tests/module/test_ngmix_defect_fill.py b/tests/module/test_ngmix_defect_fill.py index b24bf971f..0c1d5e127 100644 --- a/tests/module/test_ngmix_defect_fill.py +++ b/tests/module/test_ngmix_defect_fill.py @@ -235,6 +235,9 @@ def per_epoch(make): gal_obj = per_epoch(lambda k: rng.normal(0.0, 1.0, (N_STAMP, N_STAMP))) for epoch in gal_obj.values(): epoch["OFFSET"] = np.zeros(2) + epoch["SEG_VIGNET"] = np.zeros((N_STAMP, N_STAMP), dtype=np.int32) + epoch["NEIGHBOUR"] = np.zeros((N_STAMP, N_STAMP), dtype=bool) + epoch["OFF_TILE"] = np.zeros((N_STAMP, N_STAMP), dtype=bool) vignet = SimpleNamespace( gal_vign_cat={"1": gal_obj}, bkg_vign_cat=None, @@ -814,6 +817,7 @@ def _marker_stamp(tile, epochs=None, **kwargs): epochs = {name: (clean.copy(), ones) for name in _MARKER_EPOCH_NAMES} vignet, tile_cat, psf_obj, gal_obj = _fake_inputs(epochs) tile_cat.vign = tile[np.newaxis] + _put_categories(gal_obj, tile) stamp = prepare_postage_stamps( vignet, 1, 0, tile_cat, bkg_sub=False, psf_obj=psf_obj, gal_obj=gal_obj, **kwargs, @@ -821,6 +825,21 @@ def _marker_stamp(tile, epochs=None, **kwargs): return stamp, epochs, gal_obj +def _put_categories(gal_obj, tile, seg=None): + """Supply native-grid categorical inputs for mask-consumption tests. + + This fixture uses a discrete 180-degree geometry; independent-WCS + registration is tested in test_categorical_registration.py. + """ + neighbour, off_tile = split_tile_markers(tile, tile.shape, seg, 1) + for name, epoch in gal_obj.items(): + ccd = int(name.split("-")[1]) + epoch["NEIGHBOUR"] = Ngmix.MegaCamFlip(neighbour, ccd) + epoch["OFF_TILE"] = Ngmix.MegaCamFlip(off_tile, ccd) + if seg is not None: + epoch["SEG_VIGNET"] = Ngmix.MegaCamFlip(seg, ccd) + + def _expected_neighbours(tile, name): return Ngmix.MegaCamFlip(tile, int(name.split("-")[1])) == _MARKER @@ -1048,6 +1067,7 @@ def _seg_marker_stamp(tile, seg, blend_handling="noisefill"): vignet, tile_cat, psf_obj, gal_obj = _fake_inputs(epochs) tile_cat.vign = tile[np.newaxis] tile_cat.seg = seg[np.newaxis] + _put_categories(gal_obj, tile, seg) return prepare_postage_stamps( vignet, _OBJ, 0, tile_cat, bkg_sub=False, psf_obj=psf_obj, gal_obj=gal_obj, blend_handling=blend_handling, @@ -1077,16 +1097,17 @@ def test_noisefill_keeps_light_under_non_neighbour_markers(): assert np.all(weight[stamp.neighbours[i]] == 0) -def test_uberseg_is_unchanged_by_seg_defined_neighbours(monkeypatch): +def test_uberseg_is_unchanged_by_seg_defined_neighbours(): """Uberseg reads no marker, so defining neighbours by the seg map leaves every epoch's observation bit-identical: the same epochs survive, with the same image, weight and noise image. Noisefill does change. """ tile, seg, _ = _seg_marked_tile() - marker_split = split_tile_markers - - def observations(blend_handling): + def observations(blend_handling, bare_markers=False): stamp = _seg_marker_stamp(tile, seg, blend_handling) + if bare_markers: + stamp.neighbours = [_expected_neighbours(tile, name) + for name in stamp.epoch_names] out = [] for i in range(len(stamp.gals)): obs = make_ngmix_observation( @@ -1100,11 +1121,8 @@ def observations(blend_handling): return stamp.epoch_names, out new = {b: observations(b) for b in ("uberseg", "noisefill")} - monkeypatch.setattr( - ngmix_module, "split_tile_markers", - lambda t, shape, seg=None, object_number=None: marker_split(t, shape), - ) - old = {b: observations(b) for b in ("uberseg", "noisefill")} + old = {b: observations(b, bare_markers=True) + for b in ("uberseg", "noisefill")} assert new["uberseg"][0] == old["uberseg"][0] for got, want in zip(new["uberseg"][1], old["uberseg"][1]): diff --git a/tests/module/test_ngmix_defect_flags.py b/tests/module/test_ngmix_defect_flags.py index 53118cf5a..bd801059d 100644 --- a/tests/module/test_ngmix_defect_flags.py +++ b/tests/module/test_ngmix_defect_flags.py @@ -40,7 +40,11 @@ def _run(kind="inside", seg_kind="valid", megacam_flip=True): flag[25, 25] = 64 epochs[f"210000{i}-20"] = (flag, np.ones(seg.shape)) vignet, tile, psf, gal = _fake_inputs(epochs) - tile.seg = None if seg_kind == "missing" else seg[None] + tile.seg = seg[None] + for name, epoch in gal.items(): + epoch["SEG_VIGNET"] = Ngmix.MegaCamFlip(seg, int(name.split("-")[1])) + if seg_kind == "missing": + del epoch["SEG_VIGNET"] return prepare_postage_stamps( vignet, 1, 0, tile, bkg_sub=False, psf_obj=psf, gal_obj=gal, ) @@ -66,13 +70,18 @@ def test_footprint_flags_only_count_kept_epochs(kind, expected, flip): assert diagnostics["n_epoch_interp"] == (0 if kind == "clean" else 2) -@pytest.mark.parametrize("seg_kind", ["missing", "empty", "clipped"]) +@pytest.mark.parametrize("seg_kind", ["empty", "clipped"]) def test_unknown_or_incomplete_footprint_is_not_clean(seg_kind): diagnostics = _run(seg_kind=seg_kind).defect_diagnostics() assert diagnostics["imaflags_iso"] == -1 assert diagnostics["n_epoch_interp_iso"] == -1 +def test_missing_exposure_categories_require_reextraction(): + with pytest.raises(ValueError, match="Exposure-grid categories"): + _run(seg_kind="missing") + + @pytest.mark.parametrize("value", [np.nan, np.inf, -1, 1.5, float(2**63)]) def test_non_integral_or_unsafe_flags_raise(value): """Do not silently truncate float flags or overflow the integer OR.""" diff --git a/tests/module/test_ngmix_uberseg.py b/tests/module/test_ngmix_uberseg.py index 4be3ee697..54cc29b85 100644 --- a/tests/module/test_ngmix_uberseg.py +++ b/tests/module/test_ngmix_uberseg.py @@ -313,7 +313,7 @@ def test_check_central_seg_label_matching_number_is_silent(tmp_path): def test_check_central_seg_label_offset_centre_warns_but_proceeds(tmp_path): - """A neighbour's label on the centre pixel (registration offset) warns but + """A neighbour's label on the tile barycentre logs a diagnostic but does not raise, as long as obj_id's footprint is present somewhere.""" ngmix, log = _make_ngmix(tmp_path) seg, centre, _ = two_object_seg() @@ -321,7 +321,7 @@ def test_check_central_seg_label_offset_centre_warns_but_proceeds(tmp_path): # has its footprint elsewhere on the stamp. seg[centre] = 2 ngmix._check_central_seg_label(seg, obj_id=1) - assert any("registration offset" in m for m in log.messages) + assert any("tile barycentre" in m for m in log.messages) def test_check_central_seg_label_missing_number_raises(tmp_path): diff --git a/tests/module/test_sextractor_seg_vignet.py b/tests/module/test_sextractor_seg_vignet.py index 4bf221a17..c6f64ac8c 100644 --- a/tests/module/test_sextractor_seg_vignet.py +++ b/tests/module/test_sextractor_seg_vignet.py @@ -152,7 +152,8 @@ def test_seg_vignet_replaces_the_double_positions(tmp_path): imhead = hdul["LDAC_IMHEAD"].data.copy() _, after = _add(paths) kept = [name for name in before.names if name not in DBL] - assert after.names == kept + ["SEG_VIGNET"] + assert after.names == kept + ["SEG_VIGNET", "SEG_LABEL"] + npt.assert_array_equal(after["SEG_LABEL"], before["NUMBER"]) for name in kept: npt.assert_array_equal(after[name], before[name]) with fits.open(paths["sexcat"]) as hdul: @@ -335,6 +336,7 @@ def test_runner_seg_vignet_carries_the_final_number(tmp_path, monkeypatch): old_number = np.array([CROWD[i][0] for i in paired]) new_number = np.array([CROWD[i][3] for i in paired]) npt.assert_array_equal(data["NUMBER"], new_number) + npt.assert_array_equal(data["SEG_LABEL"], old_number) seg = data["SEG_VIGNET"] assert "X_IMAGE_DBL" not in data.names centre = CROWD_STAMP // 2 @@ -359,6 +361,7 @@ def test_runner_seg_vignet_without_a_join_keeps_sextractor_numbers( stamps are the check image's, labelled with SExtractor's NUMBER.""" data = _run_runner(tmp_path, monkeypatch, match=False) npt.assert_array_equal(data["NUMBER"], [o[0] for o in CROWD]) + npt.assert_array_equal(data["SEG_LABEL"], data["NUMBER"]) npt.assert_array_equal(data["SEG_VIGNET"], _old_stamps()) @@ -447,5 +450,5 @@ def test_seg_vignet_stays_out_of_the_final_catalogue(tmp_path): names = list( make_cat.read_sextractor_data(str(tmp_path / "sexcat-001-001.fits")) ) - assert "VIGNET" not in names and "SEG_VIGNET" not in names + assert not {"VIGNET", "SEG_VIGNET", "SEG_LABEL"}.intersection(names) assert "NUMBER" in names diff --git a/tests/mutations/flip_only_overlay.py b/tests/mutations/flip_only_overlay.py new file mode 100644 index 000000000..d8bc6ed3c --- /dev/null +++ b/tests/mutations/flip_only_overlay.py @@ -0,0 +1,61 @@ +"""Verify that registration regressions kill a flip-only ngmix mutant. + +Run inside the test environment from any directory:: + + python tests/mutations/flip_only_overlay.py + +The mutant lives in a temporary source tree; the checkout is not modified. +This command succeeds only when all three selected regressions fail. +""" + +import os +from pathlib import Path +import shutil +import subprocess +import sys +import tempfile + + +ROOT = Path(__file__).resolve().parents[2] +TARGET = Path("shapepipe/modules/ngmix_package/ngmix.py") +NATIVE = ( + " tile_seg, neighbour, off_tile = " + "(np.asarray(epoch[name]) for name in required)\n" +) +FLIP_ONLY = """ tile_seg = Ngmix.MegaCamFlip(np.copy(tile_cat.seg[i_tile]), int(ccd_n)) + tile_vign = Ngmix.MegaCamFlip(np.copy(tile_cat.vign[i_tile]), int(ccd_n)) + neighbour, off_tile = split_tile_markers(tile_vign, gal_vign.shape, tile_seg, obj_id) +""" + + +def main(): + """Run the independent-grid, off-tile-cut and retained-footprint guards.""" + with tempfile.TemporaryDirectory(prefix="flip-only-mutant-") as temporary: + source = Path(temporary) / "src" + shutil.copytree(ROOT / "src", source) + target = source / TARGET + text = target.read_text() + assert text.count(NATIVE) == 1, "Native-map consumption site changed" + target.write_text(text.replace(NATIVE, FLIP_ONLY)) + env = dict(os.environ) + env["PYTHONPATH"] = os.pathsep.join( + (str(source), str(ROOT), env.get("PYTHONPATH", "")) + ) + env["PYTEST_DISABLE_PLUGIN_AUTOLOAD"] = "1" + result = subprocess.run( + [sys.executable, "-m", "pytest", + str(ROOT / "tests/module/test_categorical_registration.py"), + "-k", "ngmix_consumes or off_tile_reaches or retained_188307", + "-o", "addopts=", "-q", "--tb=short"], + cwd=ROOT, env=env, capture_output=True, text=True, + ) + print(result.stdout) + print(result.stderr, file=sys.stderr) + assert result.returncode == 1 and "3 failed" in result.stdout, ( + "The flip-only overlay mutant must fail all three regressions" + ) + print("Flip-only mutant killed: all three regressions failed.") + + +if __name__ == "__main__": + main() diff --git a/universes/committed.yaml b/universes/committed.yaml index 13b5e3503..24f32b327 100644 --- a/universes/committed.yaml +++ b/universes/committed.yaml @@ -34,6 +34,7 @@ analyses: epoch_provenance_from_tile_history: history_parse object_position_columns: xwin_windowed stamp_positioning_and_padding: round_and_zero_pad + categorical_registration: native_grid_nearest star_selection_psf: decisions: star_selection_box: locus_scaled_box @@ -54,7 +55,6 @@ analyses: psf_epoch_averaging: galaxy_weight_sum galaxy_pixel_weights: rms_vignet_weights psf_likelihood_noise: psf_noise_1em5 - megacam_ccd_flip: megapipe_flip defect_fill: interpolate defect_flagging: footprint_or_and_interp_epochs blend_handling: uberseg diff --git a/workflow/config/cfis/config_tile_PiViVi_mccd.ini b/workflow/config/cfis/config_tile_PiViVi_mccd.ini index 838018c2d..9da6f93c3 100644 --- a/workflow/config/cfis/config_tile_PiViVi_mccd.ini +++ b/workflow/config/cfis/config_tile_PiViVi_mccd.ini @@ -112,9 +112,9 @@ ME_DOT_PSF_PATTERN = fitted_model INPUT_DIR = $SP_RUN/output/run_sp_tile_Sx/sextractor_runner/output, $SP_RUN/output/run_sp_tile_Mh_exp/merge_headers_runner/output, $SP_RUN/output/run_sp_tile_Fe/find_exposures_runner/output -FILE_PATTERN = sexcat, log_exp_headers, exp_numbers +FILE_PATTERN = sexcat, log_exp_headers, exp_numbers, segmentation -FILE_EXT = .fits, .sqlite, .txt +FILE_EXT = .fits, .sqlite, .txt, .fits # NUMBERING_SCHEME (optional) string with numbering pattern for input files NUMBERING_SCHEME = -000-000 diff --git a/workflow/config/cfis/config_tile_PiViVi_psfex.ini b/workflow/config/cfis/config_tile_PiViVi_psfex.ini index 66cc25507..304155309 100644 --- a/workflow/config/cfis/config_tile_PiViVi_psfex.ini +++ b/workflow/config/cfis/config_tile_PiViVi_psfex.ini @@ -125,9 +125,9 @@ ME_DOT_PSF_PATTERN = star_split_ratio_80 INPUT_DIR = $SP_RUN/output/run_sp_tile_Sx/sextractor_runner/output, $SP_RUN/output/run_sp_tile_Mh_exp/merge_headers_runner/output, $SP_RUN/output/run_sp_tile_Fe/find_exposures_runner/output -FILE_PATTERN = sexcat, log_exp_headers, exp_numbers +FILE_PATTERN = sexcat, log_exp_headers, exp_numbers, segmentation -FILE_EXT = .fits, .sqlite, .txt +FILE_EXT = .fits, .sqlite, .txt, .fits # NUMBERING_SCHEME (optional) string with numbering pattern for input files NUMBERING_SCHEME = -000-000 diff --git a/workflow/config/cfis_image_sims/config_tile_PiViVi_fake.ini b/workflow/config/cfis_image_sims/config_tile_PiViVi_fake.ini index e3ef8bfad..30397205b 100644 --- a/workflow/config/cfis_image_sims/config_tile_PiViVi_fake.ini +++ b/workflow/config/cfis_image_sims/config_tile_PiViVi_fake.ini @@ -100,9 +100,9 @@ PSF_DICT_PATH = $PSF_DICT INPUT_DIR = $SP_RUN/output/run_sp_tile_Sx/sextractor_runner/output, $SP_RUN/output/run_sp_tile_Mh_exp/merge_headers_runner/output, $SP_RUN/output/run_sp_tile_Fe/find_exposures_runner/output -FILE_PATTERN = sexcat, log_exp_headers, exp_numbers +FILE_PATTERN = sexcat, log_exp_headers, exp_numbers, segmentation -FILE_EXT = .fits, .sqlite, .txt +FILE_EXT = .fits, .sqlite, .txt, .fits # NUMBERING_SCHEME (optional) string with numbering pattern for input files NUMBERING_SCHEME = -000-000 From 6bfd7d4cffa2cef8cc4e7b1e78e5748a3a0bb0a1 Mon Sep 17 00:00:00 2001 From: Cail Daley Date: Thu, 29 Oct 2026 16:16:46 -0400 Subject: [PATCH 2/7] Validate Gaia-referenced celestial frame contract --- astra.yaml | 65 ++++---- src/shapepipe/modules/ngmix_package/ngmix.py | 4 +- .../vignetmaker_package/vignetmaker.py | 71 ++++++++- tests/data/registration_188307.md | 5 +- tests/data/registration_188307.npz | Bin 15677 -> 26529 bytes tests/module/test_categorical_registration.py | 28 +++- tests/module/test_registration_frames.py | 144 ++++++++++++++++++ workflow/rules/tile.smk | 24 +-- 8 files changed, 291 insertions(+), 50 deletions(-) create mode 100644 tests/module/test_registration_frames.py diff --git a/astra.yaml b/astra.yaml index f8be0dcbf..3e4bb8eee 100644 --- a/astra.yaml +++ b/astra.yaml @@ -126,10 +126,11 @@ decisions: Every stamp width is 51 px (about 9.5 arcsec): the tile VIGNET (cut by the tile SExtractor run), the multi-epoch vignetmaker stamps ngmix fits, the exposure SExtractor VIGNET PSFEx trains on, and the - PSFEx model stamp. Only the first two are coupled: ngmix lays the tile - VIGNET's -1e30 neighbour markers over each epoch stamp pixel for pixel, - so they must be the same size. The stamp truncates the wings of large - galaxies. No rationale for 51 px is recorded. + PSFEx model stamp. Exposure-grid categories are sampled from the full + tile segmentation, independently of the tile VIGNET width; categorical + registration does not couple tile and exposure stamp widths. The + stamp truncates the wings of large galaxies. No rationale for 51 px + is recorded. Values: default_noimaflags.param#VIGNET = 51; default.param#VIGNET = 51; @@ -321,8 +322,9 @@ analyses: shape_measurement.epoch_masked_fraction_cut). Tiles have no flag image, and ShapePipe's tile SExtractor run requests no IMAFLAGS_ISO (detection.detection_source_mode). Neighbour pixels are masked - separately, from the -1e30 markers SExtractor writes into the tile - VIGNET and the coadd segmentation map + separately, from full-tile segmentation labels sampled on each + native exposure grid: noisefill fills foreign nonzero footprints, + and UberSeg partitions the registered labels (shape_measurement.blend_handling). Sky-fixed masks never touch pixels: a star halo changes no stamp. Values: @@ -867,8 +869,11 @@ analyses: step on exposures uses that solution: epoch membership, multi-epoch stamp placement and OFFSET, tile-side PSF interpolation positions, and the per-epoch ngmix Jacobian. [HARDCODED] No - astrometric re-derivation or refinement exists. A re-fit would shift - stamp centres and Jacobians and could change epoch membership. + astrometric re-derivation or refinement exists. Categorical + registration normalises Gaia-referenced FK5/J2000 frame annotations + under preparation.categorical_registration without changing the + numerical solution. A re-fit would shift stamp centres and + Jacobians and could change epoch membership. default: delivered_headers options: delivered_headers: @@ -957,7 +962,16 @@ analyses: with full-tile support independent of VIGNET's marker coverage. UberSeg recomputes its Voronoi partition on the registered labels. These maps enter ngmix before masks, cuts and footprint diagnostics. - A flip alone cannot register independent pixel grids and centroids. + Numerical sky coordinates require equivalent celestial frames, + including equinox where applicable. An FK5/J2000 exposure whose + ASTCAT has a case-insensitive gaia token is treated as numerical + ICRS: frame metadata is normalised on a WCS copy, without a sky + coordinate conversion. Tokens are delimited by non-alphanumeric + characters. On 500 compact centroids in 188.307 (PR #985 review), + the median residual is (+0.006,+0.003) px under this interpretation + versus (-0.044,-0.010) px with FK5-to-ICRS conversion. All remaining + frame mismatches raise. A flip alone cannot register independent + pixel grids and centroids. default: native_grid_nearest options: native_grid_nearest: @@ -1613,16 +1627,15 @@ analyses: noise-filled defects at least 13 px away. Only the defect pixels are filled, not a four-fold symmetrized mask as in DES, since symmetrizing quadruples m and leaves an additive c1 (symmetrized_4fold_noise); the hole this - leaves near the galaxy is bounded by central_defect_veto. In the - tile VIGNET, SExtractor writes -1e30 beyond the tile edge and over - every above-threshold pixel outside the object's pre-CLEAN - footprint. Rows and columns that are entirely -1e30 and start at - the stamp border are off-tile, hence defects (the epoch has the - object's light there); the other -1e30 pixels on another object's - segmentation footprint are neighbours, handled by blend_handling. - The rest (sub-MINAREA noise peaks, the object's own CLEAN-merged - fragments) are not defects either: the epoch stamps hold real - light there, so they keep their weight and image. + leaves near the galaxy is bounded by central_defect_veto. Off-tile + cells are those whose nearest tile pixel centre is outside the full + segmentation image after WCS sampling on the exposure grid. They + are defects because the native exposure can hold the object's light + beyond the tile rectangle. Foreign nonzero registered segmentation + footprints are neighbours, handled by blend_handling rather than + counted as defects. Own CLEAN-merged fragments and sky are not + defects solely by their segmentation labels; blend handling can + still mask nearby sky. Values: VIGNETMAKER_RUNNER.MASKING = False; ngmix.py::DEFECT_FILL = "interpolate". @@ -1689,9 +1702,9 @@ analyses: depend on it: defects are filled the same way under every BLEND_HANDLING, and the epoch cuts never count neighbour pixels. The committed choice is uberseg (the workflow's default - blend_handling), which ignores the -1e30 neighbour markers in the - tile VIGNET and zeroes the weight of pixels nearer a neighbour's - coadd segmentation footprint than the target's (DILATE_NEIGHBOUR, + blend_handling), which partitions the registered full-tile labels + and zeroes the weight of pixels nearer a neighbour's sampled + footprint than the target's (DILATE_NEIGHBOUR, default 1), leaving the neighbour side's image untouched, as official uberseg does: esheldon/meds get_uberseg returns a weight map (a @@ -1827,10 +1840,10 @@ analyses: reads the same interpolated set as the fill, including the runs that end on a noisefill neighbour and so are noise-filled. Under defect_fill noise that set is empty, so every defect is vetoed at - 13 px. The tile - VIGNET's -1e30 neighbour markers are not defects: all epochs share - the tile VIGNET, so a neighbour inside the radius would drop every - epoch. Off-tile pixels are defects, so an object near the tile edge + 13 px. Foreign nonzero segmentation footprints sampled on the + exposure grid are neighbours, not defects: counting them would + reject blended objects. Off-tile pixels from the sampled tile + rectangle are defects, so an object near the tile edge is vetoed. The veto reads only masks, so it selects on nothing shear-responsive; for the same reason the radii are fixed rather than scaled by galaxy size. Each radius is the smallest at which diff --git a/src/shapepipe/modules/ngmix_package/ngmix.py b/src/shapepipe/modules/ngmix_package/ngmix.py index 4010166d1..cf1dc8f44 100644 --- a/src/shapepipe/modules/ngmix_package/ngmix.py +++ b/src/shapepipe/modules/ngmix_package/ngmix.py @@ -668,8 +668,8 @@ def __init__( self.psfs = [] self.weights = [] self.flags = [] - # Exposure-grid neighbour masks, projected upstream from tile - # other-footprint markers. Epoch cuts do not count neighbours. + # Exposure-grid neighbour masks from full-tile foreign nonzero + # segmentation footprints. Epoch cuts do not count neighbours. self.neighbours = [] self.bkg_rms = [] # Exposure-grid segmentation stamps, sampled upstream from the full diff --git a/src/shapepipe/modules/vignetmaker_package/vignetmaker.py b/src/shapepipe/modules/vignetmaker_package/vignetmaker.py index 228a11408..fa1f96f71 100644 --- a/src/shapepipe/modules/vignetmaker_package/vignetmaker.py +++ b/src/shapepipe/modules/vignetmaker_package/vignetmaker.py @@ -11,6 +11,8 @@ import numpy as np from astropy.wcs import WCS +from astropy.wcs.utils import wcs_to_celestial_frame +from astropy.coordinates import FK5 from astropy.io import fits from sqlitedict import SqliteDict @@ -86,8 +88,60 @@ def get_stamps(image, positions, rad): return stamps, int_pos, offsets +def normalise_registration_wcs(tile_wcs, epoch_wcs, epoch_header=None): + """Validate a common numerical celestial frame for categorical sampling. + + @sc [decision:preparation.categorical_registration] + An exposure in FK5/J2000 with a case-insensitive ``gaia`` token in its + header's ``ASTCAT`` has ICRS numerical coordinates. Normalize that WCS's + frame metadata on a copy, without transforming coordinates or changing + the input WCS/header. Tokens are delimited by non-alphanumeric characters. + All other exposures retain their declared frame. The resulting exposure + and tile celestial frames, including equinox where applicable, must be + equivalent; an unsupported or mismatched frame raises ``ValueError``. + + Parameters + ---------- + tile_wcs, epoch_wcs : astropy.wcs.WCS + Tile and native exposure coordinate systems. + epoch_header : mapping, optional + Exposure header carrying the astrometric reference catalogue ASTCAT. + + Returns + ------- + astropy.wcs.WCS + The exposure WCS in the validated common numerical frame. + """ + tile_frame = wcs_to_celestial_frame(tile_wcs) + epoch_frame = wcs_to_celestial_frame(epoch_wcs) + astcat = str((epoch_header or {}).get("ASTCAT", "")).casefold() + gaia_reference = "gaia" in re.split(r"[^a-z0-9]+", astcat) + if ( + isinstance(epoch_frame, FK5) + and epoch_frame.equinox.jyear == 2000.0 + and gaia_reference + ): + # On 188.307, 500 compact centroids give median residuals + # (+0.006, +0.003) px with common ICRS numbers, versus + # (-0.044, -0.010) px after FK5->ICRS conversion (PR #985 review). + # ASTCAT identifies these Gaia-referenced solutions as numerical ICRS. + epoch_wcs = epoch_wcs.deepcopy() + epoch_wcs.wcs.radesys = "ICRS" + epoch_wcs.wcs.equinox = np.nan + epoch_wcs.wcs.set() + epoch_frame = wcs_to_celestial_frame(epoch_wcs) + if not tile_frame.is_equivalent_frame(epoch_frame): + raise ValueError( + "Categorical registration requires equivalent celestial frames: " + f"tile={tile_frame!r}, exposure={epoch_frame!r}; only Gaia ASTCAT " + "FK5/J2000 exposure metadata may be normalized to ICRS" + ) + return epoch_wcs + + def register_categories( - segmentation, tile_wcs, epoch_wcs, int_pos, shape, object_number + segmentation, tile_wcs, epoch_wcs, int_pos, shape, object_number, + epoch_header=None, ): """Sample tile categories at native exposure-stamp pixel centres. @@ -101,6 +155,8 @@ def register_categories( Noisefill uses this full neighbour footprint; UberSeg recomputes its nearest-segment partition on the registered labels. Neither images nor detector masks are resampled. + :func:`normalise_registration_wcs` validates the celestial-frame contract + before numerical coordinates pass between the WCSs. Parameters ---------- @@ -115,12 +171,15 @@ def register_categories( Exposure stamp shape. object_number : int Target's catalogue NUMBER. + epoch_header : mapping, optional + Exposure header for the Gaia/FK5-J2000 frame-normalisation rule. Returns ------- dict Exposure-grid ``SEG_VIGNET``, ``NEIGHBOUR`` and ``OFF_TILE`` maps. """ + epoch_wcs = normalise_registration_wcs(tile_wcs, epoch_wcs, epoch_header) row, col = np.indices(shape, dtype=float) xy = np.stack( (col - shape[1] // 2 + int_pos[1], row - shape[0] // 2 + int_pos[0]), @@ -440,7 +499,15 @@ def _get_stamp_me(self, image_dirs, image_pattern): ind_obj = np.where(cat.get_data(hdu_index)["CCD_N"] == ccd)[0] obj_id = all_id[ind_obj] - wcs_file = self._f_wcs_file[exp_name][ccd]["WCS"] + ccd_info = self._f_wcs_file[exp_name][ccd] + wcs_file = ccd_info["WCS"] + if categories is not None: + header = ccd_info.get("header") + if isinstance(header, str): + header = fits.Header.fromstring(header) + wcs_file = normalise_registration_wcs( + tile_wcs, wcs_file, header + ) pos = np.array( wcs_file.all_world2pix( self._pos[:, 1][ind_obj], diff --git a/tests/data/registration_188307.md b/tests/data/registration_188307.md index 940ced044..d071c49ff 100644 --- a/tests/data/registration_188307.md +++ b/tests/data/registration_188307.md @@ -6,7 +6,10 @@ Other detections use label −1 and sky uses label 0. The source segmentation rectangle is the zero-based full-tile slice `[1420:1510, 640:735]`. `tile_header` is the tile WCS sliced to that rectangle, including the adjusted reference pixel. -`epoch_header` is the independently retained exposure WCS. +`epoch_header` is the full independently retained exposure header for 2254827-27. +It contains `RADECSYS=FK5`, `EQUINOX=2000`, and the Gaia reference card `ASTCAT=test.gaia`, while the tile declares ICRS. +The registration contract normalises this exposure's frame metadata to ICRS without changing its numerical solution. +The frame regressions compare all three categorical maps with the direct numerical lookup and reject an unapproved mixed-frame input. `int_pos`, `offset`, `image`, `weight`, `flag` and `rms` come from the retained epoch stores listed in `/scratch/cdaley/veto-survey/prevalence_checks.json` on Nibi. The original tile catalogue is `sexcat-188-307.fits` under `defectflag-check/run/188307/work/tiles/18/188.307/output/run_sp_tile_Sx/sextractor_runner/output`. diff --git a/tests/data/registration_188307.npz b/tests/data/registration_188307.npz index 2fa1337e19b6f5d9c7fb36dae6c4bf241a018552..9347a177c6a6e3081e1a742b4c99ed3c9e9ca577 100644 GIT binary patch delta 12639 zcmaibc~lcg*Zz!-GQKXjq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1UfqFp2BN31aBq_jXBCqYW*P!|43jQqHVF$2003!iVP|EN5N8yVfo2*4G8vPd yW;O`x82|ugY++}U5N8yV?`9eTp&FA5XEOpzIFmqUJOX|>lYVC%2CO;&0000jfPQoU diff --git a/tests/module/test_categorical_registration.py b/tests/module/test_categorical_registration.py index 86ecef091..cc9e86cc9 100644 --- a/tests/module/test_categorical_registration.py +++ b/tests/module/test_categorical_registration.py @@ -113,11 +113,12 @@ def test_rotated_tile_edge_is_not_a_border_run_heuristic(): assert not np.any(got["NEIGHBOUR"] & off) -def test_half_pixel_ties_go_upward(): +def test_half_pixel_ties_go_upward(monkeypatch): # An exact coordinate stub isolates floating-point tie semantics from # spherical WCS round-trip precision, exercised in the tests above. - identity = SimpleNamespace(all_pix2world=lambda xy, origin: xy) - shift = SimpleNamespace(all_world2pix=lambda xy, origin: xy + 0.5) + identity, shift = _wcs(), _wcs() + monkeypatch.setattr(identity, "all_pix2world", lambda xy, origin: xy) + monkeypatch.setattr(shift, "all_world2pix", lambda xy, origin: xy + 0.5) seg = np.arange(25, dtype=np.int32).reshape(5, 5) got = register_categories(seg, shift, identity, [2, 2], (3, 3), 12) npt.assert_array_equal(got["SEG_VIGNET"], seg[2:5, 2:5]) @@ -215,13 +216,15 @@ def test_retained_188307_object_5422_epoch_2254827_27(monkeypatch): path = Path(__file__).parents[1] / "data/registration_188307.npz" with np.load(path) as f: tw = WCS(fits.Header.fromstring(str(f["tile_header"]))) - ew = WCS(fits.Header.fromstring(str(f["epoch_header"]))) + epoch_header = fits.Header.fromstring(str(f["epoch_header"])) + ew = WCS(epoch_header) epoch = dict( VIGNET=f["image"], INT_POS=f["int_pos"], OFFSET=f["offset"] ) epoch.update( register_categories( - f["segmentation"], tw, ew, f["int_pos"], (51, 51), 5422 + f["segmentation"], tw, ew, f["int_pos"], (51, 51), 5422, + epoch_header=epoch_header, ) ) npt.assert_array_equal(epoch["SEG_VIGNET"], f["expected_seg"]) @@ -279,8 +282,11 @@ def test_simulation_example_produces_registration_labels(): assert "SEGMENTATION" in config.get("SEXTRACTOR_RUNNER", "CHECKIMAGE") -def test_vignetmaker_writes_joined_categories_with_image_grid(tmp_path): +@pytest.mark.parametrize("gaia_fk5", [False, True]) +def test_vignetmaker_writes_joined_categories_with_image_grid(tmp_path, gaia_fk5): seg, tw, ew = _segmentation(), _wcs(), _wcs((40.37, 42.61), 1.7, True) + if gaia_fk5: + ew.wcs.radesys, ew.wcs.equinox = "FK5", 2000.0 raw = np.where(seg == 101, 7, np.where(seg != 0, 8, 0)).astype(np.int32) sky = ew.pixel_to_world(40.27, 42.34) columns = [ @@ -315,8 +321,11 @@ def test_vignetmaker_writes_joined_categories_with_image_grid(tmp_path): image = np.random.default_rng(4).normal(size=(89, 91)) fits.writeto(image_path, image) headers = tmp_path / "headers.sqlite" + epoch_header = ew.to_header(relax=True) + if gaia_fk5: + epoch_header["ASTCAT"] = "test.gaia" with SqliteDict(str(headers)) as db: - db["2254827"] = {27: {"WCS": ew}} + db["2254827"] = {27: {"WCS": ew, "header": epoch_header.tostring()}} db.commit() maker = VignetMaker( str(cat), @@ -338,7 +347,10 @@ def test_vignetmaker_writes_joined_categories_with_image_grid(tmp_path): npt.assert_array_equal(epoch["INT_POS"], ip[0]) npt.assert_allclose(epoch["OFFSET"], offset[0], atol=1e-7) joined = np.where(raw == 7, 101, np.where(raw != 0, -1, 0)) - expected, off = _oracle(joined, tw, ew, ip[0], (51, 51)) + oracle_epoch = ew.deepcopy() + if gaia_fk5: + oracle_epoch.wcs.radesys, oracle_epoch.wcs.equinox = "ICRS", np.nan + expected, off = _oracle(joined, tw, oracle_epoch, ip[0], (51, 51)) npt.assert_array_equal(epoch["SEG_VIGNET"], expected) npt.assert_array_equal(epoch["OFF_TILE"], off) assert np.any(epoch["SEG_VIGNET"] == -1) diff --git a/tests/module/test_registration_frames.py b/tests/module/test_registration_frames.py new file mode 100644 index 000000000..24f0c3028 --- /dev/null +++ b/tests/module/test_registration_frames.py @@ -0,0 +1,144 @@ +"""Explicit numerical-frame contract for categorical registration.""" + +from pathlib import Path + +import numpy as np +import numpy.testing as npt +import pytest +from astropy.coordinates import FK5, SkyCoord +from astropy.io import fits +from astropy.wcs import WCS + +from shapepipe.modules.vignetmaker_package.vignetmaker import ( + normalise_registration_wcs, + register_categories, +) + +pytestmark = pytest.mark.decision("preparation.categorical_registration") + + +def _icrs(): + wcs = WCS(naxis=2) + wcs.wcs.ctype = ["RA---TAN", "DEC--TAN"] + wcs.wcs.radesys = "ICRS" + wcs.wcs.crval = [210.0, 63.5] + wcs.wcs.crpix = [51.0, 51.0] + wcs.wcs.cdelt = [-0.18577 / 3600, 0.18577 / 3600] + return wcs + + +def _numeric_maps(seg, tile_wcs, epoch_wcs, centre, shape, number): + """Numerical lookup with no frame reinterpretation or conversion.""" + rr, cc = np.indices(shape) + xy = np.column_stack( + ((cc + centre[1] - shape[1] // 2).ravel(), + (rr + centre[0] - shape[0] // 2).ravel()) + ) + world = epoch_wcs.all_pix2world(xy, 0) + tile = tile_wcs.all_world2pix(world, 0) + x, y = np.floor(tile + .5).astype(int).T + inside = (x >= 0) & (x < seg.shape[1]) & (y >= 0) & (y < seg.shape[0]) + expected = np.zeros(len(x), np.int32) + expected[inside] = seg[y[inside], x[inside]] + expected = expected.reshape(shape) + return dict(SEG_VIGNET=expected, OFF_TILE=~inside.reshape(shape), + NEIGHBOUR=(expected != 0) & (expected != number)) + + +def test_real_gaia_fk5_header_preserves_numerical_lookup(): + path = Path(__file__).parents[1] / "data/registration_188307.npz" + with np.load(path) as data: + tile_header = fits.Header.fromstring(str(data["tile_header"])) + epoch_header = fits.Header.fromstring(str(data["epoch_header"])) + assert tile_header["RADESYS"] == "ICRS" + assert epoch_header["RADECSYS"] == "FK5" + assert epoch_header["EQUINOX"] == 2000.0 + assert epoch_header["ASTCAT"] == "test.gaia" + tw, ew = WCS(tile_header), WCS(epoch_header) + expected = _numeric_maps( + data["segmentation"], tw, ew, data["int_pos"], (51, 51), 5422 + ) + got = register_categories( + data["segmentation"], tw, ew, data["int_pos"], (51, 51), 5422, + epoch_header=epoch_header, + ) + for key in expected: + npt.assert_array_equal(got[key], expected[key]) + npt.assert_array_equal(got["SEG_VIGNET"], data["expected_seg"]) + common = normalise_registration_wcs(tw, ew, epoch_header) + assert common is not ew + assert common.wcs.radesys == "ICRS" + assert np.isnan(common.wcs.equinox) + assert ew.wcs.radesys == "FK5" and ew.wcs.equinox == 2000.0 + assert epoch_header["RADECSYS"] == "FK5" + pixels = np.array([[1., 2.], [1000.2, 1700.7]]) + npt.assert_array_equal( + common.all_pix2world(pixels, 0), ew.all_pix2world(pixels, 0) + ) + # A WCS alone cannot establish Gaia provenance. + with pytest.raises(ValueError, match="equivalent celestial frames"): + register_categories( + data["segmentation"], tw, ew, data["int_pos"], (51, 51), 5422 + ) + + +def test_genuinely_mixed_fk5_icrs_coordinates_raise(): + tw = _icrs() + ew = tw.deepcopy() + fk5 = SkyCoord(*tw.wcs.crval, unit="deg", frame="icrs").transform_to( + FK5(equinox="J2000") + ) + ew.wcs.crval = [fk5.ra.deg, fk5.dec.deg] + ew.wcs.radesys = "FK5" + ew.wcs.equinox = 2000.0 + seg = np.arange(101 * 101, dtype=np.int32).reshape(101, 101) + with pytest.raises(ValueError, match="equivalent celestial frames"): + register_categories( + seg, tw, ew, [50, 50], (11, 11), 5100, + epoch_header={"ASTCAT": "2MASS"}, + ) + + +def test_icrs_control_matches_numerical_lookup(): + tw, ew = _icrs(), _icrs() + ew.wcs.crpix += [.51, .51] + seg = np.arange(101 * 101, dtype=np.int32).reshape(101, 101) + expected = _numeric_maps(seg, tw, ew, [50, 50], (11, 11), 5100) + assert normalise_registration_wcs(tw, ew) is ew + got = register_categories(seg, tw, ew, [50, 50], (11, 11), 5100) + for key in expected: + npt.assert_array_equal(got[key], expected[key]) + + +@pytest.mark.parametrize("astcat", ["test.gaia", "GAIA", "Gaia_DR3"]) +def test_gaia_catalogue_token_normalises_fk5_j2000(astcat): + tw, ew = _icrs(), _icrs() + ew.wcs.radesys = "FK5" + ew.wcs.equinox = 2000.0 + got = normalise_registration_wcs(tw, ew, {"ASTCAT": astcat}) + assert got.wcs.radesys == "ICRS" and np.isnan(got.wcs.equinox) + + +@pytest.mark.parametrize("astcat", ["", "2MASS", "notgaia", "gaia2"]) +def test_non_gaia_catalogue_cannot_normalise_mismatched_frames(astcat): + tw, ew = _icrs(), _icrs() + ew.wcs.radesys = "FK5" + ew.wcs.equinox = 2000.0 + with pytest.raises(ValueError, match="equivalent celestial frames"): + normalise_registration_wcs(tw, ew, {"ASTCAT": astcat}) + + +@pytest.mark.parametrize("frame,equinox", [("FK5", 2050.), ("FK4", 1950.)]) +def test_other_mismatched_frames_raise_even_with_gaia(frame, equinox): + tw, ew = _icrs(), _icrs() + ew.wcs.radesys, ew.wcs.equinox = frame, equinox + with pytest.raises(ValueError, match="equivalent celestial frames"): + normalise_registration_wcs(tw, ew, {"ASTCAT": "test.gaia"}) + + +def test_matching_fk5_frames_need_no_conversion(): + tw, ew = _icrs(), _icrs() + for wcs in [tw, ew]: + wcs.wcs.radesys = "FK5" + wcs.wcs.equinox = 2000.0 + assert normalise_registration_wcs(tw, ew, {"ASTCAT": "2MASS"}) is ew diff --git a/workflow/rules/tile.smk b/workflow/rules/tile.smk index b86246557..4f336d537 100644 --- a/workflow/rules/tile.smk +++ b/workflow/rules/tile.smk @@ -45,14 +45,14 @@ by MegaPipe on the same DR6 image with the same configuration, so the join is exact; on other pixels (a DR5 image) it fails loudly. ``blend_handling: uberseg``, the default, gives ngmix UberSeg's hard mask -instead of its own noise-fill default. Both read one coadd segmentation stamp -per object from the sexcat's SEG_VIGNET column: uberseg masks by it, and -noisefill takes as neighbours only the -1e30 VIGNET markers on another -object's footprint in it. tile_detect cuts it from SExtractor's SEGMENTATION -check image on the grid of each object's VIGNET, before the join, which -relabels every stamp to the catalogue's NUMBER (-1 on the footprints of rows -that leave, 0 on sky). The switch is one prologue variable and nothing else -(blend_env, below). +instead of its own noise-fill default. Both consume the full tile +segmentation sampled onto each native exposure stamp by vignetmaker: +uberseg partitions registered labels; noisefill fills every foreign nonzero +footprint. The sampled tile rectangle supplies OFF_TILE defects. +Tile detection retains the pre-join SEG_LABEL so vignetmaker can relabel the +full check image with catalogue NUMBERs (-1 for departed detections, 0 sky). +The tile SEG_VIGNET supplies the catalogue-level neighbour flag, not epoch +masks. The switch is one prologue variable (blend_env, below). There is no `tile_mask` rule, and there will not be one (PR #847). ShapePipe generates no masks: tiles have no instrument flag image of their own, so @@ -310,9 +310,11 @@ rule tile_merge_headers: # The blend-handling exports into a stage's prologue. tile_detect writes # SEG_VIGNET (config_tile_Sx.ini, SEG_VIGNET = ${SP_SEG_VIGNET:-False}) under -# both handlings: noisefill keeps only the -1e30 markers on another object's -# footprint in it (split_tile_markers), uberseg masks by it. uberseg (the -# default) also sets BLEND_HANDLING (config_tile_Ng_template.ini, +# both handlings, together with pre-join SEG_LABEL. Vignetmaker samples the +# full relabelled check image on each exposure grid. Noisefill fills foreign +# nonzero footprints; uberseg partitions the registered labels. The sampled +# tile rectangle supplies OFF_TILE defects. uberseg (the default) also sets +# BLEND_HANDLING (config_tile_Ng_template.ini, # ${SP_BLEND_HANDLING:-noisefill}), which reruns only tile_ngmix on a flip. BLEND_ENV = { "tile_detect": {"SP_SEG_VIGNET": "True"}, From 2de300973684a8c3e4a08e371476d04916b62dab Mon Sep 17 00:00:00 2001 From: Cail Daley Date: Thu, 29 Oct 2026 20:07:08 -0400 Subject: [PATCH 3/7] Pin native-grid registration selectors and scientific alternatives Describe registered foreign footprints and the measured conditional shape sensitivity. Co-Authored-By: GPT-6.1 Sol --- astra.yaml | 25 +++++++++++++++++-- .../config_tile_PiViVi_canfar_sx.ini | 1 + src/shapepipe/modules/ngmix_package/ngmix.py | 18 +++++++------ src/shapepipe/modules/ngmix_runner.py | 11 ++++---- .../sextractor_package/sextractor_script.py | 5 +++- tests/module/test_ngmix_defect_fill.py | 6 ++--- tests/module/test_ngmix_uberseg.py | 2 +- .../config/cfis/config_tile_PiViVi_mccd.ini | 1 + .../config/cfis/config_tile_PiViVi_psfex.ini | 1 + workflow/config/cfis/config_tile_Sx.ini | 12 ++++----- .../config_tile_PiViVi_fake.ini | 1 + 11 files changed, 56 insertions(+), 27 deletions(-) diff --git a/astra.yaml b/astra.yaml index 3e4bb8eee..5f68b1507 100644 --- a/astra.yaml +++ b/astra.yaml @@ -452,7 +452,7 @@ analyses: rationale: >- Both options run ShapePipe's tile SExtractor, so data and image simulations share one detection and measurement path: windowed - positions, VIGNET neighbour markers and every SExtractor column. + positions, segmentation labels and every SExtractor column. In real data each detection is then paired with its mutual nearest neighbour within 1 px in Gwyn's UNIONS per-tile catalogue and takes its NUMBER, so shape, photometry and photo-z catalogues share one @@ -972,10 +972,28 @@ analyses: versus (-0.044,-0.010) px with FK5-to-ICRS conversion. All remaining frame mismatches raise. A flip alone cannot register independent pixel grids and centroids. + On tile 188.307 the resolved paired sample has a response-only + m-like shift of -1.9e-3 ± 0.9e-3 and an additive-like mean shift + consistent with zero; unknown true shear prevents an absolute + calibration claim. + Values: + cfis/config_tile_PiViVi_psfex.ini#VIGNETMAKER_RUNNER.FILE_PATTERN = sexcat, log_exp_headers, exp_numbers, segmentation; + cfis/config_tile_PiViVi_mccd.ini#VIGNETMAKER_RUNNER.FILE_PATTERN = sexcat, log_exp_headers, exp_numbers, segmentation; + cfis_image_sims/config_tile_PiViVi_fake.ini#VIGNETMAKER_RUNNER.FILE_PATTERN = sexcat, log_exp_headers, exp_numbers, segmentation; + config_tile_PiViVi_canfar_sx.ini#VIGNETMAKER_RUNNER_RUN_2.FILE_PATTERN = sexcat, log_exp_headers, exp_numbers, segmentation; + cfis/config_tile_Sx.ini#SEXTRACTOR_RUNNER.SEG_VIGNET = ${SP_SEG_VIGNET:-False}; + sextractor_script.py::add_seg_vignet.seg_label_column = SEG_LABEL. default: native_grid_nearest options: native_grid_nearest: label: Full tile categories projected to native exposure centres + flip_only_overlay: + label: Flip the tile stamp without registering independent grids + excluded: true + excluded_reason: >- + Independent tile/exposure centroids differ by median 0.56 px + and P95 1.1 px on 188.307, with residual rotations up to 1.8°. + A CCD flip leaves that measured misregistration in the masks. stamp_positioning_and_padding: label: Nearest-pixel stamp extraction with zero padding rationale: >- @@ -1734,12 +1752,15 @@ analyses: default: uberseg options: noisefill: - label: Noise-fill the marked neighbour pixels (BLEND_HANDLING = noisefill) + label: Noise-fill foreign segmentation footprints description: >- Foreign nonzero segmentation footprints on the exposure grid get weight 0 and noise. The neighbour's unsegmented wings retain their weight and light, leaving residual neighbour contamination (Jarvis et al. 2016). + The foreign-footprint definition's shape effect is unmeasured; + it adds pixels for 2,456 objects on tile 188.307 relative to + the flip-only marker-supported definition. insights: [mask_uberseg_neighbour_bias] uberseg: label: UberSeg, weight-only diff --git a/example/cfis_image_sims/config_tile_PiViVi_canfar_sx.ini b/example/cfis_image_sims/config_tile_PiViVi_canfar_sx.ini index b7f45c037..33c401bb5 100644 --- a/example/cfis_image_sims/config_tile_PiViVi_canfar_sx.ini +++ b/example/cfis_image_sims/config_tile_PiViVi_canfar_sx.ini @@ -93,6 +93,7 @@ PREFIX = weight INPUT_DIR = run_sp_tile_Sx:sextractor_runner, run_sp_tile_Mh_exp:merge_headers_runner, last:find_exposures_runner +# @sc [decision:preparation.categorical_registration] FILE_PATTERN = sexcat, log_exp_headers, exp_numbers, segmentation FILE_EXT = .fits, .sqlite, .txt, .fits diff --git a/src/shapepipe/modules/ngmix_package/ngmix.py b/src/shapepipe/modules/ngmix_package/ngmix.py index cf1dc8f44..e2682d38d 100644 --- a/src/shapepipe/modules/ngmix_package/ngmix.py +++ b/src/shapepipe/modules/ngmix_package/ngmix.py @@ -1646,7 +1646,7 @@ def prepare_postage_stamps( defect near the object. The quarter-turn copies of interpolated pixels that ``DEFECT_WEIGHTING`` zero-weights or interpolates are not counted. - @sc [decision:shape_measurement.central_defect_veto,decision:shape_measurement.epoch_masked_fraction_cut,decision:shape_measurement.blend_handling] neighbour-markers-are-not-defects + @sc [decision:shape_measurement.central_defect_veto,decision:shape_measurement.epoch_masked_fraction_cut,decision:shape_measurement.blend_handling] neighbour-footprints-are-not-defects Foreign nonzero segmentation footprints, sampled upstream on each exposure grid, are the epoch's neighbour mask (``stamp.neighbours``), not defects. Counting neighbours would reject blended objects. @@ -1822,7 +1822,9 @@ def prepare_postage_stamps( return stamp def split_tile_markers(tile_vign, shape, seg=None, object_number=None): - """Split the tile VIGNET's -1e30 markers into neighbour and off-tile. + """Supply the flip-only mutant fixture; production does not call this. + + Split the tile VIGNET's -1e30 markers into neighbour and off-tile. SExtractor writes -1e30 into the tile VIGNET on stamp pixels beyond the tile's edge and, under MASK_TYPE CORRECT, on every above-threshold pixel @@ -2379,7 +2381,7 @@ def prepare_ngmix_weights( Every stamp pixel falls in one of four classes. A clean pixel keeps its light and its weight. A pixel whose light is replaced by noise keeps neither: a defect that is not interpolated, or under ``"noisefill"`` a - marked neighbour pixel. An interpolated pixel takes the interpolant, at + foreign-footprint pixel. An interpolated pixel takes the interpolant, at the weight ``defect_weighting`` gives it. A pixel whose light stays at zero weight is a hole in the likelihood only: under ``"fourfold_zero"`` the quarter-turn copies of the interpolated defects, under ``"uberseg"`` @@ -2394,13 +2396,13 @@ def prepare_ngmix_weights( background RMS. Metacal shears the whole image whatever the weights, so no raw defect value may reach it. - @sc [decision:shape_measurement.blend_handling] noisefill-fills-markers + @sc [decision:shape_measurement.blend_handling] noisefill-fills-footprints Under ``"noisefill"`` the ``neighbour`` pixels (registered foreign nonzero segmentation footprints) get weight 0 and noise. Their light is gone, so they neither support the interpolant nor receive it. - @sc [decision:shape_measurement.blend_handling] uberseg-ignores-markers - Under ``"uberseg"`` the markers are ignored: the pixels of + @sc [decision:shape_measurement.blend_handling] uberseg-weights-footprints + Under ``"uberseg"`` the foreign footprints seed the partition: the pixels of :func:`uberseg_mask` get weight 0 and keep their light, which is real sky that metacal shears with the target and which supports the interpolant. @@ -2507,8 +2509,8 @@ def prepare_ngmix_weights( defect = defect_mask(weight, flag, bkg_rms) no_pixel = np.zeros_like(defect) - # Neighbour pixels whose light noisefill replaces (noisefill-fills-markers) - # or whose weight uberseg zeroes (uberseg-ignores-markers). + # Neighbour pixels whose light noisefill replaces (noisefill-fills-footprints) + # or whose weight uberseg zeroes (uberseg-weights-footprints). removed_neighbour, neighbour_side = no_pixel, no_pixel if blend_handling == "noisefill" and neighbour is not None: removed_neighbour = np.asarray(neighbour, dtype=bool) diff --git a/src/shapepipe/modules/ngmix_runner.py b/src/shapepipe/modules/ngmix_runner.py index d55f19c06..e00999851 100644 --- a/src/shapepipe/modules/ngmix_runner.py +++ b/src/shapepipe/modules/ngmix_runner.py @@ -117,12 +117,11 @@ def ngmix_runner( else: centroid_source = "wcs" - # Neighbour treatment: "noisefill" (default) zero-weights and noise-fills - # the pixels marked -1e30 in the tile VIGNET on other objects' - # segmentation footprints (split_tile_markers); "uberseg" ignores those - # markers, zeroes the weight of every - # pixel closer to a neighbour than to the central object, from the - # segmentation map, and leaves its image raw. Defect pixels (flagged, + # Neighbour treatment uses full-tile categories registered on each native + # exposure grid. "noisefill" (default) zero-weights and noise-fills every + # foreign nonzero segmentation footprint; "uberseg" zeroes the weight of + # every pixel closer to a neighbour than to the central object, from the + # registered segmentation map, and leaves its image raw. Defect pixels (flagged, # zero-weight, invalid-RMS or off-tile) are zero-weighted and filled the # same way under both, and the epoch cuts are fixed; see # prepare_postage_stamps and prepare_ngmix_weights. diff --git a/src/shapepipe/modules/sextractor_package/sextractor_script.py b/src/shapepipe/modules/sextractor_package/sextractor_script.py index 1f598f424..d29db710e 100644 --- a/src/shapepipe/modules/sextractor_package/sextractor_script.py +++ b/src/shapepipe/modules/sextractor_package/sextractor_script.py @@ -154,6 +154,8 @@ def add_seg_vignet(cat_path, seg_path, w_log=None): vignetmaker can register the full segmentation, beyond VIGNET's support. Every other HDU and column is kept. + @sc [decision:preparation.categorical_registration] + Parameters ---------- cat_path : str @@ -185,10 +187,11 @@ def add_seg_vignet(cat_path, seg_path, w_log=None): seg_vignets = cut_stamps(fits.getdata(seg_path), col, row, size, 0) kept = [c for c in objects.columns.columns if c.name not in DOUBLE_POSITIONS] + seg_label_column = "SEG_LABEL" new = fits.BinTableHDU.from_columns( kept + [ seg_vignet_column(seg_vignets), - fits.Column(name="SEG_LABEL", format="J", array=data["NUMBER"]), + fits.Column(name=seg_label_column, format="J", array=data["NUMBER"]), ], header=objects.header, name="LDAC_OBJECTS", diff --git a/tests/module/test_ngmix_defect_fill.py b/tests/module/test_ngmix_defect_fill.py index 0c1d5e127..eaf0c427e 100644 --- a/tests/module/test_ngmix_defect_fill.py +++ b/tests/module/test_ngmix_defect_fill.py @@ -852,7 +852,7 @@ def test_neighbour_markers_near_the_centre_keep_every_epoch(): Failure mode: the markers are written into the flag stamp and counted as defects, so every epoch (they all share the tile VIGNET) is dropped by the veto or the fraction cut and the object loses its shape - (neighbour-markers-are-not-defects). + (neighbour-footprints-are-not-defects). """ small = _tile_with_neighbour() # Large, but short of the stamp border: no row or column is entirely @@ -925,7 +925,7 @@ def test_noisefill_fills_exactly_the_marked_pixels(): value and its weight. Failure mode: the neighbour markers are dropped with the flags, so - noisefill no longer removes neighbour light (noisefill-fills-markers). + noisefill retains neighbour light (noisefill-fills-footprints). """ tile = _tile_with_neighbour() stamp, epochs, _ = _marker_stamp(tile) @@ -949,7 +949,7 @@ def test_uberseg_leaves_the_marked_pixels_raw(): Failure mode: the markers reach the defect set or the fill, so uberseg noise-fills the neighbour's light instead of leaving it to the seg-based - weight (uberseg-ignores-markers). + weight (uberseg-weights-footprints). """ tile = _tile_with_neighbour() stamp, _, _ = _marker_stamp(tile) diff --git a/tests/module/test_ngmix_uberseg.py b/tests/module/test_ngmix_uberseg.py index 54cc29b85..1b5ab4d68 100644 --- a/tests/module/test_ngmix_uberseg.py +++ b/tests/module/test_ngmix_uberseg.py @@ -246,7 +246,7 @@ def test_uberseg_fills_defects_and_leaves_neighbour_pixels_raw(): Failure modes: the defect fill is skipped under uberseg, so raw bad pixels reach metacal; or the neighbour side is noise-filled (defects-filled-whatever-the-blend-handling, - uberseg-ignores-markers). + uberseg-weights-footprints). """ npix = 41 gal, flag, weight = _gal_flag_weight(npix=npix) diff --git a/workflow/config/cfis/config_tile_PiViVi_mccd.ini b/workflow/config/cfis/config_tile_PiViVi_mccd.ini index 9da6f93c3..a7c7676b0 100644 --- a/workflow/config/cfis/config_tile_PiViVi_mccd.ini +++ b/workflow/config/cfis/config_tile_PiViVi_mccd.ini @@ -112,6 +112,7 @@ ME_DOT_PSF_PATTERN = fitted_model INPUT_DIR = $SP_RUN/output/run_sp_tile_Sx/sextractor_runner/output, $SP_RUN/output/run_sp_tile_Mh_exp/merge_headers_runner/output, $SP_RUN/output/run_sp_tile_Fe/find_exposures_runner/output +# @sc [decision:preparation.categorical_registration] FILE_PATTERN = sexcat, log_exp_headers, exp_numbers, segmentation FILE_EXT = .fits, .sqlite, .txt, .fits diff --git a/workflow/config/cfis/config_tile_PiViVi_psfex.ini b/workflow/config/cfis/config_tile_PiViVi_psfex.ini index 304155309..a57d2a7d9 100644 --- a/workflow/config/cfis/config_tile_PiViVi_psfex.ini +++ b/workflow/config/cfis/config_tile_PiViVi_psfex.ini @@ -125,6 +125,7 @@ ME_DOT_PSF_PATTERN = star_split_ratio_80 INPUT_DIR = $SP_RUN/output/run_sp_tile_Sx/sextractor_runner/output, $SP_RUN/output/run_sp_tile_Mh_exp/merge_headers_runner/output, $SP_RUN/output/run_sp_tile_Fe/find_exposures_runner/output +# @sc [decision:preparation.categorical_registration] FILE_PATTERN = sexcat, log_exp_headers, exp_numbers, segmentation FILE_EXT = .fits, .sqlite, .txt, .fits diff --git a/workflow/config/cfis/config_tile_Sx.ini b/workflow/config/cfis/config_tile_Sx.ini index 8d11674ef..ed34ccdfc 100644 --- a/workflow/config/cfis/config_tile_Sx.ini +++ b/workflow/config/cfis/config_tile_Sx.ini @@ -112,12 +112,12 @@ BKG_FROM_HEADER = False # OBJECTS, -OBJECTS, SEGMENTATION, APERTURES CHECKIMAGE = BACKGROUND, SEGMENTATION -# Write the SEGMENTATION check image's stamps, cut on each VIGNET's grid, as -# the int32 SEG_VIGNET column ngmix's blend handling reads under both -# noisefill and uberseg (needs the SEGMENTATION check image; SExtractor also -# computes X/Y_IMAGE_DBL, which centre the stamps and are left out of the -# sexcat). The workflow sets SP_SEG_VIGNET under every blend_handling -# (workflow/rules/tile.smk). +# Write int32 SEG_VIGNET stamps on the tile VIGNET grid for catalogue-level +# neighbour diagnostics, and retain pre-join SEG_LABEL for registration. +# Epoch masks use the full SEGMENTATION check image on each exposure grid. +# X/Y_IMAGE_DBL centre these stamps and stay out of the sexcat. +# The workflow sets SP_SEG_VIGNET under every blend_handling. +# @sc [decision:preparation.categorical_registration] SEG_VIGNET = ${SP_SEG_VIGNET:-False} # File name suffix for the output sextractor files (optional) diff --git a/workflow/config/cfis_image_sims/config_tile_PiViVi_fake.ini b/workflow/config/cfis_image_sims/config_tile_PiViVi_fake.ini index 30397205b..5a31787d4 100644 --- a/workflow/config/cfis_image_sims/config_tile_PiViVi_fake.ini +++ b/workflow/config/cfis_image_sims/config_tile_PiViVi_fake.ini @@ -100,6 +100,7 @@ PSF_DICT_PATH = $PSF_DICT INPUT_DIR = $SP_RUN/output/run_sp_tile_Sx/sextractor_runner/output, $SP_RUN/output/run_sp_tile_Mh_exp/merge_headers_runner/output, $SP_RUN/output/run_sp_tile_Fe/find_exposures_runner/output +# @sc [decision:preparation.categorical_registration] FILE_PATTERN = sexcat, log_exp_headers, exp_numbers, segmentation FILE_EXT = .fits, .sqlite, .txt, .fits From 06e39141de72a2752682387560c4cbb6bc67ba77 Mon Sep 17 00:00:00 2001 From: Cail Daley Date: Thu, 29 Oct 2026 20:07:09 -0400 Subject: [PATCH 4/7] Exercise categorical input boundaries and selector drift Co-Authored-By: GPT-6.1 Sol --- tests/module/test_categorical_registration.py | 76 +++++++++++++++++++ tests/unit/test_decisions.py | 29 +++++++ 2 files changed, 105 insertions(+) diff --git a/tests/module/test_categorical_registration.py b/tests/module/test_categorical_registration.py index cc9e86cc9..c16e36180 100644 --- a/tests/module/test_categorical_registration.py +++ b/tests/module/test_categorical_registration.py @@ -174,6 +174,82 @@ def _prepare(epoch, tw, ew, obj_id, tile_seg, weight=None, flag=None): ) +@pytest.mark.parametrize("category", ["SEG_VIGNET", "NEIGHBOUR", "OFF_TILE"]) +def test_missing_epoch_category_raises(category): + tw, ew = _wcs(), _wcs() + shape, centre = (51, 51), [42, 40] + epoch = dict(VIGNET=np.random.default_rng(3).normal(size=shape), INT_POS=centre) + epoch.update(register_categories(_segmentation(), tw, ew, centre, shape, 101)) + del epoch[category] + with pytest.raises(ValueError, match="Exposure-grid categories are missing"): + _prepare(epoch, tw, ew, 101, np.zeros(shape, np.int32)) + + +@pytest.mark.parametrize("category", ["SEG_VIGNET", "NEIGHBOUR", "OFF_TILE"]) +def test_misshapen_epoch_category_raises(category): + tw, ew = _wcs(), _wcs() + shape, centre = (51, 51), [42, 40] + epoch = dict(VIGNET=np.random.default_rng(3).normal(size=shape), INT_POS=centre) + epoch.update(register_categories(_segmentation(), tw, ew, centre, shape, 101)) + epoch[category] = epoch[category][:-1] + with pytest.raises(ValueError, match="Exposure categories must have the image stamp shape"): + _prepare(epoch, tw, ew, 101, np.zeros(shape, np.int32)) + + +@pytest.mark.parametrize("category", ["NEIGHBOUR", "OFF_TILE"]) +@pytest.mark.parametrize("dtype", [np.int8, np.float32]) +def test_nonboolean_epoch_category_raises(category, dtype): + tw, ew = _wcs(), _wcs() + shape, centre = (51, 51), [42, 40] + epoch = dict(VIGNET=np.random.default_rng(3).normal(size=shape), INT_POS=centre) + epoch.update(register_categories(_segmentation(), tw, ew, centre, shape, 101)) + epoch[category] = epoch[category].astype(dtype) + with pytest.raises(ValueError, match="NEIGHBOUR and OFF_TILE must be boolean maps"): + _prepare(epoch, tw, ew, 101, np.zeros(shape, np.int32)) + + +def test_sexcat_without_seg_label_raises(tmp_path): + cat = tmp_path / "cat.fits" + columns = [ + fits.Column(name="NUMBER", format="J", array=[101]), + fits.Column(name="N_EPOCH", format="J", array=[1]), + fits.Column(name="XWIN_WORLD", format="D", array=[188.0]), + fits.Column(name="YWIN_WORLD", format="D", array=[30.7]), + ] + fits.HDUList([ + fits.PrimaryHDU(), fits.BinTableHDU(), + fits.BinTableHDU.from_columns(columns), + ]).writeto(cat) + maker = VignetMaker( + str(cat), "SPHE", ["XWIN_WORLD", "YWIN_WORLD"], str(tmp_path), + "-188-307", SimpleNamespace(info=lambda msg: None), + ) + with pytest.raises(ValueError, match="Exposure categories require SEG_LABEL; rerun tile detection"): + maker._get_stamp_me([], "image") + + +def test_three_input_multi_epoch_config_raises(tmp_path, monkeypatch): + from shapepipe.modules import vignetmaker_runner as runner + + values = dict( + MASKING=False, STAMP_SIZE=51, COORD="SPHE", MODE="MULTI-EPOCH", + POSITION_PARAMS=["XWIN_WORLD", "YWIN_WORLD"], ME_IMAGE_EXP_DIR=str(tmp_path), + ME_IMAGE_EXP_RUNNERS=["split_exp_runner"], ME_IMAGE_PATTERN=["image"], + ) + config = SimpleNamespace(**{ + accessor: lambda section, key: values[key] + for accessor in ("getboolean", "getint", "get", "getlist", "getexpanded") + }) + monkeypatch.setattr(runner.vm, "VignetMaker", lambda **kw: SimpleNamespace(process_me=lambda *a: None)) + monkeypatch.setattr(runner, "get_exp_output_dirs", lambda *a: []) + with pytest.raises(ValueError, match="MULTI-EPOCH requires the tile segmentation check image as fourth input"): + runner.vignetmaker_runner( + ["sexcat.fits", "headers.sqlite", "exp_numbers.txt"], + {"output": str(tmp_path)}, "-188-307", config, + "VIGNETMAKER_RUNNER", SimpleNamespace(info=lambda msg: None), + ) + + def test_ngmix_consumes_registered_maps_without_flipping(monkeypatch): seg, tw, ew = _segmentation(), _wcs(), _wcs((40.37, 42.61), 181.2, True) centre, shape = np.array([42, 40]), (51, 51) diff --git a/tests/unit/test_decisions.py b/tests/unit/test_decisions.py index 8c0f39766..9a434dcd6 100644 --- a/tests/unit/test_decisions.py +++ b/tests/unit/test_decisions.py @@ -614,6 +614,35 @@ def test_repository_decisions_have_sites_and_all_values_match(): @pytest.mark.parametrize( "path, pattern, replacement, decision, ref_fragment", [ + *[ + ( + path, + "FILE_PATTERN = sexcat, log_exp_headers, exp_numbers, segmentation", + "FILE_PATTERN = sexcat, log_exp_headers, exp_numbers", + "preparation.categorical_registration", + "FILE_PATTERN", + ) + for path in ( + "workflow/config/cfis/config_tile_PiViVi_psfex.ini", + "workflow/config/cfis/config_tile_PiViVi_mccd.ini", + "workflow/config/cfis_image_sims/config_tile_PiViVi_fake.ini", + "example/cfis_image_sims/config_tile_PiViVi_canfar_sx.ini", + ) + ], + ( + "workflow/config/cfis/config_tile_Sx.ini", + "SEG_VIGNET = ${SP_SEG_VIGNET:-False}", + "SEG_VIGNET = False", + "preparation.categorical_registration", + "SEG_VIGNET", + ), + ( + "src/shapepipe/modules/sextractor_package/sextractor_script.py", + 'seg_label_column = "SEG_LABEL"', + 'seg_label_column = "NUMBER"', + "preparation.categorical_registration", + "seg_label_column", + ), ( "workflow/config/cfis/config_tile_Sx.ini", "WEIGHT_IMAGE = True", From 4bf50f987e7f0dad9e2ce635f454b2ce141fd1ac Mon Sep 17 00:00:00 2001 From: Cail Daley Date: Thu, 29 Oct 2026 20:52:05 -0400 Subject: [PATCH 5/7] Reserve unique WCS staging files across container PID namespaces Use mktemp for atomic WCS publication and exercise concurrent copies with identical container shell PIDs. Pin the intentional campaign-boundary prologue change. Co-Authored-By: GPT-6.1 Sol --- tests/workflow/params_pin.json | 8 ++-- tests/workflow/params_pin_noisefill.json | 8 ++-- tests/workflow/test_wcs_staging.py | 50 ++++++++++++++++++++++++ workflow/rules/tile.smk | 11 ++++-- 4 files changed, 65 insertions(+), 12 deletions(-) create mode 100644 tests/workflow/test_wcs_staging.py diff --git a/tests/workflow/params_pin.json b/tests/workflow/params_pin.json index a236add48..d3ac5474b 100644 --- a/tests/workflow/params_pin.json +++ b/tests/workflow/params_pin.json @@ -18,15 +18,15 @@ "tile_find_exposures": "c883495a7ec196c61ef770507865f43834b08523793d337e8ddeaef0ad62f117", "tile_get_catalogue": "84ffd03c4bde248c06aa58a0f4b7f399390a0ff3ecbcf07e03d718df4fe0cd7f", "tile_get_images": "96e235dad9cdcde8ecf11f4516bc2303dbba1c8115ad343cdb26d3d1513da671", - "tile_make_cat": "9a980da6e176edda3a601e53db1d8945ece72199ec9d47c70bad5c3759f8b520", + "tile_make_cat": "77b02c8221730408275a3cdfcf047c3c56a911ce8746a959afdf59be547a2b62", "tile_merge_cats": "0783c93deeb7f90bdb9772bbc4117851dff1a671518c81f67edd4c7c79cc7e6a", "tile_merge_headers": "3e674f961fd5bb93ce1f3b0e2bb072a25a421f2828315a3db45a960c44a42111", - "tile_ngmix": "3eeb1f49ff01b4e8a350cc6dd97e6f9f582774c7b3f340b5b46b8eae87cec8b7", + "tile_ngmix": "00777fa01ed905a32a464d352fa12691375ab5a5e4692008613305ba2f95df3d", "tile_uncompress": "4a013cdd04bc3e3c1082e477161d2b03e0eefe280b1aabb9af25c149a977f55b", - "tile_vignets": "1d434b4a6a4bcdeb8f1e5e9a5e4f228b67ade400245b41b033a2c883fb6a3267" + "tile_vignets": "7b0aa5009434a318f848688c3143d3f370b1e64f39193e3aa63d3816d95ce867" }, "schema": 1, - "sha256": "dfdcd83495631cbe85ecb3e07ba0c1f499db295dee4186feaeb0c4aed6aa050e", + "sha256": "9543c61935c690c508dc8a6d74cdc835125ba00fd8f2237ebb47fc224d4e15d2", "unit_pre": { "exp_get_images": "dac6685a207dae3ea81d296ce53e9ba75d4636cf1f81e6399f2dda452680c992", "exp_psf": "87fc8ea1153a709ab7ba56542cfacc041f5f8b7f6cf2f38a9bc9d8004d1cecb4", diff --git a/tests/workflow/params_pin_noisefill.json b/tests/workflow/params_pin_noisefill.json index e79a9f794..5c6be626c 100644 --- a/tests/workflow/params_pin_noisefill.json +++ b/tests/workflow/params_pin_noisefill.json @@ -18,15 +18,15 @@ "tile_find_exposures": "c883495a7ec196c61ef770507865f43834b08523793d337e8ddeaef0ad62f117", "tile_get_catalogue": "84ffd03c4bde248c06aa58a0f4b7f399390a0ff3ecbcf07e03d718df4fe0cd7f", "tile_get_images": "96e235dad9cdcde8ecf11f4516bc2303dbba1c8115ad343cdb26d3d1513da671", - "tile_make_cat": "9a980da6e176edda3a601e53db1d8945ece72199ec9d47c70bad5c3759f8b520", + "tile_make_cat": "77b02c8221730408275a3cdfcf047c3c56a911ce8746a959afdf59be547a2b62", "tile_merge_cats": "0783c93deeb7f90bdb9772bbc4117851dff1a671518c81f67edd4c7c79cc7e6a", "tile_merge_headers": "3e674f961fd5bb93ce1f3b0e2bb072a25a421f2828315a3db45a960c44a42111", - "tile_ngmix": "fc27cee25484721b2291c122ee305561a8aee96b28169cc38dda8f3be8ac770c", + "tile_ngmix": "a2cf16e832eff4b2b7504fd1cce1ff3908154e4b8b2e76eedcc87e40c64b4d41", "tile_uncompress": "4a013cdd04bc3e3c1082e477161d2b03e0eefe280b1aabb9af25c149a977f55b", - "tile_vignets": "1d434b4a6a4bcdeb8f1e5e9a5e4f228b67ade400245b41b033a2c883fb6a3267" + "tile_vignets": "7b0aa5009434a318f848688c3143d3f370b1e64f39193e3aa63d3816d95ce867" }, "schema": 1, - "sha256": "abc35fc24e8e45b251019454351a171d3f1fb958df15b3076e39997c37e9ed59", + "sha256": "439efb7cde49e62d035c4d4d457adea9bf02a777d9206fa006ee470c68a52fdf", "unit_pre": { "exp_get_images": "dac6685a207dae3ea81d296ce53e9ba75d4636cf1f81e6399f2dda452680c992", "exp_psf": "87fc8ea1153a709ab7ba56542cfacc041f5f8b7f6cf2f38a9bc9d8004d1cecb4", diff --git a/tests/workflow/test_wcs_staging.py b/tests/workflow/test_wcs_staging.py new file mode 100644 index 000000000..45c6adeff --- /dev/null +++ b/tests/workflow/test_wcs_staging.py @@ -0,0 +1,50 @@ +"""Concurrent containers stage WCS without sharing PID-derived temp names.""" + +import os +import subprocess + + +def test_wcs_staging_survives_shared_container_pid(psfex_dag, tmp_path): + """Two PID namespaces can give their shells the same $$. + + A barrier makes both copies finish before either rename, exposing reuse + of a PID-only name instead of relying on a probabilistic race. + """ + tile = next(iter(psfex_dag.campaign.ready)) + prologue = psfex_dag.namespace["tile_local"](tile) + store = tmp_path / "store" + store.mkdir() + prologue = prologue.replace("/local/scratch", str(store)).replace("$$", "14") + run = tmp_path / "run" + source_dir = run / "output/run_sp_tile_Mh_exp/merge_headers_runner/output" + source_dir.mkdir(parents=True) + source = source_dir / f"log_exp_headers-{tile.replace('.', '-')}.sqlite" + source.write_bytes(b"complete WCS store\n" * 1000) + + tools = tmp_path / "bin" + tools.mkdir() + barrier = tmp_path / "barrier" + barrier.mkdir() + cp = tools / "cp" + cp.write_text( + "#!/bin/bash\nset -euo pipefail\n" + '/bin/cp "$@"\n' + 'touch "$BARRIER/$BASHPID"\n' + 'for i in $(seq 1 500); do\n' + ' [ "$(find "$BARRIER" -type f | wc -l)" -ge 2 ] && exit 0\n' + ' sleep 0.01\n' + 'done\nexit 1\n' + ) + cp.chmod(0o755) + env = dict(os.environ, SP_RUN=str(run), BARRIER=str(barrier), + PATH=f"{tools}:{os.environ['PATH']}") + children = [subprocess.Popen( + ["bash", "-euc", prologue], env=env, stdout=subprocess.PIPE, + stderr=subprocess.PIPE, text=True, + ) for _ in range(2)] + outputs = [child.communicate(timeout=30) for child in children] + assert [child.returncode for child in children] == [0, 0], outputs + staged = list(store.glob("*/wcs/log_exp_headers-*.sqlite")) + assert len(staged) == 1 + assert staged[0].read_bytes() == source.read_bytes() + assert not list(store.glob("*/wcs/.log_exp_headers.*")) diff --git a/workflow/rules/tile.smk b/workflow/rules/tile.smk index 4f336d537..de31ab968 100644 --- a/workflow/rules/tile.smk +++ b/workflow/rules/tile.smk @@ -102,7 +102,9 @@ def tile_local(tile): 147 of 176 D-state samples are in NFS RPC. Staging WCS avoids those per-read round trips, with a measured ~1.8x gain for ngmix. - Copy WCS unconditionally to a temporary name, then rename it atomically. + @sc [label:custody] wcs-staging-temp-unique-across-pid-namespaces + Reserve each WCS temporary name with mktemp: concurrent containers can + share the same shell PID. Copy WCS there, then rename it atomically. A symlink would still read NFS; cp -u could preserve a truncated file with a newer mtime. Concurrent group members can safely publish identical copies: an open reader keeps its inode. tile_merge_headers is upstream, @@ -134,10 +136,11 @@ mkdir -p "$SP_VIGNET_OUT" "$SP_WCS_DIR" || {{ # the WCS store -- see the docstring. Copy to a temp name and rename, because # `cp` is not atomic and the eight chunks share this destination. sp_wcs_src="$SP_RUN/output/run_sp_tile_Mh_exp/merge_headers_runner/output/log_exp_headers{tile_num}.sqlite" -cp "$sp_wcs_src" "$SP_WCS_DIR/.log_exp_headers.$$" && \ -mv -f "$SP_WCS_DIR/.log_exp_headers.$$" \ +sp_wcs_tmp=$(mktemp "$SP_WCS_DIR/.log_exp_headers.XXXXXXXXXX") || exit 1 +cp "$sp_wcs_src" "$sp_wcs_tmp" && \ +mv -f "$sp_wcs_tmp" \ "$SP_WCS_DIR/log_exp_headers{tile_num}.sqlite" || {{ - rm -f "$SP_WCS_DIR/.log_exp_headers.$$" + rm -f "$sp_wcs_tmp" echo "tile_shape: could not stage the WCS store." >&2 echo " source: $sp_wcs_src" >&2 echo " dest: $SP_WCS_DIR" >&2 From 3cec907668a1656bff47fb0213b8bcb2fc509e66 Mon Sep 17 00:00:00 2001 From: Cail Daley Date: Thu, 29 Oct 2026 21:27:44 -0400 Subject: [PATCH 6/7] Short-circuit populated vignette-store preflights A populated entry disproves all-empty; stop before reading the rest of each shared store in every chunk. Keep the all-empty product and guard ordering, open preflight stores read-only, and test both short circuits with poisoned later payloads. Co-Authored-By: GPT-6.1 Sol --- src/shapepipe/modules/ngmix_runner.py | 19 +++++++++----- tests/module/test_ngmix_empty_tile.py | 38 +++++++++++++++++++++++++++ 2 files changed, 51 insertions(+), 6 deletions(-) diff --git a/src/shapepipe/modules/ngmix_runner.py b/src/shapepipe/modules/ngmix_runner.py index e00999851..805338def 100644 --- a/src/shapepipe/modules/ngmix_runner.py +++ b/src/shapepipe/modules/ngmix_runner.py @@ -60,6 +60,11 @@ def ngmix_runner( and writes the same empty-catalogue product if every object ends up skipped. Either way, campaign completeness checks see one catalogue per tile. + + @sc [label:operations] empty-preflight-short-circuits + Each all-empty check reads entries only until the first populated one. + Every chunk shares the stores, so a full payload scan per chunk turns + the preflight into repeated random I/O over the entire tile. """ # Read config file entries @@ -169,10 +174,12 @@ def ngmix_runner( # crash that occurs when large numbers of numpy arrays are allocated then freed. psf_idx = 3 if bkg_sub else 2 psf_vignet_path = input_file_list[psf_idx] - with SqliteDict(psf_vignet_path) as db: + # One populated entry disproves all-empty. Short-circuit before reading + # the remaining large payloads: every ngmix chunk shares these stores. + with SqliteDict(psf_vignet_path, flag="r") as db: psf_keys = list(db.keys()) - n_empty_psf = sum(1 for k in psf_keys if len(db[k]) == 0) - if psf_keys and n_empty_psf == len(psf_keys): + all_empty_psf = all(len(db[k]) == 0 for k in psf_keys) + if psf_keys and all_empty_psf: w_log.warning( f"All {len(psf_keys)} PSF vignet entries are empty in " f"{psf_vignet_path} — no PSF coverage for this tile. Skipping ngmix." @@ -184,10 +191,10 @@ def ngmix_runner( # Check that image vignets are not all empty before initialising ngmix image_vignet_path = input_file_list[1] - with SqliteDict(image_vignet_path) as db: + with SqliteDict(image_vignet_path, flag="r") as db: keys = list(db.keys()) - n_empty = sum(1 for k in keys if db[k] == "empty") - if keys and n_empty == len(keys): + all_empty = all(db[k] == "empty" for k in keys) + if keys and all_empty: w_log.warning( f"All {len(keys)} image vignets are 'empty' in {image_vignet_path} " "— no valid CCD coverage for this tile. Skipping ngmix." diff --git a/tests/module/test_ngmix_empty_tile.py b/tests/module/test_ngmix_empty_tile.py index 447a8fc98..9b08b2b8d 100644 --- a/tests/module/test_ngmix_empty_tile.py +++ b/tests/module/test_ngmix_empty_tile.py @@ -92,6 +92,44 @@ def test_empty_tile_cli_writes_catalogue_and_health_log(tmp_path, empty_store): assert log.count("all 3 objects failed the metacal fit (0 fitted)") == 1 +@pytest.mark.parametrize("store", ["galaxy_psf", "image"]) +def test_empty_preflight_stops_at_first_populated_entry(tmp_path, monkeypatch, store): + """A populated entry disproves all-empty without reading later payloads. + + Scanning every large epoch payload in every chunk stalls on shared NFS. + A poisoned later payload makes an unnecessary read fail deterministically. + """ + import importlib + import sqlite3 + + runner = importlib.import_module("shapepipe.modules.ngmix_runner") + epoch = {"exp-1": {"VIGNET": np.ones((5, 5))}} + paths = {} + for name in ("image", "galaxy_psf"): + paths[name] = str(tmp_path / f"{name}.sqlite") + with SqliteDict(paths[name]) as db: + db["a"] = epoch + db["z"] = epoch + db.commit() + with sqlite3.connect(paths[store]) as db: + db.execute("UPDATE unnamed SET value=? WHERE key='z'", (b"unneeded payload",)) + + class ReachesFitting(Exception): + pass + + def start_fitting(*args, **kwargs): + raise ReachesFitting + + monkeypatch.setattr(runner, "Ngmix", start_fitting) + with pytest.raises(ReachesFitting): + runner.ngmix_runner( + ["sexcat.fits", paths["image"], "background.sqlite", + paths["galaxy_psf"], "weight.sqlite", "flag.sqlite", "headers.sqlite"], + {"output": str(tmp_path)}, "-001-001", _runner_config(), + "NGMIX_RUNNER", _RecordingLogger(), + ) + + class _RecordingLogger: """Minimal logger that records messages passed to warning/error/info.""" From fb4755a279321faa42453cd6217a953d403285b6 Mon Sep 17 00:00:00 2001 From: Cail Daley Date: Thu, 29 Oct 2026 23:20:38 -0400 Subject: [PATCH 7/7] Adapt zero-object tile regressions to registered vignette inputs Exercise the real four-input runner with an all-sky segmentation FITS product, preserve empty catalogue schemas, and verify registered-store dtypes, shapes, empty ranges and publication. Document the zero-detection segmentation and zero-key store contracts. Co-Authored-By: Sol --- src/shapepipe/modules/sextractor_runner.py | 9 +- .../vignetmaker_package/vignetmaker.py | 8 ++ tests/module/test_categorical_registration.py | 30 +++++- tests/module/test_zero_object_tile.py | 94 ++++++++++++++++--- tests/workflow/test_zero_object_tile.py | 3 + 5 files changed, 127 insertions(+), 17 deletions(-) diff --git a/src/shapepipe/modules/sextractor_runner.py b/src/shapepipe/modules/sextractor_runner.py index 2a0df4713..66bddab0a 100644 --- a/src/shapepipe/modules/sextractor_runner.py +++ b/src/shapepipe/modules/sextractor_runner.py @@ -38,7 +38,14 @@ def sextractor_runner( module_config_sec, w_log, ): - """Define The SExtractor Runner.""" + """Define the SExtractor runner. + + @sc [label:coupling] zero-detection-segmentation-input + SExtractor writes the requested check images even with no detections: + SEGMENTATION is a full-size all-zero label image with the tile WCS, + not an absent or zero-axis file. The cut/join/post-processing keep it + for the four-input multi-epoch vignetmaker. + """ # Set the SExtractor executable name if config.has_option(module_config_sec, "EXEC_PATH"): exec_path = config.getexpanded(module_config_sec, "EXEC_PATH") diff --git a/src/shapepipe/modules/vignetmaker_package/vignetmaker.py b/src/shapepipe/modules/vignetmaker_package/vignetmaker.py index 47480ca79..f00cbc659 100644 --- a/src/shapepipe/modules/vignetmaker_package/vignetmaker.py +++ b/src/shapepipe/modules/vignetmaker_package/vignetmaker.py @@ -623,6 +623,14 @@ def process_me( Main function to create the stamps in the multi-epoch case. + @sc [label:coupling] registered-zero-object-store + Zero-object catalogues retain SEG_LABEL and empty EPOCH HDUs. + Image-store creation still reads the tile's full-size segmentation + check image with WCS; an empty catalogue doesn't waive that input. + Their stores have zero object keys, not a dummy category-bearing row. + On populated image epochs, SEG_VIGNET is int32 and NEIGHBOUR/OFF_TILE + are boolean arrays with the image stamp's shape. + Parameters ---------- image_dirs : list diff --git a/tests/module/test_categorical_registration.py b/tests/module/test_categorical_registration.py index c16e36180..913b38c31 100644 --- a/tests/module/test_categorical_registration.py +++ b/tests/module/test_categorical_registration.py @@ -208,7 +208,8 @@ def test_nonboolean_epoch_category_raises(category, dtype): _prepare(epoch, tw, ew, 101, np.zeros(shape, np.int32)) -def test_sexcat_without_seg_label_raises(tmp_path): +@pytest.mark.parametrize("n_objects", [0, 1]) +def test_sexcat_without_seg_label_raises(tmp_path, n_objects): cat = tmp_path / "cat.fits" columns = [ fits.Column(name="NUMBER", format="J", array=[101]), @@ -220,6 +221,9 @@ def test_sexcat_without_seg_label_raises(tmp_path): fits.PrimaryHDU(), fits.BinTableHDU(), fits.BinTableHDU.from_columns(columns), ]).writeto(cat) + if n_objects == 0: + with fits.open(cat, mode="update") as hdus: + hdus[2].data = hdus[2].data[:0] maker = VignetMaker( str(cat), "SPHE", ["XWIN_WORLD", "YWIN_WORLD"], str(tmp_path), "-188-307", SimpleNamespace(info=lambda msg: None), @@ -358,8 +362,10 @@ def test_simulation_example_produces_registration_labels(): assert "SEGMENTATION" in config.get("SEXTRACTOR_RUNNER", "CHECKIMAGE") +@pytest.mark.parametrize("empty_tile", [False, True]) @pytest.mark.parametrize("gaia_fk5", [False, True]) -def test_vignetmaker_writes_joined_categories_with_image_grid(tmp_path, gaia_fk5): +def test_vignetmaker_writes_joined_categories_with_image_grid( + tmp_path, gaia_fk5, empty_tile): seg, tw, ew = _segmentation(), _wcs(), _wcs((40.37, 42.61), 1.7, True) if gaia_fk5: ew.wcs.radesys, ew.wcs.equinox = "FK5", 2000.0 @@ -389,6 +395,13 @@ def test_vignetmaker_writes_joined_categories_with_image_grid(tmp_path, gaia_fk5 ), ] ).writeto(cat) + if empty_tile: + # A zero-row tile has no category-bearing epoch entries, not a fake + # object with zero-filled maps. Keep both the column and HDU schemas. + with fits.open(cat, mode="update") as hdus: + for hdu in hdus[2:]: + hdu.data = hdu.data[:0] + raw[:] = 0 seg_path, image_path = ( tmp_path / "segmentation.fits", tmp_path / "image-2254827-27.fits", @@ -417,7 +430,20 @@ def test_vignetmaker_writes_joined_categories_with_image_grid(tmp_path, gaia_fk5 with SqliteDict( str(tmp_path / "image_vignet-188-307.sqlite"), flag="r" ) as db: + if empty_tile: + assert len(db) == 0 + # Empty catalogues don't waive the fourth-input contract. + seg_path.unlink() + with pytest.raises(FileNotFoundError): + maker.process_me( + [[str(tmp_path)]], ["image"], str(headers), 25, str(seg_path) + ) + return epoch = db["101"]["2254827-27"] + for name, dtype in [("SEG_VIGNET", np.int32), ("NEIGHBOUR", bool), + ("OFF_TILE", bool)]: + assert epoch[name].shape == epoch["VIGNET"].shape == (51, 51) + assert epoch[name].dtype == np.dtype(dtype) stamps, ip, offset = get_stamps(image, np.array([[42.34, 40.27]]), 25) npt.assert_array_equal(epoch["VIGNET"], stamps[0]) npt.assert_array_equal(epoch["INT_POS"], ip[0]) diff --git a/tests/module/test_zero_object_tile.py b/tests/module/test_zero_object_tile.py index e65d6e078..81fc0ec1a 100644 --- a/tests/module/test_zero_object_tile.py +++ b/tests/module/test_zero_object_tile.py @@ -4,6 +4,7 @@ import json from pathlib import Path import shutil +import shlex import sqlite3 import subprocess import sys @@ -17,7 +18,7 @@ from shapepipe.modules.sextractor_package import sextractor_script as sx from shapepipe.modules.sextractor_package import match_catalogue as mc from shapepipe.modules.merge_headers_package.merge_headers import merge_headers -from shapepipe.modules.vignetmaker_package.vignetmaker import VignetMaker +from shapepipe.modules.vignetmaker_runner import vignetmaker_runner from shapepipe.modules.psfex_interp_package.psfex_interp import PSFExInterpolator from shapepipe.modules.ngmix_runner import ngmix_runner from shapepipe.modules.merge_sep_cats_package.merge_sep_cats import MergeSep @@ -28,6 +29,42 @@ ) from tests.module.test_match_catalogue import _external, _grid from tests.module.test_ngmix_empty_tile import _RecordingLogger, _runner_config +from tests.module.test_categorical_registration import _wcs + + +def test_zero_detection_check_image(tmp_path): + """Real SExtractor writes a full-size all-zero segmentation even with no rows.""" + root = Path(__file__).resolve().parents[2] / "workflow/config/cfis" + image = tmp_path / "image.fits" + wcs = _wcs() + fits.writeto(image, np.zeros((64, 64), np.float32), wcs.to_header()) + param = tmp_path / "empty.param" + param.write_text("NUMBER\nX_IMAGE\nY_IMAGE\nVIGNET(3,3)\n") + augmented = sx.seg_vignet_param_file(str(param), str(tmp_path / "seg.param")) + caller = sx.SExtractorCaller( + [str(image)], str(tmp_path), "-empty", str(root / "default_tile.sex"), + augmented, str(root / "gauss_3.0_7x7.conv"), + False, False, False, False, False, False, False, + check_image=["BACKGROUND", "SEGMENTATION"], + ) + result = subprocess.run( + shlex.split(caller.make_command_line("source-extractor")), + capture_output=True, text=True, + ) + assert result.returncode == 0, result.stdout + result.stderr + with fits.open(caller.path_output_file) as hdus: + assert len(hdus["LDAC_OBJECTS"].data) == 0 + segmentation = caller.check_paths["SEGMENTATION"] + with fits.open(segmentation) as hdus: + assert hdus[0].data.shape == (64, 64) + assert hdus[0].data.dtype.kind == "i" + assert not hdus[0].data.any() + assert hdus[0].header["CTYPE1"] == "RA---TAN" + assert hdus[0].header["CRPIX1"] == wcs.wcs.crpix[0] + sx.add_seg_vignet(caller.path_output_file, segmentation) + with fits.open(caller.path_output_file) as hdus: + assert hdus["LDAC_OBJECTS"].data["SEG_LABEL"].shape == (0,) + assert hdus["LDAC_OBJECTS"].data["SEG_VIGNET"].shape == (0, 3, 3) @pytest.mark.parametrize("epoch_slots", [None, 12]) @@ -41,6 +78,7 @@ def test_zero_object_tile_modules_and_publication( products_dir = products_dir or tmp_path / "products" run = tmp_path / tile log = _RecordingLogger() + log.debug = log.info # Exposure-directory discovery also emits debug logs. def output(stage, runner): path = run / "output" / stage / runner / "output" @@ -72,12 +110,19 @@ def manifest(stage, subdir=None, suffix=""): ] + [fits.Column(name="VIGNET", format="9E", dim="(3,3)", array=np.empty((0, 3, 3), np.float32))]) hdus[2] = fits.BinTableHDU.from_columns(cols, name="LDAC_OBJECTS") - seg = tmp_path / "seg.fits" - fits.writeto(seg, np.zeros((10, 10), np.int32)) + # Zero detections still produce a full-size, all-sky SEGMENTATION check + # image, not an absent file or a zero-axis FITS image. SExtractor writes + # it before the join/post-processing (see test_zero_detection_check_image). + seg = detected / f"segmentation{number}.fits" + fits.writeto(seg, np.zeros((10, 10), np.int32), _wcs().to_header()) sx.add_seg_vignet(str(cat), str(seg), w_log=log) with fits.open(cat) as hdus: assert hdus[2].data["SEG_VIGNET"].shape == (0, 3, 3) assert hdus[2].data["SEG_VIGNET"].dtype.kind == "i" + assert hdus[2].data["SEG_VIGNET"].dtype.itemsize == 4 + labels = hdus[2].data["SEG_LABEL"] + assert labels.shape == (0,) + assert labels.dtype.kind == "i" and labels.dtype.itemsize == 4 x, y = _grid(30) ext = _external(tmp_path / "external.cat", range(1, 31), x, y) counts = mc.match_catalogue(str(cat), ext, w_log=log) @@ -89,26 +134,45 @@ def manifest(stage, subdir=None, suffix=""): with fits.open(cat) as hdus: assert len(hdus["EPOCH_0"].data) == 0 assert len(hdus["LDAC_OBJECTS"].data) == 0 + assert hdus["LDAC_OBJECTS"].data["SEG_LABEL"].shape == (0,) + assert hdus["LDAC_OBJECTS"].data["SEG_VIGNET"].shape == (0, 3, 3) - # Real PSF interpolation and all four multi-epoch vignette stores. + # Real PSF interpolation and the four-input multi-epoch runners. psfout = output("run_sp_tile_PiViVi", "psfex_interp_runner") psf = PSFExInterpolator(None, str(cat), str(psfout), number, log, pos_params=["XWIN_WORLD", "YWIN_WORLD"]) psf.process_me([str(tmp_path)], "psf", headers) viout = output("run_sp_tile_PiViVi", "vignetmaker_runner") - vi = VignetMaker(str(cat), "SPHE", ["XWIN_WORLD", "YWIN_WORLD"], - str(viout), number, log) - vi.process_me([[str(tmp_path)]], ["image", "weight", "flag"], headers, 1) + exp_root = tmp_path / "exp" + exp_numbers = tmp_path / f"exp_numbers{number}.txt" + exp_numbers.write_text(exp + "\n") + # Directory discovery is real, but zero rows must not read CCD images. + (exp_root / exp[:2] / exp / "output/run_sp_exp/split_exp_runner/output").mkdir( + parents=True) + config = CustomParser() + config.read_dict({"VIGNETMAKER_RUNNER": dict( + MASKING="False", STAMP_SIZE="3", COORD="SPHE", MODE="MULTI-EPOCH", + POSITION_PARAMS="XWIN_WORLD,YWIN_WORLD", ME_IMAGE_EXP_DIR=str(exp_root), + ME_IMAGE_EXP_RUNNERS="split_exp_runner", + )}) + for patterns in ["image,weight,flag", "exp_background,exp_background_rms"]: + config.set("VIGNETMAKER_RUNNER", "ME_IMAGE_PATTERN", patterns) + assert vignetmaker_runner( + [str(cat), headers, str(exp_numbers), str(seg)], + {"output": str(viout)}, number, config, "VIGNETMAKER_RUNNER", log, + ) == (None, None) bgout = viout - vi = VignetMaker(str(cat), "SPHE", ["XWIN_WORLD", "YWIN_WORLD"], - str(bgout), number, log) - vi.process_me([[str(tmp_path)]], ["exp_background", "exp_background_rms"], headers, 1) stores = [viout / f"{name}_vignet{number}.sqlite" for name in ["image", "weight", "flag"]] psfpath = psfout / f"galaxy_psf{number}.sqlite" bgpath = bgout / f"exp_background_vignet{number}.sqlite" - for path in [*stores, psfpath, bgpath]: - with SqliteDict(str(path)) as db: + for path in [*stores, psfpath, bgpath, + bgout / f"exp_background_rms_vignet{number}.sqlite"]: + assert path.is_file() + with SqliteDict(str(path), flag="r") as db: + # Stores are keyed by real object NUMBERs: no fake row or schema + # sentinel. Category shapes/dtypes on actual image epochs are + # checked by test_vignetmaker_writes_joined_categories_with_image_grid. assert len(db) == 0 monkeypatch.setenv("SP_PSF", "psfex") manifest("tile_vignets") @@ -120,8 +184,9 @@ def manifest(stage, subdir=None, suffix=""): log.messages.clear() config = _runner_config() config.set("NGMIX_RUNNER", "BLEND_HANDLING", "uberseg") - config.set("NGMIX_RUNNER", "ID_OBJ_MIN", str(k)) - config.set("NGMIX_RUNNER", "ID_OBJ_MAX", str(k)) + # ngmix_range's bounded empty interval also works on registered stores. + config.set("NGMIX_RUNNER", "ID_OBJ_MIN", "2") + config.set("NGMIX_RUNNER", "ID_OBJ_MAX", "1") assert ngmix_runner( [str(cat), str(stores[0]), str(bgpath), str(psfpath), str(stores[1]), str(stores[2]), headers], @@ -152,6 +217,7 @@ def manifest(stage, subdir=None, suffix=""): final = finalout / f"final_cat{number}.hdf5" with h5py.File(final) as h5: assert "TILE_ID" in h5 and "NGMIX_MCAL_FLAGS" in h5 + assert not {"SEG_LABEL", "SEG_VIGNET", "VIGNET"}.intersection(h5) assert len(h5) > 50 assert all(d.shape[0] == 0 for d in h5.values()) monkeypatch.setenv("NGMIX_N_CHUNKS", str(n_chunks)) diff --git a/tests/workflow/test_zero_object_tile.py b/tests/workflow/test_zero_object_tile.py index 8e780b16c..0acad6aa5 100644 --- a/tests/workflow/test_zero_object_tile.py +++ b/tests/workflow/test_zero_object_tile.py @@ -4,6 +4,9 @@ does not exercise the empty-tile path (Fir tile 177.257). Execute that writer and every scheduled reader from the resolved job params, then feed their exported bounds to the real module-to-publication regression. +That fixture runs the four-input vignetmaker runner with a full-size all-zero +segmentation.fits carrying the tile WCS, as written by zero-detection SExtractor; +ngmix consumes the resulting zero-key registered stores with bounds (2, 1). """ import json