lsst.afw  16.0-56-g615901931+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):
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  im = im.getMaskedImage().getImage()
481  else:
482  if self.verbose:
483  print("Reading %s: %s" % (ccd.getId(), err)) # lost by jupyterLab
484 
485  log.warn("Reading %s: %s", ccd.getId(), err)
486 
487  if im is None:
488  return self._prepareImage(ccd, imageFactory(*bbox.getDimensions()), binSize), ccd
489 
490  if self.type == "raw":
491  if hasattr(im, 'convertF'):
492  im = im.convertF()
493  if False and self.callback is None: # we need to trim the raw image
494  self.callback = rawCallback
495 
496  allowRotate = True
497  if self.callback:
498  try:
499  im = self.callback(im, ccd, imageSource=self)
500  except Exception as e:
501  if self.verbose:
502  log.error("callback failed: %s" % e)
503  im = imageFactory(*bbox.getDimensions())
504  else:
505  allowRotate = False # the callback was responsible for any rotations
506 
507  return self._prepareImage(ccd, im, binSize, allowRotate=allowRotate), ccd
508 
509 
510 def rawCallback(im, ccd=None, imageSource=None,
511  correctGain=False, subtractBias=False, convertToFloat=False):
512  """A callback function that may or may not subtract bias/correct gain/trim
513  a raw image.
514 
515  Paramters
516  ---------
517  im : `lsst.afw.image.Image` or `lsst.afw.image.MaskedImage` or `lsst.afw.image.Exposure`
518  An image of a chip, ready to be binned and maybe rotated.
519  ccd : `lsst.afw.cameraGeom.Detector` or None
520  The Detector; if None assume that im is an exposure and extract its Detector.
521  imageSource : `FakeImageDataSource` or None
522  Source to get ccd images. Must have a `getCcdImage()` method.
523  correctGain : `bool`
524  Correct each amplifier for its gain?
525  subtractBias : `bool`
526  Subtract the bias from each amplifier?
527  convertToFloat : `bool`
528  Convert im to floating point if possible.
529 
530  Returns
531  -------
532  image : `lsst.afw.image.Image` like
533  The constructed image (type returned by ``im.Factory``).
534 
535  Notes
536  -----
537  If imageSource is derived from ButlerImage, imageSource.butler is available.
538  """
539  if ccd is None:
540  ccd = im.getDetector()
541  if hasattr(im, "getMaskedImage"):
542  im = im.getMaskedImage()
543  if convertToFloat and hasattr(im, "convertF"):
544  im = im.convertF()
545 
546  isTrimmed = imageSource.isTrimmed
547  if isTrimmed:
548  bbox = ccd.getBBox()
549  else:
550  bbox = calcRawCcdBBox(ccd)
551 
552  ampImages = []
553  for a in ccd:
554  if isTrimmed:
555  data = im[a.getRawDataBBox()]
556  else:
557  data = im
558 
559  if subtractBias:
560  bias = im[a.getRawHorizontalOverscanBBox()]
561  data -= afwMath.makeStatistics(bias, afwMath.MEANCLIP).getValue()
562  if correctGain:
563  data *= a.getGain()
564 
565  ampImages.append(data)
566 
567  ccdImage = im.Factory(bbox)
568  for ampImage, amp in zip(ampImages, ccd):
569  if isTrimmed:
570  assembleAmplifierImage(ccdImage, ampImage, amp)
571  else:
572  assembleAmplifierRawImage(ccdImage, ampImage, amp)
573 
574  return ccdImage
575 
576 
577 def overlayCcdBoxes(ccd, untrimmedCcdBbox=None, nQuarter=0,
578  isTrimmed=False, ccdOrigin=(0, 0), display=None, binSize=1):
579  """Overlay bounding boxes on an image display.
580 
581  Parameters
582  ----------
583  ccd : `lsst.afw.cameraGeom.Detector`
584  Detector to iterate for the amp bounding boxes.
585  untrimmedCcdBbox : `lsst.geom.Box2I` or None
586  Bounding box of the un-trimmed Detector.
587  nQuarter : `int`
588  number of 90 degree rotations to apply to the bounding boxes (used for rotated chips).
589  isTrimmed : `bool`
590  Is the Detector image over which the boxes are layed trimmed?
591  ccdOrigin : `tuple` of `float`
592  Detector origin relative to the parent origin if in a larger pixel grid.
593  display : `lsst.afw.display.Display`
594  Image display to display on.
595  binSize : `int`
596  Bin the image by this factor in both dimensions.
597 
598  Notes
599  -----
600  The colours are:
601  - Entire detector GREEN
602  - All data for amp GREEN
603  - HorizontalPrescan YELLOW
604  - HorizontalOverscan RED
605  - Data BLUE
606  - VerticalOverscan MAGENTA
607  - VerticalOverscan MAGENTA
608  """
609  if not display: # should be second parameter, and not defaulted!!
610  raise RuntimeError("Please specify a display")
611 
612  if untrimmedCcdBbox is None:
613  if isTrimmed:
614  untrimmedCcdBbox = ccd.getBBox()
615  else:
616  untrimmedCcdBbox = lsst.geom.Box2I()
617  for a in ccd.getAmpInfoCatalog():
618  bbox = a.getRawBBox()
619  untrimmedCcdBbox.include(bbox)
620 
621  with display.Buffering():
622  ccdDim = untrimmedCcdBbox.getDimensions()
623  ccdBbox = rotateBBoxBy90(untrimmedCcdBbox, nQuarter, ccdDim)
624  for amp in ccd:
625  if isTrimmed:
626  ampbbox = amp.getBBox()
627  else:
628  ampbbox = amp.getRawBBox()
629  if nQuarter != 0:
630  ampbbox = rotateBBoxBy90(ampbbox, nQuarter, ccdDim)
631 
632  displayUtils.drawBBox(ampbbox, origin=ccdOrigin, borderWidth=0.49,
633  display=display, bin=binSize)
634 
635  if not isTrimmed and amp.getHasRawInfo():
636  for bbox, ctype in ((amp.getRawHorizontalOverscanBBox(), afwDisplay.RED),
637  (amp.getRawDataBBox(), afwDisplay.BLUE),
638  (amp.getRawVerticalOverscanBBox(),
639  afwDisplay.MAGENTA),
640  (amp.getRawPrescanBBox(), afwDisplay.YELLOW)):
641  if nQuarter != 0:
642  bbox = rotateBBoxBy90(bbox, nQuarter, ccdDim)
643  displayUtils.drawBBox(bbox, origin=ccdOrigin, borderWidth=0.49, ctype=ctype,
644  display=display, bin=binSize)
645  # Label each Amp
646  xc, yc = (ampbbox.getMin()[0] + ampbbox.getMax()[0])//2, (ampbbox.getMin()[1] +
647  ampbbox.getMax()[1])//2
648  #
649  # Rotate the amp labels too
650  #
651  if nQuarter == 0:
652  c, s = 1, 0
653  elif nQuarter == 1:
654  c, s = 0, -1
655  elif nQuarter == 2:
656  c, s = -1, 0
657  elif nQuarter == 3:
658  c, s = 0, 1
659  c, s = 1, 0
660  ccdHeight = ccdBbox.getHeight()
661  ccdWidth = ccdBbox.getWidth()
662  xc -= 0.5*ccdHeight
663  yc -= 0.5*ccdWidth
664 
665  xc, yc = 0.5*ccdHeight + c*xc + s*yc, 0.5*ccdWidth + -s*xc + c*yc
666 
667  if ccdOrigin:
668  xc += ccdOrigin[0]
669  yc += ccdOrigin[1]
670  display.dot(str(amp.getName()), xc/binSize,
671  yc/binSize, textAngle=nQuarter*90)
672 
673  displayUtils.drawBBox(ccdBbox, origin=ccdOrigin,
674  borderWidth=0.49, ctype=afwDisplay.MAGENTA, display=display, bin=binSize)
675 
676 
677 def showAmp(amp, imageSource=FakeImageDataSource(isTrimmed=False), display=None, overlay=True,
678  imageFactory=afwImage.ImageU):
679  """Show an amp in an image display.
680 
681  Parameters
682  ----------
683  amp : `lsst.afw.tables.AmpInfoRecord`
684  Amp record to use in display.
685  imageSource : `FakeImageDataSource` or None
686  Source for getting the amp image. Must have a ``getAmpImage()`` method.
687  display : `lsst.afw.display.Display`
688  Image display to use.
689  overlay : `bool`
690  Overlay bounding boxes?
691  imageFactory : callable like `lsst.afw.image.Image`
692  Type of image to display (only used if ampImage is None).
693  """
694 
695  if not display:
696  display = _getDisplayFromDisplayOrFrame()
697 
698  ampImage = imageSource.getAmpImage(amp, imageFactory=imageFactory)
699  ampImSize = ampImage.getDimensions()
700  title = amp.getName()
701  display.mtv(ampImage, title=title)
702  if overlay:
703  with display.Buffering():
704  if amp.getHasRawInfo() and ampImSize == amp.getRawBBox().getDimensions():
705  bboxes = [(amp.getRawBBox(), 0.49, afwDisplay.GREEN), ]
706  xy0 = bboxes[0][0].getMin()
707  bboxes.append(
708  (amp.getRawHorizontalOverscanBBox(), 0.49, afwDisplay.RED))
709  bboxes.append((amp.getRawDataBBox(), 0.49, afwDisplay.BLUE))
710  bboxes.append((amp.getRawPrescanBBox(),
711  0.49, afwDisplay.YELLOW))
712  bboxes.append((amp.getRawVerticalOverscanBBox(),
713  0.49, afwDisplay.MAGENTA))
714  else:
715  bboxes = [(amp.getBBox(), 0.49, None), ]
716  xy0 = bboxes[0][0].getMin()
717 
718  for bbox, borderWidth, ctype in bboxes:
719  if bbox.isEmpty():
720  continue
721  bbox = lsst.geom.Box2I(bbox)
722  bbox.shift(-lsst.geom.ExtentI(xy0))
723  displayUtils.drawBBox(
724  bbox, borderWidth=borderWidth, ctype=ctype, display=display)
725 
726 
727 def showCcd(ccd, imageSource=FakeImageDataSource(), display=None, frame=None, overlay=True,
728  imageFactory=afwImage.ImageF, binSize=1, inCameraCoords=False):
729  """Show a CCD on display.
730 
731  Parameters
732  ----------
733  ccd : `lsst.afw.cameraGeom.Detector`
734  Detector to use in display.
735  imageSource : `FakeImageDataSource` or None
736  Source to get ccd images. Must have a ``getCcdImage()`` method.
737  display : `lsst.afw.display.Display`
738  image display to use.
739  frame : None
740  frame ID on which to display. **Deprecated** in v12.
741  overlay : `bool`
742  Show amp bounding boxes on the displayed image?
743  imageFactory : callable like `lsst.afw.image.Image`
744  The image factory to use in generating the images.
745  binSize : `int`
746  Bin the image by this factor in both dimensions.
747  inCameraCoords : `bool`
748  Show the Detector in camera coordinates?
749  """
750  if frame is not None:
751  warnings.warn("The frame kwarg is deprecated; use the `lsst.afw.display` system instead.",
752  DeprecationWarning)
753 
754  display = _getDisplayFromDisplayOrFrame(display, frame)
755 
756  ccdOrigin = lsst.geom.Point2I(0, 0)
757  nQuarter = 0
758  ccdImage, ccd = imageSource.getCcdImage(
759  ccd, imageFactory=imageFactory, binSize=binSize)
760 
761  ccdBbox = ccdImage.getBBox()
762  if ccdBbox.getDimensions() == ccd.getBBox().getDimensions():
763  isTrimmed = True
764  else:
765  isTrimmed = False
766 
767  if inCameraCoords:
768  nQuarter = ccd.getOrientation().getNQuarter()
769  ccdImage = afwMath.rotateImageBy90(ccdImage, nQuarter)
770  title = ccd.getName()
771  if isTrimmed:
772  title += "(trimmed)"
773 
774  if display:
775  display.mtv(ccdImage, title=title)
776 
777  if overlay:
778  overlayCcdBoxes(ccd, ccdBbox, nQuarter, isTrimmed,
779  ccdOrigin, display, binSize)
780 
781  return ccdImage
782 
783 
784 def getCcdInCamBBoxList(ccdList, binSize, pixelSize_o, origin):
785  """Get the bounding boxes of a list of Detectors within a camera sized pixel grid
786 
787  Parameters
788  ----------
789  ccdList : `lsst.afw.cameraGeom.Detector`
790  List of Detector.
791  binSize : `int`
792  Bin the image by this factor in both dimensions.
793  pixelSize_o : `float`
794  Size of the pixel in mm.
795  origin : `int`
796  Origin of the camera pixel grid in pixels.
797 
798  Returns
799  -------
800  boxList : `list` of `lsst.geom.Box2I`
801  A list of bounding boxes in camera pixel coordinates.
802  """
803  boxList = []
804  for ccd in ccdList:
805  if not pixelSize_o == ccd.getPixelSize():
806  raise RuntimeError(
807  "Cameras with detectors with different pixel scales are not currently supported")
808 
809  dbbox = lsst.geom.Box2D()
810  for corner in ccd.getCorners(FOCAL_PLANE):
811  dbbox.include(corner)
812  llc = dbbox.getMin()
813  nQuarter = ccd.getOrientation().getNQuarter()
814  cbbox = ccd.getBBox()
815  ex = cbbox.getDimensions().getX()//binSize
816  ey = cbbox.getDimensions().getY()//binSize
817  bbox = lsst.geom.Box2I(
818  cbbox.getMin(), lsst.geom.Extent2I(int(ex), int(ey)))
819  bbox = rotateBBoxBy90(bbox, nQuarter, bbox.getDimensions())
820  bbox.shift(lsst.geom.Extent2I(int(llc.getX()//pixelSize_o.getX()/binSize),
821  int(llc.getY()//pixelSize_o.getY()/binSize)))
822  bbox.shift(lsst.geom.Extent2I(-int(origin.getX()//binSize),
823  -int(origin.getY())//binSize))
824  boxList.append(bbox)
825  return boxList
826 
827 
828 def getCameraImageBBox(camBbox, pixelSize, bufferSize):
829  """Get the bounding box of a camera sized image in pixels
830 
831  Parameters
832  ----------
833  camBbox : `lsst.geom.Box2D`
834  Camera bounding box in focal plane coordinates (mm).
835  pixelSize : `float`
836  Size of a detector pixel in mm.
837  bufferSize : `int`
838  Buffer around edge of image in pixels.
839 
840  Returns
841  -------
842  box : `lsst.geom.Box2I`
843  The resulting bounding box.
844  """
845  pixMin = lsst.geom.Point2I(int(camBbox.getMinX()//pixelSize.getX()),
846  int(camBbox.getMinY()//pixelSize.getY()))
847  pixMax = lsst.geom.Point2I(int(camBbox.getMaxX()//pixelSize.getX()),
848  int(camBbox.getMaxY()//pixelSize.getY()))
849  retBox = lsst.geom.Box2I(pixMin, pixMax)
850  retBox.grow(bufferSize)
851  return retBox
852 
853 
854 def makeImageFromCamera(camera, detectorNameList=None, background=numpy.nan, bufferSize=10,
855  imageSource=FakeImageDataSource(), imageFactory=afwImage.ImageU, binSize=1):
856  """Make an Image of a Camera.
857 
858  Put each detector's image in the correct location and orientation on the
859  focal plane. The input images can be binned to an integer fraction of their
860  original bboxes.
861 
862  Parameters
863  ----------
864  camera : `lsst.afw.cameraGeom.Camera`
865  Camera object to use to make the image.
866  detectorNameList : `list` of `str`
867  List of detector names from `camera` to use in building the image.
868  Use all Detectors if None.
869  background : `float`
870  Value to use where there is no Detector.
871  bufferSize : `int`
872  Size of border in binned pixels to make around the camera image.
873  imageSource : `FakeImageDataSource` or None
874  Source to get ccd images. Must have a ``getCcdImage()`` method.
875  imageFactory : callable like `lsst.afw.image.Image`
876  Type of image to build.
877  binSize : `int`
878  Bin the image by this factor in both dimensions.
879 
880  Returns
881  -------
882  image : `lsst.afw.image.Image`
883  Image of the entire camera.
884  """
885  log = lsst.log.Log.getLogger("afw.cameraGeom.utils.makeImageFromCamera")
886 
887  if detectorNameList is None:
888  ccdList = camera
889  else:
890  ccdList = [camera[name] for name in detectorNameList]
891 
892  if detectorNameList is None:
893  camBbox = camera.getFpBBox()
894  else:
895  camBbox = lsst.geom.Box2D()
896  for detName in detectorNameList:
897  for corner in camera[detName].getCorners(FOCAL_PLANE):
898  camBbox.include(corner)
899 
900  pixelSize_o = camera[next(camera.getNameIter())].getPixelSize()
901  camBbox = getCameraImageBBox(camBbox, pixelSize_o, bufferSize*binSize)
902  origin = camBbox.getMin()
903 
904  camIm = imageFactory(int(math.ceil(camBbox.getDimensions().getX()/binSize)),
905  int(math.ceil(camBbox.getDimensions().getY()/binSize)))
906  camIm[:] = imageSource.background
907 
908  assert imageSource.isTrimmed, "isTrimmed is False isn't supported by getCcdInCamBBoxList"
909 
910  boxList = getCcdInCamBBoxList(ccdList, binSize, pixelSize_o, origin)
911  for det, bbox in zip(ccdList, boxList):
912  im = imageSource.getCcdImage(det, imageFactory, binSize)[0]
913  if im is None:
914  continue
915 
916  nQuarter = det.getOrientation().getNQuarter()
917  im = afwMath.rotateImageBy90(im, nQuarter)
918 
919  imView = camIm.Factory(camIm, bbox, afwImage.LOCAL)
920  try:
921  imView[:] = im
922  except pexExceptions.LengthError as e:
923  log.error("Unable to fit image for detector \"%s\" into image of camera: %s" % (det.getName(), e))
924 
925  return camIm
926 
927 
928 def showCamera(camera, imageSource=FakeImageDataSource(), imageFactory=afwImage.ImageF,
929  detectorNameList=None, binSize=10, bufferSize=10, frame=None, overlay=True, title="",
930  showWcs=None, ctype=afwDisplay.GREEN, textSize=1.25, originAtCenter=True, display=None,
931  **kwargs):
932  """Show a Camera on display, with the specified display.
933 
934  The rotation of the sensors is snapped to the nearest multiple of 90 deg.
935  Also note that the pixel size is constant over the image array. The lower
936  left corner (LLC) of each sensor amp is snapped to the LLC of the pixel
937  containing the LLC of the image.
938 
939  Parameters
940  ----------
941  camera : `lsst.afw.cameraGeom.Camera`
942  Camera object to use to make the image.
943  imageSource : `FakeImageDataSource` or None
944  Source to get ccd images. Must have a ``getCcdImage()`` method.
945  imageFactory : `lsst.afw.image.Image`
946  Type of image to make
947  detectorNameList : `list` of `str`
948  List of detector names from `camera` to use in building the image.
949  Use all Detectors if None.
950  binSize : `int`
951  Bin the image by this factor in both dimensions.
952  bufferSize : `int`
953  Size of border in binned pixels to make around the camera image.
954  frame : None
955  specify image display. **Deprecated** in v12.
956  overlay : `bool`
957  Overlay Detector IDs and boundaries?
958  title : `str`
959  Title to use in display.
960  showWcs : `bool`
961  Include a WCS in the display?
962  ctype : `lsst.afw.display.COLOR` or `str`
963  Color to use when drawing Detector boundaries.
964  textSize : `float`
965  Size of detector labels
966  originAtCenter : `bool`
967  Put origin of the camera WCS at the center of the image?
968  If False, the origin will be at the lower left.
969  display : `lsst.afw.display`
970  Image display on which to display.
971  **kwargs :
972  All remaining keyword arguments are passed to makeImageFromCamera
973 
974  Returns
975  -------
976  image : `lsst.afw.image.Image`
977  The mosaic image.
978  """
979  if frame is not None:
980  warnings.warn("The frame kwarg is deprecated; use the `lsst.afw.display` system instead.",
981  DeprecationWarning)
982 
983  display = _getDisplayFromDisplayOrFrame(display, frame)
984 
985  if binSize < 1:
986  binSize = 1
987  cameraImage = makeImageFromCamera(camera, detectorNameList=detectorNameList, bufferSize=bufferSize,
988  imageSource=imageSource, imageFactory=imageFactory, binSize=binSize,
989  **kwargs)
990 
991  if detectorNameList is None:
992  ccdList = [camera[name] for name in camera.getNameIter()]
993  else:
994  ccdList = [camera[name] for name in detectorNameList]
995 
996  if detectorNameList is None:
997  camBbox = camera.getFpBBox()
998  else:
999  camBbox = lsst.geom.Box2D()
1000  for detName in detectorNameList:
1001  for corner in camera[detName].getCorners(FOCAL_PLANE):
1002  camBbox.include(corner)
1003  pixelSize = ccdList[0].getPixelSize()
1004 
1005  if showWcs:
1006  if originAtCenter:
1007  wcsReferencePixel = lsst.geom.Box2D(
1008  cameraImage.getBBox()).getCenter()
1009  else:
1010  wcsReferencePixel = lsst.geom.Point2I(0, 0)
1011  wcs = makeFocalPlaneWcs(pixelSize*binSize, wcsReferencePixel)
1012  else:
1013  wcs = None
1014 
1015  if display:
1016  if title == "":
1017  title = camera.getName()
1018  display.mtv(cameraImage, title=title, wcs=wcs)
1019 
1020  if overlay:
1021  with display.Buffering():
1022  camBbox = getCameraImageBBox(
1023  camBbox, pixelSize, bufferSize*binSize)
1024  bboxList = getCcdInCamBBoxList(
1025  ccdList, binSize, pixelSize, camBbox.getMin())
1026  for bbox, ccd in zip(bboxList, ccdList):
1027  nQuarter = ccd.getOrientation().getNQuarter()
1028  # borderWidth to 0.5 to align with the outside edge of the
1029  # pixel
1030  displayUtils.drawBBox(
1031  bbox, borderWidth=0.5, ctype=ctype, display=display)
1032  dims = bbox.getDimensions()
1033  display.dot(ccd.getName(), bbox.getMinX()+dims.getX()/2, bbox.getMinY()+dims.getY()/2,
1034  ctype=ctype, size=textSize, textAngle=nQuarter*90)
1035 
1036  return cameraImage
1037 
1038 
1039 def makeFocalPlaneWcs(pixelSize, referencePixel):
1040  """Make a WCS for the focal plane geometry
1041  (i.e. one that returns positions in "mm")
1042 
1043  Parameters
1044  ----------
1045  pixelSize : `float`
1046  Size of the image pixels in physical units
1047  referencePixel : `lsst.geom.Point2D`
1048  Pixel for origin of WCS
1049 
1050  Returns
1051  -------
1052  `lsst.afw.geom.Wcs`
1053  Wcs object for mapping between pixels and focal plane.
1054  """
1055 
1056  md = dafBase.PropertySet()
1057  if referencePixel is None:
1058  referencePixel = lsst.geom.PointD(0, 0)
1059  for i in range(2):
1060  md.set("CRPIX%d"%(i+1), referencePixel[i])
1061  md.set("CRVAL%d"%(i+1), 0.)
1062  md.set("CDELT1", pixelSize[0])
1063  md.set("CDELT2", pixelSize[1])
1064  md.set("CTYPE1", "CAMERA_X")
1065  md.set("CTYPE2", "CAMERA_Y")
1066  md.set("CUNIT1", "mm")
1067  md.set("CUNIT2", "mm")
1068 
1069  return afwGeom.makeSkyWcs(md)
1070 
1071 
1072 def findAmp(ccd, pixelPosition):
1073  """Find the Amp with the specified pixel position within the composite
1074 
1075  Parameters
1076  ----------
1077  ccd : `lsst.afw.cameraGeom.Detector`
1078  Detector to look in.
1079  pixelPosition : `lsst.geom.Point2I`
1080  The pixel position to find the amp for.
1081 
1082  Returns
1083  -------
1084  `lsst.afw.table.AmpInfoCatalog`
1085  Amp record in which pixelPosition falls or None if no Amp found.
1086  """
1087 
1088  for amp in ccd:
1089  if amp.getBBox().contains(pixelPosition):
1090  return amp
1091 
1092  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:1039
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:931
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:728
def getCcdInCamBBoxList(ccdList, binSize, pixelSize_o, origin)
Definition: utils.py:784
def getCcdImage(self, det, imageFactory, binSize)
Definition: utils.py:354
def findAmp(ccd, pixelPosition)
Definition: utils.py:1072
def getCameraImageBBox(camBbox, pixelSize, bufferSize)
Definition: utils.py:828
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:511
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:855
int max
def getCcdImage(self, ccd, imageFactory=afwImage.ImageF, binSize=1)
Definition: utils.py:452
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:678
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:578
def rotateBBoxBy90(bbox, n90, dimensions)
Rotate a bounding box by an integer multiple of 90 degrees.