LSST Applications  21.0.0-147-g0e635eb1+1acddb5be5,22.0.0+052faf71bd,22.0.0+1ea9a8b2b2,22.0.0+6312710a6c,22.0.0+729191ecac,22.0.0+7589c3a021,22.0.0+9f079a9461,22.0.1-1-g7d6de66+b8044ec9de,22.0.1-1-g87000a6+536b1ee016,22.0.1-1-g8e32f31+6312710a6c,22.0.1-10-gd060f87+016f7cdc03,22.0.1-12-g9c3108e+df145f6f68,22.0.1-16-g314fa6d+c825727ab8,22.0.1-19-g93a5c75+d23f2fb6d8,22.0.1-19-gb93eaa13+aab3ef7709,22.0.1-2-g8ef0a89+b8044ec9de,22.0.1-2-g92698f7+9f079a9461,22.0.1-2-ga9b0f51+052faf71bd,22.0.1-2-gac51dbf+052faf71bd,22.0.1-2-gb66926d+6312710a6c,22.0.1-2-gcb770ba+09e3807989,22.0.1-20-g32debb5+b8044ec9de,22.0.1-23-gc2439a9a+fb0756638e,22.0.1-3-g496fd5d+09117f784f,22.0.1-3-g59f966b+1e6ba2c031,22.0.1-3-g849a1b8+f8b568069f,22.0.1-3-gaaec9c0+c5c846a8b1,22.0.1-32-g5ddfab5d3+60ce4897b0,22.0.1-4-g037fbe1+64e601228d,22.0.1-4-g8623105+b8044ec9de,22.0.1-5-g096abc9+d18c45d440,22.0.1-5-g15c806e+57f5c03693,22.0.1-7-gba73697+57f5c03693,master-g6e05de7fdc+c1283a92b8,master-g72cdda8301+729191ecac,w.2021.39
LSST Data Management Base Package
Public Member Functions | Public Attributes | Static Public Attributes | List of all members
lsst.ip.diffim.modelPsfMatch.ModelPsfMatchTask Class Reference
Inheritance diagram for lsst.ip.diffim.modelPsfMatch.ModelPsfMatchTask:
lsst.ip.diffim.psfMatch.PsfMatchTask

Public Member Functions

def __init__ (self, *args, **kwargs)
 
def run (self, exposure, referencePsfModel, kernelSum=1.0)
 

Public Attributes

 kConfig
 
 useRegularization
 
 hMat
 

Static Public Attributes

 ConfigClass = ModelPsfMatchConfig
 

Detailed Description

Matching of two model Psfs, and application of the Psf-matching kernel to an input Exposure

Notes
-----

This Task differs from ImagePsfMatchTask in that it matches two Psf _models_, by realizing
them in an Exposure-sized SpatialCellSet and then inserting each Psf-image pair into KernelCandidates.
Because none of the pairs of sources that are to be matched should be invalid, all sigma clipping is
turned off in ModelPsfMatchConfig.  And because there is no tracked _variance_ in the Psf images, the
debugging and logging QA info should be interpreted with caution.

One item of note is that the sizes of Psf models are fixed (e.g. its defined as a 21x21 matrix).  When the
Psf-matching kernel is being solved for, the Psf "image" is convolved with each kernel basis function,
leading to a loss of information around the borders.
This pixel loss will be problematic for the numerical
stability of the kernel solution if the size of the convolution kernel
(set by ModelPsfMatchConfig.kernelSize) is much bigger than: psfSize//2.
Thus the sizes of Psf-model matching kernels are typically smaller
than their image-matching counterparts.  If the size of the kernel is too small, the convolved stars will
look "boxy"; if the kernel is too large, the kernel solution will be "noisy".  This is a trade-off that
needs careful attention for a given dataset.

The primary use case for this Task is in matching an Exposure to a
constant-across-the-sky Psf model for the purposes of image coaddition.
It is important to note that in the code, the "template" Psf is the Psf
that the science image gets matched to.  In this sense the order of template and science image are
reversed, compared to ImagePsfMatchTask, which operates on the template image.

Debug variables

The `lsst.pipe.base.cmdLineTask.CmdLineTask` command line task interface supports a
flag -d/--debug to import debug.py from your PYTHONPATH.  The relevant contents of debug.py
for this Task include:

