lsst.afw  13.0-109-g62eb66483
backgroundList.py
Go to the documentation of this file.
1 from __future__ import absolute_import, division, print_function
2 from builtins import object
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 import os
25 import lsst.daf.base as dafBase
26 import lsst.afw.geom as afwGeom
27 import lsst.afw.image as afwImage
28 from lsst.afw.fits import FitsError, MemFileManager, reduceToFits, Fits
29 from . import mathLib as afwMath
30 
31 
32 class BackgroundList(object):
33  """A list-like class to contain a list of (afwMath.Background, interpStyle, undersampleStyle) tuples
34 
35 In deference to the deprecated-but-not-yet-removed Background.getImage() API, we also accept a single
36 afwMath.Background and extract the interpStyle and undersampleStyle from the as-used values
37  """
38 
39  def __init__(self, *args):
40  self._backgrounds = []
41  for a in args:
42  self.append(a)
43 
44  def __getitem__(self, *args):
45  """Return an item"""
46  #
47  # Set any previously-unknown Styles (they are set by bkgd.getImage())
48  #
49  for i, val in enumerate(self._backgrounds):
50  bkgd, interpStyle, undersampleStyle, approxStyle, \
51  approxOrderX, approxOrderY, approxWeighting = val
52  if interpStyle is None or undersampleStyle is None:
53  interpStyle = bkgd.getAsUsedInterpStyle()
54  undersampleStyle = bkgd.getAsUsedUndersampleStyle()
55  actrl = bkgd.getBackgroundControl().getApproximateControl()
56  approxStyle = actrl.getStyle()
57  approxOrderX = actrl.getOrderX()
58  approxOrderY = actrl.getOrderY()
59  approxWeighting = actrl.getWeighting()
60  self._backgrounds[i] = (bkgd, interpStyle, undersampleStyle,
61  approxStyle, approxOrderX, approxOrderY, approxWeighting)
62  #
63  # And return what they wanted
64  #
65  return self._backgrounds.__getitem__(*args)
66 
67  def __len__(self, *args):
68  return self._backgrounds.__len__(*args)
69 
70  def append(self, val):
71  try:
72  bkgd, interpStyle, undersampleStyle, approxStyle, \
73  approxOrderX, approxOrderY, approxWeighting = val
74  except TypeError:
75  bkgd = val
76  interpStyle = None
77  undersampleStyle = None
78  approxStyle = None
79  approxOrderX = None
80  approxOrderY = None
81  approxWeighting = None
82 
83  bgInfo = (bkgd, interpStyle, undersampleStyle, approxStyle,
84  approxOrderX, approxOrderY, approxWeighting)
85  self._backgrounds.append(bgInfo)
86 
87  def clone(self):
88  """Return a shallow copy
89 
90  Shallow copies do not share backgrounds that are appended after copying,
91  but do share changes to contained background objects.
92  """
93  return BackgroundList(*self)
94 
95  def writeFits(self, fileName, flags=0):
96  """Save our list of Backgrounds to a file
97  @param fileName FITS file to write
98  @param flags Flags to control details of writing; currently unused,
99  but present for consistency with
100  afw.table.BaseCatalog.writeFits.
101  """
102 
103  for i, bkgd in enumerate(self):
104  (bkgd, interpStyle, undersampleStyle, approxStyle, approxOrderX, approxOrderY,
105  approxWeighting) = bkgd
106 
107  statsImage = bkgd.getStatsImage()
108 
109  md = dafBase.PropertyList()
110  md.set("INTERPSTYLE", int(interpStyle))
111  md.set("UNDERSAMPLESTYLE", int(undersampleStyle))
112  md.set("APPROXSTYLE", int(approxStyle))
113  md.set("APPROXORDERX", approxOrderX)
114  md.set("APPROXORDERY", approxOrderY)
115  md.set("APPROXWEIGHTING", approxWeighting)
116  bbox = bkgd.getImageBBox()
117  md.set("BKGD_X0", bbox.getMinX())
118  md.set("BKGD_Y0", bbox.getMinY())
119  md.set("BKGD_WIDTH", bbox.getWidth())
120  md.set("BKGD_HEIGHT", bbox.getHeight())
121 
122  statsImage.getImage().writeFits(fileName, md, "w" if i == 0 else "a")
123  statsImage.getMask().writeFits(fileName, md, "a")
124  statsImage.getVariance().writeFits(fileName, md, "a")
125 
126  @staticmethod
127  def readFits(fileName, hdu=0, flags=0):
128  """Read a our list of Backgrounds from a file
129  @param fileName FITS file to read
130  @param hdu First Header/Data Unit to attempt to read from
131  @param flags Flags to control details of reading; currently unused,
132  but present for consistency with
133  afw.table.BaseCatalog.readFits.
134 
135  See also getImage()
136  """
137  if not isinstance(fileName, MemFileManager) and not os.path.exists(fileName):
138  raise RuntimeError("File not found: %s" % fileName)
139 
140  self = BackgroundList()
141 
142  INT_MIN = -(1 << 31)
143  if hdu == INT_MIN:
144  hdu = -1
145  else:
146  # we want to start at 0 (post RFC-304), but are about to increment
147  hdu -= 1
148 
149  fits = Fits(fileName, "r")
150  fits.setHdu(hdu + 1)
151  if fits.checkCompressedImagePhu():
152  hdu += 1
153 
154  while True:
155  hdu += 1
156 
157  md = dafBase.PropertyList()
158  try:
159  img = afwImage.ImageF(fileName, hdu, md)
160  hdu += 1
161  except FitsError:
162  break
163 
164  msk = afwImage.Mask(fileName, hdu)
165  hdu += 1
166  var = afwImage.ImageF(fileName, hdu)
167 
168  statsImage = afwImage.makeMaskedImage(img, msk, var)
169 
170  x0 = md.get("BKGD_X0")
171  y0 = md.get("BKGD_Y0")
172  width = md.get("BKGD_WIDTH")
173  height = md.get("BKGD_HEIGHT")
174  imageBBox = afwGeom.BoxI(afwGeom.PointI(
175  x0, y0), afwGeom.ExtentI(width, height))
176 
177  interpStyle = afwMath.Interpolate.Style(md.get("INTERPSTYLE"))
178  undersampleStyle = afwMath.UndersampleStyle(
179  md.get("UNDERSAMPLESTYLE"))
180 
181  # Older outputs won't have APPROX* settings. Provide alternative defaults.
182  # Note: Currently X- and Y-orders must be equal due to a limitation in
183  # math::Chebyshev1Function2. Setting approxOrderY = -1 is equivalent
184  # to saying approxOrderY = approxOrderX.
185  approxStyle = md.get("APPROXSTYLE") if "APPROXSTYLE" in md.names() \
186  else afwMath.ApproximateControl.UNKNOWN
187  approxStyle = afwMath.ApproximateControl.Style(approxStyle)
188  approxOrderX = md.get(
189  "APPROXORDERX") if "APPROXORDERX" in md.names() else 1
190  approxOrderY = md.get(
191  "APPROXORDERY") if "APPROXORDERY" in md.names() else -1
192  approxWeighting = md.get(
193  "APPROXWEIGHTING") if "APPROXWEIGHTING" in md.names() else True
194 
195  bkgd = afwMath.BackgroundMI(imageBBox, statsImage)
196  bctrl = bkgd.getBackgroundControl()
197  bctrl.setInterpStyle(interpStyle)
198  bctrl.setUndersampleStyle(undersampleStyle)
200  approxStyle, approxOrderX, approxOrderY, approxWeighting)
201  bctrl.setApproximateControl(actrl)
202  bgInfo = (bkgd, interpStyle, undersampleStyle, approxStyle,
203  approxOrderX, approxOrderY, approxWeighting)
204  self.append(bgInfo)
205 
206  return self
207 
208  def getImage(self):
209  """
210  Compute and return a full-resolution image from our list of
211  (Background, interpStyle, undersampleStyle)
212  """
213 
214  bkgdImage = None
215  for (bkgd, interpStyle, undersampleStyle, approxStyle,
216  approxOrderX, approxOrderY, approxWeighting) in self:
217  if not bkgdImage:
218  if approxStyle != afwMath.ApproximateControl.UNKNOWN:
219  bkgdImage = bkgd.getImageF()
220  else:
221  bkgdImage = bkgd.getImageF(interpStyle, undersampleStyle)
222  else:
223  if approxStyle != afwMath.ApproximateControl.UNKNOWN:
224  bkgdImage += bkgd.getImageF()
225  else:
226  bkgdImage += bkgd.getImageF(interpStyle, undersampleStyle)
227 
228  return bkgdImage
229 
230  def __reduce__(self):
231  return reduceToFits(self)
def writeFits(self, fileName, flags=0)
A simple struct that combines the two arguments that must be passed to most cfitsio routines and cont...
Definition: fits.h:279
MaskedImage< ImagePixelT, MaskPixelT, VariancePixelT > * makeMaskedImage(typename std::shared_ptr< Image< ImagePixelT >> image, typename std::shared_ptr< Mask< MaskPixelT >> mask=Mask< MaskPixelT >(), typename std::shared_ptr< Image< VariancePixelT >> variance=Image< VariancePixelT >())
A function to return a MaskedImage of the correct type (cf.
Definition: MaskedImage.h:1267
An integer coordinate rectangle.
Definition: Box.h:55
Control how to make an approximation.
Definition: Approximate.h:50
Represent a 2-dimensional array of bitmask pixels.
Definition: Mask.h:83
def readFits(fileName, hdu=0, flags=0)
A class to evaluate image background levels.
Definition: Background.h:436