23 __all__ = [
"DetectionConfig",
"PsfMatchConfig",
"PsfMatchConfigAL",
"PsfMatchConfigDF",
"PsfMatchTask"]
36 from .
import utils
as diutils
37 from .
import diffimLib
41 """Configuration for detecting sources on images for building a 44 Configuration for turning detected lsst.afw.detection.FootPrints into an 45 acceptable (unmasked, high signal-to-noise, not too large or not too small) 46 list of `lsst.ip.diffim.KernelSources` that are used to build the 47 Psf-matching kernel""" 49 detThreshold = pexConfig.Field(
51 doc=
"Value of footprint detection threshold",
53 check=
lambda x: x >= 3.0
55 detThresholdType = pexConfig.ChoiceField(
57 doc=
"Type of detection threshold",
58 default=
"pixel_stdev",
60 "value":
"Use counts as the detection threshold type",
61 "stdev":
"Use standard deviation of image plane",
62 "variance":
"Use variance of image plane",
63 "pixel_stdev":
"Use stdev derived from variance plane" 66 detOnTemplate = pexConfig.Field(
68 doc=
"""If true run detection on the template (image to convolve); 69 if false run detection on the science image""",
72 badMaskPlanes = pexConfig.ListField(
74 doc=
"""Mask planes that lead to an invalid detection. 75 Options: NO_DATA EDGE SAT BAD CR INTRP""",
76 default=(
"NO_DATA",
"EDGE",
"SAT")
78 fpNpixMin = pexConfig.Field(
80 doc=
"Minimum number of pixels in an acceptable Footprint",
82 check=
lambda x: x >= 5
84 fpNpixMax = pexConfig.Field(
86 doc=
"""Maximum number of pixels in an acceptable Footprint; 87 too big and the subsequent convolutions become unwieldy""",
89 check=
lambda x: x <= 500
91 fpGrowKernelScaling = pexConfig.Field(
93 doc=
"""If config.scaleByFwhm, grow the footprint based on 94 the final kernelSize. Each footprint will be 95 2*fpGrowKernelScaling*kernelSize x 96 2*fpGrowKernelScaling*kernelSize. With the value 97 of 1.0, the remaining pixels in each KernelCandiate 98 after convolution by the basis functions will be 99 equal to the kernel size itself.""",
101 check=
lambda x: x >= 1.0
103 fpGrowPix = pexConfig.Field(
105 doc=
"""Growing radius (in pixels) for each raw detection 106 footprint. The smaller the faster; however the 107 kernel sum does not converge if the stamp is too 108 small; and the kernel is not constrained at all if 109 the stamp is the size of the kernel. The grown stamp 110 is 2 * fpGrowPix pixels larger in each dimension. 111 This is overridden by fpGrowKernelScaling if scaleByFwhm""",
113 check=
lambda x: x >= 10
115 scaleByFwhm = pexConfig.Field(
117 doc=
"Scale fpGrowPix by input Fwhm?",
123 """Base configuration for Psf-matching 125 The base configuration of the Psf-matching kernel, and of the warping, detection, 126 and background modeling subTasks.""" 128 warpingConfig = pexConfig.ConfigField(
"Config for warping exposures to a common alignment",
129 afwMath.warper.WarperConfig)
130 detectionConfig = pexConfig.ConfigField(
"Controlling the detection of sources for kernel building",
132 afwBackgroundConfig = pexConfig.ConfigField(
"Controlling the Afw background fitting",
133 SubtractBackgroundConfig)
135 useAfwBackground = pexConfig.Field(
137 doc=
"Use afw background subtraction instead of ip_diffim",
140 fitForBackground = pexConfig.Field(
142 doc=
"Include terms (including kernel cross terms) for background in ip_diffim",
145 kernelBasisSet = pexConfig.ChoiceField(
147 doc=
"Type of basis set for PSF matching kernel.",
148 default=
"alard-lupton",
150 "alard-lupton":
"""Alard-Lupton sum-of-gaussians basis set, 151 * The first term has no spatial variation 152 * The kernel sum is conserved 153 * You may want to turn off 'usePcaForSpatialKernel'""",
154 "delta-function":
"""Delta-function kernel basis set, 155 * You may enable the option useRegularization 156 * You should seriously consider usePcaForSpatialKernel, which will also 157 enable kernel sum conservation for the delta function kernels""" 160 kernelSize = pexConfig.Field(
162 doc=
"""Number of rows/columns in the convolution kernel; should be odd-valued. 163 Modified by kernelSizeFwhmScaling if scaleByFwhm = true""",
166 scaleByFwhm = pexConfig.Field(
168 doc=
"Scale kernelSize, alardGaussians by input Fwhm",
171 kernelSizeFwhmScaling = pexConfig.Field(
173 doc=
"""How much to scale the kernel size based on the largest AL Sigma""",
175 check=
lambda x: x >= 1.0
177 kernelSizeMin = pexConfig.Field(
179 doc=
"""Minimum Kernel Size""",
182 kernelSizeMax = pexConfig.Field(
184 doc=
"""Maximum Kernel Size""",
187 spatialModelType = pexConfig.ChoiceField(
189 doc=
"Type of spatial functions for kernel and background",
190 default=
"chebyshev1",
192 "chebyshev1":
"Chebyshev polynomial of the first kind",
193 "polynomial":
"Standard x,y polynomial",
196 spatialKernelOrder = pexConfig.Field(
198 doc=
"Spatial order of convolution kernel variation",
200 check=
lambda x: x >= 0
202 spatialBgOrder = pexConfig.Field(
204 doc=
"Spatial order of differential background variation",
206 check=
lambda x: x >= 0
208 sizeCellX = pexConfig.Field(
210 doc=
"Size (rows) in pixels of each SpatialCell for spatial modeling",
212 check=
lambda x: x >= 32
214 sizeCellY = pexConfig.Field(
216 doc=
"Size (columns) in pixels of each SpatialCell for spatial modeling",
218 check=
lambda x: x >= 32
220 nStarPerCell = pexConfig.Field(
222 doc=
"Number of KernelCandidates in each SpatialCell to use in the spatial fitting",
224 check=
lambda x: x >= 1
226 maxSpatialIterations = pexConfig.Field(
228 doc=
"Maximum number of iterations for rejecting bad KernelCandidates in spatial fitting",
230 check=
lambda x: x >= 1
and x <= 5
232 usePcaForSpatialKernel = pexConfig.Field(
234 doc=
"""Use Pca to reduce the dimensionality of the kernel basis sets. 235 This is particularly useful for delta-function kernels. 236 Functionally, after all Cells have their raw kernels determined, we run 237 a Pca on these Kernels, re-fit the Cells using the eigenKernels and then 238 fit those for spatial variation using the same technique as for Alard-Lupton kernels. 239 If this option is used, the first term will have no spatial variation and the 240 kernel sum will be conserved.""",
243 subtractMeanForPca = pexConfig.Field(
245 doc=
"Subtract off the mean feature before doing the Pca",
248 numPrincipalComponents = pexConfig.Field(
250 doc=
"""Number of principal components to use for Pca basis, including the 251 mean kernel if requested.""",
253 check=
lambda x: x >= 3
255 singleKernelClipping = pexConfig.Field(
257 doc=
"Do sigma clipping on each raw kernel candidate",
260 kernelSumClipping = pexConfig.Field(
262 doc=
"Do sigma clipping on the ensemble of kernel sums",
265 spatialKernelClipping = pexConfig.Field(
267 doc=
"Do sigma clipping after building the spatial model",
270 checkConditionNumber = pexConfig.Field(
272 doc=
"""Test for maximum condition number when inverting a kernel matrix. 273 Anything above maxConditionNumber is not used and the candidate is set as BAD. 274 Also used to truncate inverse matrix in estimateBiasedRisk. However, 275 if you are doing any deconvolution you will want to turn this off, or use 276 a large maxConditionNumber""",
279 badMaskPlanes = pexConfig.ListField(
281 doc=
"""Mask planes to ignore when calculating diffim statistics 282 Options: NO_DATA EDGE SAT BAD CR INTRP""",
283 default=(
"NO_DATA",
"EDGE",
"SAT")
285 candidateResidualMeanMax = pexConfig.Field(
287 doc=
"""Rejects KernelCandidates yielding bad difference image quality. 288 Used by BuildSingleKernelVisitor, AssessSpatialKernelVisitor. 289 Represents average over pixels of (image/sqrt(variance)).""",
291 check=
lambda x: x >= 0.0
293 candidateResidualStdMax = pexConfig.Field(
295 doc=
"""Rejects KernelCandidates yielding bad difference image quality. 296 Used by BuildSingleKernelVisitor, AssessSpatialKernelVisitor. 297 Represents stddev over pixels of (image/sqrt(variance)).""",
299 check=
lambda x: x >= 0.0
301 useCoreStats = pexConfig.Field(
303 doc=
"""Use the core of the footprint for the quality statistics, instead of the entire footprint. 304 WARNING: if there is deconvolution we probably will need to turn this off""",
307 candidateCoreRadius = pexConfig.Field(
309 doc=
"""Radius for calculation of stats in 'core' of KernelCandidate diffim. 310 Total number of pixels used will be (2*radius)**2. 311 This is used both for 'core' diffim quality as well as ranking of 312 KernelCandidates by their total flux in this core""",
314 check=
lambda x: x >= 1
316 maxKsumSigma = pexConfig.Field(
318 doc=
"""Maximum allowed sigma for outliers from kernel sum distribution. 319 Used to reject variable objects from the kernel model""",
321 check=
lambda x: x >= 0.0
323 maxConditionNumber = pexConfig.Field(
325 doc=
"Maximum condition number for a well conditioned matrix",
327 check=
lambda x: x >= 0.0
329 conditionNumberType = pexConfig.ChoiceField(
331 doc=
"Use singular values (SVD) or eigen values (EIGENVALUE) to determine condition number",
332 default=
"EIGENVALUE",
334 "SVD":
"Use singular values",
335 "EIGENVALUE":
"Use eigen values (faster)",
338 maxSpatialConditionNumber = pexConfig.Field(
340 doc=
"Maximum condition number for a well conditioned spatial matrix",
342 check=
lambda x: x >= 0.0
344 iterateSingleKernel = pexConfig.Field(
346 doc=
"""Remake KernelCandidate using better variance estimate after first pass? 347 Primarily useful when convolving a single-depth image, otherwise not necessary.""",
350 constantVarianceWeighting = pexConfig.Field(
352 doc=
"""Use constant variance weighting in single kernel fitting? 353 In some cases this is better for bright star residuals.""",
356 calculateKernelUncertainty = pexConfig.Field(
358 doc=
"""Calculate kernel and background uncertainties for each kernel candidate? 359 This comes from the inverse of the covariance matrix. 360 Warning: regularization can cause problems for this step.""",
363 useBicForKernelBasis = pexConfig.Field(
365 doc=
"""Use Bayesian Information Criterion to select the number of bases going into the kernel""",
371 """The parameters specific to the "Alard-Lupton" (sum-of-Gaussian) Psf-matching basis""" 374 PsfMatchConfig.setDefaults(self)
378 alardNGauss = pexConfig.Field(
380 doc=
"Number of Gaussians in alard-lupton basis",
382 check=
lambda x: x >= 1
384 alardDegGauss = pexConfig.ListField(
386 doc=
"Polynomial order of spatial modification of Gaussians. Must in number equal alardNGauss",
389 alardSigGauss = pexConfig.ListField(
391 doc=
"""Sigma in pixels of Gaussians (FWHM = 2.35 sigma). Must in number equal alardNGauss""",
392 default=(0.7, 1.5, 3.0),
394 alardGaussBeta = pexConfig.Field(
396 doc=
"""Default scale factor between Gaussian sigmas """,
398 check=
lambda x: x >= 0.0,
400 alardMinSig = pexConfig.Field(
402 doc=
"""Minimum Sigma (pixels) for Gaussians""",
404 check=
lambda x: x >= 0.25
406 alardDegGaussDeconv = pexConfig.Field(
408 doc=
"""Degree of spatial modification of ALL gaussians in AL basis during deconvolution""",
410 check=
lambda x: x >= 1
412 alardMinSigDeconv = pexConfig.Field(
414 doc=
"""Minimum Sigma (pixels) for Gaussians during deconvolution; 415 make smaller than alardMinSig as this is only indirectly used""",
417 check=
lambda x: x >= 0.25
419 alardNGaussDeconv = pexConfig.Field(
421 doc=
"Number of Gaussians in AL basis during deconvolution",
423 check=
lambda x: x >= 1
428 """The parameters specific to the delta-function (one basis per-pixel) Psf-matching basis""" 431 PsfMatchConfig.setDefaults(self)
438 useRegularization = pexConfig.Field(
440 doc=
"Use regularization to smooth the delta function kernels",
443 regularizationType = pexConfig.ChoiceField(
445 doc=
"Type of regularization.",
446 default=
"centralDifference",
448 "centralDifference":
"Penalize second derivative using 2-D stencil of central finite difference",
449 "forwardDifference":
"Penalize first, second, third derivatives using forward finite differeces" 452 centralRegularizationStencil = pexConfig.ChoiceField(
454 doc=
"Type of stencil to approximate central derivative (for centralDifference only)",
457 5:
"5-point stencil including only adjacent-in-x,y elements",
458 9:
"9-point stencil including diagonal elements" 461 forwardRegularizationOrders = pexConfig.ListField(
463 doc=
"Array showing which order derivatives to penalize (for forwardDifference only)",
465 itemCheck=
lambda x: (x > 0)
and (x < 4)
467 regularizationBorderPenalty = pexConfig.Field(
469 doc=
"Value of the penalty for kernel border pixels",
471 check=
lambda x: x >= 0.0
473 lambdaType = pexConfig.ChoiceField(
475 doc=
"How to choose the value of the regularization strength",
478 "absolute":
"Use lambdaValue as the value of regularization strength",
479 "relative":
"Use lambdaValue as fraction of the default regularization strength (N.R. 18.5.8)",
480 "minimizeBiasedRisk":
"Minimize biased risk estimate",
481 "minimizeUnbiasedRisk":
"Minimize unbiased risk estimate",
484 lambdaValue = pexConfig.Field(
486 doc=
"Value used for absolute determinations of regularization strength",
489 lambdaScaling = pexConfig.Field(
491 doc=
"Fraction of the default lambda strength (N.R. 18.5.8) to use. 1e-4 or 1e-5",
494 lambdaStepType = pexConfig.ChoiceField(
496 doc=
"""If a scan through lambda is needed (minimizeBiasedRisk, minimizeUnbiasedRisk), 497 use log or linear steps""",
500 "log":
"Step in log intervals; e.g. lambdaMin, lambdaMax, lambdaStep = -1.0, 2.0, 0.1",
501 "linear":
"Step in linear intervals; e.g. lambdaMin, lambdaMax, lambdaStep = 0.1, 100, 0.1",
504 lambdaMin = pexConfig.Field(
506 doc=
"""If scan through lambda needed (minimizeBiasedRisk, minimizeUnbiasedRisk), 507 start at this value. If lambdaStepType = log:linear, suggest -1:0.1""",
510 lambdaMax = pexConfig.Field(
512 doc=
"""If scan through lambda needed (minimizeBiasedRisk, minimizeUnbiasedRisk), 513 stop at this value. If lambdaStepType = log:linear, suggest 2:100""",
516 lambdaStep = pexConfig.Field(
518 doc=
"""If scan through lambda needed (minimizeBiasedRisk, minimizeUnbiasedRisk), 519 step in these increments. If lambdaStepType = log:linear, suggest 0.1:0.1""",
525 """Base class for Psf Matching; should not be called directly 529 PsfMatchTask is a base class that implements the core functionality for matching the 530 Psfs of two images using a spatially varying Psf-matching lsst.afw.math.LinearCombinationKernel. 531 The Task requires the user to provide an instance of an lsst.afw.math.SpatialCellSet, 532 filled with lsst.ip.diffim.KernelCandidate instances, and a list of lsst.afw.math.Kernels 533 of basis shapes that will be used for the decomposition. If requested, the Task 534 also performs background matching and returns the differential background model as an 535 lsst.afw.math.Kernel.SpatialFunction. 539 As a base class, this Task is not directly invoked. However, run() methods that are 540 implemented on derived classes will make use of the core _solve() functionality, 541 which defines a sequence of lsst.afw.math.CandidateVisitor classes that iterate 542 through the KernelCandidates, first building up a per-candidate solution and then 543 building up a spatial model from the ensemble of candidates. Sigma clipping is 544 performed using the mean and standard deviation of all kernel sums (to reject 545 variable objects), on the per-candidate substamp diffim residuals 546 (to indicate a bad choice of kernel basis shapes for that particular object), 547 and on the substamp diffim residuals using the spatial kernel fit (to indicate a bad 548 choice of spatial kernel order, or poor constraints on the spatial model). The 549 _diagnostic() method logs information on the quality of the spatial fit, and also 550 modifies the Task metadata. 552 .. list-table:: Quantities set in Metadata 557 * - `spatialConditionNum` 558 - Condition number of the spatial kernel fit 559 * - `spatialKernelSum` 560 - Kernel sum (10^{-0.4 * ``Delta``; zeropoint}) of the spatial Psf-matching kernel 562 - If using sum-of-Gaussian basis, the number of gaussians used 563 * - `ALBasisDegGauss` 564 - If using sum-of-Gaussian basis, the deg of spatial variation of the Gaussians 565 * - `ALBasisSigGauss` 566 - If using sum-of-Gaussian basis, the widths (sigma) of the Gaussians 568 - If using sum-of-Gaussian basis, the kernel size 569 * - `NFalsePositivesTotal` 570 - Total number of diaSources 571 * - `NFalsePositivesRefAssociated` 572 - Number of diaSources that associate with the reference catalog 573 * - `NFalsePositivesRefAssociated` 574 - Number of diaSources that associate with the source catalog 575 * - `NFalsePositivesUnassociated` 576 - Number of diaSources that are orphans 578 - Mean value of substamp diffim quality metrics across all KernelCandidates, 579 for both the per-candidate (LOCAL) and SPATIAL residuals 581 - Median value of substamp diffim quality metrics across all KernelCandidates, 582 for both the per-candidate (LOCAL) and SPATIAL residuals 584 - Standard deviation of substamp diffim quality metrics across all KernelCandidates, 585 for both the per-candidate (LOCAL) and SPATIAL residuals 589 The lsst.pipe.base.cmdLineTask.CmdLineTask command line task interface supports a 590 flag -d/--debug to import @b debug.py from your PYTHONPATH. The relevant contents of debug.py 591 for this Task include: 598 di = lsstDebug.getInfo(name) 599 if name == "lsst.ip.diffim.psfMatch": 600 # enable debug output 602 # ds9 mask transparency 603 di.maskTransparency = 80 604 # show all the candidates and residuals 605 di.displayCandidates = True 606 # show kernel basis functions 607 di.displayKernelBasis = False 608 # show kernel realized across the image 609 di.displayKernelMosaic = True 610 # show coefficients of spatial model 611 di.plotKernelSpatialModel = False 612 # show the bad candidates (red) along with good (green) 613 di.showBadCandidates = True 615 lsstDebug.Info = DebugInfo 618 Note that if you want addional logging info, you may add to your scripts: 622 import lsst.log.utils as logUtils 623 logUtils.traceSetAt("ip.diffim", 4) 625 ConfigClass = PsfMatchConfig
626 _DefaultName =
"psfMatch" 629 """Create the psf-matching Task 634 Arguments to be passed to ``lsst.pipe.base.task.Task.__init__`` 636 Keyword arguments to be passed to ``lsst.pipe.base.task.Task.__init__`` 640 The initialization sets the Psf-matching kernel configuration using the value of 641 self.config.kernel.active. If the kernel is requested with regularization to moderate 642 the bias/variance tradeoff, currently only used when a delta function kernel basis 643 is provided, it creates a regularization matrix stored as member variable 646 pipeBase.Task.__init__(self, *args, **kwargs)
649 if 'useRegularization' in self.
kConfig:
655 self.
hMat = diffimLib.makeRegularizationMatrix(pexConfig.makePolicy(self.
kConfig))
657 def _diagnostic(self, kernelCellSet, spatialSolution, spatialKernel, spatialBg):
658 """Provide logging diagnostics on quality of spatial kernel fit 663 Cellset that contains the KernelCandidates used in the fitting 664 spatialSolution : TYPE 665 KernelSolution of best-fit 667 Best-fit spatial Kernel model 669 Best-fit spatial background model 672 kImage = afwImage.ImageD(spatialKernel.getDimensions())
673 kSum = spatialKernel.computeImage(kImage,
False)
674 self.log.
info(
"Final spatial kernel sum %.3f" % (kSum))
677 conditionNum = spatialSolution.getConditionNumber(
678 getattr(diffimLib.KernelSolution, self.
kConfig.conditionNumberType))
679 self.log.
info(
"Spatial model condition number %.3e" % (conditionNum))
681 if conditionNum < 0.0:
682 self.log.
warn(
"Condition number is negative (%.3e)" % (conditionNum))
683 if conditionNum > self.
kConfig.maxSpatialConditionNumber:
684 self.log.
warn(
"Spatial solution exceeds max condition number (%.3e > %.3e)" % (
685 conditionNum, self.
kConfig.maxSpatialConditionNumber))
687 self.metadata.
set(
"spatialConditionNum", conditionNum)
688 self.metadata.
set(
"spatialKernelSum", kSum)
691 nBasisKernels = spatialKernel.getNBasisKernels()
692 nKernelTerms = spatialKernel.getNSpatialParameters()
693 if nKernelTerms == 0:
697 nBgTerms = spatialBg.getNParameters()
699 if spatialBg.getParameters()[0] == 0.0:
705 for cell
in kernelCellSet.getCellList():
706 for cand
in cell.begin(
False):
708 if cand.getStatus() == afwMath.SpatialCellCandidate.GOOD:
710 if cand.getStatus() == afwMath.SpatialCellCandidate.BAD:
713 self.log.
info(
"Doing stats of kernel candidates used in the spatial fit.")
717 self.log.
warn(
"Many more candidates rejected than accepted; %d total, %d rejected, %d used" % (
720 self.log.
info(
"%d candidates total, %d rejected, %d used" % (nTot, nBad, nGood))
723 if nGood < nKernelTerms:
724 self.log.
warn(
"Spatial kernel model underconstrained; %d candidates, %d terms, %d bases" % (
725 nGood, nKernelTerms, nBasisKernels))
726 self.log.
warn(
"Consider lowering the spatial order")
727 elif nGood <= 2*nKernelTerms:
728 self.log.
warn(
"Spatial kernel model poorly constrained; %d candidates, %d terms, %d bases" % (
729 nGood, nKernelTerms, nBasisKernels))
730 self.log.
warn(
"Consider lowering the spatial order")
732 self.log.
info(
"Spatial kernel model well constrained; %d candidates, %d terms, %d bases" % (
733 nGood, nKernelTerms, nBasisKernels))
736 self.log.
warn(
"Spatial background model underconstrained; %d candidates, %d terms" % (
738 self.log.
warn(
"Consider lowering the spatial order")
739 elif nGood <= 2*nBgTerms:
740 self.log.
warn(
"Spatial background model poorly constrained; %d candidates, %d terms" % (
742 self.log.
warn(
"Consider lowering the spatial order")
744 self.log.
info(
"Spatial background model appears well constrained; %d candidates, %d terms" % (
747 def _displayDebug(self, kernelCellSet, spatialKernel, spatialBackground):
748 """Provide visualization of the inputs and ouputs to the Psf-matching code 753 The SpatialCellSet used in determining the matching kernel and background 755 Spatially varying Psf-matching kernel 756 spatialBackground : TYPE 757 Spatially varying background-matching function 762 displayKernelMosaic =
lsstDebug.Info(__name__).displayKernelMosaic
763 plotKernelSpatialModel =
lsstDebug.Info(__name__).plotKernelSpatialModel
766 if not maskTransparency:
768 ds9.setMaskTransparency(maskTransparency)
770 if displayCandidates:
771 diutils.showKernelCandidates(kernelCellSet, kernel=spatialKernel, background=spatialBackground,
772 frame=lsstDebug.frame,
773 showBadCandidates=showBadCandidates)
775 diutils.showKernelCandidates(kernelCellSet, kernel=spatialKernel, background=spatialBackground,
776 frame=lsstDebug.frame,
777 showBadCandidates=showBadCandidates,
780 diutils.showKernelCandidates(kernelCellSet, kernel=spatialKernel, background=spatialBackground,
781 frame=lsstDebug.frame,
782 showBadCandidates=showBadCandidates,
786 if displayKernelBasis:
787 diutils.showKernelBasis(spatialKernel, frame=lsstDebug.frame)
790 if displayKernelMosaic:
791 diutils.showKernelMosaic(kernelCellSet.getBBox(), spatialKernel, frame=lsstDebug.frame)
794 if plotKernelSpatialModel:
795 diutils.plotKernelSpatialModel(spatialKernel, kernelCellSet, showBadCandidates=showBadCandidates)
797 def _createPcaBasis(self, kernelCellSet, nStarPerCell, policy):
798 """Create Principal Component basis 800 If a principal component analysis is requested, typically when using a delta function basis, 801 perform the PCA here and return a new basis list containing the new principal components. 806 a SpatialCellSet containing KernelCandidates, from which components are derived 808 the number of stars per cell to visit when doing the PCA 810 input policy controlling the single kernel visitor 815 number of KernelCandidates rejected during PCA loop 816 spatialBasisList : TYPE 817 basis list containing the principal shapes as Kernels 822 If the Eigenvalues sum to zero. 824 nComponents = self.
kConfig.numPrincipalComponents
825 imagePca = diffimLib.KernelPcaD()
826 importStarVisitor = diffimLib.KernelPcaVisitorF(imagePca)
827 kernelCellSet.visitCandidates(importStarVisitor, nStarPerCell)
828 if self.
kConfig.subtractMeanForPca:
829 importStarVisitor.subtractMean()
832 eigenValues = imagePca.getEigenValues()
833 pcaBasisList = importStarVisitor.getEigenKernels()
835 eSum = np.sum(eigenValues)
837 raise RuntimeError(
"Eigenvalues sum to zero")
838 for j
in range(len(eigenValues)):
839 log.log(
"TRACE5." + self.log.getName() +
"._solve", log.DEBUG,
840 "Eigenvalue %d : %f (%f)", j, eigenValues[j], eigenValues[j]/eSum)
842 nToUse =
min(nComponents, len(eigenValues))
844 for j
in range(nToUse):
846 kimage = afwImage.ImageD(pcaBasisList[j].getDimensions())
847 pcaBasisList[j].computeImage(kimage,
False)
848 if not (
True in np.isnan(kimage.getArray())):
849 trimBasisList.append(pcaBasisList[j])
852 spatialBasisList = diffimLib.renormalizeKernelList(trimBasisList)
855 singlekvPca = diffimLib.BuildSingleKernelVisitorF(spatialBasisList, policy)
856 singlekvPca.setSkipBuilt(
False)
857 kernelCellSet.visitCandidates(singlekvPca, nStarPerCell)
858 singlekvPca.setSkipBuilt(
True)
859 nRejectedPca = singlekvPca.getNRejected()
861 return nRejectedPca, spatialBasisList
863 def _buildCellSet(self, *args):
864 """Fill a SpatialCellSet with KernelCandidates for the Psf-matching process; 865 override in derived classes""" 869 def _solve(self, kernelCellSet, basisList, returnOnExcept=False):
870 """Solve for the PSF matching kernel 875 a SpatialCellSet to use in determining the matching kernel 876 (typically as provided by _buildCellSet) 878 list of Kernels to be used in the decomposition of the spatially varying kernel 879 (typically as provided by makeKernelBasisList) 880 returnOnExcept : `bool`, optional 881 if True then return (None, None) if an error occurs, else raise the exception 885 psfMatchingKernel : TYPE 887 backgroundModel : TYPE 888 differential background model 893 if unable to determine PSF matching kernel and returnOnExcept False 899 maxSpatialIterations = self.
kConfig.maxSpatialIterations
900 nStarPerCell = self.
kConfig.nStarPerCell
901 usePcaForSpatialKernel = self.
kConfig.usePcaForSpatialKernel
904 policy = pexConfig.makePolicy(self.
kConfig)
906 singlekv = diffimLib.BuildSingleKernelVisitorF(basisList, policy, self.
hMat)
908 singlekv = diffimLib.BuildSingleKernelVisitorF(basisList, policy)
911 ksv = diffimLib.KernelSumVisitorF(policy)
918 while (thisIteration < maxSpatialIterations):
922 while (nRejectedSkf != 0):
923 log.log(
"TRACE1." + self.log.getName() +
"._solve", log.DEBUG,
924 "Building single kernels...")
925 kernelCellSet.visitCandidates(singlekv, nStarPerCell)
926 nRejectedSkf = singlekv.getNRejected()
927 log.log(
"TRACE1." + self.log.getName() +
"._solve", log.DEBUG,
928 "Iteration %d, rejected %d candidates due to initial kernel fit",
929 thisIteration, nRejectedSkf)
933 ksv.setMode(diffimLib.KernelSumVisitorF.AGGREGATE)
934 kernelCellSet.visitCandidates(ksv, nStarPerCell)
935 ksv.processKsumDistribution()
936 ksv.setMode(diffimLib.KernelSumVisitorF.REJECT)
937 kernelCellSet.visitCandidates(ksv, nStarPerCell)
939 nRejectedKsum = ksv.getNRejected()
940 log.log(
"TRACE1." + self.log.getName() +
"._solve", log.DEBUG,
941 "Iteration %d, rejected %d candidates due to kernel sum",
942 thisIteration, nRejectedKsum)
945 if nRejectedKsum > 0:
954 if (usePcaForSpatialKernel):
955 log.log(
"TRACE0." + self.log.getName() +
"._solve", log.DEBUG,
956 "Building Pca basis")
958 nRejectedPca, spatialBasisList = self.
_createPcaBasis(kernelCellSet, nStarPerCell, policy)
959 log.log(
"TRACE1." + self.log.getName() +
"._solve", log.DEBUG,
960 "Iteration %d, rejected %d candidates due to Pca kernel fit",
961 thisIteration, nRejectedPca)
972 if (nRejectedPca > 0):
976 spatialBasisList = basisList
979 regionBBox = kernelCellSet.getBBox()
980 spatialkv = diffimLib.BuildSpatialKernelVisitorF(spatialBasisList, regionBBox, policy)
981 kernelCellSet.visitCandidates(spatialkv, nStarPerCell)
982 spatialkv.solveLinearEquation()
983 log.log(
"TRACE2." + self.log.getName() +
"._solve", log.DEBUG,
984 "Spatial kernel built with %d candidates", spatialkv.getNCandidates())
985 spatialKernel, spatialBackground = spatialkv.getSolutionPair()
988 assesskv = diffimLib.AssessSpatialKernelVisitorF(spatialKernel, spatialBackground, policy)
989 kernelCellSet.visitCandidates(assesskv, nStarPerCell)
990 nRejectedSpatial = assesskv.getNRejected()
991 nGoodSpatial = assesskv.getNGood()
992 log.log(
"TRACE1." + self.log.getName() +
"._solve", log.DEBUG,
993 "Iteration %d, rejected %d candidates due to spatial kernel fit",
994 thisIteration, nRejectedSpatial)
995 log.log(
"TRACE1." + self.log.getName() +
"._solve", log.DEBUG,
996 "%d candidates used in fit", nGoodSpatial)
999 if nGoodSpatial == 0
and nRejectedSpatial == 0:
1000 raise RuntimeError(
"No kernel candidates for spatial fit")
1002 if nRejectedSpatial == 0:
1010 if (nRejectedSpatial > 0)
and (thisIteration == maxSpatialIterations):
1011 log.log(
"TRACE1." + self.log.getName() +
"._solve", log.DEBUG,
"Final spatial fit")
1012 if (usePcaForSpatialKernel):
1013 nRejectedPca, spatialBasisList = self.
_createPcaBasis(kernelCellSet, nStarPerCell, policy)
1014 regionBBox = kernelCellSet.getBBox()
1015 spatialkv = diffimLib.BuildSpatialKernelVisitorF(spatialBasisList, regionBBox, policy)
1016 kernelCellSet.visitCandidates(spatialkv, nStarPerCell)
1017 spatialkv.solveLinearEquation()
1018 log.log(
"TRACE2." + self.log.getName() +
"._solve", log.DEBUG,
1019 "Spatial kernel built with %d candidates", spatialkv.getNCandidates())
1020 spatialKernel, spatialBackground = spatialkv.getSolutionPair()
1022 spatialSolution = spatialkv.getKernelSolution()
1024 except Exception
as e:
1025 self.log.
error(
"ERROR: Unable to calculate psf matching kernel")
1027 log.log(
"TRACE1." + self.log.getName() +
"._solve", log.DEBUG,
str(e))
1031 log.log(
"TRACE0." + self.log.getName() +
"._solve", log.DEBUG,
1032 "Total time to compute the spatial kernel : %.2f s", (t1 - t0))
1035 self.
_displayDebug(kernelCellSet, spatialKernel, spatialBackground)
1037 self.
_diagnostic(kernelCellSet, spatialSolution, spatialKernel, spatialBackground)
1039 return spatialSolution, spatialKernel, spatialBackground
1042 PsfMatch = PsfMatchTask
def _diagnostic(self, kernelCellSet, spatialSolution, spatialKernel, spatialBg)
def __init__(self, args, kwargs)
Fit spatial kernel using approximate fluxes for candidates, and solving a linear system of equations...
daf::base::PropertySet * set
def _createPcaBasis(self, kernelCellSet, nStarPerCell, policy)
def _displayDebug(self, kernelCellSet, spatialKernel, spatialBackground)