23 import matplotlib.pyplot
as plt
24 from collections
import Counter
29 from .utils
import (fitLeastSq, fitBootstrap, funcPolynomial, funcAstier)
30 from scipy.optimize
import least_squares
34 from .astierCovPtcUtils
import (fftSize, CovFft, computeCovDirect, fitData)
35 from .linearity
import LinearitySolveTask
37 from lsst.pipe.tasks.getRepositoryData
import DataRefListRunner
39 __all__ = [
'MeasurePhotonTransferCurveTask',
40 'MeasurePhotonTransferCurveTaskConfig',
41 'PhotonTransferCurveDataset']
45 """Config class for photon transfer curve measurement task"""
46 ccdKey = pexConfig.Field(
48 doc=
"The key by which to pull a detector from a dataId, e.g. 'ccd' or 'detector'.",
51 ptcFitType = pexConfig.ChoiceField(
53 doc=
"Fit PTC to approximation in Astier+19 (Equation 16) or to a polynomial.",
56 "POLYNOMIAL":
"n-degree polynomial (use 'polynomialFitDegree' to set 'n').",
57 "EXPAPPROXIMATION":
"Approximation in Astier+19 (Eq. 16).",
58 "FULLCOVARIANCE":
"Full covariances model in Astier+19 (Eq. 20)"
61 sigmaClipFullFitCovariancesAstier = pexConfig.Field(
63 doc=
"sigma clip for full model fit for FULLCOVARIANCE ptcFitType ",
66 maxIterFullFitCovariancesAstier = pexConfig.Field(
68 doc=
"Maximum number of iterations in full model fit for FULLCOVARIANCE ptcFitType",
71 maximumRangeCovariancesAstier = pexConfig.Field(
73 doc=
"Maximum range of covariances as in Astier+19",
76 covAstierRealSpace = pexConfig.Field(
78 doc=
"Calculate covariances in real space or via FFT? (see appendix A of Astier+19).",
81 polynomialFitDegree = pexConfig.Field(
83 doc=
"Degree of polynomial to fit the PTC, when 'ptcFitType'=POLYNOMIAL.",
86 linearity = pexConfig.ConfigurableField(
87 target=LinearitySolveTask,
88 doc=
"Task to solve the linearity."
91 doCreateLinearizer = pexConfig.Field(
93 doc=
"Calculate non-linearity and persist linearizer?",
97 binSize = pexConfig.Field(
99 doc=
"Bin the image by this factor in both dimensions.",
102 minMeanSignal = pexConfig.Field(
104 doc=
"Minimum value (inclusive) of mean signal (in DN) above which to consider.",
107 maxMeanSignal = pexConfig.Field(
109 doc=
"Maximum value (inclusive) of mean signal (in DN) below which to consider.",
112 initialNonLinearityExclusionThresholdPositive = pexConfig.RangeField(
114 doc=
"Initially exclude data points with a variance that are more than a factor of this from being"
115 " linear in the positive direction, from the PTC fit. Note that these points will also be"
116 " excluded from the non-linearity fit. This is done before the iterative outlier rejection,"
117 " to allow an accurate determination of the sigmas for said iterative fit.",
122 initialNonLinearityExclusionThresholdNegative = pexConfig.RangeField(
124 doc=
"Initially exclude data points with a variance that are more than a factor of this from being"
125 " linear in the negative direction, from the PTC fit. Note that these points will also be"
126 " excluded from the non-linearity fit. This is done before the iterative outlier rejection,"
127 " to allow an accurate determination of the sigmas for said iterative fit.",
132 sigmaCutPtcOutliers = pexConfig.Field(
134 doc=
"Sigma cut for outlier rejection in PTC.",
137 maskNameList = pexConfig.ListField(
139 doc=
"Mask list to exclude from statistics calculations.",
140 default=[
'SUSPECT',
'BAD',
'NO_DATA'],
142 nSigmaClipPtc = pexConfig.Field(
144 doc=
"Sigma cut for afwMath.StatisticsControl()",
147 nIterSigmaClipPtc = pexConfig.Field(
149 doc=
"Number of sigma-clipping iterations for afwMath.StatisticsControl()",
152 maxIterationsPtcOutliers = pexConfig.Field(
154 doc=
"Maximum number of iterations for outlier rejection in PTC.",
157 doFitBootstrap = pexConfig.Field(
159 doc=
"Use bootstrap for the PTC fit parameters and errors?.",
162 instrumentName = pexConfig.Field(
164 doc=
"Instrument name.",
170 """A simple class to hold the output data from the PTC task.
172 The dataset is made up of a dictionary for each item, keyed by the
173 amplifiers' names, which much be supplied at construction time.
175 New items cannot be added to the class to save accidentally saving to the
176 wrong property, and the class can be frozen if desired.
178 inputExpIdPairs records the exposures used to produce the data.
179 When fitPtc() or fitCovariancesAstier() is run, a mask is built up, which is by definition
180 always the same length as inputExpIdPairs, rawExpTimes, rawMeans
181 and rawVars, and is a list of bools, which are incrementally set to False
182 as points are discarded from the fits.
184 PTC fit parameters for polynomials are stored in a list in ascending order
185 of polynomial term, i.e. par[0]*x^0 + par[1]*x + par[2]*x^2 etc
186 with the length of the list corresponding to the order of the polynomial
192 List with the names of the amplifiers of the detector at hand.
195 Type of model fitted to the PTC: "POLYNOMIAL", "EXPAPPROXIMATION", or "FULLCOVARIANCE".
199 `lsst.cp.pipe.ptc.PhotonTransferCurveDataset`
200 Output dataset from MeasurePhotonTransferCurveTask.
207 self.__dict__[
"ptcFitType"] = ptcFitType
208 self.__dict__[
"ampNames"] = ampNames
209 self.__dict__[
"badAmps"] = []
214 self.__dict__[
"inputExpIdPairs"] = {ampName: []
for ampName
in ampNames}
215 self.__dict__[
"expIdMask"] = {ampName: []
for ampName
in ampNames}
216 self.__dict__[
"rawExpTimes"] = {ampName: []
for ampName
in ampNames}
217 self.__dict__[
"rawMeans"] = {ampName: []
for ampName
in ampNames}
218 self.__dict__[
"rawVars"] = {ampName: []
for ampName
in ampNames}
221 self.__dict__[
"gain"] = {ampName: -1.
for ampName
in ampNames}
222 self.__dict__[
"gainErr"] = {ampName: -1.
for ampName
in ampNames}
223 self.__dict__[
"noise"] = {ampName: -1.
for ampName
in ampNames}
224 self.__dict__[
"noiseErr"] = {ampName: -1.
for ampName
in ampNames}
228 self.__dict__[
"ptcFitPars"] = {ampName: []
for ampName
in ampNames}
229 self.__dict__[
"ptcFitParsError"] = {ampName: []
for ampName
in ampNames}
230 self.__dict__[
"ptcFitReducedChiSquared"] = {ampName: []
for ampName
in ampNames}
237 self.__dict__[
"covariancesTuple"] = {ampName: []
for ampName
in ampNames}
238 self.__dict__[
"covariancesFitsWithNoB"] = {ampName: []
for ampName
in ampNames}
239 self.__dict__[
"covariancesFits"] = {ampName: []
for ampName
in ampNames}
240 self.__dict__[
"aMatrix"] = {ampName: []
for ampName
in ampNames}
241 self.__dict__[
"bMatrix"] = {ampName: []
for ampName
in ampNames}
244 self.__dict__[
"finalVars"] = {ampName: []
for ampName
in ampNames}
245 self.__dict__[
"finalModelVars"] = {ampName: []
for ampName
in ampNames}
246 self.__dict__[
"finalMeans"] = {ampName: []
for ampName
in ampNames}
249 """Protect class attributes"""
250 if attribute
not in self.__dict__:
251 raise AttributeError(f
"{attribute} is not already a member of PhotonTransferCurveDataset, which"
252 " does not support setting of new attributes.")
254 self.__dict__[attribute] = value
257 """Get the exposures used, i.e. not discarded, for a given amp.
259 If no mask has been created yet, all exposures are returned.
261 if len(self.expIdMask[ampName]) == 0:
262 return self.inputExpIdPairs[ampName]
265 assert len(self.expIdMask[ampName]) == len(self.inputExpIdPairs[ampName])
267 pairs = self.inputExpIdPairs[ampName]
268 mask = self.expIdMask[ampName]
270 return [(exp1, exp2)
for ((exp1, exp2), m)
in zip(pairs, mask)
if bool(m)
is True]
273 return [amp
for amp
in self.ampNames
if amp
not in self.badAmps]
277 """A class to calculate, fit, and plot a PTC from a set of flat pairs.
279 The Photon Transfer Curve (var(signal) vs mean(signal)) is a standard tool
280 used in astronomical detectors characterization (e.g., Janesick 2001,
281 Janesick 2007). If ptcFitType is "EXPAPPROXIMATION" or "POLYNOMIAL", this task calculates the
282 PTC from a series of pairs of flat-field images; each pair taken at identical exposure
283 times. The difference image of each pair is formed to eliminate fixed pattern noise,
284 and then the variance of the difference image and the mean of the average image
285 are used to produce the PTC. An n-degree polynomial or the approximation in Equation
286 16 of Astier+19 ("The Shape of the Photon Transfer Curve of CCD sensors",
287 arXiv:1905.08677) can be fitted to the PTC curve. These models include
288 parameters such as the gain (e/DN) and readout noise.
290 Linearizers to correct for signal-chain non-linearity are also calculated.
291 The `Linearizer` class, in general, can support per-amp linearizers, but in this
292 task this is not supported.
294 If ptcFitType is "FULLCOVARIANCE", the covariances of the difference images are calculated via the
295 DFT methods described in Astier+19 and the variances for the PTC are given by the cov[0,0] elements
296 at each signal level. The full model in Equation 20 of Astier+19 is fit to the PTC to get the gain
303 Positional arguments passed to the Task constructor. None used at this
306 Keyword arguments passed on to the Task constructor. None used at this
311 RunnerClass = DataRefListRunner
312 ConfigClass = MeasurePhotonTransferCurveTaskConfig
313 _DefaultName =
"measurePhotonTransferCurve"
316 pipeBase.CmdLineTask.__init__(self, *args, **kwargs)
317 self.makeSubtask(
"linearity")
318 plt.interactive(
False)
319 self.config.validate()
324 """Run the Photon Transfer Curve (PTC) measurement task.
326 For a dataRef (which is each detector here),
327 and given a list of exposure pairs (postISR) at different exposure times,
332 dataRefList : `list` [`lsst.daf.peristence.ButlerDataRef`]
333 Data references for exposures for detectors to process.
335 if len(dataRefList) < 2:
336 raise RuntimeError(
"Insufficient inputs to combine.")
339 dataRef = dataRefList[0]
341 detNum = dataRef.dataId[self.config.ccdKey]
342 camera = dataRef.get(
'camera')
343 detector = camera[dataRef.dataId[self.config.ccdKey]]
345 amps = detector.getAmplifiers()
346 ampNames = [amp.getName()
for amp
in amps]
352 for (exp1, exp2)
in expPairs.values():
353 id1 = exp1.getInfo().getVisitInfo().getExposureId()
354 id2 = exp2.getInfo().getVisitInfo().getExposureId()
355 expIds.append((id1, id2))
356 self.log.info(f
"Measuring PTC using {expIds} exposures for detector {detector.getId()}")
359 for expTime, (exp1, exp2)
in expPairs.items():
360 expId1 = exp1.getInfo().getVisitInfo().getExposureId()
361 expId2 = exp2.getInfo().getVisitInfo().getExposureId()
364 for ampNumber, amp
in enumerate(detector):
365 ampName = amp.getName()
367 doRealSpace = self.config.covAstierRealSpace
368 muDiff, varDiff, covAstier = self.
measureMeanVarCov(exp1, exp2, region=amp.getBBox(),
369 covAstierRealSpace=doRealSpace)
370 if np.isnan(muDiff)
or np.isnan(varDiff)
or (covAstier
is None):
371 msg = (f
"NaN mean or var, or None cov in amp {ampNumber} in exposure pair {expId1},"
372 f
" {expId2} of detector {detNum}.")
376 tags = [
'mu',
'i',
'j',
'var',
'cov',
'npix',
'ext',
'expTime',
'ampName']
377 if (muDiff <= self.config.minMeanSignal)
or (muDiff >= self.config.maxMeanSignal):
379 datasetPtc.rawExpTimes[ampName].append(expTime)
380 datasetPtc.rawMeans[ampName].append(muDiff)
381 datasetPtc.rawVars[ampName].append(varDiff)
382 datasetPtc.inputExpIdPairs[ampName].append((expId1, expId2))
384 tupleRows += [(muDiff, ) + covRow + (ampNumber, expTime, ampName)
for covRow
in covAstier]
385 if nAmpsNan == len(ampNames):
386 msg = f
"NaN mean in all amps of exposure pair {expId1}, {expId2} of detector {detNum}."
390 tupleRecords += tupleRows
391 covariancesWithTags = np.core.records.fromrecords(tupleRecords, names=allTags)
393 if self.config.ptcFitType
in [
"FULLCOVARIANCE", ]:
396 elif self.config.ptcFitType
in [
"EXPAPPROXIMATION",
"POLYNOMIAL"]:
399 datasetPtc = self.
fitPtc(datasetPtc, self.config.ptcFitType)
402 if self.config.doCreateLinearizer:
408 dimensions = {
'camera': camera.getName(),
'detector': detector.getId()}
409 linearityResults = self.linearity.run(datasetPtc, camera, dimensions)
410 linearizer = linearityResults.outputLinearizer
412 butler = dataRef.getButler()
413 self.log.info(
"Writing linearizer:")
415 detName = detector.getName()
416 now = datetime.datetime.utcnow()
417 calibDate = now.strftime(
"%Y-%m-%d")
419 butler.put(linearizer, datasetType=
'Linearizer', dataId={
'detector': detNum,
420 'detectorName': detName,
'calibDate': calibDate})
421 self.log.info(f
"Writing PTC data.")
422 dataRef.put(datasetPtc, datasetType=
"photonTransferCurveDataset")
424 return pipeBase.Struct(exitStatus=0)
427 """Produce a list of flat pairs indexed by exposure time.
431 dataRefList : `list` [`lsst.daf.peristence.ButlerDataRef`]
432 Data references for exposures for detectors to process.
436 flatPairs : `dict` [`float`, `lsst.afw.image.exposure.exposure.ExposureF`]
437 Dictionary that groups flat-field exposures that have the same exposure time (seconds).
441 We use the difference of one pair of flat-field images taken at the same exposure time when
442 calculating the PTC to reduce Fixed Pattern Noise. If there are > 2 flat-field images with the
443 same exposure time, the first two are kept and the rest discarded.
448 for dataRef
in dataRefList:
450 tempFlat = dataRef.get(
"postISRCCD")
452 self.log.warn(f
"postISR exposure could not be retrieved. Ignoring flat.")
454 expDate = tempFlat.getInfo().getVisitInfo().getDate().get()
455 expDict.setdefault(expDate, tempFlat)
456 sortedExps = {k: expDict[k]
for k
in sorted(expDict)}
459 for exp
in sortedExps:
460 tempFlat = sortedExps[exp]
461 expTime = tempFlat.getInfo().getVisitInfo().getExposureTime()
462 listAtExpTime = flatPairs.setdefault(expTime, [])
463 if len(listAtExpTime) < 2:
464 listAtExpTime.append(tempFlat)
465 if len(listAtExpTime) > 2:
466 self.log.warn(
"More than 2 exposures found at expTime {expTime}. Dropping exposures "
467 f
"{listAtExpTime[2:]}.")
469 for (key, value)
in flatPairs.items():
472 self.log.warn(
"Only one exposure found at expTime {key}. Dropping exposure {value}.")
476 """Fit measured flat covariances to full model in Astier+19.
480 dataset : `lsst.cp.pipe.ptc.PhotonTransferCurveDataset`
481 The dataset containing information such as the means, variances and exposure times.
483 covariancesWithTagsArray : `numpy.recarray`
484 Tuple with at least (mu, cov, var, i, j, npix), where:
485 mu : 0.5*(m1 + m2), where:
486 mu1: mean value of flat1
487 mu2: mean value of flat2
488 cov: covariance value at lag(i, j)
489 var: variance(covariance value at lag(0, 0))
492 npix: number of pixels used for covariance calculation.
496 dataset: `lsst.cp.pipe.ptc.PhotonTransferCurveDataset`
497 This is the same dataset as the input paramter, however, it has been modified
498 to include information such as the fit vectors and the fit parameters. See
499 the class `PhotonTransferCurveDatase`.
502 covFits, covFitsNoB =
fitData(covariancesWithTagsArray, maxMu=self.config.maxMeanSignal,
503 r=self.config.maximumRangeCovariancesAstier,
504 nSigmaFullFit=self.config.sigmaClipFullFitCovariancesAstier,
505 maxIterFullFit=self.config.maxIterFullFitCovariancesAstier)
507 dataset.covariancesTuple = covariancesWithTagsArray
508 dataset.covariancesFits = covFits
509 dataset.covariancesFitsWithNoB = covFitsNoB
515 """Get output data for PhotonTransferCurveCovAstierDataset from CovFit objects.
519 dataset : `lsst.cp.pipe.ptc.PhotonTransferCurveDataset`
520 The dataset containing information such as the means, variances and exposure times.
523 Dictionary of CovFit objects, with amp names as keys.
527 dataset : `lsst.cp.pipe.ptc.PhotonTransferCurveDataset`
528 This is the same dataset as the input paramter, however, it has been modified
529 to include extra information such as the mask 1D array, gains, reoudout noise, measured signal,
530 measured variance, modeled variance, a, and b coefficient matrices (see Astier+19) per amplifier.
531 See the class `PhotonTransferCurveDatase`.
534 for i, amp
in enumerate(covFits):
536 (meanVecFinal, varVecFinal, varVecModel,
537 wc, varMask) = fit.getFitData(0, 0, divideByMu=
False, returnMasked=
True)
539 dataset.expIdMask[amp] = varMask
540 dataset.gain[amp] = gain
541 dataset.gainErr[amp] = fit.getGainErr()
542 dataset.noise[amp] = np.sqrt(np.fabs(fit.getRon()))
543 dataset.noiseErr[amp] = fit.getRonErr()
544 dataset.finalVars[amp].append(varVecFinal/(gain**2))
545 dataset.finalModelVars[amp].append(varVecModel/(gain**2))
546 dataset.finalMeans[amp].append(meanVecFinal/gain)
547 dataset.aMatrix[amp].append(fit.getA())
548 dataset.bMatrix[amp].append(fit.getB())
553 """Calculate the mean of each of two exposures and the variance and covariance of their difference.
555 The variance is calculated via afwMath, and the covariance via the methods in Astier+19 (appendix A).
556 In theory, var = covariance[0,0]. This should be validated, and in the future, we may decide to just
557 keep one (covariance).
561 exposure1 : `lsst.afw.image.exposure.exposure.ExposureF`
562 First exposure of flat field pair.
564 exposure2 : `lsst.afw.image.exposure.exposure.ExposureF`
565 Second exposure of flat field pair.
567 region : `lsst.geom.Box2I`, optional
568 Region of each exposure where to perform the calculations (e.g, an amplifier).
570 covAstierRealSpace : `bool`, optional
571 Should the covariannces in Astier+19 be calculated in real space or via FFT?
572 See Appendix A of Astier+19.
576 mu : `float` or `NaN`
577 0.5*(mu1 + mu2), where mu1, and mu2 are the clipped means of the regions in
578 both exposures. If either mu1 or m2 are NaN's, the returned value is NaN.
580 varDiff : `float` or `NaN`
581 Half of the clipped variance of the difference of the regions inthe two input
582 exposures. If either mu1 or m2 are NaN's, the returned value is NaN.
584 covDiffAstier : `list` or `NaN`
585 List with tuples of the form (dx, dy, var, cov, npix), where:
591 Variance at (dx, dy).
593 Covariance at (dx, dy).
595 Number of pixel pairs used to evaluate var and cov.
596 If either mu1 or m2 are NaN's, the returned value is NaN.
599 if region
is not None:
600 im1Area = exposure1.maskedImage[region]
601 im2Area = exposure2.maskedImage[region]
603 im1Area = exposure1.maskedImage
604 im2Area = exposure2.maskedImage
606 if self.config.binSize > 1:
607 im1Area = afwMath.binImage(im1Area, self.config.binSize)
608 im2Area = afwMath.binImage(im2Area, self.config.binSize)
610 im1MaskVal = exposure1.getMask().getPlaneBitMask(self.config.maskNameList)
611 im1StatsCtrl = afwMath.StatisticsControl(self.config.nSigmaClipPtc,
612 self.config.nIterSigmaClipPtc,
614 im1StatsCtrl.setNanSafe(
True)
615 im1StatsCtrl.setAndMask(im1MaskVal)
617 im2MaskVal = exposure2.getMask().getPlaneBitMask(self.config.maskNameList)
618 im2StatsCtrl = afwMath.StatisticsControl(self.config.nSigmaClipPtc,
619 self.config.nIterSigmaClipPtc,
621 im2StatsCtrl.setNanSafe(
True)
622 im2StatsCtrl.setAndMask(im2MaskVal)
625 mu1 = afwMath.makeStatistics(im1Area, afwMath.MEANCLIP, im1StatsCtrl).getValue()
626 mu2 = afwMath.makeStatistics(im2Area, afwMath.MEANCLIP, im2StatsCtrl).getValue()
627 if np.isnan(mu1)
or np.isnan(mu2):
628 return np.nan, np.nan,
None
633 temp = im2Area.clone()
635 diffIm = im1Area.clone()
640 diffImMaskVal = diffIm.getMask().getPlaneBitMask(self.config.maskNameList)
641 diffImStatsCtrl = afwMath.StatisticsControl(self.config.nSigmaClipPtc,
642 self.config.nIterSigmaClipPtc,
644 diffImStatsCtrl.setNanSafe(
True)
645 diffImStatsCtrl.setAndMask(diffImMaskVal)
647 varDiff = 0.5*(afwMath.makeStatistics(diffIm, afwMath.VARIANCECLIP, diffImStatsCtrl).getValue())
650 w1 = np.where(im1Area.getMask().getArray() == 0, 1, 0)
651 w2 = np.where(im2Area.getMask().getArray() == 0, 1, 0)
654 wDiff = np.where(diffIm.getMask().getArray() == 0, 1, 0)
657 maxRangeCov = self.config.maximumRangeCovariancesAstier
658 if covAstierRealSpace:
659 covDiffAstier =
computeCovDirect(diffIm.getImage().getArray(), w, maxRangeCov)
661 shapeDiff = diffIm.getImage().getArray().shape
662 fftShape = (
fftSize(shapeDiff[0] + maxRangeCov),
fftSize(shapeDiff[1]+maxRangeCov))
663 c =
CovFft(diffIm.getImage().getArray(), w, fftShape, maxRangeCov)
664 covDiffAstier = c.reportCovFft(maxRangeCov)
666 return mu, varDiff, covDiffAstier
669 """Compute covariances of diffImage in real space.
671 For lags larger than ~25, it is slower than the FFT way.
672 Taken from https://github.com/PierreAstier/bfptc/
676 diffImage : `numpy.array`
677 Image to compute the covariance of.
679 weightImage : `numpy.array`
680 Weight image of diffImage (1's and 0's for good and bad pixels, respectively).
683 Last index of the covariance to be computed.
688 List with tuples of the form (dx, dy, var, cov, npix), where:
694 Variance at (dx, dy).
696 Covariance at (dx, dy).
698 Number of pixel pairs used to evaluate var and cov.
703 for dy
in range(maxRange + 1):
704 for dx
in range(0, maxRange + 1):
707 cov2, nPix2 = self.
covDirectValue(diffImage, weightImage, dx, -dy)
708 cov = 0.5*(cov1 + cov2)
712 if (dx == 0
and dy == 0):
714 outList.append((dx, dy, var, cov, nPix))
719 """Compute covariances of diffImage in real space at lag (dx, dy).
721 Taken from https://github.com/PierreAstier/bfptc/ (c.f., appendix of Astier+19).
725 diffImage : `numpy.array`
726 Image to compute the covariance of.
728 weightImage : `numpy.array`
729 Weight image of diffImage (1's and 0's for good and bad pixels, respectively).
740 Covariance at (dx, dy)
743 Number of pixel pairs used to evaluate var and cov.
745 (nCols, nRows) = diffImage.shape
749 (dx, dy) = (-dx, -dy)
753 im1 = diffImage[dy:, dx:]
754 w1 = weightImage[dy:, dx:]
755 im2 = diffImage[:nCols - dy, :nRows - dx]
756 w2 = weightImage[:nCols - dy, :nRows - dx]
758 im1 = diffImage[:nCols + dy, dx:]
759 w1 = weightImage[:nCols + dy, dx:]
760 im2 = diffImage[-dy:, :nRows - dx]
761 w2 = weightImage[-dy:, :nRows - dx]
767 s1 = im1TimesW.sum()/nPix
768 s2 = (im2*wAll).sum()/nPix
769 p = (im1TimesW*im2).sum()/nPix
775 def _initialParsForPolynomial(order):
777 pars = np.zeros(order, dtype=np.float)
784 def _boundsForPolynomial(initialPars):
785 lowers = [np.NINF
for p
in initialPars]
786 uppers = [np.inf
for p
in initialPars]
788 return (lowers, uppers)
791 def _boundsForAstier(initialPars):
792 lowers = [np.NINF
for p
in initialPars]
793 uppers = [np.inf
for p
in initialPars]
794 return (lowers, uppers)
797 def _getInitialGoodPoints(means, variances, maxDeviationPositive, maxDeviationNegative):
798 """Return a boolean array to mask bad points.
800 A linear function has a constant ratio, so find the median
801 value of the ratios, and exclude the points that deviate
802 from that by more than a factor of maxDeviationPositive/negative.
803 Asymmetric deviations are supported as we expect the PTC to turn
804 down as the flux increases, but sometimes it anomalously turns
805 upwards just before turning over, which ruins the fits, so it
806 is wise to be stricter about restricting positive outliers than
809 Too high and points that are so bad that fit will fail will be included
810 Too low and the non-linear points will be excluded, biasing the NL fit."""
811 ratios = [b/a
for (a, b)
in zip(means, variances)]
812 medianRatio = np.median(ratios)
813 ratioDeviations = [(r/medianRatio)-1
for r
in ratios]
816 maxDeviationPositive = abs(maxDeviationPositive)
817 maxDeviationNegative = -1. * abs(maxDeviationNegative)
819 goodPoints = np.array([
True if (r < maxDeviationPositive
and r > maxDeviationNegative)
820 else False for r
in ratioDeviations])
823 def _makeZeroSafe(self, array, warn=True, substituteValue=1e-9):
825 nBad = Counter(array)[0]
830 msg = f
"Found {nBad} zeros in array at elements {[x for x in np.where(array==0)[0]]}"
833 array[array == 0] = substituteValue
837 """Fit the photon transfer curve to a polynimial or to Astier+19 approximation.
839 Fit the photon transfer curve with either a polynomial of the order
840 specified in the task config, or using the Astier approximation.
842 Sigma clipping is performed iteratively for the fit, as well as an
843 initial clipping of data points that are more than
844 config.initialNonLinearityExclusionThreshold away from lying on a
845 straight line. This other step is necessary because the photon transfer
846 curve turns over catastrophically at very high flux (because saturation
847 drops the variance to ~0) and these far outliers cause the initial fit
848 to fail, meaning the sigma cannot be calculated to perform the
853 dataset : `lsst.cp.pipe.ptc.PhotonTransferCurveDataset`
854 The dataset containing the means, variances and exposure times
857 Fit a 'POLYNOMIAL' (degree: 'polynomialFitDegree') or
858 'EXPAPPROXIMATION' (Eq. 16 of Astier+19) to the PTC
862 dataset: `lsst.cp.pipe.ptc.PhotonTransferCurveDataset`
863 This is the same dataset as the input paramter, however, it has been modified
864 to include information such as the fit vectors and the fit parameters. See
865 the class `PhotonTransferCurveDatase`.
868 def errFunc(p, x, y):
869 return ptcFunc(p, x) - y
871 sigmaCutPtcOutliers = self.config.sigmaCutPtcOutliers
872 maxIterationsPtcOutliers = self.config.maxIterationsPtcOutliers
874 for i, ampName
in enumerate(dataset.ampNames):
875 timeVecOriginal = np.array(dataset.rawExpTimes[ampName])
876 meanVecOriginal = np.array(dataset.rawMeans[ampName])
877 varVecOriginal = np.array(dataset.rawVars[ampName])
880 mask = ((meanVecOriginal >= self.config.minMeanSignal) &
881 (meanVecOriginal <= self.config.maxMeanSignal))
884 self.config.initialNonLinearityExclusionThresholdPositive,
885 self.config.initialNonLinearityExclusionThresholdNegative)
886 if not (mask.any()
and goodPoints.any()):
887 msg = (f
"\nSERIOUS: All points in either mask: {mask} or goodPoints: {goodPoints} are bad."
888 f
"Setting {ampName} to BAD.")
892 dataset.badAmps.append(ampName)
893 dataset.gain[ampName] = np.nan
894 dataset.gainErr[ampName] = np.nan
895 dataset.noise[ampName] = np.nan
896 dataset.noiseErr[ampName] = np.nan
897 dataset.ptcFitPars[ampName] = np.nan
898 dataset.ptcFitParsError[ampName] = np.nan
899 dataset.ptcFitReducedChiSquared[ampName] = np.nan
902 mask = mask & goodPoints
904 if ptcFitType ==
'EXPAPPROXIMATION':
906 parsIniPtc = [-1e-9, 1.0, 10.]
908 if ptcFitType ==
'POLYNOMIAL':
909 ptcFunc = funcPolynomial
915 while count <= maxIterationsPtcOutliers:
919 meanTempVec = meanVecOriginal[mask]
920 varTempVec = varVecOriginal[mask]
921 res = least_squares(errFunc, parsIniPtc, bounds=bounds, args=(meanTempVec, varTempVec))
927 sigResids = (varVecOriginal - ptcFunc(pars, meanVecOriginal))/np.sqrt(varVecOriginal)
928 newMask = np.array([
True if np.abs(r) < sigmaCutPtcOutliers
else False for r
in sigResids])
929 mask = mask & newMask
930 if not (mask.any()
and newMask.any()):
931 msg = (f
"\nSERIOUS: All points in either mask: {mask} or newMask: {newMask} are bad. "
932 f
"Setting {ampName} to BAD.")
936 dataset.badAmps.append(ampName)
937 dataset.gain[ampName] = np.nan
938 dataset.gainErr[ampName] = np.nan
939 dataset.noise[ampName] = np.nan
940 dataset.noiseErr[ampName] = np.nan
941 dataset.ptcFitPars[ampName] = np.nan
942 dataset.ptcFitParsError[ampName] = np.nan
943 dataset.ptcFitReducedChiSquared[ampName] = np.nan
945 nDroppedTotal = Counter(mask)[
False]
946 self.log.debug(f
"Iteration {count}: discarded {nDroppedTotal} points in total for {ampName}")
949 assert (len(mask) == len(timeVecOriginal) == len(meanVecOriginal) == len(varVecOriginal))
951 if not (mask.any()
and newMask.any()):
953 dataset.expIdMask[ampName] = mask
955 meanVecFinal = meanVecOriginal[mask]
956 varVecFinal = varVecOriginal[mask]
958 if Counter(mask)[
False] > 0:
959 self.log.info((f
"Number of points discarded in PTC of amplifier {ampName}:" +
960 f
" {Counter(mask)[False]} out of {len(meanVecOriginal)}"))
962 if (len(meanVecFinal) < len(parsIniPtc)):
963 msg = (f
"\nSERIOUS: Not enough data points ({len(meanVecFinal)}) compared to the number of"
964 f
"parameters of the PTC model({len(parsIniPtc)}). Setting {ampName} to BAD.")
968 dataset.badAmps.append(ampName)
969 dataset.gain[ampName] = np.nan
970 dataset.gainErr[ampName] = np.nan
971 dataset.noise[ampName] = np.nan
972 dataset.noiseErr[ampName] = np.nan
973 dataset.ptcFitPars[ampName] = np.nan
974 dataset.ptcFitParsError[ampName] = np.nan
975 dataset.ptcFitReducedChiSquared[ampName] = np.nan
979 if self.config.doFitBootstrap:
980 parsFit, parsFitErr, reducedChiSqPtc =
fitBootstrap(parsIniPtc, meanVecFinal,
981 varVecFinal, ptcFunc,
982 weightsY=1./np.sqrt(varVecFinal))
984 parsFit, parsFitErr, reducedChiSqPtc =
fitLeastSq(parsIniPtc, meanVecFinal,
985 varVecFinal, ptcFunc,
986 weightsY=1./np.sqrt(varVecFinal))
987 dataset.ptcFitPars[ampName] = parsFit
988 dataset.ptcFitParsError[ampName] = parsFitErr
989 dataset.ptcFitReducedChiSquared[ampName] = reducedChiSqPtc
991 if ptcFitType ==
'EXPAPPROXIMATION':
993 ptcGainErr = parsFitErr[1]
994 ptcNoise = np.sqrt(np.fabs(parsFit[2]))
995 ptcNoiseErr = 0.5*(parsFitErr[2]/np.fabs(parsFit[2]))*np.sqrt(np.fabs(parsFit[2]))
996 if ptcFitType ==
'POLYNOMIAL':
997 ptcGain = 1./parsFit[1]
998 ptcGainErr = np.fabs(1./parsFit[1])*(parsFitErr[1]/parsFit[1])
999 ptcNoise = np.sqrt(np.fabs(parsFit[0]))*ptcGain
1000 ptcNoiseErr = (0.5*(parsFitErr[0]/np.fabs(parsFit[0]))*(np.sqrt(np.fabs(parsFit[0]))))*ptcGain
1001 dataset.gain[ampName] = ptcGain
1002 dataset.gainErr[ampName] = ptcGainErr
1003 dataset.noise[ampName] = ptcNoise
1004 dataset.noiseErr[ampName] = ptcNoiseErr
1005 if not len(dataset.ptcFitType) == 0:
1006 dataset.ptcFitType = ptcFitType