Coverage for tests/test_psf.py: 96%
313 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-26 12:05 -0800
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-26 12:05 -0800
1# This file is part of meas_extensions_piff.
2#
3# Developed for the LSST Data Management System.
4# This product includes software developed by the LSST Project
5# (https://www.lsst.org).
6# See the COPYRIGHT file at the top-level directory of this distribution
7# for details of code ownership.
8#
9# This program is free software: you can redistribute it and/or modify
10# it under the terms of the GNU General Public License as published by
11# the Free Software Foundation, either version 3 of the License, or
12# (at your option) any later version.
13#
14# This program is distributed in the hope that it will be useful,
15# but WITHOUT ANY WARRANTY; without even the implied warranty of
16# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17# GNU General Public License for more details.
18#
19# You should have received a copy of the GNU General Public License
20# along with this program. If not, see <https://www.gnu.org/licenses/>.
22from pathlib import Path
24import galsim # noqa: F401
25import piff
26import unittest
27import numpy as np
28import copy
29from galsim import Lanczos # noqa: F401
30import logging
32import lsst.utils.tests
33import lsst.afw.detection as afwDetection
34import lsst.afw.geom as afwGeom
35import lsst.afw.image as afwImage
36import lsst.afw.math as afwMath
37import lsst.afw.table as afwTable
38import lsst.daf.base as dafBase
39import lsst.geom as geom
40import lsst.meas.algorithms as measAlg
41from lsst.pipe.base import AlgorithmError
42from lsst.meas.base import SingleFrameMeasurementTask
43from lsst.meas.extensions.piff.piffPsfDeterminer import PiffPsfDeterminerConfig, PiffPsfDeterminerTask
44from lsst.meas.extensions.piff.piffPsfDeterminer import _validateGalsimInterpolant
45from packaging.version import Version
48def psfVal(ix, iy, x, y, sigma1, sigma2, b):
49 """Return the value at (ix, iy) of a double Gaussian
50 (N(0, sigma1^2) + b*N(0, sigma2^2))/(1 + b)
51 centered at (x, y)
52 """
53 dx, dy = x - ix, y - iy
54 theta = np.radians(30)
55 ab = 1.0/0.75 # axis ratio
56 c, s = np.cos(theta), np.sin(theta)
57 u, v = c*dx - s*dy, s*dx + c*dy
59 return (np.exp(-0.5*(u**2 + (v*ab)**2)/sigma1**2)
60 + b*np.exp(-0.5*(u**2 + (v*ab)**2)/sigma2**2))/(1 + b)
63def make_wcs(angle_degrees=None):
64 """Make a simple SkyWcs that is rotated around the origin.
66 Parameters
67 ----------
68 angle_degrees : `float`, optional
69 The angle to rotate the WCS by, in degrees.
71 Returns
72 -------
73 wcs : `~lsst.afw.geom.SkyWcs`
74 The WCS object.
75 """
76 cdMatrix = np.array([
77 [1.0, 0.0],
78 [0.0, 1.0]
79 ]) * 0.2 / 3600
81 if angle_degrees is not None:
82 angle_radians = np.radians(angle_degrees)
83 cosang = np.cos(angle_radians)
84 sinang = np.sin(angle_radians)
85 rot = np.array([
86 [cosang, -sinang],
87 [sinang, cosang]
88 ])
89 cdMatrix = np.dot(cdMatrix, rot)
91 return afwGeom.makeSkyWcs(
92 crpix=geom.PointD(0, 0),
93 crval=geom.SpherePoint(0.0, 0.0, geom.degrees),
94 cdMatrix=cdMatrix,
95 )
98class SpatialModelPsfTestCase(lsst.utils.tests.TestCase):
99 """A test case for SpatialModelPsf"""
101 def measure(self, footprintSet, exposure):
102 """Measure a set of Footprints, returning a SourceCatalog"""
103 catalog = afwTable.SourceCatalog(self.schema)
105 footprintSet.makeSources(catalog)
107 self.measureSources.run(catalog, exposure)
108 return catalog
110 def setUp(self):
111 config = SingleFrameMeasurementTask.ConfigClass()
112 config.plugins.names = [
113 "base_PsfFlux",
114 "base_GaussianFlux",
115 "base_SdssCentroid",
116 "base_SdssShape",
117 "base_PixelFlags",
118 "base_CircularApertureFlux",
119 ]
120 config.slots.apFlux = 'base_CircularApertureFlux_12_0'
121 self.schema = afwTable.SourceTable.makeMinimalSchema()
123 self.measureSources = SingleFrameMeasurementTask(
124 self.schema, config=config
125 )
126 self.usePsfFlag = self.schema.addField("use_psf", type="Flag")
128 width, height = 110, 301
130 self.mi = afwImage.MaskedImageF(geom.ExtentI(width, height))
131 self.mi.set(0)
132 sd = 3 # standard deviation of image
133 self.mi.getVariance().set(sd*sd)
134 self.mi.getMask().addMaskPlane("DETECTED")
136 self.ksize = 31 # size of desired kernel
138 sigma1 = 1.75
139 sigma2 = 2*sigma1
141 self.exposure = afwImage.makeExposure(self.mi)
142 self.exposure.setPsf(measAlg.DoubleGaussianPsf(self.ksize, self.ksize,
143 1.5*sigma1, 1, 0.1))
144 wcs = make_wcs()
145 self.exposure.setWcs(wcs)
147 #
148 # Make a kernel with the exactly correct basis functions.
149 # Useful for debugging
150 #
151 basisKernelList = []
152 for sigma in (sigma1, sigma2):
153 basisKernel = afwMath.AnalyticKernel(
154 self.ksize, self.ksize, afwMath.GaussianFunction2D(sigma, sigma)
155 )
156 basisImage = afwImage.ImageD(basisKernel.getDimensions())
157 basisKernel.computeImage(basisImage, True)
158 basisImage /= np.sum(basisImage.getArray())
160 if sigma == sigma1:
161 basisImage0 = basisImage
162 else:
163 basisImage -= basisImage0
165 basisKernelList.append(afwMath.FixedKernel(basisImage))
167 order = 1 # 1 => up to linear
168 spFunc = afwMath.PolynomialFunction2D(order)
170 exactKernel = afwMath.LinearCombinationKernel(basisKernelList, spFunc)
171 exactKernel.setSpatialParameters(
172 [[1.0, 0, 0],
173 [0.0, 0.5*1e-2, 0.2e-2]]
174 )
176 rand = afwMath.Random() # make these tests repeatable by setting seed
178 im = self.mi.getImage()
179 afwMath.randomGaussianImage(im, rand) # N(0, 1)
180 im *= sd # N(0, sd^2)
182 xarr, yarr = [], []
184 for x, y in [(20, 20), (60, 20),
185 (30, 35),
186 (50, 50),
187 (20, 90), (70, 160), (25, 265), (75, 275), (85, 30),
188 (50, 120), (70, 80),
189 (60, 210), (20, 210),
190 ]:
191 xarr.append(x)
192 yarr.append(y)
194 for x, y in zip(xarr, yarr):
195 dx = rand.uniform() - 0.5 # random (centered) offsets
196 dy = rand.uniform() - 0.5
198 k = exactKernel.getSpatialFunction(1)(x, y)
199 b = (k*sigma1**2/((1 - k)*sigma2**2))
201 flux = 80000*(1 + 0.1*(rand.uniform() - 0.5))
202 I0 = flux*(1 + b)/(2*np.pi*(sigma1**2 + b*sigma2**2))
203 for iy in range(y - self.ksize//2, y + self.ksize//2 + 1):
204 if iy < 0 or iy >= self.mi.getHeight(): 204 ↛ 205line 204 didn't jump to line 205 because the condition on line 204 was never true
205 continue
207 for ix in range(x - self.ksize//2, x + self.ksize//2 + 1):
208 if ix < 0 or ix >= self.mi.getWidth(): 208 ↛ 209line 208 didn't jump to line 209 because the condition on line 208 was never true
209 continue
211 II = I0*psfVal(ix, iy, x + dx, y + dy, sigma1, sigma2, b)
212 Isample = rand.poisson(II)
213 self.mi.image[ix, iy, afwImage.LOCAL] += Isample
214 self.mi.variance[ix, iy, afwImage.LOCAL] += II
216 bbox = geom.BoxI(geom.PointI(0, 0), geom.ExtentI(width, height))
217 self.cellSet = afwMath.SpatialCellSet(bbox, 100)
219 self.footprintSet = afwDetection.FootprintSet(
220 self.mi, afwDetection.Threshold(100), "DETECTED"
221 )
223 self.catalog = self.measure(self.footprintSet, self.exposure)
225 for source in self.catalog:
226 cand = measAlg.makePsfCandidate(source, self.exposure)
227 self.cellSet.insertCandidate(cand)
229 def setupDeterminer(
230 self,
231 stampSize=None,
232 kernelSize=None,
233 modelSize=25,
234 debugStarData=False,
235 useCoordinates='pixel',
236 spatialOrder=1,
237 zerothOrderInterpNotEnoughStars=False,
238 piffPsfConfigYaml=None,
239 downsample=False,
240 useColor=False,
241 colorOrder=0,
242 withColorInformation=True,
243 withlog=False,
244 ):
245 """Setup the starSelector and psfDeterminer
247 Parameters
248 ----------
249 stampSize : `int`, optional
250 Set ``config.stampSize`` to this, if not None.
251 kernelSize : `int`, optional
252 Cutout size for the PSF candidates. This is unused if ``stampSize``
253 if provided and its value is used for cutout size instead.
254 modelSize : `int`, optional
255 Internal model size for PIFF.
256 debugStarData : `bool`, optional
257 Include star images used for fitting in PSF model object?
258 useCoordinates : `str`, optional
259 Spatial coordinates to regress against for PSF modelling.
260 spatialOrder : `int`, optional
261 Spatial order for PSF parameter interpolation.
262 zerothOrderInterpNotEnoughStars : `bool`, optional
263 If True, use zeroth order interpolation if not enough star.
264 piffPsfConfigYaml : `str`, optional
265 Configuration file for PIFF in YAML format.
266 downsample : `bool`, optional
267 Whether to downsample the PSF candidates before modelling?
268 useColor : `bool`, optional
269 Fit a color dependence of the PSF?
270 colorOrder : `int`, optional
271 Polynomial order of the color dependence.
272 withColorInformation : `bool`, optional
273 Set a color on every PSF candidate before fitting? If False the
274 candidates keep their default (NaN) color, which must make the
275 determiner fall back to a non-chromatic fit even if ``useColor``
276 is True. Unused here; consumed by ``checkPiffDeterminer``.
277 withlog : `bool`, optional
278 Should Piff produce chatty log messages?
279 """
280 starSelectorClass = measAlg.sourceSelectorRegistry["objectSize"]
281 starSelectorConfig = starSelectorClass.ConfigClass()
282 starSelectorConfig.sourceFluxField = "base_GaussianFlux_instFlux"
283 starSelectorConfig.badFlags = [
284 "base_PixelFlags_flag_edge",
285 "base_PixelFlags_flag_interpolatedCenter",
286 "base_PixelFlags_flag_saturatedCenter",
287 "base_PixelFlags_flag_crCenter",
288 ]
289 # Set to match when the tolerance of the test was set
290 starSelectorConfig.widthStdAllowed = 0.5
292 self.starSelector = starSelectorClass(config=starSelectorConfig)
294 makePsfCandidatesConfig = measAlg.MakePsfCandidatesTask.ConfigClass()
295 if kernelSize:
296 makePsfCandidatesConfig.kernelSize = kernelSize
297 if stampSize is not None:
298 makePsfCandidatesConfig.kernelSize = stampSize
300 self.makePsfCandidates = measAlg.MakePsfCandidatesTask(config=makePsfCandidatesConfig)
302 psfDeterminerConfig = PiffPsfDeterminerConfig()
303 psfDeterminerConfig.spatialOrder = spatialOrder
304 psfDeterminerConfig.zerothOrderInterpNotEnoughStars = zerothOrderInterpNotEnoughStars
305 psfDeterminerConfig.stampSize = stampSize
306 psfDeterminerConfig.modelSize = modelSize
308 psfDeterminerConfig.debugStarData = debugStarData
309 psfDeterminerConfig.useCoordinates = useCoordinates
310 psfDeterminerConfig.piffPsfConfigYaml = piffPsfConfigYaml
312 psfDeterminerConfig.colorOrder = colorOrder
313 psfDeterminerConfig.useColor = useColor
315 if piffPsfConfigYaml is None:
316 self.useYaml = False
317 else:
318 self.useYaml = True
320 if downsample:
321 psfDeterminerConfig.maxCandidates = 10
322 if withlog:
323 psfDeterminerConfig.piffLoggingLevel = 1
325 self.psfDeterminer = PiffPsfDeterminerTask(psfDeterminerConfig)
327 def subtractStars(self, exposure, catalog, chi_lim=-1.):
328 """Subtract the exposure's PSF from all the sources in catalog"""
329 mi, psf = exposure.getMaskedImage(), exposure.getPsf()
331 subtracted = mi.Factory(mi, True)
332 for s in catalog:
333 xc, yc = s.getX(), s.getY()
334 bbox = subtracted.getBBox(afwImage.PARENT)
335 if bbox.contains(geom.PointI(int(xc), int(yc))): 335 ↛ 332line 335 didn't jump to line 332 because the condition on line 335 was always true
336 measAlg.subtractPsf(psf, subtracted, xc, yc)
337 chi = subtracted.Factory(subtracted, True)
338 var = subtracted.getVariance()
339 np.sqrt(var.getArray(), var.getArray()) # inplace sqrt
340 chi /= var
342 chi_min = np.min(chi.getImage().getArray())
343 chi_max = np.max(chi.getImage().getArray())
345 if chi_lim > 0: 345 ↛ exitline 345 didn't return from function 'subtractStars' because the condition on line 345 was always true
346 self.assertGreater(chi_min, -chi_lim)
347 self.assertLess(chi_max, chi_lim)
349 def checkPiffDeterminer(self, **kwargs):
350 """Configure PiffPsfDeterminerTask and run basic tests on it.
352 Parameters
353 ----------
354 kwargs : `dict`, optional
355 Additional keyword arguments to pass to setupDeterminer.
356 """
357 self.setupDeterminer(**kwargs)
358 metadata = dafBase.PropertyList()
360 stars = self.starSelector.run(self.catalog, exposure=self.exposure)
361 psfCandidateList = self.makePsfCandidates.run(
362 stars.sourceCat,
363 exposure=self.exposure
364 ).psfCandidates
366 withColorInformation = kwargs.get("withColorInformation", True)
367 if withColorInformation:
368 for psf in psfCandidateList:
369 psf.setPsfColorValue(0.42)
370 psf.setPsfColorType("g-r")
372 # The chromatic fit is only done when it is requested, color
373 # information is available, and the Piff config is not overridden by
374 # a yaml config (which never fits color here).
375 expectedHasColor = (
376 kwargs.get("useColor", False)
377 and withColorInformation
378 and kwargs.get("piffPsfConfigYaml", None) is None
379 )
381 logger = logging.getLogger("lsst.psfDeterminer.Piff")
383 if Version(piff.version) >= Version("1.6"): 383 ↛ 387line 383 didn't jump to line 387 because the condition on line 383 was always true
384 log_level = logging.INFO
385 log_regex = "INFO:.*:Iteration"
386 else:
387 log_level = logging.WARNING
388 log_regex = "WARNING:.*:Iteration"
390 # Both the zeroth-order fallback and the no-color-information
391 # fallback log a warning, so do not forbid warnings in those cases.
392 expectWarning = (
393 kwargs.get("zerothOrderInterpNotEnoughStars", False)
394 or (kwargs.get("useColor", False) and not withColorInformation)
395 )
397 with self.assertLogs("lsst.psfDeterminer.Piff.piff", log_level) as cm:
398 if expectWarning:
399 psf, cellSet = self.psfDeterminer.determinePsf(
400 self.exposure,
401 psfCandidateList,
402 metadata,
403 flagKey=self.usePsfFlag
404 )
405 else:
406 with self.assertNoLogs("lsst.psfDeterminer.Piff", logging.WARNING):
407 psf, cellSet = self.psfDeterminer.determinePsf(
408 self.exposure,
409 psfCandidateList,
410 metadata,
411 flagKey=self.usePsfFlag
412 )
414 # Check that the iterations are being logged.
415 logged = "\n".join(cm.output)
416 self.assertRegex(logged, log_regex)
418 # And check that the levels are set correctly for suppression.
419 logger = logging.getLogger("lsst.psfDeterminer.Piff.piff")
420 if kwargs.get("withlog", False):
421 self.assertEqual(logger.level, logging.WARNING)
422 else:
423 self.assertEqual(logger.level, logging.CRITICAL)
425 self.exposure.setPsf(psf)
427 if kwargs.get("downsample", False):
428 # When downsampling the PSF model is not quite as
429 # good so the chi2 test limit needs to be modified.
430 numAvail = self.psfDeterminer.config.maxCandidates
431 chiLim = 7.0
432 elif kwargs.get("zerothOrderInterpNotEnoughStars", False):
433 numAvail = len(psfCandidateList)
434 chiLim = 20.31
435 else:
436 numAvail = len(psfCandidateList)
437 chiLim = 6.4
439 self.assertEqual(metadata['numAvailStars'], numAvail)
440 self.assertEqual(sum(self.catalog['use_psf']), metadata['numGoodStars'])
441 self.assertLessEqual(metadata['numGoodStars'], metadata['numAvailStars'])
443 # Check that the PSF reports whether the chromatic fit was done.
444 self.assertEqual(psf.hasColor, expectedHasColor)
445 self.assertEqual(metadata['psfHasColor'], expectedHasColor)
446 if expectedHasColor:
447 self.assertEqual(psf.getAverageColor().getColorType(), "g-r")
448 self.assertFalse(psf.getAverageColor().isIndeterminate())
449 else:
450 self.assertTrue(psf.getAverageColor().isIndeterminate())
452 self.assertEqual(
453 psf.getAveragePosition(),
454 geom.Point2D(
455 np.mean([s.x for s in psf._piffResult.stars
456 if not s.is_flagged and not s.is_reserve]),
457 np.mean([s.y for s in psf._piffResult.stars
458 if not s.is_flagged and not s.is_reserve])
459 )
460 )
461 if self.psfDeterminer.config.debugStarData:
462 self.assertIn('image', psf._piffResult.stars[0].data.__dict__)
463 else:
464 self.assertNotIn('image', psf._piffResult.stars[0].data.__dict__)
466 # Test how well we can subtract the PSF model
467 self.subtractStars(self.exposure, self.catalog, chi_lim=chiLim)
469 # Test bboxes
470 for point in [
471 psf.getAveragePosition(),
472 geom.Point2D(),
473 geom.Point2D(1, 1)
474 ]:
475 self.assertEqual(
476 psf.computeBBox(point),
477 psf.computeKernelImage(point).getBBox()
478 )
479 self.assertEqual(
480 psf.computeKernelBBox(point),
481 psf.computeKernelImage(point).getBBox()
482 )
483 self.assertEqual(
484 psf.computeImageBBox(point),
485 psf.computeImage(point).getBBox()
486 )
488 # Some roundtrips
489 with lsst.utils.tests.getTempFilePath(".fits") as tmpFile:
490 self.exposure.writeFits(tmpFile)
491 fitsIm = afwImage.ExposureF(tmpFile)
492 copyIm = copy.deepcopy(self.exposure)
494 for newIm in [fitsIm, copyIm]:
495 # Piff doesn't enable __eq__ for its results, so we just check
496 # that some PSF images come out the same.
497 for point in [
498 geom.Point2D(0, 0),
499 geom.Point2D(10, 100),
500 geom.Point2D(-200, 30),
501 geom.Point2D(float("nan")) # "nullPoint"
502 ]:
503 self.assertImagesAlmostEqual(
504 psf.computeImage(point),
505 newIm.getPsf().computeImage(point)
506 )
507 # Also check average position
508 newPsf = newIm.getPsf()
509 self.assertImagesAlmostEqual(
510 psf.computeImage(psf.getAveragePosition()),
511 newPsf.computeImage(newPsf.getAveragePosition())
512 )
513 # hasColor is derived from the Piff result, so it must
514 # survive persistence and copies.
515 self.assertEqual(newPsf.hasColor, psf.hasColor)
517 def testReadOldPiffVersions(self):
518 """Test we can read psfs serialized with older versions of Piff."""
519 point_names = [
520 (geom.Point2D(0, 0), "psfIm_0_0.fits"),
521 (geom.Point2D(10, 100), "psfIm_10_100.fits"),
522 (geom.Point2D(-200, 30), "psfIm_-200_30.fits"),
523 (geom.Point2D(float("nan")), "psfIm_nan.fits"),
524 ]
526 if False: # Documenting block that created the test data...
527 # Specifically interested in the case where the PSF is created with
528 # piff older than v1.4
529 assert Version(piff.version) < Version("1.4")
531 self.setupDeterminer()
532 stars = self.starSelector.run(self.catalog, exposure=self.exposure)
533 psfCandidateList = self.makePsfCandidates.run(
534 stars.sourceCat,
535 exposure=self.exposure
536 ).psfCandidates
537 psf, _ = self.psfDeterminer.determinePsf(
538 self.exposure,
539 psfCandidateList,
540 )
541 self.exposure.setPsf(psf)
543 path = Path(__file__).parent / "data" / "exp.fits"
544 self.exposure.writeFits(str(path))
545 for point, name in point_names:
546 psfIm = psf.computeImage(point)
547 psfIm.writeFits(str(path.with_name(name)))
549 path = Path(__file__).parent / "data" / "exp.fits"
550 exposure = afwImage.ExposureF(str(path))
551 for point, name in point_names:
552 self.assertImagesAlmostEqual(
553 afwImage.ImageF(str(path.with_name(name))),
554 exposure.getPsf().computeImage(point)
555 )
557 def testPiffDeterminer_default(self):
558 """Test piff with the default config."""
559 self.checkPiffDeterminer()
561 def testPiffDeterminer_stampSize27(self):
562 """Test Piff with a psf stampSize of 27."""
563 self.checkPiffDeterminer(stampSize=27)
564 self.assertEqual(
565 self.exposure.psf.computeKernelImage(self.exposure.getBBox().getCenter()).getDimensions(),
566 geom.Extent2I(27, 27),
567 )
569 def testPiffDeterminer_debugStarData(self):
570 """Test Piff with debugStarData=True."""
571 self.checkPiffDeterminer(debugStarData=True)
573 def testPiffDeterminer_downsample(self):
574 """Test Piff determiner with downsampling."""
575 self.checkPiffDeterminer(downsample=True)
577 def testPiffDeterminer_withlog(self):
578 """Test Piff determiner with chatty logs."""
579 self.checkPiffDeterminer(withlog=True)
581 def testPiffDeterminer_stampSize26(self):
582 """Test Piff with a psf stampSize of 26."""
583 with self.assertRaises(ValueError):
584 self.checkPiffDeterminer(stampSize=26)
586 def testPiffDeterminer_modelSize26(self):
587 """Test Piff with a psf stampSize of 26."""
588 with self.assertRaises(ValueError):
589 self.checkPiffDeterminer(modelSize=26, stampSize=25)
591 def testPiffDeterminer_skyCoords(self):
592 """Test Piff sky coords."""
594 self.checkPiffDeterminer(useCoordinates='sky')
596 @lsst.utils.tests.methodParameters(angle_degrees=[0, 35, 45, 77, 135])
597 def testPiffDeterminer_skyCoords_with_rotation(self, angle_degrees):
598 """Test Piff sky coords with rotation."""
600 wcs = make_wcs(angle_degrees=angle_degrees)
601 self.exposure.setWcs(wcs)
602 self.checkPiffDeterminer(useCoordinates='sky', kernelSize=35)
604 def testPiffDeterminer_skyCoords_failure(self, angle_degrees=135):
605 """Test that using small PSF candidates with sky coordinates fails."""
606 wcs = make_wcs(angle_degrees=angle_degrees)
607 self.exposure.setWcs(wcs)
608 with self.assertRaises(ValueError):
609 self.checkPiffDeterminer(useCoordinates='sky', stampSize=15)
611 def testPiffZerothOrderInterpNotEnoughStars(self):
612 self.checkPiffDeterminer(spatialOrder=4, zerothOrderInterpNotEnoughStars=True)
613 if not self.useYaml:
614 self.assertEqual(self.psfDeterminer._piffConfig['interp']['order'], [0, 0])
615 self.assertEqual(self.psfDeterminer._piffConfig['max_iter'], 1)
616 else:
617 # Yaml will overwrite input value.
618 self.assertEqual(self.psfDeterminer._piffConfig['interp']['order'], 1)
619 self.assertNotIn('max_iter', self.psfDeterminer._piffConfig)
621 def testPiffRaiseErrorNotEnoughStars(self):
622 with self.assertRaises(AlgorithmError):
623 self.checkPiffDeterminer(spatialOrder=42,
624 zerothOrderInterpNotEnoughStars=False,
625 piffPsfConfigYaml=None)
627 def testPiffDummyColorfit(self):
628 self.checkPiffDeterminer(useColor=True,
629 colorOrder=0,
630 piffPsfConfigYaml=None)
631 if not self.useYaml: 631 ↛ exitline 631 didn't return from function 'testPiffDummyColorfit' because the condition on line 631 was always true
632 self.assertTrue(self.exposure.getPsf().hasColor)
633 interp = self.psfDeterminer._piffConfig['interp']
634 self.assertEqual(interp['keys'], ['x', 'y', 'colorValue'])
635 self.assertIn('max_order', interp)
637 def testPiffColorfitNoColorInformation(self):
638 """Test that useColor=True without any color information on the
639 candidates falls back to a non-chromatic fit instead of fitting
640 a color dependence with all colors set to zero.
641 """
642 self.checkPiffDeterminer(useColor=True,
643 colorOrder=0,
644 piffPsfConfigYaml=None,
645 withColorInformation=False)
646 self.assertFalse(self.exposure.getPsf().hasColor)
647 if not self.useYaml: 647 ↛ exitline 647 didn't return from function 'testPiffColorfitNoColorInformation' because the condition on line 647 was always true
648 interp = self.psfDeterminer._piffConfig['interp']
649 self.assertEqual(interp['keys'], ['x', 'y'])
650 self.assertEqual(interp['order'], [1, 1])
651 self.assertNotIn('max_order', interp)
654class piffPsfConfigYamlTestCase(SpatialModelPsfTestCase):
655 """A test case to trigger the codepath that uses piffPsfConfigYaml."""
657 def checkPiffDeterminer(self, **kwargs):
658 # Docstring inherited.
659 if "piffPsfConfigYaml" not in kwargs:
660 piffPsfConfigYaml = """
661 # A minimal Piff config corresponding to the defaults.
662 type: Simple
663 model:
664 type: PixelGrid
665 scale: 0.2
666 size: 25
667 interp: Lanczos(11)
668 interp:
669 type: BasisPolynomial
670 order: 1
671 outliers:
672 type: Chisq
673 nsigma: 4.0
674 max_remove: 0.05
675 """
676 kwargs["piffPsfConfigYaml"] = piffPsfConfigYaml
677 return super().checkPiffDeterminer(**kwargs)
680class PiffConfigTestCase(lsst.utils.tests.TestCase):
681 """A test case to check for valid Piff config"""
682 def testValidateGalsimInterpolant(self):
683 # Check that random strings are not valid interpolants.
684 self.assertFalse(_validateGalsimInterpolant("foo"))
685 # Check that the Lanczos order is an integer
686 self.assertFalse(_validateGalsimInterpolant("Lanczos(3.0"))
687 self.assertFalse(_validateGalsimInterpolant("Lanczos(-5.0"))
688 self.assertFalse(_validateGalsimInterpolant("Lanczos(N)"))
689 # Check for various valid Lanczos interpolants
690 for interp in ("Lanczos(4)", "galsim.Lanczos(7)"):
691 self.assertTrue(_validateGalsimInterpolant(interp))
692 self.assertFalse(_validateGalsimInterpolant(interp.lower()))
693 # Evaluating the string should succeed. This is how Piff does it.
694 self.assertTrue(eval(interp))
695 # Check that interpolation methods are case sensitive.
696 for interp in ("Linear", "Cubic", "Quintic", "Delta", "Nearest", "SincInterpolant"):
697 self.assertFalse(_validateGalsimInterpolant(f"galsim.{interp.lower()}"))
698 self.assertFalse(_validateGalsimInterpolant(interp))
699 self.assertTrue(_validateGalsimInterpolant(f"galsim.{interp}"))
700 self.assertTrue(eval(f"galsim.{interp}"))
703class TestMemory(lsst.utils.tests.MemoryTestCase):
704 pass
707def setup_module(module):
708 lsst.utils.tests.init()
711if __name__ == "__main__": 711 ↛ 712line 711 didn't jump to line 712 because the condition on line 711 was never true
712 lsst.utils.tests.init()
713 unittest.main()