lsst.meas.algorithms g8e3bb8577d+ea375a93e1
Loading...
Searching...
No Matches
objectSizeStarSelector.py
Go to the documentation of this file.
1# This file is part of meas_algorithms.
2#
3# Developed for the LSST Data Management System.
4# This product includes software developed by the LSST Project
5# (https://www.lsst.org).
6# See the COPYRIGHT file at the top-level directory of this distribution
7# for details of code ownership.
8#
9# This program is free software: you can redistribute it and/or modify
10# it under the terms of the GNU General Public License as published by
11# the Free Software Foundation, either version 3 of the License, or
12# (at your option) any later version.
13#
14# This program is distributed in the hope that it will be useful,
15# but WITHOUT ANY WARRANTY; without even the implied warranty of
16# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17# GNU General Public License for more details.
18#
19# You should have received a copy of the GNU General Public License
20# along with this program. If not, see <https://www.gnu.org/licenses/>.
21
22__all__ = ["ObjectSizeStarSelectorConfig", "ObjectSizeStarSelectorTask",
23 "ObjectSizeNoSourcesError", "ObjectSizeNoGoodSourcesError"]
24
25import sys
26
27import numpy
28import warnings
29from functools import reduce
30
31from lsst.utils.logging import getLogger
32from lsst.pipe.base import Struct, AlgorithmError
33import lsst.geom
34from lsst.afw.cameraGeom import PIXELS, TAN_PIXELS
35import lsst.afw.geom as afwGeom
36import lsst.pex.config as pexConfig
37import lsst.afw.display as afwDisplay
38from .sourceSelector import BaseSourceSelectorTask, sourceSelectorRegistry
39
40afwDisplay.setDefaultMaskTransparency(75)
41
42_LOG = getLogger(__name__)
43
44
45class ObjectSizeNoSourcesError(AlgorithmError):
46 """Raised if no sources were supplied in the input catalog."""
47
48 def __init__(self) -> None:
49 super().__init__("Input catalog for source selection is empty.")
50
51
52class ObjectSizeNoGoodSourcesError(AlgorithmError):
53 """Raised if no good sources were available after applying configured
54 selection criteria.
55 """
56
57 def __init__(self, n_input_sources) -> None:
58 self._n_available = n_input_sources
59 super().__init__(f"No good star candidates out of {n_input_sources} input sources.")
60
61 @property
62 def metadata(self) -> dict:
63 return {
64 "n_input_sources": self._n_available,
65 }
66
67
68class ObjectSizeStarSelectorConfig(BaseSourceSelectorTask.ConfigClass):
69 doFluxLimit = pexConfig.Field(
70 doc="Apply flux limit to Psf Candidate selection?",
71 dtype=bool,
72 default=False,
73 )
74 fluxMin = pexConfig.Field(
75 doc="Minimum flux value for good Psf Candidates.",
76 dtype=float,
77 default=12500.0,
78 check=lambda x: x >= 0.0,
79 )
80 fluxMax = pexConfig.Field(
81 doc="Maximum flux value for good Psf Candidates (ignored if == 0).",
82 dtype=float,
83 default=0.0,
84 check=lambda x: x >= 0.0,
85 )
86 doSignalToNoiseLimit = pexConfig.Field(
87 doc="Apply signal-to-noise (i.e. flux/fluxErr) limit to Psf Candidate selection?",
88 dtype=bool,
89 default=True,
90 )
91 # Note that the current default is conditioned on the detection thresholds
92 # set in the characterizeImage setDefaults function for the measurePsf
93 # stage.
94 signalToNoiseMin = pexConfig.Field(
95 doc="Minimum signal-to-noise for good Psf Candidates "
96 "(value should take into consideration the detection thresholds "
97 "set for the catalog of interest).",
98 dtype=float,
99 default=50.0,
100 check=lambda x: x >= 0.0,
101 )
102 signalToNoiseMax = pexConfig.Field(
103 doc="Maximum signal-to-noise for good Psf Candidates (ignored if == 0).",
104 dtype=float,
105 default=0.0,
106 check=lambda x: x >= 0.0,
107 )
108 widthMin = pexConfig.Field(
109 doc="Minimum width to include in histogram.",
110 dtype=float,
111 default=0.9,
112 check=lambda x: x >= 0.0,
113 )
114 widthMax = pexConfig.Field(
115 doc="Maximum width to include in histogram.",
116 dtype=float,
117 default=10.0,
118 check=lambda x: x >= 0.0,
119 )
120 sourceFluxField = pexConfig.Field(
121 doc="Name of field in Source to use for flux measurement.",
122 dtype=str,
123 default="base_PsfFlux_instFlux",
124 )
125 widthStdAllowed = pexConfig.Field(
126 doc="Standard deviation of width allowed to be interpreted as good stars.",
127 dtype=float,
128 default=0.15,
129 check=lambda x: x >= 0.0,
130 )
131 nSigmaClip = pexConfig.Field(
132 doc="Keep objects within this many sigma of cluster 0's median.",
133 dtype=float,
134 default=2.0,
135 check=lambda x: x >= 0.0,
136 )
137 badFlags = pexConfig.ListField(
138 doc="List of flags which cause a source to be rejected as bad.",
139 dtype=str,
140 default=[
141 "base_PixelFlags_flag_edge",
142 "base_PixelFlags_flag_nodata",
143 "base_PixelFlags_flag_interpolatedCenter",
144 "base_PixelFlags_flag_saturatedCenter",
145 "base_PixelFlags_flag_crCenter",
146 "base_PixelFlags_flag_bad",
147 "base_PixelFlags_flag_interpolated",
148 ],
149 )
150
151 def validate(self):
152 BaseSourceSelectorTask.ConfigClass.validate(self)
153 if self.widthMin > self.widthMax:
154 msg = f"widthMin ({self.widthMin}) > widthMax ({self.widthMax})"
155 raise pexConfig.FieldValidationError(ObjectSizeStarSelectorConfig.widthMin, self, msg)
156
157
159 """A class to handle key strokes with matplotlib displays.
160 """
161
162 def __init__(self, axes, xs, ys, x, y, frames=[0]):
163 self.axes = axes
164 self.xs = xs
165 self.ys = ys
166 self.x = x
167 self.y = y
168 self.frames = frames
169
170 self.cid = self.axes.figure.canvas.mpl_connect('key_press_event', self)
171
172 def __call__(self, ev):
173 if ev.inaxes != self.axes:
174 return
175
176 if ev.key and ev.key in ("p"):
177 dist = numpy.hypot(self.xs - ev.xdata, self.ys - ev.ydata)
178 dist[numpy.where(numpy.isnan(dist))] = 1e30
179
180 which = numpy.where(dist == min(dist))
181
182 x = self.x[which][0]
183 y = self.y[which][0]
184 for frame in self.frames:
185 disp = afwDisplay.Display(frame=frame)
186 disp.pan(x, y)
187 disp.flush()
188 else:
189 pass
190
191
192def _assignClusters(yvec, centers):
193 """Return a vector of centerIds based on their distance to the centers.
194 """
195 assert len(centers) > 0
196
197 minDist = numpy.nan*numpy.ones_like(yvec)
198 clusterId = numpy.empty_like(yvec)
199 clusterId.dtype = int # zeros_like(..., dtype=int) isn't in numpy 1.5
200 dbl = _LOG.getChild("_assignClusters")
201 dbl.setLevel(dbl.INFO)
202
203 # Make sure we are logging aall numpy warnings...
204 oldSettings = numpy.seterr(all="warn")
205 with warnings.catch_warnings(record=True) as w:
206 warnings.simplefilter("always")
207 for i, mean in enumerate(centers):
208 dist = abs(yvec - mean)
209 if i == 0:
210 update = dist == dist # True for all points
211 else:
212 update = dist < minDist
213 if w: # Only do if w is not empty i.e. contains a warning message
214 dbl.trace(str(w[-1]))
215
216 minDist[update] = dist[update]
217 clusterId[update] = i
218 numpy.seterr(**oldSettings)
219
220 return clusterId
221
222
223def _kcenters(yvec, nCluster, useMedian=False, widthStdAllowed=0.15):
224 """A classic k-means algorithm, clustering yvec into nCluster clusters
225
226 Return the set of centres, and the cluster ID for each of the points
227
228 If useMedian is true, use the median of the cluster as its centre, rather than
229 the traditional mean
230
231 Serge Monkewitz points out that there other (maybe smarter) ways of seeding the means:
232 "e.g. why not use the Forgy or random partition initialization methods"
233 however, the approach adopted here seems to work well for the particular sorts of things
234 we're clustering in this application
235 """
236
237 assert nCluster > 0
238
239 mean0 = sorted(yvec)[len(yvec)//10] # guess
240 delta = mean0 * widthStdAllowed * 2.0
241 centers = mean0 + delta * numpy.arange(nCluster)
242
243 func = numpy.median if useMedian else numpy.mean
244
245 clusterId = numpy.zeros_like(yvec) - 1 # which cluster the points are assigned to
246 clusterId.dtype = int # zeros_like(..., dtype=int) isn't in numpy 1.5
247 while True:
248 oclusterId = clusterId
249 clusterId = _assignClusters(yvec, centers)
250
251 if numpy.all(clusterId == oclusterId):
252 break
253
254 for i in range(nCluster):
255 # Only compute func if some points are available; otherwise, default to NaN.
256 pointsInCluster = (clusterId == i)
257 if numpy.any(pointsInCluster):
258 centers[i] = func(yvec[pointsInCluster])
259 else:
260 centers[i] = numpy.nan
261
262 return centers, clusterId
263
264
265def _improveCluster(yvec, centers, clusterId, nsigma=2.0, nIteration=10, clusterNum=0, widthStdAllowed=0.15):
266 """Improve our estimate of one of the clusters (clusterNum) by sigma-clipping around its median.
267 """
268
269 nMember = sum(clusterId == clusterNum)
270 if nMember < 5: # can't compute meaningful interquartile range, so no chance of improvement
271 return clusterId
272 for iter in range(nIteration):
273 old_nMember = nMember
274
275 inCluster0 = clusterId == clusterNum
276 yv = yvec[inCluster0]
277
278 centers[clusterNum] = numpy.median(yv)
279 stdev = numpy.std(yv)
280
281 syv = sorted(yv)
282 stdev_iqr = 0.741*(syv[int(0.75*nMember)] - syv[int(0.25*nMember)])
283 median = syv[int(0.5*nMember)]
284
285 sd = stdev if stdev < stdev_iqr else stdev_iqr
286
287 if False:
288 print("sigma(iqr) = %.3f, sigma = %.3f" % (stdev_iqr, numpy.std(yv)))
289 newCluster0 = abs(yvec - centers[clusterNum]) < nsigma*sd
290 clusterId[numpy.logical_and(inCluster0, newCluster0)] = clusterNum
291 clusterId[numpy.logical_and(inCluster0, numpy.logical_not(newCluster0))] = -1
292
293 nMember = sum(clusterId == clusterNum)
294 # 'sd < widthStdAllowed * median' prevents too much rejections
295 if nMember == old_nMember or sd < widthStdAllowed * median:
296 break
297
298 return clusterId
299
300
301def plot(mag, width, centers, clusterId, marker="o", markersize=2, markeredgewidth=0, ltype='-',
302 magType="model", clear=True):
303
304 log = _LOG.getChild("plot")
305 try:
306 import matplotlib.pyplot as plt
307 except ImportError as e:
308 log.warning("Unable to import matplotlib: %s", e)
309 return
310
311 try:
312 fig
313 except NameError:
314 fig = plt.figure()
315 else:
316 if clear:
317 fig.clf()
318
319 axes = fig.add_axes((0.1, 0.1, 0.85, 0.80))
320
321 xmin = sorted(mag)[int(0.05*len(mag))]
322 xmax = sorted(mag)[int(0.95*len(mag))]
323
324 axes.set_xlim(-17.5, -13)
325 axes.set_xlim(xmin - 0.1*(xmax - xmin), xmax + 0.1*(xmax - xmin))
326 axes.set_ylim(0, 10)
327
328 colors = ["r", "g", "b", "c", "m", "k", ]
329 for k, mean in enumerate(centers):
330 if k == 0:
331 axes.plot(axes.get_xlim(), (mean, mean,), "k%s" % ltype)
332
333 li = (clusterId == k)
334 axes.plot(mag[li], width[li], marker, markersize=markersize, markeredgewidth=markeredgewidth,
335 color=colors[k % len(colors)])
336
337 li = (clusterId == -1)
338 axes.plot(mag[li], width[li], marker, markersize=markersize, markeredgewidth=markeredgewidth,
339 color='k')
340
341 if clear:
342 axes.set_xlabel("Instrumental %s mag" % magType)
343 axes.set_ylabel(r"$\sqrt{(I_{xx} + I_{yy})/2}$")
344
345 return fig
346
347
348@pexConfig.registerConfigurable("objectSize", sourceSelectorRegistry)
350 """A star selector that looks for a cluster of small objects in a
351 size-magnitude plot, typically to select stars for PSF estimation.
352 """
353
354 ConfigClass = ObjectSizeStarSelectorConfig
355 usesMatches = False # selectStars does not use its matches argument
356
357 def selectSources(self, sourceCat, matches=None, exposure=None):
358 """Return a selection of PSF candidates that represent likely stars.
359
360 A list of PSF candidates may be used by a PSF fitter to construct a PSF.
361
362 Parameters
363 ----------
364 sourceCat : `lsst.afw.table.SourceCatalog`
365 Catalog of sources to select from.
366 This catalog must be contiguous in memory.
367 matches : `list` of `lsst.afw.table.ReferenceMatch` or None
368 Ignored in this SourceSelector.
369 exposure : `lsst.afw.image.Exposure` or None
370 The exposure the catalog was built from; used to get the detector
371 to transform to TanPix, and for debug display.
372
373 Returns
374 -------
375 struct : `lsst.pipe.base.Struct`
376 The struct contains the following data:
377
378 ``selected``
379 Boolean array of sources that were selected, same length as
380 sourceCat. (`numpy.ndarray` of `bool`)
381 """
382 if len(sourceCat) == 0:
383 raise ObjectSizeNoSourcesError
384
385 import lsstDebug
386 display = lsstDebug.Info(__name__).display
387 displayExposure = lsstDebug.Info(__name__).displayExposure # display the Exposure + spatialCells
388 plotMagSize = lsstDebug.Info(__name__).plotMagSize # display the magnitude-size relation
389 dumpData = lsstDebug.Info(__name__).dumpData # dump data to pickle file?
390
391 detector = None
392 pixToTanPix = None
393 if exposure:
394 detector = exposure.getDetector()
395 if detector:
396 pixToTanPix = detector.getTransform(PIXELS, TAN_PIXELS)
397 #
398 # Look at the distribution of stars in the magnitude-size plane
399 #
400 flux = sourceCat[self.config.sourceFluxField]
401 fluxErr = sourceCat[self.config.sourceFluxField + "Err"]
402
403 xx = numpy.empty(len(sourceCat))
404 xy = numpy.empty_like(xx)
405 yy = numpy.empty_like(xx)
406 for i, source in enumerate(sourceCat):
407 Ixx, Ixy, Iyy = source.getIxx(), source.getIxy(), source.getIyy()
408 if pixToTanPix:
409 p = lsst.geom.Point2D(source.getX(), source.getY())
410 linTransform = afwGeom.linearizeTransform(pixToTanPix, p).getLinear()
411 m = afwGeom.Quadrupole(Ixx, Iyy, Ixy)
412 m.transform(linTransform)
413 Ixx, Iyy, Ixy = m.getIxx(), m.getIyy(), m.getIxy()
414
415 xx[i], xy[i], yy[i] = Ixx, Ixy, Iyy
416
417 width = numpy.sqrt(0.5*(xx + yy))
418 with numpy.errstate(invalid="ignore"): # suppress NAN warnings
419 bad = reduce(lambda x, y: numpy.logical_or(x, sourceCat[y]), self.config.badFlags, False)
420 bad = numpy.logical_or(bad, numpy.logical_not(numpy.isfinite(width)))
421 bad = numpy.logical_or(bad, numpy.logical_not(numpy.isfinite(flux)))
422 if self.config.doFluxLimit:
423 bad = numpy.logical_or(bad, flux < self.config.fluxMin)
424 if self.config.fluxMax > 0:
425 bad = numpy.logical_or(bad, flux > self.config.fluxMax)
426 if self.config.doSignalToNoiseLimit:
427 bad = numpy.logical_or(bad, flux/fluxErr < self.config.signalToNoiseMin)
428 if self.config.signalToNoiseMax > 0:
429 bad = numpy.logical_or(bad, flux/fluxErr > self.config.signalToNoiseMax)
430 bad = numpy.logical_or(bad, width < self.config.widthMin)
431 bad = numpy.logical_or(bad, width > self.config.widthMax)
432 good = numpy.logical_not(bad)
433
434 if not numpy.any(good):
435 raise ObjectSizeNoGoodSourcesError(n_input_sources=len(sourceCat))
436
437 mag = -2.5*numpy.log10(flux[good])
438 width = width[good]
439 #
440 # Look for the maximum in the size histogram, then search upwards for the minimum that separates
441 # the initial peak (of, we presume, stars) from the galaxies
442 #
443 if dumpData:
444 import os
445 import pickle as pickle
446 _ii = 0
447 while True:
448 pickleFile = os.path.expanduser(os.path.join("~", "widths-%d.pkl" % _ii))
449 if not os.path.exists(pickleFile):
450 break
451 _ii += 1
452
453 with open(pickleFile, "wb") as fd:
454 pickle.dump(mag, fd, -1)
455 pickle.dump(width, fd, -1)
456
457 centers, clusterId = _kcenters(width, nCluster=4, useMedian=True,
458 widthStdAllowed=self.config.widthStdAllowed)
459
460 if display and plotMagSize:
461 fig = plot(mag, width, centers, clusterId,
462 magType=self.config.sourceFluxField.split(".")[-1].title(),
463 marker="+", markersize=3, markeredgewidth=None, ltype=':', clear=True)
464 else:
465 fig = None
466
467 clusterId = _improveCluster(width, centers, clusterId,
468 nsigma=self.config.nSigmaClip,
469 widthStdAllowed=self.config.widthStdAllowed)
470
471 if display and plotMagSize:
472 plot(mag, width, centers, clusterId, marker="x", markersize=3, markeredgewidth=None, clear=False)
473
474 stellar = (clusterId == 0)
475 #
476 # We know enough to plot, if so requested
477 #
478 frame = 0
479
480 if fig:
481 if display and displayExposure:
482 disp = afwDisplay.Display(frame=frame)
483 disp.mtv(exposure.getMaskedImage(), title="PSF candidates")
484
485 global eventHandler
486 eventHandler = EventHandler(fig.get_axes()[0], mag, width,
487 sourceCat.getX()[good], sourceCat.getY()[good], frames=[frame])
488
489 fig.show()
490
491 while True:
492 try:
493 reply = input("continue? [c h(elp) q(uit) p(db)] ").strip()
494 except EOFError:
495 reply = None
496 if not reply:
497 reply = "c"
498
499 if reply:
500 if reply[0] == "h":
501 print("""\
502 We cluster the points; red are the stellar candidates and the other colours are other clusters.
503 Points labelled + are rejects from the cluster (only for cluster 0).
504
505 At this prompt, you can continue with almost any key; 'p' enters pdb, and 'h' prints this text
506
507 If displayExposure is true, you can put the cursor on a point and hit 'p' to see it in the
508 image display.
509 """)
510 elif reply[0] == "p":
511 import pdb
512 pdb.set_trace()
513 elif reply[0] == 'q':
514 sys.exit(1)
515 else:
516 break
517
518 if display and displayExposure:
519 mi = exposure.getMaskedImage()
520 with disp.Buffering():
521 for i, source in enumerate(sourceCat):
522 if good[i]:
523 ctype = afwDisplay.GREEN # star candidate
524 else:
525 ctype = afwDisplay.RED # not star
526
527 disp.dot("+", source.getX() - mi.getX0(), source.getY() - mi.getY0(), ctype=ctype)
528
529 # stellar only applies to good==True objects
530 mask = good == True # noqa (numpy bool comparison): E712
531 good[mask] = stellar
532
533 return Struct(selected=good)
_improveCluster(yvec, centers, clusterId, nsigma=2.0, nIteration=10, clusterNum=0, widthStdAllowed=0.15)
_kcenters(yvec, nCluster, useMedian=False, widthStdAllowed=0.15)
plot(mag, width, centers, clusterId, marker="o", markersize=2, markeredgewidth=0, ltype='-', magType="model", clear=True)