lsst.afw  14.0-49-g535656444+1
utils.py
Go to the documentation of this file.
1 #
2 # LSST Data Management System
3 # Copyright 2008, 2009, 2010 LSST Corporation.
4 #
5 # This product includes software developed by the
6 # LSST Project (http://www.lsst.org/).
7 #
8 # This program is free software: you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation, either version 3 of the License, or
11 # (at your option) any later version.
12 #
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
17 #
18 # You should have received a copy of the LSST License Statement and
19 # the GNU General Public License along with this program. If not,
20 # see <http://www.lsstcorp.org/LegalNotices/>.
21 #
22 
23 """
24 Support for cameraGeom
25 """
26 from __future__ import absolute_import, division, print_function
27 from builtins import zip
28 from builtins import next
29 from builtins import str
30 from builtins import range
31 from builtins import object
32 import math
33 import numpy
34 
35 import lsst.afw.geom as afwGeom
36 import lsst.afw.image as afwImage
37 import lsst.afw.math as afwMath
38 import lsst.daf.base as dafBase
39 
40 from .rotateBBoxBy90 import rotateBBoxBy90
41 from .assembleImage import assembleAmplifierImage, assembleAmplifierRawImage
42 from .cameraGeomLib import FIELD_ANGLE, FOCAL_PLANE
43 from lsst.afw.display.utils import _getDisplayFromDisplayOrFrame
44 
45 import lsst.afw.display as afwDisplay
46 import lsst.afw.display.utils as displayUtils
47 
48 
49 def prepareWcsData(wcs, amp, isTrimmed=True):
50  """!Put Wcs from an Amp image into CCD coordinates
51 
52  @param[in] wcs WCS object
53  @param[in] amp Amp object to use
54  @param[in] isTrimmed Is the image to which the WCS refers trimmed of non-imaging pixels?
55  @returns modified wcs
56  """
57  if not amp.getHasRawInfo():
58  raise RuntimeError("Cannot modify wcs without raw amp information")
59  if isTrimmed:
60  ampBox = amp.getRawDataBBox()
61  else:
62  ampBox = amp.getRawBBox()
63  ampCenter = afwGeom.Point2D(ampBox.getDimensions() / 2.0)
64  wcs = afwGeom.makeFlippedWcs(wcs, amp.getRawFlipX(), amp.getRawFlipY(), ampCenter)
65  # Shift WCS for trimming
66  if isTrimmed:
67  trim_shift = ampBox.getMin() - amp.getBBox().getMin()
68  wcs = wcs.copyAtShiftedPixelOrigin(afwGeom.Extent2D(-trim_shift.getX(), -trim_shift.getY()))
69  # Account for shift of amp data in larger ccd matrix
70  offset = amp.getRawXYOffset()
71  return wcs.copyAtShiftedPixelOrigin(afwGeom.Extent2D(offset))
72 
73 
74 def plotFocalPlane(camera, fieldSizeDeg_x=0, fieldSizeDeg_y=None, dx=0.1, dy=0.1, figsize=(10., 10.),
75  useIds=False, showFig=True, savePath=None):
76  """!Make a plot of the focal plane along with a set points that sample the field of view
77 
78  @param[in] camera a camera object
79  @param[in] fieldSizeDeg_x Amount of the field to sample in x in degrees
80  @param[in] fieldSizeDeg_y Amount of the field to sample in y in degrees
81  @param[in] dx Spacing of sample points in x in degrees
82  @param[in] dy Spacing of sample points in y in degrees
83  @param[in] figsize matplotlib style tuple indicating the size of the figure in inches
84  @param[in] useIds Label detectors by name, not id
85  @param[in] showFig Display the figure on the screen?
86  @param[in] savePath If not None, save a copy of the figure to this name
87  """
88  try:
89  from matplotlib.patches import Polygon
90  from matplotlib.collections import PatchCollection
91  import matplotlib.pyplot as plt
92  except ImportError:
93  raise ImportError(
94  "Can't run plotFocalPlane: matplotlib has not been set up")
95 
96  if fieldSizeDeg_x:
97  if fieldSizeDeg_y is None:
98  fieldSizeDeg_y = fieldSizeDeg_x
99 
100  field_gridx, field_gridy = numpy.meshgrid(numpy.arange(0., fieldSizeDeg_x+dx, dx) - fieldSizeDeg_x/2.,
101  numpy.arange(0., fieldSizeDeg_y+dy, dy) - fieldSizeDeg_y/2.)
102  field_gridx, field_gridy = field_gridx.flatten(), field_gridy.flatten()
103  else:
104  field_gridx, field_gridy = [], []
105 
106  xs = []
107  ys = []
108  pcolors = []
109  for pos in zip(field_gridx, field_gridy):
110  posRad = afwGeom.Point2D(math.radians(pos[0]), math.radians(pos[1]))
111  cp = camera.makeCameraPoint(posRad, FIELD_ANGLE)
112  ncp = camera.transform(cp, FOCAL_PLANE)
113  xs.append(ncp.getPoint().getX())
114  ys.append(ncp.getPoint().getY())
115  dets = camera.findDetectors(cp)
116  if len(dets) > 0:
117  pcolors.append('w')
118  else:
119  pcolors.append('k')
120 
121  colorMap = {0: 'b', 1: 'y', 2: 'g', 3: 'r'}
122 
123  patches = []
124  colors = []
125  plt.figure(figsize=figsize)
126  ax = plt.gca()
127  xvals = []
128  yvals = []
129  for det in camera:
130  corners = [(c.getX(), c.getY()) for c in det.getCorners(FOCAL_PLANE)]
131  for corner in corners:
132  xvals.append(corner[0])
133  yvals.append(corner[1])
134  colors.append(colorMap[det.getType()])
135  patches.append(Polygon(corners, True))
136  center = det.getOrientation().getFpPosition()
137  ax.text(center.getX(), center.getY(), det.getId() if useIds else det.getName(),
138  horizontalalignment='center', size=6)
139 
140  patchCollection = PatchCollection(patches, alpha=0.6, facecolor=colors)
141  ax.add_collection(patchCollection)
142  ax.scatter(xs, ys, s=10, alpha=.7, linewidths=0., c=pcolors)
143  ax.set_xlim(min(xvals) - abs(0.1*min(xvals)),
144  max(xvals) + abs(0.1*max(xvals)))
145  ax.set_ylim(min(yvals) - abs(0.1*min(yvals)),
146  max(yvals) + abs(0.1*max(yvals)))
147  ax.set_xlabel('Focal Plane X (mm)')
148  ax.set_ylabel('Focal Plane Y (mm)')
149  if savePath is not None:
150  plt.savefig(savePath)
151  if showFig:
152  plt.show()
153 
154 
155 def makeImageFromAmp(amp, imValue=None, imageFactory=afwImage.ImageU, markSize=10, markValue=0,
156  scaleGain = lambda gain: (gain*1000)//10):
157  """!Make an image from an amp object
158 
159  Since images are integer images by default, the gain needs to be scaled to give enough dynamic range
160  to see variation from amp to amp. The scaling algorithm is assignable.
161 
162  @param[in] amp Amp record to use for constructing the raw amp image
163  @param[in] imValue Value to assign to the constructed image scaleGain(gain) is used if not set
164  @param[in] imageFactory Type of image to construct
165  @param[in] markSize Size of mark at read corner in pixels
166  @param[in] markValue Value of pixels in the read corner mark
167  @param[in] scaleGain The function by which to scale the gain
168  @return an untrimmed amp image
169  """
170  if not amp.getHasRawInfo():
171  raise RuntimeError(
172  "Can't create a raw amp image without raw amp information")
173  bbox = amp.getRawBBox()
174  dbbox = amp.getRawDataBBox()
175  img = imageFactory(bbox)
176  if imValue is None:
177  img.set(scaleGain(amp.getGain()))
178  else:
179  img.set(imValue)
180  # Set the first pixel read to a different value
181  markbbox = afwGeom.Box2I()
182  if amp.getReadoutCorner() == 0:
183  markbbox.include(dbbox.getMin())
184  markbbox.include(dbbox.getMin()+afwGeom.Extent2I(markSize, markSize))
185  elif amp.getReadoutCorner() == 1:
186  cornerPoint = afwGeom.Point2I(dbbox.getMaxX(), dbbox.getMinY())
187  markbbox.include(cornerPoint)
188  markbbox.include(cornerPoint + afwGeom.Extent2I(-markSize, markSize))
189  elif amp.getReadoutCorner() == 2:
190  cornerPoint = afwGeom.Point2I(dbbox.getMax())
191  markbbox.include(cornerPoint)
192  markbbox.include(cornerPoint + afwGeom.Extent2I(-markSize, -markSize))
193  elif amp.getReadoutCorner() == 3:
194  cornerPoint = afwGeom.Point2I(dbbox.getMinX(), dbbox.getMaxY())
195  markbbox.include(cornerPoint)
196  markbbox.include(cornerPoint + afwGeom.Extent2I(markSize, -markSize))
197  else:
198  raise RuntimeError("Could not set readout corner")
199  mimg = imageFactory(img, markbbox)
200  mimg.set(markValue)
201  return img
202 
203 
204 def calcRawCcdBBox(ccd):
205  """!Calculate the raw ccd bounding box
206 
207  @param[in] ccd Detector for with to calculate the un-trimmed bounding box
208  @return Box2I of the un-trimmed Detector,
209  or None if there is not enough information to calculate raw BBox
210  """
211  bbox = afwGeom.Box2I()
212  for amp in ccd:
213  if not amp.getHasRawInfo():
214  return None
215  tbbox = amp.getRawBBox()
216  tbbox.shift(amp.getRawXYOffset())
217  bbox.include(tbbox)
218  return bbox
219 
220 
221 def makeImageFromCcd(ccd, isTrimmed=True, showAmpGain=True, imageFactory=afwImage.ImageU, rcMarkSize=10,
222  binSize=1):
223  """!Make an Image of a Ccd
224 
225  @param[in] ccd Detector to use in making the image
226  @param[in] isTrimmed Assemble a trimmed Detector image if True
227  @param[in] showAmpGain Use the per amp gain to color the pixels in the image
228  @param[in] imageFactory Image type to generate
229  @param[in] rcMarkSize Size of the mark to make in the amp images at the read corner
230  @param[in] binSize Bin the image by this factor in both dimensions
231  @return Image of the Detector
232  """
233  ampImages = []
234  index = 0
235  if isTrimmed:
236  bbox = ccd.getBBox()
237  else:
238  bbox = calcRawCcdBBox(ccd)
239  for amp in ccd:
240  if amp.getHasRawInfo():
241  if showAmpGain:
242  ampImages.append(makeImageFromAmp(
243  amp, imageFactory=imageFactory, markSize=rcMarkSize))
244  else:
245  ampImages.append(makeImageFromAmp(amp, imValue=(index+1)*1000,
246  imageFactory=imageFactory, markSize=rcMarkSize))
247  index += 1
248 
249  if len(ampImages) > 0:
250  ccdImage = imageFactory(bbox)
251  for ampImage, amp in zip(ampImages, ccd):
252  if isTrimmed:
253  assembleAmplifierImage(ccdImage, ampImage, amp)
254  else:
255  assembleAmplifierRawImage(ccdImage, ampImage, amp)
256  else:
257  if not isTrimmed:
258  raise RuntimeError(
259  "Cannot create untrimmed CCD without amps with raw information")
260  ccdImage = imageFactory(ccd.getBBox())
261  ccdImage = afwMath.binImage(ccdImage, binSize)
262  return ccdImage
263 
264 
265 class FakeImageDataSource(object):
266  """A class to retrieve synthetic images for display by the show* methods"""
267 
268  def __init__(self, isTrimmed=True, verbose=False, background=numpy.nan,
269  showAmpGain=True, markSize=10, markValue=0,
270  ampImValue=None, scaleGain=lambda gain: (gain*1000)//10):
271  """!Construct a FakeImageDataSource
272 
273  @param[in] isTrimmed Should amps be trimmed?
274  @param[in] verbose Be chatty
275  @param[in] background The value of any pixels that lie outside the CCDs
276  @param[in] showAmpGain color the amp segments with the gain of the amp
277  @param[in] markSize size of the side of the box used to mark the read corner
278  @param[in] markValue value to assing the read corner mark
279  @param[in] ampImValue Value to assing to amps. scaleGain(gain) is used if None
280  @param[in] scaleGain function to scale the gain by
281  """
282  self.isTrimmed = isTrimmed
283  self.verbose = verbose
284  self.background = background
285  self.showAmpGain = showAmpGain
286  self.markSize = markSize
287  self.markValue = markValue
288  self.ampImValue = ampImValue
289  self.scaleGain = scaleGain
290 
291  def getCcdImage(self, det, imageFactory, binSize):
292  """!Return a CCD image for the detector and the (possibly updated) Detector
293 
294  @param[in] det: Detector to use for making the image
295  @param[in] imageFactory: image constructor for making the image
296  @param[in] binSize: number of pixels per bin axis
297  """
298  return makeImageFromCcd(det, isTrimmed=self.isTrimmed, showAmpGain=self.showAmpGain,
299  imageFactory=imageFactory, binSize=binSize), det
300 
301  def getAmpImage(self, amp, imageFactory):
302  """!Return an amp segment image
303 
304  @param[in] amp AmpInfoTable for this amp
305  @param[in] imageFactory image constructor fo making the imag
306  """
307  ampImage = makeImageFromAmp(amp, imValue=self.ampImValue, imageFactory=imageFactory,
308  markSize=self.markSize, markValue=self.markValue,
309  scaleGain=self.scaleGain)
310  if self.isTrimmed:
311  ampImage = ampImage.Factory(ampImage, amp.getRawDataBBox())
312  return ampImage
313 
314 
316  """A class to return an Image of a given Ccd using the butler"""
317 
318  def __init__(self, butler=None, type="raw",
319  isTrimmed=True, verbose=False, background=numpy.nan, gravity=None,
320  callback=None, *args, **kwargs):
321  """!Create an object that knows how to prepare images for showCamera using the butler
322 
323  \param butler The butler to use. If no butler is provided an empty image is returned
324  \param type The type of image to read (e.g. raw, bias, flat, calexp)
325  \param isTrimmed If true, the showCamera command expects to be given trimmed images
326  \param verbose Be chatty (in particular, print any error messages from the butler)
327  \param background The value of any pixels that lie outside the CCDs
328  \param gravity If the image returned by the butler is trimmed (e.g. some of the SuprimeCam CCDs)
329  Specify how to fit the image into the available space; N => align top, W => align left
330  \param callback A function called with (image, ccd, butler) for every image, which returns the image
331  to be displayed (e.g. rawCallback). The image must be of the correct size, allowing
332  for the value of isTrimmed
333  \param *args, *kwargs Passed to the butler
334 
335  N.b. You can use a lambda as a callback, e.g.
336  callback=lambda im, ccd, imageSource : cgUtils.rawCallback(im, ccd, imageSource, correctGain=True)
337  """
338  super(ButlerImage, self).__init__(*args)
339  self.isTrimmed = isTrimmed
340  self.type = type
341  self.butler = butler
342  self.kwargs = kwargs
343  self.isRaw = False
344  self.gravity = gravity
345  self.background = background
346  self.verbose = verbose
347  self.callback = callback
348 
349  def _prepareImage(self, ccd, im, binSize, allowRotate=True):
350  if binSize > 1:
351  im = afwMath.binImage(im, binSize)
352 
353  if allowRotate:
355  im, ccd.getOrientation().getNQuarter())
356 
357  return im
358 
359  def getCcdImage(self, ccd, imageFactory=afwImage.ImageF, binSize=1):
360  """Return an image of the specified ccd, and also the (possibly updated) ccd"""
361 
362  if self.isTrimmed:
363  bbox = ccd.getBBox()
364  else:
365  bbox = calcRawCcdBBox(ccd)
366 
367  im = None
368  if self.butler is not None:
369  e = None
370  if self.type == "calexp": # reading the exposure can die if the PSF's unknown
371  try: # need to switch to cid as below. RHL has no calexp to test with
372  fileName = self.butler.get(self.type + "_filename", ccd=ccd.getId(),
373  **self.kwargs)[0]
374  im = imageFactory(fileName)
375  except Exception as e:
376  pass
377  else:
378  im = None
379  for cid in [ccd.getId(), ccd.getName()]:
380  try:
381  im = self.butler.get(self.type, ccd=cid, **self.kwargs)
382  ccd = im.getDetector() # possibly modified by assembleCcdTask
383  e = None
384  break
385  except Exception as e:
386  continue
387 
388  if im:
389  im = im.getMaskedImage().getImage()
390  else:
391  raise e
392 
393  if e:
394  if self.verbose:
395  print("Reading %s: %s" % (ccd.getId(), e))
396 
397  if im is None:
398  return self._prepareImage(ccd, imageFactory(*bbox.getDimensions()), binSize), ccd
399 
400  if self.type == "raw":
401  allowRotate = True # all other images were rotated by the ISR
402  if hasattr(im, 'convertF'):
403  im = im.convertF()
404  if False and self.callback is None: # we need to trim the raw image
405  self.callback = rawCallback
406 
407  if self.callback:
408  try:
409  im = self.callback(im, ccd, imageSource=self)
410  except Exception as e:
411  if self.verbose:
412  print("callback failed: %s" % e)
413  im = imageFactory(*bbox.getDimensions())
414 
415  return self._prepareImage(ccd, im, binSize, allowRotate=allowRotate), ccd
416 
417 
418 def rawCallback(im, ccd=None, imageSource=None,
419  correctGain=False, subtractBias=False, convertToFloat=False):
420  """!A callback function that may or may not subtract bias/correct gain/trim a raw image
421 
422  @param im An image of a chip, ready to be binned and maybe rotated. Maybe an Exposure,
423  a MaskedImage or an Image
424  @param ccd The Detector; if None assume that im is an exposure and extract it's Detector
425  @param imageSource An object derived from FakeImageDataSource (typically ButlerImage)
426  @param correctGain Correct each amplifier for its gain
427  @param subtractBias Subtract the bias from each amplifier
428  @param convertToFloat Convert im to floating point if possible
429 
430  N.b. if imageSource is derived from ButlerImage, imageSource.butler is available
431  """
432  if ccd is None:
433  ccd = im.getDetector()
434  if hasattr(im, "getMaskedImage"):
435  im = im.getMaskedImage()
436  if convertToFloat and hasattr(im, "convertF"):
437  im = im.convertF()
438 
439  isTrimmed = imageSource.isTrimmed
440  if isTrimmed:
441  bbox = ccd.getBBox()
442  else:
443  bbox = calcRawCcdBBox(ccd)
444 
445  ampImages = []
446  for a in ccd:
447  if isTrimmed:
448  data = im[a.getRawDataBBox()]
449  else:
450  data = im
451 
452  if subtractBias:
453  bias = im[a.getRawHorizontalOverscanBBox()]
454  data -= afwMath.makeStatistics(bias, afwMath.MEANCLIP).getValue()
455  if correctGain:
456  data *= a.getGain()
457 
458  ampImages.append(data)
459 
460  ccdImage = im.Factory(bbox)
461  for ampImage, amp in zip(ampImages, ccd):
462  if isTrimmed:
463  assembleAmplifierImage(ccdImage, ampImage, amp)
464  else:
465  assembleAmplifierRawImage(ccdImage, ampImage, amp)
466 
467  return ccdImage
468 
469 
470 def overlayCcdBoxes(ccd, untrimmedCcdBbox=None, nQuarter=0,
471  isTrimmed=False, ccdOrigin=(0, 0), display=None, binSize=1):
472  """!Overlay bounding boxes on an image display
473 
474  @param[in] ccd Detector to iterate for the amp bounding boxes
475  @param[in] untrimmedCcdBbox Bounding box of the un-trimmed Detector
476  @param[in] nQuarter number of 90 degree rotations to apply to the bounding boxes (used for rotated chips)
477  @param[in] isTrimmed Is the Detector image over which the boxes are layed trimmed?
478  @param[in] ccdOrigin Detector origin relative to the parent origin if in a larger pixel grid
479  @param[in] display image display to display on
480  @param[in] binSize binning factor
481 
482  The colours are:
483  Entire detector GREEN
484  All data for amp GREEN
485  HorizontalPrescan YELLOW
486  HorizontalOverscan RED
487  Data BLUE
488  VerticalOverscan MAGENTA
489  VerticalOverscan MAGENTA
490  """
491  if not display: # should be second parameter, and not defaulted!!
492  raise RuntimeError("Please specify a display")
493 
494  if untrimmedCcdBbox is None:
495  if isTrimmed:
496  untrimmedCcdBbox = ccd.getBBox()
497  else:
498  untrimmedCcdBbox = afwGeom.Box2I()
499  for a in ccd.getAmpInfoCatalog():
500  bbox = a.getRawBBox()
501  untrimmedCcdBbox.include(bbox)
502 
503  with display.Buffering():
504  ccdDim = untrimmedCcdBbox.getDimensions()
505  ccdBbox = rotateBBoxBy90(untrimmedCcdBbox, nQuarter, ccdDim)
506  for amp in ccd:
507  if isTrimmed:
508  ampbbox = amp.getBBox()
509  else:
510  ampbbox = amp.getRawBBox()
511  if nQuarter != 0:
512  ampbbox = rotateBBoxBy90(ampbbox, nQuarter, ccdDim)
513 
514  displayUtils.drawBBox(ampbbox, origin=ccdOrigin, borderWidth=0.49,
515  display=display, bin=binSize)
516 
517  if not isTrimmed and amp.getHasRawInfo():
518  for bbox, ctype in ((amp.getRawHorizontalOverscanBBox(), afwDisplay.RED),
519  (amp.getRawDataBBox(), afwDisplay.BLUE),
520  (amp.getRawVerticalOverscanBBox(),
521  afwDisplay.MAGENTA),
522  (amp.getRawPrescanBBox(), afwDisplay.YELLOW)):
523  if nQuarter != 0:
524  bbox = rotateBBoxBy90(bbox, nQuarter, ccdDim)
525  displayUtils.drawBBox(bbox, origin=ccdOrigin, borderWidth=0.49, ctype=ctype,
526  display=display, bin=binSize)
527  # Label each Amp
528  xc, yc = (ampbbox.getMin()[0] + ampbbox.getMax()[0])//2, (ampbbox.getMin()[1] +
529  ampbbox.getMax()[1])//2
530  #
531  # Rotate the amp labels too
532  #
533  if nQuarter == 0:
534  c, s = 1, 0
535  elif nQuarter == 1:
536  c, s = 0, -1
537  elif nQuarter == 2:
538  c, s = -1, 0
539  elif nQuarter == 3:
540  c, s = 0, 1
541  c, s = 1, 0
542  ccdHeight = ccdBbox.getHeight()
543  ccdWidth = ccdBbox.getWidth()
544  xc -= 0.5*ccdHeight
545  yc -= 0.5*ccdWidth
546 
547  xc, yc = 0.5*ccdHeight + c*xc + s*yc, 0.5*ccdWidth + -s*xc + c*yc
548 
549  if ccdOrigin:
550  xc += ccdOrigin[0]
551  yc += ccdOrigin[1]
552  display.dot(str(amp.getName()), xc/binSize,
553  yc/binSize, textAngle=nQuarter*90)
554 
555  displayUtils.drawBBox(ccdBbox, origin=ccdOrigin,
556  borderWidth=0.49, ctype=afwDisplay.MAGENTA, display=display, bin=binSize)
557 
558 
559 def showAmp(amp, imageSource=FakeImageDataSource(isTrimmed=False), display=None, overlay=True,
560  imageFactory=afwImage.ImageU):
561  """!Show an amp in an image display
562 
563  @param[in] amp amp record to use in display
564  @param[in] imageSource Source for getting the amp image. Must have a getAmpImage method.
565  @param[in] display image display to use
566  @param[in] overlay Overlay bounding boxes?
567  @param[in] imageFactory Type of image to display (only used if ampImage is None)
568  """
569 
570  if not display:
571  display = _getDisplayFromDisplayOrFrame()
572 
573  ampImage = imageSource.getAmpImage(amp, imageFactory=imageFactory)
574  ampImSize = ampImage.getDimensions()
575  title = amp.getName()
576  display.mtv(ampImage, title=title)
577  if overlay:
578  with display.Buffering():
579  if amp.getHasRawInfo() and ampImSize == amp.getRawBBox().getDimensions():
580  bboxes = [(amp.getRawBBox(), 0.49, afwDisplay.GREEN), ]
581  xy0 = bboxes[0][0].getMin()
582  bboxes.append(
583  (amp.getRawHorizontalOverscanBBox(), 0.49, afwDisplay.RED))
584  bboxes.append((amp.getRawDataBBox(), 0.49, afwDisplay.BLUE))
585  bboxes.append((amp.getRawPrescanBBox(),
586  0.49, afwDisplay.YELLOW))
587  bboxes.append((amp.getRawVerticalOverscanBBox(),
588  0.49, afwDisplay.MAGENTA))
589  else:
590  bboxes = [(amp.getBBox(), 0.49, None), ]
591  xy0 = bboxes[0][0].getMin()
592 
593  for bbox, borderWidth, ctype in bboxes:
594  if bbox.isEmpty():
595  continue
596  bbox = afwGeom.Box2I(bbox)
597  bbox.shift(-afwGeom.ExtentI(xy0))
598  displayUtils.drawBBox(
599  bbox, borderWidth=borderWidth, ctype=ctype, display=display)
600 
601 
602 def showCcd(ccd, imageSource=FakeImageDataSource(), display=None, frame=None, overlay=True,
603  imageFactory=afwImage.ImageF, binSize=1, inCameraCoords=False):
604  """!Show a CCD on display
605 
606  @param[in] ccd Detector to use in display
607  @param[in] imageSource Source for producing images to display. Must have a getCcdImage method.
608  @param[in] display image display to use
609  @param[in] frame frame ID on which to display
610  @param[in] overlay Show amp bounding boxes on the displayed image?
611  @param[in] imageFactory The image factory to use in generating the images.
612  @param[in] binSize Binning factor
613  @param[in] inCameraCoords Show the Detector in camera coordinates?
614  """
615  display = _getDisplayFromDisplayOrFrame(display, frame)
616 
617  ccdOrigin = afwGeom.Point2I(0, 0)
618  nQuarter = 0
619  ccdImage, ccd = imageSource.getCcdImage(
620  ccd, imageFactory=imageFactory, binSize=binSize)
621 
622  ccdBbox = ccdImage.getBBox()
623  if ccdBbox.getDimensions() == ccd.getBBox().getDimensions():
624  isTrimmed = True
625  else:
626  isTrimmed = False
627 
628  if inCameraCoords:
629  nQuarter = ccd.getOrientation().getNQuarter()
630  ccdImage = afwMath.rotateImageBy90(ccdImage, nQuarter)
631  title = ccd.getName()
632  if isTrimmed:
633  title += "(trimmed)"
634 
635  if display:
636  display.mtv(ccdImage, title=title)
637 
638  if overlay:
639  overlayCcdBoxes(ccd, ccdBbox, nQuarter, isTrimmed,
640  ccdOrigin, display, binSize)
641 
642  return ccdImage
643 
644 
645 def getCcdInCamBBoxList(ccdList, binSize, pixelSize_o, origin):
646  """!Get the bounding boxes of a list of Detectors within a camera sized pixel grid
647 
648  @param[in] ccdList List of Detector
649  @param[in] binSize Binning factor
650  @param[in] pixelSize_o Size of the pixel in mm.
651  @param[in] origin origin of the camera pixel grid in pixels
652  @return a list of bounding boxes in camera pixel coordinates
653  """
654  boxList = []
655  for ccd in ccdList:
656  if not pixelSize_o == ccd.getPixelSize():
657  raise RuntimeError(
658  "Cameras with detectors with different pixel scales are not currently supported")
659 
660  dbbox = afwGeom.Box2D()
661  for corner in ccd.getCorners(FOCAL_PLANE):
662  dbbox.include(corner)
663  llc = dbbox.getMin()
664  nQuarter = ccd.getOrientation().getNQuarter()
665  cbbox = ccd.getBBox()
666  ex = cbbox.getDimensions().getX()//binSize
667  ey = cbbox.getDimensions().getY()//binSize
668  bbox = afwGeom.Box2I(
669  cbbox.getMin(), afwGeom.Extent2I(int(ex), int(ey)))
670  bbox = rotateBBoxBy90(bbox, nQuarter, bbox.getDimensions())
671  bbox.shift(afwGeom.Extent2I(int(llc.getX()//pixelSize_o.getX()/binSize),
672  int(llc.getY()//pixelSize_o.getY()/binSize)))
673  bbox.shift(afwGeom.Extent2I(-int(origin.getX()//binSize),
674  -int(origin.getY())//binSize))
675  boxList.append(bbox)
676  return boxList
677 
678 
679 def getCameraImageBBox(camBbox, pixelSize, bufferSize):
680  """!Get the bounding box of a camera sized image in pixels
681 
682  @param[in] camBbox Camera bounding box in focal plane coordinates (mm)
683  @param[in] pixelSize Size of a detector pixel in mm
684  @param[in] bufferSize Buffer around edge of image in pixels
685  @return the resulting bounding box
686  """
687  pixMin = afwGeom.Point2I(int(camBbox.getMinX()//pixelSize.getX()),
688  int(camBbox.getMinY()//pixelSize.getY()))
689  pixMax = afwGeom.Point2I(int(camBbox.getMaxX()//pixelSize.getX()),
690  int(camBbox.getMaxY()//pixelSize.getY()))
691  retBox = afwGeom.Box2I(pixMin, pixMax)
692  retBox.grow(bufferSize)
693  return retBox
694 
695 
696 def makeImageFromCamera(camera, detectorNameList=None, background=numpy.nan, bufferSize=10,
697  imageSource=FakeImageDataSource(), imageFactory=afwImage.ImageU, binSize=1):
698  """!Make an Image of a Camera
699 
700  @param[in] camera Camera object to use to make the image
701  @param[in] detectorNameList List of detector names to use in building the image.
702  Use all Detectors if None.
703  @param[in] background Value to use where there is no Detector
704  @param[in] bufferSize Size of border in binned pixels to make around the camera image
705  @param[in] imageSource Source to get ccd images. Must have a getCcdImage method
706  @param[in] imageFactory Type of image to build
707  @param[in] binSize bin factor
708  @return an image of the camera
709  """
710  if detectorNameList is None:
711  ccdList = camera
712  else:
713  ccdList = [camera[name] for name in detectorNameList]
714 
715  if detectorNameList is None:
716  camBbox = camera.getFpBBox()
717  else:
718  camBbox = afwGeom.Box2D()
719  for detName in detectorNameList:
720  for corner in camera[detName].getCorners(FOCAL_PLANE):
721  camBbox.include(corner)
722 
723  pixelSize_o = camera[next(camera.getNameIter())].getPixelSize()
724  camBbox = getCameraImageBBox(camBbox, pixelSize_o, bufferSize*binSize)
725  origin = camBbox.getMin()
726 
727  camIm = imageFactory(int(math.ceil(camBbox.getDimensions().getX()/binSize)),
728  int(math.ceil(camBbox.getDimensions().getY()/binSize)))
729  camIm[:] = imageSource.background
730 
731  assert imageSource.isTrimmed, "isTrimmed is False isn't supported by getCcdInCamBBoxList"
732 
733  boxList = getCcdInCamBBoxList(ccdList, binSize, pixelSize_o, origin)
734  for det, bbox in zip(ccdList, boxList):
735  try:
736  im = imageSource.getCcdImage(det, imageFactory, binSize)[0]
737  except Exception as e:
738  print("Unable to get image for detector %s: %s" % (det.getName(), e))
739  continue
740 
741  nQuarter = det.getOrientation().getNQuarter()
742  im = afwMath.rotateImageBy90(im, nQuarter)
743 
744  imView = camIm.Factory(camIm, bbox, afwImage.LOCAL)
745  import lsst.pex.exceptions as pexExceptions
746  try:
747  imView[:] = im
749  print("Unable to fit image for detector \"%s\" into image of camera" % (
750  det.getName()))
751 
752  return camIm
753 
754 
755 def showCamera(camera, imageSource=FakeImageDataSource(), imageFactory=afwImage.ImageF,
756  detectorNameList=None, binSize=10, bufferSize=10, frame=None, overlay=True, title="",
757  showWcs=None, ctype=afwDisplay.GREEN, textSize=1.25, originAtCenter=True, display=None,
758  **kwargs):
759  """!Show a Camera on display, with the specified display
760 
761  The rotation of the sensors is snapped to the nearest multiple of 90 deg.
762  Also note that the pixel size is constant over the image array. The lower left corner (LLC) of each
763  sensor amp is snapped to the LLC of the pixel containing the LLC of the image.
764  if overlay show the IDs and detector boundaries
765 
766  @param[in] camera Camera to show
767  @param[in] imageSource Source to get Ccd images from. Must have a getCcdImage method.
768  @param[in] imageFactory Type of image to make
769  @param[in] detectorNameList List of names of Detectors to use. If None use all
770  @param[in] binSize bin factor
771  @param[in] bufferSize size of border in binned pixels to make around camera image.
772  @param[in] frame specify image display (@deprecated; new code should use display)
773  @param[in] overlay Overlay Detector IDs and boundaries?
774  @param[in] title Title in display
775  @param[in] showWcs whether to include a WCS in the display
776  @param[in] ctype Color to use when drawing Detector boundaries
777  @param[in] textSize Size of detector labels
778  @param[in] originAtCenter Put origin of the camera WCS at the center of the image? Else it will be LL
779  @param[in] display image display on which to display
780  @param[in] **kwargs all remaining keyword arguments are passed to makeImageFromCamera
781  @return the mosaic image
782  """
783  display = _getDisplayFromDisplayOrFrame(display, frame)
784 
785  if binSize < 1:
786  binSize = 1
787  cameraImage = makeImageFromCamera(camera, detectorNameList=detectorNameList, bufferSize=bufferSize,
788  imageSource=imageSource, imageFactory=imageFactory, binSize=binSize,
789  **kwargs)
790 
791  if detectorNameList is None:
792  ccdList = [camera[name] for name in camera.getNameIter()]
793  else:
794  ccdList = [camera[name] for name in detectorNameList]
795 
796  if detectorNameList is None:
797  camBbox = camera.getFpBBox()
798  else:
799  camBbox = afwGeom.Box2D()
800  for detName in detectorNameList:
801  for corner in camera[detName].getCorners(FOCAL_PLANE):
802  camBbox.include(corner)
803  pixelSize = ccdList[0].getPixelSize()
804 
805  if showWcs:
806  if originAtCenter:
807  wcsReferencePixel = afwGeom.Box2D(
808  cameraImage.getBBox()).getCenter()
809  else:
810  wcsReferencePixel = afwGeom.Point2I(0, 0)
811  wcs = makeFocalPlaneWcs(pixelSize*binSize, wcsReferencePixel)
812  else:
813  wcs = None
814 
815  if display:
816  if title == "":
817  title = camera.getName()
818  display.mtv(cameraImage, title=title, wcs=wcs)
819 
820  if overlay:
821  with display.Buffering():
822  camBbox = getCameraImageBBox(
823  camBbox, pixelSize, bufferSize*binSize)
824  bboxList = getCcdInCamBBoxList(
825  ccdList, binSize, pixelSize, camBbox.getMin())
826  for bbox, ccd in zip(bboxList, ccdList):
827  nQuarter = ccd.getOrientation().getNQuarter()
828  # borderWidth to 0.5 to align with the outside edge of the
829  # pixel
830  displayUtils.drawBBox(
831  bbox, borderWidth=0.5, ctype=ctype, display=display)
832  dims = bbox.getDimensions()
833  display.dot(ccd.getName(), bbox.getMinX()+dims.getX()/2, bbox.getMinY()+dims.getY()/2,
834  ctype=ctype, size=textSize, textAngle=nQuarter*90)
835 
836  return cameraImage
837 
838 
839 def makeFocalPlaneWcs(pixelSize, referencePixel):
840  """!Make a WCS for the focal plane geometry (i.e. returning positions in "mm")
841 
842  @param[in] pixelSize Size of the image pixels in physical units
843  @param[in] referencePixel Pixel for origin of WCS
844  @return Wcs object for mapping between pixels and focal plane.
845  """
846 
847  md = dafBase.PropertySet()
848  if referencePixel is None:
849  referencePixel = afwGeom.PointD(0, 0)
850  for i in range(2):
851  md.set("CRPIX%d"%(i+1), referencePixel[i])
852  md.set("CRVAL%d"%(i+1), 0.)
853  md.set("CDELT1", pixelSize[0])
854  md.set("CDELT2", pixelSize[1])
855  md.set("CTYPE1", "CAMERA_X")
856  md.set("CTYPE2", "CAMERA_Y")
857  md.set("CUNIT1", "mm")
858  md.set("CUNIT2", "mm")
859 
860  return afwGeom.makeSkyWcs(md)
861 
862 
863 def findAmp(ccd, pixelPosition):
864  """!Find the Amp with the specified pixel position within the composite
865 
866  @param[in] ccd Detector to look in
867  @param[in] pixelPosition Point2I containing the pixel position
868  @return Amp record in which pixelPosition falls or None if no Amp found.
869  """
870 
871  for amp in ccd:
872  if amp.getBBox().contains(pixelPosition):
873  return amp
874 
875  return None
def makeImageFromAmp(amp, imValue=None, imageFactory=afwImage.ImageU, markSize=10, markValue=0, scaleGain=lambda gain:(gain *1000)//10)
Make an image from an amp object.
Definition: utils.py:156
def makeFocalPlaneWcs(pixelSize, referencePixel)
Make a WCS for the focal plane geometry (i.e.
Definition: utils.py:839
def showCamera(camera, imageSource=FakeImageDataSource(), imageFactory=afwImage.ImageF, detectorNameList=None, binSize=10, bufferSize=10, frame=None, overlay=True, title="", showWcs=None, ctype=afwDisplay.GREEN, textSize=1.25, originAtCenter=True, display=None, kwargs)
Show a Camera on display, with the specified display.
Definition: utils.py:758
def plotFocalPlane(camera, fieldSizeDeg_x=0, fieldSizeDeg_y=None, dx=0.1, dy=0.1, figsize=(10., 10.), useIds=False, showFig=True, savePath=None)
Make a plot of the focal plane along with a set points that sample the field of view.
Definition: utils.py:75
def showCcd(ccd, imageSource=FakeImageDataSource(), display=None, frame=None, overlay=True, imageFactory=afwImage.ImageF, binSize=1, inCameraCoords=False)
Show a CCD on display.
Definition: utils.py:603
std::shared_ptr< SkyWcs > makeFlippedWcs(SkyWcs const &wcs, bool flipLR, bool flipTB, geom::Point2D const &center)
Return a copy of a FITS-WCS with pixel positions flipped around a specified center.
int min
Definition: Coord.cc:160
def getCcdInCamBBoxList(ccdList, binSize, pixelSize_o, origin)
Get the bounding boxes of a list of Detectors within a camera sized pixel grid.
Definition: utils.py:645
def getCcdImage(self, det, imageFactory, binSize)
Return a CCD image for the detector and the (possibly updated) Detector.
Definition: utils.py:291
std::shared_ptr< SkyWcs > makeSkyWcs(Point2D const &crpix, coord::IcrsCoord const &crval, Eigen::Matrix2d const &cdMatrix, std::string const &projection="TAN")
Construct a simple FITS SkyWcs with no distortion.
def findAmp(ccd, pixelPosition)
Find the Amp with the specified pixel position within the composite.
Definition: utils.py:863
An integer coordinate rectangle.
Definition: Box.h:55
def getCameraImageBBox(camBbox, pixelSize, bufferSize)
Get the bounding box of a camera sized image in pixels.
Definition: utils.py:679
Statistics makeStatistics(lsst::afw::math::MaskedVector< EntryT > const &mv, std::vector< WeightPixel > const &vweights, int const flags, StatisticsControl const &sctrl=StatisticsControl())
The makeStatistics() overload to handle lsst::afw::math::MaskedVector<>
Definition: Statistics.h:518
def getAmpImage(self, amp, imageFactory)
Return an amp segment image.
Definition: utils.py:301
def __init__(self, isTrimmed=True, verbose=False, background=numpy.nan, showAmpGain=True, markSize=10, markValue=0, ampImValue=None, scaleGain=lambda gain:(gain *1000)//10)
Construct a FakeImageDataSource.
Definition: utils.py:270
def rawCallback(im, ccd=None, imageSource=None, correctGain=False, subtractBias=False, convertToFloat=False)
A callback function that may or may not subtract bias/correct gain/trim a raw image.
Definition: utils.py:419
def calcRawCcdBBox(ccd)
Calculate the raw ccd bounding box.
Definition: utils.py:204
def _prepareImage(self, ccd, im, binSize, allowRotate=True)
Definition: utils.py:349
def makeImageFromCamera(camera, detectorNameList=None, background=numpy.nan, bufferSize=10, imageSource=FakeImageDataSource(), imageFactory=afwImage.ImageU, binSize=1)
Make an Image of a Camera.
Definition: utils.py:697
int max
Definition: BoundedField.cc:99
def getCcdImage(self, ccd, imageFactory=afwImage.ImageF, binSize=1)
Definition: utils.py:359
def makeImageFromCcd(ccd, isTrimmed=True, showAmpGain=True, imageFactory=afwImage.ImageU, rcMarkSize=10, binSize=1)
Make an Image of a Ccd.
Definition: utils.py:222
std::shared_ptr< ImageT > rotateImageBy90(ImageT const &image, int nQuarter)
Rotate an image by an integral number of quarter turns.
Definition: rotateImage.cc:39
def __init__(self, butler=None, type="raw", isTrimmed=True, verbose=False, background=numpy.nan, gravity=None, callback=None, args, kwargs)
Create an object that knows how to prepare images for showCamera using the butler.
Definition: utils.py:320
def assembleAmplifierImage(destImage, rawImage, amplifier)
Assemble the amplifier region of an image from a raw image.
def showAmp(amp, imageSource=FakeImageDataSource(isTrimmed=False), display=None, overlay=True, imageFactory=afwImage.ImageU)
Show an amp in an image display.
Definition: utils.py:560
def prepareWcsData(wcs, amp, isTrimmed=True)
Put Wcs from an Amp image into CCD coordinates.
Definition: utils.py:49
std::shared_ptr< ImageT > binImage(ImageT const &inImage, int const binsize, lsst::afw::math::Property const flags=lsst::afw::math::MEAN)
Definition: binImage.cc:38
def assembleAmplifierRawImage(destImage, rawImage, amplifier)
Assemble the amplifier region of a raw CCD image.
A floating-point coordinate rectangle geometry.
Definition: Box.h:266
def overlayCcdBoxes(ccd, untrimmedCcdBbox=None, nQuarter=0, isTrimmed=False, ccdOrigin=(0, 0), display=None, binSize=1)
Overlay bounding boxes on an image display.
Definition: utils.py:471
def rotateBBoxBy90(bbox, n90, dimensions)
Rotate a bounding box by an integer multiple of 90 degrees.