.. code-block:: py

    import sys
    import lsstDebug
    def DebugInfo(name):
        di = lsstDebug.getInfo(name)
        if name == "lsst.ip.diffim.psfMatch":
            di.display = True                 # global
            di.maskTransparency = 80          # mask transparency
            di.displayCandidates = True       # show all the candidates and residuals
            di.displayKernelBasis = False     # show kernel basis functions
            di.displayKernelMosaic = True     # show kernel realized across the image
            di.plotKernelSpatialModel = False # show coefficients of spatial model
            di.showBadCandidates = True       # show the bad candidates (red) along with good (green)
        elif name == "lsst.ip.diffim.modelPsfMatch":
            di.display = True                 # global
            di.maskTransparency = 30          # mask transparency
            di.displaySpatialCells = True     # show spatial cells before the fit
        return di
    lsstDebug.Info = DebugInfo
    lsstDebug.frame = 1

Note that if you want addional logging info, you may add to your scripts:

.. code-block:: py

    import lsst.log.utils as logUtils
    logUtils.traceSetAt("ip.diffim", 4)

Examples
--------
A complete example of using ModelPsfMatchTask

This code is modelPsfMatchTask.py in the examples directory, and can be run as e.g.

.. code-block :: none

    examples/modelPsfMatchTask.py
    examples/modelPsfMatchTask.py --debug
    examples/modelPsfMatchTask.py --debug --template /path/to/templateExp.fits
    --science /path/to/scienceExp.fits

Create a subclass of ModelPsfMatchTask that accepts two exposures.
Note that the "template" exposure contains the Psf that will get matched to,
and the "science" exposure is the one that will be convolved:

.. code-block :: none

    class MyModelPsfMatchTask(ModelPsfMatchTask):
        def __init__(self, *args, **kwargs):
            ModelPsfMatchTask.__init__(self, *args, **kwargs)
        def run(self, templateExp, scienceExp):
            return ModelPsfMatchTask.run(self, scienceExp, templateExp.getPsf())

And allow the user the freedom to either run the script in default mode,
or point to their own images on disk. Note that these
images must be readable as an lsst.afw.image.Exposure:

.. code-block :: none

    if __name__ == "__main__":
        import argparse
        parser = argparse.ArgumentParser(description="Demonstrate the use of ModelPsfMatchTask")
        parser.add_argument("--debug", "-d", action="store_true", help="Load debug.py?", default=False)
        parser.add_argument("--template", "-t", help="Template Exposure to use", default=None)
        parser.add_argument("--science", "-s", help="Science Exposure to use", default=None)
        args = parser.parse_args()

We have enabled some minor display debugging in this script via the –debug option.
However, if you have an lsstDebug debug.py in your PYTHONPATH you will get additional
debugging displays. The following block checks for this script:

.. code-block :: none

    if args.debug:
        try:
            import debug
            # Since I am displaying 2 images here, set the starting frame number for the LSST debug LSST
            debug.lsstDebug.frame = 3
        except ImportError as e:
            print(e, file=sys.stderr)

Finally, we call a run method that we define below.
First set up a Config and modify some of the parameters.
In particular we don't want to "grow" the sizes of the kernel or KernelCandidates,
since we are operating with fixed–size images (i.e. the size of the input Psf models).

.. code-block :: none

    def run(args):
        #
        # Create the Config and use sum of gaussian basis
        #
        config = ModelPsfMatchTask.ConfigClass()
        config.kernel.active.scaleByFwhm = False

Make sure the images (if any) that were sent to the script exist on disk and are readable.
If no images are sent, make some fake data up for the sake of this example script
(have a look at the code if you want more details on generateFakeData):

.. code-block :: none

    # Run the requested method of the Task
    if args.template is not None and args.science is not None:
        if not os.path.isfile(args.template):
            raise FileNotFoundError("Template image %s does not exist" % (args.template))
        if not os.path.isfile(args.science):
            raise FileNotFoundError("Science image %s does not exist" % (args.science))
        try:
            templateExp = afwImage.ExposureF(args.template)
        except Exception as e:
            raise RuntimeError("Cannot read template image %s" % (args.template))
        try:
            scienceExp = afwImage.ExposureF(args.science)
        except Exception as e:
            raise RuntimeError("Cannot read science image %s" % (args.science))
    else:
        templateExp, scienceExp = generateFakeData()
        config.kernel.active.sizeCellX = 128
        config.kernel.active.sizeCellY = 128

