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