114 def determinePsf(self, exposure, psfCandidateList, metadata=None, flagKey=None):
115 """Determine a PSFEX PSF model for an exposure given a list of PSF
120 exposure: `lsst.afw.image.Exposure`
121 Exposure containing the PSF candidates.
122 psfCandidateList: iterable of `lsst.meas.algorithms.PsfCandidate`
123 Sequence of PSF candidates typically obtained by detecting sources
124 and then running them through a star selector.
125 metadata: metadata, optional
126 A home for interesting tidbits of information.
127 flagKey: `lsst.afw.table.Key`, optional
128 Schema key used to mark sources actually used in PSF determination.
132 psf: `lsst.meas.extensions.psfex.PsfexPsf`
135 psfCandidateList = self.downsampleCandidates(psfCandidateList)
139 displayExposure = display
and \
141 displayPsfComponents = display
and \
143 showBadCandidates = display
and \
145 displayResiduals = display
and \
147 displayPsfMosaic = display
and \
150 afwDisplay.setDefaultMaskTransparency(75)
153 mi = exposure.getMaskedImage()
155 nCand = len(psfCandidateList)
157 raise RuntimeError(
"No PSF candidates supplied.")
163 bbox = mi.getBBox(afwImage.PARENT)
168 sizes = np.empty(nCand)
169 for i, psfCandidate
in enumerate(psfCandidateList):
172 psfCellSet.insertCandidate(psfCandidate)
173 except Exception
as e:
174 self.log.error(
"Skipping PSF candidate %d of %d: %s", i, len(psfCandidateList), e)
177 source = psfCandidate.getSource()
178 quad = afwEll.Quadrupole(source.getIxx(), source.getIyy(), source.getIxy())
179 rmsSize = quad.getTraceRadius()
182 pixKernelSize = self.config.stampSize
183 actualKernelSize = int(2*np.floor(0.5*pixKernelSize/self.config.samplingSize) + 1)
186 rms = np.median(sizes)
187 self.log.debug(
"Median PSF RMS size=%.2f pixels (\"FWHM\"=%.2f)",
188 rms, 2*np.sqrt(2*np.log(2))*rms)
190 self.log.trace(
"Psfex Kernel size=%.2f, Image Kernel Size=%.2f", actualKernelSize, pixKernelSize)
196 defaultsFile = os.path.join(os.environ[
"MEAS_EXTENSIONS_PSFEX_DIR"],
"config",
"default-lsst.psfex")
198 args_md.set(
"BASIS_TYPE", str(self.config.psfexBasis))
199 args_md.set(
"PSFVAR_DEGREES", str(self.config.spatialOrder))
200 args_md.set(
"PSF_SIZE", str(actualKernelSize))
201 args_md.set(
"PSF_SAMPLING", str(self.config.samplingSize))
202 args_md.set(
"PHOTFLUX_KEY", str(self.config.photometricFluxField))
203 args_md.set(
"PHOTFLUXERR_KEY", str(self.config.photometricFluxField) +
"Err")
204 prefs = psfex.Prefs(defaultsFile, args_md)
205 prefs.setCommandLine([])
206 prefs.addCatalog(
"psfexPsfDeterminer")
209 principalComponentExclusionFlag = bool(bool(psfex.Context.REMOVEHIDDEN)
210 if False else psfex.Context.KEEPHIDDEN)
211 context = psfex.Context(prefs.getContextName(), prefs.getContextGroup(),
212 prefs.getGroupDeg(), principalComponentExclusionFlag)
213 psfSet = psfex.Set(context)
214 psfSet.setVigSize(pixKernelSize, pixKernelSize)
215 psfSet.setFwhm(2*np.sqrt(2*np.log(2))*np.median(sizes))
216 psfSet.setRecentroid(self.config.recentroid)
220 ccd = exposure.getDetector()
222 gain = np.mean(np.array([a.getGain()
for a
in ccd]))
225 self.log.warning(
"Setting gain to %g", gain)
228 for i, key
in enumerate(context.getName()):
231 contextvalp.append(exposure.getMetadata().getScalar(key[1:]))
232 except KeyError
as e:
233 raise RuntimeError(
"%s parameter not found in the header of %s" %
234 (key[1:], prefs.getContextName()))
from e
237 contextvalp.append(np.array([psfCandidateList[_].getSource().get(key)
238 for _
in range(nCand)]))
239 except KeyError
as e:
240 raise RuntimeError(
"%s parameter not found" % (key,))
from e
241 psfSet.setContextname(i, key)
246 disp = afwDisplay.Display(frame=frame)
247 disp.mtv(exposure, title=
"psf determination")
249 badBits = mi.getMask().getPlaneBitMask(self.config.badMaskBits)
250 fluxName = prefs.getPhotfluxRkey()
251 fluxFlagName =
"base_" + fluxName +
"_flag"
254 for i, psfCandidate
in enumerate(psfCandidateList):
255 source = psfCandidate.getSource()
258 xc, yc = source.getX(), source.getY()
259 if not np.isfinite(xc)
or not np.isfinite(yc):
262 if fluxFlagName
in source.schema
and source.get(fluxFlagName):
265 flux = source.get(fluxName)
266 if flux < 0
or not np.isfinite(flux):
270 pstamp = psfCandidate.getMaskedImage(pixKernelSize, pixKernelSize).clone()
272 self.log.warning(
"Could not get stamp image for psfCandidate: %s with kernel size: %s",
273 psfCandidate, pixKernelSize)
281 sample = psfSet.newSample()
282 sample.setCatindex(catindex)
283 sample.setExtindex(ext)
284 sample.setObjindex(i)
286 imArray = pstamp.getImage().getArray()
287 imArray[np.where(np.bitwise_and(pstamp.getMask().getArray(), badBits))] = \
289 sample.setVig(imArray)
292 sample.setBacknoise2(backnoise2)
296 sample.setFluxrad(sizes[i])
298 for j
in range(psfSet.getNcontext()):
299 sample.setContext(j, float(contextvalp[j][i]))
300 except Exception
as e:
301 self.log.error(
"Exception when processing sample at (%f,%f): %s", xc, yc, e)
304 psfSet.finiSample(sample)
310 with disp.Buffering():
311 disp.dot(
"o", xc, yc, ctype=afwDisplay.CYAN, size=4)
313 if psfSet.getNsample() == 0:
314 raise RuntimeError(
"No good PSF candidates to pass to PSFEx")
317 for i
in range(psfSet.getNcontext()):
318 cmin = contextvalp[i].
min()
319 cmax = contextvalp[i].
max()
320 psfSet.setContextScale(i, cmax - cmin)
321 psfSet.setContextOffset(i, (cmin + cmax)/2.0)
331 field = psfex.Field(
"Unknown")
332 field.addExt(exposure.getWcs(), exposure.getWidth(), exposure.getHeight(), psfSet.getNsample())
340 psfex.makeit(fields, sets)
341 psfs = field.getPsfs()
345 for i
in range(sets[0].getNsample()):
346 index = sets[0].getSample(i).getObjindex()
348 good_indices.append(index)
350 if flagKey
is not None:
351 for i, psfCandidate
in enumerate(psfCandidateList):
352 source = psfCandidate.getSource()
353 if i
in good_indices:
354 source.set(flagKey,
True)
356 xpos = np.array(xpos)
357 ypos = np.array(ypos)
358 numGoodStars = len(good_indices)
359 avgX, avgY = np.mean(xpos), np.mean(ypos)
369 _ = psf.getKernel(psf.getAveragePosition())
371 raise RuntimeError(
"Failed to determine psfex psf: too few good stars.")
377 assert psfCellSet
is not None
380 maUtils.showPsfSpatialCells(exposure, psfCellSet, showChi2=
True,
381 symb=
"o", ctype=afwDisplay.YELLOW, ctypeBad=afwDisplay.RED,
382 size=8, display=disp)
384 disp4 = afwDisplay.Display(frame=4)
385 maUtils.showPsfCandidates(exposure, psfCellSet, psf=psf, display=disp4,
386 normalize=normalizeResiduals,
387 showBadCandidates=showBadCandidates)
388 if displayPsfComponents:
389 disp6 = afwDisplay.Display(frame=6)
390 maUtils.showPsf(psf, display=disp6)
392 disp7 = afwDisplay.Display(frame=7)
393 maUtils.showPsfMosaic(exposure, psf, display=disp7, showFwhm=
True)
394 disp.scale(
'linear', 0, 1)
400 if metadata
is not None:
401 metadata[
"spatialFitChi2"] = np.nan
402 metadata[
"numAvailStars"] = nCand
403 metadata[
"numGoodStars"] = numGoodStars
404 metadata[
"avgX"] = avgX
405 metadata[
"avgY"] = avgY
407 return psf, psfCellSet