.. code-block :: none

    if args.debug:
        afwDisplay.Display(frame=1).mtv(templateExp, title="Example script: Input Template")
        afwDisplay.Display(frame=2).mtv(scienceExp, title="Example script: Input Science Image")

Create and run the Task:

.. code-block :: none

    # Create the Task
    psfMatchTask = MyModelPsfMatchTask(config=config)
    # Run the Task
    result = psfMatchTask.run(templateExp, scienceExp)

And finally provide optional debugging display of the Psf-matched (via the Psf models) science image:

.. code-block :: none

    if args.debug:
        # See if the LSST debug has incremented the frame number; if not start with frame 3
        try:
            frame = debug.lsstDebug.frame + 1
        except Exception:
            frame = 3
        afwDisplay.Display(frame=frame).mtv(result.psfMatchedExposure,
                                            title="Example script: Matched Science Image")

Definition at line 93 of file modelPsfMatch.py.

Constructor & Destructor Documentation

◆ __init__()

def lsst.ip.diffim.modelPsfMatch.ModelPsfMatchTask.__init__ (   self,
args,
**  kwargs 
)
Create a ModelPsfMatchTask

Parameters
----------
*args
    arguments to be passed to lsst.ip.diffim.PsfMatchTask.__init__
**kwargs
    keyword arguments to be passed to lsst.ip.diffim.PsfMatchTask.__init__

Notes
-----
Upon initialization, the kernel configuration is defined by self.config.kernel.active.  This Task
does have a run() method, which is the default way to call the Task.

Reimplemented from lsst.ip.diffim.psfMatch.PsfMatchTask.

Definition at line 280 of file modelPsfMatch.py.

280  def __init__(self, *args, **kwargs):
281  """Create a ModelPsfMatchTask
282 
283  Parameters
284  ----------
285  *args
286  arguments to be passed to lsst.ip.diffim.PsfMatchTask.__init__
287  **kwargs
288  keyword arguments to be passed to lsst.ip.diffim.PsfMatchTask.__init__
289 
290  Notes
291  -----
292  Upon initialization, the kernel configuration is defined by self.config.kernel.active. This Task
293  does have a run() method, which is the default way to call the Task.
294  """
295  PsfMatchTask.__init__(self, *args, **kwargs)
296  self.kConfig = self.config.kernel.active
297 

Member Function Documentation

◆ run()

def lsst.ip.diffim.modelPsfMatch.ModelPsfMatchTask.run (   self,
  exposure,
  referencePsfModel,
  kernelSum = 1.0 
)
Psf-match an exposure to a model Psf

Parameters
----------
exposure : `lsst.afw.image.Exposure`
    Exposure to Psf-match to the reference Psf model;
    it must return a valid PSF model via exposure.getPsf()
referencePsfModel : `lsst.afw.detection.Psf`
    The Psf model to match to
kernelSum : `float`, optional
    A multipicative factor to apply to the kernel sum (default=1.0)

Returns
-------
result : `struct`
    - ``psfMatchedExposure`` : the Psf-matched Exposure.
        This has the same parent bbox, Wcs, PhotoCalib and
        Filter as the input Exposure but no Psf.
        In theory the Psf should equal referencePsfModel but
        the match is likely not exact.
    - ``psfMatchingKernel`` : the spatially varying Psf-matching kernel
    - ``kernelCellSet`` : SpatialCellSet used to solve for the Psf-matching kernel
    - ``referencePsfModel`` : Validated and/or modified reference model used

Raises
------
RuntimeError
    if the Exposure does not contain a Psf model

Definition at line 299 of file modelPsfMatch.py.

