lsst.afw  17.0.1-19-gee9b810f8+2
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(
126  numpy.arange(0., fieldSizeDeg_x + dx, dx) - fieldSizeDeg_x/2.,
127  numpy.arange(0., fieldSizeDeg_y + dy, dy) - fieldSizeDeg_y/2.)
128  field_gridx, field_gridy = field_gridx.flatten(), field_gridy.flatten()
129  else:
130  field_gridx, field_gridy = [], []
131 
132  xs = []
133  ys = []
134  pcolors = []
135 
136  # compute focal plane positions corresponding to field angles field_gridx, field_gridy
137  posFieldAngleList = [lsst.geom.Point2D(x*lsst.geom.radians, y*lsst.geom.radians)
138  for x, y in zip(field_gridx, field_gridy)]
139  posFocalPlaneList = camera.transform(posFieldAngleList, FIELD_ANGLE, FOCAL_PLANE)
140  for posFocalPlane in posFocalPlaneList:
141  xs.append(posFocalPlane.getX())
142  ys.append(posFocalPlane.getY())
143  dets = camera.findDetectors(posFocalPlane, FOCAL_PLANE)
144  if len(dets) > 0:
145  pcolors.append('w')
146  else:
147  pcolors.append('k')
148 
149  colorMap = {0: 'b', 1: 'y', 2: 'g', 3: 'r'}
150 
151  patches = []
152  colors = []
153  plt.figure(figsize=figsize)
154  ax = plt.gca()
155  xvals = []
156  yvals = []
157  for det in camera:
158  corners = [(c.getX(), c.getY()) for c in det.getCorners(FOCAL_PLANE)]
159  for corner in corners:
160  xvals.append(corner[0])
161  yvals.append(corner[1])
162  colors.append(colorMap[det.getType()])
163  patches.append(Polygon(corners, True))
164  center = det.getOrientation().getFpPosition()
165  ax.text(center.getX(), center.getY(), det.getId() if useIds else det.getName(),
166  horizontalalignment='center', size=6)
167 
168  patchCollection = PatchCollection(patches, alpha=0.6, facecolor=colors)
169  ax.add_collection(patchCollection)
170  ax.scatter(xs, ys, s=10, alpha=.7, linewidths=0., c=pcolors)
171  ax.set_xlim(min(xvals) - abs(0.1*min(xvals)),
172  max(xvals) + abs(0.1*max(xvals)))
173  ax.set_ylim(min(yvals) - abs(0.1*min(yvals)),
174  max(yvals) + abs(0.1*max(yvals)))
175  ax.set_xlabel('Focal Plane X (mm)')
176  ax.set_ylabel('Focal Plane Y (mm)')
177  if savePath is not None:
178  plt.savefig(savePath)
179  if showFig:
180  plt.show()
181 
182 
183 def makeImageFromAmp(amp, imValue=None, imageFactory=afwImage.ImageU, markSize=10, markValue=0,
184  scaleGain=lambda gain: (gain*1000)//10):
185  """Make an image from an amp object.
186 
187  Since images are integer images by default, the gain needs to be scaled to
188  give enough dynamic range to see variation from amp to amp.
189  The scaling algorithm is assignable.
190 
191  Parameters
192  ----------
193  amp : `lsst.afw.table.AmpInfoRecord`
194  Amp record to use for constructing the raw amp image.
195  imValue : `float` or `None`
196  Value to assign to the constructed image, or scaleGain(gain) if `None`.
197  imageFactory : callable like `lsst.afw.image.Image`
198  Type of image to construct.
199  markSize : `float`
200  Size of mark at read corner in pixels.
201  markValue : `float`
202  Value of pixels in the read corner mark.
203  scaleGain : callable
204  The function by which to scale the gain (must take a single argument).
205 
206  Returns
207  -------
208  ampImage : `lsst.afw.image`
209  An untrimmed amp image, of the type produced by ``imageFactory``.
210  """
211  if not amp.getHasRawInfo():
212  raise RuntimeError(
213  "Can't create a raw amp image without raw amp information")
214  bbox = amp.getRawBBox()
215  dbbox = amp.getRawDataBBox()
216  img = imageFactory(bbox)
217  if imValue is None:
218  img.set(int(scaleGain(amp.getGain())))
219  else:
220  img.set(imValue)
221  # Set the first pixel read to a different value
222  markbbox = lsst.geom.Box2I()
223  if amp.getReadoutCorner() == 0:
224  markbbox.include(dbbox.getMin())
225  markbbox.include(dbbox.getMin() + lsst.geom.Extent2I(markSize, markSize))
226  elif amp.getReadoutCorner() == 1:
227  cornerPoint = lsst.geom.Point2I(dbbox.getMaxX(), dbbox.getMinY())
228  markbbox.include(cornerPoint)
229  markbbox.include(cornerPoint + lsst.geom.Extent2I(-markSize, markSize))
230  elif amp.getReadoutCorner() == 2:
231  cornerPoint = lsst.geom.Point2I(dbbox.getMax())
232  markbbox.include(cornerPoint)
233  markbbox.include(cornerPoint + lsst.geom.Extent2I(-markSize, -markSize))
234  elif amp.getReadoutCorner() == 3:
235  cornerPoint = lsst.geom.Point2I(dbbox.getMinX(), dbbox.getMaxY())
236  markbbox.include(cornerPoint)
237  markbbox.include(cornerPoint + lsst.geom.Extent2I(markSize, -markSize))
238  else:
239  raise RuntimeError("Could not set readout corner")
240  mimg = imageFactory(img, markbbox)
241  mimg.set(markValue)
242  return img
243 
244 
245 def calcRawCcdBBox(ccd):
246  """Calculate the raw ccd bounding box.
247 
248  Parameters
249  ----------
250  ccd : `lsst.afw.cameraGeom.Detector`
251  Detector for which to calculate the un-trimmed bounding box.
252 
253  Returns
254  -------
255  bbox : `lsst.geom.Box2I` or `None`
256  Bounding box of the un-trimmed Detector, or `None` if there is not enough
257  information to calculate raw BBox.
258  """
259  bbox = lsst.geom.Box2I()
260  for amp in ccd:
261  if not amp.getHasRawInfo():
262  return None
263  tbbox = amp.getRawBBox()
264  tbbox.shift(amp.getRawXYOffset())
265  bbox.include(tbbox)
266  return bbox
267 
268 
269 def makeImageFromCcd(ccd, isTrimmed=True, showAmpGain=True, imageFactory=afwImage.ImageU, rcMarkSize=10,
270  binSize=1):
271  """Make an Image of a CCD.
272 
273  Parameters
274  ----------
275  ccd : `lsst.afw.cameraGeom.Detector`
276  Detector to use in making the image.
277  isTrimmed : `bool`
278  Assemble a trimmed Detector image.
279  showAmpGain : `bool`
280  Use the per-amp gain to color the pixels in the image?
281  imageFactory : callable like `lsst.afw.image.Image`
282  Image type to generate.
283  rcMarkSize : `float`
284  Size of the mark to make in the amp images at the read corner.
285  binSize : `int`
286  Bin the image by this factor in both dimensions.
287 
288  Returns
289  -------
290  image : `lsst.afw.image.Image`
291  Image of the Detector (type returned by ``imageFactory``).
292  """
293  ampImages = []
294  index = 0
295  if isTrimmed:
296  bbox = ccd.getBBox()
297  else:
298  bbox = calcRawCcdBBox(ccd)
299  for amp in ccd:
300  if amp.getHasRawInfo():
301  if showAmpGain:
302  ampImages.append(makeImageFromAmp(
303  amp, imageFactory=imageFactory, markSize=rcMarkSize))
304  else:
305  ampImages.append(makeImageFromAmp(amp, imValue=(index + 1)*1000,
306  imageFactory=imageFactory, markSize=rcMarkSize))
307  index += 1
308 
309  if len(ampImages) > 0:
310  ccdImage = imageFactory(bbox)
311  for ampImage, amp in zip(ampImages, ccd):
312  if isTrimmed:
313  assembleAmplifierImage(ccdImage, ampImage, amp)
314  else:
315  assembleAmplifierRawImage(ccdImage, ampImage, amp)
316  else:
317  if not isTrimmed:
318  raise RuntimeError(
319  "Cannot create untrimmed CCD without amps with raw information")
320  ccdImage = imageFactory(ccd.getBBox())
321  ccdImage = afwMath.binImage(ccdImage, binSize)
322  return ccdImage
323 
324 
326  """A class to retrieve synthetic images for display by the show* methods
327 
328  Parameters
329  ----------
330  isTrimmed : `bool`
331  Should amps be trimmed?
332  verbose : `bool`
333  Be chatty?
334  background : `float`
335  The value of any pixels that lie outside the CCDs.
336  showAmpGain : `bool`
337  Color the amp segments with the gain of the amp?
338  markSize : `float`
339  Size of the side of the box used to mark the read corner.
340  markValue : `float`
341  Value to assign the read corner mark.
342  ampImValue : `float` or `None`
343  Value to assign to amps; scaleGain(gain) is used if `None`.
344  scaleGain : callable
345  Function to scale the gain by.
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  def __init__(self, butler=None, type="raw",
434  isTrimmed=True, verbose=False, background=numpy.nan,
435  callback=None, *args, **kwargs):
436  super(ButlerImage, self).__init__(*args)
437  self.isTrimmed = isTrimmed
438  self.type = type
439  self.butler = butler
440  self.kwargs = kwargs
441  self.isRaw = False
442  self.background = background
443  self.verbose = verbose
444  self.callback = callback
445 
446  def _prepareImage(self, ccd, im, binSize, allowRotate=True):
447  if binSize > 1:
448  im = afwMath.binImage(im, binSize)
449 
450  if allowRotate:
452  im, ccd.getOrientation().getNQuarter())
453 
454  return im
455 
456  def getCcdImage(self, ccd, imageFactory=afwImage.ImageF, binSize=1, asMaskedImage=False):
457  """Return an image of the specified ccd, and also the (possibly updated) ccd"""
458 
459  log = lsst.log.Log.getLogger("afw.cameraGeom.utils.ButlerImage")
460 
461  if self.isTrimmed:
462  bbox = ccd.getBBox()
463  else:
464  bbox = calcRawCcdBBox(ccd)
465 
466  im = None
467  if self.butler is not None:
468  err = None
469  for dataId in [dict(detector=ccd.getId()), dict(ccd=ccd.getId()), dict(ccd=ccd.getName())]:
470  try:
471  im = self.butler.get(self.type, dataId, **self.kwargs)
472  except FitsError as e: # no point trying another dataId
473  err = IOError(e.args[0].split('\n')[0]) # It's a very chatty error
474  break
475  except Exception as e: # try a different dataId
476  if err is None:
477  err = e
478  continue
479  else:
480  ccd = im.getDetector() # possibly modified by assembleCcdTask
481  break
482 
483  if im:
484  if asMaskedImage:
485  im = im.getMaskedImage()
486  else:
487  im = im.getMaskedImage().getImage()
488  else:
489  if self.verbose:
490  print("Reading %s: %s" % (ccd.getId(), err)) # lost by jupyterLab
491 
492  log.warn("Reading %s: %s", ccd.getId(), err)
493 
494  if im is None:
495  return self._prepareImage(ccd, imageFactory(*bbox.getDimensions()), binSize), ccd
496 
497  if self.type == "raw":
498  if hasattr(im, 'convertF'):
499  im = im.convertF()
500  if False and self.callback is None: # we need to trim the raw image
501  self.callback = rawCallback
502 
503  allowRotate = True
504  if self.callback:
505  try:
506  im = self.callback(im, ccd, imageSource=self)
507  except Exception as e:
508  if self.verbose:
509  log.error("callback failed: %s" % e)
510  im = imageFactory(*bbox.getDimensions())
511  else:
512  allowRotate = False # the callback was responsible for any rotations
513 
514  return self._prepareImage(ccd, im, binSize, allowRotate=allowRotate), ccd
515 
516 
517 def rawCallback(im, ccd=None, imageSource=None,
518  correctGain=False, subtractBias=False, convertToFloat=False, obeyNQuarter=True):
519  """A callback function that may or may not subtract bias/correct gain/trim
520  a raw image.
521 
522  Parameters
523  ----------
524  im : `lsst.afw.image.Image` or `lsst.afw.image.MaskedImage` or `lsst.afw.image.Exposure`
525  An image of a chip, ready to be binned and maybe rotated.
526  ccd : `lsst.afw.cameraGeom.Detector` or `None`
527  The Detector; if `None` assume that im is an exposure and extract its Detector.
528  imageSource : `FakeImageDataSource` or `None`
529  Source to get ccd images. Must have a `getCcdImage()` method.
530  correctGain : `bool`
531  Correct each amplifier for its gain?
532  subtractBias : `bool`
533  Subtract the bias from each amplifier?
534  convertToFloat : `bool`
535  Convert ``im`` to floating point if possible.
536  obeyNQuarter : `bool`
537  Obey nQuarter from the Detector (default: True)
538 
539  Returns
540  -------
541  image : `lsst.afw.image.Image` like
542  The constructed image (type returned by ``im.Factory``).
543 
544  Notes
545  -----
546  If imageSource is derived from ButlerImage, imageSource.butler is available.
547  """
548  if ccd is None:
549  ccd = im.getDetector()
550  if hasattr(im, "getMaskedImage"):
551  im = im.getMaskedImage()
552  if convertToFloat and hasattr(im, "convertF"):
553  im = im.convertF()
554 
555  isTrimmed = imageSource.isTrimmed
556  if isTrimmed:
557  bbox = ccd.getBBox()
558  else:
559  bbox = calcRawCcdBBox(ccd)
560 
561  ampImages = []
562  for a in ccd:
563  if isTrimmed:
564  data = im[a.getRawDataBBox()]
565  else:
566  data = im
567 
568  if subtractBias:
569  bias = im[a.getRawHorizontalOverscanBBox()]
570  data -= afwMath.makeStatistics(bias, afwMath.MEANCLIP).getValue()
571  if correctGain:
572  data *= a.getGain()
573 
574  ampImages.append(data)
575 
576  ccdImage = im.Factory(bbox)
577  for ampImage, amp in zip(ampImages, ccd):
578  if isTrimmed:
579  assembleAmplifierImage(ccdImage, ampImage, amp)
580  else:
581  assembleAmplifierRawImage(ccdImage, ampImage, amp)
582 
583  if obeyNQuarter:
584  nQuarter = ccd.getOrientation().getNQuarter()
585  ccdImage = afwMath.rotateImageBy90(ccdImage, nQuarter)
586 
587  return ccdImage
588 
589 
590 def overlayCcdBoxes(ccd, untrimmedCcdBbox=None, nQuarter=0,
591  isTrimmed=False, ccdOrigin=(0, 0), display=None, binSize=1):
592  """Overlay bounding boxes on an image display.
593 
594  Parameters
595  ----------
596  ccd : `lsst.afw.cameraGeom.Detector`
597  Detector to iterate for the amp bounding boxes.
598  untrimmedCcdBbox : `lsst.geom.Box2I` or `None`
599  Bounding box of the un-trimmed Detector.
600  nQuarter : `int`
601  number of 90 degree rotations to apply to the bounding boxes (used for rotated chips).
602  isTrimmed : `bool`
603  Is the Detector image over which the boxes are layed trimmed?
604  ccdOrigin : `tuple` of `float`
605  Detector origin relative to the parent origin if in a larger pixel grid.
606  display : `lsst.afw.display.Display`
607  Image display to display on.
608  binSize : `int`
609  Bin the image by this factor in both dimensions.
610 
611  Notes
612  -----
613  The colours are:
614  - Entire detector GREEN
615  - All data for amp GREEN
616  - HorizontalPrescan YELLOW
617  - HorizontalOverscan RED
618  - Data BLUE
619  - VerticalOverscan MAGENTA
620  - VerticalOverscan MAGENTA
621  """
622  if not display: # should be second parameter, and not defaulted!!
623  raise RuntimeError("Please specify a display")
624 
625  if untrimmedCcdBbox is None:
626  if isTrimmed:
627  untrimmedCcdBbox = ccd.getBBox()
628  else:
629  untrimmedCcdBbox = lsst.geom.Box2I()
630  for a in ccd.getAmpInfoCatalog():
631  bbox = a.getRawBBox()
632  untrimmedCcdBbox.include(bbox)
633 
634  with display.Buffering():
635  ccdDim = untrimmedCcdBbox.getDimensions()
636  ccdBbox = rotateBBoxBy90(untrimmedCcdBbox, nQuarter, ccdDim)
637  for amp in ccd:
638  if isTrimmed:
639  ampbbox = amp.getBBox()
640  else:
641  ampbbox = amp.getRawBBox()
642  if nQuarter != 0:
643  ampbbox = rotateBBoxBy90(ampbbox, nQuarter, ccdDim)
644 
645  displayUtils.drawBBox(ampbbox, origin=ccdOrigin, borderWidth=0.49,
646  display=display, bin=binSize)
647 
648  if not isTrimmed and amp.getHasRawInfo():
649  for bbox, ctype in ((amp.getRawHorizontalOverscanBBox(), afwDisplay.RED),
650  (amp.getRawDataBBox(), afwDisplay.BLUE),
651  (amp.getRawVerticalOverscanBBox(),
652  afwDisplay.MAGENTA),
653  (amp.getRawPrescanBBox(), afwDisplay.YELLOW)):
654  if nQuarter != 0:
655  bbox = rotateBBoxBy90(bbox, nQuarter, ccdDim)
656  displayUtils.drawBBox(bbox, origin=ccdOrigin, borderWidth=0.49, ctype=ctype,
657  display=display, bin=binSize)
658  # Label each Amp
659  xc, yc = (ampbbox.getMin()[0] + ampbbox.getMax()[0])//2, (ampbbox.getMin()[1] +
660  ampbbox.getMax()[1])//2
661  #
662  # Rotate the amp labels too
663  #
664  if nQuarter == 0:
665  c, s = 1, 0
666  elif nQuarter == 1:
667  c, s = 0, -1
668  elif nQuarter == 2:
669  c, s = -1, 0
670  elif nQuarter == 3:
671  c, s = 0, 1
672  c, s = 1, 0
673  ccdHeight = ccdBbox.getHeight()
674  ccdWidth = ccdBbox.getWidth()
675  xc -= 0.5*ccdHeight
676  yc -= 0.5*ccdWidth
677 
678  xc, yc = 0.5*ccdHeight + c*xc + s*yc, 0.5*ccdWidth + -s*xc + c*yc
679 
680  if ccdOrigin:
681  xc += ccdOrigin[0]
682  yc += ccdOrigin[1]
683  display.dot(str(amp.getName()), xc/binSize,
684  yc/binSize, textAngle=nQuarter*90)
685 
686  displayUtils.drawBBox(ccdBbox, origin=ccdOrigin,
687  borderWidth=0.49, ctype=afwDisplay.MAGENTA, display=display, bin=binSize)
688 
689 
690 def showAmp(amp, imageSource=FakeImageDataSource(isTrimmed=False), display=None, overlay=True,
691  imageFactory=afwImage.ImageU):
692  """Show an amp in an image display.
693 
694  Parameters
695  ----------
696  amp : `lsst.afw.tables.AmpInfoRecord`
697  Amp record to use in display.
698  imageSource : `FakeImageDataSource` or `None`
699  Source for getting the amp image. Must have a ``getAmpImage()`` method.
700  display : `lsst.afw.display.Display`
701  Image display to use.
702  overlay : `bool`
703  Overlay bounding boxes?
704  imageFactory : callable like `lsst.afw.image.Image`
705  Type of image to display (only used if ampImage is `None`).
706  """
707  if not display:
708  display = _getDisplayFromDisplayOrFrame(display)
709 
710  ampImage = imageSource.getAmpImage(amp, imageFactory=imageFactory)
711  ampImSize = ampImage.getDimensions()
712  title = amp.getName()
713  display.mtv(ampImage, title=title)
714  if overlay:
715  with display.Buffering():
716  if amp.getHasRawInfo() and ampImSize == amp.getRawBBox().getDimensions():
717  bboxes = [(amp.getRawBBox(), 0.49, afwDisplay.GREEN), ]
718  xy0 = bboxes[0][0].getMin()
719  bboxes.append(
720  (amp.getRawHorizontalOverscanBBox(), 0.49, afwDisplay.RED))
721  bboxes.append((amp.getRawDataBBox(), 0.49, afwDisplay.BLUE))
722  bboxes.append((amp.getRawPrescanBBox(),
723  0.49, afwDisplay.YELLOW))
724  bboxes.append((amp.getRawVerticalOverscanBBox(),
725  0.49, afwDisplay.MAGENTA))
726  else:
727  bboxes = [(amp.getBBox(), 0.49, None), ]
728  xy0 = bboxes[0][0].getMin()
729 
730  for bbox, borderWidth, ctype in bboxes:
731  if bbox.isEmpty():
732  continue
733  bbox = lsst.geom.Box2I(bbox)
734  bbox.shift(-lsst.geom.ExtentI(xy0))
735  displayUtils.drawBBox(
736  bbox, borderWidth=borderWidth, ctype=ctype, display=display)
737 
738 
739 def showCcd(ccd, imageSource=FakeImageDataSource(), display=None, frame=None, overlay=True,
740  imageFactory=afwImage.ImageF, binSize=1, inCameraCoords=False):
741  """Show a CCD on display.
742 
743  Parameters
744  ----------
745  ccd : `lsst.afw.cameraGeom.Detector`
746  Detector to use in display.
747  imageSource : `FakeImageDataSource` or `None`
748  Source to get ccd images. Must have a ``getCcdImage()`` method.
749  display : `lsst.afw.display.Display`
750  image display to use.
751  frame : `None`
752  frame ID on which to display. **Deprecated** in v12.
753  overlay : `bool`
754  Show amp bounding boxes on the displayed image?
755  imageFactory : callable like `lsst.afw.image.Image`
756  The image factory to use in generating the images.
757  binSize : `int`
758  Bin the image by this factor in both dimensions.
759  inCameraCoords : `bool`
760  Show the Detector in camera coordinates?
761  """
762  if frame is not None:
763  warnings.warn("The frame kwarg is deprecated; use the `lsst.afw.display` system instead.",
764  DeprecationWarning)
765 
766  display = _getDisplayFromDisplayOrFrame(display, frame)
767 
768  ccdOrigin = lsst.geom.Point2I(0, 0)
769  nQuarter = 0
770  ccdImage, ccd = imageSource.getCcdImage(
771  ccd, imageFactory=imageFactory, binSize=binSize)
772 
773  ccdBbox = ccdImage.getBBox()
774  if ccdBbox.getDimensions() == ccd.getBBox().getDimensions():
775  isTrimmed = True
776  else:
777  isTrimmed = False
778 
779  if inCameraCoords:
780  nQuarter = ccd.getOrientation().getNQuarter()
781  ccdImage = afwMath.rotateImageBy90(ccdImage, nQuarter)
782  title = ccd.getName()
783  if isTrimmed:
784  title += "(trimmed)"
785 
786  if display:
787  display.mtv(ccdImage, title=title)
788 
789  if overlay:
790  overlayCcdBoxes(ccd, ccdBbox, nQuarter, isTrimmed,
791  ccdOrigin, display, binSize)
792 
793  return ccdImage
794 
795 
796 def getCcdInCamBBoxList(ccdList, binSize, pixelSize_o, origin):
797  """Get the bounding boxes of a list of Detectors within a camera sized pixel grid
798 
799  Parameters
800  ----------
801  ccdList : `lsst.afw.cameraGeom.Detector`
802  List of Detector.
803  binSize : `int`
804  Bin the image by this factor in both dimensions.
805  pixelSize_o : `float`
806  Size of the pixel in mm.
807  origin : `int`
808  Origin of the camera pixel grid in pixels.
809 
810  Returns
811  -------
812  boxList : `list` of `lsst.geom.Box2I`
813  A list of bounding boxes in camera pixel coordinates.
814  """
815  boxList = []
816  for ccd in ccdList:
817  if not pixelSize_o == ccd.getPixelSize():
818  raise RuntimeError(
819  "Cameras with detectors with different pixel scales are not currently supported")
820 
821  dbbox = lsst.geom.Box2D()
822  for corner in ccd.getCorners(FOCAL_PLANE):
823  dbbox.include(corner)
824  llc = dbbox.getMin()
825  nQuarter = ccd.getOrientation().getNQuarter()
826  cbbox = ccd.getBBox()
827  ex = cbbox.getDimensions().getX()//binSize
828  ey = cbbox.getDimensions().getY()//binSize
829  bbox = lsst.geom.Box2I(
830  cbbox.getMin(), lsst.geom.Extent2I(int(ex), int(ey)))
831  bbox = rotateBBoxBy90(bbox, nQuarter, bbox.getDimensions())
832  bbox.shift(lsst.geom.Extent2I(int(llc.getX()//pixelSize_o.getX()/binSize),
833  int(llc.getY()//pixelSize_o.getY()/binSize)))
834  bbox.shift(lsst.geom.Extent2I(-int(origin.getX()//binSize),
835  -int(origin.getY())//binSize))
836  boxList.append(bbox)
837  return boxList
838 
839 
840 def getCameraImageBBox(camBbox, pixelSize, bufferSize):
841  """Get the bounding box of a camera sized image in pixels
842 
843  Parameters
844  ----------
845  camBbox : `lsst.geom.Box2D`
846  Camera bounding box in focal plane coordinates (mm).
847  pixelSize : `float`
848  Size of a detector pixel in mm.
849  bufferSize : `int`
850  Buffer around edge of image in pixels.
851 
852  Returns
853  -------
854  box : `lsst.geom.Box2I`
855  The resulting bounding box.
856  """
857  pixMin = lsst.geom.Point2I(int(camBbox.getMinX()//pixelSize.getX()),
858  int(camBbox.getMinY()//pixelSize.getY()))
859  pixMax = lsst.geom.Point2I(int(camBbox.getMaxX()//pixelSize.getX()),
860  int(camBbox.getMaxY()//pixelSize.getY()))
861  retBox = lsst.geom.Box2I(pixMin, pixMax)
862  retBox.grow(bufferSize)
863  return retBox
864 
865 
866 def makeImageFromCamera(camera, detectorNameList=None, background=numpy.nan, bufferSize=10,
867  imageSource=FakeImageDataSource(), imageFactory=afwImage.ImageU, binSize=1):
868  """Make an Image of a Camera.
869 
870  Put each detector's image in the correct location and orientation on the
871  focal plane. The input images can be binned to an integer fraction of their
872  original bboxes.
873 
874  Parameters
875  ----------
876  camera : `lsst.afw.cameraGeom.Camera`
877  Camera object to use to make the image.
878  detectorNameList : `list` of `str`
879  List of detector names from ``camera`` to use in building the image.
880  Use all Detectors if `None`.
881  background : `float`
882  Value to use where there is no Detector.
883  bufferSize : `int`
884  Size of border in binned pixels to make around the camera image.
885  imageSource : `FakeImageDataSource` or `None`
886  Source to get ccd images. Must have a ``getCcdImage()`` method.
887  imageFactory : callable like `lsst.afw.image.Image`
888  Type of image to build.
889  binSize : `int`
890  Bin the image by this factor in both dimensions.
891 
892  Returns
893  -------
894  image : `lsst.afw.image.Image`
895  Image of the entire camera.
896  """
897  log = lsst.log.Log.getLogger("afw.cameraGeom.utils.makeImageFromCamera")
898 
899  if detectorNameList is None:
900  ccdList = camera
901  else:
902  ccdList = [camera[name] for name in detectorNameList]
903 
904  if detectorNameList is None:
905  camBbox = camera.getFpBBox()
906  else:
907  camBbox = lsst.geom.Box2D()
908  for detName in detectorNameList:
909  for corner in camera[detName].getCorners(FOCAL_PLANE):
910  camBbox.include(corner)
911 
912  pixelSize_o = camera[next(camera.getNameIter())].getPixelSize()
913  camBbox = getCameraImageBBox(camBbox, pixelSize_o, bufferSize*binSize)
914  origin = camBbox.getMin()
915 
916  camIm = imageFactory(int(math.ceil(camBbox.getDimensions().getX()/binSize)),
917  int(math.ceil(camBbox.getDimensions().getY()/binSize)))
918  camIm[:] = imageSource.background
919 
920  assert imageSource.isTrimmed, "isTrimmed is False isn't supported by getCcdInCamBBoxList"
921 
922  boxList = getCcdInCamBBoxList(ccdList, binSize, pixelSize_o, origin)
923  for det, bbox in zip(ccdList, boxList):
924  im = imageSource.getCcdImage(det, imageFactory, binSize)[0]
925  if im is None:
926  continue
927 
928  imView = camIm.Factory(camIm, bbox, afwImage.LOCAL)
929  try:
930  imView[:] = im
931  except pexExceptions.LengthError as e:
932  log.error("Unable to fit image for detector \"%s\" into image of camera: %s" % (det.getName(), e))
933 
934  return camIm
935 
936 
937 def showCamera(camera, imageSource=FakeImageDataSource(), imageFactory=afwImage.ImageF,
938  detectorNameList=None, binSize=10, bufferSize=10, frame=None, overlay=True, title="",
939  showWcs=None, ctype=afwDisplay.GREEN, textSize=1.25, originAtCenter=True, display=None,
940  **kwargs):
941  """Show a Camera on display, with the specified display.
942 
943  The rotation of the sensors is snapped to the nearest multiple of 90 deg.
944  Also note that the pixel size is constant over the image array. The lower
945  left corner (LLC) of each sensor amp is snapped to the LLC of the pixel
946  containing the LLC of the image.
947 
948  Parameters
949  ----------
950  camera : `lsst.afw.cameraGeom.Camera`
951  Camera object to use to make the image.
952  imageSource : `FakeImageDataSource` or `None`
953  Source to get ccd images. Must have a ``getCcdImage()`` method.
954  imageFactory : `lsst.afw.image.Image`
955  Type of image to make
956  detectorNameList : `list` of `str` or `None`
957  List of detector names from `camera` to use in building the image.
958  Use all Detectors if `None`.
959  binSize : `int`
960  Bin the image by this factor in both dimensions.
961  bufferSize : `int`
962  Size of border in binned pixels to make around the camera image.
963  frame : `None`
964  specify image display. **Deprecated** in v12.
965  overlay : `bool`
966  Overlay Detector IDs and boundaries?
967  title : `str`
968  Title to use in display.
969  showWcs : `bool`
970  Include a WCS in the display?
971  ctype : `lsst.afw.display.COLOR` or `str`
972  Color to use when drawing Detector boundaries.
973  textSize : `float`
974  Size of detector labels
975  originAtCenter : `bool`
976  Put origin of the camera WCS at the center of the image?
977  If `False`, the origin will be at the lower left.
978  display : `lsst.afw.display`
979  Image display on which to display.
980  **kwargs :
981  All remaining keyword arguments are passed to makeImageFromCamera
982 
983  Returns
984  -------
985  image : `lsst.afw.image.Image`
986  The mosaic image.
987  """
988  if frame is not None:
989  warnings.warn("The frame kwarg is deprecated; use the `lsst.afw.display` system instead.",
990  DeprecationWarning)
991 
992  display = _getDisplayFromDisplayOrFrame(display, frame)
993 
994  if binSize < 1:
995  binSize = 1
996  cameraImage = makeImageFromCamera(camera, detectorNameList=detectorNameList, bufferSize=bufferSize,
997  imageSource=imageSource, imageFactory=imageFactory, binSize=binSize,
998  **kwargs)
999 
1000  if detectorNameList is None:
1001  ccdList = [camera[name] for name in camera.getNameIter()]
1002  else:
1003  ccdList = [camera[name] for name in detectorNameList]
1004 
1005  if detectorNameList is None:
1006  camBbox = camera.getFpBBox()
1007  else:
1008  camBbox = lsst.geom.Box2D()
1009  for detName in detectorNameList:
1010  for corner in camera[detName].getCorners(FOCAL_PLANE):
1011  camBbox.include(corner)
1012  pixelSize = ccdList[0].getPixelSize()
1013 
1014  if showWcs:
1015  if originAtCenter:
1016  wcsReferencePixel = lsst.geom.Box2D(
1017  cameraImage.getBBox()).getCenter()
1018  else:
1019  wcsReferencePixel = lsst.geom.Point2I(0, 0)
1020  wcs = makeFocalPlaneWcs(pixelSize*binSize, wcsReferencePixel)
1021  else:
1022  wcs = None
1023 
1024  if display:
1025  if title == "":
1026  title = camera.getName()
1027  display.mtv(cameraImage, title=title, wcs=wcs)
1028 
1029  if overlay:
1030  with display.Buffering():
1031  camBbox = getCameraImageBBox(
1032  camBbox, pixelSize, bufferSize*binSize)
1033  bboxList = getCcdInCamBBoxList(
1034  ccdList, binSize, pixelSize, camBbox.getMin())
1035  for bbox, ccd in zip(bboxList, ccdList):
1036  nQuarter = ccd.getOrientation().getNQuarter()
1037  # borderWidth to 0.5 to align with the outside edge of the
1038  # pixel
1039  displayUtils.drawBBox(
1040  bbox, borderWidth=0.5, ctype=ctype, display=display)
1041  dims = bbox.getDimensions()
1042  display.dot(ccd.getName(), bbox.getMinX() + dims.getX()/2, bbox.getMinY() + dims.getY()/2,
1043  ctype=ctype, size=textSize, textAngle=nQuarter*90)
1044 
1045  return cameraImage
1046 
1047 
1048 def makeFocalPlaneWcs(pixelSize, referencePixel):
1049  """Make a WCS for the focal plane geometry
1050  (i.e. one that returns positions in "mm")
1051 
1052  Parameters
1053  ----------
1054  pixelSize : `float`
1055  Size of the image pixels in physical units
1056  referencePixel : `lsst.geom.Point2D`
1057  Pixel for origin of WCS
1058 
1059  Returns
1060  -------
1061  `lsst.afw.geom.Wcs`
1062  Wcs object for mapping between pixels and focal plane.
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  for amp in ccd:
1096  if amp.getBBox().contains(pixelPosition):
1097  return amp
1098 
1099  return None
def makeImageFromAmp(amp, imValue=None, imageFactory=afwImage.ImageU, markSize=10, markValue=0, scaleGain=lambda gain:(gain *1000)//10)
Definition: utils.py:184
def makeFocalPlaneWcs(pixelSize, referencePixel)
Definition: utils.py:1048
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:940
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:740
def getCcdInCamBBoxList(ccdList, binSize, pixelSize_o, origin)
Definition: utils.py:796
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:840
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 _prepareImage(self, ccd, im, binSize, allowRotate=True)
Definition: utils.py:446
def makeImageFromCamera(camera, detectorNameList=None, background=numpy.nan, bufferSize=10, imageSource=FakeImageDataSource(), imageFactory=afwImage.ImageU, binSize=1)
Definition: utils.py:867
int max
def __init__(self, butler=None, type="raw", isTrimmed=True, verbose=False, background=numpy.nan, callback=None, args, kwargs)
Definition: utils.py:435
def makeImageFromCcd(ccd, isTrimmed=True, showAmpGain=True, imageFactory=afwImage.ImageU, rcMarkSize=10, binSize=1)
Definition: utils.py:270
def rawCallback(im, ccd=None, imageSource=None, correctGain=False, subtractBias=False, convertToFloat=False, obeyNQuarter=True)
Definition: utils.py:518
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:691
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)
Backwards-compatibility support for depersisting the old Calib (FluxMag0/FluxMag0Err) objects...
def overlayCcdBoxes(ccd, untrimmedCcdBbox=None, nQuarter=0, isTrimmed=False, ccdOrigin=(0, 0), display=None, binSize=1)
Definition: utils.py:591
def rotateBBoxBy90(bbox, n90, dimensions)
def getCcdImage(self, ccd, imageFactory=afwImage.ImageF, binSize=1, asMaskedImage=False)
Definition: utils.py:456