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