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