lsst.afw  14.0-23-g38c323faa+3
spatialCellExample.py
1 #!/usr/bin/env python
2 
3 #
4 # LSST Data Management System
5 # Copyright 2008, 2009, 2010 LSST Corporation.
6 #
7 # This product includes software developed by the
8 # LSST Project (http://www.lsst.org/).
9 #
10 # This program is free software: you can redistribute it and/or modify
11 # it under the terms of the GNU General Public License as published by
12 # the Free Software Foundation, either version 3 of the License, or
13 # (at your option) any later version.
14 #
15 # This program is distributed in the hope that it will be useful,
16 # but WITHOUT ANY WARRANTY; without even the implied warranty of
17 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 # GNU General Public License for more details.
19 #
20 # You should have received a copy of the LSST License Statement and
21 # the GNU General Public License along with this program. If not,
22 # see <http://www.lsstcorp.org/LegalNotices/>.
23 #
24 
25 """
26 An example using SpatialCells
27 
28 Run with:
29  python SpatialCellExample.py
30 or
31  python
32  >>> import SpatialCellExample; SpatialCellExample.run()
33 """
34 from __future__ import absolute_import, division, print_function
35 from builtins import range
36 
37 import os
38 import sys
39 
40 import lsst.utils
41 import lsst.afw.detection as afwDetect
42 import lsst.afw.image as afwImage
43 import lsst.afw.math.mathLib as afwMath
44 import lsst.afw.geom as afwGeom
45 import lsst.afw.display.ds9 as ds9
46 
47 import testSpatialCellLib
48 
49 try:
50  type(display)
51 except NameError:
52  display = False
53 
54 
55 def readImage(filename=None):
56  """Read an image and background subtract it"""
57  if not filename:
58  try:
59  afwDataDir = lsst.utils.getPackageDir("afwdata")
60  except Exception:
61  raise RuntimeError(
62  "You must provide a filename or setup afwdata to run these examples")
63 
64  filename = os.path.join(afwDataDir, "CFHT", "D4",
65  "cal-53535-i-797722_1.fits")
66 
67  bbox = afwGeom.Box2I(afwGeom.Point2I(270, 2530),
68  afwGeom.Extent2I(512, 512))
69  else:
70  bbox = None
71 
72  mi = afwImage.MaskedImageF(filename, bbox=bbox, origin=afwImage.LOCAL)
73  mi.setXY0(afwGeom.Point2I(0, 0))
74  #
75  # Subtract the background. We'd use a canned procedure, but that's in meas/utils/sourceDetection.py. We
76  # can't fix those pesky cosmic rays either, as that's in a dependent product (meas/algorithms) too
77  #
78  bctrl = afwMath.BackgroundControl(afwMath.Interpolate.NATURAL_SPLINE)
79  bctrl.setNxSample(int(mi.getWidth()/256) + 1)
80  bctrl.setNySample(int(mi.getHeight()/256) + 1)
81  sctrl = bctrl.getStatisticsControl()
82  sctrl.setNumSigmaClip(3.0)
83  sctrl.setNumIter(2)
84 
85  im = mi.getImage()
86  try:
87  backobj = afwMath.makeBackground(im, bctrl)
88  except Exception as e:
89  print(e, end=' ', file=sys.stderr)
90 
91  bctrl.setInterpStyle(afwMath.Interpolate.CONSTANT)
92  backobj = afwMath.makeBackground(im, bctrl)
93 
94  im -= backobj.getImageF()
95  #
96  # Find sources
97  #
98  threshold = afwDetect.Threshold(5, afwDetect.Threshold.STDEV)
99  npixMin = 5 # we didn't smooth
100  fs = afwDetect.FootprintSet(mi, threshold, "DETECTED", npixMin)
101  grow, isotropic = 1, False
102  fs = afwDetect.FootprintSet(fs, grow, isotropic)
103  fs.setMask(mi.getMask(), "DETECTED")
104 
105  return mi, fs
106 
107 
108 def SpatialCellSetDemo(filename=None):
109  """A demonstration of the use of a SpatialCellSet"""
110 
111  im, fs = readImage(filename)
112 
113  if display:
114  ds9.mtv(im, frame=0, title="Input")
115  #
116  # Create an (empty) SpatialCellSet
117  #
118  cellSet = afwMath.SpatialCellSet(afwGeom.Box2I(afwGeom.Point2I(0, 0), im.getDimensions()),
119  260, 200)
120 
121  if display:
122  for i in range(len(cellSet.getCellList())):
123  cell = cellSet.getCellList()[i]
124  ds9.line([(cell.getBBox().getMinX(), cell.getBBox().getMinY()),
125  (cell.getBBox().getMinX(), cell.getBBox().getMaxY()),
126  (cell.getBBox().getMaxX(), cell.getBBox().getMaxY()),
127  (cell.getBBox().getMaxX(), cell.getBBox().getMinY()),
128  (cell.getBBox().getMinX(), cell.getBBox().getMinY()),
129  ], frame=0)
130  ds9.dot(cell.getLabel(),
131  (cell.getBBox().getMinX() + cell.getBBox().getMaxX())/2,
132  (cell.getBBox().getMinY() + cell.getBBox().getMaxY())/2)
133  #
134  # Populate cellSet
135  #
136  for foot in fs.getFootprints():
137  bbox = foot.getBBox()
138  xc = (bbox.getMinX() + bbox.getMaxX())/2.0
139  yc = (bbox.getMinY() + bbox.getMaxY())/2.0
140  tc = testSpatialCellLib.ExampleCandidate(xc, yc, im, bbox)
141  cellSet.insertCandidate(tc)
142  #
143  # OK, the SpatialCellList is populated. Let's do something with it
144  #
145  visitor = testSpatialCellLib.ExampleCandidateVisitor()
146 
147  cellSet.visitCandidates(visitor)
148  print("There are %d candidates" % (visitor.getN()))
149 
150  ctypes = ["red", "yellow", "cyan", ]
151  for i in range(cellSet.getCellList().size()):
152  cell = cellSet.getCellList()[i]
153  cell.visitCandidates(visitor)
154 
155  j = 0
156  for cand in cell:
157  cand = cand
158 
159  w, h = cand.getBBox().getDimensions()
160  if w*h < 75:
161  # print "%d %5.2f %5.2f %d" % (i, cand.getXCenter(),
162  # cand.getYCenter(), w*h)
163  cand.setStatus(afwMath.SpatialCellCandidate.BAD)
164 
165  if display:
166  ds9.dot("o", cand.getXCenter(), cand.getYCenter(),
167  size=4, ctype=ctypes[i%len(ctypes)])
168  else:
169  if display:
170  ds9.dot("%s:%d" % (cand.getId(), j),
171  cand.getXCenter(), cand.getYCenter(), size=4, ctype=ctypes[i%len(ctypes)])
172  j += 1
173 
174  im = cand.getMaskedImage()
175  if 0 and display:
176  ds9.mtv(im, title="Candidate", frame=1)
177  #
178  # Now count the good and bad candidates
179  #
180  for i in range(len(cellSet.getCellList())):
181  cell = cellSet.getCellList()[i]
182  cell.visitCandidates(visitor)
183 
184  cell.setIgnoreBad(False) # include BAD in cell.size()
185  print("%s nobj=%d N_good=%d NPix_good=%d" %
186  (cell.getLabel(), cell.size(), visitor.getN(), visitor.getNPix()))
187 
188  cellSet.setIgnoreBad(True) # don't visit BAD candidates
189  cellSet.visitCandidates(visitor)
190  print("There are %d good candidates" % (visitor.getN()))
191 
192 
193 def run():
194  """Run the tests"""
195 
196  SpatialCellSetDemo()
197 
198 
199 if __name__ == "__main__":
200  run()