From afc7147603ce77540ddbd016bb91fd88bcec3bf3 Mon Sep 17 00:00:00 2001 From: Mike Jarvis Date: Sun, 1 Nov 2026 17:59:14 -0500 Subject: [PATCH 01/18] Indicate that that bare strings as image header keys is deprecated for ra, dec as well --- piff/input.py | 36 ++++++++++++++++++------------------ tests/test_input.py | 20 ++++++++++++-------- tests/test_pixel.py | 10 ++++++++-- 3 files changed, 38 insertions(+), 28 deletions(-) diff --git a/piff/input.py b/piff/input.py index 72f33674..46a1d787 100644 --- a/piff/input.py +++ b/piff/input.py @@ -499,8 +499,8 @@ def __init__(self, config, base=None, logger=None): self.use_partial = top_level_params.get('use_partial', False) if 'nstars' in config: - logger.warning("input.nstars is deprecated; use select.nstars for the new global " - "highest-S/N behavior.") + logger.error("input.nstars is deprecated; use select.nstars for the new global " + "highest-S/N behavior.") if 'nimages' in config: nimages = galsim.config.ParseValue(config, 'nimages', base, int)[0] @@ -836,15 +836,17 @@ def getRawImageData(self, image_num, logger=None): config=self.config, base=self.base, logger=logger) @staticmethod - def _handle_depr_image_value(value, image, name, logger): - # gain, satur, noise, and sky used to be allowed to be in a FITS header. + def _handle_depr_image_value(value, header, name, logger): + # gain, satur, noise, sky, ra, and dec used to allow bare FITS header keys. # Now this functionality should use the ImageHeaderValue type to be more explicit. # The old behavior still works, but is deprecated. if isinstance(value, str) and value[0] not in '@$': - logger.error("WARNING: Using a bare FITS header key for %s is deprecated." - "Use { 'type': 'ImageHeaderValue': 'key': %s } instead.", - name, value) - value = float(image.header[value]) + logger.error("WARNING: Using a bare FITS header key for %s is deprecated. " + "Use {type: ImageHeaderValue, key: %s} instead.", name, value) + value = header[value] + # Pointing values may be sexagesimal strings, parsed by setPointing. + if name not in ('ra', 'dec'): + value = float(value) return value @staticmethod @@ -1503,13 +1505,13 @@ def setPointing(self, ra, dec, logger=None): 1. numerical values (in Hours, Degrees respective) for ra, dec 2. hh:mm:ss.ssss, dd:mm:ss.ssss strings giving hours/degrees, minutes, seconds for each - 3. FITS header key words to read to get the ra, dec values + 3. FITS header key words to read to get the ra, dec values [deprecated; + use ImageHeaderValue config types instead] 4. None, which will attempt to find the spatial center of all the input images using the midpoint of the min/max ra and dec values of the image corners according to their individual WCS functions. [Not implemented currently.] 5. dict with GalSim-style config types to be parsed. """ - import fitsio logger = LoggerWrapper(logger) if (ra is None) != (dec is None): @@ -1572,19 +1574,17 @@ def setPointing(self, ra, dec, logger=None): self.pointing.ra / galsim.hours, self.pointing.dec / galsim.degrees) else: + # This is now deprecated. This uses ra, dec as header keys, but these should now + # use ImageHeaderValue instead to be more explicit. file_name = self.image_file_name[0] if len(self.chipnums) == 1: logger.verbose("Setting pointing from keywords %s, %s", ra, dec) else: logger.verbose("Setting pointing from keywords %s, %s in %s", ra, dec, file_name) - fits = fitsio.FITS(file_name) hdu = 1 if file_name.endswith('.fz') else 0 - header = fits[hdu].read_header() - if ra not in header: - raise KeyError("Key %s not found in FITS header"%ra) - ra = header[ra] - if dec not in header: - raise KeyError("Key %s not found in FITS header"%dec) - dec = header[dec] + import fitsio + header = fitsio.read_header(file_name, ext=hdu) + ra = self._handle_depr_image_value(ra, header, 'ra', logger) + dec = self._handle_depr_image_value(dec, header, 'dec', logger) # Recurse to do further parsing. self.setPointing(ra, dec, logger) diff --git a/tests/test_input.py b/tests/test_input.py index abe451c8..430973b7 100644 --- a/tests/test_input.py +++ b/tests/test_input.py @@ -2252,10 +2252,10 @@ def test_pointing(): np.testing.assert_almost_equal(input.pointing.ra.rad, np.pi/2.) np.testing.assert_almost_equal(input.pointing.dec.rad, -np.pi/6.) - # Strings as keys into FITS header - config['ra'] = 'RA' - config['dec'] = 'DEC' - input = piff.InputFiles(config, logger=logger) + # Ra, dec can be values in the fits header. + config['ra'] = { 'type': 'ImageHeaderValue', 'key': 'RA' } + config['dec'] = { 'type': 'ImageHeaderValue', 'key': 'DEC' } + input = piff.InputFiles(config) np.testing.assert_almost_equal(input.pointing.ra.rad, np.pi/2.) np.testing.assert_almost_equal(input.pointing.dec.rad, -np.pi/6.) @@ -2266,10 +2266,14 @@ def test_pointing(): np.testing.assert_almost_equal(input.pointing.ra.rad, np.pi/2.) np.testing.assert_almost_equal(input.pointing.dec.rad, -np.pi/6.) - # Can use explicit config type to get the same thing. - config['ra'] = { 'type': 'ImageHeaderValue', 'key': 'RA' } - config['dec'] = { 'type': 'ImageHeaderValue', 'key': 'DEC' } - input = piff.InputFiles(config, logger=logger) + # This used to be done with bare strings. This is still allowed, but deprecated. + config['ra'] = 'RA' + config['dec'] = 'DEC' + with CaptureLog(1) as cl: + input = piff.InputFiles(config, logger=cl.logger) + assert 'Using a bare FITS header key for ra is deprecated' in cl.output + assert 'Using a bare FITS header key for dec is deprecated' in cl.output + assert 'ImageHeaderValue' in cl.output np.testing.assert_almost_equal(input.pointing.ra.rad, np.pi/2.) np.testing.assert_almost_equal(input.pointing.dec.rad, -np.pi/6.) diff --git a/tests/test_pixel.py b/tests/test_pixel.py index e7f7332a..f1551dce 100644 --- a/tests/test_pixel.py +++ b/tests/test_pixel.py @@ -1387,8 +1387,14 @@ def test_des2(): 'x_col' : 'x', 'y_col' : 'y', 'sky_col' : 'sky', - 'ra' : 'TELRA', - 'dec' : 'TELDEC', + 'ra' : { + 'type': 'ImageHeaderValue', + 'key': 'TELRA', + }, + 'dec' : { + 'type': 'ImageHeaderValue', + 'key': 'TELDEC', + }, 'gain' : 1.0, # Real version uses pixmappy WCS, but that's not important for this test, so skip it 'stamp_size' : 25 From 7abd74ad06a14d196584e8e1b077a58096f76b88 Mon Sep 17 00:00:00 2001 From: Mike Jarvis Date: Sun, 1 Nov 2026 17:59:52 -0500 Subject: [PATCH 02/18] Switch some staticmethods in input to classmethod to make them provide better hooks for subclasses to override. --- piff/input.py | 75 ++++++++++++++++++++++++++++----------------------- 1 file changed, 42 insertions(+), 33 deletions(-) diff --git a/piff/input.py b/piff/input.py index 46a1d787..4fec1b94 100644 --- a/piff/input.py +++ b/piff/input.py @@ -849,13 +849,13 @@ def _handle_depr_image_value(value, header, name, logger): value = float(value) return value - @staticmethod - def _getRawImageData(image_kwargs, cat_kwargs, wcs, + @classmethod + def _getRawImageData(cls, image_kwargs, cat_kwargs, wcs, invert_weight, remove_signal_from_weight, config, base, logger=None): from .config import LoggerWrapper logger = LoggerWrapper(logger) - image, weight = InputFiles.readImage(logger=logger, **image_kwargs) + image, weight = cls.readImage(logger=logger, **image_kwargs) if invert_weight: weight.invertSelf() @@ -863,7 +863,7 @@ def _getRawImageData(image_kwargs, cat_kwargs, wcs, # Update the wcs image.wcs = wcs - image_pos, extra_props = InputFiles.readStarCatalog( + image_pos, extra_props = cls.readStarCatalog( logger=logger, image=image, **cat_kwargs) if remove_signal_from_weight: @@ -878,24 +878,24 @@ def _getRawImageData(image_kwargs, cat_kwargs, wcs, # This isn't quite right, but hopefully the gain won't vary too much for # different objects, so it should be close. gain = np.mean(extra_props['gain']) - weight, _ = InputFiles._removeSignalFromWeight(signal, weight, gain=gain) + weight, _ = cls._removeSignalFromWeight(signal, weight, gain=gain) else: # If no gain provided, then we want to estimate the gain from the weight image. - weight, g = InputFiles._removeSignalFromWeight(signal, weight) + weight, g = cls._removeSignalFromWeight(signal, weight) extra_props['gain'] = np.array([g] * len(image_pos), dtype=float) logger.info("Empirically determined gain = %f",g) logger.verbose("Removed signal from weight image.") return image, weight, image_pos, extra_props - @staticmethod - def _makeStarsFromImage(image_kwargs, cat_kwargs, wcs, chipnum, + @classmethod + def _makeStarsFromImage(cls, image_kwargs, cat_kwargs, wcs, chipnum, stamp_size, pointing, bandpass, use_partial, invert_weight, remove_signal_from_weight, config, base, logger): """Make "stars" from a single input image """ - image, wt, image_pos, extra_props = InputFiles._getRawImageData( + image, wt, image_pos, extra_props = cls._getRawImageData( image_kwargs, cat_kwargs, wcs, invert_weight, remove_signal_from_weight, config, base, logger) logger.verbose("Processing catalog %s with %d objects",chipnum,len(image_pos)) @@ -980,7 +980,7 @@ def setWCS(self, config, base, logger): base['image_num'] = image_num image_file_name = kwargs['image_file_name'] image_hdu = kwargs['image_hdu'] - image = galsim.fits.read(image_file_name, hdu=image_hdu, read_header=True) + image = self._read_image(image_file_name, image_hdu, read_header=True) if 'wcs' in config: logger.info("Using custom wcs from config for %s",image_file_name) base['index_key'] = 'image_num' @@ -1021,7 +1021,16 @@ def _removeSignalFromWeight(image, weight, gain=None): return newweight, gain @staticmethod - def readImage(image_file_name, image_hdu, weight_file_name, weight_hdu, + def _read_image(file_name, hdu, *, read_header): + """Read one image plane, optionally including its metadata. + + Subclasses may override this method to support other file formats. The returned + GalSim image must include its WCS and, when requested, a ``header`` attribute. + """ + return galsim.fits.read(file_name, hdu=hdu, read_header=read_header) + + @classmethod + def readImage(cls, image_file_name, image_hdu, weight_file_name, weight_hdu, badpix_file_name, badpix_hdu, badpix_zeros, sky_file_name, sky_hdu, image_num, config, base, logger): """Read in the image and weight map (or make one if no weight information is given @@ -1047,7 +1056,7 @@ def readImage(image_file_name, image_hdu, weight_file_name, weight_hdu, logger.info("Reading image file %s",image_file_name) galsim.config.RemoveCurrent(base) base['image_num'] = image_num - image = galsim.fits.read(image_file_name, hdu=image_hdu, read_header=True) + image = cls._read_image(image_file_name, image_hdu, read_header=True) base['_current_image'] = image noise = None @@ -1068,14 +1077,14 @@ def readImage(image_file_name, image_hdu, weight_file_name, weight_hdu, if noise is not None: noise = galsim.config.ParseValue(config, 'noise', base, None)[0] - noise = InputFiles._handle_depr_image_value(noise, image, 'noise', logger) + noise = cls._handle_depr_image_value(noise, image.header, 'noise', logger) # Either read in the weight image, or build a dummy one if weight_file_name is not None or weight_hdu is not None: weight_file_name = weight_file_name or image_file_name weight_hdu = weight_hdu or (1 if weight_file_name.endswith('.fz') else 0) logger.verbose("Reading weight image from %s, hdu %d.", weight_file_name, weight_hdu) - weight = galsim.fits.read(weight_file_name, hdu=weight_hdu) + weight = cls._read_image(weight_file_name, weight_hdu, read_header=False) if np.all(weight.array == 0): logger.error("According to the weight mask in %s, all pixels have zero weight!", image_file_name) @@ -1101,7 +1110,7 @@ def readImage(image_file_name, image_hdu, weight_file_name, weight_hdu, if sky_file_name is not None: hdu_str = " from hdu %s"%(sky_hdu) if sky_hdu is not None else "" logger.verbose("Reading sky image %s.", sky_file_name + hdu_str) - sky = galsim.fits.read(sky_file_name, hdu=sky_hdu) + sky = cls._read_image(sky_file_name, sky_hdu, read_header=False) image -= sky # If requested, set wt=0 for any bad pixels @@ -1109,7 +1118,7 @@ def readImage(image_file_name, image_hdu, weight_file_name, weight_hdu, badpix_file_name = badpix_file_name or image_file_name badpix_hdu = badpix_hdu or (1 if badpix_file_name.endswith('.fz') else 0) logger.verbose("Reading badpix image from %s, hdu %d.", badpix_file_name, badpix_hdu) - badpix = galsim.fits.read(badpix_file_name, hdu=badpix_hdu) + badpix = cls._read_image(badpix_file_name, badpix_hdu, read_header=False) # The badpix image may be offset by 32768 from the true value. # If so, subtract it off. if np.any(badpix.array > 32767): # pragma: no cover @@ -1190,20 +1199,20 @@ def _resolve_sed_file_name(value, cat_file_name): else: return sed_file_name - @staticmethod - def _read_sed_mapping(sed_file_name, cat_file_name): + @classmethod + def _read_sed_mapping(cls, sed_file_name, cat_file_name): if isinstance(sed_file_name, dict): return sed_file_name - sed_map_file = InputFiles._resolve_sed_file_name(sed_file_name, cat_file_name) + sed_map_file = cls._resolve_sed_file_name(sed_file_name, cat_file_name) with open(sed_map_file) as f: sed_map = yaml.safe_load(f) if not isinstance(sed_map, dict): raise ValueError("SED mapping file must parse to a dict: %r" % sed_map_file) return sed_map - @staticmethod - def readStarCatalog(cat_file_name, cat_hdu, x_col, y_col, + @classmethod + def readStarCatalog(cls, cat_file_name, cat_hdu, x_col, y_col, ra_col, dec_col, ra_units, dec_units, image, flag_col, skip_flag, use_flag, property_cols, sed_col, sed_wave_type, sed_file_name, sed_flux_type, sed_wave_key, sed_flux_key, @@ -1257,7 +1266,7 @@ def readStarCatalog(cat_file_name, cat_hdu, x_col, y_col, # Read in the star catalog logger.info("Reading input catalog %s.",cat_file_name) - cat = InputFiles._read_cat(cat_file_name, cat_hdu) + cat = cls._read_cat(cat_file_name, cat_hdu) sky = None if 'sky' in config: @@ -1284,14 +1293,14 @@ def readStarCatalog(cat_file_name, cat_hdu, x_col, y_col, flag_col) if use_flag is not None: # Remove any objects with flag & use_flag == 0 - mask = InputFiles._flag_select(col, use_flag) == 0 + mask = cls._flag_select(col, use_flag) == 0 logger.verbose("Removing objects with flag (col %s) & %d == 0",flag_col,use_flag) if skip_flag != -1: - mask |= InputFiles._flag_select(col, skip_flag) != 0 + mask |= cls._flag_select(col, skip_flag) != 0 logger.verbose("Removing objects with flag (col %s) & %d != 0",flag_col,skip_flag) else: # Remove any objects with flag & skip_flag != 0 - mask = InputFiles._flag_select(col, skip_flag) != 0 + mask = cls._flag_select(col, skip_flag) != 0 if skip_flag == -1: logger.verbose("Removing objects with flag (col %s) != 0",flag_col) else: @@ -1383,7 +1392,7 @@ def safe_to_image(wcs, ra, dec): raise ValueError("sed_col = %s is not a column in %s" % (sed_col, cat_file_name)) sed_map = None if sed_file_name is not None: - sed_map = InputFiles._read_sed_mapping(sed_file_name, cat_file_name) + sed_map = cls._read_sed_mapping(sed_file_name, cat_file_name) sed_file_name_values = [] for sed_label in cat[sed_col]: if sed_map is not None: @@ -1395,7 +1404,7 @@ def safe_to_image(wcs, ra, dec): sed_file_name = sed_map[sed_label] else: sed_file_name = sed_label - sed_file_name = InputFiles._resolve_sed_file_name(sed_file_name, cat_file_name) + sed_file_name = cls._resolve_sed_file_name(sed_file_name, cat_file_name) sed_file_name_values.append(sed_file_name) extra_props['sed_file_name'] = np.array(sed_file_name_values, dtype=object) extra_props['sed_wave_type'] = np.array([sed_wave_type] * len(cat), dtype=object) @@ -1405,7 +1414,7 @@ def safe_to_image(wcs, ra, dec): extra_props['sed_tol'] = np.full(len(cat), sed_tol, dtype=float) extra_props['sed_max_samples'] = np.full(len(cat), sed_max_samples, dtype=int) elif sed_file_name is not None: - sed_file_name = InputFiles._resolve_sed_file_name(sed_file_name, cat_file_name) + sed_file_name = cls._resolve_sed_file_name(sed_file_name, cat_file_name) extra_props['sed_file_name'] = np.array([sed_file_name] * len(cat), dtype=object) extra_props['sed_wave_type'] = np.array([sed_wave_type] * len(cat), dtype=object) extra_props['sed_flux_type'] = np.array([sed_flux_type] * len(cat), dtype=object) @@ -1425,7 +1434,7 @@ def safe_to_image(wcs, ra, dec): extra_props['sky'] = np.float32(cat[sky_col]) elif sky is not None and sky != 'median': sky = galsim.config.ParseValue(config, 'sky', base, None)[0] - sky = InputFiles._handle_depr_image_value(sky, image, 'sky', logger) + sky = cls._handle_depr_image_value(sky, image.header, 'sky', logger) extra_props['sky'] = np.array([sky]*len(cat), dtype=np.float32) # Make the list of gain values: @@ -1438,13 +1447,13 @@ def safe_to_image(wcs, ra, dec): extra_props['gain'] = cat[gain_col] elif gain is not None: gain = galsim.config.ParseValue(config, 'gain', base, None)[0] - gain = InputFiles._handle_depr_image_value(gain, image, 'gain', logger) + gain = cls._handle_depr_image_value(gain, image.header, 'gain', logger) extra_props['gain'] = np.array([gain]*len(cat), dtype=float) # Get the saturation level if satur is not None: satur = galsim.config.ParseValue(config, 'satur', base, None)[0] - satur = InputFiles._handle_depr_image_value(satur, image, 'satur', logger) + satur = cls._handle_depr_image_value(satur, image.header, 'satur', logger) logger.debug("Using saturation value: %s",satur) extra_props['satur'] = np.array([satur]*len(cat), dtype=float) @@ -1454,7 +1463,7 @@ def safe_to_image(wcs, ra, dec): if properties is not None: logger.debug('properties = %s', properties) - extra_props.update(InputFiles._evaluate_properties( + extra_props.update(cls._evaluate_properties( properties, extra_props, len(cat), base, logger)) return image_pos, extra_props @@ -1547,7 +1556,7 @@ def setPointing(self, ra, dec, logger=None): (isinstance(dec, str) and (dec[0] in ['$','@']))): image_file_name = self.image_kwargs[0]['image_file_name'] image_hdu = self.image_kwargs[0]['image_hdu'] - image = galsim.fits.read(image_file_name, hdu=image_hdu, read_header=True) + image = self._read_image(image_file_name, image_hdu, read_header=True) base = galsim.config.CopyConfig(self.base) base['index_key'] = 'image_num' base['image_num'] = 0 From 7856c6385c37363a5dbc6f84a38713aaf64a1e85 Mon Sep 17 00:00:00 2001 From: Mike Jarvis Date: Mon, 2 Nov 2026 00:28:15 -0500 Subject: [PATCH 03/18] Update *_hdu -> *_ext and allow for named extensions --- piff/input.py | 150 +++++++++++++++----------- tests/sizemag.yaml | 8 +- tests/test_gp_interp.py | 8 +- tests/test_input.py | 225 +++++++++++++++++++++++++++++++-------- tests/test_knn_interp.py | 8 +- tests/test_optics.py | 2 +- tests/test_pixel.py | 16 +-- tests/test_simple.py | 2 +- tests/test_sizemag.py | 8 +- tests/test_stats.py | 14 +-- 10 files changed, 304 insertions(+), 137 deletions(-) diff --git a/piff/input.py b/piff/input.py index 4fec1b94..164d3e69 100644 --- a/piff/input.py +++ b/piff/input.py @@ -223,12 +223,13 @@ class InputFiles(Input): :chipnum: The id number of this chip used to reference this image [default: image_num] - :image_hdu: The hdu to use in the image files. [default: None, which means use - either 0 or 1 as typical given the compression sceme of the file] - :weight_hdu: The hdu to use for weight images. [default: None, which means a weight - image with all 1's will be automatically created] - :badpix_hdu: The hdu to use for badpix images. Pixels with badpix != 0 will be given - weight == 0. [default: None] + :image_ext: The extension number or name to use in the image files. [default: + None, which means use either 0 or 1 according to FITS compression] + :weight_ext: The extension number or name to use for weight images. [default: + None, which means use the weight file's default extension if supplied, + otherwise create a weight image with all 1's] + :badpix_ext: The extension number or name for badpix images. Pixels with badpix != 0 + will be given weight == 0. [default: None] :noise: Rather than a weight image, provide the noise variance in the image. (Useful for simulations where this is a known value.) [default: None] :weight_file_name: If the weight image is in a different file than the main image, @@ -237,8 +238,12 @@ class InputFiles(Input): this gives the name of the file to use. [default: None] :badpix_zeros: Whether to treat all zeros in the input image as bad pixels. [default: False] + :sky_file_name: A file containing a sky background image to subtract. [default: None] + :sky_ext: The extension number or name to use in the sky file. [default: None, + which means use the file's default image extension] - :cat_hdu: The hdu to use in the catalog files. [default: 1] + :cat_ext: The extension number or name in FITS catalog files. Ignored for parquet + catalogs. [default: None, which means use the first table extension] :x_col: The name of the X column in the input catalogs. [default: 'x'] :y_col: The name of the Y column in the input catalogs. [default: 'y'] :ra_col: (Alternative to x_col, y_col) The name of a right ascension column in @@ -448,15 +453,15 @@ def __init__(self, config, base=None, logger=None): 'flag_col' : str, 'skip_flag' : int, 'use_flag' : int, - 'image_hdu' : int, - 'weight_hdu' : int, - 'badpix_hdu' : int, + 'image_ext' : (int, str), + 'weight_ext' : (int, str), + 'badpix_ext' : (int, str), 'weight_file_name' : str, 'badpix_file_name' : str, 'badpix_zeros' : bool, 'sky_file_name' : str, - 'sky_hdu': int, - 'cat_hdu' : int, + 'sky_ext': (int, str), + 'cat_ext' : (int, str), 'invert_weight' : bool, 'remove_signal_from_weight' : bool, 'stamp_size' : int, @@ -471,6 +476,17 @@ def __init__(self, config, base=None, logger=None): config = copy.deepcopy(config) base = copy.deepcopy(base) if base is not None else {'input': config} + for prefix in ['image', 'weight', 'badpix', 'sky', 'cat']: + old = prefix + '_hdu' + new = prefix + '_ext' + if old in config: + if new in config: + raise ValueError("Cannot provide both %s and %s." % (old, new)) + logger.error("%s is deprecated as of version 1.8. Use %s instead.", old, new) + # Keep old keys in config dict in case any Current/Eval types use them. + config[new] = config[old] + ignore.append(old) + # In GalSim, the base dict holds additional parameters that may be of use. # For now, add index_kex, as this will be the only thing we index anything on. base['index_key'] = 'image_num' @@ -507,14 +523,14 @@ def __init__(self, config, base=None, logger=None): if nimages < 1: raise ValueError('input.nimages must be >= 1') - if 'image_hdu' in config and isinstance(config['image_hdu'], list): - if len(config['image_hdu']) == 0: - raise ValueError("image_hdu may not be an empty list") + if 'image_ext' in config and isinstance(config['image_ext'], list): + if len(config['image_ext']) == 0: + raise ValueError("image_ext may not be an empty list") if nimages is None: - nimages = len(config['image_hdu']) - elif nimages != len(config['image_hdu']): - raise ValueError("nimages = %s doesn't match length of image_hdu list (%d)"%( - nimages, len(config['image_hdu']))) + nimages = len(config['image_ext']) + elif nimages != len(config['image_ext']): + raise ValueError("nimages = %s doesn't match length of image_ext list (%d)" % ( + nimages, len(config['image_ext']))) # Deal with dir here, since sometimes we need to have it already attached for glob # to work. @@ -682,25 +698,25 @@ def __init__(self, config, base=None, logger=None): # Read the image image_file_name = params['image_file_name'] - image_hdu = params.get('image_hdu', None) + image_ext = params.get('image_ext', None) weight_file_name = params.get('weight_file_name', None) - weight_hdu = params.get('weight_hdu', None) + weight_ext = params.get('weight_ext', None) badpix_file_name = params.get('badpix_file_name', None) - badpix_hdu = params.get('badpix_hdu', None) + badpix_ext = params.get('badpix_ext', None) badpix_zeros = params.get('badpix_zeros', False) sky_file_name = params.get('sky_file_name', None) - sky_hdu = params.get('sky_hdu', None) + sky_ext = params.get('sky_ext', None) self.image_file_name.append(image_file_name) self.image_kwargs.append({ 'image_file_name' : image_file_name, - 'image_hdu' : image_hdu, + 'image_ext' : image_ext, 'weight_file_name' : weight_file_name, - 'weight_hdu' : weight_hdu, + 'weight_ext' : weight_ext, 'badpix_file_name' : badpix_file_name, - 'badpix_hdu' : badpix_hdu, + 'badpix_ext' : badpix_ext, 'badpix_zeros' : badpix_zeros, 'sky_file_name' : sky_file_name, - 'sky_hdu' : sky_hdu, + 'sky_ext' : sky_ext, 'image_num' : image_num, 'config' : self.config, 'base' : self.base, @@ -708,7 +724,7 @@ def __init__(self, config, base=None, logger=None): # Read the catalog cat_file_name = params['cat_file_name'] - cat_hdu = params.get('cat_hdu', None) + cat_ext = params.get('cat_ext', None) x_col = params.get('x_col', 'x') y_col = params.get('y_col', 'y') ra_col = params.get('ra_col', None) @@ -746,7 +762,7 @@ def __init__(self, config, base=None, logger=None): self.cat_file_name.append(cat_file_name) self.cat_kwargs.append({ 'cat_file_name' : cat_file_name, - 'cat_hdu' : cat_hdu, + 'cat_ext' : cat_ext, 'x_col' : x_col, 'y_col' : y_col, 'ra_col' : ra_col, @@ -979,8 +995,8 @@ def setWCS(self, config, base, logger): galsim.config.RemoveCurrent(base) # Makes any @ items work correctly base['image_num'] = image_num image_file_name = kwargs['image_file_name'] - image_hdu = kwargs['image_hdu'] - image = self._read_image(image_file_name, image_hdu, read_header=True) + image_ext = kwargs['image_ext'] + image = self._read_image(image_file_name, image_ext, read_header=True) if 'wcs' in config: logger.info("Using custom wcs from config for %s",image_file_name) base['index_key'] = 'image_num' @@ -1021,31 +1037,39 @@ def _removeSignalFromWeight(image, weight, gain=None): return newweight, gain @staticmethod - def _read_image(file_name, hdu, *, read_header): + def _read_image(file_name, ext, *, read_header): """Read one image plane, optionally including its metadata. Subclasses may override this method to support other file formats. The returned GalSim image must include its WCS and, when requested, a ``header`` attribute. """ - return galsim.fits.read(file_name, hdu=hdu, read_header=read_header) + if isinstance(ext, str): + # Apparently we never enabled named hdu access in GalSim, so as of GalSim 2.8, + # it needs a number. So if we get a string, use astropy.io.fits directly to + # get the correct hdu. + from astropy.io import fits + with fits.open(file_name) as hdus: + return galsim.fits.read(hdu_list=hdus[ext], read_header=read_header) + else: + return galsim.fits.read(file_name, hdu=ext, read_header=read_header) @classmethod - def readImage(cls, image_file_name, image_hdu, weight_file_name, weight_hdu, - badpix_file_name, badpix_hdu, badpix_zeros, sky_file_name, sky_hdu, + def readImage(cls, image_file_name, image_ext, weight_file_name, weight_ext, + badpix_file_name, badpix_ext, badpix_zeros, sky_file_name, sky_ext, image_num, config, base, logger): - """Read in the image and weight map (or make one if no weight information is given + """Read in the image and weight map (or make one if no weight information is given). :param image_file_name: The name of the file to read. - :param image_hdu: The hdu of the main image. + :param image_ext: The extension number or name of the main image. :param weight_file_name: The name if the file with the weight image (if any). - :param weight_hdu: The hdu of the weight image (if any). + :param weight_ext: The extension number or name of the weight image (if any). :param badpix_file_name: The name of the file with the bad pixel mask (if any). - :param badpix_hdu: The hdu of the bad pixel mask (if any). + :param badpix_ext: The extension number or name of the bad pixel mask (if any). :param badpix_zeros: Whether to treat all zeros in the input image as bad pixels. [default: False] :param sky_file_name: A file to use for a sky background to subtract from the image (if any). - :param sky_hdu: The hdu to use in the sky_file_name (if any). + :param sky_ext: The extension number or name in sky_file_name (if any). :param config: The input section of the config dict. :param base: The base config dict. :param logger: A logger object for logging debug info. @@ -1056,7 +1080,7 @@ def readImage(cls, image_file_name, image_hdu, weight_file_name, weight_hdu, logger.info("Reading image file %s",image_file_name) galsim.config.RemoveCurrent(base) base['image_num'] = image_num - image = cls._read_image(image_file_name, image_hdu, read_header=True) + image = cls._read_image(image_file_name, image_ext, read_header=True) base['_current_image'] = image noise = None @@ -1080,11 +1104,12 @@ def readImage(cls, image_file_name, image_hdu, weight_file_name, weight_hdu, noise = cls._handle_depr_image_value(noise, image.header, 'noise', logger) # Either read in the weight image, or build a dummy one - if weight_file_name is not None or weight_hdu is not None: + if weight_file_name is not None or weight_ext is not None: weight_file_name = weight_file_name or image_file_name - weight_hdu = weight_hdu or (1 if weight_file_name.endswith('.fz') else 0) - logger.verbose("Reading weight image from %s, hdu %d.", weight_file_name, weight_hdu) - weight = cls._read_image(weight_file_name, weight_hdu, read_header=False) + weight_ext = weight_ext or (1 if weight_file_name.endswith('.fz') else 0) + logger.verbose("Reading weight image from %s, extension %s.", + weight_file_name, weight_ext) + weight = cls._read_image(weight_file_name, weight_ext, read_header=False) if np.all(weight.array == 0): logger.error("According to the weight mask in %s, all pixels have zero weight!", image_file_name) @@ -1108,17 +1133,18 @@ def readImage(cls, image_file_name, image_hdu, weight_file_name, weight_hdu, # If requested, subtract a sky image if sky_file_name is not None: - hdu_str = " from hdu %s"%(sky_hdu) if sky_hdu is not None else "" - logger.verbose("Reading sky image %s.", sky_file_name + hdu_str) - sky = cls._read_image(sky_file_name, sky_hdu, read_header=False) + ext_str = " from extension %s"%(sky_ext) if sky_ext is not None else "" + logger.verbose("Reading sky image %s.", sky_file_name + ext_str) + sky = cls._read_image(sky_file_name, sky_ext, read_header=False) image -= sky # If requested, set wt=0 for any bad pixels - if badpix_file_name is not None or badpix_hdu is not None: + if badpix_file_name is not None or badpix_ext is not None: badpix_file_name = badpix_file_name or image_file_name - badpix_hdu = badpix_hdu or (1 if badpix_file_name.endswith('.fz') else 0) - logger.verbose("Reading badpix image from %s, hdu %d.", badpix_file_name, badpix_hdu) - badpix = cls._read_image(badpix_file_name, badpix_hdu, read_header=False) + badpix_ext = badpix_ext or (1 if badpix_file_name.endswith('.fz') else 0) + logger.verbose("Reading badpix image from %s, extension %s.", + badpix_file_name, badpix_ext) + badpix = cls._read_image(badpix_file_name, badpix_ext, read_header=False) # The badpix image may be offset by 32768 from the true value. # If so, subtract it off. if np.any(badpix.array > 32767): # pragma: no cover @@ -1159,9 +1185,9 @@ def _flag_select(col, flag): return mask @classmethod - def _read_cat(cls, cat_file_name, cat_hdu): + def _read_cat(cls, cat_file_name, cat_ext): if cat_file_name.endswith('.fits'): - return cls._read_fits_cat(cat_file_name, cat_hdu) + return cls._read_fits_cat(cat_file_name, cat_ext) elif cat_file_name.endswith('.parquet'): return cls._read_parquet_cat(cat_file_name) else: @@ -1169,12 +1195,12 @@ def _read_cat(cls, cat_file_name, cat_hdu): try: return cls._read_parquet_cat(cat_file_name) except Exception: - return cls._read_fits_cat(cat_file_name, cat_hdu) + return cls._read_fits_cat(cat_file_name, cat_ext) @classmethod - def _read_fits_cat(cls, cat_file_name, cat_hdu): + def _read_fits_cat(cls, cat_file_name, cat_ext): import fitsio - return fitsio.read(cat_file_name, cat_hdu) + return fitsio.read(cat_file_name, cat_ext) @classmethod def _read_parquet_cat(cls, cat_file_name): @@ -1212,7 +1238,7 @@ def _read_sed_mapping(cls, sed_file_name, cat_file_name): return sed_map @classmethod - def readStarCatalog(cls, cat_file_name, cat_hdu, x_col, y_col, + def readStarCatalog(cls, cat_file_name, cat_ext, x_col, y_col, ra_col, dec_col, ra_units, dec_units, image, flag_col, skip_flag, use_flag, property_cols, sed_col, sed_wave_type, sed_file_name, sed_flux_type, sed_wave_key, sed_flux_key, @@ -1222,7 +1248,7 @@ def readStarCatalog(cls, cat_file_name, cat_hdu, x_col, y_col, """Read in the star catalogs and return lists of positions for each star in each image. :param cat_file_name: The name of the catalog file to read in. - :param cat_hdu: The hdu to use. + :param cat_ext: The extension number or name to use for FITS catalogs. :param x_col: The name of the column with x values. :param y_col: The name of the column with y values. :param ra_col: The name of a column with RA values. @@ -1266,7 +1292,7 @@ def readStarCatalog(cls, cat_file_name, cat_hdu, x_col, y_col, # Read in the star catalog logger.info("Reading input catalog %s.",cat_file_name) - cat = cls._read_cat(cat_file_name, cat_hdu) + cat = cls._read_cat(cat_file_name, cat_ext) sky = None if 'sky' in config: @@ -1555,8 +1581,8 @@ def setPointing(self, ra, dec, logger=None): (isinstance(ra, str) and (ra[0] in ['$','@'])) or (isinstance(dec, str) and (dec[0] in ['$','@']))): image_file_name = self.image_kwargs[0]['image_file_name'] - image_hdu = self.image_kwargs[0]['image_hdu'] - image = self._read_image(image_file_name, image_hdu, read_header=True) + image_ext = self.image_kwargs[0]['image_ext'] + image = self._read_image(image_file_name, image_ext, read_header=True) base = galsim.config.CopyConfig(self.base) base['index_key'] = 'image_num' base['image_num'] = 0 diff --git a/tests/sizemag.yaml b/tests/sizemag.yaml index d93975e8..fd84dbf3 100644 --- a/tests/sizemag.yaml +++ b/tests/sizemag.yaml @@ -1,12 +1,12 @@ input: dir: input image_file_name: DECam_00241238_01.fits.fz - image_hdu: 1 - badpix_hdu: 2 - weight_hdu: 3 + image_ext: 1 + badpix_ext: 2 + weight_ext: 3 cat_file_name: DECam_00241238_01_cat.fits - cat_hdu: 2 + cat_ext: 2 x_col: XWIN_IMAGE y_col: YWIN_IMAGE flag_col: FLAGS diff --git a/tests/test_gp_interp.py b/tests/test_gp_interp.py index 920f9791..da83af50 100644 --- a/tests/test_gp_interp.py +++ b/tests/test_gp_interp.py @@ -413,10 +413,10 @@ def test_yaml(): }, # What hdu is everything in? - 'image_hdu' : 1, - 'badpix_hdu' : 2, - 'weight_hdu' : 3, - 'cat_hdu' : 2, + 'image_ext' : 1, + 'badpix_ext' : 2, + 'weight_ext' : 3, + 'cat_ext' : 2, # What columns in the catalog have things we need? 'x_col' : 'XWIN_IMAGE', diff --git a/tests/test_input.py b/tests/test_input.py index 430973b7..7526a9f1 100644 --- a/tests/test_input.py +++ b/tests/test_input.py @@ -262,7 +262,7 @@ def test_basic(): 'pixel_scale': {'type': 'List_float', 'items': [0.2, 0.3]}, } targets = ['image', 'cat', 'image', 'image', 'sky'] - reference_config = {'nimages': 2, 'weight_hdu': 1, 'badpix_hdu': 2} + reference_config = {'nimages': 2, 'weight_ext': 1, 'badpix_ext': 2} reference_config['wcs'] = {'type': 'PixelScale', 'scale': '$@pixel_scale'} for key, target in zip(file_keys, targets): reference_config[key] = {'type': 'Current', 'key': target} @@ -407,6 +407,124 @@ def test_basic(): assert np.count_nonzero(snr_list >= cutoff) >= len(stars) +@timer +def test_extensions(): + """Test various aspects of accessing FITS extensions, including accessing them by name. + """ + # Write named extensions with known values to test extension selection, sky subtraction, + # and bad-pixel masking. + from astropy.io import fits + file_name = os.path.join('output', 'input_extensions.fits') + science = np.arange(64 * 64, dtype=float).reshape(64, 64) + sky = np.full_like(science, 2.0) + mask = np.zeros(science.shape, dtype=np.int16) + mask[15, 15] = 1 + catalog = np.array([(16.0, 16.0), (32.0, 32.0)], dtype=[('x', float), ('y', float)]) + with fitsio.FITS(file_name, 'rw', clobber=True) as f: + f.write(science, extname='SCI', header={'GS_WCS': 'PixelScale', 'GS_SCALE': 0.4}) + f.write(science + 10, extname='SCI2', + header={'GS_WCS': 'PixelScale', 'GS_SCALE': 0.7}) + f.write(np.full_like(science, 5.0), extname='WEIGHT') + f.write(mask, extname='MASK') + f.write(sky, extname='SKY') + f.write(catalog, extname='CAT') + config = { + 'image_file_name': file_name, + 'cat_file_name': file_name, + 'sky_file_name': file_name, + 'image_ext': 0, + 'weight_ext': 2, + 'badpix_ext': 3, + 'sky_ext': 4, + 'cat_ext': 5, + } + + # Extensions can be selected by either number or name. + names = ['SCI', 'WEIGHT', 'MASK', 'SKY', 'CAT'] + keys = ['image_ext', 'weight_ext', 'badpix_ext', 'sky_ext', 'cat_ext'] + for named in [False, True]: + current = dict(config) + if named: + current.update(zip(keys, names)) + handler = piff.InputFiles(current) + image, weight, positions, _ = handler.getRawImageData(0) + np.testing.assert_array_equal(image.array, science - sky) + np.testing.assert_array_equal(weight.array, np.where(mask, 0, 5)) + assert positions == [galsim.PositionD(16, 16), galsim.PositionD(32, 32)] + assert handler.getWCS()[0] == galsim.PixelScale(0.4) + + # The old names for *_ext was *_hdu. These are still allowed, but deprecated. + for key in keys: + current = dict(config) + old = key.replace('_ext', '_hdu') + current[old] = current.pop(key) + with CaptureLog(1) as cl: + handler = piff.InputFiles(current, logger=cl.logger) + assert '%s is deprecated as of version 1.8. Use %s instead.' % (old, key) in cl.output + assert old in current and key not in current + image, weight, positions, _ = handler.getRawImageData(0) + np.testing.assert_array_equal(image.array, science - sky) + np.testing.assert_array_equal(weight.array, np.where(mask, 0, 5)) + assert positions == [galsim.PositionD(16, 16), galsim.PositionD(32, 32)] + + # References to the deprecated names in Current or Eval types still work. + current = dict(config) + current['image_hdu'] = current.pop('image_ext') + current['weight_hdu'] = '$@input.image_hdu + 2' + current.pop('weight_ext') + handler = piff.InputFiles(current, base={'input': current}) + image, weight, _, _ = handler.getRawImageData(0) + np.testing.assert_array_equal(image.array, science - sky) + np.testing.assert_array_equal(weight.array, np.where(mask, 0, 5)) + + # Extensions can be a list, which can mix numeric and named forms. + for image_ext in [[0, 1], ['SCI', 'SCI2'], [0, 'SCI2']]: + current = dict(config, image_ext=image_ext) + current['weight_ext'] = [2, 'WEIGHT'] + current['badpix_ext'] = ['MASK', 3] + current['sky_ext'] = [4, 'SKY'] + current['cat_ext'] = ['CAT', 5] + handler = piff.InputFiles(current) + assert handler.nimages == 2 + for i in range(2): + image, weight, positions, _ = handler.getRawImageData(i) + np.testing.assert_array_equal(image.array, science + 10 * i - sky) + np.testing.assert_array_equal(weight.array, np.where(mask, 0, 5)) + assert positions == [galsim.PositionD(16, 16), galsim.PositionD(32, 32)] + assert handler.getWCS()[i] == galsim.PixelScale([0.4, 0.7][i]) + + # Extensions can be a GalSim-parsed type that runs over imgae_num. + # If the number of images is not apparent from the image_file_name, then input.nimages + # needs to be given in the config. + current = dict(config, nimages=2) + current['image_ext'] = {'type': 'Sequence', 'first': 0} + current['weight_ext'] = {'type': 'List_str', 'items': ['WEIGHT', 'WEIGHT']} + handler = piff.InputFiles(current) + for i in range(2): + image, weight, _, _ = handler.getRawImageData(i) + np.testing.assert_array_equal(image.array, science + 10 * i - sky) + np.testing.assert_array_equal(weight.array, np.where(mask, 0, 5)) + + # Check named extensions in compressed FITS files. + compressed_file = os.path.join('output', 'input_extensions.fits.fz') + with fits.open(file_name) as hdus: + compressed = fits.HDUList([fits.PrimaryHDU()]) + for hdu in hdus[:-1]: + compressed.append(fits.CompImageHDU(data=hdu.data, header=hdu.header, name=hdu.name)) + compressed.append(hdus[-1].copy()) + compressed.writeto(compressed_file, overwrite=True) + current = dict(config) + current.update(zip(keys, names)) + for key in ['image_file_name', 'cat_file_name', 'sky_file_name']: + current[key] = compressed_file + handler = piff.InputFiles(current) + image, weight, positions, _ = handler.getRawImageData(0) + np.testing.assert_array_equal(image.array, science - sky) + np.testing.assert_array_equal(weight.array, np.where(mask, 0, 5)) + assert positions == [galsim.PositionD(16, 16), galsim.PositionD(32, 32)] + assert handler.getWCS()[0] == galsim.PixelScale(0.4) + + @timer def test_invalid(): """Test invalid configuration elements @@ -427,6 +545,28 @@ def test_invalid(): config = { 'cat_file_name': os.path.join('input',cat_file), 'image_file_name' : 17 } np.testing.assert_raises(ValueError, piff.InputFiles, config) + # Cannot give the old *_hdu alongside *_ext, even when their values agree. + for prefix in ['image', 'weight', 'badpix', 'sky', 'cat']: + config = { + 'image_file_name': os.path.join('input', image_file), + 'cat_file_name': os.path.join('input', cat_file), + prefix + '_hdu': 0, + prefix + '_ext': 0, + } + with np.testing.assert_raises(ValueError) as e: + piff.InputFiles(config) + assert 'Cannot provide both %s_hdu and %s_ext' % (prefix, prefix) in str(e.exception) + + # Extension lists may not include empty lists or have inconsistent counts. + for selectors, nimages in [([], 1), ([0, 1], 3)]: + config = { + 'image_file_name': os.path.join('input', image_file), + 'cat_file_name': os.path.join('input', cat_file), + 'image_ext': selectors, + 'nimages': nimages, + } + np.testing.assert_raises(ValueError, piff.InputFiles, config) + # Using the wrong name (either as a glob or not) should raise an appropriate exception config = { 'dir' : 'input', 'image_file_name' : 'x'+image_file, 'cat_file_name' : cat_file } np.testing.assert_raises(ValueError, piff.InputFiles, config) @@ -454,23 +594,23 @@ def test_invalid(): config = { 'nimages' : -1, 'image_file_name' : image_files, 'cat_file_name': cat_files } np.testing.assert_raises(ValueError, piff.InputFiles, config) - # image_hdu can define nimages, but invalid values should raise. + # image_ext can define nimages, but invalid values should raise. config = { 'image_file_name' : os.path.join('input', image_file), - 'image_hdu' : [], + 'image_ext' : [], 'cat_file_name' : os.path.join('input', cat_file), } np.testing.assert_raises(ValueError, piff.InputFiles, config) config = { 'nimages' : 3, 'image_file_name' : os.path.join('input', image_file), - 'image_hdu' : [0, 1], + 'image_ext' : [0, 1], 'cat_file_name' : os.path.join('input', cat_file), } np.testing.assert_raises(ValueError, piff.InputFiles, config) config = { 'image_file_name' : 'input/test_input_image_*.fits', - 'image_hdu' : [0, 1], + 'image_ext' : [0, 1], 'cat_file_name' : os.path.join('input', cat_file), } np.testing.assert_raises(ValueError, piff.InputFiles, config) @@ -488,7 +628,7 @@ def test_invalid(): # Auxiliary file inputs should validate types and list lengths too. config = { 'image_file_name' : os.path.join('input', image_file), - 'image_hdu' : [0, 1], + 'image_ext' : [0, 1], 'cat_file_name' : os.path.join('input', cat_file), 'sky_file_name' : 'input/test_input_*_00.fits', } @@ -498,7 +638,7 @@ def test_invalid(): config = { 'image_file_name' : os.path.join('input', image_file), - 'image_hdu' : [0, 1], + 'image_ext' : [0, 1], 'cat_file_name' : os.path.join('input', cat_file), 'weight_file_name' : 'input/test_input_*_00.fits', } @@ -510,7 +650,7 @@ def test_invalid(): config = { 'image_file_name' : os.path.join('input', image_file), - 'image_hdu' : [0, 1], + 'image_ext' : [0, 1], 'cat_file_name' : os.path.join('input', cat_file), 'badpix_file_name' : 'input/test_input_*_00.fits', } @@ -1486,8 +1626,8 @@ def test_weight(): config = { 'image_file_name' : 'input/test_input_image_00.fits', 'cat_file_name' : 'input/test_input_cat_00.fits', - 'weight_hdu' : 1, - 'badpix_hdu' : 2, + 'weight_ext' : 1, + 'badpix_ext' : 2, 'sky_col' : 'sky', # Used to determine what the value of weight should be 'gain_col' : 'gain', } @@ -1549,8 +1689,8 @@ def test_weight(): config = { 'image_file_name' : 'input/test_input_image_00.fits', 'cat_file_name' : 'input/test_input_cat_00.fits', - 'weight_hdu' : 1, - 'badpix_hdu' : 5, + 'weight_ext' : 1, + 'badpix_ext' : 5, } input = piff.InputFiles(config, logger=logger) assert input.nimages == 1 @@ -1558,7 +1698,7 @@ def test_weight(): assert weight.array.shape == (1024, 1024) np.testing.assert_almost_equal(weight.array, expected_noise**-1) - config['badpix_hdu'] = 6 + config['badpix_ext'] = 6 input = piff.InputFiles(config, logger=logger) assert input.nimages == 1 _, weight, _, _ = input.getRawImageData(0) @@ -1567,24 +1707,24 @@ def test_weight(): # Various ways to get all weight values == 0 (which will emit a logger message, but isn't # an error). - config['weight_hdu'] = 1 - config['badpix_hdu'] = 7 # badpix > 0 + config['weight_ext'] = 1 + config['badpix_ext'] = 7 # badpix > 0 input = piff.InputFiles(config, logger=logger) assert input.nimages == 1 _, weight, _, _ = input.getRawImageData(0) assert weight.array.shape == (1024, 1024) np.testing.assert_almost_equal(weight.array, 0.) - config['weight_hdu'] = 3 # wt = 0 - config['badpix_hdu'] = 2 + config['weight_ext'] = 3 # wt = 0 + config['badpix_ext'] = 2 input = piff.InputFiles(config, logger=logger) assert input.nimages == 1 _, weight, _, _ = input.getRawImageData(0) assert weight.array.shape == (1024, 1024) np.testing.assert_almost_equal(weight.array, 0.) - config['weight_hdu'] = 8 # Even cols are = 0 - config['badpix_hdu'] = 9 # Odd cols are > 0 + config['weight_ext'] = 8 # Even cols are = 0 + config['badpix_ext'] = 9 # Odd cols are > 0 input = piff.InputFiles(config, logger=logger) assert input.nimages == 1 _, weight, _, _ = input.getRawImageData(0) @@ -1593,9 +1733,9 @@ def test_weight(): # Use a different file for badpix and weight. These are hdu 2,1 in this file. config['weight_file_name'] = 'input/test_input_weight_00.fits' - config['weight_hdu'] = 1 + config['weight_ext'] = 1 config['badpix_file_name'] = 'input/test_input_badpix_00.fits' - config['badpix_hdu'] = 0 + config['badpix_ext'] = 0 input = piff.InputFiles(config, logger=logger) assert input.nimages == 1 _, weight, _, _ = input.getRawImageData(0) @@ -1605,19 +1745,19 @@ def test_weight(): # Negative valued weights are invalid del config['weight_file_name'] del config['badpix_file_name'] - config['weight_hdu'] = 4 + config['weight_ext'] = 4 input = piff.InputFiles(config) with CaptureLog() as cl: _, weight, _, _ = input.getRawImageData(0, logger=cl.logger) assert 'Warning: weight map has invalid negative-valued pixels.' in cl.output # If some input values are zero, they can be treated as bad pixels with badpix_zeros - del config['weight_hdu'] - config['badpix_hdu'] = 9 + del config['weight_ext'] + config['badpix_ext'] = 9 input = piff.InputFiles(config, logger=logger) _, weight, _, _ = input.getRawImageData(0) - del config['badpix_hdu'] - config['image_hdu'] = 11 + del config['badpix_ext'] + config['image_ext'] = 11 config['badpix_zeros'] = True input = piff.InputFiles(config, logger=logger) _, weight2, _, _ = input.getRawImageData(0) @@ -1626,11 +1766,11 @@ def test_weight(): # One image file with multiple HDUs should be treated as multiple images. config = { 'image_file_name' : 'input/test_input_image_00.fits', - 'image_hdu' : [0, 10], + 'image_ext' : [0, 10], 'cat_file_name' : 'input/test_input_cat_00.fits', 'sky_file_name' : 'input/test_input_sky_00.fits.fz', 'weight_file_name' : 'input/test_input_weight_00.fits', - 'weight_hdu' : [0, 1], + 'weight_ext' : [0, 1], } input = piff.InputFiles(config, logger=logger) assert input.nimages == 2 @@ -1655,12 +1795,12 @@ def test_weight(): 'dir' : 'input', 'nimages' : 2, 'image_file_name' : 'test_input_image_00.fits', - 'image_hdu' : [0, 10], + 'image_ext' : [0, 10], 'cat_file_name' : 'test_input_cat_00.fits', 'weight_file_name' : 'test_input_weight_00.fits', - 'weight_hdu' : [0, 1], + 'weight_ext' : [0, 1], 'badpix_file_name' : 'test_input_badpix_00.fits', - 'badpix_hdu' : 0, + 'badpix_ext' : 0, } input = piff.InputFiles(config, logger=logger) assert input.nimages == 2 @@ -1714,7 +1854,7 @@ def test_lsst_weight(): config = { 'image_file_name' : 'input/test_input_image_00.fits', 'cat_file_name' : 'input/test_input_cat_00.fits', - 'weight_hdu' : 10, + 'weight_ext' : 10, 'sky' : { 'type': 'ImageHeaderValue', 'key': 'SKYLEVEL' }, 'gain' : { 'type': 'ImageHeaderValue', 'key': 'GAIN_A' }, 'invert_weight' : True, @@ -1738,7 +1878,7 @@ def test_lsst_weight(): config = { 'image_file_name' : 'input/test_input_image_00.fits', 'cat_file_name' : 'input/test_input_cat_00.fits', - 'weight_hdu' : 10, + 'weight_ext' : 10, 'sky' : { 'type': 'ImageHeaderValue', 'key': 'SKYLEVEL' }, 'invert_weight' : True, 'remove_signal_from_weight' : True, @@ -1754,7 +1894,7 @@ def test_lsst_weight(): config = { 'image_file_name' : 'input/test_input_image_00.fits', 'cat_file_name' : 'input/test_input_cat_00.fits', - 'weight_hdu' : 10, + 'weight_ext' : 10, 'gain' : { 'type': 'ImageHeaderValue', 'key': 'GAIN_A' }, 'invert_weight' : True, 'remove_signal_from_weight' : True, @@ -1814,7 +1954,7 @@ def test_stars(): 'dir' : dir, 'image_file_name' : image_file, 'cat_file_name' : cat_file, - 'weight_hdu' : 1, + 'weight_ext' : 1, 'sky_col' : 'sky', 'gain_col' : 'gain', 'use_partial' : True, @@ -2038,7 +2178,7 @@ def test_stars(): assert len(stars) == 36 # Also skip objects which are all weight=0 - config['input']['weight_hdu'] = 3 + config['input']['weight_ext'] = 3 input = piff.InputFiles(config['input'], logger=logger) stars = input.makeStars(logger=logger) stars = select.rejectStars(stars, logger=logger) @@ -2046,7 +2186,7 @@ def test_stars(): assert len(stars) == 0 # But not ones that are only partially weight=0 - config['input']['weight_hdu'] = 8 + config['input']['weight_ext'] = 8 input = piff.InputFiles(config['input'], logger=logger) stars = input.makeStars(logger=logger) stars = select.rejectStars(stars, logger=logger) @@ -2057,7 +2197,7 @@ def test_stars(): # This is a bit artificial, b/c 512 / 1024 of the pixels are masked in the test case del config['input']['x_col'] del config['input']['y_col'] - config['input']['weight_hdu'] = 8 + config['input']['weight_ext'] = 8 config['select']['max_mask_pixels'] = 513 config = galsim.config.CleanConfig(config) input = piff.InputFiles(config['input'], logger=logger) @@ -2299,7 +2439,7 @@ def test_pointing(): 'dir' : dir, 'image_file_name' : 'DECam_00241238_01.fits.fz', 'cat_file_name' : 'DECam_00241238_01_cat.fits', - 'cat_hdu' : 2, + 'cat_ext' : 2, 'x_col' : 'XWIN_IMAGE', 'y_col' : 'YWIN_IMAGE', } @@ -2320,7 +2460,7 @@ def test_pointing(): 'dir' : dir, 'image_file_name' : ['DECam_00241238_01.fits.fz', 'DECam_00241238_01.fits.fz'], 'cat_file_name' : ['DECam_00241238_01_cat.fits', 'DECam_00241238_01_cat.fits'], - 'cat_hdu' : 2, + 'cat_ext' : 2, 'x_col' : 'XWIN_IMAGE', 'y_col' : 'YWIN_IMAGE', } @@ -2419,8 +2559,8 @@ def test_sky(): for i in range(len(stars)): np.testing.assert_allclose(stars[i].image.array, raw_stars[i].image.array - sky32) - # Can provide an explicit hdu, although the default works fine in this case. - config['sky_hdu'] = 1 + # Can provide an explicit extension, although the default works fine in this case. + config['sky_ext'] = 1 input = piff.InputFiles(config, logger=logger) image, _, _, extra_props = input.getRawImageData(0) stars = input.makeStars(logger=logger) @@ -3062,6 +3202,7 @@ def test_input_bandpass(): if __name__ == '__main__': setup() test_basic() + test_extensions() test_invalid() test_cols() test_boolarray() diff --git a/tests/test_knn_interp.py b/tests/test_knn_interp.py index 32785af3..32db85a0 100644 --- a/tests/test_knn_interp.py +++ b/tests/test_knn_interp.py @@ -103,10 +103,10 @@ def test_config(): 'image_file_name' : 'input/DECam_00241238_01.fits.fz', 'cat_file_name' : 'input/DECam_00241238_01_psfcat_tb_maxmag_17.0_magcut_3.0_findstars.fits', # What hdu is everything in? - 'image_hdu': 1, - 'badpix_hdu': 2, - 'weight_hdu': 3, - 'cat_hdu': 2, + 'image_ext': 1, + 'badpix_ext': 2, + 'weight_ext': 3, + 'cat_ext': 2, # What columns in the catalog have things we need? 'x_col': 'XWIN_IMAGE', diff --git a/tests/test_optics.py b/tests/test_optics.py index 263cdcdd..4ba911e7 100644 --- a/tests/test_optics.py +++ b/tests/test_optics.py @@ -153,7 +153,7 @@ def test_draw(): 'dir' : 'input', 'image_file_name' : 'DECam_00241238_01.fits.fz', 'cat_file_name' : 'DECam_00241238_01_cat.fits', - 'cat_hdu' : 2, + 'cat_ext' : 2, 'x_col' : 'XWIN_IMAGE', 'y_col' : 'YWIN_IMAGE', } diff --git a/tests/test_pixel.py b/tests/test_pixel.py index f1551dce..7ce0dfbf 100644 --- a/tests/test_pixel.py +++ b/tests/test_pixel.py @@ -1131,11 +1131,11 @@ def test_des_image(): 'input' : { 'nstars': nstars, 'image_file_name' : image_file, - 'image_hdu' : 1, - 'weight_hdu' : 3, - 'badpix_hdu' : 2, + 'image_ext' : 1, + 'weight_ext' : 3, + 'badpix_ext' : 2, 'cat_file_name' : cat_file, - 'cat_hdu' : 2, + 'cat_ext' : 2, 'x_col' : 'XWIN_IMAGE', 'y_col' : 'YWIN_IMAGE', 'sky_col' : 'BACKGROUND', @@ -1379,11 +1379,11 @@ def test_des2(): config = { 'input' : { 'image_file_name' : image_file, - 'image_hdu' : 1, - 'badpix_hdu' : 2, - 'weight_hdu' : 3, + 'image_ext' : 1, + 'badpix_ext' : 2, + 'weight_ext' : 3, 'cat_file_name' : cat_file, - 'cat_hdu' : 1, + 'cat_ext' : 1, 'x_col' : 'x', 'y_col' : 'y', 'sky_col' : 'sky', diff --git a/tests/test_simple.py b/tests/test_simple.py index a04dfb1f..f23c3a04 100644 --- a/tests/test_simple.py +++ b/tests/test_simple.py @@ -1196,7 +1196,7 @@ def test_depr_select(): 'dir' : dir, 'image_file_name' : image_file, 'cat_file_name' : cat_file, - 'weight_hdu' : 1, + 'weight_ext' : 1, 'sky_col' : 'sky', 'gain_col' : 'gain', 'use_partial' : True, diff --git a/tests/test_sizemag.py b/tests/test_sizemag.py index 0e4718f8..1b86fbdb 100644 --- a/tests/test_sizemag.py +++ b/tests/test_sizemag.py @@ -336,12 +336,12 @@ def test_sizemag(): config['input'] = { 'dir': 'input', 'image_file_name': 'DECam_00241238_01.fits.fz', - 'image_hdu': 1, - 'badpix_hdu': 2, - 'weight_hdu': 3, + 'image_ext': 1, + 'badpix_ext': 2, + 'weight_ext': 3, 'cat_file_name' : 'DECam_00241238_01_psfcat_tb_maxmag_17.0_magcut_3.0_findstars.fits', - 'cat_hdu' : 2, + 'cat_ext' : 2, 'x_col' : 'XWIN_IMAGE', 'y_col' : 'YWIN_IMAGE', 'sky_col' : 'BACKGROUND', diff --git a/tests/test_stats.py b/tests/test_stats.py index da1d6184..d3122fab 100644 --- a/tests/test_stats.py +++ b/tests/test_stats.py @@ -850,11 +850,11 @@ def test_bad_hsm(): 'input' : { 'nstars': 8, 'image_file_name' : image_file, - 'image_hdu' : 1, - 'weight_hdu' : 3, - 'badpix_hdu' : 2, + 'image_ext' : 1, + 'weight_ext' : 3, + 'badpix_ext' : 2, 'cat_file_name' : cat_file, - 'cat_hdu' : 2, + 'cat_ext' : 2, # These next two are intentionally backwards. The PixelGrid will find some kind # of solution, but it will be complex garbage, and hsm will fail for them. 'x_col' : 'YWIN_IMAGE', @@ -1442,9 +1442,9 @@ def test_property_cols(): 'input' : { 'nstars': nstars, 'image_file_name' : image_file, - 'image_hdu' : 1, - 'weight_hdu' : 3, - 'badpix_hdu' : 2, + 'image_ext' : 1, + 'weight_ext' : 3, + 'badpix_ext' : 2, 'cat_file_name' : cat_file, 'x_col' : 'XWIN_IMAGE', 'y_col' : 'YWIN_IMAGE', From c2feaa4b43e906109ce62161b7aa343c0eb389b3 Mon Sep 17 00:00:00 2001 From: Mike Jarvis Date: Mon, 2 Nov 2026 11:52:57 -0500 Subject: [PATCH 04/18] Add option to let SEP calculate a background. Also clean up sky handling a bit. --- piff/input.py | 201 +++++++++++++++++++++++-------------------- tests/test_input.py | 180 +++++++++++++++++++++++++++++++------- tests/test_pixel.py | 2 +- tests/test_simple.py | 4 +- 4 files changed, 259 insertions(+), 128 deletions(-) diff --git a/piff/input.py b/piff/input.py index 164d3e69..9d7e927f 100644 --- a/piff/input.py +++ b/piff/input.py @@ -238,65 +238,64 @@ class InputFiles(Input): this gives the name of the file to use. [default: None] :badpix_zeros: Whether to treat all zeros in the input image as bad pixels. [default: False] - :sky_file_name: A file containing a sky background image to subtract. [default: None] - :sky_ext: The extension number or name to use in the sky file. [default: None, - which means use the file's default image extension] - - :cat_ext: The extension number or name in FITS catalog files. Ignored for parquet - catalogs. [default: None, which means use the first table extension] - :x_col: The name of the X column in the input catalogs. [default: 'x'] - :y_col: The name of the Y column in the input catalogs. [default: 'y'] - :ra_col: (Alternative to x_col, y_col) The name of a right ascension column in - the input catalogs. Will use the WCS to find (x,y) [default: None] - :dec_col: (Alternative to x_col, y_col) The name of a declination column in - the input catalogs. Will use the WCS to find (x,y) [default: None] - :flag_col: The name of a flag column in the input catalogs. [default: None] - By default, this will skip any objects with flag != 0, but see + :sky_file_name: a file containing a sky background image to subtract. [default: none] + :sky_ext: the extension number or name to use in the sky file, or in the image + file if sky_file_name is omitted. [default: none, which means use the + sky file's default image extension] + + :cat_ext: the extension number or name in fits catalog files. ignored for parquet + catalogs. [default: none, which means use the first table extension] + :x_col: the name of the x column in the input catalogs. [default: 'x'] + :y_col: the name of the y column in the input catalogs. [default: 'y'] + :ra_col: (alternative to x_col, y_col) the name of a right ascension column in + the input catalogs. will use the wcs to find (x,y) [default: none] + :dec_col: (alternative to x_col, y_col) the name of a declination column in + the input catalogs. will use the wcs to find (x,y) [default: none] + :flag_col: the name of a flag column in the input catalogs. [default: none] + by default, this will skip any objects with flag != 0, but see skip_flag and use_flag for other possible meanings for how the flag column can be used to select stars. - :skip_flag: The flag indicating which items to not use. [default: -1] - Items with flag & skip_flag != 0 will be skipped. - :use_flag: The flag indicating which items to use. [default: None] - Items with flag & use_flag == 0 will be skipped. - :property_cols: A list of column names of star properties (e.g. star colors). - [default: None] - :properties: A dict of constant star properties to attach to every star from each - input image. The keys are property names. Values are parsed using - the GalSim config parser for each ``image_num``. Plain strings that + :skip_flag: the flag indicating which items to not use. [default: -1] + items with flag & skip_flag != 0 will be skipped. + :use_flag: the flag indicating which items to use. [default: none] + items with flag & use_flag == 0 will be skipped. + :property_cols: a list of column names of star properties (e.g. star colors). + [default: none] + :properties: a dict of constant star properties to attach to every star from each + input image. the keys are property names. values are parsed using + the galsim config parser for each ``image_num``. plain strings that begin with ``$`` or ``@`` are treated as config expressions; other - strings are left as literal strings. The explicit ``type``/``value`` - dict form is also supported. [default: None] + strings are left as literal strings. the explicit ``type``/``value`` + dict form is also supported. [default: none] - :sed_col: The name of a column with per-star SED selectors. If ``sed_file_name`` - is not provided, selectors are interpreted as SED file names. If + :sed_col: the name of a column with per-star sed selectors. if ``sed_file_name`` + is not provided, selectors are interpreted as sed file names. if ``sed_file_name`` is provided, selectors are treated as keys in the - SED mapping. [default: None] - :sed_file_name: A single SED file name to use for all stars (if ``sed_col`` is - not provided), or a dict / YAML file mapping ``sed_col`` selectors to - SED file names. [default: None] - :sed_wave_type: Wavelength unit for SED files (e.g. ``nm``, ``Angstrom``). - [required if sed_col or sed_file_name is not None] - :sed_flux_type: Flux convention for SED files (e.g. ``flambda``, ``fnu``, - ``fphotons`` or units parseable by astropy.Unit). - [required if sed_col or sed_file_name is not None] - :sed_wave_key: FITS-table column name to use for wavelength when loading - SEDs from FITS tables. [default: ``WAVE``] - :sed_flux_key: FITS-table column name to use for flux when loading SEDs - from FITS tables. [default: ``FLUX``] - :sed_tol: Relative tolerance for reducing the number of samples of input SEDs - based on the calculated flux over the given bandpass. The SEDs are each - reduced on first access, and the reduced SED object is then shared - by all matching stars. Values <= 0 disable this step. [default: 0] + sed mapping. [default: none] + :sed_file_name: a single sed file name to use for all stars (if ``sed_col`` is + not provided), or a dict / yaml file mapping ``sed_col`` selectors to + sed file names. [default: none] + :sed_wave_type: wavelength unit for sed files (e.g. ``nm``, ``angstrom``). + [required if sed_col or sed_file_name is not none] + :sed_flux_type: flux convention for sed files (e.g. ``flambda``, ``fnu``, + ``fphotons`` or units parseable by astropy.unit). + [required if sed_col or sed_file_name is not none] + :sed_wave_key: fits-table column name to use for wavelength when loading + seds from fits tables. [default: ``wave``] + :sed_flux_key: fits-table column name to use for flux when loading seds + from fits tables. [default: ``flux``] + :sed_tol: relative tolerance for reducing the number of samples of input seds + based on the calculated flux over the given bandpass. the seds are each + reduced on first access, and the reduced sed object is then shared + by all matching stars. values <= 0 disable this step. [default: 0] :sed_max_samples: - Maximum number of samples to keep in the effective SED. If set, use a + maximum number of samples to keep in the effective sed. if set, use a greedy knot-selection algorithm to choose up to this many samples, then refit their values for the best piecewise-linear approximation of the - original effective SED. Values <= 0 disable this step. [default: 0] - :bandpass: GalSim bandpass config dict describing the observing bandpass for the - input image(s). Required when using ``sed_col`` or ``sed_file_name``. - [default: None] - - .. note:: + original effective sed. values <= 0 disable this step. [default: 0] + :bandpass: galsim bandpass config dict describing the observing bandpass for the + input image(s). required when using ``sed_col`` or ``sed_file_name``. + [default: none] For chromatic PSF fitting, you must define the SED of each star in one of the following ways: @@ -369,14 +368,19 @@ class InputFiles(Input): :sky_col: The name of a column with sky values. [default: None] :gain_col: The name of a column with gain values. [default: None] :sky: The sky level to subtract from the image values. [default: None] - Note: It is an error to specify both sky and sky_col. If both are None, - no sky level will be subtracted off. + Specify only one sky source: sky, sky_col, or sky_file_name/sky_ext. + If none are provided, the input image will be assumed to have already + been sky subtracted. .. note:: - The special value sky = 'median' means to compute the median of - the image and use that as the sky level. Any other string value - (rather than a float) indicates to get the value from the FITS - header. + + There are two special values allowed for this parameter: + * ``sky: median`` computes the median of the image and uses that + as the (constant) sky level. + * ``sky: sep`` uses SEP's full spatial background image, with its + default background settings. It requires the optional ``sep`` + package to be installed. + Both estimators exclude pixels with zero weight. :gain: The gain to use for adding Poisson noise to the weight map. [default: None] It is an error for both gain and gain_col to be specified. @@ -400,13 +404,6 @@ class InputFiles(Input): WCS. It should be defined using the same style as a wcs object in GalSim config files. [defulat: None] - .. note:: - - Some values that are nominally floats may be given as FITS header key words instead. - These include sky, gain, and satur. If these are strings (other than sky=median, which - is special), then they should be a valid key word in the FITS header giving the value - to use. - The above values are parsed separately for each input image/catalog. In addition, there are a couple other parameters that are just parsed once: @@ -487,6 +484,12 @@ def __init__(self, config, base=None, logger=None): config[new] = config[old] ignore.append(old) + sky_sources = sum(['sky' in config, 'sky_col' in config, + 'sky_file_name' in config or 'sky_ext' in config]) + if sky_sources > 1: + raise ValueError("Specify only one sky source: sky, sky_col, or " + "sky_file_name/sky_ext.") + # In GalSim, the base dict holds additional parameters that may be of use. # For now, add index_kex, as this will be the only thing we index anything on. base['index_key'] = 'image_num' @@ -706,6 +709,8 @@ def __init__(self, config, base=None, logger=None): badpix_zeros = params.get('badpix_zeros', False) sky_file_name = params.get('sky_file_name', None) sky_ext = params.get('sky_ext', None) + if sky_file_name is None and sky_ext is not None: + sky_file_name = image_file_name self.image_file_name.append(image_file_name) self.image_kwargs.append({ 'image_file_name' : image_file_name, @@ -754,8 +759,6 @@ def __init__(self, config, base=None, logger=None): gain_col = params.get('gain_col', None) nstars = params.get('nstars', None) - if sky_col is not None and 'sky' in config: - raise ValueError("Cannot provide both sky_col and sky.") if gain_col is not None and 'gain' in config: raise ValueError("Cannot provide both gain_col and gain.") @@ -883,8 +886,8 @@ def _getRawImageData(cls, image_kwargs, cat_kwargs, wcs, logger=logger, image=image, **cat_kwargs) if remove_signal_from_weight: - # Subtract off the mean sky, since this isn't part of the "signal" we want to - # remove from the weights. + # Subtract the mean catalog sky from the signal used for variance removal. + # Image-level backgrounds have already been subtracted by readImage. if 'sky' in extra_props: signal = image - np.mean(extra_props['sky']) else: @@ -1021,19 +1024,18 @@ def _removeSignalFromWeight(image, weight, gain=None): :returns: newweight, gain """ - signal = image.array - variance = 1./weight.array - - use = (weight.array != 0.) & np.isfinite(signal) + use = (weight.array != 0.) & np.isfinite(image.array) + signal = image.array[use] + variance = 1./weight.array[use] if gain is None: - fit = np.polyfit(signal[use].flatten(), variance[use].flatten(), deg=1) + fit = np.polyfit(signal, variance, deg=1) gain = 1./fit[0] # fit is [ 1/gain, sky_var ] - variance[use] -= signal[use] / gain + variance -= signal / gain newweight = weight.copy() - newweight.array[use] = 1. / variance[use] + newweight.array[use] = 1. / variance return newweight, gain @staticmethod @@ -1131,13 +1133,6 @@ def readImage(cls, image_file_name, image_ext, weight_file_name, weight_ext, if badpix_zeros: weight.array[image.array == 0] = 0 - # If requested, subtract a sky image - if sky_file_name is not None: - ext_str = " from extension %s"%(sky_ext) if sky_ext is not None else "" - logger.verbose("Reading sky image %s.", sky_file_name + ext_str) - sky = cls._read_image(sky_file_name, sky_ext, read_header=False) - image -= sky - # If requested, set wt=0 for any bad pixels if badpix_file_name is not None or badpix_ext is not None: badpix_file_name = badpix_file_name or image_file_name @@ -1162,13 +1157,39 @@ def readImage(cls, image_file_name, image_ext, weight_file_name, weight_ext, image_file_name) weight.array[badpix.array != 0] = 0 - if sky == 'median': - ok = weight.array != 0 - sky = np.median(image.array[ok]) - image.array[ok] -= sky + sky_image = cls._read_sky(image, weight, sky, sky_file_name, sky_ext, logger) + if sky_image is not None: + image -= sky_image return image, weight + @classmethod + def _read_sky(cls, image, weight, sky, sky_file_name, sky_ext, logger): + """Read or estimate the image-level background after assembling the pixel mask. + + Returns a sky image for a file or SEP estimate, or a scalar for a configured value + or image median. Returns None when no image-level sky is specified. Catalog sky + values are applied later to individual stars. Subclasses can reuse the returned + background when constructing background-dependent weight maps. + """ + if sky_file_name is not None: + ext_str = " from extension %s" % sky_ext if sky_ext is not None else "" + logger.verbose("Reading sky image %s.", sky_file_name + ext_str) + return cls._read_image(sky_file_name, sky_ext, read_header=False) + elif sky == 'median': + return np.median(image.array[weight.array != 0]) + elif sky == 'sep': + import sep + # SEP requires contiguous arrays with native byte order; FITS arrays may be big-endian. + data = np.ascontiguousarray(image.array, dtype=image.array.dtype.newbyteorder('=')) + background = sep.Background(data, mask=weight.array == 0) + return galsim.Image(background.back(), bounds=image.bounds, wcs=image.wcs) + elif sky is not None: + # Float value or a (now deprecated) image header key. + return cls._handle_depr_image_value(sky, image.header, 'sky', logger) + else: + return None + @staticmethod def _flag_select(col, flag): if len(col.shape) == 1: @@ -1294,10 +1315,6 @@ def readStarCatalog(cls, cat_file_name, cat_ext, x_col, y_col, logger.info("Reading input catalog %s.",cat_file_name) cat = cls._read_cat(cat_file_name, cat_ext) - sky = None - if 'sky' in config: - sky = galsim.config.ParseValue(config, 'sky', base, (float, str))[0] - gain = None if 'gain' in config: gain = galsim.config.ParseValue(config, 'gain', base, (float, str))[0] @@ -1458,10 +1475,6 @@ def safe_to_image(wcs, ra, dec): if sky_col not in cat.dtype.names: raise ValueError("sky_col = %s is not a column in %s"%(sky_col,cat_file_name)) extra_props['sky'] = np.float32(cat[sky_col]) - elif sky is not None and sky != 'median': - sky = galsim.config.ParseValue(config, 'sky', base, None)[0] - sky = cls._handle_depr_image_value(sky, image.header, 'sky', logger) - extra_props['sky'] = np.array([sky]*len(cat), dtype=np.float32) # Make the list of gain values: # TODO: SV and Y1 DES images have two gain values, GAINA, GAINB. It would be nice if we diff --git a/tests/test_input.py b/tests/test_input.py index 7526a9f1..6d9fc501 100644 --- a/tests/test_input.py +++ b/tests/test_input.py @@ -453,6 +453,14 @@ def test_extensions(): assert positions == [galsim.PositionD(16, 16), galsim.PositionD(32, 32)] assert handler.getWCS()[0] == galsim.PixelScale(0.4) + # A sky extension without a filename selects the sky plane in the science file. + current = dict(config) + current.pop('sky_file_name') + handler = piff.InputFiles(current) + image, weight, _, _ = handler.getRawImageData(0) + np.testing.assert_array_equal(image.array, science - sky) + np.testing.assert_array_equal(weight.array, np.where(mask, 0, 5)) + # The old names for *_ext was *_hdu. These are still allowed, but deprecated. for key in keys: current = dict(config) @@ -744,7 +752,7 @@ def test_cols(): } input = piff.InputFiles(config, logger=logger) assert input.nimages == 1 - _, _, image_pos, props = input.getRawImageData(0) + raw_image, _, image_pos, props = input.getRawImageData(0) sky_list = props['sky'] gain_list = props['gain'] assert len(image_pos) == 100 @@ -763,17 +771,16 @@ def test_cols(): 'gain' : gain, } input = piff.InputFiles(config, logger=logger) - _, _, image_pos, props = input.getRawImageData(0) - sky_list = props['sky'] + image, _, image_pos, props = input.getRawImageData(0) + assert 'sky' not in props gain_list = props['gain'] assert len(image_pos) == 100 - assert len(sky_list) == 100 assert len(gain_list) == 100 # These aren't precisely equal because we go through a str value, which truncates it. # We could hack this to keep it exact, but it's probably not worth it and it's easier to # enable both str and float by reading it as str and then trying the float conversion to see # it if works. Anyway, that's why this is only decimal=9. - np.testing.assert_almost_equal(sky_list, sky, decimal=9) + np.testing.assert_allclose(image.array, raw_image.array - sky) np.testing.assert_almost_equal(gain_list, gain, decimal=9) # sky and gain can be taken from the fits header using the ImageHeaderValue type. @@ -785,13 +792,12 @@ def test_cols(): 'gain' : { 'type': 'ImageHeaderValue', 'key': 'GAIN_A' }, } input = piff.InputFiles(config, logger=logger) - _, _, image_pos, props = input.getRawImageData(0) - sky_list = props['sky'] + image, _, image_pos, props = input.getRawImageData(0) + assert 'sky' not in props gain_list = props['gain'] assert len(image_pos) == 100 - assert len(sky_list) == 100 assert len(gain_list) == 100 - np.testing.assert_almost_equal(sky_list, sky) + np.testing.assert_allclose(image.array, raw_image.array - sky) np.testing.assert_almost_equal(gain_list, gain) # The old way to do this was to treat strings as header keys. This still works, @@ -806,15 +812,14 @@ def test_cols(): } input = piff.InputFiles(config) with CaptureLog() as cl: - _, _, image_pos, props = input.getRawImageData(0, logger=cl.logger) + image, _, image_pos, props = input.getRawImageData(0, logger=cl.logger) assert "Using a bare FITS header key for sky is deprecated" in cl.output assert "Using a bare FITS header key for gain is deprecated" in cl.output - sky_list = props['sky'] + assert 'sky' not in props gain_list = props['gain'] assert len(image_pos) == 100 - assert len(sky_list) == 100 assert len(gain_list) == 100 - np.testing.assert_almost_equal(sky_list, sky) + np.testing.assert_allclose(image.array, raw_image.array - sky) np.testing.assert_almost_equal(gain_list, gain) # These can also use other parseable config values. @@ -827,12 +832,12 @@ def test_cols(): 'trust_pos' : {'type': 'Eval', 'str': 'True'}, } input = piff.InputFiles(config, logger=logger) - _, _, image_pos, props = input.getRawImageData(0) - sky_list = props['sky'] + image, _, image_pos, props = input.getRawImageData(0) + assert 'sky' not in props gain_list = props['gain'] trust_pos = props['trust_pos'] assert len(image_pos) == 100 - np.testing.assert_almost_equal(sky_list, sky) + np.testing.assert_allclose(image.array, raw_image.array - sky) np.testing.assert_almost_equal(gain_list, gain) np.testing.assert_array_equal(trust_pos, [True] * 100) @@ -859,10 +864,12 @@ def test_cols(): base = {'input': multi_config, 'first_value': 10.} multi_input = piff.InputFiles(multi_config, base=base, logger=logger) for image_num, expected in enumerate([10., 20.]): - _, weight, image_pos, props = multi_input.getRawImageData(image_num) + image, weight, image_pos, props = multi_input.getRawImageData(image_num) assert len(image_pos) == 100 np.testing.assert_allclose(weight.array, 1. / expected) - for key in ['sky', 'gain', 'satur']: + np.testing.assert_allclose(image.array, raw_image.array - expected) + assert 'sky' not in props + for key in ['gain', 'satur']: np.testing.assert_allclose(props[key], expected) # Eval references must also refresh their targets when moving to another image. @@ -871,9 +878,11 @@ def test_cols(): multi_config[key] = '$@image_value' multi_input = piff.InputFiles(multi_config, base=base, logger=logger) for image_num, expected in enumerate([10., 20.]): - _, weight, _, props = multi_input.getRawImageData(image_num) + image, weight, _, props = multi_input.getRawImageData(image_num) np.testing.assert_allclose(weight.array, 1. / expected) - for key in ['sky', 'gain', 'satur']: + np.testing.assert_allclose(image.array, raw_image.array - expected) + assert 'sky' not in props + for key in ['gain', 'satur']: np.testing.assert_allclose(props[key], expected) # gain can also be given explicitly as an ImageHeaderValue. @@ -1091,14 +1100,14 @@ def test_cols(): 'trust_pos' : '$@image_num == 1', } input = piff.InputFiles(config, logger=logger) - _, weight0, image_pos0, props0 = input.getRawImageData(0) - _, weight1, image_pos1, props1 = input.getRawImageData(1) + image0, weight0, image_pos0, props0 = input.getRawImageData(0) + image1, weight1, image_pos1, props1 = input.getRawImageData(1) assert len(image_pos0) == 100 assert len(image_pos1) == 100 np.testing.assert_allclose(weight0.array[weight0.array != 0], [1.] * np.count_nonzero(weight0.array)) np.testing.assert_allclose(weight1.array[weight1.array != 0], [0.5] * np.count_nonzero(weight1.array)) - np.testing.assert_array_equal(props0['sky'], [100.] * 100) - np.testing.assert_array_equal(props1['sky'], [101.] * 100) + np.testing.assert_allclose(image0.array, fitsio.read('input/test_input_image_00.fits') - 100) + np.testing.assert_allclose(image1.array, fitsio.read('input/test_input_image_01.fits') - 101) np.testing.assert_array_equal(props0['trust_pos'], [False] * 100) np.testing.assert_array_equal(props1['trust_pos'], [True] * 100) @@ -1143,8 +1152,22 @@ def test_cols(): np.testing.assert_raises(ValueError, piff.InputFiles, dict(flag_col='flag', use_flag='xx', **base_config)) - # Can't give duplicate sky, gain - np.testing.assert_raises(ValueError, piff.InputFiles, dict(sky_col='sky', sky=3, **base_config)) + # Sky comes from one source; a sky filename and extension together specify one source. + sky_options = { + 'sky': 3, + 'sky_col': 'sky', + 'sky_file_name': 'input/test_input_sky_00.fits.fz', + 'sky_ext': 1, + } + for first, second in [('sky', 'sky_col'), ('sky', 'sky_file_name'), + ('sky_col', 'sky_file_name'), ('sky', 'sky_ext'), + ('sky_col', 'sky_ext')]: + config = dict(base_config) + config[first] = sky_options[first] + config[second] = sky_options[second] + np.testing.assert_raises(ValueError, piff.InputFiles, config) + + # Gain can likewise come from either a configured value or a catalog column. np.testing.assert_raises(ValueError, piff.InputFiles, dict(gain_col='gain', gain=3, **base_config)) # Invalid header keys @@ -1867,7 +1890,7 @@ def test_lsst_weight(): assert image.array.shape == (1024, 1024) assert weight.array.shape == (1024, 1024) gain = props['gain'][0] - sky = props['sky'][0] + sky = fitsio.read_header('input/test_input_image_00.fits')['SKYLEVEL'] read_noise = 10 expected_noise = sky / gain + read_noise**2 / gain**2 print('expected noise = ',expected_noise) @@ -2518,11 +2541,17 @@ def test_sky(): input = piff.InputFiles(config, logger=logger) image, _, _, extra_props = input.getRawImageData(0) stars = input.makeStars(logger=logger) - np.testing.assert_allclose(image.array, raw_image.array) + np.testing.assert_allclose(image.array, raw_image.array - 7) + assert 'sky' not in extra_props for i in range(len(stars)): - assert extra_props['sky'][i] == 7 + assert 'sky' not in stars[i].data.properties np.testing.assert_allclose(stars[i].image.array, raw_stars[i].image.array - 7) + # Make sure reloading images doesn't subtract the background a second time. + loaded = input.load_images(stars) + for original, restored in zip(stars, loaded): + np.testing.assert_array_equal(restored.image.array, original.image.array) + # If sky is given as a string, it is a header key word. config = { 'image_file_name' : image_file, @@ -2533,11 +2562,10 @@ def test_sky(): input = piff.InputFiles(config, logger=logger) image, _, _, extra_props = input.getRawImageData(0) stars = input.makeStars(logger=logger) - np.testing.assert_allclose(image.array, raw_image.array) with fitsio.FITS(image_file, 'r') as f: sky = np.float32(f[0].read_header()['SKYLEVEL']) + np.testing.assert_allclose(image.array, raw_image.array - sky) for i in range(len(stars)): - assert extra_props['sky'][i] == sky np.testing.assert_allclose(stars[i].image.array, raw_stars[i].image.array - sky) # If sky_file_name is given then it is an image file to subtract @@ -2628,6 +2656,94 @@ def test_sky(): piff.InputFiles(config, logger=logger) +@timer +def test_sep_sky(): + """Test sky=sep option to let SExtractor determine the background image. + """ + # Use a sloping background with several stars and galaxies and detector noise. + sep = pytest.importorskip('sep') + rng = galsim.BaseDeviate(1234) + y, x = np.mgrid[:384, :384] + background = 100 + 0.05 * x + 0.03 * y + science_image = galsim.ImageD(384, 384, scale=0.2) + science_image.array[:] = background + psf = galsim.Moffat(beta=3.5, fwhm=0.7).shear(g1=0.03, g2=-0.02) + positions = [(71.3, 71.8), (155.4, 101.2), (289.1, 82.6), + (101.8, 260.2), (245.6, 291.3), (312.2, 225.6)] + profiles = [psf.withFlux(flux) for flux in [2000, 5000, 8000, 3000]] + for flux, radius in [(12000, 0.5), (4000, 0.3)]: + galaxy = galsim.Exponential(half_light_radius=radius, flux=flux).shear(g1=0.2, g2=0.1) + profiles.append(galsim.Convolve(psf, galaxy)) + for profile, (px, py) in zip(profiles, positions): + bounds = galsim.BoundsI(int(px) - 24, int(px) + 24, int(py) - 24, int(py) + 24) + profile.drawImage(image=science_image[bounds], center=galsim.PositionD(px, py), + add_to_image=True) + gain = 4.0 + read_variance = 25.0 + science_image.addNoise(galsim.CCDNoise(rng, gain=gain, + read_noise=gain * np.sqrt(read_variance))) + science = science_image.array + variance = read_variance + science / gain + mask = np.zeros_like(science, dtype=np.int16) + mask[80:96, 80:96] = 1 + science[mask != 0] = 0 + science[12, 12] = 0 + masked = (mask != 0) | (science == 0) + file_name = os.path.join('output', 'sep_sky.fits') + cat_name = os.path.join('output', 'sep_sky_cat.fits') + sky_name = os.path.join('output', 'sep_sky_background.fits') + with fitsio.FITS(file_name, 'rw', clobber=True) as f: + f.write(science) + f.write(1.0 / variance) + f.write(mask) + fitsio.write(cat_name, np.array(positions, dtype=[('x', float), ('y', float)]), + clobber=True) + config = { + 'image_file_name': file_name, + 'cat_file_name': cat_name, + 'weight_ext': 1, + 'badpix_ext': 2, + 'badpix_zeros': True, + 'sky': 'sep', + 'gain': gain, + 'remove_signal_from_weight': True, + 'stamp_size': 24, + } + + # SEP recovers the background to 1% despite sources and noise; Piff subtracts its full image. + estimated = sep.Background(science, mask=masked).back() + np.testing.assert_allclose(estimated[64:-64, 64:-64], background[64:-64, 64:-64], rtol=0.01) + handler = piff.InputFiles(config) + image, weight, _, props = handler.getRawImageData(0) + np.testing.assert_allclose(image.array, science - estimated) + assert 'sky' not in props + assert np.ptp(estimated) > 10 + + # Removing source variance retains the spatial background variance and all masked weights. + expected_weight = 1.0 / (read_variance + estimated / gain) + expected_weight[masked] = 0 + np.testing.assert_allclose(weight.array, expected_weight) + + # A supplied sky image produces the same image and weights as the SEP-derived image. + fitsio.write(sky_name, estimated, clobber=True) + file_config = dict(config) + file_config.pop('sky') + file_config['sky_file_name'] = sky_name + file_handler = piff.InputFiles(file_config) + file_image, file_weight, _, _ = file_handler.getRawImageData(0) + np.testing.assert_allclose(file_image.array, image.array) + np.testing.assert_allclose(file_weight.array, weight.array) + + # Stamp creation and reloading subtract the same background exactly once. + stars = handler.makeStars() + assert len(stars) == len(positions) + loaded = handler.load_images(stars) + for star, restored in zip(stars, loaded): + np.testing.assert_allclose(star.image.array, image[star.image.bounds].array) + np.testing.assert_allclose(star.weight.array, weight[star.weight.bounds].array) + np.testing.assert_array_equal(restored.image.array, star.image.array) + np.testing.assert_array_equal(restored.weight.array, star.weight.array) + @timer def test_sed_col(): """Test per-star SED loading from a catalog filename column (input.sed_col). @@ -3212,6 +3328,8 @@ def test_input_bandpass(): test_stars() test_select_min_sep() test_pointing() + test_sky() + test_sep_sky() test_sed_col() test_single_sed() test_sed_star_io() diff --git a/tests/test_pixel.py b/tests/test_pixel.py index 7ce0dfbf..c58f5d89 100644 --- a/tests/test_pixel.py +++ b/tests/test_pixel.py @@ -944,7 +944,7 @@ def test_single_image(): # Check image assert input.nimages == 1 image1, _, image_pos, _ = input.getRawImageData(0) - np.testing.assert_equal(image1.array, image.array) + np.testing.assert_equal(image1.array, image.array - sky_level) # Check catalog assert len(image_pos) == len(x_list) diff --git a/tests/test_simple.py b/tests/test_simple.py index f23c3a04..871ec11b 100644 --- a/tests/test_simple.py +++ b/tests/test_simple.py @@ -998,9 +998,9 @@ def test_load_images(): for star in psf2.stars: np.testing.assert_array_equal(star.image.array, 0.) - # First the old API: + # The old API needs an explicit sky because global sky is not stored on each star. with CaptureLog() as cl: - loaded_stars = piff.Star.load_images(psf2.stars, image_file, logger=cl.logger) + loaded_stars = piff.Star.load_images(psf2.stars, image_file, sky=sky, logger=cl.logger) assert "WARNING: The Star.load_images function is deprecated." in cl.output for star, orig in zip(loaded_stars, psf.stars): np.testing.assert_array_equal(star.image.array, orig.image.array) From 7e5f73d964016bfad834f6e96e2afa7406054c06 Mon Sep 17 00:00:00 2001 From: Mike Jarvis Date: Mon, 2 Nov 2026 14:42:26 -0500 Subject: [PATCH 05/18] Add option to provide gain_image --- piff/des/decaminfo.py | 11 +- piff/input.py | 138 +++++++++++++--- piff/star.py | 39 +++-- tests/test_input.py | 354 +++++++++++++++++++++++++++++++----------- tests/test_pixel.py | 7 +- tests/test_simple.py | 4 +- tests/test_star.py | 28 ++++ 7 files changed, 438 insertions(+), 143 deletions(-) diff --git a/piff/des/decaminfo.py b/piff/des/decaminfo.py index faf13fc9..ddc86824 100644 --- a/piff/des/decaminfo.py +++ b/piff/des/decaminfo.py @@ -16,7 +16,7 @@ .. module:: decaminfo """ -from ..star import Star, StarFit, StarData +from ..star import Star import numpy as np class DECamInfo(object): @@ -230,14 +230,7 @@ def pixel_to_focal_stardata(self, stardata): properties = stardata.properties.copy() properties['focal_x'] = focal_x[0] properties['focal_y'] = focal_y[0] - for key in ['x', 'y', 'u', 'v']: - # Get rid of keys that constructor doesn't want to see: - properties.pop(key,None) - return StarData(image=stardata.image, - image_pos=stardata.image_pos, - weight=stardata.weight, - pointing=stardata.pointing, - properties=properties) + return stardata.withNew(properties=properties) def pixel_to_focal(self, star): """Take star and add focal plane position to properties diff --git a/piff/input.py b/piff/input.py index 9d7e927f..bb1ecca4 100644 --- a/piff/input.py +++ b/piff/input.py @@ -367,6 +367,10 @@ class InputFiles(Input): :sky_col: The name of a column with sky values. [default: None] :gain_col: The name of a column with gain values. [default: None] + :gain_file_name: A file containing a per-pixel effective gain map. [default: None] + :gain_ext: The extension number or name in the gain file, or in the image file + if gain_file_name is omitted. [default: None, which means use the gain + file's default extension] :sky: The sky level to subtract from the image values. [default: None] Specify only one sky source: sky, sky_col, or sky_file_name/sky_ext. If none are provided, the input image will be assumed to have already @@ -375,17 +379,22 @@ class InputFiles(Input): .. note:: There are two special values allowed for this parameter: + * ``sky: median`` computes the median of the image and uses that as the (constant) sky level. * ``sky: sep`` uses SEP's full spatial background image, with its default background settings. It requires the optional ``sep`` package to be installed. + Both estimators exclude pixels with zero weight. - :gain: The gain to use for adding Poisson noise to the weight map. [default: - None] It is an error for both gain and gain_col to be specified. - If both are None, then no additional noise will be added to account - for the Poisson noise from the galaxy flux. + :gain: The gain to use for adding Poisson noise to the weight map. Gain is defined + such that source_variance = source_signal / gain in the image's units. + Specify only one gain source: gain, gain_col, or gain_file_name/ + gain_ext. The gain may also be inferred implicitly from the action of + remove_signal_from_weight (see below). If no gain information is provided, + then no additional noise will be added to account for the Poisson noise + from the stars' flux. [default: None] :satur: The staturation level. If any pixels for a star exceed this, then the star is skipped. [default: None] :trust_pos: Whether to trust the input position as essentially exact (True), or to @@ -407,6 +416,22 @@ class InputFiles(Input): The above values are parsed separately for each input image/catalog. In addition, there are a couple other parameters that are just parsed once: + :invert_weight: Whether the weight maps are actually variance maps, and thus should be + inverted to make the usual inverse variance weight. [default: False] + :remove_signal_from_weight: Whether the weight (either inverted or not) includes the + Poisson noise from the sources. If so, set this to true so Piff can + remove that noise to recover the noise from non-source contributions + (read noise, background, dark current, etc.). Piff will account for the + source Poisson noise itself using the current model at every iteration, + so leaving observed source Poisson noise in the input weight would be an + error. [default: False] + + .. note:: + + This works better if a gain value is provided. But if one is not + known, Piff will try to estimate the (average) gain from the + data image and the given weights. + :stamp_size: The size of the postage stamps to use for the cutouts. Note: some stamps may be smaller than this if the star is near a chip boundary. [default: 32] @@ -447,6 +472,8 @@ def __init__(self, config, base=None, logger=None): 'sed_max_samples' : int, 'sky_col' : str, 'gain_col' : str, + 'gain_file_name': str, + 'gain_ext': (int, str), 'flag_col' : str, 'skip_flag' : int, 'use_flag' : int, @@ -490,6 +517,12 @@ def __init__(self, config, base=None, logger=None): raise ValueError("Specify only one sky source: sky, sky_col, or " "sky_file_name/sky_ext.") + gain_sources = sum(['gain' in config, 'gain_col' in config, + 'gain_file_name' in config or 'gain_ext' in config]) + if gain_sources > 1: + raise ValueError("Specify only one gain source: gain, gain_col, or " + "gain_file_name/gain_ext.") + # In GalSim, the base dict holds additional parameters that may be of use. # For now, add index_kex, as this will be the only thing we index anything on. base['index_key'] = 'image_num' @@ -543,7 +576,7 @@ def __init__(self, config, base=None, logger=None): # Convert Current/Eval shorthand before literal filenames are expanded as glob patterns. for key in ['image_file_name', 'cat_file_name', 'sky_file_name', - 'weight_file_name', 'badpix_file_name']: + 'weight_file_name', 'badpix_file_name', 'gain_file_name']: value = config.get(key) if isinstance(value, str) and value.startswith('@'): config[key] = {'type': 'Current', 'key': value[1:]} @@ -645,6 +678,25 @@ def __init__(self, config, base=None, logger=None): elif not isinstance(config['badpix_file_name'], dict): raise ValueError("badpix_file_name should be either a dict or a string") + if 'gain_file_name' not in config: + pass + elif isinstance(config['gain_file_name'], str): + gain_file_name = config['gain_file_name'] + if dir is not None: + gain_file_name = os.path.join(dir, gain_file_name) + gain_list = sorted(glob.glob(gain_file_name)) + if len(gain_list) == 0: + raise ValueError("No files found corresponding to " + config['gain_file_name']) + if len(gain_list) == 1 and nimages > 1: + logger.verbose("Using the same gain file for all images") + gain_list = gain_list * nimages + elif len(gain_list) != nimages: + raise ValueError("nimages = %s doesn't match length of gain_file_name list (%d)" % ( + nimages, len(gain_list))) + config['gain_file_name'] = gain_list + elif not isinstance(config['gain_file_name'], dict): + raise ValueError("gain_file_name should be either a dict or a string") + if 'cat_file_name' not in config: raise TypeError('Parameter cat_file_name is required') elif isinstance(config['cat_file_name'], list): @@ -711,6 +763,10 @@ def __init__(self, config, base=None, logger=None): sky_ext = params.get('sky_ext', None) if sky_file_name is None and sky_ext is not None: sky_file_name = image_file_name + gain_file_name = params.get('gain_file_name', None) + gain_ext = params.get('gain_ext', None) + if gain_file_name is None and gain_ext is not None: + gain_file_name = image_file_name self.image_file_name.append(image_file_name) self.image_kwargs.append({ 'image_file_name' : image_file_name, @@ -722,6 +778,8 @@ def __init__(self, config, base=None, logger=None): 'badpix_zeros' : badpix_zeros, 'sky_file_name' : sky_file_name, 'sky_ext' : sky_ext, + 'gain_file_name': gain_file_name, + 'gain_ext': gain_ext, 'image_num' : image_num, 'config' : self.config, 'base' : self.base, @@ -759,9 +817,6 @@ def __init__(self, config, base=None, logger=None): gain_col = params.get('gain_col', None) nstars = params.get('nstars', None) - if gain_col is not None and 'gain' in config: - raise ValueError("Cannot provide both gain_col and gain.") - self.cat_file_name.append(cat_file_name) self.cat_kwargs.append({ 'cat_file_name' : cat_file_name, @@ -822,10 +877,12 @@ def load_images(self, stars, logger=None): images = {} weight_images = {} + gain_images = {} for image_num in range(self.nimages): - image, weight, _, _ = self.getRawImageData(image_num) + image, weight, _, _, gain_image = self.getRawImageData(image_num, logger) images[self.chipnums[image_num]] = image weight_images[self.chipnums[image_num]] = weight + gain_images[self.chipnums[image_num]] = gain_image loaded_stars = [] for star in stars: @@ -834,7 +891,11 @@ def load_images(self, stars, logger=None): if 'sky' in star.data.properties: image -= star['sky'] weight = weight_images[chipnum][star.data.weight.bounds].copy() - data = star.data.withNew(image=image, weight=weight) + gain_image = gain_images[chipnum] + if gain_image is not None: + gain_image = gain_image[image.bounds].copy() + data = star.data.withNew(image=image, weight=weight, orig_weight=weight, + gain_image=gain_image) loaded_stars.append(Star(data=data, fit=star.fit)) return loaded_stars @@ -845,7 +906,7 @@ def getRawImageData(self, image_num, logger=None): :param image_num: The index of the image to read. :param logger: A logger object for logging debug info. [default: None] - :returns: image, weight, image_pos, extra_props. + :returns: image, weight, image_pos, extra_props, gain_image. """ self.base['index_key'] = 'image_num' self.base['image_num'] = image_num @@ -874,7 +935,7 @@ def _getRawImageData(cls, image_kwargs, cat_kwargs, wcs, config, base, logger=None): from .config import LoggerWrapper logger = LoggerWrapper(logger) - image, weight = cls.readImage(logger=logger, **image_kwargs) + image, weight, gain_image = cls.readImage(logger=logger, **image_kwargs) if invert_weight: weight.invertSelf() @@ -886,13 +947,16 @@ def _getRawImageData(cls, image_kwargs, cat_kwargs, wcs, logger=logger, image=image, **cat_kwargs) if remove_signal_from_weight: + nmasked = np.count_nonzero(weight.array == 0) # Subtract the mean catalog sky from the signal used for variance removal. # Image-level backgrounds have already been subtracted by readImage. if 'sky' in extra_props: signal = image - np.mean(extra_props['sky']) else: signal = image - if 'gain' in extra_props: + if gain_image is not None: + weight, _ = cls._removeSignalFromWeight(signal, weight, gain=gain_image) + elif 'gain' in extra_props: # If given, use the mean gain when removing the signal. # This isn't quite right, but hopefully the gain won't vary too much for # different objects, so it should be close. @@ -904,8 +968,12 @@ def _getRawImageData(cls, image_kwargs, cat_kwargs, wcs, extra_props['gain'] = np.array([g] * len(image_pos), dtype=float) logger.info("Empirically determined gain = %f",g) logger.verbose("Removed signal from weight image.") + added_masks = np.count_nonzero(weight.array == 0) - nmasked + if added_masks: + logger.warning("Masked %d pixels with invalid variance after removing source noise", + added_masks) - return image, weight, image_pos, extra_props + return image, weight, image_pos, extra_props, gain_image @classmethod def _makeStarsFromImage(cls, image_kwargs, cat_kwargs, wcs, chipnum, @@ -914,7 +982,7 @@ def _makeStarsFromImage(cls, image_kwargs, cat_kwargs, wcs, chipnum, config, base, logger): """Make "stars" from a single input image """ - image, wt, image_pos, extra_props = cls._getRawImageData( + image, wt, image_pos, extra_props, gain_image = cls._getRawImageData( image_kwargs, cat_kwargs, wcs, invert_weight, remove_signal_from_weight, config, base, logger) logger.verbose("Processing catalog %s with %d objects",chipnum,len(image_pos)) @@ -979,9 +1047,11 @@ def _makeStarsFromImage(cls, image_kwargs, cat_kwargs, wcs, chipnum, stamp -= sky pos = galsim.PositionD(x,y) + gain_stamp = gain_image[bounds].copy() if gain_image is not None else None data = StarData(stamp, pos, weight=wt_stamp, pointing=pointing, bandpass=bandpass, - properties=props, property_types=prop_types) + properties=props, property_types=prop_types, + gain_image=gain_stamp) # Attach an attribute so we can tell later whether the weight is real or # if it's just the default w=1.0. data._piff_default_weight = getattr(wt, '_piff_default_weight', False) @@ -1018,9 +1088,9 @@ def _removeSignalFromWeight(image, weight, gain=None): :param image: The image to use as the signal :param weight: The weight image. - :param gain: Optionally, the gain to use as the proportionality relation. - If gain is None, then it will be estimated automatically and returned. - [default: None] + :param gain: Optionally, the gain to use as the proportionality relation. May be + either a scalar or an image. If gain is None, then it will be estimated + automatically and returned. [default: None] :returns: newweight, gain """ @@ -1032,10 +1102,14 @@ def _removeSignalFromWeight(image, weight, gain=None): fit = np.polyfit(signal, variance, deg=1) gain = 1./fit[0] # fit is [ 1/gain, sky_var ] - variance -= signal / gain + gain_values = gain.array[use] if isinstance(gain, galsim.Image) else gain + variance -= signal / gain_values newweight = weight.copy() - newweight.array[use] = 1. / variance + valid = np.isfinite(variance) & (variance > 0) + new_values = np.zeros_like(variance) + np.divide(1.0, variance, out=new_values, where=valid) + newweight.array[use] = new_values return newweight, gain @staticmethod @@ -1058,8 +1132,10 @@ def _read_image(file_name, ext, *, read_header): @classmethod def readImage(cls, image_file_name, image_ext, weight_file_name, weight_ext, badpix_file_name, badpix_ext, badpix_zeros, sky_file_name, sky_ext, - image_num, config, base, logger): - """Read in the image and weight map (or make one if no weight information is given). + gain_file_name, gain_ext, image_num, config, base, logger): + """Read the science image, weight map, and optional gain image. + + Make a weight map if no weight information is given. :param image_file_name: The name of the file to read. :param image_ext: The extension number or name of the main image. @@ -1072,11 +1148,13 @@ def readImage(cls, image_file_name, image_ext, weight_file_name, weight_ext, :param sky_file_name: A file to use for a sky background to subtract from the image (if any). :param sky_ext: The extension number or name in sky_file_name (if any). + :param gain_file_name: The name of the file with the gain image (if any). + :param gain_ext: The extension number or name of the gain image (if any). :param config: The input section of the config dict. :param base: The base config dict. :param logger: A logger object for logging debug info. - :returns: image, weight + :returns: image, weight, gain_image (None when no gain image is supplied) """ # Read in the image logger.info("Reading image file %s",image_file_name) @@ -1161,7 +1239,17 @@ def readImage(cls, image_file_name, image_ext, weight_file_name, weight_ext, if sky_image is not None: image -= sky_image - return image, weight + gain_image = None + if gain_file_name is not None: + logger.verbose("Reading gain image from %s, extension %s.", gain_file_name, gain_ext) + gain_image = cls._read_image(gain_file_name, gain_ext, read_header=False) + if gain_image.bounds != image.bounds: + raise ValueError('Gain image bounds do not match science image bounds') + use = weight.array != 0 + if np.any(~np.isfinite(gain_image.array[use]) | (gain_image.array[use] <= 0)): + raise ValueError('Gain image must be finite and positive at unmasked pixels') + + return image, weight, gain_image @classmethod def _read_sky(cls, image, weight, sky, sky_file_name, sky_ext, logger): diff --git a/piff/star.py b/piff/star.py index f5d53e83..41bc1e9d 100644 --- a/piff/star.py +++ b/piff/star.py @@ -809,6 +809,7 @@ def load_images(stars, file_name, pointing=None, pointing=s.data.pointing, bandpass=s.data.bandpass, sed_eff=s.data._sed_eff, + gain_image=s.data.gain_image, properties=dict(s.data.properties, sky=sky), property_types=s.data.property_types, _xyuv_set = True), @@ -855,10 +856,10 @@ def addPoisson(self, signal=None, gain=None): :param signal: The signal (as a Star instance) from which the Poisson variance is extracted. If None, the data image is used. All signals are - clipped from below at zero. - :param gain: The gain, in e per ADU, assumed in calculating new weights. If None - is given, then the 'gain' property is used, else defaults to not - adding any variance. + clipped from below at zero. [default: None] + :param gain: The gain in e per ADU, either as a scalar or an image. If None, we use + gain_image if available or a scalar 'gain' property. If neither + is set, no variance is added. [default: None] :returns: a new Star instance with updated weight array. """ @@ -941,15 +942,17 @@ class StarData(object): [default: None] :param sed_eff: The unit-flux SED multiplied by the observing bandpass. [default: None] + :param gain_image: Per-pixel gain as a galsim.Image. [default: None] """ _sed_cache = {} def __init__(self, image, image_pos, weight=None, pointing=None, field_pos=None, properties=None, property_types=None, orig_weight=None, logger=None, - _xyuv_set=False, bandpass=None, sed_eff=None): + _xyuv_set=False, bandpass=None, sed_eff=None, gain_image=None): # Save all of these as attributes. self.image = image self.image_pos = image_pos + self.gain_image = gain_image # Make sure we have a local wcs in case the provided image is more complex. self.local_wcs = image.wcs.local(image_pos) self.pixel_area = self.local_wcs.pixelArea() @@ -1334,16 +1337,16 @@ def addPoisson(self, signal=None, gain=None): :param signal: The signal (as a Star instance) from which the Poisson variance is extracted. If None, the data image is used. All signals are - clipped from below at zero. - :param gain: The gain, in e per ADU, assumed in calculating new weights. If None - is given, then the 'gain' property is used, else defaults to not - adding any variance. + clipped from below at zero. [default: None] + :param gain: The gain in e per ADU, either as a scalar or an image. If None, we use + gain_image if available or a scalar 'gain' property. If neither + is set, no variance is added. [default: None] :returns: a new StarData instance with updated weight array. """ - # Get the gain. None both here and in properties, means don't add any variance. + # If gain not given, use the stored image or property value. if gain is None: - gain = self.properties.get('gain',None) + gain = self.gain_image if self.gain_image is not None else self.properties.get('gain') if gain is None: return self @@ -1365,7 +1368,16 @@ def addPoisson(self, signal=None, gain=None): # Note: use the original weight here, not the current weight, since this may have already # had some Poisson noise added to the weight. newweight = self.orig_weight.copy() - newweight.array[use] = 1. / (1./self.orig_weight.array[use] + variance[use] / gain) + if isinstance(gain, galsim.Image): + gain_values = gain.array[use] + gain_image = gain + properties = self.properties.copy() + properties.pop('gain', None) + else: + gain_values = gain + gain_image = None + properties = dict(self.properties, gain=gain) + newweight.array[use] = 1. / (1./self.orig_weight.array[use] + variance[use] / gain_values) # Return new object return StarData(image=self.image, @@ -1375,7 +1387,8 @@ def addPoisson(self, signal=None, gain=None): pointing=self.pointing, bandpass=self.bandpass, sed_eff=self._sed_eff, - properties=dict(self.properties, gain=gain), + gain_image=gain_image, + properties=properties, property_types=self.property_types, _xyuv_set = True) diff --git a/tests/test_input.py b/tests/test_input.py index 6d9fc501..cf0d17a3 100644 --- a/tests/test_input.py +++ b/tests/test_input.py @@ -172,27 +172,27 @@ def test_basic(): } input = piff.InputFiles(config, logger=logger) assert input.nimages == 1 - _, _, image_pos, _ = input.getRawImageData(0) + _, _, image_pos, _, _ = input.getRawImageData(0) assert len(image_pos) == 100 # Check alternate file suffix for catalog. config['cat_file_name'] = 'test_input_cat_00.fit' input = piff.InputFiles(config, logger=logger) assert input.nimages == 1 - _, _, image_pos2, _ = input.getRawImageData(0) + _, _, image_pos2, _, _ = input.getRawImageData(0) np.testing.assert_array_equal(image_pos, image_pos2) # Check parquet files config['cat_file_name'] = 'test_input_cat_00.parquet' input = piff.InputFiles(config, logger=logger) assert input.nimages == 1 - _, _, image_pos2, _ = input.getRawImageData(0) + _, _, image_pos2, _, _ = input.getRawImageData(0) np.testing.assert_array_equal(image_pos, image_pos2) config['cat_file_name'] = 'test_input_cat_00.pq' input = piff.InputFiles(config, logger=logger) assert input.nimages == 1 - _, _, image_pos2, _ = input.getRawImageData(0) + _, _, image_pos2, _, _ = input.getRawImageData(0) np.testing.assert_array_equal(image_pos, image_pos2) config['cat_file_name'] = 'test_input_cat_00.invalid' @@ -206,7 +206,7 @@ def test_basic(): } input = piff.InputFiles(config, logger=logger) assert input.nimages == 1 - _, _, image_pos, _ = input.getRawImageData(0) + _, _, image_pos, _, _ = input.getRawImageData(0) assert len(image_pos) == 100 # 3 images in a list @@ -220,7 +220,7 @@ def test_basic(): input = piff.InputFiles(config, logger=logger) assert input.nimages == 3 for i in range(3): - _, _, image_pos, _ = input.getRawImageData(i) + _, _, image_pos, _, _ = input.getRawImageData(i) assert len(image_pos) == 100 # Again without dir. @@ -233,7 +233,7 @@ def test_basic(): input = piff.InputFiles(config, logger=logger) assert input.nimages == 3 for i in range(3): - _, _, image_pos, _ = input.getRawImageData(i) + _, _, image_pos, _, _ = input.getRawImageData(i) assert len(image_pos) == 100 # 3 images using glob @@ -247,7 +247,7 @@ def test_basic(): input = piff.InputFiles(config, logger=logger) assert input.nimages == 3 for i in range(3): - _, _, image_pos, _ = input.getRawImageData(i) + _, _, image_pos, _, _ = input.getRawImageData(i) assert len(image_pos) == 100 # Filename shorthand must follow the same per-image parsing as explicit dicts. @@ -282,8 +282,8 @@ def test_basic(): assert shorthand.image_file_name[0] != shorthand.image_file_name[1] assert shorthand.wcs_list == reference.wcs_list for image_num in range(2): - image, weight, positions, _ = shorthand.getRawImageData(image_num) - ref_image, ref_weight, ref_positions, _ = reference.getRawImageData(image_num) + image, weight, positions, _, _ = shorthand.getRawImageData(image_num) + ref_image, ref_weight, ref_positions, _, _ = reference.getRawImageData(image_num) np.testing.assert_array_equal(image.array, ref_image.array) np.testing.assert_array_equal(weight.array, ref_weight.array) assert positions == ref_positions @@ -298,7 +298,7 @@ def test_basic(): assert "input.nstars is deprecated" in cl.output assert input.nimages == 3 for i in range(3): - _, _, image_pos, _ = input.getRawImageData(i) + _, _, image_pos, _, _ = input.getRawImageData(i) assert len(image_pos) == 37 # input.nstars can still vary by image with the old per-catalog behavior. @@ -306,7 +306,7 @@ def test_basic(): input = piff.InputFiles(config) assert input.nimages == 3 for i in range(3): - _, _, image_pos, _ = input.getRawImageData(i) + _, _, image_pos, _, _ = input.getRawImageData(i) if i == 0: assert len(image_pos) == 40 elif i == 1: @@ -447,7 +447,7 @@ def test_extensions(): if named: current.update(zip(keys, names)) handler = piff.InputFiles(current) - image, weight, positions, _ = handler.getRawImageData(0) + image, weight, positions, _, _ = handler.getRawImageData(0) np.testing.assert_array_equal(image.array, science - sky) np.testing.assert_array_equal(weight.array, np.where(mask, 0, 5)) assert positions == [galsim.PositionD(16, 16), galsim.PositionD(32, 32)] @@ -457,7 +457,7 @@ def test_extensions(): current = dict(config) current.pop('sky_file_name') handler = piff.InputFiles(current) - image, weight, _, _ = handler.getRawImageData(0) + image, weight, _, _, _ = handler.getRawImageData(0) np.testing.assert_array_equal(image.array, science - sky) np.testing.assert_array_equal(weight.array, np.where(mask, 0, 5)) @@ -470,7 +470,7 @@ def test_extensions(): handler = piff.InputFiles(current, logger=cl.logger) assert '%s is deprecated as of version 1.8. Use %s instead.' % (old, key) in cl.output assert old in current and key not in current - image, weight, positions, _ = handler.getRawImageData(0) + image, weight, positions, _, _ = handler.getRawImageData(0) np.testing.assert_array_equal(image.array, science - sky) np.testing.assert_array_equal(weight.array, np.where(mask, 0, 5)) assert positions == [galsim.PositionD(16, 16), galsim.PositionD(32, 32)] @@ -481,7 +481,7 @@ def test_extensions(): current['weight_hdu'] = '$@input.image_hdu + 2' current.pop('weight_ext') handler = piff.InputFiles(current, base={'input': current}) - image, weight, _, _ = handler.getRawImageData(0) + image, weight, _, _, _ = handler.getRawImageData(0) np.testing.assert_array_equal(image.array, science - sky) np.testing.assert_array_equal(weight.array, np.where(mask, 0, 5)) @@ -495,7 +495,7 @@ def test_extensions(): handler = piff.InputFiles(current) assert handler.nimages == 2 for i in range(2): - image, weight, positions, _ = handler.getRawImageData(i) + image, weight, positions, _, _ = handler.getRawImageData(i) np.testing.assert_array_equal(image.array, science + 10 * i - sky) np.testing.assert_array_equal(weight.array, np.where(mask, 0, 5)) assert positions == [galsim.PositionD(16, 16), galsim.PositionD(32, 32)] @@ -509,7 +509,7 @@ def test_extensions(): current['weight_ext'] = {'type': 'List_str', 'items': ['WEIGHT', 'WEIGHT']} handler = piff.InputFiles(current) for i in range(2): - image, weight, _, _ = handler.getRawImageData(i) + image, weight, _, _, _ = handler.getRawImageData(i) np.testing.assert_array_equal(image.array, science + 10 * i - sky) np.testing.assert_array_equal(weight.array, np.where(mask, 0, 5)) @@ -526,7 +526,7 @@ def test_extensions(): for key in ['image_file_name', 'cat_file_name', 'sky_file_name']: current[key] = compressed_file handler = piff.InputFiles(current) - image, weight, positions, _ = handler.getRawImageData(0) + image, weight, positions, _, _ = handler.getRawImageData(0) np.testing.assert_array_equal(image.array, science - sky) np.testing.assert_array_equal(weight.array, np.where(mask, 0, 5)) assert positions == [galsim.PositionD(16, 16), galsim.PositionD(32, 32)] @@ -710,7 +710,7 @@ def test_cols(): } input = piff.InputFiles(config, logger=logger) assert input.nimages == 1 - _, _, image_pos, _ = input.getRawImageData(0) + _, _, image_pos, _, _ = input.getRawImageData(0) assert len(image_pos) == 100 # Can do ra, dec instead of x, y @@ -725,7 +725,7 @@ def test_cols(): } input2 = piff.InputFiles(config, logger=logger) assert input2.nimages == 1 - _, _, image_pos2, _ = input2.getRawImageData(0) + _, _, image_pos2, _, _ = input2.getRawImageData(0) print('input.image_pos = ',image_pos) print('input2.image_pos = ',image_pos2) assert len(image_pos2) == 100 @@ -752,7 +752,7 @@ def test_cols(): } input = piff.InputFiles(config, logger=logger) assert input.nimages == 1 - raw_image, _, image_pos, props = input.getRawImageData(0) + raw_image, _, image_pos, props, _ = input.getRawImageData(0) sky_list = props['sky'] gain_list = props['gain'] assert len(image_pos) == 100 @@ -771,7 +771,7 @@ def test_cols(): 'gain' : gain, } input = piff.InputFiles(config, logger=logger) - image, _, image_pos, props = input.getRawImageData(0) + image, _, image_pos, props, _ = input.getRawImageData(0) assert 'sky' not in props gain_list = props['gain'] assert len(image_pos) == 100 @@ -792,7 +792,7 @@ def test_cols(): 'gain' : { 'type': 'ImageHeaderValue', 'key': 'GAIN_A' }, } input = piff.InputFiles(config, logger=logger) - image, _, image_pos, props = input.getRawImageData(0) + image, _, image_pos, props, _ = input.getRawImageData(0) assert 'sky' not in props gain_list = props['gain'] assert len(image_pos) == 100 @@ -812,7 +812,7 @@ def test_cols(): } input = piff.InputFiles(config) with CaptureLog() as cl: - image, _, image_pos, props = input.getRawImageData(0, logger=cl.logger) + image, _, image_pos, props, _ = input.getRawImageData(0, logger=cl.logger) assert "Using a bare FITS header key for sky is deprecated" in cl.output assert "Using a bare FITS header key for gain is deprecated" in cl.output assert 'sky' not in props @@ -832,7 +832,7 @@ def test_cols(): 'trust_pos' : {'type': 'Eval', 'str': 'True'}, } input = piff.InputFiles(config, logger=logger) - image, _, image_pos, props = input.getRawImageData(0) + image, _, image_pos, props, _ = input.getRawImageData(0) assert 'sky' not in props gain_list = props['gain'] trust_pos = props['trust_pos'] @@ -849,7 +849,7 @@ def test_cols(): 'noise' : '$2 + 3', } input = piff.InputFiles(config, logger=logger) - image, weight, image_pos, _ = input.getRawImageData(0) + image, weight, image_pos, _, _ = input.getRawImageData(0) assert len(image_pos) == 100 np.testing.assert_allclose(weight.array[weight.array != 0], [1./5.] * np.count_nonzero(weight.array)) @@ -864,7 +864,7 @@ def test_cols(): base = {'input': multi_config, 'first_value': 10.} multi_input = piff.InputFiles(multi_config, base=base, logger=logger) for image_num, expected in enumerate([10., 20.]): - image, weight, image_pos, props = multi_input.getRawImageData(image_num) + image, weight, image_pos, props, _ = multi_input.getRawImageData(image_num) assert len(image_pos) == 100 np.testing.assert_allclose(weight.array, 1. / expected) np.testing.assert_allclose(image.array, raw_image.array - expected) @@ -878,7 +878,7 @@ def test_cols(): multi_config[key] = '$@image_value' multi_input = piff.InputFiles(multi_config, base=base, logger=logger) for image_num, expected in enumerate([10., 20.]): - image, weight, _, props = multi_input.getRawImageData(image_num) + image, weight, _, props, _ = multi_input.getRawImageData(image_num) np.testing.assert_allclose(weight.array, 1. / expected) np.testing.assert_allclose(image.array, raw_image.array - expected) assert 'sky' not in props @@ -888,7 +888,7 @@ def test_cols(): # gain can also be given explicitly as an ImageHeaderValue. config['gain'] = { 'type': 'ImageHeaderValue', 'key': 'GAIN_A' } input = piff.InputFiles(config, logger=logger) - _, _, image_pos, props = input.getRawImageData(0) + _, _, image_pos, props, _ = input.getRawImageData(0) gain_list = props['gain'] assert len(image_pos) == 100 assert len(gain_list) == 100 @@ -915,7 +915,7 @@ def test_cols(): 'satur' : 1890, } input = piff.InputFiles(config, logger=logger) - _, _, image_pos, props = input.getRawImageData(0) + _, _, image_pos, props, _ = input.getRawImageData(0) satur = props['satur'][0] assert satur == 1890 assert len(image_pos) == 100 @@ -929,7 +929,7 @@ def test_cols(): 'satur' : '$1800 + 90', } input = piff.InputFiles(config, logger=logger) - _, _, image_pos, props = input.getRawImageData(0) + _, _, image_pos, props, _ = input.getRawImageData(0) satur = props['satur'][0] assert satur == 1890 assert len(image_pos) == 100 @@ -943,7 +943,7 @@ def test_cols(): 'satur' : { 'type': 'ImageHeaderValue', 'key': 'SATURAT' }, } input = piff.InputFiles(config, logger=logger) - _, _, image_pos, props = input.getRawImageData(0) + _, _, image_pos, props, _ = input.getRawImageData(0) satur = props['satur'][0] assert satur == 1890 assert len(image_pos) == 100 @@ -959,7 +959,7 @@ def test_cols(): } input = piff.InputFiles(config) with CaptureLog() as cl: - _, _, image_pos, props = input.getRawImageData(0, logger=cl.logger) + _, _, image_pos, props, _ = input.getRawImageData(0, logger=cl.logger) assert "Using a bare FITS header key for satur is deprecated" in cl.output satur = props['satur'][0] assert satur == 1890 @@ -974,7 +974,7 @@ def test_cols(): 'skip_flag' : 4 } input = piff.InputFiles(config, logger=logger) - _, _, image_pos, _ = input.getRawImageData(0) + _, _, image_pos, _, _ = input.getRawImageData(0) assert input.nimages == 1 print('len = ',len(image_pos)) assert len(image_pos) == 80 @@ -988,7 +988,7 @@ def test_cols(): 'use_flag' : 1 } input = piff.InputFiles(config, logger=logger) - _, _, image_pos, _ = input.getRawImageData(0) + _, _, image_pos, _, _ = input.getRawImageData(0) print('len = ',len(image_pos)) assert len(image_pos) == 85 @@ -1002,7 +1002,7 @@ def test_cols(): 'use_flag' : '$2**0', } input = piff.InputFiles(config, logger=logger) - _, _, image_pos, _ = input.getRawImageData(0) + _, _, image_pos, _, _ = input.getRawImageData(0) print('len = ',len(image_pos)) assert len(image_pos) == 68 @@ -1014,7 +1014,7 @@ def test_cols(): 'flag_col' : 'flag', } input = piff.InputFiles(config, logger=logger) - _, _, image_pos, _ = input.getRawImageData(0) + _, _, image_pos, _, _ = input.getRawImageData(0) print('len = ',len(image_pos)) assert len(image_pos) == 12 @@ -1028,7 +1028,7 @@ def test_cols(): 'use_flag' : 128 } input = piff.InputFiles(config, logger=logger) - _, _, image_pos, _ = input.getRawImageData(0) + _, _, image_pos, _, _ = input.getRawImageData(0) print('len = ',len(image_pos)) assert len(image_pos) == 0 with np.testing.assert_raises(RuntimeError): @@ -1045,12 +1045,12 @@ def test_cols(): 'cat_file_name' : 'test_input_cat_00.fits', } input = piff.InputFiles(dict(property_cols=['gr_color'], **base_config), logger=logger) - _, _, _, props_dict = input.getRawImageData(0) + _, _, _, props_dict, _ = input.getRawImageData(0) assert len(props_dict['gr_color']) == 100 np.testing.assert_array_equal(props_dict['gr_color'], gr_color) input = piff.InputFiles(dict(property_cols=['gr_color', 'rz_color'], **base_config), logger=logger) - _, _, _, props_dict = input.getRawImageData(0) + _, _, _, props_dict, _ = input.getRawImageData(0) print(props_dict) assert len(props_dict['gr_color']) == 100 assert len(props_dict['rz_color']) == 100 @@ -1076,11 +1076,11 @@ def test_cols(): 'property_cols' : ['gr_color'], } input = piff.InputFiles(config, logger=logger) - _, _, _, props_dict = input.getRawImageData(0) + _, _, _, props_dict, _ = input.getRawImageData(0) np.testing.assert_array_equal(props_dict['const_prop'], [1.5] * 100) np.testing.assert_array_equal(props_dict['image_id'], [10] * 100) np.testing.assert_allclose(props_dict['gr_plus_one'], gr_color + 1) - _, _, _, props_dict = input.getRawImageData(1) + _, _, _, props_dict, _ = input.getRawImageData(1) np.testing.assert_array_equal(props_dict['const_prop'], [1.5] * 100) np.testing.assert_array_equal(props_dict['image_id'], [11] * 100) @@ -1100,8 +1100,8 @@ def test_cols(): 'trust_pos' : '$@image_num == 1', } input = piff.InputFiles(config, logger=logger) - image0, weight0, image_pos0, props0 = input.getRawImageData(0) - image1, weight1, image_pos1, props1 = input.getRawImageData(1) + image0, weight0, image_pos0, props0, _ = input.getRawImageData(0) + image1, weight1, image_pos1, props1, _ = input.getRawImageData(1) assert len(image_pos0) == 100 assert len(image_pos1) == 100 np.testing.assert_allclose(weight0.array[weight0.array != 0], [1.] * np.count_nonzero(weight0.array)) @@ -1561,7 +1561,7 @@ def test_boolarray(): } input = piff.InputFiles(config, logger=logger) assert input.nimages == 1 - _, _, image_pos, _ = input.getRawImageData(0) + _, _, image_pos, _, _ = input.getRawImageData(0) print('len = ',len(image_pos)) assert len(image_pos) == 80 @@ -1638,7 +1638,7 @@ def test_weight(): } input = piff.InputFiles(config, logger=logger) assert input.nimages == 1 - image, weight, image_pos, _ = input.getRawImageData(0) + image, weight, image_pos, _, _ = input.getRawImageData(0) assert len(image_pos) == 100 assert image.array.shape == (1024, 1024) assert weight.array.shape == (1024, 1024) @@ -1656,7 +1656,7 @@ def test_weight(): } input = piff.InputFiles(config, logger=logger) assert input.nimages == 1 - image, weight, image_pos, extra_props = input.getRawImageData(0) + image, weight, image_pos, extra_props, _ = input.getRawImageData(0) assert len(image_pos) == 100 assert image.array.shape == (1024, 1024) assert weight.array.shape == (1024, 1024) @@ -1674,7 +1674,7 @@ def test_weight(): } input = piff.InputFiles(config, logger=logger) assert input.nimages == 1 - _, weight, _, _ = input.getRawImageData(0) + _, weight, _, _, _ = input.getRawImageData(0) assert weight.array.shape == (1024, 1024) np.testing.assert_almost_equal(weight.array, 32.**-1) @@ -1687,7 +1687,7 @@ def test_weight(): } input = piff.InputFiles(config, logger=logger) assert input.nimages == 1 - _, weight, _, _ = input.getRawImageData(0) + _, weight, _, _, _ = input.getRawImageData(0) assert weight.array.shape == (1024, 1024) np.testing.assert_almost_equal(weight.array, 34.**-1) @@ -1696,7 +1696,7 @@ def test_weight(): input = piff.InputFiles(config) assert input.nimages == 1 with CaptureLog() as cl: - _, weight, _, _ = input.getRawImageData(0, logger=cl.logger) + _, weight, _, _, _ = input.getRawImageData(0, logger=cl.logger) assert "Using a bare FITS header key for noise is deprecated" in cl.output assert weight.array.shape == (1024, 1024) np.testing.assert_almost_equal(weight.array, 34.**-1) @@ -1717,14 +1717,14 @@ def test_weight(): } input = piff.InputFiles(config, logger=logger) assert input.nimages == 1 - _, weight, _, _ = input.getRawImageData(0) + _, weight, _, _, _ = input.getRawImageData(0) assert weight.array.shape == (1024, 1024) np.testing.assert_almost_equal(weight.array, expected_noise**-1) config['badpix_ext'] = 6 input = piff.InputFiles(config, logger=logger) assert input.nimages == 1 - _, weight, _, _ = input.getRawImageData(0) + _, weight, _, _, _ = input.getRawImageData(0) assert weight.array.shape == (1024, 1024) np.testing.assert_almost_equal(weight.array, expected_noise**-1) @@ -1734,7 +1734,7 @@ def test_weight(): config['badpix_ext'] = 7 # badpix > 0 input = piff.InputFiles(config, logger=logger) assert input.nimages == 1 - _, weight, _, _ = input.getRawImageData(0) + _, weight, _, _, _ = input.getRawImageData(0) assert weight.array.shape == (1024, 1024) np.testing.assert_almost_equal(weight.array, 0.) @@ -1742,7 +1742,7 @@ def test_weight(): config['badpix_ext'] = 2 input = piff.InputFiles(config, logger=logger) assert input.nimages == 1 - _, weight, _, _ = input.getRawImageData(0) + _, weight, _, _, _ = input.getRawImageData(0) assert weight.array.shape == (1024, 1024) np.testing.assert_almost_equal(weight.array, 0.) @@ -1750,7 +1750,7 @@ def test_weight(): config['badpix_ext'] = 9 # Odd cols are > 0 input = piff.InputFiles(config, logger=logger) assert input.nimages == 1 - _, weight, _, _ = input.getRawImageData(0) + _, weight, _, _, _ = input.getRawImageData(0) assert weight.array.shape == (1024, 1024) np.testing.assert_almost_equal(weight.array, 0.) @@ -1761,7 +1761,7 @@ def test_weight(): config['badpix_ext'] = 0 input = piff.InputFiles(config, logger=logger) assert input.nimages == 1 - _, weight, _, _ = input.getRawImageData(0) + _, weight, _, _, _ = input.getRawImageData(0) assert weight.array.shape == (1024, 1024) np.testing.assert_almost_equal(weight.array, 0.) @@ -1771,19 +1771,19 @@ def test_weight(): config['weight_ext'] = 4 input = piff.InputFiles(config) with CaptureLog() as cl: - _, weight, _, _ = input.getRawImageData(0, logger=cl.logger) + _, weight, _, _, _ = input.getRawImageData(0, logger=cl.logger) assert 'Warning: weight map has invalid negative-valued pixels.' in cl.output # If some input values are zero, they can be treated as bad pixels with badpix_zeros del config['weight_ext'] config['badpix_ext'] = 9 input = piff.InputFiles(config, logger=logger) - _, weight, _, _ = input.getRawImageData(0) + _, weight, _, _, _ = input.getRawImageData(0) del config['badpix_ext'] config['image_ext'] = 11 config['badpix_zeros'] = True input = piff.InputFiles(config, logger=logger) - _, weight2, _, _ = input.getRawImageData(0) + _, weight2, _, _, _ = input.getRawImageData(0) np.testing.assert_array_equal(weight.array, weight2.array) # One image file with multiple HDUs should be treated as multiple images. @@ -1799,13 +1799,13 @@ def test_weight(): assert input.nimages == 2 assert input.image_file_name == ['input/test_input_image_00.fits'] * 2 assert input.cat_file_name == ['input/test_input_cat_00.fits'] * 2 - image, weight, image_pos, _ = input.getRawImageData(0) + image, weight, image_pos, _, _ = input.getRawImageData(0) assert len(image_pos) == 100 np.testing.assert_allclose(image.array, fitsio.read('input/test_input_image_00.fits', ext=0) - sky) np.testing.assert_allclose(weight.array, fitsio.read('input/test_input_weight_00.fits', ext=0)) - image, weight, image_pos, _ = input.getRawImageData(1) + image, weight, image_pos, _, _ = input.getRawImageData(1) assert len(image_pos) == 100 np.testing.assert_allclose(image.array, fitsio.read('input/test_input_image_00.fits', ext=10) - sky) @@ -1835,12 +1835,12 @@ def test_weight(): assert input.image_kwargs[1]['badpix_file_name'] == 'input/test_input_badpix_00.fits' expected_weight0 = fitsio.read('input/test_input_weight_00.fits', ext=0) expected_weight0[1::2, :] = 0 - _, weight, image_pos, _ = input.getRawImageData(0) + _, weight, image_pos, _, _ = input.getRawImageData(0) assert len(image_pos) == 100 np.testing.assert_allclose(weight.array, expected_weight0) expected_weight1 = fitsio.read('input/test_input_weight_00.fits', ext=1) expected_weight1[1::2, :] = 0 - _, weight, image_pos, _ = input.getRawImageData(1) + _, weight, image_pos, _, _ = input.getRawImageData(1) assert len(image_pos) == 100 np.testing.assert_allclose(weight.array, expected_weight1) @@ -1855,10 +1855,10 @@ def test_weight(): assert input.image_kwargs[1]['weight_file_name'] == 'input/test_input_weight_00.fits' assert input.image_kwargs[0]['badpix_file_name'] == 'input/test_input_badpix_00.fits' assert input.image_kwargs[1]['badpix_file_name'] == 'input/test_input_badpix_00.fits' - _, weight, image_pos, _ = input.getRawImageData(0) + _, weight, image_pos, _, _ = input.getRawImageData(0) assert len(image_pos) == 100 np.testing.assert_allclose(weight.array, expected_weight0) - _, weight, image_pos, _ = input.getRawImageData(1) + _, weight, image_pos, _, _ = input.getRawImageData(1) assert len(image_pos) == 100 np.testing.assert_allclose(weight.array, expected_weight1) @@ -1885,7 +1885,7 @@ def test_lsst_weight(): } input = piff.InputFiles(config, logger=logger) assert input.nimages == 1 - image, weight, image_pos, props = input.getRawImageData(0) + image, weight, image_pos, props, _ = input.getRawImageData(0) assert len(image_pos) == 100 assert image.array.shape == (1024, 1024) assert weight.array.shape == (1024, 1024) @@ -1908,7 +1908,7 @@ def test_lsst_weight(): } input = piff.InputFiles(config, logger=logger) assert input.nimages == 1 - image, weight, image_pos, props = input.getRawImageData(0) + image, weight, image_pos, props, _ = input.getRawImageData(0) np.testing.assert_allclose(props['gain'], gain, rtol=1.e-6) np.testing.assert_allclose(weight.array, expected_noise**-1, rtol=1.e-6) @@ -1924,7 +1924,7 @@ def test_lsst_weight(): } input = piff.InputFiles(config, logger=logger) assert input.nimages == 1 - image, weight, image_pos, props = input.getRawImageData(0) + image, weight, image_pos, props, _ = input.getRawImageData(0) assert len(image_pos) == 100 assert image.array.shape == (1024, 1024) assert weight.array.shape == (1024, 1024) @@ -1946,7 +1946,7 @@ def test_lsst_weight(): } input = piff.InputFiles(config, logger=logger) assert input.nimages == 1 - image, weight1, image_pos, props = input.getRawImageData(0) + image, weight1, image_pos, props, _ = input.getRawImageData(0) assert len(image_pos) == 100 assert image.array.shape == (1024, 1024) assert weight.array.shape == (1024, 1024) @@ -1958,6 +1958,177 @@ def test_lsst_weight(): np.testing.assert_allclose(weight.array, expected_noise**-1, rtol=1.e-5) +@timer +def test_gain_image(): + """Test passing an image for the gain, which different values at each pixel. + """ + from piff.writers import FitsWriter + from piff.readers import FitsReader + + # Draw several stars with GalSim and form the known per-pixel Poisson variance. + signal = galsim.ImageD(128, 128, scale=0.2) + positions = [(5.2, 6.3), (40.1, 48.6), (91.7, 99.4)] + psf = galsim.Moffat(beta=3.5, fwhm=0.7) + for pos, flux in zip(positions, [2000, 5000, 8000]): + psf.withFlux(flux).drawImage(image=signal, center=galsim.PositionD(*pos), + add_to_image=True) + y, x = np.mgrid[:128, :128] + gain = 2.0 + 0.01 * x + 0.005 * y + sky = 15.0 + background_variance = 4.0 + sky / gain + background_weight = 1.0 / background_variance + background_weight[0, 0] = 0 + observed_weight = 1.0 / (background_variance + signal.array / gain) + observed_weight[0, 0] = 0 + gain[0, 0] = 0 # Masked pixels need not have a usable gain. + image_name = os.path.join('output', 'gain_science.fits') + gain_name = os.path.join('output', 'gain_map.fits') + cat_name = os.path.join('output', 'gain_cat.fits') + with fitsio.FITS(image_name, 'rw', clobber=True) as f: + f.write(signal.array + sky) + f.write(observed_weight) + f.write(gain, extname='GAIN') + f.write(background_weight, extname='BACKGROUND_WEIGHT') + fitsio.write(gain_name, gain, extname='GAIN', clobber=True) + fitsio.write(cat_name, np.array(positions, dtype=[('x', float), ('y', float)]), clobber=True) + config = { + 'image_file_name': image_name, + 'cat_file_name': cat_name, + 'weight_ext': 1, + 'sky': sky, + 'remove_signal_from_weight': True, + 'stamp_size': 24, + 'use_partial': True, + } + + # Numeric/named extensions and separate files give the same gain cutouts and weights. + for options in [{'gain_ext': 2}, {'gain_ext': 'GAIN'}, {'gain_file_name': gain_name}, + {'gain_file_name': image_name, 'gain_ext': 'GAIN'}]: + reader = piff.InputFiles(dict(config, **options)) + _, _, _, props, gain_image = reader.getRawImageData(0) + np.testing.assert_array_equal(gain_image.array, gain) + assert 'gain' not in props + stars = reader.makeStars() + assert len(stars) == len(positions) + assert stars[0].image.array.size < 24**2 + for star in stars: + bounds = star.image.bounds + expected_gain = galsim.Image(gain)[bounds] + np.testing.assert_array_equal(star.data.gain_image.array, expected_gain.array) + assert 'gain' not in star.data.properties + expected_variance = galsim.Image(background_variance)[bounds].array + expected_weight = 1.0 / expected_variance + expected_observed = galsim.Image(observed_weight)[bounds].array + expected_weight[expected_observed == 0] = 0 + np.testing.assert_allclose(star.weight.array, expected_weight) + np.testing.assert_allclose(star.addPoisson().weight.array, expected_observed) + + # Background-only weights use the map directly without first removing source variance. + background_config = { + **config, + 'gain_ext': 'GAIN', + 'weight_ext': 'BACKGROUND_WEIGHT', + 'remove_signal_from_weight': False, + } + background_stars = piff.InputFiles(background_config).makeStars() + for original, loaded in zip(stars, background_stars): + np.testing.assert_allclose(loaded.weight.array, original.weight.array) + np.testing.assert_allclose(loaded.addPoisson().weight.array, + original.addPoisson().weight.array) + + # Model Poisson updates replace, rather than accumulate, the source contribution. + for star in stars: + model = piff.Star(star.data.withNew(image=2 * star.image), star.fit) + updated = star.addPoisson(model) + use = star.weight.array != 0 + expected_variance = 1.0 / star.weight.array[use] + expected_variance += 2 * star.image.array[use] / star.data.gain_image.array[use] + np.testing.assert_allclose(1.0 / updated.weight.array[use], expected_variance) + np.testing.assert_array_equal(updated.weight.array[~use], 0) + np.testing.assert_array_equal(updated.addPoisson(model).weight.array, updated.weight.array) + + # Star.write omits gain images; InputFiles.load_images restores them from the source files. + saved_name = os.path.join('output', 'gain_stars.fits') + with FitsWriter.open(saved_name) as writer: + piff.Star.write(stars, writer, 'stars') + with FitsReader.open(saved_name) as fits_reader: + restored = piff.Star.read(fits_reader, 'stars') + assert all(star.data.gain_image is None for star in restored) + restored = reader.load_images(restored) + for original, loaded in zip(stars, restored): + assert loaded.data.gain_image == original.data.gain_image + np.testing.assert_array_equal(loaded.data.orig_weight.array, + original.data.orig_weight.array) + np.testing.assert_allclose(loaded.addPoisson().weight.array, + original.addPoisson().weight.array) + + # Gain filenames support dir, globs, and config references. + filename_config = dict(config) + filename_config['dir'] = 'output' + filename_config['image_file_name'] = 'gain_science.fits' + filename_config['cat_file_name'] = 'gain_cat.fits' + base = {'input': filename_config, 'gain_path': gain_name} + for filename in ['gain_ma*.fits', {'type': 'List', 'items': [gain_name]}, '@gain_path']: + filename_config['gain_file_name'] = filename + loaded_stars = piff.InputFiles(filename_config, base=base).makeStars() + assert len(loaded_stars) == len(stars) + for original, loaded in zip(stars, loaded_stars): + assert loaded.data.gain_image == original.data.gain_image + + # A single gain file can be reused across multiple science images. + multi_config = dict(config) + multi_config['image_file_name'] = [image_name] * 2 + multi_config['gain_file_name'] = gain_name + multi_stars = piff.InputFiles(multi_config).makeStars() + assert len(multi_stars) == 2 * len(stars) + for original, loaded in zip(stars * 2, multi_stars): + assert loaded.data.gain_image == original.data.gain_image + + # Gain extensions can vary by image using either an extension index or name. + multi_config.pop('gain_file_name') + multi_config['gain_ext'] = [2, 'GAIN'] + multi_stars = piff.InputFiles(multi_config).makeStars() + for original, loaded in zip(stars * 2, multi_stars): + assert loaded.data.gain_image == original.data.gain_image + + # Cannot combine gain image with scalar gain or gain_col. + for map_option in [{'gain_ext': 2}, {'gain_file_name': gain_name}]: + for value_option in [{'gain': 3.0}, {'gain_col': 'gain'}]: + np.testing.assert_raises(ValueError, piff.InputFiles, + dict(config, **map_option, **value_option)) + + # Gain files must exist, have a valid filename config, and match the image count. + for filename in ['output/missing_gain.fits', 17, 'input/test_input_image_*.fits']: + np.testing.assert_raises(ValueError, piff.InputFiles, dict(config, gain_file_name=filename)) + + # Unmasked gains must be finite and positive. + reader = piff.InputFiles(dict(config, gain_ext='GAIN')) + for bad_value in [0, -1, np.nan, np.inf]: + bad_gain = gain.copy() + bad_gain[50, 50] = bad_value + with fitsio.FITS(image_name, 'rw') as f: + f[2].write(bad_gain) + with np.testing.assert_raises(ValueError) as e: + reader.makeStars() + assert 'finite and positive' in str(e.exception) + + # An inconsistent gain that implies negative remaining variance masks the affected pixel. + bad_gain = gain.copy() + bad_gain[48, 39] = 0.001 + with fitsio.FITS(image_name, 'rw') as f: + f[2].write(bad_gain) + with CaptureLog() as cl: + bad_stars = reader.makeStars(logger=cl.logger) + assert bad_stars[1].weight(40, 49) == 0 + assert 'Masked 1 pixels with invalid variance' in cl.output + + # The gain image must be the same shape as the data image. + with fitsio.FITS(image_name, 'rw') as f: + f[2].reshape((64, 256)) + with np.testing.assert_raises(ValueError) as e: + reader.makeStars() + assert 'bounds' in str(e.exception) + @timer def test_stars(): """Test the input.makeStars function @@ -2510,7 +2681,7 @@ def test_sky(): 'use_partial' : True, } input = piff.InputFiles(config, logger=logger) - raw_image, _, _, _ = input.getRawImageData(0) + raw_image, _, _, _, _ = input.getRawImageData(0) raw_stars = input.makeStars(logger=logger) assert raw_image.array.shape == (1024, 1024) assert len(raw_stars) == 100 @@ -2523,7 +2694,7 @@ def test_sky(): 'sky_col' : 'sky', } input = piff.InputFiles(config, logger=logger) - image, _, _, extra_props = input.getRawImageData(0) + image, _, _, extra_props, _ = input.getRawImageData(0) stars = input.makeStars(logger=logger) np.testing.assert_allclose(image.array, raw_image.array) assert len(extra_props['sky']) == 100 @@ -2539,7 +2710,7 @@ def test_sky(): 'sky' : 7, } input = piff.InputFiles(config, logger=logger) - image, _, _, extra_props = input.getRawImageData(0) + image, _, _, extra_props, _ = input.getRawImageData(0) stars = input.makeStars(logger=logger) np.testing.assert_allclose(image.array, raw_image.array - 7) assert 'sky' not in extra_props @@ -2560,7 +2731,7 @@ def test_sky(): 'sky' : { 'type': 'ImageHeaderValue', 'key': 'SKYLEVEL' }, } input = piff.InputFiles(config, logger=logger) - image, _, _, extra_props = input.getRawImageData(0) + image, _, _, extra_props, _ = input.getRawImageData(0) stars = input.makeStars(logger=logger) with fitsio.FITS(image_file, 'r') as f: sky = np.float32(f[0].read_header()['SKYLEVEL']) @@ -2580,7 +2751,7 @@ def test_sky(): 'sky_file_name' : sky_file, } input = piff.InputFiles(config, logger=logger) - image, _, _, extra_props = input.getRawImageData(0) + image, _, _, extra_props, _ = input.getRawImageData(0) stars = input.makeStars(logger=logger) np.testing.assert_allclose(image.array, raw_image.array - sky32) assert 'sky' not in extra_props # No sky property in this case. @@ -2590,7 +2761,7 @@ def test_sky(): # Can provide an explicit extension, although the default works fine in this case. config['sky_ext'] = 1 input = piff.InputFiles(config, logger=logger) - image, _, _, extra_props = input.getRawImageData(0) + image, _, _, extra_props, _ = input.getRawImageData(0) stars = input.makeStars(logger=logger) np.testing.assert_allclose(image.array, raw_image.array - sky32) assert 'sky' not in extra_props @@ -2606,7 +2777,7 @@ def test_sky(): 'sky_file_name' : sky_file[6:], } input = piff.InputFiles(config, logger=logger) - image, _, _, extra_props = input.getRawImageData(0) + image, _, _, extra_props, _ = input.getRawImageData(0) stars = input.makeStars(logger=logger) np.testing.assert_allclose(image.array, raw_image.array - sky32) assert 'sky' not in extra_props @@ -2621,7 +2792,7 @@ def test_sky(): 'sky_file_name' : { 'type': 'List', 'items': [sky_file], }, } input = piff.InputFiles(config, logger=logger) - image, _, _, extra_props = input.getRawImageData(0) + image, _, _, extra_props, _ = input.getRawImageData(0) stars = input.makeStars(logger=logger) np.testing.assert_allclose(image.array, raw_image.array - sky32) assert 'sky' not in extra_props @@ -2637,7 +2808,7 @@ def test_sky(): 'sky' : 'median', } input = piff.InputFiles(config, logger=logger) - image, _, _, extra_props = input.getRawImageData(0) + image, _, _, extra_props, _ = input.getRawImageData(0) stars = input.makeStars(logger=logger) sky_med = np.median(raw_image.array) np.testing.assert_allclose(image.array, raw_image.array - sky_med) @@ -2714,7 +2885,7 @@ def test_sep_sky(): estimated = sep.Background(science, mask=masked).back() np.testing.assert_allclose(estimated[64:-64, 64:-64], background[64:-64, 64:-64], rtol=0.01) handler = piff.InputFiles(config) - image, weight, _, props = handler.getRawImageData(0) + image, weight, _, props, _ = handler.getRawImageData(0) np.testing.assert_allclose(image.array, science - estimated) assert 'sky' not in props assert np.ptp(estimated) > 10 @@ -2730,7 +2901,7 @@ def test_sep_sky(): file_config.pop('sky') file_config['sky_file_name'] = sky_name file_handler = piff.InputFiles(file_config) - file_image, file_weight, _, _ = file_handler.getRawImageData(0) + file_image, file_weight, _, _, _ = file_handler.getRawImageData(0) np.testing.assert_allclose(file_image.array, image.array) np.testing.assert_allclose(file_weight.array, weight.array) @@ -2767,7 +2938,7 @@ def test_sed_col(): } piff.StarData._sed_cache = {} input = piff.InputFiles(config, logger=logger) - _, _, image_pos, extra_props = input.getRawImageData(0) + _, _, image_pos, extra_props, _ = input.getRawImageData(0) assert not piff.StarData._sed_cache stars = input.makeStars(logger=logger) assert not piff.StarData._sed_cache @@ -2806,7 +2977,7 @@ def test_sed_col(): # With a sed_file_name dict, sed_col entries act as labels into the mapping. config3 = dict(config, sed_col='sed_label', sed_file_name='test_sed_map.yaml') input = piff.InputFiles(config3, logger=logger) - _, _, _, extra_props2 = input.getRawImageData(0) + _, _, _, extra_props2, _ = input.getRawImageData(0) seds2 = [star.data.sed_eff for star in input.makeStars(logger=logger)] assert 'sed_eff' not in extra_props2 assert seds2[0] is seds2[4] @@ -2867,7 +3038,7 @@ def test_single_sed(): }, } input = piff.InputFiles(config, logger=logger) - _, _, image_pos, extra_props = input.getRawImageData(0) + _, _, image_pos, extra_props, _ = input.getRawImageData(0) seds = [star.data.sed_eff for star in input.makeStars(logger=logger)] assert len(image_pos) == 100 assert len(seds) == 95 @@ -2886,7 +3057,7 @@ def test_single_sed(): # after forming sed * bandpass, which should take the len(wave) == 0 branch in _read_sed_file. config['sed_file_name'] = '1./wave' input = piff.InputFiles(config, logger=logger) - _, _, image_pos, extra_props = input.getRawImageData(0) + _, _, image_pos, extra_props, _ = input.getRawImageData(0) seds = [star.data.sed_eff for star in input.makeStars(logger=logger)] assert len(image_pos) == 100 assert len(seds) == 95 @@ -2907,7 +3078,7 @@ def test_single_sed(): } piff.StarData._sed_cache = {} input = piff.InputFiles(config, logger=logger) - _, _, _, props = input.getRawImageData(0) + _, _, _, props, _ = input.getRawImageData(0) seds = [star.data.sed_eff for star in input.makeStars(logger=logger)] assert len(seds) == 95 assert seds[0] is seds[1] @@ -3039,7 +3210,7 @@ def weighted_line_fit(wave, flux): # First default is no thinning. piff.StarData._sed_cache = {} input = piff.InputFiles(config, logger=logger) - _, _, _, props = input.getRawImageData(0) + _, _, _, props, _ = input.getRawImageData(0) seds = [star.data.sed_eff for star in input.makeStars(logger=logger)] sed = seds[0] assert seds[0] is seds[1] @@ -3056,7 +3227,7 @@ def weighted_line_fit(wave, flux): piff.StarData._sed_cache = {} thin_config = dict(config, sed_tol=0.1) input = piff.InputFiles(thin_config, logger=logger) - _, _, _, thin_props = input.getRawImageData(0) + _, _, _, thin_props, _ = input.getRawImageData(0) thin_seds = [star.data.sed_eff for star in input.makeStars(logger=logger)] thin_sed = thin_seds[0] assert thin_seds[0] is thin_seds[1] @@ -3075,7 +3246,7 @@ def weighted_line_fit(wave, flux): piff.StarData._sed_cache = {} sample_config = dict(config, sed_max_samples=2) input = piff.InputFiles(sample_config, logger=logger) - _, _, _, sample_props = input.getRawImageData(0) + _, _, _, sample_props, _ = input.getRawImageData(0) sample_seds = [star.data.sed_eff for star in input.makeStars(logger=logger)] sample_sed = sample_seds[0] assert sample_seds[0] is sample_seds[1] @@ -3098,7 +3269,7 @@ def weighted_line_fit(wave, flux): piff.StarData._sed_cache = {} combo_config = dict(config, sed_tol=0.1, sed_max_samples=4) input = piff.InputFiles(combo_config, logger=logger) - _, _, _, combo_props = input.getRawImageData(0) + _, _, _, combo_props, _ = input.getRawImageData(0) combo_seds = [star.data.sed_eff for star in input.makeStars(logger=logger)] combo_sed = combo_seds[0] assert combo_props['sed_tol'][0] == 0.1 @@ -3112,7 +3283,7 @@ def weighted_line_fit(wave, flux): piff.StarData._sed_cache = {} no_op_config = dict(config, sed_tol=0.1, sed_max_samples=100) input = piff.InputFiles(no_op_config, logger=logger) - _, _, _, no_op_props = input.getRawImageData(0) + _, _, _, no_op_props, _ = input.getRawImageData(0) no_op_seds = [star.data.sed_eff for star in input.makeStars(logger=logger)] no_op_sed = no_op_seds[0] assert no_op_props['sed_tol'][0] == 0.1 @@ -3325,6 +3496,7 @@ def test_input_bandpass(): test_chipnum() test_weight() test_lsst_weight() + test_gain_image() test_stars() test_select_min_sep() test_pointing() diff --git a/tests/test_pixel.py b/tests/test_pixel.py index c58f5d89..762ef63d 100644 --- a/tests/test_pixel.py +++ b/tests/test_pixel.py @@ -943,7 +943,7 @@ def test_single_image(): # Check image assert input.nimages == 1 - image1, _, image_pos, _ = input.getRawImageData(0) + image1, _, image_pos, _, _ = input.getRawImageData(0) np.testing.assert_equal(image1.array, image.array - sky_level) # Check catalog @@ -1636,7 +1636,7 @@ def test_color(): assert input.image_file_name == [image_file] assert input.cat_file_name == [cat_file] assert input.nimages == 1 - image1, _, image_pos, props = input.getRawImageData(0) + image1, _, image_pos, props, _ = input.getRawImageData(0) np.testing.assert_equal(image1.array, image.array) assert len(image_pos) == len(x_list) np.testing.assert_equal([pos.x for pos in image_pos], x_list) @@ -1959,10 +1959,11 @@ def test_too_small(): # This test comes directly from the bug report in issue #131 import pickle stars = pickle.load(open("input/stars_131.pickle", "rb")) - # This historical fixture predates the SED fields initialized by StarData.__init__. + # This historical fixture predates the SED and gain fields initialized by StarData.__init__. for star in stars: star.data.bandpass = None star.data._sed_eff = None + star.data.gain_image = None piffConfig = { 'type': "Simple", diff --git a/tests/test_simple.py b/tests/test_simple.py index 871ec11b..a40ed904 100644 --- a/tests/test_simple.py +++ b/tests/test_simple.py @@ -189,7 +189,7 @@ def test_single_image(): # Check image assert input.nimages == 1 - image1, _, image_pos, _ = input.getRawImageData(0) + image1, _, image_pos, _, _ = input.getRawImageData(0) np.testing.assert_equal(image1.array, image.array) # Check catalog @@ -205,7 +205,7 @@ def test_single_image(): 'stamp_size': 48 } input = piff.InputFiles(config, logger=logger) assert input.nimages == 1 - _, _, image_pos, _ = input.getRawImageData(0) + _, _, image_pos, _, _ = input.getRawImageData(0) assert len(image_pos) == 7 # Make star data diff --git a/tests/test_star.py b/tests/test_star.py index 7017e4cf..6c9c1d20 100644 --- a/tests/test_star.py +++ b/tests/test_star.py @@ -316,6 +316,34 @@ def test_add_poisson(): test = test.addPoisson(stardata1) np.testing.assert_allclose(1./test.weight.array, 1./weight.array + image.array/2) + # A spatial gain map supplies the gain separately at every pixel and survives Poisson updates. + yy, xx = np.indices(image.array.shape) + gain_image = galsim.Image(2.0 + 0.01 * xx + 0.02 * yy, bounds=image.bounds, wcs=image.wcs) + mapped = piff.StarData(image, image_pos, weight=weight, gain_image=gain_image) + test = mapped.addPoisson() + np.testing.assert_allclose(1.0 / test.weight.array, + 1.0 / weight.array + image.array / gain_image.array) + assert test.gain_image == gain_image + assert 'gain' not in test.properties + np.testing.assert_array_equal(test.addPoisson().weight.array, test.weight.array) + + # Explicit gains replace the stored gain source, with the same precedence as scalar gains. + scalar = test.addPoisson(gain=3.0) + assert scalar.gain_image is None + np.testing.assert_allclose(1.0 / scalar.weight.array, 1.0 / weight.array + image.array / 3.0) + remapped = scalar.addPoisson(gain=gain_image) + assert 'gain' not in remapped.properties + np.testing.assert_array_equal(remapped.weight.array, test.weight.array) + + # Pickle and copies preserve gain maps, bandpasses, and cached chromatic metadata together. + bandpass = galsim.Bandpass('1', wave_type='nm', blue_limit=400, red_limit=800) + sed = galsim.SED('1', wave_type='nm', flux_type='fphotons') + chromatic = mapped.withNew(bandpass=bandpass, _sed_eff=sed).addPoisson() + for copied in [chromatic.copy(), pickle.loads(pickle.dumps(chromatic))]: + assert copied.gain_image == gain_image + assert copied.bandpass == bandpass + assert copied.sed_eff == sed + # Error if signal is different shape small_image = galsim.Image(15,15, scale=0.25) stardata4 = piff.StarData(small_image, image_pos) From 59066d314ee93885da71376a8bb8f420d8422b2b Mon Sep 17 00:00:00 2001 From: Mike Jarvis Date: Mon, 2 Nov 2026 14:53:40 -0500 Subject: [PATCH 06/18] Have getRawImageData return a NamedTuple to simplify access --- piff/__init__.py | 2 +- piff/input.py | 33 ++++++-- tests/test_input.py | 191 ++++++++++++++++++++++++++++--------------- tests/test_pixel.py | 4 +- tests/test_simple.py | 6 +- 5 files changed, 159 insertions(+), 77 deletions(-) diff --git a/piff/__init__.py b/piff/__init__.py index cb8b46e0..8b2b313e 100644 --- a/piff/__init__.py +++ b/piff/__init__.py @@ -93,7 +93,7 @@ from .outliers import Outliers, ChisqOutliers, CentroidOutliers # Input handlers are named InputBlah where Blah is what they are called in the config file -from .input import Input, InputFiles +from .input import Input, InputFiles, RawImageData from .select import Select, FlagSelect, PropertiesSelect from .star import Star, StarData, StarFit from .star import set_shape_method, get_shape_method, get_shape_weight_fwhm diff --git a/piff/input.py b/piff/input.py index bb1ecca4..ba1db007 100644 --- a/piff/input.py +++ b/piff/input.py @@ -22,11 +22,29 @@ import os import galsim import yaml +from typing import NamedTuple from .util import run_multi from .star import Star, StarData from .config import LoggerWrapper +class RawImageData(NamedTuple): + """Image and catalog data returned by `InputFiles.getRawImageData`. + + Fields can be accessed by name or unpacked in the order listed below. + + :param image: Science image after image-level sky subtraction. + :param weight: Weight image after masking and any source-variance removal. + :param image_pos: List of catalog positions in image coordinates. + :param extra_props: Dict of additional catalog properties, with an array for each property. + :param gain_image: Per-pixel gain image, or None when no gain image was supplied. + """ + image: galsim.Image + weight: galsim.Image + image_pos: list + extra_props: dict + gain_image: galsim.Image | None + class Input(object): """The base class for handling inputs for building a Piff model. @@ -879,10 +897,10 @@ def load_images(self, stars, logger=None): weight_images = {} gain_images = {} for image_num in range(self.nimages): - image, weight, _, _, gain_image = self.getRawImageData(image_num, logger) - images[self.chipnums[image_num]] = image - weight_images[self.chipnums[image_num]] = weight - gain_images[self.chipnums[image_num]] = gain_image + data = self.getRawImageData(image_num, logger) + images[self.chipnums[image_num]] = data.image + weight_images[self.chipnums[image_num]] = data.weight + gain_images[self.chipnums[image_num]] = data.gain_image loaded_stars = [] for star in stars: @@ -906,7 +924,9 @@ def getRawImageData(self, image_num, logger=None): :param image_num: The index of the image to read. :param logger: A logger object for logging debug info. [default: None] - :returns: image, weight, image_pos, extra_props, gain_image. + :returns: A `RawImageData` named tuple with fields image, weight, image_pos, + extra_props, and gain_image. Fields can be accessed by name or unpacked + in that order. """ self.base['index_key'] = 'image_num' self.base['image_num'] = image_num @@ -973,7 +993,8 @@ def _getRawImageData(cls, image_kwargs, cat_kwargs, wcs, logger.warning("Masked %d pixels with invalid variance after removing source noise", added_masks) - return image, weight, image_pos, extra_props, gain_image + return RawImageData(image=image, weight=weight, image_pos=image_pos, + extra_props=extra_props, gain_image=gain_image) @classmethod def _makeStarsFromImage(cls, image_kwargs, cat_kwargs, wcs, chipnum, diff --git a/tests/test_input.py b/tests/test_input.py index cf0d17a3..2de1b1b9 100644 --- a/tests/test_input.py +++ b/tests/test_input.py @@ -172,27 +172,34 @@ def test_basic(): } input = piff.InputFiles(config, logger=logger) assert input.nimages == 1 - _, _, image_pos, _, _ = input.getRawImageData(0) + # Raw image results support both tuple unpacking and access by field name. + raw_data = input.getRawImageData(0) + image, weight, image_pos, extra_props, gain_image = raw_data + assert raw_data.image is image + assert raw_data.weight is weight + assert raw_data.image_pos is image_pos + assert raw_data.extra_props is extra_props + assert raw_data.gain_image is gain_image is None assert len(image_pos) == 100 # Check alternate file suffix for catalog. config['cat_file_name'] = 'test_input_cat_00.fit' input = piff.InputFiles(config, logger=logger) assert input.nimages == 1 - _, _, image_pos2, _, _ = input.getRawImageData(0) + image_pos2 = input.getRawImageData(0).image_pos np.testing.assert_array_equal(image_pos, image_pos2) # Check parquet files config['cat_file_name'] = 'test_input_cat_00.parquet' input = piff.InputFiles(config, logger=logger) assert input.nimages == 1 - _, _, image_pos2, _, _ = input.getRawImageData(0) + image_pos2 = input.getRawImageData(0).image_pos np.testing.assert_array_equal(image_pos, image_pos2) config['cat_file_name'] = 'test_input_cat_00.pq' input = piff.InputFiles(config, logger=logger) assert input.nimages == 1 - _, _, image_pos2, _, _ = input.getRawImageData(0) + image_pos2 = input.getRawImageData(0).image_pos np.testing.assert_array_equal(image_pos, image_pos2) config['cat_file_name'] = 'test_input_cat_00.invalid' @@ -206,7 +213,7 @@ def test_basic(): } input = piff.InputFiles(config, logger=logger) assert input.nimages == 1 - _, _, image_pos, _, _ = input.getRawImageData(0) + image_pos = input.getRawImageData(0).image_pos assert len(image_pos) == 100 # 3 images in a list @@ -220,7 +227,7 @@ def test_basic(): input = piff.InputFiles(config, logger=logger) assert input.nimages == 3 for i in range(3): - _, _, image_pos, _, _ = input.getRawImageData(i) + image_pos = input.getRawImageData(i).image_pos assert len(image_pos) == 100 # Again without dir. @@ -233,7 +240,7 @@ def test_basic(): input = piff.InputFiles(config, logger=logger) assert input.nimages == 3 for i in range(3): - _, _, image_pos, _, _ = input.getRawImageData(i) + image_pos = input.getRawImageData(i).image_pos assert len(image_pos) == 100 # 3 images using glob @@ -247,7 +254,7 @@ def test_basic(): input = piff.InputFiles(config, logger=logger) assert input.nimages == 3 for i in range(3): - _, _, image_pos, _, _ = input.getRawImageData(i) + image_pos = input.getRawImageData(i).image_pos assert len(image_pos) == 100 # Filename shorthand must follow the same per-image parsing as explicit dicts. @@ -298,7 +305,7 @@ def test_basic(): assert "input.nstars is deprecated" in cl.output assert input.nimages == 3 for i in range(3): - _, _, image_pos, _, _ = input.getRawImageData(i) + image_pos = input.getRawImageData(i).image_pos assert len(image_pos) == 37 # input.nstars can still vary by image with the old per-catalog behavior. @@ -306,7 +313,7 @@ def test_basic(): input = piff.InputFiles(config) assert input.nimages == 3 for i in range(3): - _, _, image_pos, _, _ = input.getRawImageData(i) + image_pos = input.getRawImageData(i).image_pos if i == 0: assert len(image_pos) == 40 elif i == 1: @@ -457,7 +464,9 @@ def test_extensions(): current = dict(config) current.pop('sky_file_name') handler = piff.InputFiles(current) - image, weight, _, _, _ = handler.getRawImageData(0) + raw_data = handler.getRawImageData(0) + image = raw_data.image + weight = raw_data.weight np.testing.assert_array_equal(image.array, science - sky) np.testing.assert_array_equal(weight.array, np.where(mask, 0, 5)) @@ -481,7 +490,9 @@ def test_extensions(): current['weight_hdu'] = '$@input.image_hdu + 2' current.pop('weight_ext') handler = piff.InputFiles(current, base={'input': current}) - image, weight, _, _, _ = handler.getRawImageData(0) + raw_data = handler.getRawImageData(0) + image = raw_data.image + weight = raw_data.weight np.testing.assert_array_equal(image.array, science - sky) np.testing.assert_array_equal(weight.array, np.where(mask, 0, 5)) @@ -509,7 +520,9 @@ def test_extensions(): current['weight_ext'] = {'type': 'List_str', 'items': ['WEIGHT', 'WEIGHT']} handler = piff.InputFiles(current) for i in range(2): - image, weight, _, _, _ = handler.getRawImageData(i) + raw_data = handler.getRawImageData(i) + image = raw_data.image + weight = raw_data.weight np.testing.assert_array_equal(image.array, science + 10 * i - sky) np.testing.assert_array_equal(weight.array, np.where(mask, 0, 5)) @@ -710,7 +723,7 @@ def test_cols(): } input = piff.InputFiles(config, logger=logger) assert input.nimages == 1 - _, _, image_pos, _, _ = input.getRawImageData(0) + image_pos = input.getRawImageData(0).image_pos assert len(image_pos) == 100 # Can do ra, dec instead of x, y @@ -725,7 +738,7 @@ def test_cols(): } input2 = piff.InputFiles(config, logger=logger) assert input2.nimages == 1 - _, _, image_pos2, _, _ = input2.getRawImageData(0) + image_pos2 = input2.getRawImageData(0).image_pos print('input.image_pos = ',image_pos) print('input2.image_pos = ',image_pos2) assert len(image_pos2) == 100 @@ -888,7 +901,9 @@ def test_cols(): # gain can also be given explicitly as an ImageHeaderValue. config['gain'] = { 'type': 'ImageHeaderValue', 'key': 'GAIN_A' } input = piff.InputFiles(config, logger=logger) - _, _, image_pos, props, _ = input.getRawImageData(0) + raw_data = input.getRawImageData(0) + image_pos = raw_data.image_pos + props = raw_data.extra_props gain_list = props['gain'] assert len(image_pos) == 100 assert len(gain_list) == 100 @@ -915,7 +930,9 @@ def test_cols(): 'satur' : 1890, } input = piff.InputFiles(config, logger=logger) - _, _, image_pos, props, _ = input.getRawImageData(0) + raw_data = input.getRawImageData(0) + image_pos = raw_data.image_pos + props = raw_data.extra_props satur = props['satur'][0] assert satur == 1890 assert len(image_pos) == 100 @@ -929,7 +946,9 @@ def test_cols(): 'satur' : '$1800 + 90', } input = piff.InputFiles(config, logger=logger) - _, _, image_pos, props, _ = input.getRawImageData(0) + raw_data = input.getRawImageData(0) + image_pos = raw_data.image_pos + props = raw_data.extra_props satur = props['satur'][0] assert satur == 1890 assert len(image_pos) == 100 @@ -943,7 +962,9 @@ def test_cols(): 'satur' : { 'type': 'ImageHeaderValue', 'key': 'SATURAT' }, } input = piff.InputFiles(config, logger=logger) - _, _, image_pos, props, _ = input.getRawImageData(0) + raw_data = input.getRawImageData(0) + image_pos = raw_data.image_pos + props = raw_data.extra_props satur = props['satur'][0] assert satur == 1890 assert len(image_pos) == 100 @@ -959,7 +980,9 @@ def test_cols(): } input = piff.InputFiles(config) with CaptureLog() as cl: - _, _, image_pos, props, _ = input.getRawImageData(0, logger=cl.logger) + raw_data = input.getRawImageData(0, logger=cl.logger) + image_pos = raw_data.image_pos + props = raw_data.extra_props assert "Using a bare FITS header key for satur is deprecated" in cl.output satur = props['satur'][0] assert satur == 1890 @@ -974,7 +997,7 @@ def test_cols(): 'skip_flag' : 4 } input = piff.InputFiles(config, logger=logger) - _, _, image_pos, _, _ = input.getRawImageData(0) + image_pos = input.getRawImageData(0).image_pos assert input.nimages == 1 print('len = ',len(image_pos)) assert len(image_pos) == 80 @@ -988,7 +1011,7 @@ def test_cols(): 'use_flag' : 1 } input = piff.InputFiles(config, logger=logger) - _, _, image_pos, _, _ = input.getRawImageData(0) + image_pos = input.getRawImageData(0).image_pos print('len = ',len(image_pos)) assert len(image_pos) == 85 @@ -1002,7 +1025,7 @@ def test_cols(): 'use_flag' : '$2**0', } input = piff.InputFiles(config, logger=logger) - _, _, image_pos, _, _ = input.getRawImageData(0) + image_pos = input.getRawImageData(0).image_pos print('len = ',len(image_pos)) assert len(image_pos) == 68 @@ -1014,7 +1037,7 @@ def test_cols(): 'flag_col' : 'flag', } input = piff.InputFiles(config, logger=logger) - _, _, image_pos, _, _ = input.getRawImageData(0) + image_pos = input.getRawImageData(0).image_pos print('len = ',len(image_pos)) assert len(image_pos) == 12 @@ -1028,7 +1051,7 @@ def test_cols(): 'use_flag' : 128 } input = piff.InputFiles(config, logger=logger) - _, _, image_pos, _, _ = input.getRawImageData(0) + image_pos = input.getRawImageData(0).image_pos print('len = ',len(image_pos)) assert len(image_pos) == 0 with np.testing.assert_raises(RuntimeError): @@ -1045,12 +1068,12 @@ def test_cols(): 'cat_file_name' : 'test_input_cat_00.fits', } input = piff.InputFiles(dict(property_cols=['gr_color'], **base_config), logger=logger) - _, _, _, props_dict, _ = input.getRawImageData(0) + props_dict = input.getRawImageData(0).extra_props assert len(props_dict['gr_color']) == 100 np.testing.assert_array_equal(props_dict['gr_color'], gr_color) input = piff.InputFiles(dict(property_cols=['gr_color', 'rz_color'], **base_config), logger=logger) - _, _, _, props_dict, _ = input.getRawImageData(0) + props_dict = input.getRawImageData(0).extra_props print(props_dict) assert len(props_dict['gr_color']) == 100 assert len(props_dict['rz_color']) == 100 @@ -1076,11 +1099,11 @@ def test_cols(): 'property_cols' : ['gr_color'], } input = piff.InputFiles(config, logger=logger) - _, _, _, props_dict, _ = input.getRawImageData(0) + props_dict = input.getRawImageData(0).extra_props np.testing.assert_array_equal(props_dict['const_prop'], [1.5] * 100) np.testing.assert_array_equal(props_dict['image_id'], [10] * 100) np.testing.assert_allclose(props_dict['gr_plus_one'], gr_color + 1) - _, _, _, props_dict, _ = input.getRawImageData(1) + props_dict = input.getRawImageData(1).extra_props np.testing.assert_array_equal(props_dict['const_prop'], [1.5] * 100) np.testing.assert_array_equal(props_dict['image_id'], [11] * 100) @@ -1561,7 +1584,7 @@ def test_boolarray(): } input = piff.InputFiles(config, logger=logger) assert input.nimages == 1 - _, _, image_pos, _, _ = input.getRawImageData(0) + image_pos = input.getRawImageData(0).image_pos print('len = ',len(image_pos)) assert len(image_pos) == 80 @@ -1674,7 +1697,7 @@ def test_weight(): } input = piff.InputFiles(config, logger=logger) assert input.nimages == 1 - _, weight, _, _, _ = input.getRawImageData(0) + weight = input.getRawImageData(0).weight assert weight.array.shape == (1024, 1024) np.testing.assert_almost_equal(weight.array, 32.**-1) @@ -1687,7 +1710,7 @@ def test_weight(): } input = piff.InputFiles(config, logger=logger) assert input.nimages == 1 - _, weight, _, _, _ = input.getRawImageData(0) + weight = input.getRawImageData(0).weight assert weight.array.shape == (1024, 1024) np.testing.assert_almost_equal(weight.array, 34.**-1) @@ -1696,7 +1719,7 @@ def test_weight(): input = piff.InputFiles(config) assert input.nimages == 1 with CaptureLog() as cl: - _, weight, _, _, _ = input.getRawImageData(0, logger=cl.logger) + weight = input.getRawImageData(0, logger=cl.logger).weight assert "Using a bare FITS header key for noise is deprecated" in cl.output assert weight.array.shape == (1024, 1024) np.testing.assert_almost_equal(weight.array, 34.**-1) @@ -1717,14 +1740,14 @@ def test_weight(): } input = piff.InputFiles(config, logger=logger) assert input.nimages == 1 - _, weight, _, _, _ = input.getRawImageData(0) + weight = input.getRawImageData(0).weight assert weight.array.shape == (1024, 1024) np.testing.assert_almost_equal(weight.array, expected_noise**-1) config['badpix_ext'] = 6 input = piff.InputFiles(config, logger=logger) assert input.nimages == 1 - _, weight, _, _, _ = input.getRawImageData(0) + weight = input.getRawImageData(0).weight assert weight.array.shape == (1024, 1024) np.testing.assert_almost_equal(weight.array, expected_noise**-1) @@ -1734,7 +1757,7 @@ def test_weight(): config['badpix_ext'] = 7 # badpix > 0 input = piff.InputFiles(config, logger=logger) assert input.nimages == 1 - _, weight, _, _, _ = input.getRawImageData(0) + weight = input.getRawImageData(0).weight assert weight.array.shape == (1024, 1024) np.testing.assert_almost_equal(weight.array, 0.) @@ -1742,7 +1765,7 @@ def test_weight(): config['badpix_ext'] = 2 input = piff.InputFiles(config, logger=logger) assert input.nimages == 1 - _, weight, _, _, _ = input.getRawImageData(0) + weight = input.getRawImageData(0).weight assert weight.array.shape == (1024, 1024) np.testing.assert_almost_equal(weight.array, 0.) @@ -1750,7 +1773,7 @@ def test_weight(): config['badpix_ext'] = 9 # Odd cols are > 0 input = piff.InputFiles(config, logger=logger) assert input.nimages == 1 - _, weight, _, _, _ = input.getRawImageData(0) + weight = input.getRawImageData(0).weight assert weight.array.shape == (1024, 1024) np.testing.assert_almost_equal(weight.array, 0.) @@ -1761,7 +1784,7 @@ def test_weight(): config['badpix_ext'] = 0 input = piff.InputFiles(config, logger=logger) assert input.nimages == 1 - _, weight, _, _, _ = input.getRawImageData(0) + weight = input.getRawImageData(0).weight assert weight.array.shape == (1024, 1024) np.testing.assert_almost_equal(weight.array, 0.) @@ -1771,19 +1794,19 @@ def test_weight(): config['weight_ext'] = 4 input = piff.InputFiles(config) with CaptureLog() as cl: - _, weight, _, _, _ = input.getRawImageData(0, logger=cl.logger) + weight = input.getRawImageData(0, logger=cl.logger).weight assert 'Warning: weight map has invalid negative-valued pixels.' in cl.output # If some input values are zero, they can be treated as bad pixels with badpix_zeros del config['weight_ext'] config['badpix_ext'] = 9 input = piff.InputFiles(config, logger=logger) - _, weight, _, _, _ = input.getRawImageData(0) + weight = input.getRawImageData(0).weight del config['badpix_ext'] config['image_ext'] = 11 config['badpix_zeros'] = True input = piff.InputFiles(config, logger=logger) - _, weight2, _, _, _ = input.getRawImageData(0) + weight2 = input.getRawImageData(0).weight np.testing.assert_array_equal(weight.array, weight2.array) # One image file with multiple HDUs should be treated as multiple images. @@ -1835,12 +1858,16 @@ def test_weight(): assert input.image_kwargs[1]['badpix_file_name'] == 'input/test_input_badpix_00.fits' expected_weight0 = fitsio.read('input/test_input_weight_00.fits', ext=0) expected_weight0[1::2, :] = 0 - _, weight, image_pos, _, _ = input.getRawImageData(0) + raw_data = input.getRawImageData(0) + weight = raw_data.weight + image_pos = raw_data.image_pos assert len(image_pos) == 100 np.testing.assert_allclose(weight.array, expected_weight0) expected_weight1 = fitsio.read('input/test_input_weight_00.fits', ext=1) expected_weight1[1::2, :] = 0 - _, weight, image_pos, _, _ = input.getRawImageData(1) + raw_data = input.getRawImageData(1) + weight = raw_data.weight + image_pos = raw_data.image_pos assert len(image_pos) == 100 np.testing.assert_allclose(weight.array, expected_weight1) @@ -1855,10 +1882,14 @@ def test_weight(): assert input.image_kwargs[1]['weight_file_name'] == 'input/test_input_weight_00.fits' assert input.image_kwargs[0]['badpix_file_name'] == 'input/test_input_badpix_00.fits' assert input.image_kwargs[1]['badpix_file_name'] == 'input/test_input_badpix_00.fits' - _, weight, image_pos, _, _ = input.getRawImageData(0) + raw_data = input.getRawImageData(0) + weight = raw_data.weight + image_pos = raw_data.image_pos assert len(image_pos) == 100 np.testing.assert_allclose(weight.array, expected_weight0) - _, weight, image_pos, _, _ = input.getRawImageData(1) + raw_data = input.getRawImageData(1) + weight = raw_data.weight + image_pos = raw_data.image_pos assert len(image_pos) == 100 np.testing.assert_allclose(weight.array, expected_weight1) @@ -2005,7 +2036,9 @@ def test_gain_image(): for options in [{'gain_ext': 2}, {'gain_ext': 'GAIN'}, {'gain_file_name': gain_name}, {'gain_file_name': image_name, 'gain_ext': 'GAIN'}]: reader = piff.InputFiles(dict(config, **options)) - _, _, _, props, gain_image = reader.getRawImageData(0) + raw_data = reader.getRawImageData(0) + props = raw_data.extra_props + gain_image = raw_data.gain_image np.testing.assert_array_equal(gain_image.array, gain) assert 'gain' not in props stars = reader.makeStars() @@ -2681,7 +2714,7 @@ def test_sky(): 'use_partial' : True, } input = piff.InputFiles(config, logger=logger) - raw_image, _, _, _, _ = input.getRawImageData(0) + raw_image = input.getRawImageData(0).image raw_stars = input.makeStars(logger=logger) assert raw_image.array.shape == (1024, 1024) assert len(raw_stars) == 100 @@ -2694,7 +2727,9 @@ def test_sky(): 'sky_col' : 'sky', } input = piff.InputFiles(config, logger=logger) - image, _, _, extra_props, _ = input.getRawImageData(0) + raw_data = input.getRawImageData(0) + image = raw_data.image + extra_props = raw_data.extra_props stars = input.makeStars(logger=logger) np.testing.assert_allclose(image.array, raw_image.array) assert len(extra_props['sky']) == 100 @@ -2710,7 +2745,9 @@ def test_sky(): 'sky' : 7, } input = piff.InputFiles(config, logger=logger) - image, _, _, extra_props, _ = input.getRawImageData(0) + raw_data = input.getRawImageData(0) + image = raw_data.image + extra_props = raw_data.extra_props stars = input.makeStars(logger=logger) np.testing.assert_allclose(image.array, raw_image.array - 7) assert 'sky' not in extra_props @@ -2731,7 +2768,9 @@ def test_sky(): 'sky' : { 'type': 'ImageHeaderValue', 'key': 'SKYLEVEL' }, } input = piff.InputFiles(config, logger=logger) - image, _, _, extra_props, _ = input.getRawImageData(0) + raw_data = input.getRawImageData(0) + image = raw_data.image + extra_props = raw_data.extra_props stars = input.makeStars(logger=logger) with fitsio.FITS(image_file, 'r') as f: sky = np.float32(f[0].read_header()['SKYLEVEL']) @@ -2751,7 +2790,9 @@ def test_sky(): 'sky_file_name' : sky_file, } input = piff.InputFiles(config, logger=logger) - image, _, _, extra_props, _ = input.getRawImageData(0) + raw_data = input.getRawImageData(0) + image = raw_data.image + extra_props = raw_data.extra_props stars = input.makeStars(logger=logger) np.testing.assert_allclose(image.array, raw_image.array - sky32) assert 'sky' not in extra_props # No sky property in this case. @@ -2761,7 +2802,9 @@ def test_sky(): # Can provide an explicit extension, although the default works fine in this case. config['sky_ext'] = 1 input = piff.InputFiles(config, logger=logger) - image, _, _, extra_props, _ = input.getRawImageData(0) + raw_data = input.getRawImageData(0) + image = raw_data.image + extra_props = raw_data.extra_props stars = input.makeStars(logger=logger) np.testing.assert_allclose(image.array, raw_image.array - sky32) assert 'sky' not in extra_props @@ -2777,7 +2820,9 @@ def test_sky(): 'sky_file_name' : sky_file[6:], } input = piff.InputFiles(config, logger=logger) - image, _, _, extra_props, _ = input.getRawImageData(0) + raw_data = input.getRawImageData(0) + image = raw_data.image + extra_props = raw_data.extra_props stars = input.makeStars(logger=logger) np.testing.assert_allclose(image.array, raw_image.array - sky32) assert 'sky' not in extra_props @@ -2792,7 +2837,9 @@ def test_sky(): 'sky_file_name' : { 'type': 'List', 'items': [sky_file], }, } input = piff.InputFiles(config, logger=logger) - image, _, _, extra_props, _ = input.getRawImageData(0) + raw_data = input.getRawImageData(0) + image = raw_data.image + extra_props = raw_data.extra_props stars = input.makeStars(logger=logger) np.testing.assert_allclose(image.array, raw_image.array - sky32) assert 'sky' not in extra_props @@ -2808,7 +2855,9 @@ def test_sky(): 'sky' : 'median', } input = piff.InputFiles(config, logger=logger) - image, _, _, extra_props, _ = input.getRawImageData(0) + raw_data = input.getRawImageData(0) + image = raw_data.image + extra_props = raw_data.extra_props stars = input.makeStars(logger=logger) sky_med = np.median(raw_image.array) np.testing.assert_allclose(image.array, raw_image.array - sky_med) @@ -2901,7 +2950,9 @@ def test_sep_sky(): file_config.pop('sky') file_config['sky_file_name'] = sky_name file_handler = piff.InputFiles(file_config) - file_image, file_weight, _, _, _ = file_handler.getRawImageData(0) + raw_data = file_handler.getRawImageData(0) + file_image = raw_data.image + file_weight = raw_data.weight np.testing.assert_allclose(file_image.array, image.array) np.testing.assert_allclose(file_weight.array, weight.array) @@ -2938,7 +2989,9 @@ def test_sed_col(): } piff.StarData._sed_cache = {} input = piff.InputFiles(config, logger=logger) - _, _, image_pos, extra_props, _ = input.getRawImageData(0) + raw_data = input.getRawImageData(0) + image_pos = raw_data.image_pos + extra_props = raw_data.extra_props assert not piff.StarData._sed_cache stars = input.makeStars(logger=logger) assert not piff.StarData._sed_cache @@ -2977,7 +3030,7 @@ def test_sed_col(): # With a sed_file_name dict, sed_col entries act as labels into the mapping. config3 = dict(config, sed_col='sed_label', sed_file_name='test_sed_map.yaml') input = piff.InputFiles(config3, logger=logger) - _, _, _, extra_props2, _ = input.getRawImageData(0) + extra_props2 = input.getRawImageData(0).extra_props seds2 = [star.data.sed_eff for star in input.makeStars(logger=logger)] assert 'sed_eff' not in extra_props2 assert seds2[0] is seds2[4] @@ -3038,7 +3091,9 @@ def test_single_sed(): }, } input = piff.InputFiles(config, logger=logger) - _, _, image_pos, extra_props, _ = input.getRawImageData(0) + raw_data = input.getRawImageData(0) + image_pos = raw_data.image_pos + extra_props = raw_data.extra_props seds = [star.data.sed_eff for star in input.makeStars(logger=logger)] assert len(image_pos) == 100 assert len(seds) == 95 @@ -3057,7 +3112,9 @@ def test_single_sed(): # after forming sed * bandpass, which should take the len(wave) == 0 branch in _read_sed_file. config['sed_file_name'] = '1./wave' input = piff.InputFiles(config, logger=logger) - _, _, image_pos, extra_props, _ = input.getRawImageData(0) + raw_data = input.getRawImageData(0) + image_pos = raw_data.image_pos + extra_props = raw_data.extra_props seds = [star.data.sed_eff for star in input.makeStars(logger=logger)] assert len(image_pos) == 100 assert len(seds) == 95 @@ -3078,7 +3135,7 @@ def test_single_sed(): } piff.StarData._sed_cache = {} input = piff.InputFiles(config, logger=logger) - _, _, _, props, _ = input.getRawImageData(0) + props = input.getRawImageData(0).extra_props seds = [star.data.sed_eff for star in input.makeStars(logger=logger)] assert len(seds) == 95 assert seds[0] is seds[1] @@ -3210,7 +3267,7 @@ def weighted_line_fit(wave, flux): # First default is no thinning. piff.StarData._sed_cache = {} input = piff.InputFiles(config, logger=logger) - _, _, _, props, _ = input.getRawImageData(0) + props = input.getRawImageData(0).extra_props seds = [star.data.sed_eff for star in input.makeStars(logger=logger)] sed = seds[0] assert seds[0] is seds[1] @@ -3227,7 +3284,7 @@ def weighted_line_fit(wave, flux): piff.StarData._sed_cache = {} thin_config = dict(config, sed_tol=0.1) input = piff.InputFiles(thin_config, logger=logger) - _, _, _, thin_props, _ = input.getRawImageData(0) + thin_props = input.getRawImageData(0).extra_props thin_seds = [star.data.sed_eff for star in input.makeStars(logger=logger)] thin_sed = thin_seds[0] assert thin_seds[0] is thin_seds[1] @@ -3246,7 +3303,7 @@ def weighted_line_fit(wave, flux): piff.StarData._sed_cache = {} sample_config = dict(config, sed_max_samples=2) input = piff.InputFiles(sample_config, logger=logger) - _, _, _, sample_props, _ = input.getRawImageData(0) + sample_props = input.getRawImageData(0).extra_props sample_seds = [star.data.sed_eff for star in input.makeStars(logger=logger)] sample_sed = sample_seds[0] assert sample_seds[0] is sample_seds[1] @@ -3269,7 +3326,7 @@ def weighted_line_fit(wave, flux): piff.StarData._sed_cache = {} combo_config = dict(config, sed_tol=0.1, sed_max_samples=4) input = piff.InputFiles(combo_config, logger=logger) - _, _, _, combo_props, _ = input.getRawImageData(0) + combo_props = input.getRawImageData(0).extra_props combo_seds = [star.data.sed_eff for star in input.makeStars(logger=logger)] combo_sed = combo_seds[0] assert combo_props['sed_tol'][0] == 0.1 @@ -3283,7 +3340,7 @@ def weighted_line_fit(wave, flux): piff.StarData._sed_cache = {} no_op_config = dict(config, sed_tol=0.1, sed_max_samples=100) input = piff.InputFiles(no_op_config, logger=logger) - _, _, _, no_op_props, _ = input.getRawImageData(0) + no_op_props = input.getRawImageData(0).extra_props no_op_seds = [star.data.sed_eff for star in input.makeStars(logger=logger)] no_op_sed = no_op_seds[0] assert no_op_props['sed_tol'][0] == 0.1 diff --git a/tests/test_pixel.py b/tests/test_pixel.py index 762ef63d..8821185c 100644 --- a/tests/test_pixel.py +++ b/tests/test_pixel.py @@ -943,7 +943,9 @@ def test_single_image(): # Check image assert input.nimages == 1 - image1, _, image_pos, _, _ = input.getRawImageData(0) + raw_data = input.getRawImageData(0) + image1 = raw_data.image + image_pos = raw_data.image_pos np.testing.assert_equal(image1.array, image.array - sky_level) # Check catalog diff --git a/tests/test_simple.py b/tests/test_simple.py index a40ed904..ba7a1681 100644 --- a/tests/test_simple.py +++ b/tests/test_simple.py @@ -189,7 +189,9 @@ def test_single_image(): # Check image assert input.nimages == 1 - image1, _, image_pos, _, _ = input.getRawImageData(0) + raw_data = input.getRawImageData(0) + image1 = raw_data.image + image_pos = raw_data.image_pos np.testing.assert_equal(image1.array, image.array) # Check catalog @@ -205,7 +207,7 @@ def test_single_image(): 'stamp_size': 48 } input = piff.InputFiles(config, logger=logger) assert input.nimages == 1 - _, _, image_pos, _, _ = input.getRawImageData(0) + image_pos = input.getRawImageData(0).image_pos assert len(image_pos) == 7 # Make star data From 98d980b410800393a2adcbae6b8e55379fd5500c Mon Sep 17 00:00:00 2001 From: Mike Jarvis Date: Mon, 2 Nov 2026 15:22:01 -0500 Subject: [PATCH 07/18] Make sure NaN and Inf in the input data are cleared --- piff/input.py | 7 +++++++ tests/test_input.py | 27 +++++++++++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/piff/input.py b/piff/input.py index ba1db007..c4dc1b2c 100644 --- a/piff/input.py +++ b/piff/input.py @@ -1256,6 +1256,13 @@ def readImage(cls, image_file_name, image_ext, weight_file_name, weight_ext, image_file_name) weight.array[badpix.array != 0] = 0 + # Any Inf or NaN pixels in the science image should also be given weight=0. + # Additionally, set the value to 0, so downstream processing that does math like + # weight * image doesn't get NaNs in the calculation. + nonfinite = ~np.isfinite(image.array) + weight.array[nonfinite] = 0 + image.array[nonfinite] = 0 + sky_image = cls._read_sky(image, weight, sky, sky_file_name, sky_ext, logger) if sky_image is not None: image -= sky_image diff --git a/tests/test_input.py b/tests/test_input.py index 2de1b1b9..761e0443 100644 --- a/tests/test_input.py +++ b/tests/test_input.py @@ -1893,6 +1893,33 @@ def test_weight(): assert len(image_pos) == 100 np.testing.assert_allclose(weight.array, expected_weight1) + # Nonfinite science pixels are masked and cleared + science = galsim.fits.read('input/test_input_image_00.fits').array.astype(float) + science[30, 30:33] = [np.nan, np.inf, -np.inf] + badpix = np.zeros(science.shape, dtype=np.int16) + badpix[30, 30] = 1 + badpix[40, 40] = 1 + weight = np.ones(science.shape) + file_name = os.path.join('output', 'nonfinite_science.fits') + with fitsio.FITS(file_name, 'rw', clobber=True) as f: + f.write(science) + f.write(weight) + f.write(badpix) + config = { + 'image_file_name': file_name, + 'cat_file_name': 'input/test_input_cat_00.fits', + 'weight_ext': 1, + 'badpix_ext': 2, + 'sky': 3.0, + } + raw_data = piff.InputFiles(config).getRawImageData(0) + expected_image = science - 3.0 + expected_image[30, 30:33] = 0 - 3.0 # The sky subtraction happens after they are set to 0. + expected_weight = weight.copy() + expected_weight[30, 30:33] = 0 + expected_weight[40, 40] = 0 + np.testing.assert_array_equal(raw_data.image.array, expected_image) + np.testing.assert_array_equal(raw_data.weight.array, expected_weight) @timer def test_lsst_weight(): From fe1f6391a8f671cd8ab929791ce7ea93bc6a2600 Mon Sep 17 00:00:00 2001 From: Mike Jarvis Date: Mon, 2 Nov 2026 15:23:15 -0500 Subject: [PATCH 08/18] Add the devel script I've been using to convert asdf to fits --- devel/roman/asdf_to_fits.py | 498 ++++++++++++++++++++++++++++++++++++ 1 file changed, 498 insertions(+) create mode 100644 devel/roman/asdf_to_fits.py diff --git a/devel/roman/asdf_to_fits.py b/devel/roman/asdf_to_fits.py new file mode 100644 index 00000000..9697e1bb --- /dev/null +++ b/devel/roman/asdf_to_fits.py @@ -0,0 +1,498 @@ +#!/usr/bin/env python3 +"""Convert calibrated Roman ASDF images to ordinary multi-extension FITS. + +Simple usage +------------ + +python asdf_to_fits.py path/to/*.asdf + +This creates fits files with the same name, but a .fits extension alongside the asdf files. + +Options: + + --output-dir selects a different output directory for the fits files. + --no-wcs skips the WCS conversion and does not put WCS information into the FITS files. + --gain-map adds the GAIN HDU to the output. + --background-weights uses sep to determine a good background to compute accurate weights. + --uniform adds additional HDUs (see Uniform Weights below). + --mesh-size sets a tile size in pixels for the uniform noise calibration. (default: 128) + --overwrite lets the script replace existing output files. + +Output HDUs +----------- + +The output fits files include the following HDUs copied from the asdf data (whenever the +asdf file includes these arrays): + +SCI: The science image. Called data in the asdf file. It is the "optimal" pixel values + favored by the project. It includes the WCS information in the fits header. + +DQ: Data quality flags. Most non-zero values indicate pixels to mask. Some that we + think are ok (at least in early commissioning data) are JUMP_DET (4) and + UNRELIABLE_SLOPE (16777216). We looked at LOW_QE (8192), and most of these are + ok too, but they include a population of pixels that appear more like HOT + pixels, so we reject this one. + +ERR: An estimate of the error in the SCI values. It is a sigma value, so ERR^2 is the + variance. It includes both read noise and poisson noise from source and background. + +VAR_POISSON: The project estimate of the poisson noise. It includes noise from both + background and sources. + +VAR_RNOISE: The project estimate of the read noise. + +VAR_FLAT: An estimate of the noise from flat field uncertainty. + +CHISQ: The per-pixel ramp-fit chi-squared statistic. Not sure if this is useful. + +DUMO: Difference Uniform Minus Optimal. It supplies a way to convert from the project "optimal" + weight to a uniform weight ramp slope. + + +The following hdus are constructed from the above for convenience when used with Piff: + +MASK: A mask plane usable by Piff. This converts the DQ values into either 1 or 0. + 1 for DQ values other than JUMP_DET and UNRELIABLE_SLOPE, 0 otherwise. + We also set this to 1 for pixels where we obtain an invalid value for something + such as the GAIN. + +IVAR: A normal inverse variance weight that Piff prefers. If the option --background-weights + is used, they will have the Poisson noise from sources removed. Note: for Piff, if you + don't use --background-weights, then you should use `remove_signal_from_weight: true` + to get Piff to remove the source Poisson noise from the variance. Otherwise, this + script will already have done that for you. + +SCI_UNIF: The sum of data + dumo; i.e. the uniform-weight ramp slope for each pixel. + When using this, you probably also want to run with --uniform. See the next section. + +GAIN: The ratio SCI / VAR_POISSON, which is the effective gain in each pixel. Because of how + the pixel weighting and cosmic ray removal is done, each pixel effectively has a different + gain. This map lets Piff use that information correctly. + + +Uniform Weights +--------------- + +The "optimal" weights give pretty bad results on early commissioning data with the guider +problems. Uniform turns out to work a lot better, so we recommend using SCI_UNIF rather +than the regular SCI. This may change when the guiding improves, but for the images with +very bad jitter, the uniform weight is a big improvement. However, to use it properly, we +also need to compute a few additional things. + +The following additional HDUs are output when using --uniform: + +MASK_UNIF: This keeps most of the JUMP_DET pixels, but masks isolated pixels marked + as JUMP_DET with large DUMO values. + +IVAR_UNIF: The inverse variance estimate for the UNIF image. This involves recalculating + both the read variance and the background Poisson variance for uniform ramp weights, + and it uses GAIN_UNIF rather than the normal GAIN when computing the Poisson noise + from the background. + +GAIN_UNIF: An estimate of the effective gain in the UNIF image. + + +World Coordinate System +----------------------- + +The asdf file includes the WCS in GWCS format, which doesn't directly work in a FITS +file, so we convert it to a TAN-SIP WCS, targeting 0.01 pixel accuracy. +The sampled maximum residual is recorded in the FITS header of the SCI HDU as WCSERR. + + +Dependencies +------------ + +The code requires the following modules to be installed: + +numpy, scipy, astropy, gwcs, +asdf, asdf-astropy, roman_datamodels + +The ASDF-related packages need to be fairly recent to read the input files from Roman, +including roman_datamodels, which is used implicitly by these packages. + +Additionally, sep is required for --uniform or --background-weights. +""" + +import argparse +from pathlib import Path +import warnings + +import asdf +from asdf.exceptions import AsdfConversionWarning +import numpy as np +from astropy.io import fits +from astropy.wcs import WCS +from scipy.interpolate import RegularGridInterpolator +from scipy.ndimage import binary_dilation, uniform_filter + + +def estimate_uniform_noise(science, read_variance, poisson_variance, samples, read_times, + *, mesh_size): + """Infer uniform-ramp read variance and effective gain from clean background pixels. + + ``read_times`` contains individual read times in seconds, grouped by resultant. + ``samples`` selects finite, positive, unflagged source-free measurements. Input + variances describe the optimal full-ramp fit. The returned read variance and + gain maps have the input image shape; metadata records the temporal factors and + the number of calibration samples. The gain converts model intensity into + uniform-ramp Poisson variance via ``model / gain``. + + We model the covariance of the calibrated resultants as A*R + C*P. R has + diagonal 1/N_i for N_i independent reads averaged into resultant i. P averages + min(t_a, t_b) over read pairs, since cumulative Poisson counts share all earlier + arrivals. A is the calibrated per-read variance; C is the calibrated photon + covariance amplitude for the local illumination. The image is a slope, so its + read and photon variances also contain temporal factors from the slope weights. + + The optimal fitter's separate variance planes identify A and C by inverting + the predicted variance ratio under full-ramp GLS. This assumes the unflagged + optimal fit uses that covariance model. For the uniform slope coefficient + vector w (sum(w)=0, w dot resultant_times=1), the new variances are + A*(w^T R w) and C*(w^T P w). C is proportional to illumination, so C/SCI on + background pixels provides an inverse gain amplitude. The returned gain also + includes the uniform temporal factor; it is NOT the detector gain in e-/DN. + Calibration/flat/photometric scaling is inherited from the calibrated planes. + + Only clean background samples are inverted: jump-affected optimal fits can use + different read subsets, so their variances cannot reliably be propagated this + way. Robust tile medians and interpolation supply amplitudes at sources and + flagged pixels. This is an inferred noise model, not a rerun of calibration. + """ + if mesh_size <= 0: + raise ValueError('mesh_size must be positive') + nreads = np.array([len(t) for t in read_times]) + times = np.array([np.mean(t) for t in read_times]) + read_covariance = np.diag(1.0 / nreads) + photon_covariance = np.array([ + [np.minimum(a[:, None], b[None, :]).mean() for b in read_times] + for a in read_times]) + total_reads = nreads.sum() + nt = nreads @ times + # Equal per-read weights become N_i weights for averaged resultants. These + # slope coefficients cancel a constant intercept and give unit response to t. + uniform = (total_reads * nreads * times - nt * nreads) / ( + total_reads * (nreads @ times**2) - nt**2) + uniform_read = uniform @ read_covariance @ uniform + uniform_photon = uniform @ photon_covariance @ uniform + + # Differencing removes the nuisance intercept. At each photon/read amplitude + # ratio q=C/A, GLS predicts the reported slope variance ratio as + # VAR_POISSON/VAR_READ = q * photon_factor(q)/read_factor(q). Tabulate this + # monotonic relation so we can invert it for every background sample. + difference = np.diff(np.eye(len(times)), axis=0) / np.diff(times)[:, None] + read_diff = difference @ read_covariance @ difference.T + photon_diff = difference @ photon_covariance @ difference.T + log_ratio = np.linspace(-8 * np.log(10), 8 * np.log(10), 4097) + ratio = np.exp(log_ratio) + covariance = read_diff[None, :, :] + ratio[:, None, None] * photon_diff[None, :, :] + weights = np.linalg.solve(covariance, np.ones((len(ratio), len(times) - 1, 1)))[..., 0] + weights /= weights.sum(axis=1)[:, None] + read_factor = np.einsum('ni,ij,nj->n', weights, read_diff, weights) + photon_factor = np.einsum('ni,ij,nj->n', weights, photon_diff, weights) + predicted_ratio = np.log(ratio * photon_factor / read_factor) + + # Infer calibration amplitudes only on clean background pixels, not on the + # jump-affected stellar pixels whose optimal-fit uncertainties are unsuitable. + ny, nx = science.shape + x_edges = list(range(0, nx, mesh_size)) + [nx] + y_edges = list(range(0, ny, mesh_size)) + [ny] + x_centers = (np.array(x_edges[:-1]) + np.array(x_edges[1:]) - 1) / 2.0 + y_centers = (np.array(y_edges[:-1]) + np.array(y_edges[1:]) - 1) / 2.0 + mesh = np.empty((len(y_centers), len(x_centers), 2)) + for j, (y0, y1) in enumerate(zip(y_edges[:-1], y_edges[1:])): + for i, (x0, x1) in enumerate(zip(x_edges[:-1], x_edges[1:])): + region = np.s_[y0:y1, x0:x1] + use = samples[region] + if not np.any(use): + raise ValueError(f'No clean background samples in tile ({i}, {j}); ' + 'increase --mesh-size') + read = read_variance[region][use] + photon = poisson_variance[region][use] + inferred_ratio = np.interp(np.log(photon / read), predicted_ratio, log_ratio) + read_amplitude = read / np.interp(inferred_ratio, log_ratio, read_factor) + photon_amplitude = photon / np.interp(inferred_ratio, log_ratio, photon_factor) + mesh[j, i, 0] = np.median(read_amplitude) + mesh[j, i, 1] = np.median(photon_amplitude) / np.median(science[region][use]) + + # Interpolate inverse gain, so interpolation is linear in the noise amplitudes. + # Clip at outer tile centers to avoid extrapolating to negative variances. + interpolate = RegularGridInterpolator((y_centers, x_centers), mesh) + read_map = np.empty(science.shape, dtype=np.float32) + gain_map = np.empty(science.shape, dtype=np.float32) + x = np.clip(np.arange(nx), x_centers[0], x_centers[-1]) + for start in range(0, ny, mesh_size): + end = min(start + mesh_size, ny) + y = np.clip(np.arange(start, end), y_centers[0], y_centers[-1]) + xx, yy = np.meshgrid(x, y) + amplitudes = interpolate(np.stack([yy, xx], axis=-1)) + read_map[start:end] = amplitudes[:, :, 0] * uniform_read + gain_map[start:end] = 1.0 / (amplitudes[:, :, 1] * uniform_photon) + metadata = { + 'MESH': mesh_size, + 'NSAMP': int(np.count_nonzero(samples)), + 'UNIRFAC': float(uniform_read), + 'UNIPFAC': float(uniform_photon), + } + return read_map, gain_map, metadata + + +def source_mask(science, error, mask, background): + """Find source footprints for noise calibration, using our SEP detection settings. + + ERR sets a reference threshold here, not the final uniform-ramp noise model. + Use the union of optimal and uniform footprints so jumps and source cores in + either estimate cannot enter the background calibration sample. + """ + import sep + image = np.array(science, dtype=np.float32, order='C') + noise = np.array(error, dtype=np.float32, order='C') + image[mask] = 0 + noise[mask] = 1 + image -= background + sep.set_extract_pixstack(1000000) + _, segmentation = sep.extract( + image, 1.5, err=noise, mask=mask, minarea=4, deblend_nthresh=32, + deblend_cont=0.005, filter_type='conv', segmentation_map=True) + # Omitting filter_kernel uses SEP's compact built-in 3x3 detection filter. + return segmentation != 0 + + +def uniform_hdus(roman, header, original_mask, *, mesh_size): + """Build the extra mask and noise planes for SCI_UNIF, without companion files.""" + science = np.asarray(roman['data'], dtype=np.float32) + error = np.asarray(roman['err'], dtype=np.float32) + poisson = np.asarray(roman['var_poisson'], dtype=np.float32) + dumo = np.asarray(roman['dumo'], dtype=np.float32) + uniform = science + dumo + dq = np.asarray(roman['dq']) + background = header['SKYBKG'] + + # Guiding makes many real stellar cores JUMP_DET. Rejecting that bit wholesale + # destroys the stars. Instead flag a >10 ERR positive DUMO excursion only when + # its eight SCI neighbors lack 10-sigma summed support. Exclude the tested + # pixel itself and masked neighbors: an isolated spike cannot support itself. + # This empirical screen can retain a real jump on a bright source; it is not + # a calibrated cosmic-ray classifier. WARM/LOW_QE stay in original_mask. + signal = np.where(original_mask, 0, science - background) + variance = np.where(original_mask, 0, error**2) + neighbor_signal = 9 * uniform_filter(signal, size=3, mode='constant') - signal + neighbor_variance = 9 * uniform_filter(variance, size=3, mode='constant') - variance + supported = neighbor_signal > 10 * np.sqrt(np.maximum(neighbor_variance, 0)) + added_mask = ~original_mask & ((dq & 4) != 0) & (dumo > 10 * error) & ~supported + mask = original_mask | added_mask | ~np.isfinite(uniform) + + sources = source_mask(science, error, original_mask, background) + sources |= source_mask(uniform, error, mask, background) + sources = binary_dilation(sources, iterations=3) + # ERR^2 includes source AND background Poisson noise. Remove that entire + # component (and flat variance if supplied) to isolate read variance. Never + # clip negative estimates into the calibration sample: use finite positive, + # completely unflagged background pixels only, then interpolate amplitudes. + if 'var_rnoise' in roman: + read = np.asarray(roman['var_rnoise'], dtype=float) + read_source = 'VAR_RNOISE' + else: + read = error.astype(float)**2 - poisson + if 'var_flat' in roman: + read -= np.asarray(roman['var_flat']) + read_source = 'ERR^2 minus other variances' + samples = ~mask & ~sources & (dq == 0) + samples &= np.isfinite(science) & (science > 0) + samples &= np.isfinite(read) & (read > 0) & np.isfinite(poisson) & (poisson > 0) + exposure = roman['meta']['exposure'] + read_times = [np.asarray(t) * exposure['frame_time'] for t in exposure['read_pattern']] + read_map, gain, info = estimate_uniform_noise( + science, read, poisson, samples, read_times, mesh_size=mesh_size) + # Add back ONLY the background photon variance. Source noise must be added + # later from the fitted source model, not the observed noisy pixel intensity. + variance = read_map + background / gain + ivar = np.zeros_like(read_map) + np.divide(1.0, variance, out=ivar, where=~mask) + + mask_header = header.copy() + mask_header['DUMOSIG'] = (10.0, 'Minimum positive DUMO/ERR for rejection') + mask_header['SUPPSNR'] = (10.0, 'Required SCI neighbor S/N to retain excursion') + mask_header.add_history('Empirical DUMO screen; no science pixel values replaced.') + noise_header = header.copy() + noise_header.update(info) + noise_header['WGTTYPE'] = ('BACKGROUND', 'IVAR excludes source Poisson variance') + noise_header['RNMETHOD'] = read_source + noise_header['NOISEMOD'] = 'UNFLAGGED_GLS' + noise_header['SRCDIL'] = (3, 'Segmentation exclusion buffer in pixels') + noise_header.add_history('Uniform noise inferred from clean optimal-fit variances.') + noise_header.add_history('GAIN_UNIF assumes stationary illumination for source noise.') + print(f'Uniform: {added_mask.sum()} additional masked pixels; {info["NSAMP"]} ' + f'clean samples; median background variance={np.median(variance[~mask]):.7g}, ' + f'median gain={np.median(gain[~mask]):.7g}', flush=True) + return [fits.ImageHDU(mask.astype(np.int16), mask_header, name='MASK_UNIF'), + fits.ImageHDU(ivar, noise_header, name='IVAR_UNIF'), + fits.ImageHDU(gain, noise_header, name='GAIN_UNIF')] + + +def convert(input_path, output_path, *, include_wcs=True, overwrite=False, include_gain=False, + background_weights=False, uniform_weights=False, mesh_size=128): + """Write one calibrated Roman image to FITS, returning the output path.""" + background_weights = background_weights or uniform_weights + include_gain = include_gain or background_weights + input_path = Path(input_path) + output_path = Path(output_path) + # Reject unrecognized tags, but allow package-version provenance warnings + # when the installed readers can deserialize all objects successfully. + with (warnings.catch_warnings(action='error', category=AsdfConversionWarning), + asdf.open(input_path) as af): + roman = af['roman'] + if 'data' not in roman: + raise ValueError(f'{input_path} has no science image; use a *_cal.asdf file') + if uniform_weights and 'dumo' not in roman: + raise ValueError('--uniform requires the DUMO plane') + meta = roman['meta'] + header = fits.Header() + header['TELESCOP'] = meta['telescope'] + header['INSTRUME'] = meta['instrument']['name'] + header['DETECTOR'] = meta['instrument']['detector'] + header['FILTER'] = meta['instrument']['optical_element'] + header['EXPTIME'] = (meta['exposure']['exposure_time'], 'Exposure time in seconds') + header['EFFEXPTM'] = meta['exposure']['effective_exposure_time'] + header['ORIGFILE'] = input_path.name + header.add_history('Converted from Roman ASDF; pixel values copied without rescaling.') + + image_header = header.copy() + if include_wcs: + ny, nx = roman['data'].shape + gwcs = meta['wcs'] + image_header.update(gwcs.to_fits_sip( + bounding_box=((0, nx - 1), (0, ny - 1)), + max_pix_error=0.01, max_inv_pix_error=0.01)) + # Check a separate grid, including the science image edges. GWCS uses + # zero-based pixels; so does Astropy with origin=0 below. + x, y = np.meshgrid(np.linspace(0, nx - 1, 17), np.linspace(0, ny - 1, 17)) + ra, dec = gwcs(x, y) + fit_x, fit_y = WCS(image_header).all_world2pix(ra, dec, 0) + error = np.max(np.hypot(fit_x - x, fit_y - y)) + if not np.isfinite(error) or error > 0.01: + raise ValueError(f'FITS WCS residual {error:.6g} exceeds 0.01 pixel') + image_header['WCSERR'] = (float(error), 'Max pixel residual on 17x17 check grid') + image_header.add_history('TAN-SIP approximation to original ASDF GWCS.') + print(f'{input_path.name}: maximum sampled WCS error = {error:.6g} pixel') + + hdus = [fits.PrimaryHDU(header=header)] + for key, name in [('data', 'SCI'), ('dq', 'DQ'), ('err', 'ERR'), + ('var_poisson', 'VAR_POISSON'), ('var_rnoise', 'VAR_RNOISE'), + ('var_flat', 'VAR_FLAT'), ('chisq', 'CHISQ'), ('dumo', 'DUMO')]: + if key in roman: + data = np.asarray(roman[key]) + if data.dtype == np.float16: + data = data.astype(np.float32) + hdus.append(fits.ImageHDU(data=data, header=image_header.copy(), name=name)) + error = np.asarray(roman['err'], dtype=np.float32) + good_dq_bits = np.uint32(4 | 16777216) # JUMP_DET | UNRELIABLE_SLOPE + mask = (((np.asarray(roman['dq']) & ~good_dq_bits) != 0) | + ~np.isfinite(roman['data']) | + ~np.isfinite(error) | (error <= 0)) + if include_gain: + poisson = np.asarray(roman['var_poisson'], dtype=np.float32) + science = np.asarray(roman['data']) + gain = np.zeros_like(error) + valid_gain = np.isfinite(science) & (science > 0) + valid_gain &= np.isfinite(poisson) & (poisson > 0) + # SCI/VAR_POISSON estimates the optimal-fit effective gain, including + # temporal weighting. At jump-affected pixels this can differ greatly + # from uniform-ramp gain; do not reuse it for SCI_UNIF source noise. + np.divide(science, poisson, out=gain, where=valid_gain) + mask |= ~valid_gain | ~np.isfinite(gain) | (gain <= 0) + variance = error.astype(float)**2 + if background_weights: + import sep + # Use the same mask and scalar SEP estimator as detection. Preserve SCI/ERR. + background_image = np.array(roman['data'], dtype=np.float32, order='C') + background_image[mask] = 0 + background = float(sep.Background(background_image, mask=mask).globalback) + if 'var_rnoise' in roman: + read_variance = np.array(roman['var_rnoise'], dtype=float) + read_source = 'VAR_RNOISE' + else: + read_variance = np.zeros_like(variance) + np.subtract(variance, poisson, out=read_variance, where=~mask) + read_source = 'ERR^2-VAR_POISSON' + if 'var_flat' in roman: + read_variance -= np.asarray(roman['var_flat']) + read_source = 'ERR^2-VAR_POISSON-VAR_FLAT' + usable_read = ~mask & (np.asarray(roman['dq']) == 0) + usable_read &= np.isfinite(read_variance) & (read_variance > 0) + if not usable_read.any(): + raise ValueError('No usable unflagged pixels to estimate median read variance') + median_read = float(np.median(read_variance[usable_read])) + replace = ~mask & (read_variance < 0) + # This repair is only for the legacy optimal-image weights. The + # uniform model below discards these pixels from its calibration. + read_variance[replace] = median_read + mask |= ~np.isfinite(read_variance) + variance = read_variance.copy() + variance[~mask] += background / gain[~mask] + image_header['SKYBKG'] = (background, 'Scalar SEP background in SCI units') + image_header['WGTTYPE'] = ('BACKGROUND', 'IVAR excludes source Poisson noise') + image_header['RNMETHOD'] = (read_source, 'Read variance estimate') + image_header['RNVAR'] = (median_read, 'Median unflagged read variance') + image_header['RNREPLAC'] = (int(replace.sum()), 'Negative read variances replaced') + # Detection and Piff must subtract the same background used for these weights. + for hdu in hdus: + hdu.header['SKYBKG'] = image_header['SKYBKG'] + print(f'{input_path.name}: background={background:.7g}, ' + f'median read variance={median_read:.7g}, ' + f'replaced {replace.sum()} negative read variances') + image_header['DQGOOD'] = (int(good_dq_bits), 'DQ bits allowed in MASK/IVAR') + hdus.insert(4, fits.ImageHDU(data=mask.astype(np.int16), + header=image_header.copy(), name='MASK')) + ivar = np.zeros_like(error) + np.divide(1.0, variance, out=ivar, where=~mask) + hdus.insert(5, fits.ImageHDU(data=ivar, header=image_header.copy(), name='IVAR')) + if include_gain: + gain_header = image_header.copy() + gain_header['GAINMETH'] = ('SCI/VAR_POISSON', 'Estimated effective Poisson gain') + gain_ref = meta.get('ref_file', {}).get('gain') + if gain_ref is not None: + gain_header['GAINREF'] = (str(gain_ref), 'Detector gain reference') + hdus.append(fits.ImageHDU(data=gain, header=gain_header, name='GAIN')) + if 'dumo' in roman: + uniform = np.asarray(roman['data'], dtype=np.float32) + np.asarray( + roman['dumo'], dtype=np.float32) + uniform_header = image_header.copy() + uniform_header['RAMPFIT'] = ('UNIFORM', 'SCI_UNIF = original data + DUMO') + uniform_header.add_history('ERR, IVAR, GAIN describe the original optimal ramp fit.') + hdus.append(fits.ImageHDU(data=uniform, header=uniform_header, name='SCI_UNIF')) + if uniform_weights: + hdus.extend(uniform_hdus(roman, uniform_header, mask, mesh_size=mesh_size)) + output_path.parent.mkdir(parents=True, exist_ok=True) + with fits.HDUList(hdus) as hdul: + hdul.writeto(output_path, overwrite=overwrite, checksum=True) + return output_path + + +def main(): + parser = argparse.ArgumentParser(description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument('inputs', type=Path, nargs='+', help='Calibrated *_cal.asdf files') + parser.add_argument('--output-dir', type=Path, + help='Output directory (default: alongside each input ASDF)') + parser.add_argument('--no-wcs', action='store_true', help='Export arrays without sky WCS') + parser.add_argument('--gain-map', action='store_true', help='Export effective Poisson GAIN map') + parser.add_argument('--background-weights', action='store_true', + help='Write read+background IVAR and effective GAIN (requires SEP)') + parser.add_argument('--uniform', action='store_true', + help='Also build the uniform-ramp mask, IVAR and GAIN (requires SEP)') + parser.add_argument('--mesh-size', type=int, default=128, + help='Uniform noise calibration tile size in pixels (default: 128)') + parser.add_argument('--overwrite', action='store_true', help='Replace existing output files') + args = parser.parse_args() + for path in args.inputs: + output_dir = path.parent if args.output_dir is None else args.output_dir + output = convert(path, output_dir / path.with_suffix('.fits').name, + include_wcs=not args.no_wcs, overwrite=args.overwrite, + include_gain=args.gain_map, background_weights=args.background_weights, + uniform_weights=args.uniform, mesh_size=args.mesh_size) + print(f'Wrote {output}') + + +if __name__ == '__main__': + main() From 8606d2d6459a87fc05956f98a705bab766b6f90d Mon Sep 17 00:00:00 2001 From: Mike Jarvis Date: Mon, 2 Nov 2026 19:03:52 -0500 Subject: [PATCH 09/18] Add RomanGWCS to read the full gwcs stored in the asdf files. --- docs/roman.rst | 3 + piff/roman/__init__.py | 3 +- piff/roman/gwcs.py | 97 +++++++++++++++++++++ tests/output/.gitignore | 1 + tests/test_wcs.py | 187 ++++++++++++++++++++++++++++++++++++++++ 5 files changed, 290 insertions(+), 1 deletion(-) create mode 100644 piff/roman/gwcs.py diff --git a/docs/roman.rst b/docs/roman.rst index c7418cfc..df6a7e01 100644 --- a/docs/roman.rst +++ b/docs/roman.rst @@ -4,6 +4,9 @@ Roman PSF module Classes and functions that are specific to the Nancy Grace Roman Space Telescope live in the sub-module piff.roman. They include the following: +.. autoclass:: piff.roman.RomanGWCS + :members: + .. autoclass:: piff.roman.RomanOpticsPSF :members: diff --git a/piff/roman/__init__.py b/piff/roman/__init__.py index 96f25bda..6c368eec 100644 --- a/piff/roman/__init__.py +++ b/piff/roman/__init__.py @@ -13,7 +13,8 @@ # and/or other materials provided with the distribution. """ -Some specialized features that specific to the DES survey and the DECam camera. +Specialized features for the Nancy Grace Roman Space Telescope. """ from .roman_psf import RomanOpticsPSF, RomanOpticalModel, RomanSCAInterp +from .gwcs import RomanGWCS diff --git a/piff/roman/gwcs.py b/piff/roman/gwcs.py new file mode 100644 index 00000000..eb01bebe --- /dev/null +++ b/piff/roman/gwcs.py @@ -0,0 +1,97 @@ +# Copyright (c) 2026 by Mike Jarvis and the other collaborators on GitHub at +# https://github.com/rmjarvis/Piff All rights reserved. +# +# Piff is free software: Redistribution and use in source and binary forms +# with or without modification, are permitted provided that the following +# conditions are met: +# +# 1. Redistributions of source code must retain the above copyright notice, this +# list of conditions and the disclaimer given in the accompanying LICENSE +# file. +# 2. Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the disclaimer given in the documentation +# and/or other materials provided with the distribution. + +import galsim +import numpy as np +import os +from galsim.wcs import CelestialWCS + + +class RomanGWCS(CelestialWCS): + """Use a Roman GWCS object as a GalSim celestial WCS. + + This really just wraps a ``gwcs.WCS`` instance to work as a ``galsim.CelestialWCS``. + It requires the gwcs module to be installed to work. + + By default, Piff pixel (1, 1) corresponds to GWCS pixel (0, 0). Local Jacobians use + GalSim's numerical derivatives. + + The typical usage would be to let the GWCS be automatically loaded from the Roman + asdf files. But you can also load the WCS separately using an explicit input.wcs field:: + + input: + wcs: + type: RomanGWCS + file_name: exposure_cal.asdf + path: roman.meta.wcs # This is the default. + + The optional ``path`` specifies the dot-separated path to the GWCS in the ASDF tree. + The default is roman.meta.wcs. You can also specify a ``dir`` using the normal Piff + pattern for file access. + + The default origin (``galsim.PositionD(1,1)``) accounts for the different convention + between gwcs and GalSim. + + :param wcs: A gwcs.WCS instance, typically read from the Roman image metadata. + :param origin: Image position corresponding to GWCS pixel (0, 0). + [default: galsim.PositionD(1, 1)] + """ + + def __init__(self, wcs, origin=None): + self.wcs = wcs + self._color = None + self._set_origin(galsim.PositionD(1, 1) if origin is None else origin) + + @property + def origin(self): + """Image position corresponding to GWCS pixel (0, 0).""" + return self._origin + + def _radec(self, x, y, color=None): + # Stamp rendering may evaluate positions just outside the detector bounding box. + ra, dec = self.wcs(x, y, with_bounding_box=False) + return np.deg2rad(ra), np.deg2rad(dec) + + def _xy(self, ra, dec, color=None): + return self.wcs.invert(np.rad2deg(ra), np.rad2deg(dec), with_bounding_box=False) + + def _newOrigin(self, origin): + return RomanGWCS(self.wcs, origin=origin) + + def copy(self): + return RomanGWCS(self.wcs, origin=self.origin) + + def _writeHeader(self, header, bounds): + raise NotImplementedError('A full GWCS cannot be written into a FITS image header') + + +class _RomanGWCSBuilder(galsim.config.WCSBuilder): + def buildWCS(self, config, base, logger): + import asdf + + kwargs = galsim.config.GetAllParams( + config, base, req={'file_name': str}, + opt={'dir': str, 'path': str})[0] + file_name = kwargs['file_name'] + if 'dir' in kwargs: + file_name = os.path.join(kwargs['dir'], file_name) + logger.info('Reading Roman GWCS from %s', file_name) + with asdf.open(file_name) as af: + wcs = af.tree + for key in kwargs.get('path', 'roman.meta.wcs').split('.'): + wcs = wcs[key] + return RomanGWCS(wcs) + + +galsim.config.RegisterWCSType('RomanGWCS', _RomanGWCSBuilder()) diff --git a/tests/output/.gitignore b/tests/output/.gitignore index dd0e6da0..4d2baff0 100644 --- a/tests/output/.gitignore +++ b/tests/output/.gitignore @@ -1,4 +1,5 @@ *.fits* +*.asdf *.pdf *.png *.piff diff --git a/tests/test_wcs.py b/tests/test_wcs.py index 05baa883..303a777a 100644 --- a/tests/test_wcs.py +++ b/tests/test_wcs.py @@ -20,6 +20,7 @@ import os import warnings import coord +import pytest from piff_test_helper import get_script_name, timer, CaptureLog @@ -782,6 +783,191 @@ def test_des_wcs(): np.testing.assert_allclose(wcs3.toWorld(im.center).y, wcs1.toWorld(im.center).y, rtol=0.04) +@timer +def test_gwcs(): + """Test the RomanGWCS class.""" + # Make a gwcs instance with a rotated TAN projection so we can make an equivalent galsim wcs. + gwcs = pytest.importorskip('gwcs') + import pickle + from astropy import units as u + from astropy.coordinates import ICRS + from astropy.modeling import models + from gwcs.coordinate_frames import Frame2D, CelestialFrame + center = galsim.CelestialCoord(53 * galsim.degrees, -27 * galsim.degrees) + matrix = np.array([[-0.11, 0.005], [0.003, 0.108]]) + transform = ((models.Shift(-1024) & models.Shift(-1024)) + | models.AffineTransformation2D(matrix=matrix / 3600) + | models.Pix2Sky_TAN() + | models.RotateNative2Celestial(53, -27, 180)) + native = gwcs.WCS( + transform, + input_frame=Frame2D(name='detector', unit=(u.pix, u.pix)), + output_frame=CelestialFrame(reference_frame=ICRS(), name='world', + unit=(u.deg, u.deg)), + ) + native.bounding_box = ((0, 2047), (0, 2047)) + wcs = piff.roman.RomanGWCS(native) + reference = galsim.TanWCS( + galsim.AffineTransform(0.11, -0.005, 0.003, 0.108, + origin=galsim.PositionD(1025, 1025)), center) + + # Check that to and from world coordinates matches the reference wcs. + positions = [galsim.PositionD(x, y) for x, y in + [(1, 1), (100.3, 800.7), (1025, 1025), (2048, 2048), (2050, -2)]] + x = np.array([pos.x for pos in positions]) + y = np.array([pos.y for pos in positions]) + expected_ra, expected_dec = reference.xyToradec(x, y, units=galsim.degrees) + ra, dec = wcs.xyToradec(x, y, units=galsim.degrees) + np.testing.assert_allclose(ra, expected_ra, rtol=0, atol=1.e-10) + np.testing.assert_allclose(dec, expected_dec, rtol=0, atol=1.e-10) + np.testing.assert_allclose(wcs.radecToxy(ra, dec, units=galsim.degrees), [x, y], + rtol=0, atol=1.e-7) + for pos in positions: + world = wcs.toWorld(pos) + assert world.distanceTo(reference.toWorld(pos)) / galsim.arcsec < 1.e-6 + recovered = wcs.toImage(world) + np.testing.assert_allclose([recovered.x, recovered.y], [pos.x, pos.y], + rtol=0, atol=1.e-7) + + # Local Jacobians and pixel areas agree with the independent tangent-plane projection. + # The RomanGWCS calculates this with finite differences. GalSim's GSFits does an analytic + # derivative. They match very well here. + for pos in positions: + np.testing.assert_allclose(wcs.jacobian(pos).getMatrix(), + reference.jacobian(pos).getMatrix(), + rtol=1.e-7, atol=1.e-8) + np.testing.assert_allclose(wcs.pixelArea(pos), reference.pixelArea(pos), rtol=1.e-7) + + # Make two asdf files each with two gwcs objects stored at different paths. + # The alternate at alternate.astrometry and the normal one in the second file include + # a shift of 0.1 degrees in RA compared to the reference wcs. + asdf = pytest.importorskip('asdf') + asdf_names = [os.path.join('output', 'gwcs_input_%d.asdf' % i) for i in range(2)] + second_native = gwcs.WCS( + transform | (models.Shift(0.1) & models.Shift(0)), # Shift RA by 0.1 degrees + input_frame=native.input_frame, output_frame=native.output_frame) + for file_name, native_wcs in zip(asdf_names, [native, second_native]): + tree = { + 'roman': {'meta': {'wcs': native_wcs}}, + 'alternate': {'astrometry': second_native}, + } + with asdf.AsdfFile(tree) as af: + af.write_to(file_name) + + # RomanGWCS loads the metadata from ASDF, with literal or directory/reference filenames. + config = { + 'input': { + 'wcs': { + 'type': 'RomanGWCS', + 'file_name': asdf_names[0], + } + } + } + loaded = galsim.config.BuildWCS(config['input'], 'wcs', config) + np.testing.assert_allclose(loaded.xyToradec(x, y, units='degrees'), [ra, dec], + rtol=0, atol=1.e-10) + + # Check using dir and reading file name with special GalSim config processing. + config = { + 'input': { + 'wcs': { + 'type': 'RomanGWCS', + 'dir': 'output', + 'file_name': '@gwcs_name', + } + }, + 'gwcs_name': os.path.basename(asdf_names[0]), + } + loaded = galsim.config.BuildWCS(config['input'], 'wcs', config) + np.testing.assert_allclose(loaded.xyToradec(x, y, units='degrees'), [ra, dec], + rtol=0, atol=1.e-10) + + # The path option specifies a different place in the asdf tree. + config = { + 'input': { + 'wcs': { + 'type': 'RomanGWCS', + 'file_name': asdf_names[0], + 'path': 'alternate.astrometry' + } + } + } + alternate = galsim.config.BuildWCS(config['input'], 'wcs', config) + np.testing.assert_allclose(alternate.xyToradec(x, y, units='degrees'), [ra + 0.1, dec], + rtol=0, atol=1.e-10) + + # The file_name parsing can use the image_num to get a different wcs for each input image. + image_name = os.path.join('output', 'gwcs_override.fits') + cat_name = os.path.join('output', 'gwcs_override_cat.fits') + image = galsim.Gaussian(sigma=0.17).drawImage(nx=64, ny=64, wcs=reference) + image.wcs = galsim.PixelScale(0.5) + image.write(image_name) + fitsio.write(cat_name, np.array([(32.0, 32.0)], dtype=[('x', float), ('y', float)]), + clobber=True) + config = { + 'input': { + 'image_file_name': [image_name, image_name], + 'cat_file_name': cat_name, + 'stamp_size': 25, + 'nproc': 2, + 'wcs': { + 'type': 'RomanGWCS', + 'dir': 'output', + 'file_name': '$"gwcs_input_%s.asdf"%image_num', + } + } + } + reader = piff.InputFiles(config['input'], base=config) + stars = reader.makeStars(logger=piff.config.setup_logger(verbose=0)) + assert len(stars) == 2 + for i, star in enumerate(stars): + expected_ra = ra + 0.1 * i + np.testing.assert_allclose(star.image.wcs.xyToradec(x, y, units='degrees'), + [expected_ra, dec], rtol=0, atol=1.e-10) + + # Origin shifts preserve the mapping in the corresponding image coordinates. + # The WCS object also survives a serialization round trip. + shift = galsim.PositionD(13, -8) + shifted = wcs.shiftOrigin(shift) + assert shifted.origin == wcs.origin + shift + for copied in [wcs.copy(), pickle.loads(pickle.dumps(wcs))]: + np.testing.assert_allclose(copied.xyToradec(x, y, units='degrees'), [ra, dec], + rtol=0, atol=1.e-10) + np.testing.assert_allclose(shifted.xyToradec(x + shift.x, y + shift.y, units='degrees'), + [ra, dec], rtol=0, atol=1.e-10) + + # Test using Piff to fit stars drawn with the GWCS. + profile = galsim.Gaussian(sigma=0.17).shear(g1=0.08, g2=-0.04).withFlux(1000) + stars = [] + for pos in positions[:4]: + star = piff.Star.makeTarget(x=pos.x, y=pos.y, wcs=wcs, pointing=center, + stamp_size=25, chipnum=0) + profile.drawImage(image=star.image, center=pos, method='no_pixel') + stars.append(star) + psf = piff.SimplePSF(piff.Gaussian(include_pixel=False), piff.Mean()) + psf.set_context({0: loaded}, center) + psf.fit(stars) + drawn = psf.draw(800.3, 1200.7, stamp_size=25) + expected = profile.withFlux(1).drawImage(bounds=drawn.bounds, wcs=reference, + center=galsim.PositionD(800.3, 1200.7), + method='no_pixel') + np.testing.assert_allclose(drawn.array, expected.array, rtol=1.e-4, atol=1.e-7) + + # The PSF roundtrips correctly through a piff output file. + file_name = os.path.join('output', 'gwcs.piff') + psf.write(file_name) + restored = piff.read(file_name) + np.testing.assert_allclose(restored.wcs[0].xyToradec(x, y, units='degrees'), [ra, dec], + rtol=0, atol=1.e-10) + np.testing.assert_array_equal(restored.draw(800.3, 1200.7, stamp_size=25).array, drawn.array) + np.testing.assert_allclose(restored.wcs[0].radecToxy(ra, dec, units='degrees'), [x, y], + rtol=0, atol=1.e-7) + + # Full GWCS models cannot be represented by a FITS image header. + with np.testing.assert_raises(NotImplementedError): + drawn.write(os.path.join('output', 'gwcs_image.fits')) + + if __name__ == '__main__': #import cProfile, pstats #pr = cProfile.Profile() @@ -794,6 +980,7 @@ def test_des_wcs(): test_olddes() test_newdes() test_des_wcs() + test_gwcs() #pr.disable() #ps = pstats.Stats(pr).sort_stats('tottime') #ps.print_stats(20) From d539d34d66920f78b3cde9f8ed76c26010ded4a7 Mon Sep 17 00:00:00 2001 From: Mike Jarvis Date: Mon, 2 Nov 2026 23:07:17 -0500 Subject: [PATCH 10/18] Add fix_ushort_badpix to make that correction explicit --- piff/input.py | 38 ++++++++++++++++++++++++-------------- tests/sizemag.yaml | 1 + tests/test_gp_interp.py | 1 + tests/test_input.py | 6 ++++-- tests/test_knn_interp.py | 1 + tests/test_pixel.py | 1 + tests/test_sizemag.py | 1 + tests/test_stats.py | 1 + 8 files changed, 34 insertions(+), 16 deletions(-) diff --git a/piff/input.py b/piff/input.py index c4dc1b2c..b576ec79 100644 --- a/piff/input.py +++ b/piff/input.py @@ -256,6 +256,9 @@ class InputFiles(Input): this gives the name of the file to use. [default: None] :badpix_zeros: Whether to treat all zeros in the input image as bad pixels. [default: False] + :fix_ushort_badpix: Correct a legacy 32768 offset in the bad-pixel mask. Old FITS files + sometimes offset their badpix arrays by 32768. Set this to True to + undo that. [default: False] :sky_file_name: a file containing a sky background image to subtract. [default: none] :sky_ext: the extension number or name to use in the sky file, or in the image file if sky_file_name is omitted. [default: none, which means use the @@ -501,6 +504,7 @@ def __init__(self, config, base=None, logger=None): 'weight_file_name' : str, 'badpix_file_name' : str, 'badpix_zeros' : bool, + 'fix_ushort_badpix' : bool, 'sky_file_name' : str, 'sky_ext': (int, str), 'cat_ext' : (int, str), @@ -777,6 +781,7 @@ def __init__(self, config, base=None, logger=None): badpix_file_name = params.get('badpix_file_name', None) badpix_ext = params.get('badpix_ext', None) badpix_zeros = params.get('badpix_zeros', False) + fix_ushort_badpix = params.get('fix_ushort_badpix', False) sky_file_name = params.get('sky_file_name', None) sky_ext = params.get('sky_ext', None) if sky_file_name is None and sky_ext is not None: @@ -794,6 +799,7 @@ def __init__(self, config, base=None, logger=None): 'badpix_file_name' : badpix_file_name, 'badpix_ext' : badpix_ext, 'badpix_zeros' : badpix_zeros, + 'fix_ushort_badpix' : fix_ushort_badpix, 'sky_file_name' : sky_file_name, 'sky_ext' : sky_ext, 'gain_file_name': gain_file_name, @@ -1152,7 +1158,8 @@ def _read_image(file_name, ext, *, read_header): @classmethod def readImage(cls, image_file_name, image_ext, weight_file_name, weight_ext, - badpix_file_name, badpix_ext, badpix_zeros, sky_file_name, sky_ext, + badpix_file_name, badpix_ext, badpix_zeros, fix_ushort_badpix, + sky_file_name, sky_ext, gain_file_name, gain_ext, image_num, config, base, logger): """Read the science image, weight map, and optional gain image. @@ -1166,6 +1173,8 @@ def readImage(cls, image_file_name, image_ext, weight_file_name, weight_ext, :param badpix_ext: The extension number or name of the bad pixel mask (if any). :param badpix_zeros: Whether to treat all zeros in the input image as bad pixels. [default: False] + :param fix_ushort_badpix: Whether to correct badpix arrays with a 32768 offset value. + [default: False] :param sky_file_name: A file to use for a sky background to subtract from the image (if any). :param sky_ext: The extension number or name in sky_file_name (if any). @@ -1239,19 +1248,20 @@ def readImage(cls, image_file_name, image_ext, weight_file_name, weight_ext, logger.verbose("Reading badpix image from %s, extension %s.", badpix_file_name, badpix_ext) badpix = cls._read_image(badpix_file_name, badpix_ext, read_header=False) - # The badpix image may be offset by 32768 from the true value. - # If so, subtract it off. - if np.any(badpix.array > 32767): # pragma: no cover - logger.debug('min(badpix) = %s',np.min(badpix.array)) - logger.debug('max(badpix) = %s',np.max(badpix.array)) - logger.debug("subtracting 32768 from all values in badpix image") - badpix -= 32768 - if np.any(badpix.array < -32767): # pragma: no cover - logger.debug('min(badpix) = %s',np.min(badpix.array)) - logger.debug('max(badpix) = %s',np.max(badpix.array)) - logger.debug("adding 32768 to all values in badpix image") - badpix += 32768 - if np.all(badpix.array != 0): # pragma: no cover + + # Correct legacy unsigned-integer offsets if requested. + if fix_ushort_badpix: + if np.any(badpix.array > 32767): + logger.debug('min(badpix) = %s',np.min(badpix.array)) + logger.debug('max(badpix) = %s',np.max(badpix.array)) + logger.debug("subtracting 32768 from all values in badpix image") + badpix -= 32768 + if np.any(badpix.array < -32767): + logger.debug('min(badpix) = %s',np.min(badpix.array)) + logger.debug('max(badpix) = %s',np.max(badpix.array)) + logger.debug("adding 32768 to all values in badpix image") + badpix += 32768 + if np.all(badpix.array != 0): logger.error("According to the bad pixel array in %s, all pixels are masked!", image_file_name) weight.array[badpix.array != 0] = 0 diff --git a/tests/sizemag.yaml b/tests/sizemag.yaml index fd84dbf3..6ce0cbdb 100644 --- a/tests/sizemag.yaml +++ b/tests/sizemag.yaml @@ -3,6 +3,7 @@ input: image_file_name: DECam_00241238_01.fits.fz image_ext: 1 badpix_ext: 2 + fix_ushort_badpix: true # GalSim reads this mask with a 32768 offset. weight_ext: 3 cat_file_name: DECam_00241238_01_cat.fits diff --git a/tests/test_gp_interp.py b/tests/test_gp_interp.py index da83af50..be0a5a1e 100644 --- a/tests/test_gp_interp.py +++ b/tests/test_gp_interp.py @@ -415,6 +415,7 @@ def test_yaml(): # What hdu is everything in? 'image_ext' : 1, 'badpix_ext' : 2, + 'fix_ushort_badpix': True, # GalSim reads this mask with a 32768 offset. 'weight_ext' : 3, 'cat_ext' : 2, diff --git a/tests/test_input.py b/tests/test_input.py index 761e0443..15e08b80 100644 --- a/tests/test_input.py +++ b/tests/test_input.py @@ -545,7 +545,6 @@ def test_extensions(): assert positions == [galsim.PositionD(16, 16), galsim.PositionD(32, 32)] assert handler.getWCS()[0] == galsim.PixelScale(0.4) - @timer def test_invalid(): """Test invalid configuration elements @@ -1731,12 +1730,13 @@ def test_weight(): np.testing.assert_raises(KeyError, piff.InputFiles(config).getRawImageData, 0) # Some old versions of fitsio had a bug where the badpix mask could be offset by 32768. - # We move them back to 0 + # This can be fixed using fix_ushort_badpix = True. config = { 'image_file_name' : 'input/test_input_image_00.fits', 'cat_file_name' : 'input/test_input_cat_00.fits', 'weight_ext' : 1, 'badpix_ext' : 5, + 'fix_ushort_badpix' : True, } input = piff.InputFiles(config, logger=logger) assert input.nimages == 1 @@ -1744,6 +1744,7 @@ def test_weight(): assert weight.array.shape == (1024, 1024) np.testing.assert_almost_equal(weight.array, expected_noise**-1) + # The correction also handles an offset of -32768. config['badpix_ext'] = 6 input = piff.InputFiles(config, logger=logger) assert input.nimages == 1 @@ -1753,6 +1754,7 @@ def test_weight(): # Various ways to get all weight values == 0 (which will emit a logger message, but isn't # an error). + del config['fix_ushort_badpix'] config['weight_ext'] = 1 config['badpix_ext'] = 7 # badpix > 0 input = piff.InputFiles(config, logger=logger) diff --git a/tests/test_knn_interp.py b/tests/test_knn_interp.py index 32db85a0..ff069595 100644 --- a/tests/test_knn_interp.py +++ b/tests/test_knn_interp.py @@ -105,6 +105,7 @@ def test_config(): # What hdu is everything in? 'image_ext': 1, 'badpix_ext': 2, + 'fix_ushort_badpix': True, # GalSim reads this mask with a 32768 offset. 'weight_ext': 3, 'cat_ext': 2, diff --git a/tests/test_pixel.py b/tests/test_pixel.py index 8821185c..b2062fdb 100644 --- a/tests/test_pixel.py +++ b/tests/test_pixel.py @@ -1136,6 +1136,7 @@ def test_des_image(): 'image_ext' : 1, 'weight_ext' : 3, 'badpix_ext' : 2, + 'fix_ushort_badpix': True, # GalSim reads this mask with a 32768 offset. 'cat_file_name' : cat_file, 'cat_ext' : 2, 'x_col' : 'XWIN_IMAGE', diff --git a/tests/test_sizemag.py b/tests/test_sizemag.py index 1b86fbdb..b480e2c4 100644 --- a/tests/test_sizemag.py +++ b/tests/test_sizemag.py @@ -338,6 +338,7 @@ def test_sizemag(): 'image_file_name': 'DECam_00241238_01.fits.fz', 'image_ext': 1, 'badpix_ext': 2, + 'fix_ushort_badpix': True, # GalSim reads this mask with a 32768 offset. 'weight_ext': 3, 'cat_file_name' : 'DECam_00241238_01_psfcat_tb_maxmag_17.0_magcut_3.0_findstars.fits', diff --git a/tests/test_stats.py b/tests/test_stats.py index d3122fab..4fe13b67 100644 --- a/tests/test_stats.py +++ b/tests/test_stats.py @@ -853,6 +853,7 @@ def test_bad_hsm(): 'image_ext' : 1, 'weight_ext' : 3, 'badpix_ext' : 2, + 'fix_ushort_badpix': True, # GalSim reads this mask with a 32768 offset. 'cat_file_name' : cat_file, 'cat_ext' : 2, # These next two are intentionally backwards. The PixelGrid will find some kind From c9723dc1c9c486e0f52f2b16b9e16099f7ec8177 Mon Sep 17 00:00:00 2001 From: Mike Jarvis Date: Tue, 3 Nov 2026 00:27:29 -0500 Subject: [PATCH 11/18] Add ASDFValue config type --- piff/config_value.py | 22 ++++++++++ piff/roman/gwcs.py | 5 +-- piff/util.py | 6 +++ tests/test_config_value.py | 89 ++++++++++++++++++++++++++++++++++++++ tests/test_input.py | 12 +---- 5 files changed, 120 insertions(+), 14 deletions(-) create mode 100644 tests/test_config_value.py diff --git a/piff/config_value.py b/piff/config_value.py index 394d2f62..07561e83 100644 --- a/piff/config_value.py +++ b/piff/config_value.py @@ -17,6 +17,7 @@ """ import galsim +import os def _GenerateImageHeaderValue(config, base, value_type): @@ -30,11 +31,32 @@ def _GenerateImageHeaderValue(config, base, value_type): raise ValueError("ImageHeaderValue requires base['_current_image'] to be set.") header = base['_current_image'].header + if header is None: + raise ValueError('Current image has no header information. Required for ImageHeaderValue.') if key not in header: raise KeyError("Key %s not found in FITS header" % key) return header[key], safe +def _GenerateASDFValue(config, base, value_type): + """Read scalar metadata from an ASDF file using a dotted path. + """ + import asdf + from .util import get_asdf_value + + req = { 'file_name': str, 'path': str } + opt = { 'dir': str } + kwargs, safe = galsim.config.GetAllParams(config, base, req=req, opt=opt) + file_name = kwargs['file_name'] + if 'dir' in kwargs: + file_name = os.path.join(kwargs['dir'], file_name) + with asdf.open(file_name) as af: + value = get_asdf_value(af.tree, kwargs['path']) + return value, safe + + galsim.config.RegisterValueType('ImageHeaderValue', _GenerateImageHeaderValue, [float, int, bool, str, None]) +galsim.config.RegisterValueType('ASDFValue', _GenerateASDFValue, + [float, int, bool, str, None]) diff --git a/piff/roman/gwcs.py b/piff/roman/gwcs.py index eb01bebe..950a5068 100644 --- a/piff/roman/gwcs.py +++ b/piff/roman/gwcs.py @@ -16,6 +16,7 @@ import numpy as np import os from galsim.wcs import CelestialWCS +from ..util import get_asdf_value class RomanGWCS(CelestialWCS): @@ -88,9 +89,7 @@ def buildWCS(self, config, base, logger): file_name = os.path.join(kwargs['dir'], file_name) logger.info('Reading Roman GWCS from %s', file_name) with asdf.open(file_name) as af: - wcs = af.tree - for key in kwargs.get('path', 'roman.meta.wcs').split('.'): - wcs = wcs[key] + wcs = get_asdf_value(af.tree, kwargs.get('path', 'roman.meta.wcs')) return RomanGWCS(wcs) diff --git a/piff/util.py b/piff/util.py index 10161b61..75c5d10c 100644 --- a/piff/util.py +++ b/piff/util.py @@ -112,6 +112,12 @@ def adjust_value(value, dtype): # For other numpy arrays, we can use astype instead. return np.array(value).astype(t) +def get_asdf_value(tree, path): + """Select a value from an ASDF tree using a dotted path.""" + for key in path.split('.'): + tree = tree[key] + return tree + def estimate_cov_from_jac(jac): """Estimate a covariance matrix from a jacobian as returned by scipy.optimize.least_squares .. math:: diff --git a/tests/test_config_value.py b/tests/test_config_value.py new file mode 100644 index 00000000..c1c84177 --- /dev/null +++ b/tests/test_config_value.py @@ -0,0 +1,89 @@ +# Copyright (c) 2026 by Mike Jarvis and the other collaborators on GitHub at +# https://github.com/rmjarvis/Piff All rights reserved. +# +# Piff is free software: Redistribution and use in source and binary forms +# with or without modification, are permitted provided that the following +# conditions are met: +# +# 1. Redistributions of source code must retain the above copyright notice, this +# list of conditions and the disclaimer given in the accompanying LICENSE +# file. +# 2. Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the disclaimer given in the documentation +# and/or other materials provided with the distribution. + +import os +import fitsio +import galsim +import numpy as np +import pytest +import piff # Register Piff's GalSim config value types. + +from piff_test_helper import timer + + +@timer +def test_image_header_value(): + """Test FITS header values and the current-image requirements of ImageHeaderValue.""" + # Header values retain their numeric and string types through config parsing. + file_name = os.path.join('output', 'config_value.fits') + header = {'SKYLEVEL': 15.0, 'DETECTOR': 'WFI01'} + fitsio.write(file_name, np.zeros((2, 2)), header=header, clobber=True) + image = galsim.fits.read(file_name, read_header=True) + base = {'_current_image': image} + for key, value_type in [('SKYLEVEL', float), ('DETECTOR', str)]: + config = {'value': {'type': 'ImageHeaderValue', 'key': key}} + value = galsim.config.ParseValue(config, 'value', base, value_type)[0] + assert value == header[key] + + # A missing header key raises KeyError. + config = {'value': {'type': 'ImageHeaderValue', 'key': 'MISSING'}} + np.testing.assert_raises(KeyError, galsim.config.ParseValue, config, 'value', base, None) + + # A current image is required even if the requested keyword is valid. + config = {'value': {'type': 'ImageHeaderValue', 'key': 'SKYLEVEL'}} + np.testing.assert_raises(ValueError, galsim.config.ParseValue, config, 'value', {}, None) + + # An image without a FITS header cannot supply ImageHeaderValue. + image.header = None + with np.testing.assert_raises(ValueError) as e: + galsim.config.ParseValue(config, 'value', base, None) + assert 'Current image has no header information' in str(e.exception) + + +@timer +def test_asdf_value(): + """Test independent ASDFValue lookup of scalar metadata and filename expressions.""" + # The ASDF tree contains scalar metadata without any science-image requirements. + asdf = pytest.importorskip('asdf') + file_name = os.path.join('output', 'config_value.asdf') + metadata = {'sky': 15.0, 'detector': 'WFI01'} + with asdf.AsdfFile({'metadata': metadata}) as af: + af.write_to(file_name) + + # A dotted path reads a scalar value without a current input image. + config = { + 'sky': { + 'type': 'ASDFValue', + 'file_name': file_name, + 'path': 'metadata.sky', + }, + } + assert galsim.config.ParseValue(config, 'sky', config, float)[0] == metadata['sky'] + + # Directory and filename config references resolve to the selected ASDF file. + config = { + 'detector': { + 'type': 'ASDFValue', + 'dir': 'output', + 'file_name': '@asdf_name', + 'path': 'metadata.detector', + }, + 'asdf_name': os.path.basename(file_name), + } + assert galsim.config.ParseValue(config, 'detector', config, str)[0] == metadata['detector'] + + +if __name__ == '__main__': + test_image_header_value() + test_asdf_value() diff --git a/tests/test_input.py b/tests/test_input.py index 15e08b80..95f1599c 100644 --- a/tests/test_input.py +++ b/tests/test_input.py @@ -908,17 +908,7 @@ def test_cols(): assert len(gain_list) == 100 np.testing.assert_almost_equal(gain_list, gain) - # Missing ImageHeaderValue keys should raise a KeyError. - config['gain'] = { 'type': 'ImageHeaderValue', 'key': 'BAD_GAIN' } - with np.testing.assert_raises(KeyError): - piff.InputFiles(config, logger=logger).getRawImageData(0) - - # ImageHeaderValue requires a current image context. - with np.testing.assert_raises(ValueError): - galsim.config.ParseValue( - { 'x': { 'type': 'ImageHeaderValue', 'key': 'GAIN_A' } }, 'x', {}, None) - - # including satur will skip stars that are over the given saturation value. + # Including satur will skip stars that are over the given saturation value. # (It won't skip them here, just when building the stars list.) config = { 'dir' : 'input', From 7dd30081e367e70837569c6318d2af2c9e5fd8a5 Mon Sep 17 00:00:00 2001 From: Mike Jarvis Date: Tue, 3 Nov 2026 00:36:16 -0500 Subject: [PATCH 12/18] Add ability to read asdf files --- piff/input.py | 60 ++++++++++++++--------- piff/util.py | 16 +++++++ tests/test_input.py | 114 ++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 167 insertions(+), 23 deletions(-) diff --git a/piff/input.py b/piff/input.py index b576ec79..3089ffd5 100644 --- a/piff/input.py +++ b/piff/input.py @@ -24,7 +24,7 @@ import yaml from typing import NamedTuple -from .util import run_multi +from .util import run_multi, read_asdf_image from .star import Star, StarData from .config import LoggerWrapper @@ -192,6 +192,19 @@ class InputFiles(Input): Parse the input config dict (Normally the 'input' field in the overall configuration dict). + We currently support FITS and ASDF file formats for the input images, and FITS or Parquet + files for the catalog data. + + For FITS files, the *_ext parameters refer to the HDU with the given data, which may be + specified either by number or name. + + For ASDF files, the *_ext parameters refer to the path in the ASDF tree. Use dots to + indicate heirarchy levels. E.g. roman.data means af['roman']['data']. + + FITS files automatically load the WCS data given in the image header if present. + ASDF files don't seem to have a standard location, so you must specify the WCS + explicitly with an input.wcs field. + The two required fields in the input dict are: :image_file_name: The file name(s) of the input image(s). @@ -241,13 +254,14 @@ class InputFiles(Input): :chipnum: The id number of this chip used to reference this image [default: image_num] - :image_ext: The extension number or name to use in the image files. [default: - None, which means use either 0 or 1 according to FITS compression] - :weight_ext: The extension number or name to use for weight images. [default: - None, which means use the weight file's default extension if supplied, - otherwise create a weight image with all 1's] - :badpix_ext: The extension number or name for badpix images. Pixels with badpix != 0 - will be given weight == 0. [default: None] + :image_ext: The FITS extension number/name or ASDF path to the image. + [default: None, which means use either 0 or 1 according to FITS + compression; required for ASDF files] + :weight_ext: The FITS extension number/name or ASDF path for weight images. + [default: None, which means use the weight file's default extension + if supplied, otherwise create a weight image with all 1's] + :badpix_ext: The FITS extension number/name or ASDF path for badpix images. + Pixels with badpix != 0 will be given weight == 0. [default: None] :noise: Rather than a weight image, provide the noise variance in the image. (Useful for simulations where this is a known value.) [default: None] :weight_file_name: If the weight image is in a different file than the main image, @@ -260,9 +274,9 @@ class InputFiles(Input): sometimes offset their badpix arrays by 32768. Set this to True to undo that. [default: False] :sky_file_name: a file containing a sky background image to subtract. [default: none] - :sky_ext: the extension number or name to use in the sky file, or in the image - file if sky_file_name is omitted. [default: none, which means use the - sky file's default image extension] + :sky_ext: the FITS extension number/name or ASDF path in the sky file, + or in the image file if sky_file_name is omitted. + [default: none, which means use the sky file's default image extension] :cat_ext: the extension number or name in fits catalog files. ignored for parquet catalogs. [default: none, which means use the first table extension] @@ -389,9 +403,9 @@ class InputFiles(Input): :sky_col: The name of a column with sky values. [default: None] :gain_col: The name of a column with gain values. [default: None] :gain_file_name: A file containing a per-pixel effective gain map. [default: None] - :gain_ext: The extension number or name in the gain file, or in the image file - if gain_file_name is omitted. [default: None, which means use the gain - file's default extension] + :gain_ext: The FITS extension number/name or ASDF path in the gain file, + or in the image file if gain_file_name is omitted. + [default: None, which means use the gain file's default extension] :sky: The sky level to subtract from the image values. [default: None] Specify only one sky source: sky, sky_col, or sky_file_name/sky_ext. If none are provided, the input image will be assumed to have already @@ -1141,12 +1155,14 @@ def _removeSignalFromWeight(image, weight, gain=None): @staticmethod def _read_image(file_name, ext, *, read_header): - """Read one image plane, optionally including its metadata. + """Read one image, optionally including its metadata. Subclasses may override this method to support other file formats. The returned GalSim image must include its WCS and, when requested, a ``header`` attribute. """ - if isinstance(ext, str): + if file_name.endswith('.asdf'): + return read_asdf_image(file_name, ext, read_header=read_header) + elif isinstance(ext, str): # Apparently we never enabled named hdu access in GalSim, so as of GalSim 2.8, # it needs a number. So if we get a string, use astropy.io.fits directly to # get the correct hdu. @@ -1166,20 +1182,20 @@ def readImage(cls, image_file_name, image_ext, weight_file_name, weight_ext, Make a weight map if no weight information is given. :param image_file_name: The name of the file to read. - :param image_ext: The extension number or name of the main image. + :param image_ext: The FITS extension number/name or ASDF path of the image. :param weight_file_name: The name if the file with the weight image (if any). - :param weight_ext: The extension number or name of the weight image (if any). + :param weight_ext: The FITS extension number/name or ASDF path of the weight image. :param badpix_file_name: The name of the file with the bad pixel mask (if any). - :param badpix_ext: The extension number or name of the bad pixel mask (if any). + :param badpix_ext: The FITS extension number/name or ASDF path of the bad pixel mask. :param badpix_zeros: Whether to treat all zeros in the input image as bad pixels. [default: False] :param fix_ushort_badpix: Whether to correct badpix arrays with a 32768 offset value. [default: False] :param sky_file_name: A file to use for a sky background to subtract from the image (if any). - :param sky_ext: The extension number or name in sky_file_name (if any). + :param sky_ext: The FITS extension number/name or ASDF path in sky_file_name. :param gain_file_name: The name of the file with the gain image (if any). - :param gain_ext: The extension number or name of the gain image (if any). + :param gain_ext: The FITS extension number/name or ASDF path of the gain image. :param config: The input section of the config dict. :param base: The base config dict. :param logger: A logger object for logging debug info. @@ -1216,7 +1232,6 @@ def readImage(cls, image_file_name, image_ext, weight_file_name, weight_ext, # Either read in the weight image, or build a dummy one if weight_file_name is not None or weight_ext is not None: weight_file_name = weight_file_name or image_file_name - weight_ext = weight_ext or (1 if weight_file_name.endswith('.fz') else 0) logger.verbose("Reading weight image from %s, extension %s.", weight_file_name, weight_ext) weight = cls._read_image(weight_file_name, weight_ext, read_header=False) @@ -1244,7 +1259,6 @@ def readImage(cls, image_file_name, image_ext, weight_file_name, weight_ext, # If requested, set wt=0 for any bad pixels if badpix_file_name is not None or badpix_ext is not None: badpix_file_name = badpix_file_name or image_file_name - badpix_ext = badpix_ext or (1 if badpix_file_name.endswith('.fz') else 0) logger.verbose("Reading badpix image from %s, extension %s.", badpix_file_name, badpix_ext) badpix = cls._read_image(badpix_file_name, badpix_ext, read_header=False) diff --git a/piff/util.py b/piff/util.py index 75c5d10c..ef6a8d9d 100644 --- a/piff/util.py +++ b/piff/util.py @@ -118,6 +118,22 @@ def get_asdf_value(tree, path): tree = tree[key] return tree + +def read_asdf_image(file_name, ext, *, read_header): + """Read an ASDF image array, materializing it before closing the file.""" + import asdf + + with asdf.open(file_name) as af: + if not isinstance(ext, str): + raise ValueError('ext must be a dot-separated path when used with ASDF files') + array = np.array(get_asdf_value(af.tree, ext), copy=True) + if array.dtype == np.float16: + array = array.astype(np.float32) + image = galsim.Image(array, scale=1.0) + if read_header: + image.header = None + return image + def estimate_cov_from_jac(jac): """Estimate a covariance matrix from a jacobian as returned by scipy.optimize.least_squares .. math:: diff --git a/tests/test_input.py b/tests/test_input.py index 95f1599c..80879d9e 100644 --- a/tests/test_input.py +++ b/tests/test_input.py @@ -3561,6 +3561,119 @@ def test_input_bandpass(): assert psf3.pointing == pointing assert psf3.bandpass == bandpass +@timer +def test_asdf(): + """Test reading ASDF files.""" + asdf = pytest.importorskip('asdf') + + # Make an asdf file with all the possible data arrays we might want to read. + y, x = np.mgrid[:128, :128] + sky = 15 + 0.01 * x + 0.02 * y + gain = 2 + 0.002 * x + 0.003 * y + signal = galsim.ImageD(128, 128, scale=0.2) + positions = [(32.3, 35.7), (90.1, 41.2), (65.6, 93.4)] + for pos, flux in zip(positions, [1000, 2000, 1500]): + profile = galsim.Moffat(beta=3.5, fwhm=0.7, flux=flux).shear(g1=0.04, g2=-0.02) + profile.drawImage(image=signal, center=galsim.PositionD(*pos), add_to_image=True) + science = signal.array + sky + variance = 4 + science / gain + badpix = np.zeros(science.shape, dtype=np.uint32) + badpix[20, 20] = 1 << 20 + science[30, 30] = np.nan + file_name = os.path.join('output', 'input_data.asdf') + cat_name = os.path.join('output', 'input_asdf_cat.fits') + tree = { + 'data_arrays': { + 'science': science, + 'second': science + 5, + 'weight': 1.0 / variance, + 'badpix': badpix, + 'sky': sky, + 'gain': gain, + }, + } + with asdf.AsdfFile(tree) as af: + af.write_to(file_name) + fitsio.write(cat_name, np.array(positions, dtype=[('x', float), ('y', float)]), clobber=True) + + # The extension values are "paths" in the asdf file using . to connect the levels. + config = { + 'image_file_name': file_name, + 'cat_file_name': cat_name, + 'image_ext': 'data_arrays.science', + 'weight_ext': 'data_arrays.weight', + 'badpix_ext': 'data_arrays.badpix', + 'sky_ext': 'data_arrays.sky', + 'gain_ext': 'data_arrays.gain', + 'remove_signal_from_weight': True, + 'stamp_size': 24, + 'wcs': {'type': 'PixelScale', 'scale': 0.2}, + } + reader = piff.InputFiles(config) + data = reader.getRawImageData(0) + expected_image = signal.array.copy() + expected_image[30, 30] = -sky[30, 30] + expected_weight = 1.0 / (4 + sky / gain) + expected_weight[badpix != 0] = 0 + expected_weight[30, 30] = 0 + np.testing.assert_allclose(data.image.array, expected_image, atol=1.e-12) + np.testing.assert_allclose(data.weight.array, expected_weight) + np.testing.assert_array_equal(data.gain_image.array, gain) + assert data.image.wcs == galsim.PixelScale(0.2) + assert data.image_pos == [galsim.PositionD(*pos) for pos in positions] + + # Make stars from these input data. + stars = reader.makeStars() + assert len(stars) == len(positions) + for star in stars: + bounds = star.image.bounds + np.testing.assert_allclose(star.image.array, data.image[bounds].array) + np.testing.assert_allclose(star.weight.array, data.weight[bounds].array) + np.testing.assert_array_equal(star.data.gain_image.array, data.gain_image[bounds].array) + + # Multiple data arrays in an asdf file at different paths can represent mutliple input images. + multi_config = { + 'image_file_name': file_name, + 'cat_file_name': cat_name, + 'image_ext': ['data_arrays.science', 'data_arrays.second'], + } + multi = piff.InputFiles(multi_config) + assert multi.nimages == 2 + for i in range(2): + expected = science + 5 * i + expected[30, 30] = 0 + data = multi.getRawImageData(i) + np.testing.assert_array_equal(data.image.array, expected) + assert data.image.wcs == galsim.PixelScale(1.0) + + # It's allowed to get the main image from asdf and another (e.g. weight) from FITS. + weight_name = os.path.join('output', 'asdf_weight.fits') + galsim.Image(1.0 / variance).write(weight_name) + mixed_config = dict(config) + mixed_config.pop('weight_ext') + mixed_config['weight_file_name'] = weight_name + mixed = piff.InputFiles(mixed_config).getRawImageData(0) + np.testing.assert_allclose(mixed.weight.array, expected_weight) + + # It's also allowed get the main image from FITS and others from ASDF. + science_name = os.path.join('output', 'asdf_science.fits') + galsim.Image(science).write(science_name) + mixed_config = dict(config) + mixed_config['image_file_name'] = science_name + mixed_config.pop('image_ext') + for plane in ['weight', 'badpix', 'sky', 'gain']: + mixed_config[plane + '_file_name'] = file_name + mixed = piff.InputFiles(mixed_config).getRawImageData(0) + np.testing.assert_allclose(mixed.image.array, expected_image, atol=1.e-12) + np.testing.assert_allclose(mixed.weight.array, expected_weight) + np.testing.assert_array_equal(mixed.gain_image.array, gain) + + # There is no default ext for asdf. + # Also check invalid ext values, including an integer. + for ext in [None, 1, 'data_arrays.missing', 'invalid']: + invalid = dict(config, image_ext=ext) + error = KeyError if isinstance(ext, str) else ValueError + np.testing.assert_raises(error, piff.InputFiles, invalid) if __name__ == '__main__': setup() @@ -3583,3 +3696,4 @@ def test_input_bandpass(): test_sed_star_io() test_wcs_bandpass_io() test_input_bandpass() + test_asdf() From cbeac860231fabeadf66ceeda6dce67d4d8de6f4 Mon Sep 17 00:00:00 2001 From: Mike Jarvis Date: Tue, 3 Nov 2026 23:42:14 -0500 Subject: [PATCH 13/18] Refactor InputFiles to provide clearer hooks for how the image loading works and where subclasses might want to do something different. --- piff/input.py | 2194 +++++++++++++++++++++--------------------- tests/test_input.py | 132 ++- tests/test_pixel.py | 8 +- tests/test_simple.py | 4 +- 4 files changed, 1187 insertions(+), 1151 deletions(-) diff --git a/piff/input.py b/piff/input.py index 3089ffd5..6666d2db 100644 --- a/piff/input.py +++ b/piff/input.py @@ -22,13 +22,26 @@ import os import galsim import yaml -from typing import NamedTuple +import copy +from dataclasses import dataclass, field -from .util import run_multi, read_asdf_image +from .util import run_multi, read_asdf_image, get_asdf_value from .star import Star, StarData from .config import LoggerWrapper -class RawImageData(NamedTuple): +@dataclass +class ImageMetadata: + """Meta-data from an image on disk. + + It includes the bounds, wcs, and optional header. + """ + bounds: galsim.BoundsI + wcs: galsim.BaseWCS + header: object + + +@dataclass(kw_only=True) +class RawImageData: """Image and catalog data returned by `InputFiles.getRawImageData`. Fields can be accessed by name or unpacked in the order listed below. @@ -39,11 +52,33 @@ class RawImageData(NamedTuple): :param extra_props: Dict of additional catalog properties, with an array for each property. :param gain_image: Per-pixel gain image, or None when no gain image was supplied. """ - image: galsim.Image - weight: galsim.Image - image_pos: list - extra_props: dict - gain_image: galsim.Image | None + # These are the primary attributes, which are used by callers of getRawImageData() + image: galsim.Image | None = None + weight: galsim.Image | None = None + image_pos: list | None = None + extra_props: dict = field(default_factory=dict) + gain_image: galsim.Image | None = None + + # The rest of these are intermediate products we use when building the above data. + image_num: int + config: dict + base: dict + mask: np.ndarray | None = None + sky: float | str | galsim.Image | None = None + + def __post_init__(self): + # Copy one object graph so nested config references stay connected inside the job. + self.config, self.base = copy.deepcopy((self.config, self.base)) + self.base['index_key'] = 'image_num' + self.base['image_num'] = self.image_num + + def __iter__(self): + yield self.image + yield self.weight + yield self.image_pos + yield self.extra_props + yield self.gain_image + class Input(object): """The base class for handling inputs for building a Piff model. @@ -122,12 +157,8 @@ def makeStars(self, logger=None): """Process the input images and star data, cutting out stamps for each star along with other relevant information. - The base class implementation expects the derived class to have appropriately set the - following attributes: - - :stamp_size: The size of the postage stamp to use for the cutouts - :x_col: The name of the column in the catalogs to use for the x position. - :y_col: The name of the column in the catalogs to use for the y position. + Read metadata on first use to establish image WCS solutions and the common pointing. + Per-image settings are parsed in each worker's private configuration context. :param logger: A logger object for logging debug info. [default: None] @@ -135,21 +166,18 @@ def makeStars(self, logger=None): """ logger = LoggerWrapper(logger) + if self.metadata_list is None: + self.readMetadata(logger) + if self.nimages == 1: logger.debug("Making star list") else: logger.debug("Making star list from %d catalogs", self.nimages) - args = [(self.image_kwargs[k], self.cat_kwargs[k], self.wcs_list[k], self.chipnums[k]) - for k in range(self.nimages)] - kwargs = dict(stamp_size=self.stamp_size, - pointing=self.pointing, bandpass=self.bandpass, use_partial=self.use_partial, - invert_weight=self.invert_weight, - remove_signal_from_weight=self.remove_signal_from_weight, - config=self.config, base=self.base) + args = [(image_num,) for image_num in range(self.nimages)] all_stars = run_multi(self._makeStarsFromImage, self.nproc, raise_except=True, - args=args, logger=logger, kwargs=kwargs) + args=args, logger=logger) # Concatenate the star lists into a single list stars = [s for slist in all_stars if slist is not None for s in slist if slist] @@ -166,6 +194,8 @@ def getWCS(self, logger=None): :returns: a dict of WCS solutions (galsim.BaseWCS instances) indexed by chipnum """ + if self.metadata_list is None: + self.readMetadata(logger) return { chipnum : w for w, chipnum in zip(self.wcs_list, self.chipnums) } def getPointing(self, logger=None): @@ -175,6 +205,8 @@ def getPointing(self, logger=None): :returns: a galsim.CelestialCoord of the pointing direction. """ + if self.metadata_list is None: + self.readMetadata(logger) return self.pointing def getBandpass(self, logger=None): @@ -184,6 +216,8 @@ def getBandpass(self, logger=None): :returns: a galsim.Bandpass or None. """ + if self.metadata_list is None: + self.readMetadata(logger) return self.bandpass @@ -248,6 +282,74 @@ class InputFiles(Input): `https://github.com/GalSim-developers/GalSim/wiki/Config-Values`_ + For chromatic PSF fitting, you must define the SED of each star in one of the + following ways: + + 1. Use a single SED for each every star. + + In this case, the SED should probably be some kind of median SED of the stars + in your sample. You won't be capturing the variation in the chromaticity among + the various stars, but at least you will be using the correct average chromatic + effect of the stellar population. For this case, give the SED file name as + ``sed_file_name``. + + Sample config file excerpt:: + + input: + [...] + sed_file_name: 'stellar_sed.fits' + sed_wave_type: 'nm' + sed_flux_type: 'erg cm**(-2) s**(-1) angstrom**(-1)' + + 2. Specify a file name for the SED of each star. + + You may instead want to specify a (potentially) different SED file for each star. + In this case, you can give that file name in the input catalog as one of the + columns. Set ``sed_col`` to the name of the catalog column containing the file names. + + Sample config file excerpt:: + + input: + [...] + sed_col: 'sed_file' + sed_wave_type: 'nm' + sed_flux_type: 'erg cm**(-2) s**(-1) angstrom**(-1)' + + 3. Specify the SED of each star by some label. + + Another way to give each star its own SED is to have the values in the input catalog + be some kind of label indicating which file to use. The mapping of these labels to + file names would then be in a YAML file, which should parse as a dict giving + ``sed_file_name[label]``. In this case, specify ``sed_col`` to be the input column + with the labels and ``sed_file_name`` to be the YAML file with the mapping. + + Sample config file excerpt:: + + input: + [...] + sed_col: 'sed_label' + sed_file_name: 'sed_mapping.yaml' + sed_wave_type: 'nm' + sed_flux_type: 'erg cm**(-2) s**(-1) angstrom**(-1)' + + If you want, you can also put the mapping dict directly in the config file:: + + input: + [...] + sed_col: 'stellar_type' + sed_file_name: + 'F': 'xsl_spectrum_X0529_merged.fits' + 'G': 'xsl_spectrum_X0203_merged.fits' + 'K': 'xsl_spectrum_X0066_merged_scl.fits' + 'M': 'xsl_spectrum_X0527_merged.fits' + sed_wave_type: 'nm' + sed_flux_type: 'erg cm**(-2) s**(-1) angstrom**(-1)' + + In each case, ``sed_wave_type`` and ``sed_flux_type`` are required values, specifying + the units to use for the wavelengths and flux values in the SED file. For SED files + that are FITS tables, you may also want to set ``sed_wave_key`` and ``sed_flux_key`` to + specify which columns correspond to the wave and flux arrays. + There are many other optional parameters, which help govern how the input files are read or interpreted: @@ -332,74 +434,6 @@ class InputFiles(Input): input image(s). required when using ``sed_col`` or ``sed_file_name``. [default: none] - For chromatic PSF fitting, you must define the SED of each star in one of the - following ways: - - 1. Use a single SED for each every star. - - In this case, the SED should probably be some kind of median SED of the stars - in your sample. You won't be capturing the variation in the chromaticity among - the various stars, but at least you will be using the correct average chromatic - effect of the stellar population. For this case, give the SED file name as - ``sed_file_name``. - - Sample config file excerpt:: - - input: - [...] - sed_file_name: 'stellar_sed.fits' - sed_wave_type: 'nm' - sed_flux_type: 'erg cm**(-2) s**(-1) angstrom**(-1)' - - 2. Specify a file name for the SED of each star. - - You may instead want to specify a (potentially) different SED file for each star. - In this case, you can give that file name in the input catalog as one of the - columns. Set ``sed_col`` to the name of the catalog column containing the file names. - - Sample config file excerpt:: - - input: - [...] - sed_col: 'sed_file' - sed_wave_type: 'nm' - sed_flux_type: 'erg cm**(-2) s**(-1) angstrom**(-1)' - - 3. Specify the SED of each star by some label. - - Another way to give each star its own SED is to have the values in the input catalog - be some kind of label indicating which file to use. The mapping of these labels to - file names would then be in a YAML file, which should parse as a dict giving - ``sed_file_name[label]``. In this case, specify ``sed_col`` to be the input column - with the labels and ``sed_file_name`` to be the YAML file with the mapping. - - Sample config file excerpt:: - - input: - [...] - sed_col: 'sed_label' - sed_file_name: 'sed_mapping.yaml' - sed_wave_type: 'nm' - sed_flux_type: 'erg cm**(-2) s**(-1) angstrom**(-1)' - - If you want, you can also put the mapping dict directly in the config file:: - - input: - [...] - sed_col: 'stellar_type' - sed_file_name: - 'F': 'xsl_spectrum_X0529_merged.fits' - 'G': 'xsl_spectrum_X0203_merged.fits' - 'K': 'xsl_spectrum_X0066_merged_scl.fits' - 'M': 'xsl_spectrum_X0527_merged.fits' - sed_wave_type: 'nm' - sed_flux_type: 'erg cm**(-2) s**(-1) angstrom**(-1)' - - In each case, ``sed_wave_type`` and ``sed_flux_type`` are required values, specifying - the units to use for the wavelengths and flux values in the SED file. For SED files - that are FITS tables, you may also want to set ``sed_wave_key`` and ``sed_flux_key`` to - specify which columns correspond to the wave and flux arrays. - :sky_col: The name of a column with sky values. [default: None] :gain_col: The name of a column with gain values. [default: None] :gain_file_name: A file containing a per-pixel effective gain map. [default: None] @@ -448,9 +482,6 @@ class InputFiles(Input): WCS. It should be defined using the same style as a wcs object in GalSim config files. [defulat: None] - The above values are parsed separately for each input image/catalog. In addition, there - are a couple other parameters that are just parsed once: - :invert_weight: Whether the weight maps are actually variance maps, and thus should be inverted to make the usual inverse variance weight. [default: False] :remove_signal_from_weight: Whether the weight (either inverted or not) includes the @@ -471,71 +502,73 @@ class InputFiles(Input): stamps may be smaller than this if the star is near a chip boundary. [default: 32] :ra, dec: The RA, Dec of the telescope pointing. [default: None; See - `setPointing` for details about how this can be specified] + `readMetadata` for details about how this can be specified] :param config: The configuration dict used to define the above parameters. :param base: The base configuration dict if needed for value parsing. [default: None] :param logger: A logger object for logging debug info. [default: None] """ _type_name = 'Files' + _req_params = { + 'image_file_name': str, + 'cat_file_name': str, + } + _opt_params = { + 'dir': str, + 'chipnum': int, + 'x_col': str, + 'y_col': str, + 'ra_col': str, + 'dec_col': str, + 'ra_units': str, + 'dec_units': str, + 'property_cols': list, + 'properties': dict, + 'sed_col': str, + 'sed_file_name': (str, dict), + 'sed_wave_type': str, + 'sed_flux_type': str, + 'sed_wave_key': str, + 'sed_flux_key': str, + 'sed_tol': float, + 'sed_max_samples': int, + 'sky_col': str, + 'gain_col': str, + 'gain_file_name': str, + 'gain_ext': (int, str), + 'flag_col': str, + 'skip_flag': int, + 'use_flag': int, + 'image_ext': (int, str), + 'weight_ext': (int, str), + 'badpix_ext': (int, str), + 'weight_file_name': str, + 'badpix_file_name': str, + 'badpix_zeros': bool, + 'fix_ushort_badpix': bool, + 'sky_file_name': str, + 'sky_ext': (int, str), + 'cat_ext': (int, str), + 'invert_weight': bool, + 'remove_signal_from_weight': bool, + 'stamp_size': int, + 'use_partial': bool, + 'nstars': int, + } def __init__(self, config, base=None, logger=None): - import copy logger = LoggerWrapper(logger) - req = { 'image_file_name': str, - 'cat_file_name': str, - } - opt = { - 'dir' : str, - 'chipnum' : int, - 'x_col' : str, - 'y_col' : str, - 'ra_col' : str, - 'dec_col' : str, - 'ra_units' : str, - 'dec_units' : str, - 'property_cols' : list, - 'properties' : dict, - 'sed_col' : str, - 'sed_file_name' : (str, dict), - 'sed_wave_type' : str, - 'sed_flux_type' : str, - 'sed_wave_key' : str, - 'sed_flux_key' : str, - 'sed_tol' : float, - 'sed_max_samples' : int, - 'sky_col' : str, - 'gain_col' : str, - 'gain_file_name': str, - 'gain_ext': (int, str), - 'flag_col' : str, - 'skip_flag' : int, - 'use_flag' : int, - 'image_ext' : (int, str), - 'weight_ext' : (int, str), - 'badpix_ext' : (int, str), - 'weight_file_name' : str, - 'badpix_file_name' : str, - 'badpix_zeros' : bool, - 'fix_ushort_badpix' : bool, - 'sky_file_name' : str, - 'sky_ext': (int, str), - 'cat_ext' : (int, str), - 'invert_weight' : bool, - 'remove_signal_from_weight' : bool, - 'stamp_size' : int, - 'use_partial' : bool, - 'nstars' : int, - } + req = self._req_params + opt = self._opt_params ignore = [ 'nproc', 'nimages', 'ra', 'dec', 'wcs', 'bandpass', 'sky', 'gain', 'satur', 'noise', 'trust_pos' ] - # We're going to change the config dict a bit. Make a copy so we don't mess up the - # user's original dict (in case they care). + # Normalize filenames and deprecated keys on copies of the caller's configuration. config = copy.deepcopy(config) base = copy.deepcopy(base) if base is not None else {'input': config} + # Copy deprecated extension selectors to their canonical names before validation. for prefix in ['image', 'weight', 'badpix', 'sky', 'cat']: old = prefix + '_hdu' new = prefix + '_ext' @@ -547,6 +580,8 @@ def __init__(self, config, base=None, logger=None): config[new] = config[old] ignore.append(old) + # A filename and extension together select one plane; alternative sky or gain + # sources are mutually exclusive. sky_sources = sum(['sky' in config, 'sky_col' in config, 'sky_file_name' in config or 'sky_ext' in config]) if sky_sources > 1: @@ -559,11 +594,9 @@ def __init__(self, config, base=None, logger=None): raise ValueError("Specify only one gain source: gain, gain_col, or " "gain_file_name/gain_ext.") - # In GalSim, the base dict holds additional parameters that may be of use. - # For now, add index_kex, as this will be the only thing we index anything on. + # Index GalSim lists and sequences by input image rather than by star. base['index_key'] = 'image_num' - # Convert options 2 and 3 above into option 4. (1 is also parseable by GalSim's config.) nimages = None image_list = None cat_list = None @@ -572,24 +605,13 @@ def __init__(self, config, base=None, logger=None): if 'nproc' in config: self.nproc = galsim.config.ParseValue(config, 'nproc', base, int)[0] - top_level_opt = { - 'stamp_size' : int, - 'invert_weight' : bool, - 'remove_signal_from_weight' : bool, - 'use_partial' : bool, - } - top_level_params = galsim.config.GetAllParams( - config, base, opt=top_level_opt, ignore=list(req) + list(opt) + ignore)[0] - config.pop('_get') - self.stamp_size = top_level_params.get('stamp_size', 32) - self.invert_weight = top_level_params.get('invert_weight', False) - self.remove_signal_from_weight = top_level_params.get('remove_signal_from_weight', False) - self.use_partial = top_level_params.get('use_partial', False) - if 'nstars' in config: logger.error("input.nstars is deprecated; use select.nstars for the new global " "highest-S/N behavior.") + # The number of images may be either explicit (nimages) or implicit in the length of + # a list, which may include a glob (e.g. *.fits). If there are multiple such lists, then + # the lengths must match. if 'nimages' in config: nimages = galsim.config.ParseValue(config, 'nimages', base, int)[0] if nimages < 1: @@ -604,13 +626,14 @@ def __init__(self, config, base=None, logger=None): raise ValueError("nimages = %s doesn't match length of image_ext list (%d)" % ( nimages, len(config['image_ext']))) - # Deal with dir here, since sometimes we need to have it already attached for glob - # to work. + # Apply dir before expanding literal filename patterns, then remove it so later + # parsing does not apply it again. if 'dir' in config: dir = galsim.config.ParseValue(config, 'dir', base, str)[0] del config['dir'] - # Convert Current/Eval shorthand before literal filenames are expanded as glob patterns. + # Preserve @/$ expressions as config dictionaries so they are evaluated per image, + # rather than treated as literal filename patterns by glob.glob later. for key in ['image_file_name', 'cat_file_name', 'sky_file_name', 'weight_file_name', 'badpix_file_name', 'gain_file_name']: value = config.get(key) @@ -619,6 +642,8 @@ def __init__(self, config, base=None, logger=None): elif isinstance(value, str) and value.startswith('$'): config[key] = {'type': 'Eval', 'str': value[1:]} + # Turn literal science filenames and glob patterns into ordered lists. Config + # dictionaries remain unevaluated and require the image count to be known already. if 'image_file_name' not in config: raise TypeError('Parameter image_file_name is required') elif isinstance(config['image_file_name'], list): @@ -642,6 +667,8 @@ def __init__(self, config, base=None, logger=None): else: raise ValueError("image_file_name should be either a dict or a string") + # Reuse a single science file when multiple images/extensions were requested; + # otherwise its list length must agree with the requested image count. if image_list is not None: logger.debug('image_list = %s',image_list) if len(image_list) == 1 and nimages is not None and nimages > 1: @@ -656,83 +683,29 @@ def __init__(self, config, base=None, logger=None): logger.debug('nimages = %d',nimages) assert nimages is not None - # Set up sky_file_name if appropriate - if 'sky_file_name' not in config: - pass - elif isinstance(config['sky_file_name'], str): - sky_file_name = config['sky_file_name'] - if dir is not None: - sky_file_name = os.path.join(dir, sky_file_name) - sky_list = sorted(glob.glob(sky_file_name)) - if len(sky_list) == 0: - raise ValueError("No files found corresponding to "+config['sky_file_name']) - if len(sky_list) == 1 and nimages is not None and nimages > 1: - logger.verbose("Using the same sky file for all images") - sky_list = sky_list * nimages - elif nimages is not None and len(sky_list) != nimages: - raise ValueError("nimages = %s doesn't match length of sky_file_name list (%d)"%( - nimages, len(sky_list))) - config['sky_file_name'] = sky_list - elif not isinstance(config['sky_file_name'], dict): - raise ValueError("sky_file_name should be either a dict or a string") - - if 'weight_file_name' not in config: - pass - elif isinstance(config['weight_file_name'], str): - weight_file_name = config['weight_file_name'] - if dir is not None: - weight_file_name = os.path.join(dir, weight_file_name) - weight_list = sorted(glob.glob(weight_file_name)) - if len(weight_list) == 0: - raise ValueError("No files found corresponding to "+config['weight_file_name']) - if len(weight_list) == 1 and nimages is not None and nimages > 1: - logger.verbose("Using the same weight file for all images") - weight_list = weight_list * nimages - elif nimages is not None and len(weight_list) != nimages: - raise ValueError("nimages = %s doesn't match length of weight_file_name list (%d)"%( - nimages, len(weight_list))) - config['weight_file_name'] = weight_list - elif not isinstance(config['weight_file_name'], dict): - raise ValueError("weight_file_name should be either a dict or a string") - - if 'badpix_file_name' not in config: - pass - elif isinstance(config['badpix_file_name'], str): - badpix_file_name = config['badpix_file_name'] - if dir is not None: - badpix_file_name = os.path.join(dir, badpix_file_name) - badpix_list = sorted(glob.glob(badpix_file_name)) - if len(badpix_list) == 0: - raise ValueError("No files found corresponding to "+config['badpix_file_name']) - if len(badpix_list) == 1 and nimages is not None and nimages > 1: - logger.verbose("Using the same badpix file for all images") - badpix_list = badpix_list * nimages - elif nimages is not None and len(badpix_list) != nimages: - raise ValueError("nimages = %s doesn't match length of badpix_file_name list (%d)"%( - nimages, len(badpix_list))) - config['badpix_file_name'] = badpix_list - elif not isinstance(config['badpix_file_name'], dict): - raise ValueError("badpix_file_name should be either a dict or a string") - - if 'gain_file_name' not in config: - pass - elif isinstance(config['gain_file_name'], str): - gain_file_name = config['gain_file_name'] - if dir is not None: - gain_file_name = os.path.join(dir, gain_file_name) - gain_list = sorted(glob.glob(gain_file_name)) - if len(gain_list) == 0: - raise ValueError("No files found corresponding to " + config['gain_file_name']) - if len(gain_list) == 1 and nimages > 1: - logger.verbose("Using the same gain file for all images") - gain_list = gain_list * nimages - elif len(gain_list) != nimages: - raise ValueError("nimages = %s doesn't match length of gain_file_name list (%d)" % ( - nimages, len(gain_list))) - config['gain_file_name'] = gain_list - elif not isinstance(config['gain_file_name'], dict): - raise ValueError("gain_file_name should be either a dict or a string") - + # Expand auxiliary file patterns in the same order as the science files, reusing + # a single match for every image. + for key in ['sky_file_name', 'weight_file_name', 'badpix_file_name', 'gain_file_name']: + if key not in config: + continue + value = config[key] + if isinstance(value, str): + pattern = os.path.join(dir, value) if dir is not None else value + file_list = sorted(glob.glob(pattern)) + if len(file_list) == 0: + raise ValueError("No files found corresponding to " + value) + if len(file_list) == 1 and nimages > 1: + logger.verbose("Using the same %s for all images", key) + file_list = file_list * nimages + elif len(file_list) != nimages: + raise ValueError("nimages = %s doesn't match length of %s list (%d)" % + (nimages, key, len(file_list))) + config[key] = file_list + elif not isinstance(value, dict): + raise ValueError("%s should be either a dict or a string" % key) + + # Catalog filenames also accept explicit lists, literal names, glob patterns, or + # per-image config dictionaries. None skips catalog loading when restoring stars. if 'cat_file_name' not in config: raise TypeError('Parameter cat_file_name is required') elif isinstance(config['cat_file_name'], list): @@ -751,6 +724,7 @@ def __init__(self, config, base=None, logger=None): elif not isinstance(config['cat_file_name'], (dict, type(None))): raise ValueError("cat_file_name should be either a dict or a string") + # Pair catalogs with science images, or reuse a single catalog for every image. if cat_list is not None: logger.debug('cat_list = %s',cat_list) if len(cat_list) == 1 and nimages > 1: @@ -762,403 +736,603 @@ def __init__(self, config, base=None, logger=None): config['cat_file_name'] = cat_list self.nimages = nimages - self.chipnums = list(range(nimages)) - self.image_file_name = [] - self.cat_file_name = [] - self.image_kwargs = [] - self.cat_kwargs = [] + # Just check that optional parameters are valid without parsing them. + # Most of the opt params will be parsed in later stages. + galsim.config.CheckAllParams(config, req=req, opt=opt, ignore=ignore) self.config = galsim.config.CleanConfig(config) self.base = galsim.config.CleanConfig(base) + self.metadata_list = None - logger.verbose("Reading in %d images",nimages) - for image_num in range(nimages): - - # This changes for each input image. - galsim.config.RemoveCurrent(base) - base['index_key'] = 'image_num' - base['image_num'] = image_num - - logger.debug("config = %s", config) - params = galsim.config.GetAllParams(config, base, req=req, opt=opt, ignore=ignore)[0] - logger.debug("image_num = %d: params = %s", image_num, params) - - # Update the chipnum if not just using image_num - if 'chipnum' in params: - self.chipnums[image_num] = params['chipnum'] - - # Read the image - image_file_name = params['image_file_name'] - image_ext = params.get('image_ext', None) - weight_file_name = params.get('weight_file_name', None) - weight_ext = params.get('weight_ext', None) - badpix_file_name = params.get('badpix_file_name', None) - badpix_ext = params.get('badpix_ext', None) - badpix_zeros = params.get('badpix_zeros', False) - fix_ushort_badpix = params.get('fix_ushort_badpix', False) - sky_file_name = params.get('sky_file_name', None) - sky_ext = params.get('sky_ext', None) - if sky_file_name is None and sky_ext is not None: - sky_file_name = image_file_name - gain_file_name = params.get('gain_file_name', None) - gain_ext = params.get('gain_ext', None) - if gain_file_name is None and gain_ext is not None: - gain_file_name = image_file_name - self.image_file_name.append(image_file_name) - self.image_kwargs.append({ - 'image_file_name' : image_file_name, - 'image_ext' : image_ext, - 'weight_file_name' : weight_file_name, - 'weight_ext' : weight_ext, - 'badpix_file_name' : badpix_file_name, - 'badpix_ext' : badpix_ext, - 'badpix_zeros' : badpix_zeros, - 'fix_ushort_badpix' : fix_ushort_badpix, - 'sky_file_name' : sky_file_name, - 'sky_ext' : sky_ext, - 'gain_file_name': gain_file_name, - 'gain_ext': gain_ext, - 'image_num' : image_num, - 'config' : self.config, - 'base' : self.base, - }) - - # Read the catalog - cat_file_name = params['cat_file_name'] - cat_ext = params.get('cat_ext', None) - x_col = params.get('x_col', 'x') - y_col = params.get('y_col', 'y') - ra_col = params.get('ra_col', None) - dec_col = params.get('dec_col', None) - ra_units = params.get('ra_units', 'deg') - dec_units = params.get('dec_units', 'deg') - flag_col = params.get('flag_col', None) - skip_flag = params.get('skip_flag', -1) - use_flag = params.get('use_flag', None) - property_cols = params.get('property_cols', None) - properties = params.get('properties', None) - sed_col = params.get('sed_col', None) - sed_file_name = params.get('sed_file_name', None) - sed_wave_type = params.get('sed_wave_type', None) - sed_flux_type = params.get('sed_flux_type', None) - sed_wave_key = params.get('sed_wave_key', 'WAVE') - sed_flux_key = params.get('sed_flux_key', 'FLUX') - sed_tol = params.get('sed_tol', 0.0) - sed_max_samples = params.get('sed_max_samples', 0) - if 'bandpass' in config: - bandpass = galsim.config.BuildBandpass(config, 'bandpass', base, logger)[0] - else: - if sed_col is not None or sed_file_name is not None: - raise ValueError("bandpass is required when using sed_col or sed_file_name") - bandpass = None - sky_col = params.get('sky_col', None) - gain_col = params.get('gain_col', None) - nstars = params.get('nstars', None) - - self.cat_file_name.append(cat_file_name) - self.cat_kwargs.append({ - 'cat_file_name' : cat_file_name, - 'cat_ext' : cat_ext, - 'x_col' : x_col, - 'y_col' : y_col, - 'ra_col' : ra_col, - 'dec_col' : dec_col, - 'ra_units' : ra_units, - 'dec_units' : dec_units, - 'flag_col' : flag_col, - 'skip_flag' : skip_flag, - 'use_flag' : use_flag, - 'property_cols': property_cols, - 'properties': properties, - 'sed_col': sed_col, - 'sed_file_name': sed_file_name, - 'sed_wave_type': sed_wave_type, - 'sed_flux_type': sed_flux_type, - 'sed_wave_key': sed_wave_key, - 'sed_flux_key': sed_flux_key, - 'sed_tol': sed_tol, - 'sed_max_samples': sed_max_samples, - 'sky_col' : sky_col, - 'gain_col' : gain_col, - 'nstars' : nstars, - 'stamp_size' : self.stamp_size, - 'config' : self.config, - 'base' : self.base, - }) - - self.bandpass = bandpass - - # Read all the wcs's, since we'll need this for the pointing, which in turn we'll - # need for when we make the stars. - self.setWCS(config, base, logger) - - # Finally, set the pointing coordinate. - # Note: setPointing will do the config parsing of these if appropriate. - ra = config.get('ra', None) - dec = config.get('dec', None) - self.setPointing(ra, dec, logger) - - def load_images(self, stars, logger=None): - """Load the image data into a list of Stars. + # + # The next set of methods are intended to provide hooks for subclasses to potentially + # change how aspects of the read are performed. Images may be constructed in memory from + # other data in the input file, or additional operations might be performed on the data, etc. + # Data are held in a RawImageData object, called data in all of these functions. + # - We don't store the image data for Stars when we write them to a file, since that - would take up a lot of space and is usually not desired. However, we do store the - bounds in the original image where the star was cutout, so if you want to load back in - the original data from the image file(s), you can do so with this function. + def load_image(self, data, logger): + """Load the main image. - :param stars: A list of Star instances. - :param logger: A logger object for logging debug info. [default: None] + Input data: image_num, config, base. + This function sets: image - :returns: a new list of Stars with the images information loaded. + The image includes a header and wcs as appropriate. It is also stored in + base['_current_image'] for possible use by later config processing. """ - logger = LoggerWrapper(logger) + kwargs = self._parse_params(data, {'image_file_name': None, 'image_ext': None}) + logger.info("Reading image file %s", kwargs['image_file_name']) + data.image = self.read_image(kwargs['image_file_name'], kwargs['image_ext'], + read_header=True) + if data.image.dtype not in [np.float32, np.float64]: + header = data.image.header # This doesn't get copied by view(). + data.image = data.image.view(dtype=np.float32) + data.image.header = header + data.base['_current_image'] = data.image + + def load_weight(self, data, logger): + """Load an optional weight image. + + Input data: image_num, config, base. + This function sets: weight + + This loads the raw weight image, which may or may not be in the eventual inverse + variance format. That will be done in finalize_weight, since it may need other + things to be loaded first. Entries that should eventually be zero weight may be + set to zero here. The inversion will not change them. + """ + kwargs = self._parse_params(data, { + 'weight_file_name': None, + 'weight_ext': None, + 'image_file_name': None, + }) + if kwargs['weight_file_name'] is not None or kwargs['weight_ext'] is not None: + file_name = kwargs['weight_file_name'] or kwargs['image_file_name'] + logger.verbose("Reading weight image from %s, extension %s.", + file_name, kwargs['weight_ext']) + data.weight = self.read_image(file_name, kwargs['weight_ext'], read_header=False) + if np.all(data.weight.array == 0): + logger.error("According to the weight mask in %s, all pixels have zero weight!", + kwargs['image_file_name']) - images = {} - weight_images = {} - gain_images = {} - for image_num in range(self.nimages): - data = self.getRawImageData(image_num, logger) - images[self.chipnums[image_num]] = data.image - weight_images[self.chipnums[image_num]] = data.weight - gain_images[self.chipnums[image_num]] = data.gain_image + def load_gain(self, data, logger): + """Load an optional per-pixel gain map. - loaded_stars = [] - for star in stars: - chipnum = star['chipnum'] - image = images[chipnum][star.data.image.bounds].copy() - if 'sky' in star.data.properties: - image -= star['sky'] - weight = weight_images[chipnum][star.data.weight.bounds].copy() - gain_image = gain_images[chipnum] - if gain_image is not None: - gain_image = gain_image[image.bounds].copy() - data = star.data.withNew(image=image, weight=weight, orig_weight=weight, - gain_image=gain_image) - loaded_stars.append(Star(data=data, fit=star.fit)) + Input data: image_num, config, base. + This function sets: gain_image + """ + kwargs = self._parse_params(data, { + 'gain_file_name': None, + 'gain_ext': None, + 'image_file_name': None, + }) + if kwargs['gain_file_name'] is not None or kwargs['gain_ext'] is not None: + file_name = kwargs['gain_file_name'] or kwargs['image_file_name'] + logger.verbose("Reading gain image from %s, extension %s.", + file_name, kwargs['gain_ext']) + data.gain_image = self.read_image(file_name, kwargs['gain_ext'], + read_header=False) + if data.gain_image.bounds != data.image.bounds: + raise ValueError('Gain image bounds do not match science image bounds') - return loaded_stars + def build_mask(self, data, logger): + """Build a mask of which pixels Piff should not use. - def getRawImageData(self, image_num, logger=None): - """Read an image and catalog. + Input data: image_num, image, weight, gain_image, config, base. + This function sets: mask, and may update image. - :param image_num: The index of the image to read. - :param logger: A logger object for logging debug info. [default: None] + The mask comes from several sources in the default implementation: + 1. A badpix image if one is specified. + 2. Any weight=0 pixels (regardless of whether this is variance or inverse variance yet). + 3. Non-finite pixels in the image, weight or gain. + 4. Pixels with negative weight or gain. + 5. If badpix_zeros, any data pixels with value 0. - :returns: A `RawImageData` named tuple with fields image, weight, image_pos, - extra_props, and gain_image. Fields can be accessed by name or unpacked - in that order. + The final mask is True for any masked pixels. """ - self.base['index_key'] = 'image_num' - self.base['image_num'] = image_num - return self._getRawImageData(self.image_kwargs[image_num], self.cat_kwargs[image_num], - self.wcs_list[image_num], self.invert_weight, - self.remove_signal_from_weight, - config=self.config, base=self.base, logger=logger) + data.mask = np.zeros(data.image.array.shape, dtype=bool) + kwargs = self._parse_params(data, { + 'badpix_file_name': None, + 'badpix_ext': None, + 'badpix_zeros': False, + 'fix_ushort_badpix': False, + 'image_file_name': None, + }) + if kwargs['badpix_file_name'] is not None or kwargs['badpix_ext'] is not None: + file_name = kwargs['badpix_file_name'] or kwargs['image_file_name'] + logger.verbose("Reading badpix image from %s, extension %s.", + file_name, kwargs['badpix_ext']) + badpix = self.read_image(file_name, kwargs['badpix_ext'], read_header=False) - @staticmethod - def _handle_depr_image_value(value, header, name, logger): - # gain, satur, noise, sky, ra, and dec used to allow bare FITS header keys. - # Now this functionality should use the ImageHeaderValue type to be more explicit. - # The old behavior still works, but is deprecated. - if isinstance(value, str) and value[0] not in '@$': - logger.error("WARNING: Using a bare FITS header key for %s is deprecated. " - "Use {type: ImageHeaderValue, key: %s} instead.", name, value) - value = header[value] - # Pointing values may be sexagesimal strings, parsed by setPointing. - if name not in ('ra', 'dec'): - value = float(value) - return value + # Correct legacy unsigned-integer offsets if requested. + if kwargs['fix_ushort_badpix']: + if np.any(badpix.array > 32767): + logger.debug('min(badpix) = %s',np.min(badpix.array)) + logger.debug('max(badpix) = %s',np.max(badpix.array)) + logger.debug("subtracting 32768 from all values in badpix image") + badpix -= 32768 + if np.any(badpix.array < -32767): + logger.debug('min(badpix) = %s',np.min(badpix.array)) + logger.debug('max(badpix) = %s',np.max(badpix.array)) + logger.debug("adding 32768 to all values in badpix image") + badpix += 32768 + if np.all(badpix.array != 0): + logger.error("According to the bad pixel array in %s, all pixels are masked!", + kwargs['image_file_name']) + data.mask |= badpix.array != 0 - @classmethod - def _getRawImageData(cls, image_kwargs, cat_kwargs, wcs, - invert_weight, remove_signal_from_weight, - config, base, logger=None): - from .config import LoggerWrapper - logger = LoggerWrapper(logger) - image, weight, gain_image = cls.readImage(logger=logger, **image_kwargs) + if data.weight is not None: + weight = data.weight.array + if np.any(weight < 0): + logger.warning("Warning: weight map has invalid negative-valued pixels. "+ + "Taking them to be 0.0") + nonfinite = ~np.isfinite(weight) + if np.any(nonfinite): + logger.warning("Warning: weight map has non-finite pixels. " + "Taking them to be 0.0") + data.mask |= nonfinite | (weight <= 0) + if data.gain_image is not None: + gain = data.gain_image.array + nonfinite = ~np.isfinite(gain) + if np.any(nonfinite): + logger.warning("Warning: gain image has non-finite pixels. Masking them.") + nonpositive = gain <= 0 + if np.any(nonpositive): + logger.warning("Warning: gain image has non-positive pixels. Masking them.") + data.mask |= nonfinite | nonpositive + if kwargs['badpix_zeros']: + data.mask |= data.image.array == 0 + + # Clear nonfinite science so downstream weight * image cannot produce NaN * 0. + nonfinite = ~np.isfinite(data.image.array) + if np.any(nonfinite): + logger.warning("Warning: image has non-finite pixels. " + "Masking and setting them to 0.0") + data.mask |= nonfinite + data.image.array[nonfinite] = 0 + + def subtract_sky(self, data, logger): + """Load or estimate the image-level sky and subtract it from the science image. + + Input data: image_num, image, mask, config, base. + This function sets: sky, and updates: image + + The sky is retained for later calculations, which may use it. + + This doesn't handle any catalog-level sky values. Those are handled by `load_catalog`. + """ + if 'sky' in data.config: + data.sky = galsim.config.ParseValue(data.config, 'sky', data.base, (float, str))[0] + kwargs = self._parse_params(data, { + 'sky_file_name': None, + 'sky_ext': None, + 'image_file_name': None, + }) + if kwargs['sky_file_name'] is not None or kwargs['sky_ext'] is not None: + file_name = kwargs['sky_file_name'] or kwargs['image_file_name'] + logger.verbose("Reading sky image from %s, extension %s.", + file_name, kwargs['sky_ext']) + data.sky = self.read_image(file_name, kwargs['sky_ext'], + read_header=False) + if isinstance(data.sky, str): + if data.sky == 'median': + data.sky = np.median(data.image.array[~data.mask]) + elif data.sky == 'sep': + import sep + # SEP requires contiguous arrays with native byte order. + array = np.ascontiguousarray( + data.image.array, dtype=data.image.array.dtype.newbyteorder('=')) + background = sep.Background(array, mask=data.mask) + data.sky = galsim.Image(background.back(), bounds=data.image.bounds, + wcs=data.image.wcs) + else: + data.sky = self._handle_depr_image_value( + data.sky, data.image.header, 'sky', logger) - if invert_weight: - weight.invertSelf() + if data.sky is not None: + data.image -= data.sky - # Update the wcs - image.wcs = wcs + def finalize_weight(self, data, logger): + """Finish building the weight image based on all the ancillary data. - image_pos, extra_props = cls.readStarCatalog( - logger=logger, image=image, **cat_kwargs) + Input data: image_num, image, weight, gain_image, mask, image_pos, extra_props, + config, base. + This function sets or updates: weight, and may update mask, extra_props - if remove_signal_from_weight: - nmasked = np.count_nonzero(weight.array == 0) - # Subtract the mean catalog sky from the signal used for variance removal. - # Image-level backgrounds have already been subtracted by readImage. - if 'sky' in extra_props: - signal = image - np.mean(extra_props['sky']) + This finishes the calculation of the weight image, converting it to an inverse + variance weight if necessary and removing any contribution from the signal's + Poisson variance. + """ + if data.weight is not None: + data.weight._piff_default_weight = False + else: + noise = None + if 'noise' in data.config: + noise = galsim.config.ParseValue(data.config, 'noise', data.base, (float, str))[0] + if noise is not None: + noise = self._handle_depr_image_value(noise, data.image.header, 'noise', logger) + logger.debug("Making uniform weight image based on noise variance = %f", noise) + data.weight = galsim.ImageF(data.image.bounds, init_value=1./noise) + data.weight._piff_default_weight = False else: - signal = image - if gain_image is not None: - weight, _ = cls._removeSignalFromWeight(signal, weight, gain=gain_image) - elif 'gain' in extra_props: - # If given, use the mean gain when removing the signal. - # This isn't quite right, but hopefully the gain won't vary too much for - # different objects, so it should be close. - gain = np.mean(extra_props['gain']) - weight, _ = cls._removeSignalFromWeight(signal, weight, gain=gain) + logger.debug("Making trivial (wt==1) weight image") + data.weight = galsim.ImageF(data.image.bounds, init_value=1) + data.weight._piff_default_weight = True + data.weight.array[data.mask] = 0 + params = self._parse_params(data, { + 'invert_weight': False, + 'remove_signal_from_weight': False, + }) + if params['invert_weight']: + data.weight._invertSelf() + if params['remove_signal_from_weight']: + nmasked = np.count_nonzero(data.weight.array == 0) + # Image-level backgrounds have already been subtracted. Catalog backgrounds + # currently contribute their mean to the whole-image variance calculation. + if 'sky' in data.extra_props: + signal = data.image - np.mean(data.extra_props['sky']) else: - # If no gain provided, then we want to estimate the gain from the weight image. - weight, g = cls._removeSignalFromWeight(signal, weight) - extra_props['gain'] = np.array([g] * len(image_pos), dtype=float) - logger.info("Empirically determined gain = %f",g) + signal = data.image + if data.gain_image is not None: + data.weight, _ = self._removeSignalFromWeight(signal, data.weight, + gain=data.gain_image) + elif 'gain' in data.extra_props: + gain = np.mean(data.extra_props['gain']) + data.weight, _ = self._removeSignalFromWeight(signal, data.weight, gain=gain) + else: + data.weight, gain = self._removeSignalFromWeight(signal, data.weight) + data.extra_props['gain'] = np.array([gain] * len(data.image_pos), dtype=float) + logger.info("Empirically determined gain = %f", gain) logger.verbose("Removed signal from weight image.") - added_masks = np.count_nonzero(weight.array == 0) - nmasked + data.mask |= data.weight.array == 0 + added_masks = np.count_nonzero(data.weight.array == 0) - nmasked if added_masks: logger.warning("Masked %d pixels with invalid variance after removing source noise", added_masks) - return RawImageData(image=image, weight=weight, image_pos=image_pos, - extra_props=extra_props, gain_image=gain_image) + def update_wcs(self, data, logger): + """Update the image's wcs if necessary. - @classmethod - def _makeStarsFromImage(cls, image_kwargs, cat_kwargs, wcs, chipnum, - stamp_size, pointing, bandpass, use_partial, - invert_weight, remove_signal_from_weight, - config, base, logger): - """Make "stars" from a single input image - """ - image, wt, image_pos, extra_props, gain_image = cls._getRawImageData( - image_kwargs, cat_kwargs, wcs, invert_weight, remove_signal_from_weight, - config, base, logger) - logger.verbose("Processing catalog %s with %d objects",chipnum,len(image_pos)) + Input data: image + This function updates: image.wcs - objects = [] + The image's wcs at this point is the WCS from the input file. If there is a different + WCS specified by the config, it has already been processed and stored in + self.wcs_list. This step updates the image to have the correct WCS attached. + """ + data.image.wcs = self.wcs_list[data.image_num] - # Make a dict of the types to use for the extra_props, so we can preserve the type - # if we need to output them (e.g. in ShapeCatalog). - prop_types = {key: extra_props[key].dtype.type for key in extra_props} + def load_catalog(self, data, logger): + """Load star positions and properties. - for k in range(len(image_pos)): - x = image_pos[k].x - y = image_pos[k].y - icen = int(x+0.5) - jcen = int(y+0.5) - half_size = stamp_size // 2 - bounds = galsim.BoundsI(icen+half_size-stamp_size+1, icen+half_size, - jcen+half_size-stamp_size+1, jcen+half_size) - if not image.bounds.includes(bounds): - bounds = bounds & image.bounds - if not bounds.isDefined(): - logger.warning("Object at position %f,%f is off the edge of the image.", x, y) - logger.warning("Skipping this object.") - continue - if use_partial: - logger.verbose("Object at position %f,%f overlaps the edge of the image. " - "Using smaller than the full stamp size: %s", x, y, bounds) - else: - logger.info("Object at position %f,%f overlaps the edge of the image.", x, y) - logger.info("Skipping this object.") - continue - stamp = image[bounds].copy() - wt_stamp = wt[bounds].copy() - props = { 'chipnum' : chipnum } + Input data: image_num, image, config, base. + This function sets: image_pos, extra_props + """ + params = self._parse_params(data, { + 'cat_file_name': None, + 'cat_ext': None, + 'x_col': 'x', + 'y_col': 'y', + 'ra_col': None, + 'dec_col': None, + 'ra_units': 'deg', + 'dec_units': 'deg', + 'flag_col': None, + 'skip_flag': -1, + 'use_flag': None, + 'property_cols': None, + 'properties': None, + 'sed_col': None, + 'sed_file_name': None, + 'sed_wave_type': None, + 'sed_flux_type': None, + 'sed_wave_key': 'WAVE', + 'sed_flux_key': 'FLUX', + 'sed_tol': 0.0, + 'sed_max_samples': 0, + 'sky_col': None, + 'gain_col': None, + 'nstars': None, + 'stamp_size': 32, + }) + if self.bandpass is None and (params['sed_col'] is not None or + params['sed_file_name'] is not None): + raise ValueError("bandpass is required when using sed_col or sed_file_name") + image = data.image + config = data.config + base = data.base + + if params['cat_file_name'] is None: + # This is possible e.g. when loading images into an existing list of star instances. + logger.info("Not reading input catalog.") + data.image_pos = data.extra_props = None + return - # if an object is totally masked, then don't add it! - if np.all(wt_stamp.array == 0): - logger.warning("Object at position %f,%f is completely masked.", x, y) - logger.warning("Skipping this object.") - continue + # Read in the star catalog + logger.info("Reading input catalog %s.",params['cat_file_name']) + cat = self.read_catalog(params['cat_file_name'], params['cat_ext']) - # Add this object's entry in each list of the extra_props dictionary - # to the StarData properties dictionary - for key in extra_props: - logger.debug("Assigning {} value = {}".format(key, extra_props[key][k])) - props[key] = extra_props[key][k] + gain = None + if 'gain' in config: + gain = galsim.config.ParseValue(config, 'gain', base, (float, str))[0] - # If any pixels are saturated, skip it. - if 'satur' in props: - max_val = np.max(stamp.array) - if max_val > props['satur']: - logger.info("Object at position %f,%f has saturated pixels.", x, y) - logger.info("Maximum value is %f.", max_val) - logger.info("Skipping this object.") - continue + satur = None + if 'satur' in config: + satur = galsim.config.ParseValue(config, 'satur', base, (float, str))[0] - # Subtract the sky - if 'sky' in props: - sky = props['sky'] - logger.debug("Subtracting off sky = %f", sky) - logger.debug("Median pixel value = %f", np.median(stamp.array)) - stamp -= sky + trust_pos = None + if 'trust_pos' in config: + trust_pos = galsim.config.ParseValue(config, 'trust_pos', base, bool)[0] - pos = galsim.PositionD(x,y) - gain_stamp = gain_image[bounds].copy() if gain_image is not None else None - data = StarData(stamp, pos, weight=wt_stamp, pointing=pointing, - bandpass=bandpass, - properties=props, property_types=prop_types, - gain_image=gain_stamp) - # Attach an attribute so we can tell later whether the weight is real or - # if it's just the default w=1.0. - data._piff_default_weight = getattr(wt, '_piff_default_weight', False) - star = Star(data, None) + if params['flag_col'] is not None: + if params['flag_col'] not in cat.dtype.names: + raise ValueError("flag_col = %s is not a column in %s" % + (params['flag_col'], params['cat_file_name'])) + col = cat[params['flag_col']] + if len(col.shape) == 2: + logger.info("Flag col (%s) is multidimensional. Treating as an array of bool", + params['flag_col']) + if params['use_flag'] is not None: + # Remove any objects with flag & use_flag == 0 + mask = self._flag_select(col, params['use_flag']) == 0 + logger.verbose("Removing objects with flag (col %s) & %d == 0", + params['flag_col'], params['use_flag']) + if params['skip_flag'] != -1: + mask |= self._flag_select(col, params['skip_flag']) != 0 + logger.verbose("Removing objects with flag (col %s) & %d != 0", + params['flag_col'], params['skip_flag']) + else: + # Remove any objects with flag & skip_flag != 0 + mask = self._flag_select(col, params['skip_flag']) != 0 + if params['skip_flag'] == -1: + logger.verbose("Removing objects with flag (col %s) != 0",params['flag_col']) + else: + logger.verbose("Removing objects with flag (col %s) & %d != 0", + params['flag_col'], params['skip_flag']) + cat = cat[mask == 0] - objects.append(star) + # Limit to nstars objects + if params['nstars'] is not None and params['nstars'] < len(cat): + logger.verbose("Limiting to %d objects for %s", + params['nstars'], params['cat_file_name']) + cat = cat[:params['nstars']] - return objects + # Make the list of positions: + if params['ra_col'] is not None or params['dec_col'] is not None: + if params['ra_col'] is None or params['dec_col'] is None: + raise ValueError("ra_col and dec_col are both required if one is provided.") + if params['ra_col'] not in cat.dtype.names: + raise ValueError("ra_col = %s is not a column in %s" % + (params['ra_col'], params['cat_file_name'])) + if params['dec_col'] not in cat.dtype.names: + raise ValueError("dec_col = %s is not a column in %s" % + (params['dec_col'], params['cat_file_name'])) + logger.debug("Starting to make a list of positions from ra, dec") + ra_values = cat[params['ra_col']] + dec_values = cat[params['dec_col']] + params['ra_units'] = galsim.AngleUnit.from_name(params['ra_units']) + params['dec_units'] = galsim.AngleUnit.from_name(params['dec_units']) + ra = ra_values * params['ra_units'] + dec = dec_values * params['dec_units'] + logger.debug("Initially %d positions",len(ra)) - def setWCS(self, config, base, logger): - self.wcs_list = [] - self.center_list = [] - for image_num, kwargs in enumerate(self.image_kwargs): - galsim.config.RemoveCurrent(base) # Makes any @ items work correctly - base['image_num'] = image_num - image_file_name = kwargs['image_file_name'] - image_ext = kwargs['image_ext'] - image = self._read_image(image_file_name, image_ext, read_header=True) - if 'wcs' in config: - logger.info("Using custom wcs from config for %s",image_file_name) - base['index_key'] = 'image_num' - base['image_num'] = image_num - base['_current_image'] = image - wcs = galsim.config.BuildWCS(config, 'wcs', base, logger) - else: - logger.info("Getting wcs from image file %s",image_file_name) - wcs = image.wcs - self.wcs_list.append(wcs) - self.center_list.append(image.true_center) + # First limit to only those that could possibly be on the image by checking the + # min/max ra and dec from the image corners. + cen = image.wcs.toWorld(image.center) + logger.debug("Center at %s",cen) + x_corners = [image.xmin, image.xmin, image.xmax, image.xmax] + y_corners = [image.ymin, image.ymax, image.ymax, image.ymin] + corners = [image.wcs.toWorld(galsim.PositionD(x,y)) + for (x,y) in zip(x_corners, y_corners)] + logger.debug("Corners at %s",corners) + min_ra = np.min([c.ra.wrap(cen.ra) for c in corners]) + max_ra = np.max([c.ra.wrap(cen.ra) for c in corners]) + min_dec = np.min([c.dec.wrap(cen.dec) for c in corners]) + max_dec = np.max([c.dec.wrap(cen.dec) for c in corners]) + logger.debug("RA range = %s .. %s",min_ra,max_ra) + logger.debug("Dec range = %s .. %s",min_dec,max_dec) + use = [(r.wrap(cen.ra) > min_ra) & (r.wrap(cen.ra) < max_ra) & + (d.wrap(cen.dec) > min_dec) & (d.wrap(cen.dec) < max_dec) + for r,d in zip(ra,dec)] + ra = ra[use] + dec = dec[use] + logger.debug("After limiting to image ra,dec range, len = %s",len(ra)) - @staticmethod - def _removeSignalFromWeight(image, weight, gain=None): - """Remove the image signal from the weight map. + # Now convert to x,y + def safe_to_image(wcs, ra, dec): + try: + return wcs.toImage(galsim.CelestialCoord(ra, dec)) + except galsim.GalSimError: # pragma: no cover + # If the ra,dec is way off the image, this might fail to converge. + # In this case return None, which we can get rid of simply. + return None + image_pos = [ safe_to_image(image.wcs,r,d) for r,d in zip(ra, dec) ] + image_pos = [ pos for pos in image_pos if pos is not None ] + logger.debug("Resulting image_pos list has %s positions",len(image_pos)) + else: + if params['x_col'] not in cat.dtype.names: + raise ValueError("x_col = %s is not a column in %s" % + (params['x_col'], params['cat_file_name'])) + if params['y_col'] not in cat.dtype.names: + raise ValueError("y_col = %s is not a column in %s" % + (params['y_col'], params['cat_file_name'])) + x_values = cat[params['x_col']] + y_values = cat[params['y_col']] + logger.debug("Initially %d positions",len(x_values)) + image_pos = [ galsim.PositionD(x,y) for x,y in zip(x_values, y_values) ] - :param image: The image to use as the signal - :param weight: The weight image. - :param gain: Optionally, the gain to use as the proportionality relation. May be - either a scalar or an image. If gain is None, then it will be estimated - automatically and returned. [default: None] + # Check for objects well off the edge. We won't use them. + big_bounds = image.bounds.expand(params['stamp_size']) + image_pos = [ pos for pos in image_pos if big_bounds.includes(pos) ] + logger.debug("After remove those that are off the image, len = %s",len(image_pos)) - :returns: newweight, gain - """ - use = (weight.array != 0.) & np.isfinite(image.array) - signal = image.array[use] - variance = 1./weight.array[use] + # Make a dictionary of the star properties: + extra_props = {} + if params['property_cols'] is not None: + logger.debug('property_cols = %s'%params['property_cols']) + for col_name in params['property_cols']: + if col_name not in cat.dtype.names: + raise ValueError("Entry in property_cols = " + + "%s is not a column in %s"%(col_name,params['cat_file_name'])) + extra_props[col_name] = cat[col_name] - if gain is None: - fit = np.polyfit(signal, variance, deg=1) - gain = 1./fit[0] # fit is [ 1/gain, sky_var ] + if params['sed_col'] is not None: + if params['sed_col'] not in cat.dtype.names: + raise ValueError("sed_col = %s is not a column in %s" % + (params['sed_col'], params['cat_file_name'])) + sed_map = None + if params['sed_file_name'] is not None: + sed_map = self._read_sed_mapping(params['sed_file_name'], params['cat_file_name']) + sed_file_name_values = [] + for sed_label in cat[params['sed_col']]: + if sed_map is not None: + sed_label = os.fsdecode(sed_label).strip() + if sed_label not in sed_map: + raise ValueError( + "sed_col value %r is not in sed_file_name mapping" % sed_label + ) + params['sed_file_name'] = sed_map[sed_label] + else: + params['sed_file_name'] = sed_label + params['sed_file_name'] = self._resolve_sed_file_name( + params['sed_file_name'], params['cat_file_name']) + sed_file_name_values.append(params['sed_file_name']) + extra_props['sed_file_name'] = np.array(sed_file_name_values, dtype=object) + extra_props['sed_wave_type'] = np.array( + [params['sed_wave_type']] * len(cat), dtype=object) + extra_props['sed_flux_type'] = np.array( + [params['sed_flux_type']] * len(cat), dtype=object) + extra_props['sed_wave_key'] = np.array( + [params['sed_wave_key']] * len(cat), dtype=object) + extra_props['sed_flux_key'] = np.array( + [params['sed_flux_key']] * len(cat), dtype=object) + extra_props['sed_tol'] = np.full(len(cat), params['sed_tol'], dtype=float) + extra_props['sed_max_samples'] = np.full(len(cat), params['sed_max_samples'], dtype=int) + elif params['sed_file_name'] is not None: + params['sed_file_name'] = self._resolve_sed_file_name( + params['sed_file_name'], params['cat_file_name']) + extra_props['sed_file_name'] = np.array( + [params['sed_file_name']] * len(cat), dtype=object) + extra_props['sed_wave_type'] = np.array( + [params['sed_wave_type']] * len(cat), dtype=object) + extra_props['sed_flux_type'] = np.array( + [params['sed_flux_type']] * len(cat), dtype=object) + extra_props['sed_wave_key'] = np.array( + [params['sed_wave_key']] * len(cat), dtype=object) + extra_props['sed_flux_key'] = np.array( + [params['sed_flux_key']] * len(cat), dtype=object) + extra_props['sed_tol'] = np.full(len(cat), params['sed_tol'], dtype=float) + extra_props['sed_max_samples'] = np.full(len(cat), params['sed_max_samples'], dtype=int) - gain_values = gain.array[use] if isinstance(gain, galsim.Image) else gain - variance -= signal / gain_values + # If we used a flag column, keep it as a property. + if params['flag_col'] is not None: + extra_props[params['flag_col']] = cat[params['flag_col']] - newweight = weight.copy() - valid = np.isfinite(variance) & (variance > 0) - new_values = np.zeros_like(variance) - np.divide(1.0, variance, out=new_values, where=valid) - newweight.array[use] = new_values - return newweight, gain + # Make the list of sky values: + if params['sky_col'] is not None: + if params['sky_col'] not in cat.dtype.names: + raise ValueError("sky_col = %s is not a column in %s" % + (params['sky_col'], params['cat_file_name'])) + extra_props['sky'] = np.float32(cat[params['sky_col']]) - @staticmethod - def _read_image(file_name, ext, *, read_header): - """Read one image, optionally including its metadata. + # Make the list of gain values: + if params['gain_col'] is not None: + if params['gain_col'] not in cat.dtype.names: + raise ValueError("gain_col = %s is not a column in %s" % + (params['gain_col'], params['cat_file_name'])) + extra_props['gain'] = cat[params['gain_col']] + elif gain is not None: + gain = self._handle_depr_image_value(gain, image.header, 'gain', logger) + extra_props['gain'] = np.array([gain]*len(cat), dtype=float) + + # Get the saturation level + if satur is not None: + satur = self._handle_depr_image_value(satur, image.header, 'satur', logger) + logger.debug("Using saturation value: %s",satur) + extra_props['satur'] = np.array([satur]*len(cat), dtype=float) + + # Check whether we should trust the positions + if trust_pos is not None: + extra_props['trust_pos'] = np.array([trust_pos]*len(cat), dtype=bool) - Subclasses may override this method to support other file formats. The returned - GalSim image must include its WCS and, when requested, a ``header`` attribute. + if params['properties'] is not None: + logger.debug('properties = %s', params['properties']) + extra_props.update(self._evaluate_properties( + params['properties'], extra_props, len(cat), base, logger)) + + data.image_pos = image_pos + data.extra_props = extra_props + + def finish_star(self, data, logger, star): + """Finish one star cutout using per-star properties and whole-image calibration. + + For this function, data is provided just for reference in case subclasses want + information stored there. The base implementation doesn't use it. + + This takes in a star instance and performs any adjustments required. It returns the + updated star. + + The base class implementation just subtracts a catalog-level sky from the image, + since that version of providing the sky information couldn't be handled in + subtract_sky. + + :param data: A RawImageData object with the current data. + :param logger: Logger for input diagnostics. + :param star: Star instance to finish processing. + + :returns: The updated star. + """ + if 'sky' in star.data.properties: + sky = star.data.properties['sky'] + logger.debug("Subtracting off sky = %f", sky) + logger.debug("Median pixel value = %f", np.median(star.image.array)) + image = star.image - sky + return Star(star.data.withNew(image=image), star.fit) + else: + return star + + def read_metadata(self, file_name, ext): + """Read bounds, wcs, and header associated with an image on disk without loading the + pixel array. + + :param file_name: Science image filename. + :param ext: FITS extension or dot-separated ASDF path. + + :returns: An `ImageMetadata` instance with the meta-data. + """ + if file_name.endswith('.asdf'): + import asdf + if not isinstance(ext, str): + raise ValueError('ext must be a dot-separated path when used with ASDF files') + with asdf.open(file_name) as af: + ny, nx = get_asdf_value(af.tree, ext).shape + return ImageMetadata(galsim.BoundsI(1, nx, 1, ny), galsim.PixelScale(1), None) + else: + if isinstance(ext, str): + from astropy.io import fits + with fits.open(file_name) as hdus: + header = galsim.FitsHeader(header=hdus[ext].header.copy()) + else: + header = galsim.FitsHeader(file_name=file_name, hdu=ext) + wcs, origin = galsim.wcs.readFromFitsHeader(header) + bounds = galsim.BoundsI(origin.x, origin.x + header['NAXIS1'] - 1, + origin.y, origin.y + header['NAXIS2'] - 1) + return ImageMetadata(bounds, wcs, header) + + def read_image(self, file_name, ext, *, read_header): + """Read one stored image plane for science or an auxiliary calibration. + + Reads from either a FITS hdu or an asdf file, for which ext mean the path to the + data array. For FITS files, it attaches the header if read_header=True. The + wcs is automatically set for FITS files, but not for ASDF files for which there is + no standard location to grab the wcs, so that must be specified separately. + + :param file_name: Filename of the image plane. + :param ext: FITS extension number/name, None for the FITS default, or a + dot-separated ASDF array path. + :param read_header: Whether to include the header attribute on the returned image. + + :returns: The loaded GalSim image. """ if file_name.endswith('.asdf'): return read_asdf_image(file_name, ext, read_header=read_header) @@ -1172,163 +1346,346 @@ def _read_image(file_name, ext, *, read_header): else: return galsim.fits.read(file_name, hdu=ext, read_header=read_header) - @classmethod - def readImage(cls, image_file_name, image_ext, weight_file_name, weight_ext, - badpix_file_name, badpix_ext, badpix_zeros, fix_ushort_badpix, - sky_file_name, sky_ext, - gain_file_name, gain_ext, image_num, config, base, logger): - """Read the science image, weight map, and optional gain image. - - Make a weight map if no weight information is given. - - :param image_file_name: The name of the file to read. - :param image_ext: The FITS extension number/name or ASDF path of the image. - :param weight_file_name: The name if the file with the weight image (if any). - :param weight_ext: The FITS extension number/name or ASDF path of the weight image. - :param badpix_file_name: The name of the file with the bad pixel mask (if any). - :param badpix_ext: The FITS extension number/name or ASDF path of the bad pixel mask. - :param badpix_zeros: Whether to treat all zeros in the input image as bad pixels. - [default: False] - :param fix_ushort_badpix: Whether to correct badpix arrays with a 32768 offset value. - [default: False] - :param sky_file_name: A file to use for a sky background to subtract from the image - (if any). - :param sky_ext: The FITS extension number/name or ASDF path in sky_file_name. - :param gain_file_name: The name of the file with the gain image (if any). - :param gain_ext: The FITS extension number/name or ASDF path of the gain image. - :param config: The input section of the config dict. - :param base: The base config dict. - :param logger: A logger object for logging debug info. - - :returns: image, weight, gain_image (None when no gain image is supplied) + def read_catalog(self, cat_file_name, cat_ext): + """Read an unprocessed catalog table for the standard catalog-processing stage. + + This can read either a FITS binary table or a parquet file. It returns a + numpy structured array with the loaded data. + + :param cat_file_name: Filename of the catalog. + :param cat_ext: FITS table extension selector, or None for the default. + Ignored for Parquet files. + + :returns: Structured array of catalog rows. """ - # Read in the image - logger.info("Reading image file %s",image_file_name) - galsim.config.RemoveCurrent(base) - base['image_num'] = image_num - image = cls._read_image(image_file_name, image_ext, read_header=True) - base['_current_image'] = image - - noise = None - if 'noise' in config: - noise = galsim.config.ParseValue(config, 'noise', base, (float, str))[0] - - sky = None - if 'sky' in config: - sky = galsim.config.ParseValue(config, 'sky', base, (float, str))[0] - - # Make sure dtype is at least float32 - if image.dtype not in [np.float32, np.float64]: - header = image.header # This doesn't get copied by view() - image = image.view(dtype=np.float32) - image.header = header - - config['_current_image'] = image - - if noise is not None: - noise = galsim.config.ParseValue(config, 'noise', base, None)[0] - noise = cls._handle_depr_image_value(noise, image.header, 'noise', logger) - - # Either read in the weight image, or build a dummy one - if weight_file_name is not None or weight_ext is not None: - weight_file_name = weight_file_name or image_file_name - logger.verbose("Reading weight image from %s, extension %s.", - weight_file_name, weight_ext) - weight = cls._read_image(weight_file_name, weight_ext, read_header=False) - if np.all(weight.array == 0): - logger.error("According to the weight mask in %s, all pixels have zero weight!", - image_file_name) - if np.any(weight.array < 0): - logger.warning("Warning: weight map has invalid negative-valued pixels. "+ - "Taking them to be 0.0") - weight.array[weight.array < 0] = 0. - weight._piff_default_weight = False - elif noise is not None: - logger.debug("Making uniform weight image based on noise variance = %f", noise) - weight = galsim.ImageF(image.bounds, init_value=1./noise) - weight._piff_default_weight = False + if cat_file_name.endswith('.fits'): + return self._read_fits_cat(cat_file_name, cat_ext) + elif cat_file_name.endswith('.parquet'): + return self._read_parquet_cat(cat_file_name) else: - logger.debug("Making trivial (wt==1) weight image") - weight = galsim.ImageF(image.bounds, init_value=1) - weight._piff_default_weight = True - - # Make sure to do this before anything that could modify the input image. - if badpix_zeros: - weight.array[image.array == 0] = 0 + # For other endings, try parquet then fits so error message is for fits. + try: + return self._read_parquet_cat(cat_file_name) + except Exception: + return self._read_fits_cat(cat_file_name, cat_ext) - # If requested, set wt=0 for any bad pixels - if badpix_file_name is not None or badpix_ext is not None: - badpix_file_name = badpix_file_name or image_file_name - logger.verbose("Reading badpix image from %s, extension %s.", - badpix_file_name, badpix_ext) - badpix = cls._read_image(badpix_file_name, badpix_ext, read_header=False) + # User-facing methods. - # Correct legacy unsigned-integer offsets if requested. - if fix_ushort_badpix: - if np.any(badpix.array > 32767): - logger.debug('min(badpix) = %s',np.min(badpix.array)) - logger.debug('max(badpix) = %s',np.max(badpix.array)) - logger.debug("subtracting 32768 from all values in badpix image") - badpix -= 32768 - if np.any(badpix.array < -32767): - logger.debug('min(badpix) = %s',np.min(badpix.array)) - logger.debug('max(badpix) = %s',np.max(badpix.array)) - logger.debug("adding 32768 to all values in badpix image") - badpix += 32768 - if np.all(badpix.array != 0): - logger.error("According to the bad pixel array in %s, all pixels are masked!", - image_file_name) - weight.array[badpix.array != 0] = 0 - - # Any Inf or NaN pixels in the science image should also be given weight=0. - # Additionally, set the value to 0, so downstream processing that does math like - # weight * image doesn't get NaNs in the calculation. - nonfinite = ~np.isfinite(image.array) - weight.array[nonfinite] = 0 - image.array[nonfinite] = 0 - - sky_image = cls._read_sky(image, weight, sky, sky_file_name, sky_ext, logger) - if sky_image is not None: - image -= sky_image - - gain_image = None - if gain_file_name is not None: - logger.verbose("Reading gain image from %s, extension %s.", gain_file_name, gain_ext) - gain_image = cls._read_image(gain_file_name, gain_ext, read_header=False) - if gain_image.bounds != image.bounds: - raise ValueError('Gain image bounds do not match science image bounds') - use = weight.array != 0 - if np.any(~np.isfinite(gain_image.array[use]) | (gain_image.array[use] <= 0)): - raise ValueError('Gain image must be finite and positive at unmasked pixels') + def readMetadata(self, logger=None): + """Read image metadata and set the common pointing before processing stars. - return image, weight, gain_image + Reading images/stars or querying metadata calls this automatically on first use. + It may also be called explicitly to read or refresh metadata beforehand. - @classmethod - def _read_sky(cls, image, weight, sky, sky_file_name, sky_ext, logger): - """Read or estimate the image-level background after assembling the pixel mask. + It only reads meta-data such as the image bounds, WCS, and headers. + No pixel data is loaded here. An explicit input.wcs overrides the stored WCS. - Returns a sky image for a file or SEP estimate, or a scalar for a configured value - or image median. Returns None when no image-level sky is specified. Catalog sky - values are applied later to individual stars. Subclasses can reuse the returned - background when constructing background-dependent weight maps. + :param logger: Optional logger for input diagnostics. [default: None] """ - if sky_file_name is not None: - ext_str = " from extension %s" % sky_ext if sky_ext is not None else "" - logger.verbose("Reading sky image %s.", sky_file_name + ext_str) - return cls._read_image(sky_file_name, sky_ext, read_header=False) - elif sky == 'median': - return np.median(image.array[weight.array != 0]) - elif sky == 'sep': - import sep - # SEP requires contiguous arrays with native byte order; FITS arrays may be big-endian. - data = np.ascontiguousarray(image.array, dtype=image.array.dtype.newbyteorder('=')) - background = sep.Background(data, mask=weight.array == 0) - return galsim.Image(background.back(), bounds=image.bounds, wcs=image.wcs) - elif sky is not None: - # Float value or a (now deprecated) image header key. - return cls._handle_depr_image_value(sky, image.header, 'sky', logger) + logger = LoggerWrapper(logger) + self.metadata_list = [] + self.wcs_list = [] + self.center_list = [] + self.chipnums = [] + self.image_file_name = [] + self.cat_file_name = [] + for image_num in range(self.nimages): + data = RawImageData(image_num=image_num, config=self.config, base=self.base) + if image_num == 0: + first_data = data + params = self._parse_params(data, {'image_file_name': None, 'image_ext': None}) + file_name = params['image_file_name'] + logger.info("Reading metadata from image file %s", file_name) + metadata = self.read_metadata(file_name, params['image_ext']) + self.metadata_list.append(metadata) + self.center_list.append(metadata.bounds.true_center) + self.image_file_name.append(file_name) + data.base['_current_image'] = metadata + params = self._parse_params(data, {'chipnum': image_num, 'cat_file_name': None}) + self.chipnums.append(params['chipnum']) + self.cat_file_name.append(params['cat_file_name']) + if 'wcs' in data.config: + logger.info("Using custom wcs from config for %s", file_name) + wcs = galsim.config.BuildWCS(data.config, 'wcs', data.base, logger) + else: + wcs = metadata.wcs + self.wcs_list.append(wcs) + if 'bandpass' in data.config: + self.bandpass = galsim.config.BuildBandpass( + data.config, 'bandpass', data.base, logger)[0] + else: + self.bandpass = None + + # Resolve configured coordinates once using the first image's metadata. + config, base = first_data.config, first_data.base + ra = None + if config.get('ra') is not None: + ra = galsim.config.ParseValue(config, 'ra', base, None)[0] + dec = None + if config.get('dec') is not None: + dec = galsim.config.ParseValue(config, 'dec', base, None)[0] + if (ra is None) != (dec is None): + raise ValueError("Only one of ra, dec was specified") + + if ra is None: + if self.wcs_list[0].isCelestial(): + if self.nimages == 1: + # Here we can just use the image center. + wcs = self.wcs_list[0] + center = self.center_list[0] + self.pointing = wcs.toWorld(center) + logger.verbose("Setting pointing to image center: %.3f h, %.3f d", + self.pointing.ra / galsim.hours, + self.pointing.dec / galsim.degrees) + else: + # Use the mean of all the image centers + plist = [wcs.toWorld(center) + for wcs,center in zip(self.wcs_list,self.center_list)] + # Do this in x,y,z coords, not ra, dec so we don't mess up near ra=0. + xlist, ylist, zlist = zip(*[p.get_xyz() for p in plist]) + x = np.mean(xlist) + y = np.mean(ylist) + z = np.mean(zlist) + self.pointing = galsim.CelestialCoord.from_xyz(x,y,z) + logger.verbose("Setting pointing to mean of image centers: %.3f h, %.3f d", + self.pointing.ra / galsim.hours, + self.pointing.dec / galsim.degrees) + else: + self.pointing = None else: - return None + # Deprecated bare keys refer to the primary FITS header; resolve them before + # interpreting the resulting numerical or sexagesimal coordinates. + if isinstance(ra, str) and isinstance(dec, str) and not (':' in ra and ':' in dec): + file_name = self.image_file_name[0] + if self.nimages == 1: + logger.verbose("Setting pointing from keywords %s, %s", ra, dec) + else: + logger.verbose("Setting pointing from keywords %s, %s in %s", + ra, dec, file_name) + hdu = 1 if file_name.endswith('.fz') else 0 + import fitsio + header = fitsio.read_header(file_name, ext=hdu) + ra = self._handle_depr_image_value(ra, header, 'ra', logger) + dec = self._handle_depr_image_value(dec, header, 'dec', logger) + + if type(ra) in [float, int]: + ra = float(ra) * galsim.hours + dec = float(dec) * galsim.degrees + elif str(ra) != ra: + raise ValueError("Unable to parse input ra: %s"%ra) + elif str(dec) != dec: + raise ValueError("Unable to parse input dec: %s"%dec) + elif ':' in ra and ':' in dec: + ra = galsim.Angle.from_hms(ra) + dec = galsim.Angle.from_dms(dec) + else: + raise ValueError("Unable to parse input ra, dec: %s, %s" % (ra, dec)) + self.pointing = galsim.CelestialCoord(ra, dec) + logger.verbose("Setting pointing to: %.3f h, %.3f d", + self.pointing.ra / galsim.hours, + self.pointing.dec / galsim.degrees) + + def getRawImageData(self, image_num, logger=None): + """Read an image and catalog. + + :param image_num: The index of the image to read. + :param logger: A logger object for logging debug info. [default: None] + + :returns: A `RawImageData` dataclass with fields image, weight, image_pos, + extra_props, and gain_image. Fields can be accessed by name or unpacked + in that order. + """ + if self.metadata_list is None: + self.readMetadata(logger) + data = RawImageData(image_num=image_num, config=self.config, base=self.base) + logger = LoggerWrapper(logger) + self.load_image(data, logger) + self.load_weight(data, logger) + self.load_gain(data, logger) + self.build_mask(data, logger) + self.subtract_sky(data, logger) + self.update_wcs(data, logger) + self.load_catalog(data, logger) + self.finalize_weight(data, logger) + return data + + def load_images(self, stars, logger=None): + """Load the image data into a list of Stars. + + We don't store the image data for Stars when we write them to a file, since that + would take up a lot of space and is usually not desired. However, we do store the + bounds in the original image where the star was cutout, so if you want to load back in + the original data from the image file(s), you can do so with this function. + + :param stars: A list of Star instances. + :param logger: A logger object for logging debug info. [default: None] + + :returns: a new list of Stars with the images information loaded. + """ + logger = LoggerWrapper(logger) + if self.metadata_list is None: + self.readMetadata(logger) + + image_data = {} + for image_num in range(self.nimages): + image_data[self.chipnums[image_num]] = self.getRawImageData(image_num, logger) + + loaded_stars = [] + for star in stars: + chipnum = star['chipnum'] + full_data = image_data[chipnum] + image = full_data.image[star.data.image.bounds].copy() + weight = full_data.weight[star.data.weight.bounds].copy() + gain_image = full_data.gain_image + if gain_image is not None: + gain_image = gain_image[image.bounds].copy() + data = star.data.withNew(image=image, weight=weight, orig_weight=weight, + gain_image=gain_image) + loaded_star = Star(data=data, fit=star.fit) + loaded_stars.append(self.finish_star(full_data, logger, loaded_star)) + + return loaded_stars + + # Implementation details. + + def _parse_params(self, data, params): + """Parse the given params, taking the default value if not in data.config. + + The input params should be a dict with key: default_value for each parameter + to be parsed. The return will be the same structure, but with the parsed value + replacing the default if the paramter is given in the config dict. + """ + types = self._req_params | self._opt_params + return { + key: galsim.config.ParseValue(data.config, key, data.base, types[key])[0] + if key in data.config else default + for key, default in params.items() + } + + def _makeStarsFromImage(self, image_num, logger): + """Make "stars" from a single input image + """ + full_data = self.getRawImageData(image_num, logger) + chipnum = self.chipnums[image_num] + params = self._parse_params(full_data, {'stamp_size': 32, 'use_partial': False}) + stamp_size = params['stamp_size'] + image = full_data.image + wt = full_data.weight + image_pos = full_data.image_pos + extra_props = full_data.extra_props + gain_image = full_data.gain_image + logger.verbose("Processing catalog %s with %d objects",chipnum,len(image_pos)) + + objects = [] + + # Make a dict of the types to use for the extra_props, so we can preserve the type + # if we need to output them (e.g. in ShapeCatalog). + prop_types = {key: extra_props[key].dtype.type for key in extra_props} + + for k in range(len(image_pos)): + x = image_pos[k].x + y = image_pos[k].y + icen = int(x+0.5) + jcen = int(y+0.5) + half_size = stamp_size // 2 + bounds = galsim.BoundsI(icen+half_size-stamp_size+1, icen+half_size, + jcen+half_size-stamp_size+1, jcen+half_size) + if not image.bounds.includes(bounds): + bounds = bounds & image.bounds + if not bounds.isDefined(): + logger.warning("Object at position %f,%f is off the edge of the image.", x, y) + logger.warning("Skipping this object.") + continue + if params['use_partial']: + logger.verbose("Object at position %f,%f overlaps the edge of the image. " + "Using smaller than the full stamp size: %s", x, y, bounds) + else: + logger.info("Object at position %f,%f overlaps the edge of the image.", x, y) + logger.info("Skipping this object.") + continue + stamp = image[bounds].copy() + wt_stamp = wt[bounds].copy() + props = { 'chipnum' : chipnum } + + # if an object is totally masked, then don't add it! + if np.all(wt_stamp.array == 0): + logger.warning("Object at position %f,%f is completely masked.", x, y) + logger.warning("Skipping this object.") + continue + + # Add this object's entry in each list of the extra_props dictionary + # to the StarData properties dictionary + for key in extra_props: + logger.debug("Assigning {} value = {}".format(key, extra_props[key][k])) + props[key] = extra_props[key][k] + + # If any pixels are saturated, skip it. + if 'satur' in props: + max_val = np.max(stamp.array) + if max_val > props['satur']: + logger.info("Object at position %f,%f has saturated pixels.", x, y) + logger.info("Maximum value is %f.", max_val) + logger.info("Skipping this object.") + continue + + pos = galsim.PositionD(x,y) + gain_stamp = gain_image[bounds].copy() if gain_image is not None else None + data = StarData(stamp, pos, weight=wt_stamp, pointing=self.pointing, + bandpass=self.bandpass, + properties=props, property_types=prop_types, + gain_image=gain_stamp) + # Attach an attribute so we can tell later whether the weight is real or + # if it's just the default w=1.0. + data._piff_default_weight = getattr(wt, '_piff_default_weight', False) + star = Star(data, None) + star = self.finish_star(full_data, logger, star) + + objects.append(star) + + return objects + + @staticmethod + def _handle_depr_image_value(value, header, name, logger): + # gain, satur, noise, sky, ra, and dec used to allow bare FITS header keys. + # Now this functionality should use the ImageHeaderValue type to be more explicit. + # The old behavior still works, but is deprecated. + if isinstance(value, str) and value[0] not in '@$': + logger.error("WARNING: Using a bare FITS header key for %s is deprecated. " + "Use {type: ImageHeaderValue, key: %s} instead.", name, value) + value = header[value] + # Pointing values may be sexagesimal strings, parsed by readMetadata. + if name not in ('ra', 'dec'): + value = float(value) + return value + + @staticmethod + def _removeSignalFromWeight(image, weight, gain=None): + """Remove the image signal from the weight map. + + :param image: The image to use as the signal + :param weight: The weight image. + :param gain: Optionally, the gain to use as the proportionality relation. May be + either a scalar or an image. If gain is None, then it will be estimated + automatically and returned. [default: None] + + :returns: newweight, gain + """ + use = (weight.array != 0.) & np.isfinite(image.array) + signal = image.array[use] + variance = 1./weight.array[use] + + if gain is None: + fit = np.polyfit(signal, variance, deg=1) + gain = 1./fit[0] # fit is [ 1/gain, sky_var ] + + gain_values = gain.array[use] if isinstance(gain, galsim.Image) else gain + variance -= signal / gain_values + variance[~np.isfinite(variance) | (variance <= 0)] = 0 + + newweight = weight.copy() + newweight.array[use] = variance + newweight._invertSelf() + return newweight, gain @staticmethod def _flag_select(col, flag): @@ -1345,26 +1702,11 @@ def _flag_select(col, flag): if flag == 0: break return mask - @classmethod - def _read_cat(cls, cat_file_name, cat_ext): - if cat_file_name.endswith('.fits'): - return cls._read_fits_cat(cat_file_name, cat_ext) - elif cat_file_name.endswith('.parquet'): - return cls._read_parquet_cat(cat_file_name) - else: - # For other endings, try parquet then fits so error message is for fits. - try: - return cls._read_parquet_cat(cat_file_name) - except Exception: - return cls._read_fits_cat(cat_file_name, cat_ext) - - @classmethod - def _read_fits_cat(cls, cat_file_name, cat_ext): + def _read_fits_cat(self, cat_file_name, cat_ext): import fitsio return fitsio.read(cat_file_name, cat_ext) - @classmethod - def _read_parquet_cat(cls, cat_file_name): + def _read_parquet_cat(self, cat_file_name): import pyarrow.parquet as pq tab = pq.read_table(cat_file_name) # This works, but requires pandas @@ -1386,267 +1728,17 @@ def _resolve_sed_file_name(value, cat_file_name): else: return sed_file_name - @classmethod - def _read_sed_mapping(cls, sed_file_name, cat_file_name): + def _read_sed_mapping(self, sed_file_name, cat_file_name): if isinstance(sed_file_name, dict): return sed_file_name - sed_map_file = cls._resolve_sed_file_name(sed_file_name, cat_file_name) + sed_map_file = self._resolve_sed_file_name(sed_file_name, cat_file_name) with open(sed_map_file) as f: sed_map = yaml.safe_load(f) if not isinstance(sed_map, dict): raise ValueError("SED mapping file must parse to a dict: %r" % sed_map_file) return sed_map - @classmethod - def readStarCatalog(cls, cat_file_name, cat_ext, x_col, y_col, - ra_col, dec_col, ra_units, dec_units, image, - flag_col, skip_flag, use_flag, property_cols, sed_col, sed_wave_type, - sed_file_name, sed_flux_type, sed_wave_key, sed_flux_key, - sed_tol, sed_max_samples, - properties, sky_col, gain_col, nstars, stamp_size, - config, base, logger): - """Read in the star catalogs and return lists of positions for each star in each image. - - :param cat_file_name: The name of the catalog file to read in. - :param cat_ext: The extension number or name to use for FITS catalogs. - :param x_col: The name of the column with x values. - :param y_col: The name of the column with y values. - :param ra_col: The name of a column with RA values. - :param dec_col: The name of a column with Dec values. - :param ra_units: The units of the ra column. - :param dec_units: The units of the dec column. - :param image: The image that was already read in (mostly for the wcs). - :param flag_col: The name of a column with flag values. - :param skip_flag: The flag indicating which items to not use. [default: -1] - Items with flag & skip_flag != 0 will be skipped. - :param use_flag: The flag indicating which items to use. [default: None] - Items with flag & use_flag == 0 will be skipped. - :param property_cols: A list of column names with star properties (e.g. star colors). - :param properties: A dict of additional star properties to attach to every star. - :param sed_col: A column with per-star SED file names. - :param sed_file_name: A single SED file name for all stars (if sed_col is None). - :param sed_wave_type: Wave type for SED files. - :param sed_flux_type: Flux type for SED files. - :param sed_wave_key: FITS-table wavelength column name for SED files. - :param sed_flux_key: FITS-table flux column name for SED files. - :param sed_tol: Relative tolerance for reducing loaded SEDs. - :param sed_max_samples: Maximum number of retained SED samples. - :param sky_col: A column with sky (background) levels. - :param gain_col: A column with gain values. - :param nstars: Optionally a maximum number of stars to use from this catalog. - :param stamp_size: The stamp size being used for the star stamps. - :param config: The input section of the config dict. - :param base: The base config dict. - :param logger: A logger object for logging debug info. [default: None] - - :returns: lists image_pos, extra_props - """ - import fitsio - - base['_current_image'] = image - - if cat_file_name is None: - # This is possible e.g. when loading images into an existing list of star instances. - logger.info("Not reading input catalog.") - return None, None - - # Read in the star catalog - logger.info("Reading input catalog %s.",cat_file_name) - cat = cls._read_cat(cat_file_name, cat_ext) - - gain = None - if 'gain' in config: - gain = galsim.config.ParseValue(config, 'gain', base, (float, str))[0] - - satur = None - if 'satur' in config: - satur = galsim.config.ParseValue(config, 'satur', base, (float, str))[0] - - trust_pos = None - if 'trust_pos' in config: - trust_pos = galsim.config.ParseValue(config, 'trust_pos', base, bool)[0] - - if flag_col is not None: - if flag_col not in cat.dtype.names: - raise ValueError("flag_col = %s is not a column in %s"%(flag_col,cat_file_name)) - col = cat[flag_col] - if len(col.shape) == 2: - logger.info("Flag col (%s) is multidimensional. Treating as an array of bool", - flag_col) - if use_flag is not None: - # Remove any objects with flag & use_flag == 0 - mask = cls._flag_select(col, use_flag) == 0 - logger.verbose("Removing objects with flag (col %s) & %d == 0",flag_col,use_flag) - if skip_flag != -1: - mask |= cls._flag_select(col, skip_flag) != 0 - logger.verbose("Removing objects with flag (col %s) & %d != 0",flag_col,skip_flag) - else: - # Remove any objects with flag & skip_flag != 0 - mask = cls._flag_select(col, skip_flag) != 0 - if skip_flag == -1: - logger.verbose("Removing objects with flag (col %s) != 0",flag_col) - else: - logger.verbose("Removing objects with flag (col %s) & %d != 0",flag_col,skip_flag) - cat = cat[mask == 0] - - # Limit to nstars objects - if nstars is not None and nstars < len(cat): - logger.verbose("Limiting to %d objects for %s", nstars, cat_file_name) - cat = cat[:nstars] - - # Make the list of positions: - if ra_col is not None or dec_col is not None: - if ra_col is None or dec_col is None: - raise ValueError("ra_col and dec_col are both required if one is provided.") - if ra_col not in cat.dtype.names: - raise ValueError("ra_col = %s is not a column in %s"%(ra_col,cat_file_name)) - if dec_col not in cat.dtype.names: - raise ValueError("dec_col = %s is not a column in %s"%(dec_col,cat_file_name)) - logger.debug("Starting to make a list of positions from ra, dec") - ra_values = cat[ra_col] - dec_values = cat[dec_col] - ra_units = galsim.AngleUnit.from_name(ra_units) - dec_units = galsim.AngleUnit.from_name(dec_units) - ra = ra_values * ra_units - dec = dec_values * dec_units - logger.debug("Initially %d positions",len(ra)) - - # First limit to only those that could possibly be on the image by checking the - # min/max ra and dec from the image corners. - cen = image.wcs.toWorld(image.center) - logger.debug("Center at %s",cen) - x_corners = [image.xmin, image.xmin, image.xmax, image.xmax] - y_corners = [image.ymin, image.ymax, image.ymax, image.ymin] - corners = [image.wcs.toWorld(galsim.PositionD(x,y)) - for (x,y) in zip(x_corners, y_corners)] - logger.debug("Corners at %s",corners) - min_ra = np.min([c.ra.wrap(cen.ra) for c in corners]) - max_ra = np.max([c.ra.wrap(cen.ra) for c in corners]) - min_dec = np.min([c.dec.wrap(cen.dec) for c in corners]) - max_dec = np.max([c.dec.wrap(cen.dec) for c in corners]) - logger.debug("RA range = %s .. %s",min_ra,max_ra) - logger.debug("Dec range = %s .. %s",min_dec,max_dec) - use = [(r.wrap(cen.ra) > min_ra) & (r.wrap(cen.ra) < max_ra) & - (d.wrap(cen.dec) > min_dec) & (d.wrap(cen.dec) < max_dec) - for r,d in zip(ra,dec)] - ra = ra[use] - dec = dec[use] - logger.debug("After limiting to image ra,dec range, len = %s",len(ra)) - - # Now convert to x,y - def safe_to_image(wcs, ra, dec): - try: - return wcs.toImage(galsim.CelestialCoord(ra, dec)) - except galsim.GalSimError: # pragma: no cover - # If the ra,dec is way off the image, this might fail to converge. - # In this case return None, which we can get rid of simply. - return None - image_pos = [ safe_to_image(image.wcs,r,d) for r,d in zip(ra, dec) ] - image_pos = [ pos for pos in image_pos if pos is not None ] - logger.debug("Resulting image_pos list has %s positions",len(image_pos)) - else: - if x_col not in cat.dtype.names: - raise ValueError("x_col = %s is not a column in %s"%(x_col,cat_file_name)) - if y_col not in cat.dtype.names: - raise ValueError("y_col = %s is not a column in %s"%(y_col,cat_file_name)) - x_values = cat[x_col] - y_values = cat[y_col] - logger.debug("Initially %d positions",len(x_values)) - image_pos = [ galsim.PositionD(x,y) for x,y in zip(x_values, y_values) ] - - # Check for objects well off the edge. We won't use them. - big_bounds = image.bounds.expand(stamp_size) - image_pos = [ pos for pos in image_pos if big_bounds.includes(pos) ] - logger.debug("After remove those that are off the image, len = %s",len(image_pos)) - - # Make a dictionary of the star properties: - extra_props = {} - if property_cols is not None: - logger.debug('property_cols = %s'%property_cols) - for col_name in property_cols: - if col_name not in cat.dtype.names: - raise ValueError("Entry in property_cols = " + - "%s is not a column in %s"%(col_name,cat_file_name)) - extra_props[col_name] = cat[col_name] - - if sed_col is not None: - if sed_col not in cat.dtype.names: - raise ValueError("sed_col = %s is not a column in %s" % (sed_col, cat_file_name)) - sed_map = None - if sed_file_name is not None: - sed_map = cls._read_sed_mapping(sed_file_name, cat_file_name) - sed_file_name_values = [] - for sed_label in cat[sed_col]: - if sed_map is not None: - sed_label = os.fsdecode(sed_label).strip() - if sed_label not in sed_map: - raise ValueError( - "sed_col value %r is not in sed_file_name mapping" % sed_label - ) - sed_file_name = sed_map[sed_label] - else: - sed_file_name = sed_label - sed_file_name = cls._resolve_sed_file_name(sed_file_name, cat_file_name) - sed_file_name_values.append(sed_file_name) - extra_props['sed_file_name'] = np.array(sed_file_name_values, dtype=object) - extra_props['sed_wave_type'] = np.array([sed_wave_type] * len(cat), dtype=object) - extra_props['sed_flux_type'] = np.array([sed_flux_type] * len(cat), dtype=object) - extra_props['sed_wave_key'] = np.array([sed_wave_key] * len(cat), dtype=object) - extra_props['sed_flux_key'] = np.array([sed_flux_key] * len(cat), dtype=object) - extra_props['sed_tol'] = np.full(len(cat), sed_tol, dtype=float) - extra_props['sed_max_samples'] = np.full(len(cat), sed_max_samples, dtype=int) - elif sed_file_name is not None: - sed_file_name = cls._resolve_sed_file_name(sed_file_name, cat_file_name) - extra_props['sed_file_name'] = np.array([sed_file_name] * len(cat), dtype=object) - extra_props['sed_wave_type'] = np.array([sed_wave_type] * len(cat), dtype=object) - extra_props['sed_flux_type'] = np.array([sed_flux_type] * len(cat), dtype=object) - extra_props['sed_wave_key'] = np.array([sed_wave_key] * len(cat), dtype=object) - extra_props['sed_flux_key'] = np.array([sed_flux_key] * len(cat), dtype=object) - extra_props['sed_tol'] = np.full(len(cat), sed_tol, dtype=float) - extra_props['sed_max_samples'] = np.full(len(cat), sed_max_samples, dtype=int) - - # If we used a flag column, keep it as a property. - if flag_col is not None: - extra_props[flag_col] = cat[flag_col] - - # Make the list of sky values: - if sky_col is not None: - if sky_col not in cat.dtype.names: - raise ValueError("sky_col = %s is not a column in %s"%(sky_col,cat_file_name)) - extra_props['sky'] = np.float32(cat[sky_col]) - - # Make the list of gain values: - # TODO: SV and Y1 DES images have two gain values, GAINA, GAINB. It would be nice if we - # could get the right one properly. OTOH, Y3+ will be in electrons, so gain=1 will - # the right value for all images. So maybe not worth worrying about. - if gain_col is not None: - if gain_col not in cat.dtype.names: - raise ValueError("gain_col = %s is not a column in %s"%(gain_col,cat_file_name)) - extra_props['gain'] = cat[gain_col] - elif gain is not None: - gain = galsim.config.ParseValue(config, 'gain', base, None)[0] - gain = cls._handle_depr_image_value(gain, image.header, 'gain', logger) - extra_props['gain'] = np.array([gain]*len(cat), dtype=float) - - # Get the saturation level - if satur is not None: - satur = galsim.config.ParseValue(config, 'satur', base, None)[0] - satur = cls._handle_depr_image_value(satur, image.header, 'satur', logger) - logger.debug("Using saturation value: %s",satur) - extra_props['satur'] = np.array([satur]*len(cat), dtype=float) - - # Check whether we should trust the positions - if trust_pos is not None: - extra_props['trust_pos'] = np.array([trust_pos]*len(cat), dtype=bool) - - if properties is not None: - logger.debug('properties = %s', properties) - extra_props.update(cls._evaluate_properties( - properties, extra_props, len(cat), base, logger)) - - return image_pos, extra_props - @staticmethod def _evaluate_properties(properties, extra_props, nstars, base, logger): if not isinstance(properties, dict): @@ -1684,95 +1776,3 @@ def _evaluate_properties(properties, extra_props, nstars, base, logger): parsed[key] = result return parsed - - def setPointing(self, ra, dec, logger=None): - """Set the pointing attribute based on the input ra, dec (given in the initializer) - - There are a number of ways the pointing can be specified. - Even this is probably not sufficiently generic for all applications, but it's a start. - - 1. numerical values (in Hours, Degrees respective) for ra, dec - 2. hh:mm:ss.ssss, dd:mm:ss.ssss strings giving hours/degrees, minutes, seconds for each - 3. FITS header key words to read to get the ra, dec values [deprecated; - use ImageHeaderValue config types instead] - 4. None, which will attempt to find the spatial center of all the input images using the - midpoint of the min/max ra and dec values of the image corners according to their - individual WCS functions. [Not implemented currently.] - 5. dict with GalSim-style config types to be parsed. - """ - logger = LoggerWrapper(logger) - - if (ra is None) != (dec is None): - raise ValueError("Only one of ra, dec was specified") - - if ra is None: - if self.wcs_list[0].isCelestial(): - if self.nimages == 1: - # Here we can just use the image center. - wcs = self.wcs_list[0] - center = self.center_list[0] - self.pointing = wcs.toWorld(center) - logger.verbose("Setting pointing to image center: %.3f h, %.3f d", - self.pointing.ra / galsim.hours, - self.pointing.dec / galsim.degrees) - else: - # Use the mean of all the image centers - plist = [wcs.toWorld(center) - for wcs,center in zip(self.wcs_list,self.center_list)] - # Do this in x,y,z coords, not ra, dec so we don't mess up near ra=0. - xlist, ylist, zlist = zip(*[p.get_xyz() for p in plist]) - x = np.mean(xlist) - y = np.mean(ylist) - z = np.mean(zlist) - self.pointing = galsim.CelestialCoord.from_xyz(x,y,z) - logger.verbose("Setting pointing to mean of image centers: %.3f h, %.3f d", - self.pointing.ra / galsim.hours, - self.pointing.dec / galsim.degrees) - else: - self.pointing = None - elif (isinstance(ra, dict) or isinstance(dec, dict) or - (isinstance(ra, str) and (ra[0] in ['$','@'])) or - (isinstance(dec, str) and (dec[0] in ['$','@']))): - image_file_name = self.image_kwargs[0]['image_file_name'] - image_ext = self.image_kwargs[0]['image_ext'] - image = self._read_image(image_file_name, image_ext, read_header=True) - base = galsim.config.CopyConfig(self.base) - base['index_key'] = 'image_num' - base['image_num'] = 0 - base['_current_image'] = image - ra = galsim.config.ParseValue({'ra': ra}, 'ra', base, None)[0] - dec = galsim.config.ParseValue({'dec': dec}, 'dec', base, None)[0] - self.setPointing(ra, dec, logger) - elif type(ra) in [float, int]: - ra = float(ra) * galsim.hours - dec = float(dec) * galsim.degrees - self.pointing = galsim.CelestialCoord(ra,dec) - logger.verbose("Setting pointing to: %.3f h, %.3f d", - self.pointing.ra / galsim.hours, - self.pointing.dec / galsim.degrees) - elif str(ra) != ra: - raise ValueError("Unable to parse input ra: %s"%ra) - elif str(dec) != dec: - raise ValueError("Unable to parse input dec: %s"%dec) - elif ':' in ra and ':' in dec: - ra = galsim.Angle.from_hms(ra) - dec = galsim.Angle.from_dms(dec) - self.pointing = galsim.CelestialCoord(ra,dec) - logger.verbose("Setting pointing to: %.3f h, %.3f d", - self.pointing.ra / galsim.hours, - self.pointing.dec / galsim.degrees) - else: - # This is now deprecated. This uses ra, dec as header keys, but these should now - # use ImageHeaderValue instead to be more explicit. - file_name = self.image_file_name[0] - if len(self.chipnums) == 1: - logger.verbose("Setting pointing from keywords %s, %s", ra, dec) - else: - logger.verbose("Setting pointing from keywords %s, %s in %s", ra, dec, file_name) - hdu = 1 if file_name.endswith('.fz') else 0 - import fitsio - header = fitsio.read_header(file_name, ext=hdu) - ra = self._handle_depr_image_value(ra, header, 'ra', logger) - dec = self._handle_depr_image_value(dec, header, 'dec', logger) - # Recurse to do further parsing. - self.setPointing(ra, dec, logger) diff --git a/tests/test_input.py b/tests/test_input.py index 80879d9e..4b727d58 100644 --- a/tests/test_input.py +++ b/tests/test_input.py @@ -174,6 +174,7 @@ def test_basic(): assert input.nimages == 1 # Raw image results support both tuple unpacking and access by field name. raw_data = input.getRawImageData(0) + assert isinstance(raw_data, piff.RawImageData) image, weight, image_pos, extra_props, gain_image = raw_data assert raw_data.image is image assert raw_data.weight is weight @@ -274,7 +275,7 @@ def test_basic(): for key, target in zip(file_keys, targets): reference_config[key] = {'type': 'Current', 'key': target} reference = piff.InputFiles(reference_config, base=base, logger=logger) - assert reference.wcs_list == [galsim.PixelScale(0.2), galsim.PixelScale(0.3)] + assert reference.getWCS(logger) == {0: galsim.PixelScale(0.2), 1: galsim.PixelScale(0.3)} for prefix in ['@', '$@']: print('prefix = ',prefix) shorthand_config = reference_config.copy() @@ -282,12 +283,12 @@ def test_basic(): shorthand_config[key] = prefix + target print('shorthand_config = ',shorthand_config) shorthand = piff.InputFiles(shorthand_config, base=base, logger=logger) + assert shorthand.getWCS(logger) == reference.getWCS(logger) print('shorthand = ',shorthand) print('image_file_name = ',shorthand.image_file_name, reference.image_file_name) assert shorthand.image_file_name == reference.image_file_name assert shorthand.cat_file_name == reference.cat_file_name assert shorthand.image_file_name[0] != shorthand.image_file_name[1] - assert shorthand.wcs_list == reference.wcs_list for image_num in range(2): image, weight, positions, _, _ = shorthand.getRawImageData(image_num) ref_image, ref_weight, ref_positions, _, _ = reference.getRawImageData(image_num) @@ -1148,8 +1149,10 @@ def test_cols(): np.testing.assert_raises(ValueError, input.getRawImageData, 0) with np.testing.assert_raises(ValueError): input = piff.InputFiles(dict(property_cols='invalid_string', **base_config)) + input.getRawImageData(0) with np.testing.assert_raises(galsim.GalSimConfigError): input = piff.InputFiles(dict(properties='invalid_string', **base_config)) + input.getRawImageData(0) input = piff.InputFiles( dict(properties={'foo': {'type': 'invalid', 'value': 1}}, **base_config)) np.testing.assert_raises(ValueError, input.getRawImageData, 0) @@ -1159,10 +1162,9 @@ def test_cols(): np.testing.assert_raises(ValueError, input.getRawImageData, 0) # skip_flag, use_flag need to be integers - np.testing.assert_raises(ValueError, piff.InputFiles, - dict(flag_col='flag', skip_flag='xx', **base_config)) - np.testing.assert_raises(ValueError, piff.InputFiles, - dict(flag_col='flag', use_flag='xx', **base_config)) + for key in ['skip_flag', 'use_flag']: + input = piff.InputFiles(dict(base_config, flag_col='flag', **{key: 'xx'})) + np.testing.assert_raises(ValueError, input.getRawImageData, 0) # Sky comes from one source; a sky filename and extension together specify one source. sky_options = { @@ -1184,19 +1186,25 @@ def test_cols(): # Invalid header keys config = dict(sky={'type': 'ImageHeaderValue', 'key': 'sky'}, **base_config) - np.testing.assert_raises(KeyError, piff.InputFiles(config).getRawImageData, 0) + reader = piff.InputFiles(config) + np.testing.assert_raises(KeyError, reader.getRawImageData, 0) config = dict(gain={'type': 'ImageHeaderValue', 'key': 'gain'}, **base_config) - np.testing.assert_raises(KeyError, piff.InputFiles(config).getRawImageData, 0) + reader = piff.InputFiles(config) + np.testing.assert_raises(KeyError, reader.getRawImageData, 0) config = dict(satur={'type': 'ImageHeaderValue', 'key': 'satur'}, **base_config) - np.testing.assert_raises(KeyError, piff.InputFiles(config).getRawImageData, 0) + reader = piff.InputFiles(config) + np.testing.assert_raises(KeyError, reader.getRawImageData, 0) # Same with the deprecated versions: config = dict(sky='sky', **base_config) - np.testing.assert_raises(KeyError, piff.InputFiles(config).getRawImageData, 0) + reader = piff.InputFiles(config) + np.testing.assert_raises(KeyError, reader.getRawImageData, 0) config = dict(gain='gain', **base_config) - np.testing.assert_raises(KeyError, piff.InputFiles(config).getRawImageData, 0) + reader = piff.InputFiles(config) + np.testing.assert_raises(KeyError, reader.getRawImageData, 0) config = dict(satur='satur', **base_config) - np.testing.assert_raises(KeyError, piff.InputFiles(config).getRawImageData, 0) + reader = piff.InputFiles(config) + np.testing.assert_raises(KeyError, reader.getRawImageData, 0) @timer @@ -1597,6 +1605,7 @@ def test_chipnum(): 'cat_file_name': cat_files } input = piff.InputFiles(config, logger=logger) + input.readMetadata(logger) assert input.chipnums == list(range(3)) # Now make the chipnums something else @@ -1607,6 +1616,7 @@ def test_chipnum(): 'chipnum' : [ 5, 6, 7 ] } input = piff.InputFiles(config, logger=logger) + input.readMetadata(logger) assert input.chipnums == [ i+5 for i in range(3) ] # Use the GalSim Eval capability to get the index + 1 @@ -1617,6 +1627,7 @@ def test_chipnum(): 'chipnum' : '$image_num + 1' } input = piff.InputFiles(config, logger=logger) + input.readMetadata(logger) assert input.chipnums == [ i+1 for i in range(3) ] # Or parse it from the image_file_name @@ -1631,6 +1642,7 @@ def test_chipnum(): } } input = piff.InputFiles(config, logger=logger) + input.readMetadata(logger) assert input.chipnums == list(range(3)) @@ -1812,9 +1824,9 @@ def test_weight(): } input = piff.InputFiles(config, logger=logger) assert input.nimages == 2 + image, weight, image_pos, _, _ = input.getRawImageData(0) assert input.image_file_name == ['input/test_input_image_00.fits'] * 2 assert input.cat_file_name == ['input/test_input_cat_00.fits'] * 2 - image, weight, image_pos, _, _ = input.getRawImageData(0) assert len(image_pos) == 100 np.testing.assert_allclose(image.array, fitsio.read('input/test_input_image_00.fits', ext=0) - sky) @@ -1842,15 +1854,11 @@ def test_weight(): } input = piff.InputFiles(config, logger=logger) assert input.nimages == 2 - assert input.image_file_name == ['input/test_input_image_00.fits'] * 2 - assert input.cat_file_name == ['input/test_input_cat_00.fits'] * 2 - assert input.image_kwargs[0]['weight_file_name'] == 'input/test_input_weight_00.fits' - assert input.image_kwargs[1]['weight_file_name'] == 'input/test_input_weight_00.fits' - assert input.image_kwargs[0]['badpix_file_name'] == 'input/test_input_badpix_00.fits' - assert input.image_kwargs[1]['badpix_file_name'] == 'input/test_input_badpix_00.fits' expected_weight0 = fitsio.read('input/test_input_weight_00.fits', ext=0) expected_weight0[1::2, :] = 0 raw_data = input.getRawImageData(0) + assert input.image_file_name == ['input/test_input_image_00.fits'] * 2 + assert input.cat_file_name == ['input/test_input_cat_00.fits'] * 2 weight = raw_data.weight image_pos = raw_data.image_pos assert len(image_pos) == 100 @@ -1868,13 +1876,9 @@ def test_weight(): config['badpix_file_name'] = { 'type': 'List', 'items': ['input/test_input_badpix_00.fits'], } input = piff.InputFiles(config, logger=logger) assert input.nimages == 2 + raw_data = input.getRawImageData(0) assert input.image_file_name == ['input/test_input_image_00.fits'] * 2 assert input.cat_file_name == ['input/test_input_cat_00.fits'] * 2 - assert input.image_kwargs[0]['weight_file_name'] == 'input/test_input_weight_00.fits' - assert input.image_kwargs[1]['weight_file_name'] == 'input/test_input_weight_00.fits' - assert input.image_kwargs[0]['badpix_file_name'] == 'input/test_input_badpix_00.fits' - assert input.image_kwargs[1]['badpix_file_name'] == 'input/test_input_badpix_00.fits' - raw_data = input.getRawImageData(0) weight = raw_data.weight image_pos = raw_data.image_pos assert len(image_pos) == 100 @@ -1885,13 +1889,15 @@ def test_weight(): assert len(image_pos) == 100 np.testing.assert_allclose(weight.array, expected_weight1) - # Nonfinite science pixels are masked and cleared + # Nonfinite science pixels are masked and cleared. + # Nonfinite and negative weights are masked. science = galsim.fits.read('input/test_input_image_00.fits').array.astype(float) science[30, 30:33] = [np.nan, np.inf, -np.inf] badpix = np.zeros(science.shape, dtype=np.int16) badpix[30, 30] = 1 badpix[40, 40] = 1 weight = np.ones(science.shape) + weight[31, 30:34] = [np.nan, np.inf, -np.inf, -1.0] file_name = os.path.join('output', 'nonfinite_science.fits') with fitsio.FITS(file_name, 'rw', clobber=True) as f: f.write(science) @@ -1904,11 +1910,16 @@ def test_weight(): 'badpix_ext': 2, 'sky': 3.0, } - raw_data = piff.InputFiles(config).getRawImageData(0) + with CaptureLog() as cl: + reader = piff.InputFiles(config) + raw_data = reader.getRawImageData(0, logger=cl.logger) + assert 'weight map has non-finite pixels' in cl.output + assert 'image has non-finite pixels' in cl.output expected_image = science - 3.0 expected_image[30, 30:33] = 0 - 3.0 # The sky subtraction happens after they are set to 0. expected_weight = weight.copy() expected_weight[30, 30:33] = 0 + expected_weight[31, 30:34] = 0 expected_weight[40, 40] = 0 np.testing.assert_array_equal(raw_data.image.array, expected_image) np.testing.assert_array_equal(raw_data.weight.array, expected_weight) @@ -2153,16 +2164,29 @@ def test_gain_image(): for filename in ['output/missing_gain.fits', 17, 'input/test_input_image_*.fits']: np.testing.assert_raises(ValueError, piff.InputFiles, dict(config, gain_file_name=filename)) - # Unmasked gains must be finite and positive. + # Invalid gains are masked. reader = piff.InputFiles(dict(config, gain_ext='GAIN')) for bad_value in [0, -1, np.nan, np.inf]: bad_gain = gain.copy() bad_gain[50, 50] = bad_value with fitsio.FITS(image_name, 'rw') as f: f[2].write(bad_gain) - with np.testing.assert_raises(ValueError) as e: - reader.makeStars() - assert 'finite and positive' in str(e.exception) + with CaptureLog() as cl: + raw_data = reader.getRawImageData(0, logger=cl.logger) + if np.isfinite(bad_value): + assert 'gain image has non-positive pixels' in cl.output + else: + assert 'gain image has non-finite pixels' in cl.output + expected_weight = background_weight.copy() + expected_weight[50, 50] = 0 + np.testing.assert_allclose(raw_data.weight.array, expected_weight) + masked_stars = reader.makeStars() + assert len(masked_stars) == len(stars) + assert masked_stars[1].weight(51, 51) == 0 + for star in masked_stars: + np.testing.assert_allclose(star.weight.array, + galsim.Image(expected_weight)[star.image.bounds].array) + assert np.all(np.isfinite(star.addPoisson().weight.array)) # An inconsistent gain that implies negative remaining variance masks the affected pixel. bad_gain = gain.copy() @@ -2587,7 +2611,7 @@ def test_select_min_sep(): @timer def test_pointing(): - """Test the input.setPointing function + """Test how the pointing gets set in input. """ if __name__ == '__main__': logger = piff.config.setup_logger(verbose=2) @@ -2605,12 +2629,13 @@ def test_pointing(): 'cat_file_name' : cat_file, } input = piff.InputFiles(config, logger=logger) - assert input.pointing is None + assert input.getPointing(logger) is None # Explicit ra, dec as floats config['ra'] = 6.0 config['dec'] = -30.0 input = piff.InputFiles(config, logger=logger) + input.readMetadata(logger=logger) np.testing.assert_almost_equal(input.pointing.ra.rad, np.pi/2.) np.testing.assert_almost_equal(input.pointing.dec.rad, -np.pi/6.) @@ -2618,6 +2643,7 @@ def test_pointing(): config['ra'] = 6 config['dec'] = -30 input = piff.InputFiles(config, logger=logger) + input.readMetadata(logger=logger) np.testing.assert_almost_equal(input.pointing.ra.rad, np.pi/2.) np.testing.assert_almost_equal(input.pointing.dec.rad, -np.pi/6.) @@ -2625,6 +2651,7 @@ def test_pointing(): config['ra'] = '06:00:00' config['dec'] = '-30:00:00' input = piff.InputFiles(config, logger=logger) + input.readMetadata(logger=logger) np.testing.assert_almost_equal(input.pointing.ra.rad, np.pi/2.) np.testing.assert_almost_equal(input.pointing.dec.rad, -np.pi/6.) @@ -2635,6 +2662,7 @@ def test_pointing(): config['ra'] = ra config['dec'] = dec input = piff.InputFiles(config, logger=logger) + input.readMetadata(logger=logger) np.testing.assert_almost_equal(input.pointing.ra.rad, np.pi/2.) np.testing.assert_almost_equal(input.pointing.dec.rad, -np.pi/6.) @@ -2642,6 +2670,7 @@ def test_pointing(): config['ra'] = { 'type': 'ImageHeaderValue', 'key': 'RA' } config['dec'] = { 'type': 'ImageHeaderValue', 'key': 'DEC' } input = piff.InputFiles(config) + input.readMetadata() np.testing.assert_almost_equal(input.pointing.ra.rad, np.pi/2.) np.testing.assert_almost_equal(input.pointing.dec.rad, -np.pi/6.) @@ -2649,6 +2678,7 @@ def test_pointing(): config['image_file_name'] = 'test_input_image_*.fits' config['cat_file_name'] = 'test_input_cat_*.fits' input = piff.InputFiles(config, logger=logger) + input.readMetadata(logger=logger) np.testing.assert_almost_equal(input.pointing.ra.rad, np.pi/2.) np.testing.assert_almost_equal(input.pointing.dec.rad, -np.pi/6.) @@ -2657,6 +2687,7 @@ def test_pointing(): config['dec'] = 'DEC' with CaptureLog(1) as cl: input = piff.InputFiles(config, logger=cl.logger) + input.readMetadata(logger=cl.logger) assert 'Using a bare FITS header key for ra is deprecated' in cl.output assert 'Using a bare FITS header key for dec is deprecated' in cl.output assert 'ImageHeaderValue' in cl.output @@ -2665,20 +2696,18 @@ def test_pointing(): # Check invalid ra,dec values base_config = { 'dir' : dir, 'image_file_name' : image_file, 'cat_file_name' : cat_file } - np.testing.assert_raises(ValueError, piff.InputFiles, - dict(ra=0, dec='00:00:00' , **base_config)) - np.testing.assert_raises(ValueError, piff.InputFiles, - dict(ra='00:00:00', dec=0, **base_config)) - np.testing.assert_raises(ValueError, piff.InputFiles, - dict(ra=0*galsim.degrees, dec=0*galsim.radians, **base_config)) - np.testing.assert_raises(KeyError, piff.InputFiles, - dict(ra='bad_ra', dec='DEC', **base_config)) - np.testing.assert_raises(KeyError, piff.InputFiles, - dict(ra='RA', dec='bad_dec', **base_config)) - np.testing.assert_raises(ValueError, piff.InputFiles, - dict(ra=0, **base_config)) - np.testing.assert_raises(ValueError, piff.InputFiles, - dict(dec=0, **base_config)) + for error, coords in [ + (ValueError, {'ra': 0, 'dec': '00:00:00'}), + (ValueError, {'ra': '00:00:00', 'dec': 0}), + (ValueError, {'ra': 0*galsim.degrees, 'dec': 0*galsim.radians}), + (KeyError, {'ra': 'bad_ra', 'dec': 'DEC'}), + (KeyError, {'ra': 'RA', 'dec': 'bad_dec'}), + (ValueError, {'ra': 'GS_WCS', 'dec': 'GS_WCS'}), + (ValueError, {'ra': 0}), + (ValueError, {'dec': 0}), + ]: + input = piff.InputFiles(dict(base_config, **coords)) + np.testing.assert_raises(error, input.readMetadata) # If image has celestial wcs, and no ra, dec specified then it will compute it for you config = { @@ -2690,6 +2719,7 @@ def test_pointing(): 'y_col' : 'YWIN_IMAGE', } input = piff.InputFiles(config, logger=logger) + input.readMetadata(logger=logger) np.testing.assert_almost_equal(input.pointing.ra / galsim.hours, 4.063, decimal=3) np.testing.assert_almost_equal(input.pointing.dec / galsim.degrees, -51.471, decimal=3) @@ -2697,6 +2727,7 @@ def test_pointing(): config['ra'] = 'TELRA' config['dec'] = 'TELDEC' input = piff.InputFiles(config, logger=logger) + input.readMetadata(logger=logger) np.testing.assert_almost_equal(input.pointing.ra / galsim.hours, 4.097, decimal=3) np.testing.assert_almost_equal(input.pointing.dec / galsim.degrees, -52.375, decimal=3) @@ -2711,6 +2742,7 @@ def test_pointing(): 'y_col' : 'YWIN_IMAGE', } input = piff.InputFiles(config, logger=logger) + input.readMetadata(logger=logger) np.testing.assert_almost_equal(input.pointing.ra / galsim.hours, 4.063, decimal=3) np.testing.assert_almost_equal(input.pointing.dec / galsim.degrees, -51.471, decimal=3) @@ -2769,6 +2801,7 @@ def test_sky(): extra_props = raw_data.extra_props stars = input.makeStars(logger=logger) np.testing.assert_allclose(image.array, raw_image.array - 7) + assert raw_data.sky == 7 assert 'sky' not in extra_props for i in range(len(stars)): assert 'sky' not in stars[i].data.properties @@ -3246,7 +3279,7 @@ def test_single_sed(): config6 = dict(config) del config6['bandpass'] with np.testing.assert_raises(ValueError) as e: - piff.InputFiles(config6, logger=logger) + piff.InputFiles(config6, logger=logger).getRawImageData(0) assert "bandpass is required" in str(e.exception) @@ -3525,6 +3558,9 @@ def test_input_bandpass(): assert pointing is None assert bandpass is not None + # Bandpass queries also read metadata automatically before any image processing. + assert piff.InputFiles(config['input']).getBandpass(logger) == bandpass + # PSF.process creates a PSF object without the wcs, pointing, bandpass context yet. psf = piff.PSF.process(config['psf'], logger=logger) assert psf.wcs is None @@ -3673,7 +3709,7 @@ def test_asdf(): for ext in [None, 1, 'data_arrays.missing', 'invalid']: invalid = dict(config, image_ext=ext) error = KeyError if isinstance(ext, str) else ValueError - np.testing.assert_raises(error, piff.InputFiles, invalid) + np.testing.assert_raises(error, piff.InputFiles(invalid).readMetadata) if __name__ == '__main__': setup() diff --git a/tests/test_pixel.py b/tests/test_pixel.py index b2062fdb..fa10c8ff 100644 --- a/tests/test_pixel.py +++ b/tests/test_pixel.py @@ -938,12 +938,12 @@ def test_single_image(): 'sky' : sky_level, } input = piff.InputFiles(config) - assert input.image_file_name == [image_file] - assert input.cat_file_name == [cat_file] # Check image assert input.nimages == 1 raw_data = input.getRawImageData(0) + assert input.image_file_name == [image_file] + assert input.cat_file_name == [cat_file] image1 = raw_data.image image_pos = raw_data.image_pos np.testing.assert_equal(image1.array, image.array - sky_level) @@ -1636,10 +1636,10 @@ def test_color(): 'property_cols' : ['color'] } input = piff.InputFiles(config) - assert input.image_file_name == [image_file] - assert input.cat_file_name == [cat_file] assert input.nimages == 1 image1, _, image_pos, props, _ = input.getRawImageData(0) + assert input.image_file_name == [image_file] + assert input.cat_file_name == [cat_file] np.testing.assert_equal(image1.array, image.array) assert len(image_pos) == len(x_list) np.testing.assert_equal([pos.x for pos in image_pos], x_list) diff --git a/tests/test_simple.py b/tests/test_simple.py index ba7a1681..2d51d7d5 100644 --- a/tests/test_simple.py +++ b/tests/test_simple.py @@ -184,12 +184,12 @@ def test_single_image(): config = { 'image_file_name' : image_file, 'cat_file_name': cat_file } input = piff.InputFiles(config, logger=logger) - assert input.image_file_name == [ image_file ] - assert input.cat_file_name == [ cat_file ] # Check image assert input.nimages == 1 raw_data = input.getRawImageData(0) + assert input.image_file_name == [ image_file ] + assert input.cat_file_name == [ cat_file ] image1 = raw_data.image image_pos = raw_data.image_pos np.testing.assert_equal(image1.array, image.array) From f9885f3cc942b52277be53b63af6b836ebf2da6e Mon Sep 17 00:00:00 2001 From: Mike Jarvis Date: Thu, 5 Nov 2026 16:24:11 -0500 Subject: [PATCH 14/18] Make sure sky property is invalid when using another sky specification --- piff/input.py | 3 +++ tests/test_input.py | 15 +++++++++++++++ 2 files changed, 18 insertions(+) diff --git a/piff/input.py b/piff/input.py index 6666d2db..ece0880b 100644 --- a/piff/input.py +++ b/piff/input.py @@ -1260,6 +1260,9 @@ def safe_to_image(wcs, ra, dec): extra_props.update(self._evaluate_properties( params['properties'], extra_props, len(cat), base, logger)) + if 'sky' in extra_props and data.sky is not None: + raise ValueError("A sky property cannot coexist with an image-level sky source.") + data.image_pos = image_pos data.extra_props = extra_props diff --git a/tests/test_input.py b/tests/test_input.py index 4b727d58..ff1baffd 100644 --- a/tests/test_input.py +++ b/tests/test_input.py @@ -2917,6 +2917,21 @@ def test_sky(): for i in range(len(stars)): np.testing.assert_allclose(stars[i].image.array, raw_stars[i].image.array - sky_med) + # Make sure a sky property can't sneak in via the property_cols or properties avenue. + # These should still be invalid in conjunction with other sky specifications. + for properties in [{'property_cols': ['sky']}, {'properties': {'sky': 7}}]: + for sky_source in [{'sky': 0}, {'sky_file_name': sky_file}]: + conflicting_config = { + 'image_file_name': image_file, + 'cat_file_name': cat_file, + **properties, + **sky_source, + } + reader = piff.InputFiles(conflicting_config) + with np.testing.assert_raises(ValueError) as e: + reader.getRawImageData(0) + assert 'sky property' in str(e.exception) + # Error if sky_file doesn't exist config['sky_file_name'] = sky_file[-2] with np.testing.assert_raises(ValueError): From e40051c5976a2b18f4de8ee34dd9640907525493 Mon Sep 17 00:00:00 2001 From: Mike Jarvis Date: Thu, 5 Nov 2026 17:55:13 -0500 Subject: [PATCH 15/18] Add RomanFiles custom input type --- docs/roman.rst | 3 + piff/roman/__init__.py | 1 + piff/roman/roman_files.py | 425 ++++++++++++++++++++++++++++++++++++++ tests/output/.gitignore | 1 + tests/test_roman_files.py | 332 +++++++++++++++++++++++++++++ 5 files changed, 762 insertions(+) create mode 100644 piff/roman/roman_files.py create mode 100644 tests/test_roman_files.py diff --git a/docs/roman.rst b/docs/roman.rst index df6a7e01..37aee42a 100644 --- a/docs/roman.rst +++ b/docs/roman.rst @@ -7,6 +7,9 @@ live in the sub-module piff.roman. They include the following: .. autoclass:: piff.roman.RomanGWCS :members: +.. autoclass:: piff.roman.RomanFiles + :members: + .. autoclass:: piff.roman.RomanOpticsPSF :members: diff --git a/piff/roman/__init__.py b/piff/roman/__init__.py index 6c368eec..1eb1ca2a 100644 --- a/piff/roman/__init__.py +++ b/piff/roman/__init__.py @@ -18,3 +18,4 @@ from .roman_psf import RomanOpticsPSF, RomanOpticalModel, RomanSCAInterp from .gwcs import RomanGWCS +from .roman_files import RomanFiles diff --git a/piff/roman/roman_files.py b/piff/roman/roman_files.py new file mode 100644 index 00000000..69e2eb20 --- /dev/null +++ b/piff/roman/roman_files.py @@ -0,0 +1,425 @@ +# Copyright (c) 2026 by Mike Jarvis and the other collaborators on GitHub at +# https://github.com/rmjarvis/Piff All rights reserved. +# +# Piff is free software: Redistribution and use in source and binary forms +# with or without modification, are permitted provided that the following +# conditions are met: +# +# 1. Redistributions of source code must retain the above copyright notice, this +# list of conditions and the disclaimer given in the accompanying LICENSE +# file. +# 2. Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the disclaimer given in the documentation +# and/or other materials provided with the distribution. + +import numpy as np +import galsim +from scipy.fft import fftn, ifftn +from scipy.ndimage import uniform_filter + +from ..input import InputFiles, ImageMetadata +from .gwcs import RomanGWCS + + +class RomanFiles(InputFiles): + """Read calibrated Roman ASDF images and their ramp-fit noise information. + + This automatically reads the correct data arrays from the Roman image files + without the need for explicit ext values for the mask, image, wcs, etc. + + It is recommended to use ``sky: sep`` to determine a good background to use + both for sky subtraction and to determine the appropriate background variance + for the weight map. + + Additional input options are: + + :ramp_fit: ``optimal`` (default) uses the calibrated data and ERR variance. + ``uniform`` uses data + DUMO and infers read variance and gain + from clean optimal-ramp background pixels and the read pattern. + :good_dq_bits: Integer bit mask of DQ flags to allow. Default 0 rejects every + nonzero DQ value. To allow JUMP_DET and UNRELIABLE_SLOPE, use + ``good_dq_bits: 16777220`` (4 | 16777216). + :smoothing_scale: Gaussian standard deviation in pixels for smoothing the uniform + gain and non-Poisson variance estimates. [default: 64] + :mask_dumo_spikes: For uniform ramps, whether to reject DUMO values that spike + up to high values (>10 x ERR) at JUMP_DET pixels unless their + eight neighbor data pixels have summed S/N > 10. This empirical + screen is optional and only matters when JUMP_DET is allowed. + [default: False] + + Uniform-noise calibration selects pixels within twice ERR of the median in both + ramp images. See `load_gain` and `estimate_uniform_noise` for more details. + + :param config: The input configuration dictionary. + :param base: The base configuration dictionary. [default: None] + :param logger: Optional logger. [default: None] + """ + _type_name = 'RomanFiles' + _opt_params = InputFiles._opt_params | { + 'ramp_fit': str, + 'good_dq_bits': int, + 'smoothing_scale': float, + 'mask_dumo_spikes': bool, + } + + def __init__(self, config, base=None, logger=None): + for key in ['image_ext', 'weight_file_name', 'weight_ext', + 'badpix_file_name', 'badpix_ext', 'fix_ushort_badpix', + 'gain_file_name', 'gain_ext', 'gain', 'gain_col', 'noise', 'invert_weight']: + if key in config: + raise ValueError('RomanFiles constructs its own image, weight, mask, and gain; ' + '%s is not supported' % key) + config = dict(config) + config['image_ext'] = 'roman.data' + config.setdefault('remove_signal_from_weight', True) + super().__init__(config, base=base, logger=logger) + + def read_metadata(self, file_name, ext): + """Read Roman image bounds and native WCS.""" + import asdf + + with asdf.open(file_name) as af: + roman = af['roman'] + ny, nx = roman['data'].shape + return ImageMetadata(galsim.BoundsI(1, nx, 1, ny), + RomanGWCS(roman['meta']['wcs']), None) + + def load_image(self, data, logger): + """Load Roman science and auxiliary ramp data from the ASDF file. + + Input data: image_num, config, base. + This function sets: image, ramp_fit, optimal, dumo + + The latter 3 are used by later stages to compute the primary data products. + """ + import asdf + + data.ramp_fit = self._parse_params(data, {'ramp_fit': 'optimal'})['ramp_fit'] + if data.ramp_fit not in ('optimal', 'uniform'): + raise ValueError('ramp_fit must be optimal or uniform') + file_name = self._parse_params(data, {'image_file_name': None})['image_file_name'] + logger.info('Reading Roman %s ramp image from %s', data.ramp_fit, file_name) + with asdf.open(file_name) as af: + roman = af['roman'] + data.optimal = np.array(roman['data'], dtype=np.float32) + if data.ramp_fit == 'uniform': + data.dumo = np.array(roman['dumo'], dtype=np.float32) + image = data.optimal + data.dumo + else: + image = data.optimal + data.image = galsim.Image(image, wcs=self.metadata_list[data.image_num].wcs) + data.image.header = None + data.base['_current_image'] = data.image + + def load_weight(self, data, logger): + """Read ERR and photon variance, and derive the total non-Poisson variance. + + Input data: image_num, image, config, base. + This function sets: err, var_rnoise, var_poisson + """ + import asdf + + file_name = self._parse_params(data, {'image_file_name': None})['image_file_name'] + with asdf.open(file_name) as af: + roman = af['roman'] + data.err = np.array(roman['err'], dtype=float) + data.var_poisson = np.array(roman['var_poisson'], dtype=float) + # Treat all non-Poisson contributions together as the effective total read noise. + data.var_rnoise = data.err**2 - data.var_poisson + + def load_gain(self, data, logger): + """Read DQ and derive the gain for the selected ramp fit. + + Input data: image, optimal, ramp_fit, err, var_rnoise, var_poisson, config, base. + This function sets: gain_image, dq, and updates: var_rnoise. + + For ramp_fit=optimal, gain = optimal / var_poisson + For ramp_fit=uniform, the procedure is more complicate. The gain and read_variance + are inferred together from unflagged background pixels. See estimate_uniform_noise + for details. + + var_rnoise represents all non-Poisson variance, without separating read noise + from flat-field or other contributions. + """ + import asdf + + file_name = self._parse_params(data, {'image_file_name': None})['image_file_name'] + with asdf.open(file_name) as af: + roman = af['roman'] + data.dq = np.array(roman['dq']) + if data.ramp_fit == 'optimal': + gain = np.zeros(data.image.array.shape) + np.divide(data.optimal, data.var_poisson, out=gain, + where=np.isfinite(data.var_poisson) & (data.var_poisson > 0)) + else: + data.var_rnoise, gain = self.estimate_uniform_noise(data) + data.gain_image = galsim.Image(gain, bounds=data.image.bounds) + + def build_mask(self, data, logger): + """Build a mask of which pixels Piff should not use. + + Input data: image, weight, gain_image, optimal, dumo, err, var_poisson, dq, + ramp_fit, config, base + This function sets: mask + """ + super().build_mask(data, logger) + options = self._parse_params(data, {'good_dq_bits': 0, 'mask_dumo_spikes': False}) + good_bits = options['good_dq_bits'] + if good_bits < 0 or good_bits > np.iinfo(np.uint32).max: + raise ValueError('good_dq_bits must be an unsigned 32-bit bit mask') + + # Mask dq pixels not marked as "good_dq_bits". + data.mask |= (data.dq & ~np.uint32(good_bits)) != 0 + + # Mask any non-finite or otherwise invalid values. + data.mask |= ~np.isfinite(data.optimal) | (data.optimal <= 0) + data.mask |= ~np.isfinite(data.err) | (data.err <= 0) + data.mask |= ~np.isfinite(data.var_poisson) | (data.var_poisson <= 0) + + # If requested mask DUMO pixels with clear spike values. + # This looks for dumo pixels where: + # 1. dq = JUMP_DET (=4) + # 2. dumo > 10 * err (i.e. the pixel's own S/N > 10) + # 3. total S/N in surrounding 8 pixels < 10 + # This is a rough proxy for pixels where the JUMP_DET is doing the right thing rather + # than spuriously triggering due to the guider problems in commissioning data. + if data.ramp_fit == 'uniform' and options['mask_dumo_spikes']: + background = np.median(data.optimal[~data.mask]) + signal = np.where(data.mask, 0, data.optimal - background) + variance = np.where(data.mask, 0, data.err**2) + neighbor_signal = 9 * uniform_filter(signal, size=3, mode='constant') - signal + neighbor_variance = 9 * uniform_filter(variance, size=3, mode='constant') - variance + supported = neighbor_signal > 10 * np.sqrt(np.maximum(neighbor_variance, 0)) + data.mask |= ((data.dq & 4) != 0) & (data.dumo > 10 * data.err) & ~supported + + def finalize_weight(self, data, logger): + """Finalize the weight image to be inverse variance weight without source poisson noise. + + Note: technically, the user can select remove_signal_from_weight=False to not remove + the source Poisson noise, but this is not advised. + + Input data: image, var_rnoise, var_poisson, ramp_fit, mask, gain_image, sky, extra_props, + config, base. + Uniform ramps also use: optimal, dumo. + This function updates: weight, mask + """ + params = self._parse_params(data, {'remove_signal_from_weight': True}) + gain = data.gain_image.array + # Start with the read noise. + variance = data.var_rnoise.copy() + if params['remove_signal_from_weight']: + # Add in the poisson noise from the background photons. + sky = data.sky + if 'sky' in data.extra_props: + sky = np.mean(data.extra_props['sky']) + if sky is not None: + sky = sky.array if isinstance(sky, galsim.Image) else sky + variance += sky / gain + logger.verbose("Removed source variance.") + elif data.ramp_fit == 'uniform': + # Add in the poisson noise from all photons. + variance += (data.optimal + data.dumo) / gain + else: + variance += data.var_poisson + invalid = ~data.mask & (~np.isfinite(variance) | (variance <= 0)) + data.mask |= invalid + if np.any(invalid): + logger.warning("Masked %d pixels with invalid variance in Roman weight calculation", + np.count_nonzero(invalid)) + # weight is 1/variance + # Do this carefully to keep masked pixels = 0. + data.weight = galsim.Image(variance, bounds=data.image.bounds) + data.weight.array[data.mask] = 0 + data.weight._invertSelf() + data.weight._piff_default_weight = False + + def estimate_uniform_noise(self, data): + """Estimate uniform-ramp noise and gain. + + Input data: image, optimal, err, var_rnoise, var_poisson, dq, config, base. + Return estimate of var_rnoise, gain + + Uniform ramp fitting uses fixed slope coefficients. For illumination that is + constant during the ramp, photon variance is proportional to the signal with a + brightness-independent coefficient: variance = signal / gain. Bright sources + therefore have the same effective gain as other nearby pixels. (We do see evidence + of spatial structure in the gain map, so it's not just a single constant value.) + Optimal fitting instead changes its coefficients with the photon/read-noise + balance, so its effective gain varies significantly with brightness. + + The project supplies dumo (difference uniform minus optimal) to let us calculate + the uniform ramp data value. But they don't provide the necessary information + to directly determine either the gain or the noise that one would get with the + uniform-weight ramp fits. + + They do, however, provide the read times for the ramp samples (the resultants). + From this we can calculate the expected correlation between samples assuming + uniform illumination during an exposure. We can propagate this covariance to + estimate the variance in the measurements for a given weight vector. + + The project tells us the poisson noise variance on each pixel and the total error + from which we can infer the read noise. (Technically, we use ERR^2 - VAR_POISSON, + which includes all non-poisson sources of noise, including flat fielding noise. + We take this all to be read noise, which is probably not 100% accurate.) + + We then make the assumption that the background pixels have uniform illumination + (i.e. they are not affected by any guiding problems). From this we can estimate the + optimal weight vector for a typical background pixel, which gives us a scaling relation + for the read noise and gain between optimal and uniform weights. + + Finally, we use those scalings to get the read noise and gain for the background + pixels and smooth/interpolate these to the rest of the pixels in the image. + This is valid for uniform weights, since the read noise and gain are expected to be + independent of the pixel flux. + + There are inline code comments about each step with further details about how + this works, including the math involved. + + Returns the estimated read noise variance and gain as numpy arrays. + """ + from astropy.convolution import Gaussian2DKernel, convolve_fft + import asdf + + smoothing_scale = self._parse_params(data, {'smoothing_scale': 64})['smoothing_scale'] + if smoothing_scale <= 0: + raise ValueError('smoothing_scale must be positive') + + # We first pick out pixels that are basically just background. Our calculations will + # assume uniform illumination, which isn't true for bright pixels when there are + # guiding issues (the main reason to use this). We do this by selecting pixels that + # are within 2 sigma of the median for both data and data+dumo images. + samples = data.dq == 0 + # DQ=0 excludes most problematic pixels, but weirdly some still have var_poisson=0. + samples &= (data.optimal > 0) & (data.var_poisson > 0) + if np.any(samples): + background = np.median(data.optimal[samples]) + samples &= np.abs(data.optimal - background) < 2 * data.err + uniform_background = np.median(data.image.array[samples]) + samples &= np.abs(data.image.array - uniform_background) < 2 * data.err + if not np.any(samples): + raise ValueError('No clean background samples for uniform-noise calibration') + + # Use the provided read times to calculate P. + # + # Each read is N(t_i) with expectation value E(N(t_i)) = f t_i, where f is the rate of + # photon arrival, photons/sec. Its noise includes both read noise and poisson noise on + # the photon counts. We take the read noise variance, g, to be constant for each read. + # + # The covariance between two reads (N(t_1) and N(t_2)) is simple -- they share the + # photons that arrived before the earlier read, and not anything between then and the + # later read: + # + # Cov(N(t_i), N(t_j)) = f min(t_i, t_j) + delta_ij g + # + # Each resultant, R_a, is the average of several such reads at a set of times. + # E.g. the first resultant might be the average of reads at times [1, 2] + # Then the next could be at times [3, 4, 5], etc. + # + # The covariance between two resultants is then the average of the covariances of all + # the pairs of reads they comprise: + # + # Cov(R_a, R_b) = f Sum_(i in a) Sum_(j in b) min(t_i, t_j)/(n_a n_b) + delta_ab g/n_a + # + # We define P_ab and R_ab matrices such that + # + # Cov(R_a, R_b) = f P_ab + g R_ab + + file_name = self._parse_params(data, {'image_file_name': None})['image_file_name'] + with asdf.open(file_name) as af: + exposure = af['roman']['meta']['exposure'] + read_times = [np.array(t) * exposure['frame_time'] + for t in exposure['read_pattern']] + nreads = np.array([len(t) for t in read_times]) + times = np.array([np.mean(t) for t in read_times]) + R = np.diag(1.0 / nreads) + P = np.array([[np.minimum(a[:, None], b[None, :]).mean() + for b in read_times] + for a in read_times]) + + # For a given pixel with resultants R_i, the expected values along the ramp are + # R_i = f t_i where t_i is the average of the individual reads for that resultant. + # There may also be an initial value before the exposure starts, which we want to + # ignore, so E(R_i) = b + f t_i in general. + # + # A uniform-weight fit of the slope, f, is uniform in the reads, but since resultants + # can each have a different number of reads, we actually weight by n_i. This is just + # the normal inverse-variance weighting, since the read noise variance is g/n_i. + # The uniform here means we don't account for the varying poisson noise in the weights. + # + # The least squares solution can be written as: + # + # f^ = Sum_i u_i R_i + # + # u_i = n_i (t_i W - T) / (U W - T^2) + # + # where W = Sum_i n_i, T = Sum_i n_i t_i, and U = Sum_i n_i t_i^2. + # + # These weights can be used to calculate the poisson noise contribution to the + # pixel variance. Along with the read noise, the total variance is: + # + # Var(f^) = f u^T P u + g u^T R u + + W = nreads.sum() + T = nreads @ times + U = nreads @ times**2 + u = nreads * (times * W - T) / (U * W - T**2) + uTPu = u @ P @ u + uTRu = u @ R @ u + + # The optimal weights are different depending on the brightness. Specifically, + # they depend on the ratio f/g. For the background pixels we're considering here, + # the average ratio is found from the read noise and poisson noise. + # We make the approximation that the photon/read variance ratio is equal for optimal + # and uniform fits, allowing us to estimate f/g using the uniform noise factors. + # That's not exactly true, and we'll have better estimate of the difference by the + # end of this process, but it's close enough for this starting value. + ratio = np.median(data.var_poisson[samples] / data.var_rnoise[samples]) + q = ratio * uTRu / uTPu + + # The optimal weights for a uniform illumination can be thought of as finding the + # minimum variance linear estimate of the slope between successive resultants. + # I.e. the differences divided by the time. We make d as this difference operator, so + # d @ resultants would be the slopes to be fit for a given pixel. + d = np.diff(np.eye(len(times)), axis=0) / np.diff(times)[:, None] + R_d = d @ R @ d.T + P_d = d @ P @ d.T + cov_d = R_d + q * P_d # Ignore the overall factor of g, which drops out. + + # Solve for w given that the expectation value of the slopes are all equal. + w = np.linalg.solve(cov_d, np.ones(len(d))) + w /= w.sum() + + # This now gives us a scaling we can apply to convert var_rnoise and var_poisson from + # the optimal weight to uniform. + # However, we actually want the gain, which scales inversely with var_poisson for + # these background images. We can then assume that gain pattern also applies to the + # brighter objects for uniform weights. (That's not true for optimal.) + R_scale = uTRu / (w @ R_d @ w) + gain_scale = (w @ P_d @ w) / uTPu + + # The read noise and gain both seem to have real structure across the SCA, so we + # don't just use a single mean value and apply it everywhere. Instead, use a + # 2D Gaussian smoothing kernel from astropy to smooth the raw values over the whole + # image and interpolate to the non-background pixels. + # Also, we want the final maps to be read noise and gain. At fixed signal, gain is + # inversely proportional to the photon variance. We choose to interpolate 1/gain + # rather than gain, since that's the quantity we eventually use, but it probably + # doesn't matter much either way. + kernel = Gaussian2DKernel(smoothing_scale) + kwargs = { + 'mask': ~samples, + 'fill_value': np.nan, + 'nan_treatment': 'interpolate', + 'preserve_nan': False, + 'min_wt': 1.e-6, + 'complex_dtype': np.complex64, + 'fftn': fftn, + 'ifftn': ifftn, + } + read_map = convolve_fft(data.var_rnoise, kernel, **kwargs) + read_map *= R_scale + inverse_gain = np.zeros(data.optimal.shape, dtype=np.float32) + np.divide(data.var_poisson, data.optimal, out=inverse_gain, where=samples) + inverse_gain = convolve_fft(inverse_gain, kernel, **kwargs) + gain_map = gain_scale / inverse_gain + return read_map, gain_map diff --git a/tests/output/.gitignore b/tests/output/.gitignore index 4d2baff0..3c4533b5 100644 --- a/tests/output/.gitignore +++ b/tests/output/.gitignore @@ -3,4 +3,5 @@ *.pdf *.png *.piff +*.npz test_dir diff --git a/tests/test_roman_files.py b/tests/test_roman_files.py new file mode 100644 index 00000000..6efabe8f --- /dev/null +++ b/tests/test_roman_files.py @@ -0,0 +1,332 @@ +# Copyright (c) 2026 by Mike Jarvis and the other collaborators on GitHub at +# https://github.com/rmjarvis/Piff All rights reserved. +# +# Piff is free software: Redistribution and use in source and binary forms +# with or without modification, are permitted provided that the following +# conditions are met: +# +# 1. Redistributions of source code must retain the above copyright notice, this +# list of conditions and the disclaimer given in the accompanying LICENSE +# file. +# 2. Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the disclaimer given in the documentation +# and/or other materials provided with the distribution. + +import os +import shutil +import numpy as np +import galsim +import fitsio +import pytest +import piff + +from piff_test_helper import timer + + +@pytest.fixture(scope='module', autouse=True) +def setup(): + """Write the Roman image, catalog, sky, and reference calibration used by these tests.""" + asdf = pytest.importorskip('asdf') + gwcs = pytest.importorskip('gwcs') + from astropy import units + from astropy.coordinates import ICRS + from astropy.modeling import models + from gwcs.coordinate_frames import Frame2D, CelestialFrame + + # Build an image with sloping sky and 3 stars in it. + y, x = np.indices((128, 128)) + sky = 5 + 0.001 * x + 0.002 * y + signal = galsim.ImageD(128, 128, scale=0.11) + positions = [(33.2, 35.7), (93.4, 42.2), (65.1, 93.8)] + for pos, flux in zip(positions, [3000, 6000, 4000]): + profile = galsim.Moffat(beta=3.5, fwhm=0.3, flux=flux).shear(g1=0.04, g2=-0.02) + profile.drawImage(image=signal, center=galsim.PositionD(*pos), add_to_image=True) + science = (sky + signal.array).astype(np.float32) + + # Make the variances realistic given a specific set of read times. + pattern = [[1], [2, 3], [4, 5, 6], [7, 8], [9, 10, 11, 12]] + t_read = np.arange(1, 13) * 2.0 # Individual read times in seconds. + n = np.array([len(reads) for reads in pattern]) # Number of reads per resultant. + + # R averages individual reads into resultants. + # C_r and C_p are the resultant covariances for the read noise and poisson noise respectively, + # per unit read variance (g) and photon arrival rate (f). + # t gives the mean resultant times. + R = np.zeros((len(pattern), len(t_read))) + for i, reads in enumerate(pattern): + for read_number in reads: + R[i, read_number - 1] = 1.0 / n[i] + C_r = R @ R.T + P = np.array([[min(t1, t2) for t2 in t_read] for t1 in t_read]) + C_p = R @ P @ R.T + t = R @ t_read + + # Compute the optimal up-the-ramp estimates with optimal weights the way the project + # computes these. + g = 12.5 # Read-noise variance per individual read. + gain = 3.7 # Actual detector gain; the photon covariance amplitude is f = signal/gain. + A = np.array([[1.0, ti] for ti in t]) # Design matrix for fitting the ramp. + f = science / gain + + # The first two axes index pixels; the last two hold each pixel's covariance matrix. + C = g * C_r + f[:, :, None, None] * C_p + + # Fit intercept and slope to resultants r via + # beta = F r, where F = (A.T C^-1 A)^-1 A.T C^-1. + # Row 1 of each pixel's F gives its slope weights w. + Cinv = np.linalg.inv(C) + F = np.linalg.inv(A.T @ Cinv @ A) @ A.T @ Cinv + w = F[:, :, 1, :] + + # Propagate each covariance contribution: w.T C w. Summing over the last axis + # contracts the resultant index, leaving read- and photon-variance images V_r and V_p. + V_r = g * np.sum((w @ C_r) * w, axis=-1) + V_p = f * np.sum((w @ C_p) * w, axis=-1) + + # Uniform fitting uses resultant weights W=diag(n). Solve the weighted normal + # equations directly, independently of the closed-form coefficients in RomanFiles. + # As above, F maps resultants to intercept and slope; u is the uniform slope vector. + W = np.diag(n) + F = np.linalg.inv(A.T @ W @ A) @ A.T @ W + u = F[1] + + # Propagating the uniform weights gives read variance g u.T C_r u and photon variance + # (signal/gain) u.T C_p u. Thus the effective gain is gain/(u.T C_p u). + uniform_read = g * (u @ C_r @ u) + uniform_gain = gain / (u @ C_p @ u) + + # Make a TAN WCS in GWCS format. + wcs = gwcs.WCS( + (models.Shift(-63.5) & models.Shift(-63.5)) + | (models.Scale(-0.11 / 3600) & models.Scale(0.11 / 3600)) + | models.Pix2Sky_TAN() | models.RotateNative2Celestial(53, -27, 180), + input_frame=Frame2D(name='detector', unit=(units.pix, units.pix)), + output_frame=CelestialFrame(reference_frame=ICRS(), name='world', + unit=(units.deg, units.deg)), + ) + + # Include two allowed DQ bits and one disallowed bit for the masking tests below. + dq = np.zeros(science.shape, dtype=np.uint32) + dq[10, 10] = 8192 + dq[11, 11] = 4 + dq[12, 12] = 16777216 + dq[35, 32] = 4 + + # A 30-ERR DUMO excursion at an isolated pixel should be rejected by the optional + # spike screen; the same excursion beside a bright source should be preserved. + dumo = np.full(science.shape, 0.01, dtype=np.float32) + dumo[11, 11] = 30 * np.sqrt(V_r[11, 11] + V_p[11, 11]) + dumo[35, 32] = 30 * np.sqrt(V_r[35, 32] + V_p[35, 32]) + + tree = { + 'roman': { + 'data': science, + 'err': np.sqrt(V_r + V_p), + 'var_poisson': V_p, + 'dq': dq, + 'dumo': dumo, + 'meta': { + 'wcs': wcs, + 'exposure': {'frame_time': 2.0, 'read_pattern': pattern}, + }, + }, + } + output_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'output') + os.makedirs(output_dir, exist_ok=True) + with asdf.AsdfFile(tree) as af: + af.write_to(os.path.join(output_dir, 'roman_input.asdf')) + catalog_rows = [] + for (x, y), sky_value in zip(positions, [4.0, 5.0, 6.0]): + catalog_rows.append((x, y, sky_value)) + catalog = np.array(catalog_rows, dtype=[('x', float), ('y', float), ('sky', float)]) + fitsio.write(os.path.join(output_dir, 'roman_cat.fits'), catalog, clobber=True) + fitsio.write(os.path.join(output_dir, 'roman_sky.fits'), sky.astype(np.float32), clobber=True) + np.savez(os.path.join(output_dir, 'roman_truth.npz'), + uniform_read=uniform_read, uniform_gain=uniform_gain) + + +@timer +def test_roman_input(): + """Test the normal path using the optimal-ramp values.""" + # Default optimal fitting uses DATA, rejects nonzero DQ, and removes photon variance. + asdf = pytest.importorskip('asdf') + file_name = os.path.join('output', 'roman_input.asdf') + cat_name = os.path.join('output', 'roman_cat.fits') + with asdf.open(file_name) as af: + roman = {} + for key in ['data', 'err', 'var_poisson', 'dq']: + roman[key] = np.array(af['roman'][key]) + config = { + 'type': 'RomanFiles', + 'image_file_name': file_name, + 'cat_file_name': cat_name, + 'stamp_size': 25, + } + data = piff.roman.RomanFiles(config).getRawImageData(0) + good = roman['dq'] == 0 + expected_gain = roman['data'] / roman['var_poisson'] + expected_variance = roman['err']**2 - roman['var_poisson'] + np.testing.assert_array_equal(data.image.array, roman['data']) + np.testing.assert_allclose(data.gain_image.array[good], expected_gain[good]) + np.testing.assert_allclose(data.weight.array[good], 1 / expected_variance[good], rtol=3.e-6) + np.testing.assert_array_equal(data.weight.array[~good], 0) + + # Allowing selected DQ bits makes those pixels usable without allowing other flags. + config['good_dq_bits'] = 4 | 16777216 + data = piff.roman.RomanFiles(config).getRawImageData(0) + good = roman['dq'] != 8192 + np.testing.assert_allclose(data.weight.array[good], 1 / expected_variance[good], rtol=3.e-6) + np.testing.assert_array_equal(data.weight.array[~good], 0) + + # A supplied sky image is subtracted from DATA and its photon variance is retained. + sky_name = os.path.join('output', 'roman_sky.fits') + sky_image = fitsio.read(sky_name) + config['sky_file_name'] = sky_name + data = piff.roman.RomanFiles(config).getRawImageData(0) + expected_variance += sky_image / expected_gain + np.testing.assert_allclose(data.image.array, roman['data'] - sky_image) + np.testing.assert_allclose(data.weight.array[good], 1 / expected_variance[good], rtol=3.e-6) + np.testing.assert_array_equal(data.weight.array[~good], 0) + + # Check that stars get the right image, wcs, gain, weight. + stars, wcs, _, _ = piff.Input.process(config) + assert len(stars) == len(fitsio.read(cat_name)) + assert isinstance(wcs[0], piff.roman.RomanGWCS) + for star in stars: + bounds = star.image.bounds + np.testing.assert_allclose(star.image.array, data.image[bounds].array) + np.testing.assert_allclose(star.weight.array, data.weight[bounds].array) + np.testing.assert_allclose(star.data.gain_image.array, data.gain_image[bounds].array) + assert star.image.wcs == wcs[0] + + # remove_signal_from_weight defaults to true, but can be turned off. + config.pop('sky_file_name') + config['remove_signal_from_weight'] = False + data = piff.roman.RomanFiles(config).getRawImageData(0) + np.testing.assert_allclose(data.weight.array[good], 1 / roman['err'][good]**2) + + # An explicit WCS overrides the native Roman GWCS. + config['wcs'] = {'type': 'PixelScale', 'scale': 0.2} + assert piff.roman.RomanFiles(config).getWCS()[0] == galsim.PixelScale(0.2) + + # Nonpositive science/ERR/photon variance and negative residual variance are masked. + invalid_file = os.path.join('output', 'roman_invalid.asdf') + shutil.copyfile(file_name, invalid_file) + with asdf.open(invalid_file, mode='rw') as af: + roman = af['roman'] + roman['data'][20, 20] = 0 + roman['err'][21, 20] = 0 + roman['err'][21, 21] = np.sqrt(0.5 * roman['var_poisson'][21, 21]) + roman['var_poisson'][22, 20] = 0 + af.update() + invalid_config = dict(config, image_file_name=invalid_file, remove_signal_from_weight=True) + data = piff.roman.RomanFiles(invalid_config).getRawImageData(0) + assert data.weight.array[20, 20] == 0 + assert data.weight.array[21, 20] == 0 + assert data.weight.array[21, 21] == 0 # Total non-poisson variance is negative. + assert data.weight.array[22, 20] == 0 + + # Overriding the locations of weight, gain, badpix, noise are not currently allowed. + for option in ['weight_ext', 'gain_ext', 'badpix_ext', 'noise']: + invalid_config = dict(config) + invalid_config[option] = 1 + with np.testing.assert_raises(ValueError) as e: + piff.roman.RomanFiles(invalid_config) + assert option in str(e.exception) + + # Check invalid ramp_fit. + invalid_config = dict(config, ramp_fit='other') + with np.testing.assert_raises(ValueError) as e: + piff.roman.RomanFiles(invalid_config).getRawImageData(0) + assert 'ramp_fit' in str(e.exception) + + # good_dq_bits must be a valid uint32 number. + for value in [-1, 2**32]: + invalid_config = dict(config, good_dq_bits=value) + with np.testing.assert_raises(ValueError) as e: + piff.roman.RomanFiles(invalid_config).getRawImageData(0) + assert 'good_dq_bits' in str(e.exception) + +@timer +def test_roman_uniform(): + """Test the ramp_fit=uniform option.""" + asdf = pytest.importorskip('asdf') + + # The uniform image is computed from data + dumo. + file_name = os.path.join('output', 'roman_input.asdf') + cat_name = os.path.join('output', 'roman_cat.fits') + with asdf.open(file_name) as af: + roman = {} + for key in ['data', 'dumo', 'dq']: + roman[key] = np.array(af['roman'][key]) + config = { + 'type': 'RomanFiles', + 'image_file_name': file_name, + 'cat_file_name': cat_name, + 'ramp_fit': 'uniform', + 'good_dq_bits': 4 | 16777216, + } + data = piff.roman.RomanFiles(config).getRawImageData(0) + good = roman['dq'] != 8192 + np.testing.assert_array_equal(data.image.array, roman['data'] + roman['dumo']) + + # setup saved the correct uniform read noise and gain in roman_truth.npz so we can + # compare what RomanFiles calculates from the asdf image. + with np.load(os.path.join('output', 'roman_truth.npz')) as truth: + uniform_read = truth['uniform_read'] + uniform_gain = truth['uniform_gain'] + + # The global approximation recovers gain within 0.5% and variance within 1%. + np.testing.assert_allclose(data.gain_image.array, uniform_gain, rtol=0.005) + np.testing.assert_allclose(data.weight.array[good], 1 / uniform_read, rtol=0.01) + np.testing.assert_array_equal(data.weight.array[~good], 0) + + # remove_signal_from_weight defaults to true, but can be turned off. + total = piff.roman.RomanFiles(dict(config, remove_signal_from_weight=False)).getRawImageData(0) + expected_variance = uniform_read + (roman['data'] + roman['dumo']) / uniform_gain + np.testing.assert_allclose(total.weight.array[good], 1 / expected_variance[good], rtol=0.01) + + # If sky is given, it contributes sky/gain to the uniform variance. + data = piff.roman.RomanFiles(dict(config, sky=5.0)).getRawImageData(0) + np.testing.assert_allclose(data.image.array, roman['data'] + roman['dumo'] - 5.0) + np.testing.assert_allclose(data.weight.array[good], + 1 / (uniform_read + 5.0 / uniform_gain), rtol=0.01) + + # A sky image contributes its local sky/gain to the uniform variance. + sky_name = os.path.join('output', 'roman_sky.fits') + sky_image = fitsio.read(sky_name) + data = piff.roman.RomanFiles(dict(config, sky_file_name=sky_name)).getRawImageData(0) + expected_variance = uniform_read + sky_image / uniform_gain + np.testing.assert_allclose(data.weight.array[good], 1 / expected_variance[good], rtol=0.01) + + # If sky is given per star, the mean catalog sky sets the background variance. + data = piff.roman.RomanFiles(dict(config, sky_col='sky')).getRawImageData(0) + np.testing.assert_allclose(data.weight.array[good], + 1 / (uniform_read + 5.0 / uniform_gain), rtol=0.01) + + # The mask_dumo_spikes options masks isolated spikes, but keeps any connected to a source. + data = piff.roman.RomanFiles(dict(config, mask_dumo_spikes=True)).getRawImageData(0) + assert data.weight.array[11, 11] == 0 + assert data.weight.array[12, 12] != 0 + assert data.weight.array[35, 32] != 0 + + # smoothing_scale must be positive. + with np.testing.assert_raises(ValueError) as e: + piff.roman.RomanFiles(dict(config, smoothing_scale=0)).getRawImageData(0) + assert 'smoothing_scale must be positive' in str(e.exception) + + # The uniform calculation only uses DQ=0 pixels, even if those are considered "good_dq_bits". + # So if the whole image is marked as JUMP_DET, the uniform calculation will fail. + alljump_file = os.path.join('output', 'roman_no_background.asdf') + shutil.copyfile(file_name, alljump_file) + with asdf.open(alljump_file, mode='rw') as af: + af['roman']['dq'][:] = 4 + af.update() + with np.testing.assert_raises(ValueError) as e: + piff.roman.RomanFiles(dict(config, image_file_name=alljump_file)).getRawImageData(0) + assert 'No clean background samples' in str(e.exception) + + +if __name__ == '__main__': + test_roman_input() + test_roman_uniform() From 07ebe7bc3e3db5c55c8958e9686c11d824228599 Mon Sep 17 00:00:00 2001 From: Mike Jarvis Date: Thu, 5 Nov 2026 18:04:28 -0500 Subject: [PATCH 16/18] Add asdf, gwcs, sep to ci installation --- .github/workflows/ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f6292584..be21b561 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -112,7 +112,7 @@ jobs: pip install -U -r requirements.txt # Extra packages needed for testing - pip install -U nose coverage "pytest<8" nbval ipykernel pillow + pip install -U nose coverage pytest nbval ipykernel pillow sep asdf gwcs # ngmix isn't on pypi pip install -U numba git+https://github.com/esheldon/ngmix.git From 05ab9779c4eacd1efe37a771b8d1e6c21ef4bcf4 Mon Sep 17 00:00:00 2001 From: Mike Jarvis Date: Thu, 5 Nov 2026 20:01:36 -0500 Subject: [PATCH 17/18] coverage --- piff/singlechip.py | 12 +++++++++--- tests/test_input.py | 27 ++++++++++++++++++++++++++- 2 files changed, 35 insertions(+), 4 deletions(-) diff --git a/piff/singlechip.py b/piff/singlechip.py index 9dba248f..2b22f666 100644 --- a/piff/singlechip.py +++ b/piff/singlechip.py @@ -137,11 +137,17 @@ def fit(self, stars, wcs=None, pointing=None, logger=None, convert_funcs=None, self.psf_by_chip = {} chipnums = list(self.wcs.keys()) - args = [(chipnum, self.single_psf, stars, self.wcs, convert_funcs, draw_method) - for chipnum in chipnums] + args = [(chipnum,) for chipnum in chipnums] + kwargs = dict( + single_psf=self.single_psf, + stars=stars, + wcs=self.wcs, + convert_funcs=convert_funcs, + draw_method=draw_method, + ) output = run_multi(single_chip_run, self.nproc, raise_except=False, - args=args, logger=logger) + args=args, logger=logger, kwargs=kwargs) for chipnum, psf in zip(chipnums, output): self.psf_by_chip[chipnum] = psf diff --git a/tests/test_input.py b/tests/test_input.py index ff1baffd..725449ce 100644 --- a/tests/test_input.py +++ b/tests/test_input.py @@ -2051,7 +2051,9 @@ def test_gain_image(): f.write(gain, extname='GAIN') f.write(background_weight, extname='BACKGROUND_WEIGHT') fitsio.write(gain_name, gain, extname='GAIN', clobber=True) - fitsio.write(cat_name, np.array(positions, dtype=[('x', float), ('y', float)]), clobber=True) + catalog = np.array([(x, y, sky) for x, y in positions], + dtype=[('x', float), ('y', float), ('sky', float)]) + fitsio.write(cat_name, catalog, clobber=True) config = { 'image_file_name': image_name, 'cat_file_name': cat_name, @@ -2062,6 +2064,12 @@ def test_gain_image(): 'use_partial': True, } + # Catalog sky levels preserve the known background variance during source-noise removal. + catalog_config = dict(config, gain_ext='GAIN', sky_col='sky') + catalog_config.pop('sky') + catalog_data = piff.InputFiles(catalog_config).getRawImageData(0) + np.testing.assert_allclose(catalog_data.weight.array, background_weight) + # Numeric/named extensions and separate files give the same gain cutouts and weights. for options in [{'gain_ext': 2}, {'gain_ext': 'GAIN'}, {'gain_file_name': gain_name}, {'gain_file_name': image_name, 'gain_ext': 'GAIN'}]: @@ -3636,6 +3644,7 @@ def test_asdf(): tree = { 'data_arrays': { 'science': science, + 'half': science.astype(np.float16), 'second': science + 5, 'weight': 1.0 / variance, 'badpix': badpix, @@ -3697,6 +3706,22 @@ def test_asdf(): np.testing.assert_array_equal(data.image.array, expected) assert data.image.wcs == galsim.PixelScale(1.0) + # Half-precision science arrays are promoted to a GalSim-supported image dtype. + half_config = { + 'image_file_name': file_name, + 'cat_file_name': cat_name, + 'image_ext': 'data_arrays.half', + } + half_data = piff.InputFiles(half_config).getRawImageData(0) + expected = science.astype(np.float16).astype(np.float32) + expected[30, 30] = 0 + assert half_data.image.dtype == np.float32 + np.testing.assert_array_equal(half_data.image.array, expected) + + # Auxiliary ASDF planes also require dotted paths rather than FITS extension numbers. + invalid = dict(config, weight_ext=1) + np.testing.assert_raises(ValueError, piff.InputFiles(invalid).getRawImageData, 0) + # It's allowed to get the main image from asdf and another (e.g. weight) from FITS. weight_name = os.path.join('output', 'asdf_weight.fits') galsim.Image(1.0 / variance).write(weight_name) From 4d8e1f449d6339239d618cb431941351f5a110d9 Mon Sep 17 00:00:00 2001 From: Mike Jarvis Date: Tue, 17 Nov 2026 00:01:02 -0500 Subject: [PATCH 18/18] Add doc suggestion from Nihar --- piff/roman/roman_files.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/piff/roman/roman_files.py b/piff/roman/roman_files.py index 69e2eb20..dd0c1011 100644 --- a/piff/roman/roman_files.py +++ b/piff/roman/roman_files.py @@ -22,7 +22,7 @@ class RomanFiles(InputFiles): - """Read calibrated Roman ASDF images and their ramp-fit noise information. + """Read calibrated L2 Roman ASDF images and their ramp-fit noise information. This automatically reads the correct data arrays from the Roman image files without the need for explicit ext values for the mask, image, wcs, etc.