lsst.afw  16.0-79-g81b2eb930+1
utils.py
Go to the documentation of this file.
1 # This file is part of afw.
2 #
3 # Developed for the LSST Data Management System.
4 # This product includes software developed by the LSST Project
5 # (https://www.lsst.org).
6 # See the COPYRIGHT file at the top-level directory of this distribution
7 # for details of code ownership.
8 #
9 # This program is free software: you can redistribute it and/or modify
10 # it under the terms of the GNU General Public License as published by
11 # the Free Software Foundation, either version 3 of the License, or
12 # (at your option) any later version.
13 #
14 # This program is distributed in the hope that it will be useful,
15 # but WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 # GNU General Public License for more details.
18 #
19 # You should have received a copy of the GNU General Public License
20 # along with this program. If not, see <https://www.gnu.org/licenses/>.
21 
22 """
23 Support for displaying cameraGeom objects.
24 """
25 
26 __all__ = ['prepareWcsData', 'plotFocalPlane', 'makeImageFromAmp', 'calcRawCcdBBox', 'makeImageFromCcd',
27  'FakeImageDataSource', 'ButlerImage', 'rawCallback', 'overlayCcdBoxes',
28  'showAmp', 'showCcd', 'getCcdInCamBBoxList', 'getCameraImageBBox',
29  'makeImageFromCamera', 'showCamera', 'makeFocalPlaneWcs', 'findAmp']
30 
31 import math
32 import numpy
33 import warnings
34 
35 import lsst.geom
36 from lsst.afw.fits import FitsError
37 import lsst.afw.geom as afwGeom
38 import lsst.afw.image as afwImage
39 import lsst.afw.math as afwMath
40 import lsst.daf.base as dafBase
41 import lsst.log
42 import lsst.pex.exceptions as pexExceptions
43 
44 from .rotateBBoxBy90 import rotateBBoxBy90
45 from .assembleImage import assembleAmplifierImage, assembleAmplifierRawImage
46 from .cameraGeomLib import FIELD_ANGLE, FOCAL_PLANE
47 from lsst.afw.display.utils import _getDisplayFromDisplayOrFrame
48 
49 import lsst.afw.display as afwDisplay
50 import lsst.afw.display.utils as displayUtils
51 
52 
53 def prepareWcsData(wcs, amp, isTrimmed=True):
54  """Put Wcs from an Amp image into CCD coordinates
55 
56  Parameters
57  ----------
58  wcs : `lsst.afw.geom.SkyWcs`
59  The WCS object to start from.
60  amp : `lsst.afw.table.AmpInfoRecord`
61  Amp object to use
62  isTrimmed : `bool`
63  Is the image to which the WCS refers trimmed of non-imaging pixels?
64 
65  Returns
66  -------
67  ampWcs : `lsst.afw.geom.SkyWcs`
68  The modified WCS.
69  """
70  if not amp.getHasRawInfo():
71  raise RuntimeError("Cannot modify wcs without raw amp information")
72  if isTrimmed:
73  ampBox = amp.getRawDataBBox()
74  else:
75  ampBox = amp.getRawBBox()
76  ampCenter = lsst.geom.Point2D(ampBox.getDimensions() / 2.0)
77  wcs = afwGeom.makeFlippedWcs(wcs, amp.getRawFlipX(), amp.getRawFlipY(), ampCenter)
78  # Shift WCS for trimming
79  if isTrimmed:
80  trim_shift = ampBox.getMin() - amp.getBBox().getMin()
81  wcs = wcs.copyAtShiftedPixelOrigin(lsst.geom.Extent2D(-trim_shift.getX(), -trim_shift.getY()))
82  # Account for shift of amp data in larger ccd matrix
83  offset = amp.getRawXYOffset()
84  return wcs.copyAtShiftedPixelOrigin(lsst.geom.Extent2D(offset))
85 
86 
87 def plotFocalPlane(camera, fieldSizeDeg_x=0, fieldSizeDeg_y=None, dx=0.1, dy=0.1, figsize=(10., 10.),
88  useIds=False, showFig=True, savePath=None):
89  """Make a plot of the focal plane along with a set points that sample
90  the field of view.
91 
92  Parameters
93  ----------
94  camera : `lsst.afw.cameraGeom.Camera`
95  A camera object
96  fieldSizeDeg_x : `float`
97  Amount of the field to sample in x in degrees
98  fieldSizeDeg_y : `float` or None
99  Amount of the field to sample in y in degrees
100  dx : `float`
101  Spacing of sample points in x in degrees
102  dy : `float`
103  Spacing of sample points in y in degrees
104  figsize : `tuple` containing two `float`
105  Matplotlib style tuple indicating the size of the figure in inches
106  useIds : `bool`
107  Label detectors by name, not id?
108  showFig : `bool`
109  Display the figure on the screen?
110  savePath : `str` or None
111  If not None, save a copy of the figure to this name.
112  """
113  try:
114  from matplotlib.patches import Polygon
115  from matplotlib.collections import PatchCollection
116  import matplotlib.pyplot as plt
117  except ImportError:
118  raise ImportError(
119  "Can't run plotFocalPlane: matplotlib has not been set up")
120 
121  if fieldSizeDeg_x:
122  if fieldSizeDeg_y is None:
123  fieldSizeDeg_y = fieldSizeDeg_x
124 
125  field_gridx, field_gridy = numpy.meshgrid(numpy.arange(0., fieldSizeDeg_x+dx, dx) - fieldSizeDeg_x/2.,
126  numpy.arange(0., fieldSizeDeg_y+dy, dy) - fieldSizeDeg_y/2.)
127  field_gridx, field_gridy = field_gridx.flatten(), field_gridy.flatten()
128  else:
129  field_gridx, field_gridy = [], []
130 
131  xs = []
132  ys = []
133  pcolors = []
134 
135  # compute focal plane positions corresponding to field angles field_gridx, field_gridy
136  posFieldAngleList = [lsst.geom.Point2D(x.asRadians(), y.asRadians())
137  for x, y in zip(field_gridx, field_gridy)]
138  posFocalPlaneList = camera.transform(posFieldAngleList, FIELD_ANGLE, FOCAL_PLANE)
139  for posFocalPlane in posFocalPlaneList:
140  xs.append(posFocalPlane.getX())
141  ys.append(posFocalPlane.getY())
142  dets = camera.findDetectors(posFocalPlane, FOCAL_PLANE)
143  if len(dets) > 0:
144  pcolors.append('w')
145  else:
146  pcolors.append('k')
147 
148  colorMap = {0: 'b', 1: 'y', 2: 'g', 3: 'r'}
149 
150  patches = []
151  colors = []
152  plt.figure(figsize=figsize)
153  ax = plt.gca()
154  xvals = []
155  yvals = []
156  for det in camera:
157  corners = [(c.getX(), c.getY()) for c in det.getCorners(FOCAL_PLANE)]
158  for corner in corners:
159  xvals.append(corner[0])
160  yvals.append(corner[1])
161  colors.append(colorMap[det.getType()])
162  patches.append(Polygon(corners, True))
163  center = det.getOrientation().getFpPosition()
164  ax.text(center.getX(), center.getY(), det.getId() if useIds else det.getName(),
165  horizontalalignment='center', size=6)
166 
167  patchCollection = PatchCollection(patches, alpha=0.6, facecolor=colors)
168  ax.add_collection(patchCollection)
169  ax.scatter(xs, ys, s=10, alpha=.7, linewidths=0., c=pcolors)
170  ax.set_xlim(min(xvals) - abs(0.1*min(xvals)),
171  max(xvals) + abs(0.1*max(xvals)))
172  ax.set_ylim(min(yvals) - abs(0.1*min(yvals)),
173  max(yvals) + abs(0.1*max(yvals)))
174  ax.set_xlabel('Focal Plane X (mm)')
175  ax.set_ylabel('Focal Plane Y (mm)')
176  if savePath is not None:
177  plt.savefig(savePath)
178  if showFig:
179  plt.show()
180 
181 
182 def makeImageFromAmp(amp, imValue=None, imageFactory=afwImage.ImageU, markSize=10, markValue=0,
183  scaleGain=lambda gain: (gain*1000)//10):
184  """Make an image from an amp object.
185 
186  Since images are integer images by default, the gain needs to be scaled to
187  give enough dynamic range to see variation from amp to amp.
188  The scaling algorithm is assignable.
189 
190  Parameters
191  ----------
192  amp : `lsst.afw.table.AmpInfoRecord`
193  Amp record to use for constructing the raw amp image.
194  imValue : `float` or None
195  Value to assign to the constructed image, or scaleGain(gain) if None.
196  imageFactory : callable like `lsst.afw.image.Image`
197  Type of image to construct.
198  markSize : `float`
199  Size of mark at read corner in pixels.
200  markValue : `float`
201  Value of pixels in the read corner mark.
202  scaleGain : callable
203  The function by which to scale the gain (must take a single argument).
204 
205  Returns
206  -------
207  ampImage : `lsst.afw.image`
208  An untrimmed amp image, of the type produced by ``imageFactory``.
209  """
210  if not amp.getHasRawInfo():
211  raise RuntimeError(
212  "Can't create a raw amp image without raw amp information")
213  bbox = amp.getRawBBox()
214  dbbox = amp.getRawDataBBox()
215  img = imageFactory(bbox)
216  if imValue is None:
217  img.set(scaleGain(amp.getGain()))
218  else:
219  img.set(imValue)
220  # Set the first pixel read to a different value
221  markbbox = lsst.geom.Box2I()
222  if amp.getReadoutCorner() == 0:
223  markbbox.include(dbbox.getMin())
224  markbbox.include(dbbox.getMin()+lsst.geom.Extent2I(markSize, markSize))
225  elif amp.getReadoutCorner() == 1:
226  cornerPoint = lsst.geom.Point2I(dbbox.getMaxX(), dbbox.getMinY())
227  markbbox.include(cornerPoint)
228  markbbox.include(cornerPoint + lsst.geom.Extent2I(-markSize, markSize))
229  elif amp.getReadoutCorner() == 2:
230  cornerPoint = lsst.geom.Point2I(dbbox.getMax())
231  markbbox.include(cornerPoint)
232  markbbox.include(cornerPoint + lsst.geom.Extent2I(-markSize, -markSize))
233  elif amp.getReadoutCorner() == 3:
234  cornerPoint = lsst.geom.Point2I(dbbox.getMinX(), dbbox.getMaxY())
235  markbbox.include(cornerPoint)
236  markbbox.include(cornerPoint + lsst.geom.Extent2I(markSize, -markSize))
237  else:
238  raise RuntimeError("Could not set readout corner")
239  mimg = imageFactory(img, markbbox)
240  mimg.set(markValue)
241  return img
242 
243 
244 def calcRawCcdBBox(ccd):
245  """Calculate the raw ccd bounding box.
246 
247  Parameters
248  ----------
249  ccd : `lsst.afw.cameraGeom.Detector`
250  Detector for which to calculate the un-trimmed bounding box.
251 
252  Returns
253  -------
254  box : `Box2I` or None
255  Bounding box of the un-trimmed Detector, or None if there is not enough
256  information to calculate raw BBox.
257  """
258  bbox = lsst.geom.Box2I()
259  for amp in ccd:
260  if not amp.getHasRawInfo():
261  return None
262  tbbox = amp.getRawBBox()
263  tbbox.shift(amp.getRawXYOffset())
264  bbox.include(tbbox)
265  return bbox
266 
267 
268 def makeImageFromCcd(ccd, isTrimmed=True, showAmpGain=True, imageFactory=afwImage.ImageU, rcMarkSize=10,
269  binSize=1):
270  """Make an Image of a CCD.
271 
272  Parameters
273  ----------
274  ccd : `lsst.afw.cameraGeom.Detector`
275  Detector to use in making the image.
276  isTrimmed : `bool`
277  Assemble a trimmed Detector image.
278  showAmpGain : `bool`
279  Use the per-amp gain to color the pixels in the image?
280  imageFactory : callable like `lsst.afw.image.Image`
281  Image type to generate.
282  rcMarkSize : `float`
283  Size of the mark to make in the amp images at the read corner.
284  binSize : `int`
285  Bin the image by this factor in both dimensions.
286 
287  Returns
288  -------
289  image : `lsst.afw.image.Image`
290  Image of the Detector (type returned by ``imageFactory``).
291  """
292  ampImages = []
293  index = 0
294  if isTrimmed:
295  bbox = ccd.getBBox()
296  else:
297  bbox = calcRawCcdBBox(ccd)
298  for amp in ccd:
299  if amp.getHasRawInfo():
300  if showAmpGain:
301  ampImages.append(makeImageFromAmp(
302  amp, imageFactory=imageFactory, markSize=rcMarkSize))
303  else:
304  ampImages.append(makeImageFromAmp(amp, imValue=(index+1)*1000,
305  imageFactory=imageFactory, markSize=rcMarkSize))
306  index += 1
307 
308  if len(ampImages) > 0:
309  ccdImage = imageFactory(bbox)
310  for ampImage, amp in zip(ampImages, ccd):
311  if isTrimmed:
312  assembleAmplifierImage(ccdImage, ampImage, amp)
313  else:
314  assembleAmplifierRawImage(ccdImage, ampImage, amp)
315  else:
316  if not isTrimmed:
317  raise RuntimeError(
318  "Cannot create untrimmed CCD without amps with raw information")
319  ccdImage = imageFactory(ccd.getBBox())
320  ccdImage = afwMath.binImage(ccdImage, binSize)
321  return ccdImage
322 
323 
325  """A class to retrieve synthetic images for display by the show* methods
326 
327  Parameters
328  ----------
329  isTrimmed : `bool`
330  Should amps be trimmed?
331  verbose : `bool`
332  Be chatty?
333  background : `float`
334  The value of any pixels that lie outside the CCDs.
335  showAmpGain : `bool`
336  Color the amp segments with the gain of the amp?
337  markSize : `float`
338  Size of the side of the box used to mark the read corner.
339  markValue : `float`
340  Value to assign the read corner mark.
341  ampImValue : `float` or None
342  Value to assign to amps; scaleGain(gain) is used if None.
343  scaleGain : callable
344  Function to scale the gain by.
345  """
346 
347  def __init__(self, isTrimmed=True, verbose=False, background=numpy.nan,
348  showAmpGain=True, markSize=10, markValue=0,
349  ampImValue=None, scaleGain=lambda gain: (gain*1000)//10):
350  self.isTrimmed = isTrimmed
351  self.verbose = verbose
352  self.background = background
353  self.showAmpGain = showAmpGain
354  self.markSize = markSize
355  self.markValue = markValue
356  self.ampImValue = ampImValue
357  self.scaleGain = scaleGain
358 
359  def getCcdImage(self, det, imageFactory, binSize):
360  """Return a CCD image for the detector and the (possibly updated) Detector.
361 
362  Parameters
363  ----------
364  det : `lsst.afw.cameraGeom.Detector`
365  Detector to use for making the image.
366  imageFactory : callable like `lsst.afw.image.Image`
367  Image constructor for making the image.
368  binSize : `int`
369  Bin the image by this factor in both dimensions.
370 
371  Returns
372  -------
373  ccdImage : `lsst.afw.image.Image`
374  The constructed image.
375  """
376  return makeImageFromCcd(det, isTrimmed=self.isTrimmed, showAmpGain=self.showAmpGain,
377  imageFactory=imageFactory, binSize=binSize), det
378 
379  def getAmpImage(self, amp, imageFactory):
380  """Return an amp segment image.
381 
382  Parameters
383  ----------
384  amp : `lsst.afw.table.AmpInfoTable`
385  AmpInfoTable for this amp.
386  imageFactory : callable like `lsst.afw.image.Image`
387  Image constructor for making the image.
388 
389  Returns
390  -------
391  ampImage : `lsst.afw.image.Image`
392  The constructed image.
393  """
394  ampImage = makeImageFromAmp(amp, imValue=self.ampImValue, imageFactory=imageFactory,
395  markSize=self.markSize, markValue=self.markValue,
396  scaleGain=self.scaleGain)
397  if self.isTrimmed:
398  ampImage = ampImage.Factory(ampImage, amp.getRawDataBBox())
399  return ampImage
400 
401 
403  """A class to return an Image of a given Ccd using the butler.
404 
405  Parameters
406  ----------
407  butler : `lsst.daf.persistence.Butler` or None
408  The butler to use. If None, an empty image is returned.
409  type : `str`
410  The type of image to read (e.g. raw, bias, flat, calexp).
411  isTrimmed : `bool`
412  If true, the showCamera command expects to be given trimmed images.
413  verbose : `bool`
414  Be chatty (in particular, log any error messages from the butler)?
415  background : `float`
416  The value of any pixels that lie outside the CCDs.
417  callback : callable
418  A function called with (image, ccd, butler) for every image, which
419  returns the image to be displayed (e.g. rawCallback). The image must
420  be of the correct size, allowing for the value of isTrimmed.
421  *args : `list`
422  Passed to the butler.
423  **kwargs : `dict`
424  Passed to the butler.
425 
426  Notes
427  -----
428  You can define a short named function as a callback::
429 
430  def callback(im, ccd, imageSource):
431  return cameraGeom.utils.rawCallback(im, ccd, imageSource, correctGain=True)
432  """
433 
434  def __init__(self, butler=None, type="raw",
435  isTrimmed=True, verbose=False, background=numpy.nan,
436  callback=None, *args, **kwargs):
437  super(ButlerImage, self).__init__(*args)
438  self.isTrimmed = isTrimmed
439  self.type = type
440  self.butler = butler
441  self.kwargs = kwargs
442  self.isRaw = False
443  self.background = background
444  self.verbose = verbose
445  self.callback = callback
446 
447  def _prepareImage(self, ccd, im, binSize, allowRotate=True):
448  if binSize > 1:
449  im = afwMath.binImage(im, binSize)
450 
451  if allowRotate:
453  im, ccd.getOrientation().getNQuarter())
454 
455  return im
456 
457  def getCcdImage(self, ccd, imageFactory=afwImage.ImageF, binSize=1, asMaskedImage=False):
458  """Return an image of the specified ccd, and also the (possibly updated) ccd"""
459 
460  log = lsst.log.Log.getLogger("afw.cameraGeom.utils.ButlerImage")
461 
462  if self.isTrimmed:
463  bbox = ccd.getBBox()
464  else:
465  bbox = calcRawCcdBBox(ccd)
466 
467  im = None
468  if self.butler is not None:
469  err = None
470  for dataId in [dict(detector=ccd.getId()), dict(ccd=ccd.getId()), dict(ccd=ccd.getName())]:
471  try:
472  im = self.butler.get(self.type, dataId, **self.kwargs)
473  except FitsError as e: # no point trying another dataId
474  err = IOError(e.args[0].split('\n')[0]) # It's a very chatty error
475  break
476  except Exception as e: # try a different dataId
477  if err is None:
478  err = e
479  continue
480  else:
481  ccd = im.getDetector() # possibly modified by assembleCcdTask
482  break
483 
484  if im:
485  if asMaskedImage:
486  im = im.getMaskedImage()
487  else:
488  im = im.getMaskedImage().getImage()
489  else:
490  if self.verbose:
491  print("Reading %s: %s" % (ccd.getId(), err)) # lost by jupyterLab
492 
493  log.warn("Reading %s: %s", ccd.getId(), err)
494 
495  if im is None:
496  return self._prepareImage(ccd, imageFactory(*bbox.getDimensions()), binSize), ccd
497 
498  if self.type == "raw":
499  if hasattr(im, 'convertF'):
500  im = im.convertF()
501  if False and self.callback is None: # we need to trim the raw image
502  self.callback = rawCallback
503 
504  allowRotate = True
505  if self.callback:
506  try:
507  im = self.callback(im, ccd, imageSource=self)
508  except Exception as e:
509  if self.verbose:
510  log.error("callback failed: %s" % e)
511  im = imageFactory(*bbox.getDimensions())
512  else:
513  allowRotate = False # the callback was responsible for any rotations
514 
515  return self._prepareImage(ccd, im, binSize, allowRotate=allowRotate), ccd
516 
517 
518 def rawCallback(im, ccd=None, imageSource=None,
519  correctGain=False, subtractBias=False, convertToFloat=False):
520  """A callback function that may or may not subtract bias/correct gain/trim
521  a raw image.
522 
523  Parameters
524  ----------
525  im : `lsst.afw.image.Image` or `lsst.afw.image.MaskedImage` or `lsst.afw.image.Exposure`
526  An image of a chip, ready to be binned and maybe rotated.
527  ccd : `lsst.afw.cameraGeom.Detector` or None
528  The Detector; if None assume that im is an exposure and extract its Detector.
529  imageSource : `FakeImageDataSource` or None
530  Source to get ccd images. Must have a `getCcdImage()` method.
531  correctGain : `bool`
532  Correct each amplifier for its gain?
533  subtractBias : `bool`
534  Subtract the bias from each amplifier?
535  convertToFloat : `bool`
536  Convert im to floating point if possible.
537 
538  Returns
539  -------
540  image : `lsst.afw.image.Image` like
541  The constructed image (type returned by ``im.Factory``).
542 
543  Notes
544  -----
545  If imageSource is derived from ButlerImage, imageSource.butler is available.
546  """
547  if ccd is None:
548  ccd = im.getDetector()
549  if hasattr(im, "getMaskedImage"):
550  im = im.getMaskedImage()
551  if convertToFloat and hasattr(im, "convertF"):
552  im = im.convertF()
553 
554  isTrimmed = imageSource.isTrimmed
555  if isTrimmed:
556  bbox = ccd.getBBox()
557  else:
558  bbox = calcRawCcdBBox(ccd)
559 
560  ampImages = []
561  for a in ccd:
562  if isTrimmed:
563  data = im[a.getRawDataBBox()]
564  else:
565  data = im
566 
567  if subtractBias:
568  bias = im[a.getRawHorizontalOverscanBBox()]
569  data -= afwMath.makeStatistics(bias, afwMath.MEANCLIP).getValue()
570  if correctGain:
571  data *= a.getGain()
572 
573  ampImages.append(data)
574 
575  ccdImage = im.Factory(bbox)
576  for ampImage, amp in zip(ampImages, ccd):
577  if isTrimmed:
578  assembleAmplifierImage(ccdImage, ampImage, amp)
579  else:
580  assembleAmplifierRawImage(ccdImage, ampImage, amp)
581 
582  return ccdImage
583 
584 
585 def overlayCcdBoxes(ccd, untrimmedCcdBbox=None, nQuarter=0,
586  isTrimmed=False, ccdOrigin=(0, 0), display=None, binSize=1):
587  """Overlay bounding boxes on an image display.
588 
589  Parameters
590  ----------
591  ccd : `lsst.afw.cameraGeom.Detector`
592  Detector to iterate for the amp bounding boxes.
593  untrimmedCcdBbox : `lsst.geom.Box2I` or None
594  Bounding box of the un-trimmed Detector.
595  nQuarter : `int`
596  number of 90 degree rotations to apply to the bounding boxes (used for rotated chips).
597  isTrimmed : `bool`
598  Is the Detector image over which the boxes are layed trimmed?
599  ccdOrigin : `tuple` of `float`
600  Detector origin relative to the parent origin if in a larger pixel grid.
601  display : `lsst.afw.display.Display`
602  Image display to display on.
603  binSize : `int`
604  Bin the image by this factor in both dimensions.
605 
606  Notes
607  -----
608  The colours are:
609  - Entire detector GREEN
610  - All data for amp GREEN
611  - HorizontalPrescan YELLOW
612  - HorizontalOverscan RED
613  - Data BLUE
614  - VerticalOverscan MAGENTA
615  - VerticalOverscan MAGENTA
616  """
617  if not display: # should be second parameter, and not defaulted!!
618  raise RuntimeError("Please specify a display")
619 
620  if untrimmedCcdBbox is None:
621  if isTrimmed:
622  untrimmedCcdBbox = ccd.getBBox()
623  else:
624  untrimmedCcdBbox = lsst.geom.Box2I()
625  for a in ccd.getAmpInfoCatalog():
626  bbox = a.getRawBBox()
627  untrimmedCcdBbox.include(bbox)
628 
629  with display.Buffering():
630  ccdDim = untrimmedCcdBbox.getDimensions()
631  ccdBbox = rotateBBoxBy90(untrimmedCcdBbox, nQuarter, ccdDim)
632  for amp in ccd:
633  if isTrimmed:
634  ampbbox = amp.getBBox()
635  else:
636  ampbbox = amp.getRawBBox()
637  if nQuarter != 0:
638  ampbbox = rotateBBoxBy90(ampbbox, nQuarter, ccdDim)
639 
640  displayUtils.drawBBox(ampbbox, origin=ccdOrigin, borderWidth=0.49,
641  display=display, bin=binSize)
642 
643  if not isTrimmed and amp.getHasRawInfo():
644  for bbox, ctype in ((amp.getRawHorizontalOverscanBBox(), afwDisplay.RED),
645  (amp.getRawDataBBox(), afwDisplay.BLUE),
646  (amp.getRawVerticalOverscanBBox(),
647  afwDisplay.MAGENTA),
648  (amp.getRawPrescanBBox(), afwDisplay.YELLOW)):
649  if nQuarter != 0:
650  bbox = rotateBBoxBy90(bbox, nQuarter, ccdDim)
651  displayUtils.drawBBox(bbox, origin=ccdOrigin, borderWidth=0.49, ctype=ctype,
652  display=display, bin=binSize)
653  # Label each Amp
654  xc, yc = (ampbbox.getMin()[0] + ampbbox.getMax()[0])//2, (ampbbox.getMin()[1] +
655  ampbbox.getMax()[1])//2
656  #
657  # Rotate the amp labels too
658  #
659  if nQuarter == 0:
660  c, s = 1, 0
661  elif nQuarter == 1:
662  c, s = 0, -1
663  elif nQuarter == 2:
664  c, s = -1, 0
665  elif nQuarter == 3:
666  c, s = 0, 1
667  c, s = 1, 0
668  ccdHeight = ccdBbox.getHeight()
669  ccdWidth = ccdBbox.getWidth()
670  xc -= 0.5*ccdHeight
671  yc -= 0.5*ccdWidth
672 
673  xc, yc = 0.5*ccdHeight + c*xc + s*yc, 0.5*ccdWidth + -s*xc + c*yc
674 
675  if ccdOrigin:
676  xc += ccdOrigin[0]
677  yc += ccdOrigin[1]
678  display.dot(str(amp.getName()), xc/binSize,
679  yc/binSize, textAngle=nQuarter*90)
680 
681  displayUtils.drawBBox(ccdBbox, origin=ccdOrigin,
682  borderWidth=0.49, ctype=afwDisplay.MAGENTA, display=display, bin=binSize)
683 
684 
685 def showAmp(amp, imageSource=FakeImageDataSource(isTrimmed=False), display=None, overlay=True,
686  imageFactory=afwImage.ImageU):
687  """Show an amp in an image display.
688 
689  Parameters
690  ----------
691  amp : `lsst.afw.tables.AmpInfoRecord`
692  Amp record to use in display.
693  imageSource : `FakeImageDataSource` or None
694  Source for getting the amp image. Must have a ``getAmpImage()`` method.
695  display : `lsst.afw.display.Display`
696  Image display to use.
697  overlay : `bool`
698  Overlay bounding boxes?
699  imageFactory : callable like `lsst.afw.image.Image`
700  Type of image to display (only used if ampImage is None).
701  """
702 
703  if not display:
704  display = _getDisplayFromDisplayOrFrame()
705 
706  ampImage = imageSource.getAmpImage(amp, imageFactory=imageFactory)
707  ampImSize = ampImage.getDimensions()
708  title = amp.getName()
709  display.mtv(ampImage, title=title)
710  if overlay:
711  with display.Buffering():
712  if amp.getHasRawInfo() and ampImSize == amp.getRawBBox().getDimensions():
713  bboxes = [(amp.getRawBBox(), 0.49, afwDisplay.GREEN), ]
714  xy0 = bboxes[0][0].getMin()
715  bboxes.append(
716  (amp.getRawHorizontalOverscanBBox(), 0.49, afwDisplay.RED))
717  bboxes.append((amp.getRawDataBBox(), 0.49, afwDisplay.BLUE))
718  bboxes.append((amp.getRawPrescanBBox(),
719  0.49, afwDisplay.YELLOW))
720  bboxes.append((amp.getRawVerticalOverscanBBox(),
721  0.49, afwDisplay.MAGENTA))
722  else:
723  bboxes = [(amp.getBBox(), 0.49, None), ]
724  xy0 = bboxes[0][0].getMin()
725 
726  for bbox, borderWidth, ctype in bboxes:
727  if bbox.isEmpty():
728  continue
729  bbox = lsst.geom.Box2I(bbox)
730  bbox.shift(-lsst.geom.ExtentI(xy0))
731  displayUtils.drawBBox(
732  bbox, borderWidth=borderWidth, ctype=ctype, display=display)
733 
734 
735 def showCcd(ccd, imageSource=FakeImageDataSource(), display=None, frame=None, overlay=True,
736  imageFactory=afwImage.ImageF, binSize=1, inCameraCoords=False):
737  """Show a CCD on display.
738 
739  Parameters
740  ----------
741  ccd : `lsst.afw.cameraGeom.Detector`
742  Detector to use in display.
743  imageSource : `FakeImageDataSource` or None
744  Source to get ccd images. Must have a ``getCcdImage()`` method.
745  display : `lsst.afw.display.Display`
746  image display to use.
747  frame : None
748  frame ID on which to display. **Deprecated** in v12.
749  overlay : `bool`
750  Show amp bounding boxes on the displayed image?
751  imageFactory : callable like `lsst.afw.image.Image`
752  The image factory to use in generating the images.
753  binSize : `int`
754  Bin the image by this factor in both dimensions.
755  inCameraCoords : `bool`
756  Show the Detector in camera coordinates?
757  """
758  if frame is not None:
759  warnings.warn("The frame kwarg is deprecated; use the `lsst.afw.display` system instead.",
760  DeprecationWarning)
761 
762  display = _getDisplayFromDisplayOrFrame(display, frame)
763 
764  ccdOrigin = lsst.geom.Point2I(0, 0)
765  nQuarter = 0
766  ccdImage, ccd = imageSource.getCcdImage(
767  ccd, imageFactory=imageFactory, binSize=binSize)
768 
769  ccdBbox = ccdImage.getBBox()
770  if ccdBbox.getDimensions() == ccd.getBBox().getDimensions():
771  isTrimmed = True
772  else:
773  isTrimmed = False
774 
775  if inCameraCoords:
776  nQuarter = ccd.getOrientation().getNQuarter()
777  ccdImage = afwMath.rotateImageBy90(ccdImage, nQuarter)
778  title = ccd.getName()
779  if isTrimmed:
780  title += "(trimmed)"
781 
782  if display:
783  display.mtv(ccdImage, title=title)
784 
785  if overlay:
786  overlayCcdBoxes(ccd, ccdBbox, nQuarter, isTrimmed,
787  ccdOrigin, display, binSize)
788 
789  return ccdImage
790 
791 
792 def getCcdInCamBBoxList(ccdList, binSize, pixelSize_o, origin):
793  """Get the bounding boxes of a list of Detectors within a camera sized pixel grid
794 
795  Parameters
796  ----------
797  ccdList : `lsst.afw.cameraGeom.Detector`
798  List of Detector.
799  binSize : `int`
800  Bin the image by this factor in both dimensions.
801  pixelSize_o : `float`
802  Size of the pixel in mm.
803  origin : `int`
804  Origin of the camera pixel grid in pixels.
805 
806  Returns
807  -------
808  boxList : `list` of `lsst.geom.Box2I`
809  A list of bounding boxes in camera pixel coordinates.
810  """
811  boxList = []
812  for ccd in ccdList:
813  if not pixelSize_o == ccd.getPixelSize():
814  raise RuntimeError(
815  "Cameras with detectors with different pixel scales are not currently supported")
816 
817  dbbox = lsst.geom.Box2D()
818  for corner in ccd.getCorners(FOCAL_PLANE):
819  dbbox.include(corner)
820  llc = dbbox.getMin()
821  nQuarter = ccd.getOrientation().getNQuarter()
822  cbbox = ccd.getBBox()
823  ex = cbbox.getDimensions().getX()//binSize
824  ey = cbbox.getDimensions().getY()//binSize
825  bbox = lsst.geom.Box2I(
826  cbbox.getMin(), lsst.geom.Extent2I(int(ex), int(ey)))
827  bbox = rotateBBoxBy90(bbox, nQuarter, bbox.getDimensions())
828  bbox.shift(lsst.geom.Extent2I(int(llc.getX()//pixelSize_o.getX()/binSize),
829  int(llc.getY()//pixelSize_o.getY()/binSize)))
830  bbox.shift(lsst.geom.Extent2I(-int(origin.getX()//binSize),
831  -int(origin.getY())//binSize))
832  boxList.append(bbox)
833  return boxList
834 
835 
836 def getCameraImageBBox(camBbox, pixelSize, bufferSize):
837  """Get the bounding box of a camera sized image in pixels
838 
839  Parameters
840  ----------
841  camBbox : `lsst.geom.Box2D`
842  Camera bounding box in focal plane coordinates (mm).
843  pixelSize : `float`
844  Size of a detector pixel in mm.
845  bufferSize : `int`
846  Buffer around edge of image in pixels.
847 
848  Returns
849  -------
850  box : `lsst.geom.Box2I`
851  The resulting bounding box.
852  """
853  pixMin = lsst.geom.Point2I(int(camBbox.getMinX()//pixelSize.getX()),
854  int(camBbox.getMinY()//pixelSize.getY()))
855  pixMax = lsst.geom.Point2I(int(camBbox.getMaxX()//pixelSize.getX()),
856  int(camBbox.getMaxY()//pixelSize.getY()))
857  retBox = lsst.geom.Box2I(pixMin, pixMax)
858  retBox.grow(bufferSize)
859  return retBox
860 
861 
862 def makeImageFromCamera(camera, detectorNameList=None, background=numpy.nan, bufferSize=10,
863  imageSource=FakeImageDataSource(), imageFactory=afwImage.ImageU, binSize=1):
864  """Make an Image of a Camera.
865 
866  Put each detector's image in the correct location and orientation on the
867  focal plane. The input images can be binned to an integer fraction of their
868  original bboxes.
869 
870  Parameters
871  ----------
872  camera : `lsst.afw.cameraGeom.Camera`
873  Camera object to use to make the image.
874  detectorNameList : `list` of `str`
875  List of detector names from `camera` to use in building the image.
876  Use all Detectors if None.
877  background : `float`
878  Value to use where there is no Detector.
879  bufferSize : `int`
880  Size of border in binned pixels to make around the camera image.
881  imageSource : `FakeImageDataSource` or None
882  Source to get ccd images. Must have a ``getCcdImage()`` method.
883  imageFactory : callable like `lsst.afw.image.Image`
884  Type of image to build.
885  binSize : `int`
886  Bin the image by this factor in both dimensions.
887 
888  Returns
889  -------
890  image : `lsst.afw.image.Image`
891  Image of the entire camera.
892  """
893  log = lsst.log.Log.getLogger("afw.cameraGeom.utils.makeImageFromCamera")
894 
895  if detectorNameList is None:
896  ccdList = camera
897  else:
898  ccdList = [camera[name] for name in detectorNameList]
899 
900  if detectorNameList is None:
901  camBbox = camera.getFpBBox()
902  else:
903  camBbox = lsst.geom.Box2D()
904  for detName in detectorNameList:
905  for corner in camera[detName].getCorners(FOCAL_PLANE):
906  camBbox.include(corner)
907 
908  pixelSize_o = camera[next(camera.getNameIter())].getPixelSize()
909  camBbox = getCameraImageBBox(camBbox, pixelSize_o, bufferSize*binSize)
910  origin = camBbox.getMin()
911 
912  camIm = imageFactory(int(math.ceil(camBbox.getDimensions().getX()/binSize)),
913  int(math.ceil(camBbox.getDimensions().getY()/binSize)))
914  camIm[:] = imageSource.background
915 
916  assert imageSource.isTrimmed, "isTrimmed is False isn't supported by getCcdInCamBBoxList"
917 
918  boxList = getCcdInCamBBoxList(ccdList, binSize, pixelSize_o, origin)
919  for det, bbox in zip(ccdList, boxList):
920  im = imageSource.getCcdImage(det, imageFactory, binSize)[0]
921  if im is None:
922  continue
923 
924  nQuarter = det.getOrientation().getNQuarter()
925  im = afwMath.rotateImageBy90(im, nQuarter)
926 
927  imView = camIm.Factory(camIm, bbox, afwImage.LOCAL)
928  try:
929  imView[:] = im
930  except pexExceptions.LengthError as e:
931  log.error("Unable to fit image for detector \"%s\" into image of camera: %s" % (det.getName(), e))
932 
933  return camIm
934 
935 
936 def showCamera(camera, imageSource=FakeImageDataSource(), imageFactory=afwImage.ImageF,
937  detectorNameList=None, binSize=10, bufferSize=10, frame=None, overlay=True, title="",
938  showWcs=None, ctype=afwDisplay.GREEN, textSize=1.25, originAtCenter=True, display=None,
939  **kwargs):
940  """Show a Camera on display, with the specified display.
941 
942  The rotation of the sensors is snapped to the nearest multiple of 90 deg.
943  Also note that the pixel size is constant over the image array. The lower
944  left corner (LLC) of each sensor amp is snapped to the LLC of the pixel
945  containing the LLC of the image.
946 
947  Parameters
948  ----------
949  camera : `lsst.afw.cameraGeom.Camera`
950  Camera object to use to make the image.
951  imageSource : `FakeImageDataSource` or None
952  Source to get ccd images. Must have a ``getCcdImage()`` method.
953  imageFactory : `lsst.afw.image.Image`
954  Type of image to make
955  detectorNameList : `list` of `str`
956  List of detector names from `camera` to use in building the image.
957  Use all Detectors if None.
958  binSize : `int`
959  Bin the image by this factor in both dimensions.
960  bufferSize : `int`
961  Size of border in binned pixels to make around the camera image.
962  frame : None
963  specify image display. **Deprecated** in v12.
964  overlay : `bool`
965  Overlay Detector IDs and boundaries?
966  title : `str`
967  Title to use in display.
968  showWcs : `bool`
969  Include a WCS in the display?
970  ctype : `lsst.afw.display.COLOR` or `str`
971  Color to use when drawing Detector boundaries.
972  textSize : `float`
973  Size of detector labels
974  originAtCenter : `bool`
975  Put origin of the camera WCS at the center of the image?
976  If False, the origin will be at the lower left.
977  display : `lsst.afw.display`
978  Image display on which to display.
979  **kwargs :
980  All remaining keyword arguments are passed to makeImageFromCamera
981 
982  Returns
983  -------
984  image : `lsst.afw.image.Image`
985  The mosaic image.
986  """
987  if frame is not None:
988  warnings.warn("The frame kwarg is deprecated; use the `lsst.afw.display` system instead.",
989  DeprecationWarning)
990 
991  display = _getDisplayFromDisplayOrFrame(display, frame)
992 
993  if binSize < 1:
994  binSize = 1
995  cameraImage = makeImageFromCamera(camera, detectorNameList=detectorNameList, bufferSize=bufferSize,
996  imageSource=imageSource, imageFactory=imageFactory, binSize=binSize,
997  **kwargs)
998 
999  if detectorNameList is None:
1000  ccdList = [camera[name] for name in camera.getNameIter()]
1001  else:
1002  ccdList = [camera[name] for name in detectorNameList]
1003 
1004  if detectorNameList is None:
1005  camBbox = camera.getFpBBox()
1006  else:
1007  camBbox = lsst.geom.Box2D()
1008  for detName in detectorNameList:
1009  for corner in camera[detName].getCorners(FOCAL_PLANE):
1010  camBbox.include(corner)
1011  pixelSize = ccdList[0].getPixelSize()
1012 
1013  if showWcs:
1014  if originAtCenter:
1015  wcsReferencePixel = lsst.geom.Box2D(
1016  cameraImage.getBBox()).getCenter()
1017  else:
1018  wcsReferencePixel = lsst.geom.Point2I(0, 0)
1019  wcs = makeFocalPlaneWcs(pixelSize*binSize, wcsReferencePixel)
1020  else:
1021  wcs = None
1022 
1023  if display:
1024  if title == "":
1025  title = camera.getName()
1026  display.mtv(cameraImage, title=title, wcs=wcs)
1027 
1028  if overlay:
1029  with display.Buffering():
1030  camBbox = getCameraImageBBox(
1031  camBbox, pixelSize, bufferSize*binSize)
1032  bboxList = getCcdInCamBBoxList(
1033  ccdList, binSize, pixelSize, camBbox.getMin())
1034  for bbox, ccd in zip(bboxList, ccdList):
1035  nQuarter = ccd.getOrientation().getNQuarter()
1036  # borderWidth to 0.5 to align with the outside edge of the
1037  # pixel
1038  displayUtils.drawBBox(
1039  bbox, borderWidth=0.5, ctype=ctype, display=display)
1040  dims = bbox.getDimensions()
1041  display.dot(ccd.getName(), bbox.getMinX()+dims.getX()/2, bbox.getMinY()+dims.getY()/2,
1042  ctype=ctype, size=textSize, textAngle=nQuarter*90)
1043 
1044  return cameraImage
1045 
1046 
1047 def makeFocalPlaneWcs(pixelSize, referencePixel):
1048  """Make a WCS for the focal plane geometry
1049  (i.e. one that returns positions in "mm")
1050 
1051  Parameters
1052  ----------
1053  pixelSize : `float`
1054  Size of the image pixels in physical units
1055  referencePixel : `lsst.geom.Point2D`
1056  Pixel for origin of WCS
1057 
1058  Returns
1059  -------
1060  `lsst.afw.geom.Wcs`
1061  Wcs object for mapping between pixels and focal plane.
1062  """
1063 
1064  md = dafBase.PropertySet()
1065  if referencePixel is None:
1066  referencePixel = lsst.geom.PointD(0, 0)
1067  for i in range(2):
1068  md.set("CRPIX%d"%(i+1), referencePixel[i])
1069  md.set("CRVAL%d"%(i+1), 0.)
1070  md.set("CDELT1", pixelSize[0])
1071  md.set("CDELT2", pixelSize[1])
1072  md.set("CTYPE1", "CAMERA_X")
1073  md.set("CTYPE2", "CAMERA_Y")
1074  md.set("CUNIT1", "mm")
1075  md.set("CUNIT2", "mm")
1076 
1077  return afwGeom.makeSkyWcs(md)
1078 
1079 
1080 def findAmp(ccd, pixelPosition):
1081  """Find the Amp with the specified pixel position within the composite
1082 
1083  Parameters
1084  ----------
1085  ccd : `lsst.afw.cameraGeom.Detector`
1086  Detector to look in.
1087  pixelPosition : `lsst.geom.Point2I`
1088  The pixel position to find the amp for.
1089 
1090  Returns
1091  -------
1092  `lsst.afw.table.AmpInfoCatalog`
1093  Amp record in which pixelPosition falls or None if no Amp found.
1094  """
1095 
1096  for amp in ccd:
1097  if amp.getBBox().contains(pixelPosition):
1098  return amp
1099 
1100  return None
def makeImageFromAmp(amp, imValue=None, imageFactory=afwImage.ImageU, markSize=10, markValue=0, scaleGain=lambda gain:(gain *1000)//10)
Definition: utils.py:183
def makeFocalPlaneWcs(pixelSize, referencePixel)
Definition: utils.py:1047
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)
Definition: utils.py:939
def plotFocalPlane(camera, fieldSizeDeg_x=0, fieldSizeDeg_y=None, dx=0.1, dy=0.1, figsize=(10., 10.), useIds=False, showFig=True, savePath=None)
Definition: utils.py:88
def showCcd(ccd, imageSource=FakeImageDataSource(), display=None, frame=None, overlay=True, imageFactory=afwImage.ImageF, binSize=1, inCameraCoords=False)
Definition: utils.py:736
def getCcdInCamBBoxList(ccdList, binSize, pixelSize_o, origin)
Definition: utils.py:792
def getCcdImage(self, det, imageFactory, binSize)
Definition: utils.py:359
def findAmp(ccd, pixelPosition)
Definition: utils.py:1080
def getCameraImageBBox(camBbox, pixelSize, bufferSize)
Definition: utils.py:836
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:520
def getAmpImage(self, amp, imageFactory)
Definition: utils.py:379
def __init__(self, isTrimmed=True, verbose=False, background=numpy.nan, showAmpGain=True, markSize=10, markValue=0, ampImValue=None, scaleGain=lambda gain:(gain *1000)//10)
Definition: utils.py:349
def rawCallback(im, ccd=None, imageSource=None, correctGain=False, subtractBias=False, convertToFloat=False)
Definition: utils.py:519
def _prepareImage(self, ccd, im, binSize, allowRotate=True)
Definition: utils.py:447
def makeImageFromCamera(camera, detectorNameList=None, background=numpy.nan, bufferSize=10, imageSource=FakeImageDataSource(), imageFactory=afwImage.ImageU, binSize=1)
Definition: utils.py:863
int max
def __init__(self, butler=None, type="raw", isTrimmed=True, verbose=False, background=numpy.nan, callback=None, args, kwargs)
Definition: utils.py:436
def makeImageFromCcd(ccd, isTrimmed=True, showAmpGain=True, imageFactory=afwImage.ImageU, rcMarkSize=10, binSize=1)
Definition: utils.py:269
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 assembleAmplifierImage(destImage, rawImage, amplifier)
def showAmp(amp, imageSource=FakeImageDataSource(isTrimmed=False), display=None, overlay=True, imageFactory=afwImage.ImageU)
Definition: utils.py:686
int min
def prepareWcsData(wcs, amp, isTrimmed=True)
Definition: utils.py:53
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)
static Log getLogger(std::string const &loggername)
def overlayCcdBoxes(ccd, untrimmedCcdBbox=None, nQuarter=0, isTrimmed=False, ccdOrigin=(0, 0), display=None, binSize=1)
Definition: utils.py:586
def rotateBBoxBy90(bbox, n90, dimensions)
def getCcdImage(self, ccd, imageFactory=afwImage.ImageF, binSize=1, asMaskedImage=False)
Definition: utils.py:457