27 import matplotlib.pyplot
as plt
37 from .
import psfexLib
38 from .psfex
import compute_fwhmrange
40 __all__ = [
"PsfexStarSelectorConfig",
"PsfexStarSelectorTask"]
44 fluxName = pexConfig.Field(
46 doc=
"Name of photometric flux key ",
47 default=
"base_PsfFlux",
49 fluxErrName = pexConfig.Field(
51 doc=
"Name of phot. flux err. key",
54 minFwhm = pexConfig.Field(
56 doc=
"Maximum allowed FWHM ",
59 maxFwhm = pexConfig.Field(
61 doc=
"Minimum allowed FWHM ",
64 maxFwhmVariability = pexConfig.Field(
66 doc=
"Allowed FWHM variability (1.0 = 100%)",
69 maxbad = pexConfig.Field(
71 doc=
"Max number of bad pixels ",
73 check=
lambda x: x >= 0,
75 maxbadflag = pexConfig.Field(
77 doc=
"Filter bad pixels? ",
80 maxellip = pexConfig.Field(
82 doc=
"Maximum (A-B)/(A+B) ",
84 check=
lambda x: x >= 0.0,
86 minsn = pexConfig.Field(
88 doc=
"Minimum S/N for candidates",
90 check=
lambda x: x >= 0.0,
94 pexConfig.Config.validate(self)
99 raise pexConfig.FieldValidationError(
"fluxErrName (%s) doesn't correspond to fluxName (%s)" 103 raise pexConfig.FieldValidationError(
"minFwhm (%f) > maxFwhm (%f)" % (self.
minFwhm, self.
maxFwhm))
107 "base_PixelFlags_flag_edge",
108 "base_PixelFlags_flag_saturatedCenter",
109 "base_PixelFlags_flag_crCenter",
110 "base_PixelFlags_flag_bad",
111 "base_PixelFlags_flag_suspectCenter",
118 """A class to handle key strokes with matplotlib displays 121 def __init__(self, axes, xs, ys, x, y, frames=[0]):
129 self.
cid = self.
axes.figure.canvas.mpl_connect(
'key_press_event', self)
132 if ev.inaxes != self.
axes:
135 if ev.key
and ev.key
in (
"p"):
136 dist = np.hypot(self.
xs - ev.xdata, self.
ys - ev.ydata)
137 dist[np.where(np.isnan(dist))] = 1e30
139 which = np.where(dist == min(dist))
144 ds9.pan(x, y, frame=frame)
145 ds9.cmdBuffer.flush()
152 def plot(mag, width, centers, clusterId, marker="o", markersize=2, markeredgewidth=0, ltype='-',
164 axes = fig.add_axes((0.1, 0.1, 0.85, 0.80))
166 xmin = sorted(mag)[int(0.05*len(mag))]
167 xmax = sorted(mag)[int(0.95*len(mag))]
169 axes.set_xlim(-17.5, -13)
170 axes.set_xlim(xmin - 0.1*(xmax - xmin), xmax + 0.1*(xmax - xmin))
173 colors = [
"r", "g", "b", "c", "m", "k", ]
174 for k, mean
in enumerate(centers):
176 axes.plot(axes.get_xlim(), (mean, mean,),
"k%s" % ltype)
179 axes.plot(mag[l], width[l], marker, markersize=markersize, markeredgewidth=markeredgewidth,
180 color=colors[k%len(colors)])
182 l = (clusterId == -1)
183 axes.plot(mag[l], width[l], marker, markersize=markersize, markeredgewidth=markeredgewidth,
187 axes.set_xlabel(
"model")
188 axes.set_ylabel(
r"$\sqrt{I_{xx} + I_{yy}}$")
201 """A star selector whose algorithm is not yet documented. 203 @anchor PsfexStarSelectorTask_ 205 @section meas_extensions_psfex_psfexStarSelectorStarSelector_Contents Contents 207 - @ref meas_extensions_psfex_psfexStarSelectorStarSelector_Purpose 208 - @ref meas_extensions_psfex_psfexStarSelectorStarSelector_Initialize 209 - @ref meas_extensions_psfex_psfexStarSelectorStarSelector_IO 210 - @ref meas_extensions_psfex_psfexStarSelectorStarSelector_Config 211 - @ref meas_extensions_psfex_psfexStarSelectorStarSelector_Debug 213 @section meas_extensions_psfex_psfexStarSelectorStarSelector_Purpose Description 215 A star selector whose algorithm is not yet documented 217 @section meas_extensions_psfex_psfexStarSelectorStarSelector_Initialize Task initialisation 219 @copydoc \_\_init\_\_ 221 @section meas_extensions_psfex_psfexStarSelectorStarSelector_IO Invoking the Task 223 Like all star selectors, the main method is `run`. 225 @section meas_extensions_psfex_psfexStarSelectorStarSelector_Config Configuration parameters 227 See @ref PsfexStarSelectorConfig 229 @section meas_extensions_psfex_psfexStarSelectorStarSelector_Debug Debug variables 231 PsfexStarSelectorTask has a debug dictionary with the following keys: 234 <dd>bool; if True display debug information 236 <dd>bool; if True display the exposure and spatial cells 237 <dt>plotFwhmHistogram 238 <dd>bool; if True plot histogram of FWHM 240 <dd>bool: if True plot the sources coloured by their flags 242 <dd>bool; if True plot why sources are rejected 245 For example, put something like: 249 di = lsstDebug.getInfo(name) # N.b. lsstDebug.Info(name) would call us recursively 250 if name.endswith("objectSizeStarSelector"): 252 di.displayExposure = True 253 di.plotFwhmHistogram = True 257 lsstDebug.Info = DebugInfo 259 into your `debug.py` file and run your task with the `--debug` flag. 261 ConfigClass = PsfexStarSelectorConfig
265 """!Select stars from source catalog 267 @param[in] exposure the exposure containing the sources 268 @param[in] sourceCat catalog of sources that may be stars (an lsst.afw.table.SourceCatalog) 269 @param[in] matches astrometric matches; ignored by this star selector 271 @return a Struct containing: 272 - starCat a subset of sourceCat containing the selected stars 277 displayExposure = display
and \
279 plotFwhmHistogram = display
and plt
and \
281 plotFlags = display
and plt
and \
283 plotRejection = display
and plt
and \
288 fluxName = self.config.fluxName
289 fluxErrName = self.config.fluxErrName
290 minFwhm = self.config.minFwhm
291 maxFwhm = self.config.maxFwhm
292 maxFwhmVariability = self.config.maxFwhmVariability
293 maxbad = self.config.maxbad
294 maxbadflag = self.config.maxbadflag
295 maxellip = self.config.maxellip
296 minsn = self.config.minsn
298 maxelong = (maxellip + 1.0)/(1.0 - maxellip)
if maxellip < 1.0
else 100
301 shape = sourceCat.getShapeDefinition()
302 ixx = sourceCat.get(
"%s.xx" % shape)
303 iyy = sourceCat.get(
"%s.yy" % shape)
305 fwhm = 2*np.sqrt(2*np.log(2))*np.sqrt(0.5*(ixx + iyy))
306 elong = 0.5*(ixx - iyy)/(ixx + iyy)
308 flux = sourceCat.get(fluxName)
309 fluxErr = sourceCat.get(fluxErrName)
310 sn = flux/np.where(fluxErr > 0, fluxErr, 1)
311 sn[fluxErr <= 0] = -psfexLib.BIG
314 for i, f
in enumerate(self.config.badFlags):
315 flags = np.bitwise_or(flags, np.where(sourceCat.get(f), 1 << i, 0))
319 good = np.logical_and(sn > minsn, np.logical_not(flags))
320 good = np.logical_and(good, elong < maxelong)
321 good = np.logical_and(good, fwhm >= minFwhm)
322 good = np.logical_and(good, fwhm < maxFwhm)
324 fwhmMode, fwhmMin, fwhmMax =
compute_fwhmrange(fwhm[good], maxFwhmVariability, minFwhm, maxFwhm,
325 plot=dict(fwhmHistogram=plotFwhmHistogram))
337 selectionVectors = []
338 selectionVectors.append((bad,
"flags %d" % sum(bad)))
342 bad = np.logical_or(bad, dbad)
344 selectionVectors.append((dbad,
"S/N %d" % sum(dbad)))
346 dbad = fwhm < fwhmMin
348 bad = np.logical_or(bad, dbad)
350 selectionVectors.append((dbad,
"fwhmMin %d" % sum(dbad)))
352 dbad = fwhm > fwhmMax
354 bad = np.logical_or(bad, dbad)
356 selectionVectors.append((dbad,
"fwhmMax %d" % sum(dbad)))
358 dbad = elong > maxelong
360 bad = np.logical_or(bad, dbad)
362 selectionVectors.append((dbad,
"elong %d" % sum(dbad)))
366 nbad = np.array([(v <= -psfexLib.BIG).sum()
for v
in vignet])
369 bad = np.logical_or(bad, dbad)
371 selectionVectors.append((dbad,
"badpix %d" % sum(dbad)))
373 good = np.logical_not(bad)
379 mi = exposure.getMaskedImage()
381 ds9.mtv(mi, frame=frame, title=
"PSF candidates")
383 with ds9.Buffering():
384 for i, source
in enumerate(sourceCat):
390 ds9.dot(
"+", source.getX() - mi.getX0(), source.getY() - mi.getY0(),
391 frame=frame, ctype=ctype)
393 if plotFlags
or plotRejection:
394 imag = -2.5*np.log10(flux)
399 isSet = np.where(flags == 0x0)[0]
400 plt.plot(imag[isSet], fwhm[isSet],
'o', alpha=alpha, label=
"good")
402 for i, f
in enumerate(self.config.badFlags):
404 isSet = np.where(np.bitwise_and(flags, mask))[0]
406 if np.isfinite(imag[isSet] + fwhm[isSet]).any():
407 label = re.sub(
r"\_flag",
"",
408 re.sub(
r"^base\_",
"",
409 re.sub(
r"^.*base\_PixelFlags\_flag\_",
"", f)))
410 plt.plot(imag[isSet], fwhm[isSet],
'o', alpha=alpha, label=label)
412 for bad, label
in selectionVectors:
413 plt.plot(imag[bad], fwhm[bad],
'o', alpha=alpha, label=label)
415 plt.plot(imag[good], fwhm[good],
'o', color=
"black", label=
"selected")
416 [plt.axhline(_, color=
'red')
for _
in [fwhmMin, fwhmMax]]
417 plt.xlim(np.median(imag[good]) + 5*np.array([-1, 1]))
418 plt.ylim(fwhm[np.where(np.isfinite(fwhm + imag))].min(), 2*fwhmMax)
420 plt.xlabel(
"Instrumental %s Magnitude" % fluxName.split(
".")[-1].title())
422 title =
"PSFEX Star Selection" 423 plt.title(
"%s %d selected" % (title, sum(good)))
427 eventHandler =
EventHandler(plt.axes(), imag, fwhm, sourceCat.getX(), sourceCat.getY(),
430 if plotFlags
or plotRejection:
433 reply = input(
"continue? [y[es] h(elp) p(db) q(uit)] ").strip()
442 At this prompt, you can continue with almost any key; 'p' enters pdb, 443 'q' returns to the shell, and 449 If you put the cursor on a point in the matplotlib scatter plot and hit 'p' you'll see it in ds9.""")
450 elif reply[0] ==
"p":
453 elif reply[0] ==
'q':
458 starCat = SourceCatalog(sourceCat.schema)
459 for source, isGood
in zip(sourceCat, good):
461 starCat.append(source)
467 starSelectorRegistry.register(
"psfex", PsfexStarSelectorTask)
def selectStars(self, exposure, sourceCat, matches=None)
Select stars from source catalog.
def compute_fwhmrange(fwhm, maxvar, minin, maxin, plot=dict(fwhmHistogram=False))
def __init__(self, axes, xs, ys, x, y, frames=[0])
def plot(mag, width, centers, clusterId, marker="o", markersize=2, markeredgewidth=0, ltype='-', clear=True)