299  def run(self, exposure, referencePsfModel, kernelSum=1.0):
300  """Psf-match an exposure to a model Psf
301 
302  Parameters
303  ----------
304  exposure : `lsst.afw.image.Exposure`
305  Exposure to Psf-match to the reference Psf model;
306  it must return a valid PSF model via exposure.getPsf()
307  referencePsfModel : `lsst.afw.detection.Psf`
308  The Psf model to match to
309  kernelSum : `float`, optional
310  A multipicative factor to apply to the kernel sum (default=1.0)
311 
312  Returns
313  -------
314  result : `struct`
315  - ``psfMatchedExposure`` : the Psf-matched Exposure.
316  This has the same parent bbox, Wcs, PhotoCalib and
317  Filter as the input Exposure but no Psf.
318  In theory the Psf should equal referencePsfModel but
319  the match is likely not exact.
320  - ``psfMatchingKernel`` : the spatially varying Psf-matching kernel
321  - ``kernelCellSet`` : SpatialCellSet used to solve for the Psf-matching kernel
322  - ``referencePsfModel`` : Validated and/or modified reference model used
323 
324  Raises
325  ------
326  RuntimeError
327  if the Exposure does not contain a Psf model
328  """
329  if not exposure.hasPsf():
330  raise RuntimeError("exposure does not contain a Psf model")
331 
332  maskedImage = exposure.getMaskedImage()
333 
334  self.log.info("compute Psf-matching kernel")
335  result = self._buildCellSet(exposure, referencePsfModel)
336  kernelCellSet = result.kernelCellSet
337  referencePsfModel = result.referencePsfModel
338  fwhmScience = exposure.getPsf().computeShape().getDeterminantRadius()*sigma2fwhm
339  fwhmModel = referencePsfModel.computeShape().getDeterminantRadius()*sigma2fwhm
340 
341  basisList = makeKernelBasisList(self.kConfig, fwhmScience, fwhmModel, metadata=self.metadata)
342  spatialSolution, psfMatchingKernel, backgroundModel = self._solve(kernelCellSet, basisList)
343 
344  if psfMatchingKernel.isSpatiallyVarying():
345  sParameters = np.array(psfMatchingKernel.getSpatialParameters())
346  sParameters[0][0] = kernelSum
347  psfMatchingKernel.setSpatialParameters(sParameters)
348  else:
349  kParameters = np.array(psfMatchingKernel.getKernelParameters())
350  kParameters[0] = kernelSum
351  psfMatchingKernel.setKernelParameters(kParameters)
352 
353  self.log.info("Psf-match science exposure to reference")
354  psfMatchedExposure = afwImage.ExposureF(exposure.getBBox(), exposure.getWcs())
355  psfMatchedExposure.setFilterLabel(exposure.getFilterLabel())
356  psfMatchedExposure.setPhotoCalib(exposure.getPhotoCalib())
357  psfMatchedExposure.getInfo().setVisitInfo(exposure.getInfo().getVisitInfo())
358  psfMatchedExposure.setPsf(referencePsfModel)
359  psfMatchedMaskedImage = psfMatchedExposure.getMaskedImage()
360 
361  # Normalize the psf-matching kernel while convolving since its magnitude is meaningless
362  # when PSF-matching one model to another.
363  convolutionControl = afwMath.ConvolutionControl()
364  convolutionControl.setDoNormalize(True)
365  afwMath.convolve(psfMatchedMaskedImage, maskedImage, psfMatchingKernel, convolutionControl)
366 
367  self.log.info("done")
368  return pipeBase.Struct(psfMatchedExposure=psfMatchedExposure,
369  psfMatchingKernel=psfMatchingKernel,
370  kernelCellSet=kernelCellSet,
371  metadata=self.metadata,
372  )
373 
Parameters to control convolution.
Definition: ConvolveImage.h:50
void convolve(OutImageT &convolvedImage, InImageT const &inImage, KernelT const &kernel, ConvolutionControl const &convolutionControl=ConvolutionControl())
Convolve an Image or MaskedImage with a Kernel, setting pixels of an existing output image.
def run(self, coaddExposures, bbox, wcs)
Definition: getTemplate.py:603
def makeKernelBasisList(config, targetFwhmPix=None, referenceFwhmPix=None, basisDegGauss=None, basisSigmaGauss=None, metadata=None)

Member Data Documentation

◆ ConfigClass

lsst.ip.diffim.modelPsfMatch.ModelPsfMatchTask.ConfigClass = ModelPsfMatchConfig
static

Definition at line 278 of file modelPsfMatch.py.

◆ hMat

lsst.ip.diffim.psfMatch.PsfMatchTask.hMat
inherited

Definition at line 660 of file psfMatch.py.

◆ kConfig

lsst.ip.diffim.modelPsfMatch.ModelPsfMatchTask.kConfig

Definition at line 296 of file modelPsfMatch.py.

◆ useRegularization

lsst.ip.diffim.psfMatch.PsfMatchTask.useRegularization
inherited

Definition at line 655 of file psfMatch.py.


The documentation for this class was generated from the following file: