541 fitBackground=1, bgGradientOrder=1, maxSepInSigma=5.,
542 separateNegParams=True, verbose=False):
543 """Fit a dipole model to an input difference image.
545 Actually, fits the subimage bounded by the input source's
546 footprint) and optionally constrain the fit using the
547 pre-subtraction images posImage and negImage.
551 source : TODO: DM-17458
553 tol : float, optional
555 rel_weight : `float`, optional
557 fitBackground : `int`, optional
559 bgGradientOrder : `int`, optional
561 maxSepInSigma : `float`, optional
563 separateNegParams : `bool`, optional
565 verbose : `bool`, optional
570 result : `lmfit.MinimizerResult`
571 return `lmfit.MinimizerResult` object containing the fit
572 parameters and other information.
578 fp = source.getFootprint()
580 subim = afwImage.MaskedImageF(self.
diffim.getMaskedImage(), bbox=bbox, origin=afwImage.PARENT)
582 z = diArr = subim.image.array
585 weights = 1. / subim.variance.array
587 if rel_weight > 0.
and ((self.
posImage is not None)
or (self.
negImage is not None)):
589 negSubim = afwImage.MaskedImageF(self.
negImage.getMaskedImage(), bbox, origin=afwImage.PARENT)
591 posSubim = afwImage.MaskedImageF(self.
posImage.getMaskedImage(), bbox, origin=afwImage.PARENT)
593 posSubim = subim.clone()
596 negSubim = posSubim.clone()
599 z = np.append([z], [posSubim.image.array,
600 negSubim.image.array], axis=0)
602 weights = np.append([weights], [1. / posSubim.variance.array * rel_weight,
603 1. / negSubim.variance.array * rel_weight], axis=0)
611 b=None, x1=None, y1=None, xy=None, x2=None, y2=None,
612 bNeg=None, x1Neg=None, y1Neg=None, xyNeg=None, x2Neg=None, y2Neg=None,
614 """Generate dipole model with given parameters.
616 It simply defers to `modelObj.makeModel()`, where `modelObj` comes
617 out of `kwargs['modelObj']`.
619 modelObj = kwargs.pop(
'modelObj')
620 return modelObj.makeModel(x, flux, xcenPos, ycenPos, xcenNeg, ycenNeg, fluxNeg=fluxNeg,
621 b=b, x1=x1, y1=y1, xy=xy, x2=x2, y2=y2,
622 bNeg=bNeg, x1Neg=x1Neg, y1Neg=y1Neg, xyNeg=xyNeg,
623 x2Neg=x2Neg, y2Neg=y2Neg, **kwargs)
627 modelFunctor = dipoleModelFunctor
630 gmod = lmfit.Model(modelFunctor, verbose=verbose)
634 fpCentroid = np.array([fp.getCentroid().getX(), fp.getCentroid().getY()])
635 cenNeg = cenPos = fpCentroid
640 cenPos = pks[0].getF()
642 cenNeg = pks[-1].getF()
646 maxSep = self.
psfSigma * maxSepInSigma
649 if np.sum(np.sqrt((np.array(cenPos) - fpCentroid)**2.)) > maxSep:
651 if np.sum(np.sqrt((np.array(cenNeg) - fpCentroid)**2.)) > maxSep:
657 gmod.set_param_hint(
'xcenPos', value=cenPos[0],
658 min=cenPos[0]-maxSep, max=cenPos[0]+maxSep)
659 gmod.set_param_hint(
'ycenPos', value=cenPos[1],
660 min=cenPos[1]-maxSep, max=cenPos[1]+maxSep)
661 gmod.set_param_hint(
'xcenNeg', value=cenNeg[0],
662 min=cenNeg[0]-maxSep, max=cenNeg[0]+maxSep)
663 gmod.set_param_hint(
'ycenNeg', value=cenNeg[1],
664 min=cenNeg[1]-maxSep, max=cenNeg[1]+maxSep)
668 startingFlux = np.nansum(np.abs(diArr) - np.nanmedian(np.abs(diArr))) * 5.
669 posFlux = negFlux = startingFlux
672 gmod.set_param_hint(
'flux', value=posFlux, min=0.1)
674 if separateNegParams:
676 gmod.set_param_hint(
'fluxNeg', value=np.abs(negFlux), min=0.1)
684 bgParsPos = bgParsNeg = (0., 0., 0.)
685 if ((rel_weight > 0.)
and (fitBackground != 0)
and (bgGradientOrder >= 0)):
689 bgParsPos = bgParsNeg = dipoleModel.fitFootprintBackground(source, bgFitImage,
690 order=bgGradientOrder)
693 if fitBackground == 1:
694 in_x = dipoleModel._generateXYGrid(bbox)
695 pbg = dipoleModel.makeBackgroundModel(in_x, tuple(bgParsPos))
697 z[1, :] -= np.nanmedian(z[1, :])
698 posFlux = np.nansum(z[1, :])
699 gmod.set_param_hint(
'flux', value=posFlux*1.5, min=0.1)
701 if separateNegParams
and self.
negImage is not None:
702 bgParsNeg = dipoleModel.fitFootprintBackground(source, self.
negImage,
703 order=bgGradientOrder)
704 pbg = dipoleModel.makeBackgroundModel(in_x, tuple(bgParsNeg))
706 z[2, :] -= np.nanmedian(z[2, :])
707 if separateNegParams:
708 negFlux = np.nansum(z[2, :])
709 gmod.set_param_hint(
'fluxNeg', value=negFlux*1.5, min=0.1)
712 if fitBackground == 2:
713 if bgGradientOrder >= 0:
714 gmod.set_param_hint(
'b', value=bgParsPos[0])
715 if separateNegParams:
716 gmod.set_param_hint(
'bNeg', value=bgParsNeg[0])
717 if bgGradientOrder >= 1:
718 gmod.set_param_hint(
'x1', value=bgParsPos[1])
719 gmod.set_param_hint(
'y1', value=bgParsPos[2])
720 if separateNegParams:
721 gmod.set_param_hint(
'x1Neg', value=bgParsNeg[1])
722 gmod.set_param_hint(
'y1Neg', value=bgParsNeg[2])
723 if bgGradientOrder >= 2:
724 gmod.set_param_hint(
'xy', value=bgParsPos[3])
725 gmod.set_param_hint(
'x2', value=bgParsPos[4])
726 gmod.set_param_hint(
'y2', value=bgParsPos[5])
727 if separateNegParams:
728 gmod.set_param_hint(
'xyNeg', value=bgParsNeg[3])
729 gmod.set_param_hint(
'x2Neg', value=bgParsNeg[4])
730 gmod.set_param_hint(
'y2Neg', value=bgParsNeg[5])
732 y, x = np.mgrid[bbox.getBeginY():bbox.getEndY(), bbox.getBeginX():bbox.getEndX()]
733 in_x = np.array([x, y]).
astype(np.float64)
734 in_x[0, :] -= in_x[0, :].mean()
735 in_x[1, :] -= in_x[1, :].mean()
739 mask = np.ones_like(z, dtype=bool)
744 weights = mask.astype(np.float64)
745 if self.
posImage is not None and rel_weight > 0.:
746 weights = np.array([np.ones_like(diArr), np.ones_like(diArr)*rel_weight,
747 np.ones_like(diArr)*rel_weight])
754 nans = (np.isnan(z) | np.isnan(weights))
758 z[nans] = np.nanmedian(z)
766 with warnings.catch_warnings():
769 warnings.filterwarnings(
"ignore",
"The keyword argument .* does not match", UserWarning)
770 result = gmod.fit(z, weights=weights, x=in_x, max_nfev=250,
774 fit_kws={
'ftol': tol,
'xtol': tol,
'gtol': tol,
778 rel_weight=rel_weight,
780 modelObj=dipoleModel)
787 print(result.fit_report(show_correl=
False))
788 if separateNegParams:
789 print(result.ci_report())
794 fitBackground=1, maxSepInSigma=5., separateNegParams=True,
795 bgGradientOrder=1, verbose=False, display=False):
796 """Fit a dipole model to an input ``diaSource`` (wraps `fitDipoleImpl`).
798 Actually, fits the subimage bounded by the input source's
799 footprint) and optionally constrain the fit using the
800 pre-subtraction images self.posImage (science) and
801 self.negImage (template). Wraps the output into a
802 `pipeBase.Struct` named tuple after computing additional
803 statistics such as orientation and SNR.
807 source : `lsst.afw.table.SourceRecord`
808 Record containing the (merged) dipole source footprint detected on the diffim
809 tol : `float`, optional
810 Tolerance parameter for scipy.leastsq() optimization
811 rel_weight : `float`, optional
812 Weighting of posImage/negImage relative to the diffim in the fit
813 fitBackground : `int`, {0, 1, 2}, optional
814 How to fit linear background gradient in posImage/negImage
816 - 0: do not fit background at all
817 - 1 (default): pre-fit the background using linear least squares and then do not fit it
818 as part of the dipole fitting optimization
819 - 2: pre-fit the background using linear least squares (as in 1), and use the parameter
820 estimates from that fit as starting parameters for an integrated "re-fit" of the
821 background as part of the overall dipole fitting optimization.
822 maxSepInSigma : `float`, optional
823 Allowed window of centroid parameters relative to peak in input source footprint
824 separateNegParams : `bool`, optional
825 Fit separate parameters to the flux and background gradient in
826 bgGradientOrder : `int`, {0, 1, 2}, optional
827 Desired polynomial order of background gradient
828 verbose: `bool`, optional
831 Display input data, best fit model(s) and residuals in a matplotlib window.
836 `pipeBase.Struct` object containing the fit parameters and other information.
839 `lmfit.MinimizerResult` object for debugging and error estimation, etc.
843 Parameter `fitBackground` has three options, thus it is an integer:
848 source, tol=tol, rel_weight=rel_weight, fitBackground=fitBackground,
849 maxSepInSigma=maxSepInSigma, separateNegParams=separateNegParams,
850 bgGradientOrder=bgGradientOrder, verbose=verbose)
854 fp = source.getFootprint()
857 fitParams = fitResult.best_values
858 if fitParams[
'flux'] <= 1.:
859 out = Struct(posCentroidX=np.nan, posCentroidY=np.nan,
860 negCentroidX=np.nan, negCentroidY=np.nan,
861 posFlux=np.nan, negFlux=np.nan, posFluxErr=np.nan, negFluxErr=np.nan,
862 centroidX=np.nan, centroidY=np.nan, orientation=np.nan,
863 signalToNoise=np.nan, chi2=np.nan, redChi2=np.nan)
864 return out, fitResult
866 centroid = ((fitParams[
'xcenPos'] + fitParams[
'xcenNeg']) / 2.,
867 (fitParams[
'ycenPos'] + fitParams[
'ycenNeg']) / 2.)
868 dx, dy = fitParams[
'xcenPos'] - fitParams[
'xcenNeg'], fitParams[
'ycenPos'] - fitParams[
'ycenNeg']
869 angle = np.arctan2(dy, dx) / np.pi * 180.
874 return np.sqrt(np.nansum(exposure[footprint.getBBox(), afwImage.PARENT].variance.array))
876 fluxVal = fluxVar = fitParams[
'flux']
877 fluxErr = fluxErrNeg = fitResult.params[
'flux'].stderr
883 fluxValNeg, fluxVarNeg = fluxVal, fluxVar
884 if separateNegParams:
885 fluxValNeg = fitParams[
'fluxNeg']
886 fluxErrNeg = fitResult.params[
'fluxNeg'].stderr
891 signalToNoise = np.sqrt((fluxVal/fluxVar)**2 + (fluxValNeg/fluxVarNeg)**2)
892 except ZeroDivisionError:
893 signalToNoise = np.nan
895 out = Struct(posCentroidX=fitParams[
'xcenPos'], posCentroidY=fitParams[
'ycenPos'],
896 negCentroidX=fitParams[
'xcenNeg'], negCentroidY=fitParams[
'ycenNeg'],
897 posFlux=fluxVal, negFlux=-fluxValNeg, posFluxErr=fluxErr, negFluxErr=fluxErrNeg,
898 centroidX=centroid[0], centroidY=centroid[1], orientation=angle,
899 signalToNoise=signalToNoise, chi2=fitResult.chisqr, redChi2=fitResult.redchi)
902 return out, fitResult