208 def determinePsf(self, exposure, psfCandidateList, metadata=None, flagKey=None):
209 """Determine a PSFEX PSF model for an exposure given a list of PSF
214 exposure: `lsst.afw.image.Exposure`
215 Exposure containing the PSF candidates.
216 psfCandidateList: iterable of `lsst.meas.algorithms.PsfCandidate`
217 Sequence of PSF candidates typically obtained by detecting sources
218 and then running them through a star selector.
219 metadata: metadata, optional
220 A home for interesting tidbits of information.
221 flagKey: `lsst.afw.table.Key`, optional
222 Schema key used to mark sources actually used in PSF determination.
226 psf: `lsst.meas.extensions.psfex.PsfexPsf`
229 psfCandidateList = self.downsampleCandidates(psfCandidateList)
233 displayExposure = display
and \
235 displayPsfComponents = display
and \
237 showBadCandidates = display
and \
239 displayResiduals = display
and \
241 displayPsfMosaic = display
and \
244 afwDisplay.setDefaultMaskTransparency(75)
247 mi = exposure.getMaskedImage()
249 nCand = len(psfCandidateList)
257 bbox = mi.getBBox(afwImage.PARENT)
262 sizes = np.empty(nCand)
263 for i, psfCandidate
in enumerate(psfCandidateList):
266 psfCellSet.insertCandidate(psfCandidate)
267 except Exception
as e:
268 self.log.error(
"Skipping PSF candidate %d of %d: %s", i, len(psfCandidateList), e)
271 source = psfCandidate.getSource()
272 quad = afwEll.Quadrupole(source.getIxx(), source.getIyy(), source.getIxy())
273 rmsSize = quad.getTraceRadius()
276 pixKernelSize = self.config.stampSize
277 actualKernelSize = int(2*np.floor(0.5*pixKernelSize/self.config.samplingSize) + 1)
280 rms = np.median(sizes)
281 self.log.debug(
"Median PSF RMS size=%.2f pixels (\"FWHM\"=%.2f)",
282 rms, 2*np.sqrt(2*np.log(2))*rms)
284 self.log.trace(
"Psfex Kernel size=%.2f, Image Kernel Size=%.2f", actualKernelSize, pixKernelSize)
290 defaultsFile = os.path.join(os.environ[
"MEAS_EXTENSIONS_PSFEX_DIR"],
"config",
"default-lsst.psfex")
292 args_md.set(
"BASIS_TYPE", str(self.config.psfexBasis))
293 args_md.set(
"PSFVAR_DEGREES", str(self.config.spatialOrder))
294 args_md.set(
"PSF_SIZE", str(actualKernelSize))
295 args_md.set(
"PSF_SAMPLING", str(self.config.samplingSize))
296 args_md.set(
"PHOTFLUX_KEY", str(self.config.photometricFluxField))
297 args_md.set(
"PHOTFLUXERR_KEY", str(self.config.photometricFluxField) +
"Err")
298 prefs = psfex.Prefs(defaultsFile, args_md)
299 prefs.setCommandLine([])
300 prefs.addCatalog(
"psfexPsfDeterminer")
303 principalComponentExclusionFlag = bool(bool(psfex.Context.REMOVEHIDDEN)
304 if False else psfex.Context.KEEPHIDDEN)
305 context = psfex.Context(prefs.getContextName(), prefs.getContextGroup(),
306 prefs.getGroupDeg(), principalComponentExclusionFlag)
307 psfSet = psfex.Set(context)
308 psfSet.setVigSize(pixKernelSize, pixKernelSize)
309 psfSet.setFwhm(2*np.sqrt(2*np.log(2))*np.median(sizes))
310 psfSet.setRecentroid(self.config.recentroid)
314 ccd = exposure.getDetector()
316 gain = np.mean(np.array([a.getGain()
for a
in ccd]))
319 self.log.warning(
"Setting gain to %g", gain)
322 for i, key
in enumerate(context.getName()):
325 contextvalp.append(exposure.getMetadata().getScalar(key[1:]))
326 except KeyError
as e:
327 raise RuntimeError(
"%s parameter not found in the header of %s" %
328 (key[1:], prefs.getContextName()))
from e
331 contextvalp.append(np.array([psfCandidateList[_].getSource().get(key)
332 for _
in range(nCand)]))
333 except KeyError
as e:
334 raise RuntimeError(
"%s parameter not found" % (key,))
from e
335 psfSet.setContextname(i, key)
340 disp = afwDisplay.Display(frame=frame)
341 disp.mtv(exposure, title=
"psf determination")
343 badBits = mi.getMask().getPlaneBitMask(self.config.badMaskBits)
344 fluxName = prefs.getPhotfluxRkey()
345 fluxFlagName = fluxName.rpartition(
"_")[0] +
"_flag"
348 for i, psfCandidate
in enumerate(psfCandidateList):
349 source = psfCandidate.getSource()
352 xc, yc = source.getX(), source.getY()
353 if not np.isfinite(xc)
or not np.isfinite(yc):
356 if source.get(fluxFlagName):
359 flux = source.get(fluxName)
360 if flux < 0
or not np.isfinite(flux):
364 pstamp = psfCandidate.getMaskedImage(pixKernelSize, pixKernelSize).clone()
365 except pexExcept.LengthError:
366 self.log.warning(
"Could not get stamp image for psfCandidate: %s with kernel size: %s",
367 psfCandidate, pixKernelSize)
375 sample = psfSet.newSample()
376 sample.setCatindex(catindex)
377 sample.setExtindex(ext)
378 sample.setObjindex(i)
380 imArray = pstamp.getImage().getArray()
381 imArray[np.where(np.bitwise_and(pstamp.getMask().getArray(), badBits))] = \
383 sample.setVig(imArray)
386 sample.setBacknoise2(backnoise2)
390 sample.setFluxrad(sizes[i])
392 for j
in range(psfSet.getNcontext()):
393 sample.setContext(j, float(contextvalp[j][i]))
394 except Exception
as e:
395 self.log.error(
"Exception when processing sample at (%f,%f): %s", xc, yc, e)
398 psfSet.finiSample(sample)
404 with disp.Buffering():
405 disp.dot(
"o", xc, yc, ctype=afwDisplay.CYAN, size=4)
407 if psfSet.getNsample() == 0:
411 for i
in range(psfSet.getNcontext()):
412 cmin = contextvalp[i].min()
413 cmax = contextvalp[i].max()
414 psfSet.setContextScale(i, cmax - cmin)
415 psfSet.setContextOffset(i, (cmin + cmax)/2.0)
425 field = psfex.Field(
"Unknown")
426 field.addExt(exposure.getWcs(), exposure.getWidth(), exposure.getHeight(), psfSet.getNsample())
434 psfex.makeit(fields, sets)
435 psfs = field.getPsfs()
439 for i
in range(sets[0].getNsample()):
440 index = sets[0].getSample(i).getObjindex()
442 good_indices.append(index)
444 if flagKey
is not None:
445 for i, psfCandidate
in enumerate(psfCandidateList):
446 source = psfCandidate.getSource()
447 if i
in good_indices:
448 source.set(flagKey,
True)
450 xpos = np.array(xpos)
451 ypos = np.array(ypos)
452 numGoodStars = len(good_indices)
453 avgX, avgY = np.mean(xpos), np.mean(ypos)
461 if (ndim := psf.getNdim()) == 0:
463 num_available_stars=nCand,
464 num_good_stars=numGoodStars,
465 poly_ndim_initial=psfSet.getNcontext(),
466 poly_ndim_final=ndim,
473 assert psfCellSet
is not None
476 maUtils.showPsfSpatialCells(exposure, psfCellSet, showChi2=
True,
477 symb=
"o", ctype=afwDisplay.YELLOW, ctypeBad=afwDisplay.RED,
478 size=8, display=disp)
480 disp4 = afwDisplay.Display(frame=4)
481 maUtils.showPsfCandidates(exposure, psfCellSet, psf=psf, display=disp4,
482 normalize=normalizeResiduals,
483 showBadCandidates=showBadCandidates)
484 if displayPsfComponents:
485 disp6 = afwDisplay.Display(frame=6)
486 maUtils.showPsf(psf, display=disp6)
488 disp7 = afwDisplay.Display(frame=7)
489 maUtils.showPsfMosaic(exposure, psf, display=disp7, showFwhm=
True)
490 disp.scale(
'linear', 0, 1)
496 if metadata
is not None:
497 metadata[
"spatialFitChi2"] = np.nan
498 metadata[
"numAvailStars"] = nCand
499 metadata[
"numGoodStars"] = numGoodStars
500 metadata[
"avgX"] = avgX
501 metadata[
"avgY"] = avgY
503 return psf, psfCellSet