213 def determinePsf(self, exposure, psfCandidateList, metadata=None, flagKey=None):
214 """Determine a PSFEX PSF model for an exposure given a list of PSF
219 exposure: `lsst.afw.image.Exposure`
220 Exposure containing the PSF candidates.
221 psfCandidateList: iterable of `lsst.meas.algorithms.PsfCandidate`
222 Sequence of PSF candidates typically obtained by detecting sources
223 and then running them through a star selector.
224 metadata: metadata, optional
225 A home for interesting tidbits of information.
226 flagKey: `lsst.afw.table.Key`, optional
227 Schema key used to mark sources actually used in PSF determination.
231 psf: `lsst.meas.extensions.psfex.PsfexPsf`
234 psfCandidateList = self.downsampleCandidates(psfCandidateList)
238 displayExposure = display
and \
240 displayPsfComponents = display
and \
242 showBadCandidates = display
and \
244 displayResiduals = display
and \
246 displayPsfMosaic = display
and \
249 afwDisplay.setDefaultMaskTransparency(75)
252 mi = exposure.getMaskedImage()
254 nCand = len(psfCandidateList)
262 bbox = mi.getBBox(afwImage.PARENT)
267 sizes = np.empty(nCand)
268 for i, psfCandidate
in enumerate(psfCandidateList):
271 psfCellSet.insertCandidate(psfCandidate)
272 except Exception
as e:
273 self.log.error(
"Skipping PSF candidate %d of %d: %s", i, len(psfCandidateList), e)
276 source = psfCandidate.getSource()
277 quad = afwEll.Quadrupole(source.getIxx(), source.getIyy(), source.getIxy())
278 rmsSize = quad.getTraceRadius()
281 pixKernelSize = self.config.stampSize
282 actualKernelSize = int(2*np.floor(0.5*pixKernelSize/self.config.samplingSize) + 1)
285 rms = np.median(sizes)
286 self.log.debug(
"Median PSF RMS size=%.2f pixels (\"FWHM\"=%.2f)",
287 rms, 2*np.sqrt(2*np.log(2))*rms)
289 self.log.trace(
"Psfex Kernel size=%.2f, Image Kernel Size=%.2f", actualKernelSize, pixKernelSize)
295 defaultsFile = os.path.join(os.environ[
"MEAS_EXTENSIONS_PSFEX_DIR"],
"config",
"default-lsst.psfex")
297 args_md.set(
"BASIS_TYPE", str(self.config.psfexBasis))
298 args_md.set(
"PSFVAR_DEGREES", str(self.config.spatialOrder))
299 args_md.set(
"PSF_SIZE", str(actualKernelSize))
300 args_md.set(
"PSF_SAMPLING", str(self.config.samplingSize))
301 args_md.set(
"PHOTFLUX_KEY", str(self.config.photometricFluxField))
302 args_md.set(
"PHOTFLUXERR_KEY", str(self.config.photometricFluxField) +
"Err")
303 prefs = psfex.Prefs(defaultsFile, args_md)
304 prefs.setCommandLine([])
305 prefs.addCatalog(
"psfexPsfDeterminer")
308 principalComponentExclusionFlag = bool(bool(psfex.Context.REMOVEHIDDEN)
309 if False else psfex.Context.KEEPHIDDEN)
310 context = psfex.Context(prefs.getContextName(), prefs.getContextGroup(),
311 prefs.getGroupDeg(), principalComponentExclusionFlag)
312 psfSet = psfex.Set(context)
313 psfSet.setVigSize(pixKernelSize, pixKernelSize)
314 psfSet.setFwhm(2*np.sqrt(2*np.log(2))*np.median(sizes))
315 psfSet.setRecentroid(self.config.recentroid)
319 ccd = exposure.getDetector()
321 gain = np.mean(np.array([a.getGain()
for a
in ccd]))
324 self.log.warning(
"Setting gain to %g", gain)
327 for i, key
in enumerate(context.getName()):
330 contextvalp.append(exposure.getMetadata().getScalar(key[1:]))
331 except KeyError
as e:
332 raise RuntimeError(
"%s parameter not found in the header of %s" %
333 (key[1:], prefs.getContextName()))
from e
336 contextvalp.append(np.array([psfCandidateList[_].getSource().get(key)
337 for _
in range(nCand)]))
338 except KeyError
as e:
339 raise RuntimeError(
"%s parameter not found" % (key,))
from e
340 psfSet.setContextname(i, key)
345 disp = afwDisplay.Display(frame=frame)
346 disp.mtv(exposure, title=
"psf determination")
348 badBits = mi.getMask().getPlaneBitMask(self.config.badMaskBits)
349 fluxName = prefs.getPhotfluxRkey()
350 fluxFlagName = fluxName.rpartition(
"_")[0] +
"_flag"
353 for i, psfCandidate
in enumerate(psfCandidateList):
354 source = psfCandidate.getSource()
357 xc, yc = source.getX(), source.getY()
358 if not np.isfinite(xc)
or not np.isfinite(yc):
360 if self.config.rejectFlaggedCentroids:
362 if source.get(
"slot_Centroid_flag"):
365 if source.get(fluxFlagName):
368 flux = source.get(fluxName)
369 if flux < 0
or not np.isfinite(flux):
373 pstamp = psfCandidate.getMaskedImage(pixKernelSize, pixKernelSize).clone()
374 except pexExcept.LengthError:
375 self.log.warning(
"Could not get stamp image for psfCandidate: %s with kernel size: %s",
376 psfCandidate, pixKernelSize)
384 sample = psfSet.newSample()
385 sample.setCatindex(catindex)
386 sample.setExtindex(ext)
387 sample.setObjindex(i)
389 imArray = pstamp.getImage().getArray()
390 imArray[np.where(np.bitwise_and(pstamp.getMask().getArray(), badBits))] = \
392 sample.setVig(imArray)
395 sample.setBacknoise2(backnoise2)
399 sample.setFluxrad(sizes[i])
401 for j
in range(psfSet.getNcontext()):
402 sample.setContext(j, float(contextvalp[j][i]))
403 except Exception
as e:
404 self.log.error(
"Exception when processing sample at (%f,%f): %s", xc, yc, e)
407 psfSet.finiSample(sample)
413 with disp.Buffering():
414 disp.dot(
"o", xc, yc, ctype=afwDisplay.CYAN, size=4)
416 if psfSet.getNsample() == 0:
420 for i
in range(psfSet.getNcontext()):
421 cmin = contextvalp[i].min()
422 cmax = contextvalp[i].max()
423 psfSet.setContextScale(i, cmax - cmin)
424 psfSet.setContextOffset(i, (cmin + cmax)/2.0)
434 field = psfex.Field(
"Unknown")
435 field.addExt(exposure.getWcs(), exposure.getWidth(), exposure.getHeight(), psfSet.getNsample())
443 psfex.makeit(fields, sets)
444 psfs = field.getPsfs()
448 for i
in range(sets[0].getNsample()):
449 index = sets[0].getSample(i).getObjindex()
451 good_indices.append(index)
453 if flagKey
is not None:
454 for i, psfCandidate
in enumerate(psfCandidateList):
455 source = psfCandidate.getSource()
456 if i
in good_indices:
457 source.set(flagKey,
True)
459 xpos = np.array(xpos)
460 ypos = np.array(ypos)
461 numGoodStars = len(good_indices)
462 avgX, avgY = np.mean(xpos), np.mean(ypos)
470 if (ndim := psf.getNdim()) == 0:
472 num_available_stars=nCand,
473 num_good_stars=numGoodStars,
474 poly_ndim_initial=psfSet.getNcontext(),
475 poly_ndim_final=ndim,
482 assert psfCellSet
is not None
485 maUtils.showPsfSpatialCells(exposure, psfCellSet, showChi2=
True,
486 symb=
"o", ctype=afwDisplay.YELLOW, ctypeBad=afwDisplay.RED,
487 size=8, display=disp)
489 disp4 = afwDisplay.Display(frame=4)
490 maUtils.showPsfCandidates(exposure, psfCellSet, psf=psf, display=disp4,
491 normalize=normalizeResiduals,
492 showBadCandidates=showBadCandidates)
493 if displayPsfComponents:
494 disp6 = afwDisplay.Display(frame=6)
495 maUtils.showPsf(psf, display=disp6)
497 disp7 = afwDisplay.Display(frame=7)
498 maUtils.showPsfMosaic(exposure, psf, display=disp7, showFwhm=
True)
499 disp.scale(
'linear', 0, 1)
505 if metadata
is not None:
506 metadata[
"spatialFitChi2"] = np.nan
507 metadata[
"numAvailStars"] = nCand
508 metadata[
"numGoodStars"] = numGoodStars
509 metadata[
"avgX"] = avgX
510 metadata[
"avgY"] = avgY
512 return psf, psfCellSet