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""" 120 def __init__(self, axes, xs, ys, x, y, frames=[0]):
128 self.
cid = self.
axes.figure.canvas.mpl_connect(
'key_press_event', self)
131 if ev.inaxes != self.
axes:
134 if ev.key
and ev.key
in (
"p"):
135 dist = np.hypot(self.
xs - ev.xdata, self.
ys - ev.ydata)
136 dist[np.where(np.isnan(dist))] = 1e30
138 which = np.where(dist == min(dist))
143 ds9.pan(x, y, frame=frame)
144 ds9.cmdBuffer.flush()
151 def plot(mag, width, centers, clusterId, marker="o", markersize=2, markeredgewidth=0, ltype='-',
163 axes = fig.add_axes((0.1, 0.1, 0.85, 0.80))
165 xmin = sorted(mag)[int(0.05*len(mag))]
166 xmax = sorted(mag)[int(0.95*len(mag))]
168 axes.set_xlim(-17.5, -13)
169 axes.set_xlim(xmin - 0.1*(xmax - xmin), xmax + 0.1*(xmax - xmin))
172 colors = [
"r", "g", "b", "c", "m", "k", ]
173 for k, mean
in enumerate(centers):
175 axes.plot(axes.get_xlim(), (mean, mean,),
"k%s" % ltype)
178 axes.plot(mag[l], width[l], marker, markersize=markersize, markeredgewidth=markeredgewidth,
179 color=colors[k%len(colors)])
181 l = (clusterId == -1)
182 axes.plot(mag[l], width[l], marker, markersize=markersize, markeredgewidth=markeredgewidth,
186 axes.set_xlabel(
"model")
187 axes.set_ylabel(
r"$\sqrt{I_{xx} + I_{yy}}$")
200 """!A star selector whose algorithm is not yet documented 202 @anchor PsfexStarSelectorTask_ 204 @section meas_extensions_psfex_psfexStarSelectorStarSelector_Contents Contents 206 - @ref meas_extensions_psfex_psfexStarSelectorStarSelector_Purpose 207 - @ref meas_extensions_psfex_psfexStarSelectorStarSelector_Initialize 208 - @ref meas_extensions_psfex_psfexStarSelectorStarSelector_IO 209 - @ref meas_extensions_psfex_psfexStarSelectorStarSelector_Config 210 - @ref meas_extensions_psfex_psfexStarSelectorStarSelector_Debug 212 @section meas_extensions_psfex_psfexStarSelectorStarSelector_Purpose Description 214 A star selector whose algorithm is not yet documented 216 @section meas_extensions_psfex_psfexStarSelectorStarSelector_Initialize Task initialisation 218 @copydoc \_\_init\_\_ 220 @section meas_extensions_psfex_psfexStarSelectorStarSelector_IO Invoking the Task 222 Like all star selectors, the main method is `run`. 224 @section meas_extensions_psfex_psfexStarSelectorStarSelector_Config Configuration parameters 226 See @ref PsfexStarSelectorConfig 228 @section meas_extensions_psfex_psfexStarSelectorStarSelector_Debug Debug variables 230 PsfexStarSelectorTask has a debug dictionary with the following keys: 233 <dd>bool; if True display debug information 235 <dd>bool; if True display the exposure and spatial cells 236 <dt>plotFwhmHistogram 237 <dd>bool; if True plot histogram of FWHM 239 <dd>bool: if True plot the sources coloured by their flags 241 <dd>bool; if True plot why sources are rejected 244 For example, put something like: 248 di = lsstDebug.getInfo(name) # N.b. lsstDebug.Info(name) would call us recursively 249 if name.endswith("objectSizeStarSelector"): 251 di.displayExposure = True 252 di.plotFwhmHistogram = True 256 lsstDebug.Info = DebugInfo 258 into your `debug.py` file and run your task with the `--debug` flag. 260 ConfigClass = PsfexStarSelectorConfig
264 """!Select stars from source catalog 266 @param[in] exposure the exposure containing the sources 267 @param[in] sourceCat catalog of sources that may be stars (an lsst.afw.table.SourceCatalog) 268 @param[in] matches astrometric matches; ignored by this star selector 270 @return a Struct containing: 271 - starCat a subset of sourceCat containing the selected stars 276 displayExposure = display
and \
278 plotFwhmHistogram = display
and plt
and \
280 plotFlags = display
and plt
and \
282 plotRejection = display
and plt
and \
287 fluxName = self.config.fluxName
288 fluxErrName = self.config.fluxErrName
289 minFwhm = self.config.minFwhm
290 maxFwhm = self.config.maxFwhm
291 maxFwhmVariability = self.config.maxFwhmVariability
292 maxbad = self.config.maxbad
293 maxbadflag = self.config.maxbadflag
294 maxellip = self.config.maxellip
295 minsn = self.config.minsn
297 maxelong = (maxellip + 1.0)/(1.0 - maxellip)
if maxellip < 1.0
else 100
300 shape = sourceCat.getShapeDefinition()
301 ixx = sourceCat.get(
"%s.xx" % shape)
302 iyy = sourceCat.get(
"%s.yy" % shape)
304 fwhm = 2*np.sqrt(2*np.log(2))*np.sqrt(0.5*(ixx + iyy))
305 elong = 0.5*(ixx - iyy)/(ixx + iyy)
307 flux = sourceCat.get(fluxName)
308 fluxErr = sourceCat.get(fluxErrName)
309 sn = flux/np.where(fluxErr > 0, fluxErr, 1)
310 sn[fluxErr <= 0] = -psfexLib.BIG
313 for i, f
in enumerate(self.config.badFlags):
314 flags = np.bitwise_or(flags, np.where(sourceCat.get(f), 1 << i, 0))
318 good = np.logical_and(sn > minsn, np.logical_not(flags))
319 good = np.logical_and(good, elong < maxelong)
320 good = np.logical_and(good, fwhm >= minFwhm)
321 good = np.logical_and(good, fwhm < maxFwhm)
323 fwhmMode, fwhmMin, fwhmMax =
compute_fwhmrange(fwhm[good], maxFwhmVariability, minFwhm, maxFwhm,
324 plot=dict(fwhmHistogram=plotFwhmHistogram))
336 selectionVectors = []
337 selectionVectors.append((bad,
"flags %d" % sum(bad)))
341 bad = np.logical_or(bad, dbad)
343 selectionVectors.append((dbad,
"S/N %d" % sum(dbad)))
345 dbad = fwhm < fwhmMin
347 bad = np.logical_or(bad, dbad)
349 selectionVectors.append((dbad,
"fwhmMin %d" % sum(dbad)))
351 dbad = fwhm > fwhmMax
353 bad = np.logical_or(bad, dbad)
355 selectionVectors.append((dbad,
"fwhmMax %d" % sum(dbad)))
357 dbad = elong > maxelong
359 bad = np.logical_or(bad, dbad)
361 selectionVectors.append((dbad,
"elong %d" % sum(dbad)))
365 nbad = np.array([(v <= -psfexLib.BIG).sum()
for v
in vignet])
368 bad = np.logical_or(bad, dbad)
370 selectionVectors.append((dbad,
"badpix %d" % sum(dbad)))
372 good = np.logical_not(bad)
378 mi = exposure.getMaskedImage()
380 ds9.mtv(mi, frame=frame, title=
"PSF candidates")
382 with ds9.Buffering():
383 for i, source
in enumerate(sourceCat):
389 ds9.dot(
"+", source.getX() - mi.getX0(), source.getY() - mi.getY0(),
390 frame=frame, ctype=ctype)
392 if plotFlags
or plotRejection:
393 imag = -2.5*np.log10(flux)
398 isSet = np.where(flags == 0x0)[0]
399 plt.plot(imag[isSet], fwhm[isSet],
'o', alpha=alpha, label=
"good")
401 for i, f
in enumerate(self.config.badFlags):
403 isSet = np.where(np.bitwise_and(flags, mask))[0]
405 if np.isfinite(imag[isSet] + fwhm[isSet]).any():
406 label = re.sub(
r"\_flag",
"",
407 re.sub(
r"^base\_",
"",
408 re.sub(
r"^.*base\_PixelFlags\_flag\_",
"", f)))
409 plt.plot(imag[isSet], fwhm[isSet],
'o', alpha=alpha, label=label)
411 for bad, label
in selectionVectors:
412 plt.plot(imag[bad], fwhm[bad],
'o', alpha=alpha, label=label)
414 plt.plot(imag[good], fwhm[good],
'o', color=
"black", label=
"selected")
415 [plt.axhline(_, color=
'red')
for _
in [fwhmMin, fwhmMax]]
416 plt.xlim(np.median(imag[good]) + 5*np.array([-1, 1]))
417 plt.ylim(fwhm[np.where(np.isfinite(fwhm + imag))].min(), 2*fwhmMax)
419 plt.xlabel(
"Instrumental %s Magnitude" % fluxName.split(
".")[-1].title())
421 title =
"PSFEX Star Selection" 422 plt.title(
"%s %d selected" % (title, sum(good)))
426 eventHandler =
EventHandler(plt.axes(), imag, fwhm, sourceCat.getX(), sourceCat.getY(),
429 if plotFlags
or plotRejection:
432 reply = input(
"continue? [y[es] h(elp) p(db) q(uit)] ").strip()
441 At this prompt, you can continue with almost any key; 'p' enters pdb, 442 'q' returns to the shell, and 448 If you put the cursor on a point in the matplotlib scatter plot and hit 'p' you'll see it in ds9.""")
449 elif reply[0] ==
"p":
452 elif reply[0] ==
'q':
457 starCat = SourceCatalog(sourceCat.schema)
458 for source, isGood
in zip(sourceCat, good):
460 starCat.append(source)
466 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])
A star selector whose algorithm is not yet documented.
def plot(mag, width, centers, clusterId, marker="o", markersize=2, markeredgewidth=0, ltype='-', clear=True)