lsst.afw  14.0-49-g535656444+1
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, DEFAULT_HDU
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  if hdu == DEFAULT_HDU:
143  hdu = -1
144  else:
145  # we want to start at 0 (post RFC-304), but are about to increment
146  hdu -= 1
147 
148  fits = Fits(fileName, "r")
149  fits.setHdu(hdu + 1)
150  if fits.checkCompressedImagePhu():
151  hdu += 1
152 
153  while True:
154  hdu += 1
155 
156  md = dafBase.PropertyList()
157  try:
158  img = afwImage.ImageF(fileName, hdu, md)
159  hdu += 1
160  except FitsError:
161  break
162 
163  msk = afwImage.Mask(fileName, hdu)
164  hdu += 1
165  var = afwImage.ImageF(fileName, hdu)
166 
167  statsImage = afwImage.makeMaskedImage(img, msk, var)
168 
169  x0 = md.get("BKGD_X0")
170  y0 = md.get("BKGD_Y0")
171  width = md.get("BKGD_WIDTH")
172  height = md.get("BKGD_HEIGHT")
173  imageBBox = afwGeom.BoxI(afwGeom.PointI(
174  x0, y0), afwGeom.ExtentI(width, height))
175 
176  interpStyle = afwMath.Interpolate.Style(md.get("INTERPSTYLE"))
177  undersampleStyle = afwMath.UndersampleStyle(
178  md.get("UNDERSAMPLESTYLE"))
179 
180  # Older outputs won't have APPROX* settings. Provide alternative defaults.
181  # Note: Currently X- and Y-orders must be equal due to a limitation in
182  # math::Chebyshev1Function2. Setting approxOrderY = -1 is equivalent
183  # to saying approxOrderY = approxOrderX.
184  approxStyle = md.get("APPROXSTYLE") if "APPROXSTYLE" in md.names() \
185  else afwMath.ApproximateControl.UNKNOWN
186  approxStyle = afwMath.ApproximateControl.Style(approxStyle)
187  approxOrderX = md.get(
188  "APPROXORDERX") if "APPROXORDERX" in md.names() else 1
189  approxOrderY = md.get(
190  "APPROXORDERY") if "APPROXORDERY" in md.names() else -1
191  approxWeighting = md.get(
192  "APPROXWEIGHTING") if "APPROXWEIGHTING" in md.names() else True
193 
194  bkgd = afwMath.BackgroundMI(imageBBox, statsImage)
195  bctrl = bkgd.getBackgroundControl()
196  bctrl.setInterpStyle(interpStyle)
197  bctrl.setUndersampleStyle(undersampleStyle)
199  approxStyle, approxOrderX, approxOrderY, approxWeighting)
200  bctrl.setApproximateControl(actrl)
201  bgInfo = (bkgd, interpStyle, undersampleStyle, approxStyle,
202  approxOrderX, approxOrderY, approxWeighting)
203  self.append(bgInfo)
204 
205  return self
206 
207  def getImage(self):
208  """
209  Compute and return a full-resolution image from our list of
210  (Background, interpStyle, undersampleStyle)
211  """
212 
213  bkgdImage = None
214  for (bkgd, interpStyle, undersampleStyle, approxStyle,
215  approxOrderX, approxOrderY, approxWeighting) in self:
216  if not bkgdImage:
217  if approxStyle != afwMath.ApproximateControl.UNKNOWN:
218  bkgdImage = bkgd.getImageF()
219  else:
220  bkgdImage = bkgd.getImageF(interpStyle, undersampleStyle)
221  else:
222  if approxStyle != afwMath.ApproximateControl.UNKNOWN:
223  bkgdImage += bkgd.getImageF()
224  else:
225  bkgdImage += bkgd.getImageF(interpStyle, undersampleStyle)
226 
227  return bkgdImage
228 
229  def __reduce__(self):
230  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:298
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:1268
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:84
def readFits(fileName, hdu=0, flags=0)
A class to evaluate image background levels.
Definition: Background.h:444