LSSTApplications  17.0+11,17.0+34,17.0+56,17.0+57,17.0+59,17.0+7,17.0-1-g377950a+33,17.0.1-1-g114240f+2,17.0.1-1-g4d4fbc4+28,17.0.1-1-g55520dc+49,17.0.1-1-g5f4ed7e+52,17.0.1-1-g6dd7d69+17,17.0.1-1-g8de6c91+11,17.0.1-1-gb9095d2+7,17.0.1-1-ge9fec5e+5,17.0.1-1-gf4e0155+55,17.0.1-1-gfc65f5f+50,17.0.1-1-gfc6fb1f+20,17.0.1-10-g87f9f3f+1,17.0.1-11-ge9de802+16,17.0.1-16-ga14f7d5c+4,17.0.1-17-gc79d625+1,17.0.1-17-gdae4c4a+8,17.0.1-2-g26618f5+29,17.0.1-2-g54f2ebc+9,17.0.1-2-gf403422+1,17.0.1-20-g2ca2f74+6,17.0.1-23-gf3eadeb7+1,17.0.1-3-g7e86b59+39,17.0.1-3-gb5ca14a,17.0.1-3-gd08d533+40,17.0.1-30-g596af8797,17.0.1-4-g59d126d+4,17.0.1-4-gc69c472+5,17.0.1-6-g5afd9b9+4,17.0.1-7-g35889ee+1,17.0.1-7-gc7c8782+18,17.0.1-9-gc4bbfb2+3,w.2019.22
LSSTDataManagementBasePackage
psfexStarSelector.py
Go to the documentation of this file.
1 #
2 # LSST Data Management System
3 # Copyright 2008, 2009, 2010 LSST Corporation.
4 #
5 # This product includes software developed by the
6 # LSST Project (http://www.lsst.org/).
7 #
8 # This program is free software: you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation, either version 3 of the License, or
11 # (at your option) any later version.
12 #
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
17 #
18 # You should have received a copy of the LSST License Statement and
19 # the GNU General Public License along with this program. If not,
20 # see <http://www.lsstcorp.org/LegalNotices/>.
21 #
22 import re
23 import sys
24 
25 import numpy as np
26 try:
27  import matplotlib.pyplot as plt
28  fig = None
29 except ImportError:
30  plt = None
31 
32 from lsst.pipe.base import Struct
33 import lsst.pex.config as pexConfig
34 import lsst.afw.display as afwDisplay
35 from lsst.meas.algorithms import BaseSourceSelectorTask, sourceSelectorRegistry
36 from . import psfexLib
37 from .psfex import compute_fwhmrange
38 
39 __all__ = ["PsfexStarSelectorConfig", "PsfexStarSelectorTask"]
40 
41 
42 class PsfexStarSelectorConfig(BaseSourceSelectorTask.ConfigClass):
43  fluxName = pexConfig.Field(
44  dtype=str,
45  doc="Name of photometric flux key ",
46  default="base_PsfFlux",
47  )
48  fluxErrName = pexConfig.Field(
49  dtype=str,
50  doc="Name of phot. flux err. key",
51  default="",
52  )
53  minFwhm = pexConfig.Field(
54  dtype=float,
55  doc="Maximum allowed FWHM ",
56  default=2,
57  )
58  maxFwhm = pexConfig.Field(
59  dtype=float,
60  doc="Minimum allowed FWHM ",
61  default=10,
62  )
63  maxFwhmVariability = pexConfig.Field(
64  dtype=float,
65  doc="Allowed FWHM variability (1.0 = 100%)",
66  default=0.2,
67  )
68  maxbad = pexConfig.Field(
69  dtype=int,
70  doc="Max number of bad pixels ",
71  default=0,
72  check=lambda x: x >= 0,
73  )
74  maxbadflag = pexConfig.Field(
75  dtype=bool,
76  doc="Filter bad pixels? ",
77  default=True
78  )
79  maxellip = pexConfig.Field(
80  dtype=float,
81  doc="Maximum (A-B)/(A+B) ",
82  default=0.3,
83  check=lambda x: x >= 0.0,
84  )
85  minsn = pexConfig.Field(
86  dtype=float,
87  doc="Minimum S/N for candidates",
88  default=100,
89  check=lambda x: x >= 0.0,
90  )
91 
92  def validate(self):
93  pexConfig.Config.validate(self)
94 
95  if self.fluxErrName == "":
96  self.fluxErrName = self.fluxName + ".err"
97  elif self.fluxErrName != self.fluxName + ".err":
98  msg = f"fluxErrName ({self.fluxErrName}) doesn't correspond to fluxName ({self.fluxName})"
99  raise pexConfig.FieldValidationError(PsfexStarSelectorConfig.fluxName, self, msg)
100 
101  if self.minFwhm > self.maxFwhm:
102  raise pexConfig.FieldValidationError(PsfexStarSelectorConfig.minFwhm, self,
103  f"minFwhm ({self.minFwhm}) > maxFwhm ({self.maxFwhm})")
104 
105  def setDefaults(self):
106  self.badFlags = [
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",
112  "base_PsfFlux_flag",
113  # "parent", # actually this is a test on deblend_nChild
114  ]
115 
116 
117 class EventHandler():
118  """A class to handle key strokes with matplotlib displays
119  """
120 
121  def __init__(self, axes, xs, ys, x, y, frames=[0]):
122  self.axes = axes
123  self.xs = xs
124  self.ys = ys
125  self.x = x
126  self.y = y
127  self.frames = frames
128 
129  self.cid = self.axes.figure.canvas.mpl_connect('key_press_event', self)
130 
131  def __call__(self, ev):
132  if ev.inaxes != self.axes:
133  return
134 
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
138 
139  which = np.where(dist == min(dist))
140 
141  x = self.x[which][0]
142  y = self.y[which][0]
143  for frame in self.frames:
144  disp = afwDisplay.Display(frame=frame)
145  disp.pan(x, y)
146  disp.flush()
147  else:
148  pass
149 
150 
151 def plot(mag, width, centers, clusterId, marker="o", markersize=2, markeredgewidth=0, ltype='-',
152  clear=True):
153 
154  global fig
155  if not fig:
156  fig = plt.figure()
157  newFig = True
158  else:
159  newFig = False
160  if clear:
161  fig.clf()
162 
163  axes = fig.add_axes((0.1, 0.1, 0.85, 0.80))
164 
165  xmin = sorted(mag)[int(0.05*len(mag))]
166  xmax = sorted(mag)[int(0.95*len(mag))]
167 
168  axes.set_xlim(-17.5, -13)
169  axes.set_xlim(xmin - 0.1*(xmax - xmin), xmax + 0.1*(xmax - xmin))
170  axes.set_ylim(0, 10)
171 
172  colors = ["r", "g", "b", "c", "m", "k", ]
173  for k, mean in enumerate(centers):
174  if k == 0:
175  axes.plot(axes.get_xlim(), (mean, mean,), "k%s" % ltype)
176 
177  l = (clusterId == k)
178  axes.plot(mag[l], width[l], marker, markersize=markersize, markeredgewidth=markeredgewidth,
179  color=colors[k%len(colors)])
180 
181  l = (clusterId == -1)
182  axes.plot(mag[l], width[l], marker, markersize=markersize, markeredgewidth=markeredgewidth,
183  color='k')
184 
185  if newFig:
186  axes.set_xlabel("model")
187  axes.set_ylabel(r"$\sqrt{I_{xx} + I_{yy}}$")
188 
189  return fig
190 
191 
197 
198 
199 @pexConfig.registerConfigurable("psfex", sourceSelectorRegistry)
201  """A star selector whose algorithm is not yet documented.
202 
203  @anchor PsfexStarSelectorTask_
204 
205  @section meas_extensions_psfex_psfexStarSelectorStarSelector_Contents Contents
206 
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
212 
213  @section meas_extensions_psfex_psfexStarSelectorStarSelector_Purpose Description
214 
215  A star selector whose algorithm is not yet documented
216 
217  @section meas_extensions_psfex_psfexStarSelectorStarSelector_Initialize Task initialisation
218 
219  @copydoc \_\_init\_\_
220 
221  @section meas_extensions_psfex_psfexStarSelectorStarSelector_IO Invoking the Task
222 
223  Like all star selectors, the main method is `run`.
224 
225  @section meas_extensions_psfex_psfexStarSelectorStarSelector_Config Configuration parameters
226 
227  See @ref PsfexStarSelectorConfig
228 
229  @section meas_extensions_psfex_psfexStarSelectorStarSelector_Debug Debug variables
230 
231  PsfexStarSelectorTask has a debug dictionary with the following keys:
232  <dl>
233  <dt>display
234  <dd>bool; if True display debug information
235  <dt>displayExposure
236  <dd>bool; if True display the exposure and spatial cells
237  <dt>plotFwhmHistogram
238  <dd>bool; if True plot histogram of FWHM
239  <dt>plotFlags
240  <dd>bool: if True plot the sources coloured by their flags
241  <dt>plotRejection
242  <dd>bool; if True plot why sources are rejected
243  </dl>
244 
245  For example, put something like:
246  @code{.py}
247  import lsstDebug
248  def DebugInfo(name):
249  di = lsstDebug.getInfo(name) # N.b. lsstDebug.Info(name) would call us recursively
250  if name.endswith("objectSizeStarSelector"):
251  di.display = True
252  di.displayExposure = True
253  di.plotFwhmHistogram = True
254 
255  return di
256 
257  lsstDebug.Info = DebugInfo
258  @endcode
259  into your `debug.py` file and run your task with the `--debug` flag.
260  """
261  ConfigClass = PsfexStarSelectorConfig
262  usesMatches = False # selectStars does not use its matches argument
263 
264  def selectSources(self, sourceCat, matches=None, exposure=None):
265  """Return a selection of psf-like objects.
266 
267  Parameters
268  ----------
269  sourceCat : `lsst.afw.table.SourceCatalog`
270  Catalog of sources to select from.
271  This catalog must be contiguous in memory.
272  matches : `list` of `lsst.afw.table.ReferenceMatch` or None
273  Ignored by this source selector.
274  exposure : `lsst.afw.image.Exposure` or None
275  The exposure the catalog was built from; used for debug display.
276 
277  Return
278  ------
279  struct : `lsst.pipe.base.Struct`
280  The struct contains the following data:
281 
282  - selected : `numpy.ndarray` of `bool``
283  Boolean array of sources that were selected, same length as
284  sourceCat.
285  """
286  import lsstDebug
287  display = lsstDebug.Info(__name__).display
288 
289  displayExposure = display and \
290  lsstDebug.Info(__name__).displayExposure # display the Exposure + spatialCells
291  plotFwhmHistogram = display and plt and \
292  lsstDebug.Info(__name__).plotFwhmHistogram # Plot histogram of FWHM
293  plotFlags = display and plt and \
294  lsstDebug.Info(__name__).plotFlags # Plot the sources coloured by their flags
295  plotRejection = display and plt and \
296  lsstDebug.Info(__name__).plotRejection # Plot why sources are rejected
297  afwDisplay.setDefaultMaskTransparency(75)
298 
299  fluxName = self.config.fluxName
300  fluxErrName = self.config.fluxErrName
301  minFwhm = self.config.minFwhm
302  maxFwhm = self.config.maxFwhm
303  maxFwhmVariability = self.config.maxFwhmVariability
304  maxbad = self.config.maxbad
305  maxbadflag = self.config.maxbadflag
306  maxellip = self.config.maxellip
307  minsn = self.config.minsn
308 
309  maxelong = (maxellip + 1.0)/(1.0 - maxellip) if maxellip < 1.0 else 100
310 
311  # Unpack the catalogue
312  shape = sourceCat.getShapeDefinition()
313  ixx = sourceCat.get("%s.xx" % shape)
314  iyy = sourceCat.get("%s.yy" % shape)
315 
316  fwhm = 2*np.sqrt(2*np.log(2))*np.sqrt(0.5*(ixx + iyy))
317  elong = 0.5*(ixx - iyy)/(ixx + iyy)
318 
319  flux = sourceCat.get(fluxName)
320  fluxErr = sourceCat.get(fluxErrName)
321  sn = flux/np.where(fluxErr > 0, fluxErr, 1)
322  sn[fluxErr <= 0] = -psfexLib.BIG
323 
324  flags = 0x0
325  for i, f in enumerate(self.config.badFlags):
326  flags = np.bitwise_or(flags, np.where(sourceCat.get(f), 1 << i, 0))
327  #
328  # Estimate the acceptable range of source widths
329  #
330  good = np.logical_and(sn > minsn, np.logical_not(flags))
331  good = np.logical_and(good, elong < maxelong)
332  good = np.logical_and(good, fwhm >= minFwhm)
333  good = np.logical_and(good, fwhm < maxFwhm)
334 
335  fwhmMode, fwhmMin, fwhmMax = compute_fwhmrange(fwhm[good], maxFwhmVariability, minFwhm, maxFwhm,
336  plot=dict(fwhmHistogram=plotFwhmHistogram))
337 
338  # -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
339  #
340  # Here's select_candidates
341  #
342  # ---- Apply some selection over flags, fluxes...
343 
344  bad = (flags != 0)
345  # set.setBadFlags(int(sum(bad)))
346 
347  if plotRejection:
348  selectionVectors = []
349  selectionVectors.append((bad, "flags %d" % sum(bad)))
350 
351  dbad = sn < minsn
352  # set.setBadSN(int(sum(dbad)))
353  bad = np.logical_or(bad, dbad)
354  if plotRejection:
355  selectionVectors.append((dbad, "S/N %d" % sum(dbad)))
356 
357  dbad = fwhm < fwhmMin
358  # set.setBadFrmin(int(sum(dbad)))
359  bad = np.logical_or(bad, dbad)
360  if plotRejection:
361  selectionVectors.append((dbad, "fwhmMin %d" % sum(dbad)))
362 
363  dbad = fwhm > fwhmMax
364  # set.setBadFrmax(int(sum(dbad)))
365  bad = np.logical_or(bad, dbad)
366  if plotRejection:
367  selectionVectors.append((dbad, "fwhmMax %d" % sum(dbad)))
368 
369  dbad = elong > maxelong
370  # set.setBadElong(int(sum(dbad)))
371  bad = np.logical_or(bad, dbad)
372  if plotRejection:
373  selectionVectors.append((dbad, "elong %d" % sum(dbad)))
374 
375  # -- ... and check the integrity of the sample
376  if maxbadflag:
377  nbad = np.array([(v <= -psfexLib.BIG).sum() for v in vignet])
378  dbad = nbad > maxbad
379  # set.setBadPix(int(sum(dbad)))
380  bad = np.logical_or(bad, dbad)
381  if plotRejection:
382  selectionVectors.append((dbad, "badpix %d" % sum(dbad)))
383 
384  good = np.logical_not(bad)
385  #
386  # We know enough to plot, if so requested
387  #
388  frame = 0
389  if displayExposure:
390  mi = exposure.getMaskedImage()
391  disp = afwDisplay.Display(frame=frame)
392  disp.mtv(mi, title="PSF candidates")
393 
394  with disp.Buffering():
395  for i, source in enumerate(sourceCat):
396  if good[i]:
397  ctype = afwDisplay.GREEN # star candidate
398  else:
399  ctype = afwDisplay.RED # not star
400 
401  disp.dot("+", source.getX() - mi.getX0(), source.getY() - mi.getY0(),
402  ctype=ctype)
403 
404  if plotFlags or plotRejection:
405  imag = -2.5*np.log10(flux)
406  plt.clf()
407 
408  alpha = 0.5
409  if plotFlags:
410  isSet = np.where(flags == 0x0)[0]
411  plt.plot(imag[isSet], fwhm[isSet], 'o', alpha=alpha, label="good")
412 
413  for i, f in enumerate(self.config.badFlags):
414  mask = 1 << i
415  isSet = np.where(np.bitwise_and(flags, mask))[0]
416  if isSet.any():
417  if np.isfinite(imag[isSet] + fwhm[isSet]).any():
418  label = re.sub(r"\_flag", "",
419  re.sub(r"^base\_", "",
420  re.sub(r"^.*base\_PixelFlags\_flag\_", "", f)))
421  plt.plot(imag[isSet], fwhm[isSet], 'o', alpha=alpha, label=label)
422  else:
423  for bad, label in selectionVectors:
424  plt.plot(imag[bad], fwhm[bad], 'o', alpha=alpha, label=label)
425 
426  plt.plot(imag[good], fwhm[good], 'o', color="black", label="selected")
427  [plt.axhline(_, color='red') for _ in [fwhmMin, fwhmMax]]
428  plt.xlim(np.median(imag[good]) + 5*np.array([-1, 1]))
429  plt.ylim(fwhm[np.where(np.isfinite(fwhm + imag))].min(), 2*fwhmMax)
430  plt.legend(loc=2)
431  plt.xlabel("Instrumental %s Magnitude" % fluxName.split(".")[-1].title())
432  plt.ylabel("fwhm")
433  title = "PSFEX Star Selection"
434  plt.title("%s %d selected" % (title, sum(good)))
435 
436  if displayExposure:
437  global eventHandler
438  eventHandler = EventHandler(plt.axes(), imag, fwhm, sourceCat.getX(), sourceCat.getY(),
439  frames=[frame])
440 
441  if plotFlags or plotRejection:
442  while True:
443  try:
444  reply = input("continue? [y[es] h(elp) p(db) q(uit)] ").strip()
445  except EOFError:
446  reply = "y"
447 
448  if not reply:
449  reply = "y"
450 
451  if reply[0] == "h":
452  print("""\
453 At this prompt, you can continue with almost any key; 'p' enters pdb,
454  'q' returns to the shell, and
455  'h' prints this text
456 """, end=' ')
457 
458  if displayExposure:
459  print("""
460 If you put the cursor on a point in the matplotlib scatter plot and hit 'p' you'll see it in ds9.""")
461  elif reply[0] == "p":
462  import pdb
463  pdb.set_trace()
464  elif reply[0] == 'q':
465  sys.exit(1)
466  else:
467  break
468 
469  return Struct(selected=good)
def selectSources(self, sourceCat, matches=None, exposure=None)
Fit spatial kernel using approximate fluxes for candidates, and solving a linear system of equations...
int min
bool any(CoordinateExpr< N > const &expr) noexcept
Return true if any elements are true.
def compute_fwhmrange(fwhm, maxvar, minin, maxin, plot=dict(fwhmHistogram=False))
Definition: psfex.py:55
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)
bool strip
Definition: fits.cc:883