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