lsst.afw  15.0-29-ga12a2b06e
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.afw.geom as afwGeom
31 import lsst.afw.image as afwImage
32 import lsst.afw.math as afwMath
33 import lsst.daf.base as dafBase
34 import lsst.log
35 
36 from .rotateBBoxBy90 import rotateBBoxBy90
37 from .assembleImage import assembleAmplifierImage, assembleAmplifierRawImage
38 from .cameraGeomLib import FIELD_ANGLE, FOCAL_PLANE
39 from lsst.afw.display.utils import _getDisplayFromDisplayOrFrame
40 
41 import lsst.afw.display as afwDisplay
42 import lsst.afw.display.utils as displayUtils
43 
44 
45 def prepareWcsData(wcs, amp, isTrimmed=True):
46  """Put Wcs from an Amp image into CCD coordinates
47 
48  Parameters
49  ----------
50  wcs : `lsst.afw.geom.SkyWcs`
51  The WCS object to start from.
52  amp : `lsst.afw.table.AmpInfoRecord`
53  Amp object to use
54  isTrimmed : `bool`
55  Is the image to which the WCS refers trimmed of non-imaging pixels?
56 
57  Returns
58  -------
59  ampWcs : `lsst.afw.geom.SkyWcs`
60  The modified WCS.
61  """
62  if not amp.getHasRawInfo():
63  raise RuntimeError("Cannot modify wcs without raw amp information")
64  if isTrimmed:
65  ampBox = amp.getRawDataBBox()
66  else:
67  ampBox = amp.getRawBBox()
68  ampCenter = afwGeom.Point2D(ampBox.getDimensions() / 2.0)
69  wcs = afwGeom.makeFlippedWcs(wcs, amp.getRawFlipX(), amp.getRawFlipY(), ampCenter)
70  # Shift WCS for trimming
71  if isTrimmed:
72  trim_shift = ampBox.getMin() - amp.getBBox().getMin()
73  wcs = wcs.copyAtShiftedPixelOrigin(afwGeom.Extent2D(-trim_shift.getX(), -trim_shift.getY()))
74  # Account for shift of amp data in larger ccd matrix
75  offset = amp.getRawXYOffset()
76  return wcs.copyAtShiftedPixelOrigin(afwGeom.Extent2D(offset))
77 
78 
79 def plotFocalPlane(camera, fieldSizeDeg_x=0, fieldSizeDeg_y=None, dx=0.1, dy=0.1, figsize=(10., 10.),
80  useIds=False, showFig=True, savePath=None):
81  """Make a plot of the focal plane along with a set points that sample
82  the field of view.
83 
84  Parameters
85  ----------
86  camera : `lsst.afw.cameraGeom.Camera`
87  A camera object
88  fieldSizeDeg_x : `float`
89  Amount of the field to sample in x in degrees
90  fieldSizeDeg_y : `float` or None
91  Amount of the field to sample in y in degrees
92  dx : `float`
93  Spacing of sample points in x in degrees
94  dy : `float`
95  Spacing of sample points in y in degrees
96  figsize : `tuple` containing two `float`s
97  Matplotlib style tuple indicating the size of the figure in inches
98  useIds : `bool`
99  Label detectors by name, not id?
100  showFig : `bool`
101  Display the figure on the screen?
102  savePath : `str` or None
103  If not None, save a copy of the figure to this name.
104  """
105  try:
106  from matplotlib.patches import Polygon
107  from matplotlib.collections import PatchCollection
108  import matplotlib.pyplot as plt
109  except ImportError:
110  raise ImportError(
111  "Can't run plotFocalPlane: matplotlib has not been set up")
112 
113  if fieldSizeDeg_x:
114  if fieldSizeDeg_y is None:
115  fieldSizeDeg_y = fieldSizeDeg_x
116 
117  field_gridx, field_gridy = numpy.meshgrid(numpy.arange(0., fieldSizeDeg_x+dx, dx) - fieldSizeDeg_x/2.,
118  numpy.arange(0., fieldSizeDeg_y+dy, dy) - fieldSizeDeg_y/2.)
119  field_gridx, field_gridy = field_gridx.flatten(), field_gridy.flatten()
120  else:
121  field_gridx, field_gridy = [], []
122 
123  xs = []
124  ys = []
125  pcolors = []
126 
127  # compute focal plane positions corresponding to field angles field_gridx, field_gridy
128  posFieldAngleList = [afwGeom.Point2D(x.asRadians(), y.asRadians())
129  for x, y in zip(field_gridx, field_gridy)]
130  posFocalPlaneList = camera.transform(posFieldAngleList, FIELD_ANGLE, FOCAL_PLANE)
131  for posFocalPlane in posFocalPlaneList:
132  xs.append(posFocalPlane.getX())
133  ys.append(posFocalPlane.getY())
134  dets = camera.findDetectors(posFocalPlane, FOCAL_PLANE)
135  if len(dets) > 0:
136  pcolors.append('w')
137  else:
138  pcolors.append('k')
139 
140  colorMap = {0: 'b', 1: 'y', 2: 'g', 3: 'r'}
141 
142  patches = []
143  colors = []
144  plt.figure(figsize=figsize)
145  ax = plt.gca()
146  xvals = []
147  yvals = []
148  for det in camera:
149  corners = [(c.getX(), c.getY()) for c in det.getCorners(FOCAL_PLANE)]
150  for corner in corners:
151  xvals.append(corner[0])
152  yvals.append(corner[1])
153  colors.append(colorMap[det.getType()])
154  patches.append(Polygon(corners, True))
155  center = det.getOrientation().getFpPosition()
156  ax.text(center.getX(), center.getY(), det.getId() if useIds else det.getName(),
157  horizontalalignment='center', size=6)
158 
159  patchCollection = PatchCollection(patches, alpha=0.6, facecolor=colors)
160  ax.add_collection(patchCollection)
161  ax.scatter(xs, ys, s=10, alpha=.7, linewidths=0., c=pcolors)
162  ax.set_xlim(min(xvals) - abs(0.1*min(xvals)),
163  max(xvals) + abs(0.1*max(xvals)))
164  ax.set_ylim(min(yvals) - abs(0.1*min(yvals)),
165  max(yvals) + abs(0.1*max(yvals)))
166  ax.set_xlabel('Focal Plane X (mm)')
167  ax.set_ylabel('Focal Plane Y (mm)')
168  if savePath is not None:
169  plt.savefig(savePath)
170  if showFig:
171  plt.show()
172 
173 
174 def makeImageFromAmp(amp, imValue=None, imageFactory=afwImage.ImageU, markSize=10, markValue=0,
175  scaleGain=lambda gain: (gain*1000)//10):
176  """Make an image from an amp object.
177 
178  Since images are integer images by default, the gain needs to be scaled to
179  give enough dynamic range to see variation from amp to amp.
180  The scaling algorithm is assignable.
181 
182  Parameters
183  ----------
184  amp : `lsst.afw.table.AmpInfoRecord`
185  Amp record to use for constructing the raw amp image.
186  imValue : `float` or None
187  Value to assign to the constructed image, or scaleGain(gain) if None.
188  imageFactory : callable like `lsst.afw.image.Image`
189  Type of image to construct.
190  markSize : `float`
191  Size of mark at read corner in pixels.
192  markValue : `float`
193  Value of pixels in the read corner mark.
194  scaleGain : callable
195  The function by which to scale the gain (must take a single argument).
196 
197  Returns
198  -------
199  ampImage : `lsst.afw.image`
200  An untrimmed amp image, of the type produced by ``imageFactory``.
201  """
202  if not amp.getHasRawInfo():
203  raise RuntimeError(
204  "Can't create a raw amp image without raw amp information")
205  bbox = amp.getRawBBox()
206  dbbox = amp.getRawDataBBox()
207  img = imageFactory(bbox)
208  if imValue is None:
209  img.set(scaleGain(amp.getGain()))
210  else:
211  img.set(imValue)
212  # Set the first pixel read to a different value
213  markbbox = afwGeom.Box2I()
214  if amp.getReadoutCorner() == 0:
215  markbbox.include(dbbox.getMin())
216  markbbox.include(dbbox.getMin()+afwGeom.Extent2I(markSize, markSize))
217  elif amp.getReadoutCorner() == 1:
218  cornerPoint = afwGeom.Point2I(dbbox.getMaxX(), dbbox.getMinY())
219  markbbox.include(cornerPoint)
220  markbbox.include(cornerPoint + afwGeom.Extent2I(-markSize, markSize))
221  elif amp.getReadoutCorner() == 2:
222  cornerPoint = afwGeom.Point2I(dbbox.getMax())
223  markbbox.include(cornerPoint)
224  markbbox.include(cornerPoint + afwGeom.Extent2I(-markSize, -markSize))
225  elif amp.getReadoutCorner() == 3:
226  cornerPoint = afwGeom.Point2I(dbbox.getMinX(), dbbox.getMaxY())
227  markbbox.include(cornerPoint)
228  markbbox.include(cornerPoint + afwGeom.Extent2I(markSize, -markSize))
229  else:
230  raise RuntimeError("Could not set readout corner")
231  mimg = imageFactory(img, markbbox)
232  mimg.set(markValue)
233  return img
234 
235 
236 def calcRawCcdBBox(ccd):
237  """Calculate the raw ccd bounding box.
238 
239  Parameters
240  ----------
241  ccd : `lsst.afw.cameraGeom.Detector`
242  Detector for which to calculate the un-trimmed bounding box.
243 
244  Returns
245  -------
246  box : `Box2I` or None
247  Bounding box of the un-trimmed Detector, or None if there is not enough
248  information to calculate raw BBox.
249  """
250  bbox = afwGeom.Box2I()
251  for amp in ccd:
252  if not amp.getHasRawInfo():
253  return None
254  tbbox = amp.getRawBBox()
255  tbbox.shift(amp.getRawXYOffset())
256  bbox.include(tbbox)
257  return bbox
258 
259 
260 def makeImageFromCcd(ccd, isTrimmed=True, showAmpGain=True, imageFactory=afwImage.ImageU, rcMarkSize=10,
261  binSize=1):
262  """Make an Image of a CCD.
263 
264  Parameters
265  ----------
266  ccd : `lsst.afw.cameraGeom.Detector`
267  Detector to use in making the image.
268  isTrimmed : `bool`
269  Assemble a trimmed Detector image.
270  showAmpGain : `bool`
271  Use the per-amp gain to color the pixels in the image?
272  imageFactory : callable like `lsst.afw.image.Image`
273  Image type to generate.
274  rcMarkSize : `float`
275  Size of the mark to make in the amp images at the read corner.
276  binSize : `int`
277  Bin the image by this factor in both dimensions.
278 
279  Returns
280  -------
281  image : `lsst.afw.image.Image`
282  Image of the Detector (type returned by ``imageFactory``).
283  """
284  ampImages = []
285  index = 0
286  if isTrimmed:
287  bbox = ccd.getBBox()
288  else:
289  bbox = calcRawCcdBBox(ccd)
290  for amp in ccd:
291  if amp.getHasRawInfo():
292  if showAmpGain:
293  ampImages.append(makeImageFromAmp(
294  amp, imageFactory=imageFactory, markSize=rcMarkSize))
295  else:
296  ampImages.append(makeImageFromAmp(amp, imValue=(index+1)*1000,
297  imageFactory=imageFactory, markSize=rcMarkSize))
298  index += 1
299 
300  if len(ampImages) > 0:
301  ccdImage = imageFactory(bbox)
302  for ampImage, amp in zip(ampImages, ccd):
303  if isTrimmed:
304  assembleAmplifierImage(ccdImage, ampImage, amp)
305  else:
306  assembleAmplifierRawImage(ccdImage, ampImage, amp)
307  else:
308  if not isTrimmed:
309  raise RuntimeError(
310  "Cannot create untrimmed CCD without amps with raw information")
311  ccdImage = imageFactory(ccd.getBBox())
312  ccdImage = afwMath.binImage(ccdImage, binSize)
313  return ccdImage
314 
315 
317  """A class to retrieve synthetic images for display by the show* methods
318 
319  Parameters
320  ----------
321  isTrimmed : `bool`
322  Should amps be trimmed?
323  verbose : `bool`
324  Be chatty?
325  background : `float`
326  The value of any pixels that lie outside the CCDs.
327  showAmpGain : `bool`
328  Color the amp segments with the gain of the amp?
329  markSize : `float`
330  Size of the side of the box used to mark the read corner.
331  markValue : `float`
332  Value to assign the read corner mark.
333  ampImValue : `float` or None
334  Value to assign to amps; scaleGain(gain) is used if None.
335  scaleGain : callable
336  Function to scale the gain by.
337  """
338 
339  def __init__(self, isTrimmed=True, verbose=False, background=numpy.nan,
340  showAmpGain=True, markSize=10, markValue=0,
341  ampImValue=None, scaleGain=lambda gain: (gain*1000)//10):
342  self.isTrimmed = isTrimmed
343  self.verbose = verbose
344  self.background = background
345  self.showAmpGain = showAmpGain
346  self.markSize = markSize
347  self.markValue = markValue
348  self.ampImValue = ampImValue
349  self.scaleGain = scaleGain
350 
351  def getCcdImage(self, det, imageFactory, binSize):
352  """Return a CCD image for the detector and the (possibly updated) Detector.
353 
354  Parameters
355  ----------
356  det : `lsst.afw.cameraGeom.Detector`
357  Detector to use for making the image.
358  imageFactory : callable like `lsst.afw.image.Image`
359  Image constructor for making the image.
360  binSize : `int`
361  Bin the image by this factor in both dimensions.
362 
363  Returns
364  -------
365  ccdImage : `lsst.afw.image.Image`
366  The constructed image.
367  """
368  return makeImageFromCcd(det, isTrimmed=self.isTrimmed, showAmpGain=self.showAmpGain,
369  imageFactory=imageFactory, binSize=binSize), det
370 
371  def getAmpImage(self, amp, imageFactory):
372  """Return an amp segment image.
373 
374  Parameters
375  ----------
376  amp : `lsst.afw.table.AmpInfoTable`
377  AmpInfoTable for this amp.
378  imageFactory : callable like `lsst.afw.image.Image`
379  Image constructor for making the image.
380 
381  Returns
382  -------
383  ampImage : `lsst.afw.image.Image`
384  The constructed image.
385  """
386  ampImage = makeImageFromAmp(amp, imValue=self.ampImValue, imageFactory=imageFactory,
387  markSize=self.markSize, markValue=self.markValue,
388  scaleGain=self.scaleGain)
389  if self.isTrimmed:
390  ampImage = ampImage.Factory(ampImage, amp.getRawDataBBox())
391  return ampImage
392 
393 
395  """A class to return an Image of a given Ccd using the butler.
396 
397  Parameters
398  ----------
399  butler : `lsst.daf.persistence.Butler` or None
400  The butler to use. If None, an empty image is returned.
401  type : `str`
402  The type of image to read (e.g. raw, bias, flat, calexp).
403  isTrimmed : `bool`
404  If true, the showCamera command expects to be given trimmed images.
405  verbose : `bool`
406  Be chatty (in particular, log any error messages from the butler)?
407  background : `float`
408  The value of any pixels that lie outside the CCDs.
409  callback : callable
410  A function called with (image, ccd, butler) for every image, which
411  returns the image to be displayed (e.g. rawCallback). The image must
412  be of the correct size, allowing for the value of isTrimmed.
413  *args : `list`
414  Passed to the butler.
415  **kwargs : `dict`
416  Passed to the butler.
417 
418  Notes
419  -----
420  You can define a short named function as a callback::
421 
422  def callback(im, ccd, imageSource):
423  return cameraGeom.utils.rawCallback(im, ccd, imageSource, correctGain=True)
424  """
425 
426  def __init__(self, butler=None, type="raw",
427  isTrimmed=True, verbose=False, background=numpy.nan,
428  callback=None, *args, **kwargs):
429  super(ButlerImage, self).__init__(*args)
430  self.isTrimmed = isTrimmed
431  self.type = type
432  self.butler = butler
433  self.kwargs = kwargs
434  self.isRaw = False
435  self.background = background
436  self.verbose = verbose
437  self.callback = callback
438 
439  def _prepareImage(self, ccd, im, binSize, allowRotate=True):
440  if binSize > 1:
441  im = afwMath.binImage(im, binSize)
442 
443  if allowRotate:
445  im, ccd.getOrientation().getNQuarter())
446 
447  return im
448 
449  def getCcdImage(self, ccd, imageFactory=afwImage.ImageF, binSize=1):
450  """Return an image of the specified ccd, and also the (possibly updated) ccd"""
451 
452  log = lsst.log.Log.getLogger("afw.cameraGeom.utils.ButlerImage")
453 
454  if self.isTrimmed:
455  bbox = ccd.getBBox()
456  else:
457  bbox = calcRawCcdBBox(ccd)
458 
459  im = None
460  if self.butler is not None:
461  e = None
462  if self.type == "calexp": # reading the exposure can die if the PSF's unknown
463  try: # need to switch to cid as below. RHL has no calexp to test with
464  fileName = self.butler.get(self.type + "_filename", ccd=ccd.getId(),
465  **self.kwargs)[0]
466  im = imageFactory(fileName)
467  except Exception as e:
468  pass
469  else:
470  im = None
471  for cid in [ccd.getId(), ccd.getName()]:
472  try:
473  im = self.butler.get(self.type, ccd=cid, **self.kwargs)
474  ccd = im.getDetector() # possibly modified by assembleCcdTask
475  e = None
476  break
477  except Exception as e:
478  continue
479 
480  if im:
481  im = im.getMaskedImage().getImage()
482  else:
483  raise e
484 
485  if e:
486  if self.verbose:
487  log.info("Reading %s: %s" % (ccd.getId(), e))
488 
489  if im is None:
490  return self._prepareImage(ccd, imageFactory(*bbox.getDimensions()), binSize), ccd
491 
492  if self.type == "raw":
493  allowRotate = True # all other images were rotated by the ISR
494  if hasattr(im, 'convertF'):
495  im = im.convertF()
496  if False and self.callback is None: # we need to trim the raw image
497  self.callback = rawCallback
498 
499  if self.callback:
500  try:
501  im = self.callback(im, ccd, imageSource=self)
502  except Exception as e:
503  if self.verbose:
504  log.error("callback failed: %s" % e)
505  im = imageFactory(*bbox.getDimensions())
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.afw.geom.Box` 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 = afwGeom.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 = afwGeom.Box2I(bbox)
722  bbox.shift(-afwGeom.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 = afwGeom.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.afw.geom.Box`
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 = afwGeom.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 = afwGeom.Box2I(
818  cbbox.getMin(), afwGeom.Extent2I(int(ex), int(ey)))
819  bbox = rotateBBoxBy90(bbox, nQuarter, bbox.getDimensions())
820  bbox.shift(afwGeom.Extent2I(int(llc.getX()//pixelSize_o.getX()/binSize),
821  int(llc.getY()//pixelSize_o.getY()/binSize)))
822  bbox.shift(afwGeom.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.afw.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.afw.geom.Box2I`
843  The resulting bounding box.
844  """
845  pixMin = afwGeom.Point2I(int(camBbox.getMinX()//pixelSize.getX()),
846  int(camBbox.getMinY()//pixelSize.getY()))
847  pixMax = afwGeom.Point2I(int(camBbox.getMaxX()//pixelSize.getX()),
848  int(camBbox.getMaxY()//pixelSize.getY()))
849  retBox = afwGeom.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 = afwGeom.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  import lsst.pex.exceptions as pexExceptions
921  try:
922  imView[:] = im
923  except pexExceptions.LengthError as e:
924  log.error("Unable to fit image for detector \"%s\" into image of camera: %s" % (det.getName(), e))
925 
926  return camIm
927 
928 
929 def showCamera(camera, imageSource=FakeImageDataSource(), imageFactory=afwImage.ImageF,
930  detectorNameList=None, binSize=10, bufferSize=10, frame=None, overlay=True, title="",
931  showWcs=None, ctype=afwDisplay.GREEN, textSize=1.25, originAtCenter=True, display=None,
932  **kwargs):
933  """Show a Camera on display, with the specified display.
934 
935  The rotation of the sensors is snapped to the nearest multiple of 90 deg.
936  Also note that the pixel size is constant over the image array. The lower
937  left corner (LLC) of each sensor amp is snapped to the LLC of the pixel
938  containing the LLC of the image.
939 
940  Parameters
941  ----------
942  camera : `lsst.afw.cameraGeom.Camera`
943  Camera object to use to make the image.
944  imageSource : `FakeImageDataSource` or None
945  Source to get ccd images. Must have a ``getCcdImage()`` method.
946  imageFactory : `lsst.afw.image.Image`
947  Type of image to make
948  detectorNameList : `list` of `str`
949  List of detector names from `camera` to use in building the image.
950  Use all Detectors if None.
951  binSize : `int`
952  Bin the image by this factor in both dimensions.
953  bufferSize : `int`
954  Size of border in binned pixels to make around the camera image.
955  frame : None
956  specify image display. **Deprecated** in v12.
957  overlay : `bool`
958  Overlay Detector IDs and boundaries?
959  title : `str`
960  Title to use in display.
961  showWcs : `bool`
962  Include a WCS in the display?
963  ctype : `lsst.afw.display.COLOR` or `str`
964  Color to use when drawing Detector boundaries.
965  textSize : `float`
966  Size of detector labels
967  originAtCenter : `bool`
968  Put origin of the camera WCS at the center of the image?
969  If False, the origin will be at the lower left.
970  display : `lsst.afw.display`
971  Image display on which to display.
972  **kwargs :
973  All remaining keyword arguments are passed to makeImageFromCamera
974 
975  Returns
976  -------
977  image : `lsst.afw.image.Image`
978  The mosaic image.
979  """
980  if frame is not None:
981  warnings.warn("The frame kwarg is deprecated; use the `lsst.afw.display` system instead.",
982  DeprecationWarning)
983 
984  display = _getDisplayFromDisplayOrFrame(display, frame)
985 
986  if binSize < 1:
987  binSize = 1
988  cameraImage = makeImageFromCamera(camera, detectorNameList=detectorNameList, bufferSize=bufferSize,
989  imageSource=imageSource, imageFactory=imageFactory, binSize=binSize,
990  **kwargs)
991 
992  if detectorNameList is None:
993  ccdList = [camera[name] for name in camera.getNameIter()]
994  else:
995  ccdList = [camera[name] for name in detectorNameList]
996 
997  if detectorNameList is None:
998  camBbox = camera.getFpBBox()
999  else:
1000  camBbox = afwGeom.Box2D()
1001  for detName in detectorNameList:
1002  for corner in camera[detName].getCorners(FOCAL_PLANE):
1003  camBbox.include(corner)
1004  pixelSize = ccdList[0].getPixelSize()
1005 
1006  if showWcs:
1007  if originAtCenter:
1008  wcsReferencePixel = afwGeom.Box2D(
1009  cameraImage.getBBox()).getCenter()
1010  else:
1011  wcsReferencePixel = afwGeom.Point2I(0, 0)
1012  wcs = makeFocalPlaneWcs(pixelSize*binSize, wcsReferencePixel)
1013  else:
1014  wcs = None
1015 
1016  if display:
1017  if title == "":
1018  title = camera.getName()
1019  display.mtv(cameraImage, title=title, wcs=wcs)
1020 
1021  if overlay:
1022  with display.Buffering():
1023  camBbox = getCameraImageBBox(
1024  camBbox, pixelSize, bufferSize*binSize)
1025  bboxList = getCcdInCamBBoxList(
1026  ccdList, binSize, pixelSize, camBbox.getMin())
1027  for bbox, ccd in zip(bboxList, ccdList):
1028  nQuarter = ccd.getOrientation().getNQuarter()
1029  # borderWidth to 0.5 to align with the outside edge of the
1030  # pixel
1031  displayUtils.drawBBox(
1032  bbox, borderWidth=0.5, ctype=ctype, display=display)
1033  dims = bbox.getDimensions()
1034  display.dot(ccd.getName(), bbox.getMinX()+dims.getX()/2, bbox.getMinY()+dims.getY()/2,
1035  ctype=ctype, size=textSize, textAngle=nQuarter*90)
1036 
1037  return cameraImage
1038 
1039 
1040 def makeFocalPlaneWcs(pixelSize, referencePixel):
1041  """Make a WCS for the focal plane geometry
1042  (i.e. one that returns positions in "mm")
1043 
1044  Parameters
1045  ----------
1046  pixelSize : `float`
1047  Size of the image pixels in physical units
1048  referencePixel : `lsst.afw.geom.Point2D`
1049  Pixel for origin of WCS
1050 
1051  Returns
1052  -------
1053  `lsst.afw.geom.Wcs`
1054  Wcs object for mapping between pixels and focal plane.
1055  """
1056 
1057  md = dafBase.PropertySet()
1058  if referencePixel is None:
1059  referencePixel = afwGeom.PointD(0, 0)
1060  for i in range(2):
1061  md.set("CRPIX%d"%(i+1), referencePixel[i])
1062  md.set("CRVAL%d"%(i+1), 0.)
1063  md.set("CDELT1", pixelSize[0])
1064  md.set("CDELT2", pixelSize[1])
1065  md.set("CTYPE1", "CAMERA_X")
1066  md.set("CTYPE2", "CAMERA_Y")
1067  md.set("CUNIT1", "mm")
1068  md.set("CUNIT2", "mm")
1069 
1070  return afwGeom.makeSkyWcs(md)
1071 
1072 
1073 def findAmp(ccd, pixelPosition):
1074  """Find the Amp with the specified pixel position within the composite
1075 
1076  Parameters
1077  ----------
1078  ccd : `lsst.afw.cameraGeom.Detector`
1079  Detector to look in.
1080  pixelPosition : `lsst.afw.geom.Point2I`
1081  The pixel position to find the amp for.
1082 
1083  Returns
1084  -------
1085  `lsst.afw.table.AmpInfoCatalog`
1086  Amp record in which pixelPosition falls or None if no Amp found.
1087  """
1088 
1089  for amp in ccd:
1090  if amp.getBBox().contains(pixelPosition):
1091  return amp
1092 
1093  return None
def makeImageFromAmp(amp, imValue=None, imageFactory=afwImage.ImageU, markSize=10, markValue=0, scaleGain=lambda gain:(gain *1000)//10)
Definition: utils.py:175
def makeFocalPlaneWcs(pixelSize, referencePixel)
Definition: utils.py:1040
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:932
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:80
def showCcd(ccd, imageSource=FakeImageDataSource(), display=None, frame=None, overlay=True, imageFactory=afwImage.ImageF, binSize=1, inCameraCoords=False)
Definition: utils.py:728
int min
Definition: Coord.cc:82
def getCcdInCamBBoxList(ccdList, binSize, pixelSize_o, origin)
Definition: utils.py:784
def getCcdImage(self, det, imageFactory, binSize)
Definition: utils.py:351
def findAmp(ccd, pixelPosition)
Definition: utils.py:1073
An integer coordinate rectangle.
Definition: Box.h:55
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:518
def getAmpImage(self, amp, imageFactory)
Definition: utils.py:371
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:341
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:439
def makeImageFromCamera(camera, detectorNameList=None, background=numpy.nan, bufferSize=10, imageSource=FakeImageDataSource(), imageFactory=afwImage.ImageU, binSize=1)
Definition: utils.py:855
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:392
int max
Definition: BoundedField.cc:99
def getCcdImage(self, ccd, imageFactory=afwImage.ImageF, binSize=1)
Definition: utils.py:449
def __init__(self, butler=None, type="raw", isTrimmed=True, verbose=False, background=numpy.nan, callback=None, args, kwargs)
Definition: utils.py:428
def makeImageFromCcd(ccd, isTrimmed=True, showAmpGain=True, imageFactory=afwImage.ImageU, rcMarkSize=10, binSize=1)
Definition: utils.py:261
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:450
def showAmp(amp, imageSource=FakeImageDataSource(isTrimmed=False), display=None, overlay=True, imageFactory=afwImage.ImageU)
Definition: utils.py:678
def prepareWcsData(wcs, amp, isTrimmed=True)
Definition: utils.py:45
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:578
def rotateBBoxBy90(bbox, n90, dimensions)
Rotate a bounding box by an integer multiple of 90 degrees.