Coverage for python/lsst/meas/extensions/piff/piffPsfDeterminer.py: 85%
246 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-25 22:48 -0800
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-25 22:48 -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/>.
22__all__ = ["PiffPsfDeterminerConfig", "PiffPsfDeterminerTask"]
24import numpy as np
25import piff
26import galsim
27import re
28import logging
29import yaml
31import lsst.utils.logging
32from lsst.afw.cameraGeom import PIXELS, FIELD_ANGLE
33import lsst.pex.config as pexConfig
34import lsst.meas.algorithms as measAlg
35from lsst.meas.algorithms.psfDeterminer import BasePsfDeterminerTask
36from lsst.pipe.base import AlgorithmError
37from .piffPsf import PiffPsf
38from .wcs_wrapper import CelestialWcsWrapper, UVWcsWrapper
41def _validateGalsimInterpolant(name: str) -> bool:
42 """A helper function to validate the GalSim interpolant at config time.
44 Parameters
45 ----------
46 name : str
47 The name of the interpolant to use from GalSim. Valid options are:
48 galsim.Lanczos(N) or Lancsos(N), where N is a positive integer
49 galsim.Linear
50 galsim.Cubic
51 galsim.Quintic
52 galsim.Delta
53 galsim.Nearest
54 galsim.SincInterpolant
56 Returns
57 -------
58 is_valid : bool
59 Whether the provided interpolant name is valid.
60 """
61 # First, check if ``name`` is a valid Lanczos interpolant.
62 for pattern in (re.compile(r"Lanczos\(\d+\)"), re.compile(r"galsim.Lanczos\(\d+\)"),):
63 match = re.match(pattern, name) # Search from the start of the string.
64 if match is not None:
65 # Check that the pattern is also the end of the string.
66 return match.end() == len(name)
68 # If not, check if ``name`` is any other valid GalSim interpolant.
69 names = {f"galsim.{interp}" for interp in
70 ("Cubic", "Delta", "Linear", "Nearest", "Quintic", "SincInterpolant")
71 }
72 return name in names
75class PiffTooFewGoodStarsError(AlgorithmError):
76 """Raised if too few good stars are available for PSF determination.
78 Parameters
79 ----------
80 num_good_stars : `int`
81 Number of good stars used for PSF determination.
82 poly_ndim : `int`
83 Number of dependency parameters (dimensions) used in
84 polynomial fitting.
85 minimum_dof : `int`
86 Minimum number of degree of freedom to do the fit.
87 """
89 def __init__(
90 self,
91 num_good_stars,
92 minimum_dof,
93 poly_ndim,
94 ):
95 self._num_good_stars = num_good_stars
96 self._poly_ndim = poly_ndim
97 self._minimum_dof = minimum_dof
98 super().__init__(
99 f"Failed to determine piff psf: too few good stars ({num_good_stars}) and minimum dof to fit "
100 f"a {poly_ndim} order polynomial is {minimum_dof}."
101 )
103 @property
104 def metadata(self):
105 return {
106 "num_good_stars": self._num_good_stars,
107 "poly_ndim": self._poly_ndim,
108 "minimum_dof": self._minimum_dof,
109 }
112class PiffPsfDeterminerConfig(BasePsfDeterminerTask.ConfigClass):
113 spatialOrderPerBand = pexConfig.DictField(
114 doc="Per-band spatial order for PSF kernel creation. "
115 "Ignored if piffPsfConfigYaml is set.",
116 keytype=str,
117 itemtype=int,
118 default={},
119 )
120 spatialOrder = pexConfig.Field[int](
121 doc="Spatial order for PSF kernel creation. "
122 "Ignored if piffPsfConfigYaml is set or if the current "
123 "band is in the spatialOrderPerBand dict config.",
124 default=2,
125 )
126 piffBasisPolynomialSolver = pexConfig.ChoiceField[str](
127 doc="Solver to solve linear algebra for "
128 "the spatial interpolation of the PSF. "
129 "Ignore if piffPsfConfigYaml is not None.",
130 allowed=dict(
131 scipy="Default solver using scipy.",
132 cpp="C++ solver using eigen.",
133 jax="JAX solver.",
134 qr="QR decomposition using scipy/numpy.",
135 ),
136 default="scipy",
137 )
138 piffPixelGridFitCenter = pexConfig.Field[bool](
139 doc="PixelGrid can re-estimate center if this option is True. "
140 "Will use provided centroid if set to False. Default in Piff "
141 "is set to True. Depends on how input centroids can be trust. "
142 "Ignore if piffPsfConfigYaml is not None.",
143 default=True
144 )
145 samplingSize = pexConfig.Field[float](
146 doc="Resolution of the internal PSF model relative to the pixel size; "
147 "e.g. 0.5 is equal to 2x oversampling. This affects only the size of "
148 "the PSF model stamp if piffPsfConfigYaml is set.",
149 default=1,
150 )
151 modelSize = pexConfig.Field[int](
152 doc="Internal model size for PIFF (typically odd, but not enforced). "
153 "Partially ignored if piffPsfConfigYaml is set.",
154 default=25,
155 )
156 outlierNSigma = pexConfig.Field[float](
157 doc="n sigma for chisq outlier rejection. "
158 "Ignored if piffPsfConfigYaml is set.",
159 default=4.0
160 )
161 outlierMaxRemove = pexConfig.Field[float](
162 doc="Max fraction of stars to remove as outliers each iteration. "
163 "Ignored if piffPsfConfigYaml is set.",
164 default=0.05
165 )
166 maxSNR = pexConfig.Field[float](
167 doc="Rescale the weight of bright stars such that their SNR is less "
168 "than this value.",
169 default=200.0
170 )
171 zeroWeightMaskBits = pexConfig.ListField[str](
172 doc="List of mask bits for which to set pixel weights to zero.",
173 default=['BAD', 'CR', 'INTRP', 'SAT', 'SUSPECT', 'NO_DATA']
174 )
175 minimumUnmaskedFraction = pexConfig.Field[float](
176 doc="Minimum fraction of unmasked pixels required to use star.",
177 default=0.5
178 )
179 useColor = pexConfig.Field[bool](
180 doc="Use color information to correct for amtospheric turbulences and "
181 "differential chromatic refraction. If no PSF candidate carries a "
182 "finite color, color is not fitted and a purely spatial PSF model "
183 "is produced (see ``PiffPsf.hasColor``). "
184 "Ignored if piffPsfConfigYaml is set.",
185 default=False,
186 )
187 color = pexConfig.DictField(
188 doc="The bands to use for calculating color."
189 "Ignored if piffPsfConfigYaml is set.",
190 default={},
191 keytype=str,
192 itemtype=str,
193 )
194 colorOrder = pexConfig.Field[int](
195 doc="Color order for PSF kernel creation. Only pure color terms are "
196 "fitted; cross terms between color and spatial coordinates are "
197 "not included. Ignored if piffPsfConfigYaml is set.",
198 default=1,
199 )
200 interpolant = pexConfig.Field[str](
201 doc="GalSim interpolant name for Piff to use. "
202 "Options include 'Lanczos(N)', where N is an integer, along with "
203 "galsim.Cubic, galsim.Delta, galsim.Linear, galsim.Nearest, "
204 "galsim.Quintic, and galsim.SincInterpolant. Ignored if "
205 "piffPsfConfigYaml is set.",
206 check=_validateGalsimInterpolant,
207 default="Lanczos(11)",
208 )
209 zerothOrderInterpNotEnoughStars = pexConfig.Field[bool](
210 doc="If True, use zeroth order interpolation if not enough stars are found.",
211 default=False
212 )
213 debugStarData = pexConfig.Field[bool](
214 doc="Include star images used for fitting in PSF model object.",
215 default=False
216 )
217 useCoordinates = pexConfig.ChoiceField[str](
218 doc="Which spatial coordinates to regress against in PSF modeling.",
219 allowed=dict(
220 pixel='Regress against pixel coordinates',
221 field='Regress against field angles',
222 sky='Regress against RA/Dec'
223 ),
224 default='pixel'
225 )
226 piffMaxIter = pexConfig.Field[int](
227 doc="Maximum iteration while doing outlier rejection."
228 "Might be overwrite if zerothOrderInterpNotEnoughStars is True and "
229 "ignore if piffPsfConfigYaml is not None.",
230 default=15
231 )
232 piffLoggingLevel = pexConfig.RangeField[int](
233 doc="PIFF-specific logging level, from 0 (least chatty) to 3 (very verbose); "
234 "note that logs will come out with unrelated notations (e.g. WARNING does "
235 "not imply a warning.)",
236 default=0,
237 min=0,
238 max=3,
239 )
240 piffPsfConfigYaml = pexConfig.Field[str](
241 doc="Configuration file for PIFF in YAML format. This overrides many "
242 "other settings in this config and is not validated ahead of runtime.",
243 default=None,
244 optional=True,
245 )
247 def setDefaults(self):
248 super().setDefaults()
249 # stampSize should be at least 25 so that
250 # i) aperture flux with 12 pixel radius can be compared to PSF flux.
251 # ii) fake sources injected to match the 12 pixel aperture flux get
252 # measured correctly
253 # stampSize should also be at least sqrt(2)*modelSize/samplingSize so
254 # that rotated images have support in the model
256 self.stampSize = 27
257 # Resize the stamp to accommodate the model, but only if necessary.
258 if self.useCoordinates == "sky": 258 ↛ 259line 258 didn't jump to line 259 because the condition on line 258 was never true
259 self.stampSize = max(25, 2*int(0.5*self.modelSize*np.sqrt(2)/self.samplingSize) + 1)
261 def validate(self):
262 super().validate()
264 if (stamp_size := self.stampSize) is not None:
265 model_size = self.modelSize
266 sampling_size = self.samplingSize
267 if self.useCoordinates == 'sky':
268 min_stamp_size = int(np.sqrt(2) * model_size / sampling_size)
269 else:
270 min_stamp_size = int(model_size / sampling_size)
272 if stamp_size < min_stamp_size:
273 msg = (f"PIFF model size of {model_size} is too large for stamp size {stamp_size}. "
274 f"Set stampSize >= {min_stamp_size}"
275 )
276 raise pexConfig.FieldValidationError(self.__class__.modelSize, self, msg)
279def getGoodPixels(maskedImage, zeroWeightMaskBits):
280 """Compute an index array indicating good pixels to use.
282 Parameters
283 ----------
284 maskedImage : `afw.image.MaskedImage`
285 PSF candidate postage stamp
286 zeroWeightMaskBits : `List[str]`
287 List of mask bits for which to set pixel weights to zero.
289 Returns
290 -------
291 good : `ndarray`
292 Index array indicating good pixels.
293 """
294 imArr = maskedImage.image.array
295 varArr = maskedImage.variance.array
296 bitmask = maskedImage.mask.getPlaneBitMask(zeroWeightMaskBits)
297 good = (
298 (varArr != 0)
299 & (np.isfinite(varArr))
300 & (np.isfinite(imArr))
301 & ((maskedImage.mask.array & bitmask) == 0)
302 )
303 return good
306def computeWeight(maskedImage, maxSNR, good):
307 """Derive a weight map without Poisson variance component due to signal.
309 Parameters
310 ----------
311 maskedImage : `afw.image.MaskedImage`
312 PSF candidate postage stamp
313 maxSNR : `float`
314 Maximum SNR applying variance floor.
315 good : `ndarray`
316 Index array indicating good pixels.
318 Returns
319 -------
320 weightArr : `ndarry`
321 Array to use for weight.
323 See Also
324 --------
325 `lsst.meas.algorithms.variance_plance.remove_signal_from_variance` :
326 Remove the Poisson contribution from sources in the variance plane of
327 an Exposure.
328 """
329 imArr = maskedImage.image.array
330 varArr = maskedImage.variance.array
332 # Fit a straight line to variance vs (sky-subtracted) signal.
333 # The evaluate that line at zero signal to get an estimate of the
334 # signal-free variance.
335 fit = np.polyfit(imArr[good], varArr[good], deg=1)
336 # fit is [1/gain, sky_var]
337 weightArr = np.zeros_like(imArr, dtype=float)
338 weightArr[good] = 1./fit[1]
340 applyMaxSNR(imArr, weightArr, good, maxSNR)
341 return weightArr
344def applyMaxSNR(imArr, weightArr, good, maxSNR):
345 """Rescale weight of bright stars to cap the computed SNR.
347 Parameters
348 ----------
349 imArr : `ndarray`
350 Signal (image) array of stamp.
351 weightArr : `ndarray`
352 Weight map array. May be rescaled in place.
353 good : `ndarray`
354 Index array of pixels to use when computing SNR.
355 maxSNR : `float`
356 Threshold for adjusting variance plane implementing maximum SNR.
357 """
358 # We define the SNR value following Piff. Here's the comment from that
359 # code base explaining the calculation.
360 #
361 # The S/N value that we use will be the weighted total flux where the
362 # weight function is the star's profile itself. This is the maximum S/N
363 # value that any flux measurement can possibly produce, which will be
364 # closer to an in-practice S/N than using all the pixels equally.
365 #
366 # F = Sum_i w_i I_i^2
367 # var(F) = Sum_i w_i^2 I_i^2 var(I_i)
368 # = Sum_i w_i I_i^2 <--- Assumes var(I_i) = 1/w_i
369 #
370 # S/N = F / sqrt(var(F))
371 #
372 # Note that if the image is pure noise, this will produce a "signal" of
373 #
374 # F_noise = Sum_i w_i 1/w_i = Npix
375 #
376 # So for a more accurate estimate of the S/N of the actual star itself, one
377 # should subtract off Npix from the measured F.
378 #
379 # The final formula then is:
380 #
381 # F = Sum_i w_i I_i^2
382 # S/N = (F-Npix) / sqrt(F)
383 F = np.sum(weightArr[good]*imArr[good]**2, dtype=float)
384 Npix = np.sum(good)
385 SNR = 0.0 if F < Npix else (F-Npix)/np.sqrt(F)
386 # rescale weight of bright stars. Essentially makes an error floor.
387 if SNR > maxSNR: 387 ↛ exitline 387 didn't return from function 'applyMaxSNR' because the condition on line 387 was always true
388 factor = (maxSNR / SNR)**2
389 weightArr[good] *= factor
392def _computeWeightAlternative(maskedImage, maxSNR):
393 """Alternative algorithm for creating weight map.
395 This version is equivalent to that used by Piff internally. The weight map
396 it produces tends to leave a residual when removing the Poisson component
397 due to the signal. We leave it here as a reference, but without intending
398 that it be used (or be maintained).
399 """
400 imArr = maskedImage.image.array
401 varArr = maskedImage.variance.array
402 good = (varArr != 0) & np.isfinite(varArr) & np.isfinite(imArr)
404 fit = np.polyfit(imArr[good], varArr[good], deg=1)
405 # fit is [1/gain, sky_var]
406 gain = 1./fit[0]
407 varArr[good] -= imArr[good] / gain
408 weightArr = np.zeros_like(imArr, dtype=float)
409 weightArr[good] = 1./varArr[good]
411 applyMaxSNR(imArr, weightArr, good, maxSNR)
412 return weightArr
415class PiffPsfDeterminerTask(BasePsfDeterminerTask):
416 """A measurePsfTask PSF estimator using Piff as the implementation.
417 """
418 ConfigClass = PiffPsfDeterminerConfig
419 _DefaultName = "psfDeterminer.Piff"
421 def __init__(self, config, schema=None, **kwds):
422 BasePsfDeterminerTask.__init__(self, config, schema=schema, **kwds)
424 piffLoggingLevels = {
425 0: logging.CRITICAL,
426 1: logging.WARNING,
427 2: logging.INFO,
428 3: logging.DEBUG,
429 }
430 self.piffLogger = lsst.utils.logging.getLogger(f"{self.log.name}.piff")
431 self.piffLogger.setLevel(piffLoggingLevels[self.config.piffLoggingLevel])
433 def determinePsf(
434 self, exposure, psfCandidateList, metadata=None, flagKey=None,
435 ):
436 """Determine a Piff PSF model for an exposure given a list of PSF
437 candidates.
439 Parameters
440 ----------
441 exposure : `lsst.afw.image.Exposure`
442 Exposure containing the PSF candidates.
443 psfCandidateList : `list` of `lsst.meas.algorithms.PsfCandidate`
444 A sequence of PSF candidates typically obtained by detecting sources
445 and then running them through a star selector.
446 metadata : `lsst.daf.base import PropertyList` or `None`, optional
447 A home for interesting tidbits of information.
448 flagKey : `str` or `None`, optional
449 Schema key used to mark sources actually used in PSF determination.
451 Returns
452 -------
453 psf : `lsst.meas.extensions.piff.PiffPsf`
454 The measured PSF model.
455 psfCellSet : `None`
456 Unused by this PsfDeterminer.
457 """
458 psfCandidateList = self.downsampleCandidates(psfCandidateList)
460 if self.config.stampSize:
461 stampSize = self.config.stampSize
462 if stampSize > psfCandidateList[0].getWidth(): 462 ↛ 463line 462 didn't jump to line 463 because the condition on line 462 was never true
463 self.log.warning("stampSize is larger than the PSF candidate size. Using candidate size.")
464 stampSize = psfCandidateList[0].getWidth()
465 else: # TODO: Only the if block should stay after DM-36311
466 self.log.debug("stampSize not set. Using candidate size.")
467 stampSize = psfCandidateList[0].getWidth()
469 scale = exposure.getWcs().getPixelScale(exposure.getBBox().getCenter()).asArcseconds()
471 match self.config.useCoordinates:
472 case 'field': 472 ↛ 473line 472 didn't jump to line 473 because the pattern on line 472 never matched
473 detector = exposure.getDetector()
474 pix_to_field = detector.getTransform(PIXELS, FIELD_ANGLE)
475 gswcs = UVWcsWrapper(pix_to_field)
476 pointing = None
477 keys = ['u', 'v']
479 case 'sky':
480 gswcs = CelestialWcsWrapper(exposure.getWcs())
481 skyOrigin = exposure.getWcs().getSkyOrigin()
482 ra = skyOrigin.getLongitude().asDegrees()
483 dec = skyOrigin.getLatitude().asDegrees()
484 pointing = galsim.CelestialCoord(
485 ra*galsim.degrees,
486 dec*galsim.degrees
487 )
488 keys = ['u', 'v']
490 case 'pixel': 490 ↛ 495line 490 didn't jump to line 495 because the pattern on line 490 always matched
491 gswcs = galsim.PixelScale(scale)
492 pointing = None
493 keys = ['x', 'y']
495 stars = []
496 for candidate in psfCandidateList:
497 cmi = candidate.getMaskedImage(stampSize, stampSize)
498 good = getGoodPixels(cmi, self.config.zeroWeightMaskBits)
499 fracGood = np.sum(good)/good.size
500 if fracGood < self.config.minimumUnmaskedFraction: 500 ↛ 501line 500 didn't jump to line 501 because the condition on line 500 was never true
501 continue
502 weight = computeWeight(cmi, self.config.maxSNR, good)
504 bbox = cmi.getBBox()
505 bds = galsim.BoundsI(
506 galsim.PositionI(*bbox.getMin()),
507 galsim.PositionI(*bbox.getMax())
508 )
509 gsImage = galsim.Image(bds, wcs=gswcs, dtype=float)
510 gsImage.array[:] = cmi.image.array
511 gsWeight = galsim.Image(bds, wcs=gswcs, dtype=float)
512 gsWeight.array[:] = weight
514 source = candidate.getSource()
515 starId = source.getId()
516 image_pos = galsim.PositionD(source.getX(), source.getY())
518 data = piff.StarData(
519 gsImage,
520 image_pos,
521 weight=gsWeight,
522 pointing=pointing
523 )
524 star = piff.Star(data, None)
525 star.data.properties['starId'] = starId
526 star.data.properties['colorValue'] = candidate.getPsfColorValue()
527 star.data.properties['colorType'] = candidate.getPsfColorType()
528 stars.append(star)
530 # The following is mostly accommodating unittests that don't have
531 # the filter attribute set on the mock exposure.
532 if hasattr(exposure.filter, "bandLabel"): 532 ↛ 533line 532 didn't jump to line 533 because the condition on line 532 was never true
533 band = exposure.filter.bandLabel
534 else:
535 band = None
536 spatialOrder = self.config.spatialOrderPerBand.get(band, self.config.spatialOrder)
537 orders = [spatialOrder] * len(keys)
539 # Whether the chromatic fit is actually done. It requires useColor
540 # and at least one PSF candidate with a finite color.
541 fitColor = False
542 if self.config.useColor:
543 colors = [s.data.properties['colorValue'] for s in stars
544 if np.isfinite(s.data.properties['colorValue'])]
545 colorTypes = [s.data.properties['colorType'] for s in stars
546 if np.isfinite(s.data.properties['colorValue'])]
547 if len(colors) == 0:
548 self.log.warning(
549 "useColor is True but no PSF candidate has color information; "
550 "fitting a non-chromatic PSF (no color dependence)."
551 )
552 else:
553 fitColor = True
554 meanColors = np.mean(colors)
555 colorType = list(set(colorTypes))
556 if len(colorType) > 1: 556 ↛ 557line 556 didn't jump to line 557 because the condition on line 556 was never true
557 raise ValueError(f"More than one colorType was provided:{colorType}")
558 colorType = colorType[0]
559 for s in stars:
560 if not np.isfinite(s.data.properties['colorValue']): 560 ↛ 561line 560 didn't jump to line 561 because the condition on line 560 was never true
561 s.data.properties['colorValue'] = meanColors
562 s.data.properties['colorType'] = colorType
563 keys.append('colorValue')
564 orders.append(self.config.colorOrder)
566 if self.config.piffPsfConfigYaml is None:
567 piffConfig = {
568 'type': 'Simple',
569 'model': {
570 'type': 'PixelGrid',
571 'scale': scale * self.config.samplingSize,
572 'size': self.config.modelSize,
573 'interp': self.config.interpolant,
574 'centered': self.config.piffPixelGridFitCenter,
575 },
576 'interp': {
577 'type': 'BasisPolynomial',
578 'order': orders,
579 'keys': keys,
580 'solver': self.config.piffBasisPolynomialSolver,
581 },
582 'outliers': {
583 'type': 'Chisq',
584 'nsigma': self.config.outlierNSigma,
585 'max_remove': self.config.outlierMaxRemove,
586 },
587 'max_iter': self.config.piffMaxIter
588 }
589 if fitColor:
590 # Cross terms between the two spatial coordinates are kept up
591 # to spatialOrder. Cross terms between color and the spatial
592 # coordinates are set to zero, i.e. only pure color terms up
593 # to colorOrder are fitted, so the basis is e.g.
594 # [1, c, y, y^2, x, x*y, x^2] for spatialOrder=2, colorOrder=1.
595 #
596 # In Piff's BasisPolynomial, a pair of keys omitted from the
597 # max_order dict gets no cross terms. The color/spatial pairs
598 # must be omitted rather than listed with an explicit 0:
599 # Piff <= 1.7 indexes dict pairs within the pair tuple instead
600 # of within `keys`, so an explicit ('x', 'colorValue'): 0
601 # entry would also remove the x*y term.
602 spatialKeys = (keys[0], keys[1])
603 piffConfig['interp']['max_order'] = {spatialKeys: spatialOrder}
604 else:
605 piffConfig = yaml.safe_load(self.config.piffPsfConfigYaml)
607 def _get_threshold(nth_order):
608 if isinstance(nth_order, list):
609 # right now, nth_order[0] and nth_order[1] are the same.
610 freeParameters = ((nth_order[0] + 1) * (nth_order[0] + 2)) // 2
611 if len(nth_order) == 3: # when color correction
612 freeParameters += nth_order[2]
613 else:
614 # number of free parameter in the polynomial interpolation
615 freeParameters = ((nth_order + 1) * (nth_order + 2)) // 2
616 return freeParameters
618 if piffConfig['interp']['type'] in ['BasisPolynomial', 'Polynomial']: 618 ↛ 636line 618 didn't jump to line 636 because the condition on line 618 was always true
619 threshold = _get_threshold(piffConfig['interp']['order'])
620 if len(stars) < threshold:
621 if self.config.zerothOrderInterpNotEnoughStars:
622 self.log.warning(
623 "Only %d stars found, "
624 "but %d required. Using zeroth order interpolation."%((len(stars), threshold))
625 )
626 piffConfig['interp']['order'] = [0] * len(keys)
627 # No need to do any outlier rejection assume
628 # PSF to be average of few stars.
629 piffConfig['max_iter'] = 1
630 else:
631 raise PiffTooFewGoodStarsError(
632 num_good_stars=len(stars),
633 minimum_dof=threshold,
634 poly_ndim=piffConfig['interp']['order'],
635 )
636 self._piffConfig = piffConfig
637 piffResult = piff.PSF.process(piffConfig)
638 wcs = {0: gswcs}
640 piffResult.fit(stars, wcs, pointing, logger=self.piffLogger)
642 nUsedStars = len([s for s in piffResult.stars if not s.is_flagged and not s.is_reserve])
644 if piffConfig['interp']['type'] in ['BasisPolynomial', 'Polynomial']: 644 ↛ 665line 644 didn't jump to line 665 because the condition on line 644 was always true
645 threshold = _get_threshold(piffConfig['interp']['order'])
646 if nUsedStars < threshold: 646 ↛ 647line 646 didn't jump to line 647 because the condition on line 646 was never true
647 if self.config.zerothOrderInterpNotEnoughStars:
648 self.log.warning(
649 "Only %d after outlier rejection, "
650 "but %d required. Using zeroth order interpolation."%((nUsedStars, threshold))
651 )
652 piffConfig['interp']['order'] = [0] * len(keys)
653 # No need to do any outlier rejection assume
654 # PSF to be average of few stars.
655 piffConfig['max_iter'] = 1
656 piffResult.fit(stars, wcs, pointing, logger=self.piffLogger)
657 nUsedStars = len(stars)
658 else:
659 raise PiffTooFewGoodStarsError(
660 num_good_stars=nUsedStars,
661 minimum_dof=threshold,
662 poly_ndim=piffConfig['interp']['order'],
663 )
665 drawSize = 2*np.floor(0.5*stampSize/self.config.samplingSize) + 1
667 used_image_starId = {s.data.properties['starId'] for s in piffResult.stars
668 if not s.is_flagged and not s.is_reserve}
670 assert len(used_image_starId) == nUsedStars, "Star IDs are not unique"
672 if flagKey: 672 ↛ 679line 672 didn't jump to line 679 because the condition on line 672 was always true
673 for candidate in psfCandidateList:
674 source = candidate.getSource()
675 starId = source.getId()
676 if starId in used_image_starId: 676 ↛ 673line 676 didn't jump to line 673 because the condition on line 676 was always true
677 source.set(flagKey, True)
679 if metadata is not None: 679 ↛ 689line 679 didn't jump to line 689 because the condition on line 679 was always true
680 metadata["spatialFitChi2"] = piffResult.chisq
681 metadata["numAvailStars"] = len(stars)
682 metadata["numGoodStars"] = nUsedStars
683 metadata["psfHasColor"] = fitColor
684 metadata["avgX"] = np.mean([s.x for s in piffResult.stars
685 if not s.is_flagged and not s.is_reserve])
686 metadata["avgY"] = np.mean([s.y for s in piffResult.stars
687 if not s.is_flagged and not s.is_reserve])
689 if not self.config.debugStarData:
690 for star in piffResult.stars:
691 # Remove large data objects from the stars
692 del star.fit.params
693 del star.fit.params_var
694 del star.fit.A
695 del star.fit.b
696 del star.data.image
697 del star.data.weight
698 del star.data.orig_weight
700 return PiffPsf(drawSize, drawSize, piffResult), None
703measAlg.psfDeterminerRegistry.register("piff", PiffPsfDeterminerTask)