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