lsst.afw  16.0-61-g8d4b44b59+2
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 
35 import os
36 import sys
37 
38 import lsst.utils
39 import lsst.afw.detection as afwDetect
40 import lsst.geom
41 import lsst.afw.image as afwImage
42 import lsst.afw.math.mathLib as afwMath
43 import lsst.afw.display.ds9 as ds9
44 
45 import testSpatialCellLib
46 
47 try:
48  type(display)
49 except NameError:
50  display = False
51 
52 
53 def readImage(filename=None):
54  """Read an image and background subtract it"""
55  if not filename:
56  try:
57  afwDataDir = lsst.utils.getPackageDir("afwdata")
58  except Exception:
59  raise RuntimeError(
60  "You must provide a filename or setup afwdata to run these examples")
61 
62  filename = os.path.join(afwDataDir, "CFHT", "D4",
63  "cal-53535-i-797722_1.fits")
64 
65  bbox = lsst.geom.Box2I(lsst.geom.Point2I(270, 2530),
66  lsst.geom.Extent2I(512, 512))
67  else:
68  bbox = None
69 
70  mi = afwImage.MaskedImageF(filename, bbox=bbox, origin=afwImage.LOCAL)
71  mi.setXY0(lsst.geom.Point2I(0, 0))
72  #
73  # Subtract the background. We'd use a canned procedure, but that's in meas/utils/sourceDetection.py. We
74  # can't fix those pesky cosmic rays either, as that's in a dependent product (meas/algorithms) too
75  #
76  bctrl = afwMath.BackgroundControl(afwMath.Interpolate.NATURAL_SPLINE)
77  bctrl.setNxSample(int(mi.getWidth()/256) + 1)
78  bctrl.setNySample(int(mi.getHeight()/256) + 1)
79  sctrl = bctrl.getStatisticsControl()
80  sctrl.setNumSigmaClip(3.0)
81  sctrl.setNumIter(2)
82 
83  im = mi.getImage()
84  try:
85  backobj = afwMath.makeBackground(im, bctrl)
86  except Exception as e:
87  print(e, end=' ', file=sys.stderr)
88 
89  bctrl.setInterpStyle(afwMath.Interpolate.CONSTANT)
90  backobj = afwMath.makeBackground(im, bctrl)
91 
92  im -= backobj.getImageF()
93  #
94  # Find sources
95  #
96  threshold = afwDetect.Threshold(5, afwDetect.Threshold.STDEV)
97  npixMin = 5 # we didn't smooth
98  fs = afwDetect.FootprintSet(mi, threshold, "DETECTED", npixMin)
99  grow, isotropic = 1, False
100  fs = afwDetect.FootprintSet(fs, grow, isotropic)
101  fs.setMask(mi.getMask(), "DETECTED")
102 
103  return mi, fs
104 
105 
106 def SpatialCellSetDemo(filename=None):
107  """A demonstration of the use of a SpatialCellSet"""
108 
109  im, fs = readImage(filename)
110 
111  if display:
112  ds9.mtv(im, frame=0, title="Input")
113  #
114  # Create an (empty) SpatialCellSet
115  #
116  cellSet = afwMath.SpatialCellSet(lsst.geom.Box2I(lsst.geom.Point2I(0, 0), im.getDimensions()),
117  260, 200)
118 
119  if display:
120  for i in range(len(cellSet.getCellList())):
121  cell = cellSet.getCellList()[i]
122  ds9.line([(cell.getBBox().getMinX(), cell.getBBox().getMinY()),
123  (cell.getBBox().getMinX(), cell.getBBox().getMaxY()),
124  (cell.getBBox().getMaxX(), cell.getBBox().getMaxY()),
125  (cell.getBBox().getMaxX(), cell.getBBox().getMinY()),
126  (cell.getBBox().getMinX(), cell.getBBox().getMinY()),
127  ], frame=0)
128  ds9.dot(cell.getLabel(),
129  (cell.getBBox().getMinX() + cell.getBBox().getMaxX())/2,
130  (cell.getBBox().getMinY() + cell.getBBox().getMaxY())/2)
131  #
132  # Populate cellSet
133  #
134  for foot in fs.getFootprints():
135  bbox = foot.getBBox()
136  xc = (bbox.getMinX() + bbox.getMaxX())/2.0
137  yc = (bbox.getMinY() + bbox.getMaxY())/2.0
138  tc = testSpatialCellLib.ExampleCandidate(xc, yc, im, bbox)
139  cellSet.insertCandidate(tc)
140  #
141  # OK, the SpatialCellList is populated. Let's do something with it
142  #
143  visitor = testSpatialCellLib.ExampleCandidateVisitor()
144 
145  cellSet.visitCandidates(visitor)
146  print("There are %d candidates" % (visitor.getN()))
147 
148  ctypes = ["red", "yellow", "cyan", ]
149  for i in range(cellSet.getCellList().size()):
150  cell = cellSet.getCellList()[i]
151  cell.visitCandidates(visitor)
152 
153  j = 0
154  for cand in cell:
155  cand = cand
156 
157  w, h = cand.getBBox().getDimensions()
158  if w*h < 75:
159  # print "%d %5.2f %5.2f %d" % (i, cand.getXCenter(),
160  # cand.getYCenter(), w*h)
161  cand.setStatus(afwMath.SpatialCellCandidate.BAD)
162 
163  if display:
164  ds9.dot("o", cand.getXCenter(), cand.getYCenter(),
165  size=4, ctype=ctypes[i%len(ctypes)])
166  else:
167  if display:
168  ds9.dot("%s:%d" % (cand.getId(), j),
169  cand.getXCenter(), cand.getYCenter(), size=4, ctype=ctypes[i%len(ctypes)])
170  j += 1
171 
172  im = cand.getMaskedImage()
173  if 0 and display:
174  ds9.mtv(im, title="Candidate", frame=1)
175  #
176  # Now count the good and bad candidates
177  #
178  for i in range(len(cellSet.getCellList())):
179  cell = cellSet.getCellList()[i]
180  cell.visitCandidates(visitor)
181 
182  cell.setIgnoreBad(False) # include BAD in cell.size()
183  print("%s nobj=%d N_good=%d NPix_good=%d" %
184  (cell.getLabel(), cell.size(), visitor.getN(), visitor.getNPix()))
185 
186  cellSet.setIgnoreBad(True) # don't visit BAD candidates
187  cellSet.visitCandidates(visitor)
188  print("There are %d good candidates" % (visitor.getN()))
189 
190 
191 def run():
192  """Run the tests"""
193 
194  SpatialCellSetDemo()
195 
196 
197 if __name__ == "__main__":
198  run()