LSST Applications g0265f82a02+0e5473021a,g02d81e74bb+f5613e8b4f,g1470d8bcf6+190ad2ba91,g14a832a312+311607e4ab,g2079a07aa2+86d27d4dc4,g2305ad1205+a8e3196225,g295015adf3+b67ee847e5,g2bbee38e9b+0e5473021a,g337abbeb29+0e5473021a,g3ddfee87b4+a761f810f3,g487adcacf7+17c8fdbcbd,g50ff169b8f+96c6868917,g52b1c1532d+585e252eca,g591dd9f2cf+65b5bd823e,g5a732f18d5+53520f316c,g64a986408d+f5613e8b4f,g6c1bc301e9+51106c2951,g858d7b2824+f5613e8b4f,g8a8a8dda67+585e252eca,g99cad8db69+6729933424,g9ddcbc5298+9a081db1e4,ga1e77700b3+15fc3df1f7,ga8c6da7877+ef4e3a5875,gb0e22166c9+60f28cb32d,gb6a65358fc+0e5473021a,gba4ed39666+c2a2e4ac27,gbb8dafda3b+e9bba80f27,gc120e1dc64+eee469a5e5,gc28159a63d+0e5473021a,gcf0d15dbbd+a761f810f3,gdaeeff99f8+f9a426f77a,ge6526c86ff+d4c1d4bfef,ge79ae78c31+0e5473021a,gee10cc3b42+585e252eca,gf1cff7945b+f5613e8b4f,w.2024.16
LSST Data Management Base Package
Loading...
Searching...
No Matches
Classes | Variables
lsst.pipe.tasks.subtractBrightStars Namespace Reference

Classes

class  SubtractBrightStarsConnections
 

Variables

 logger = logging.getLogger(__name__)
 
 inputExposure : `~lsst.afw.image.ExposureF`
 
 inputBrightStarStamps :
 
 inputExtendedPsf : `~lsst.pipe.tasks.extended_psf.ExtendedPsf`
 
 dataId : `dict` or `~lsst.daf.butler.DataCoordinate`
 
 skyCorr : `~lsst.afw.math.backgroundList.BackgroundList`, optional
 
 refObjLoader : `~lsst.meas.algorithms.ReferenceObjectLoader`, optional
 
 subtractorExp : `~lsst.afw.image.ExposureF`
 
 invImages : `list` [`~lsst.afw.image.MaskedImageF`]
 
 invImage : `~lsst.afw.image.MaskedImageF`
 
 brightStarStamps :
 
 subtractor : `~lsst.afw.image.MaskedImageF`
 
bool multipleAnnuli , optional
 

Detailed Description

Retrieve extended PSF model and subtract bright stars at visit level.

Variable Documentation

◆ brightStarStamps

lsst.pipe.tasks.subtractBrightStars.brightStarStamps :
bbox, invImage = self.preparePlaneModelStamp(brightStarStamp)
bbox.clip(self.inputExpBBox)
if bbox.getArea() > 0:
    if multipleAnnuli:
        cond = self.psf_annular_fluxes[:, 0] == brightStarStamp.optimalOuterRadius
        psf_annular_flux = self.psf_annular_fluxes[cond, 1][0]
        self.scaleModel(
            invImage,
            brightStarStamp,
            inPlace=True,
            nb90Rots=self.inv90Rots,
            psf_annular_flux=psf_annular_flux,
        )
    else:
        self.scaleModel(invImage, brightStarStamp, inPlace=True, nb90Rots=self.inv90Rots)
    # Replace NaNs before subtraction (all NaNs have the NO_DATA flag).
    invImage.image.array[np.isnan(invImage.image.array)] = 0
    subtractor[bbox] += invImage[bbox]
return subtractor, invImage

def buildSubtractor(self, brightStarStamps, subtractor, invImages, multipleAnnuli=False):

Definition at line 805 of file subtractBrightStars.py.

◆ dataId

lsst.pipe.tasks.subtractBrightStars.dataId : `dict` or `~lsst.daf.butler.DataCoordinate`

Definition at line 301 of file subtractBrightStars.py.

◆ inputBrightStarStamps

lsst.pipe.tasks.subtractBrightStars.inputBrightStarStamps :

Definition at line 293 of file subtractBrightStars.py.

◆ inputExposure

lsst.pipe.tasks.subtractBrightStars.inputExposure : `~lsst.afw.image.ExposureF`
    doWriteSubtractor = Field[bool](
        doc="Should an exposure containing all bright star models be written to disk?",
        default=True,
    )
    doWriteSubtractedExposure = Field[bool](
        doc="Should an exposure with bright stars subtracted be written to disk?",
        default=True,
    )
    magLimit = Field[float](
        doc="Magnitude limit, in Gaia G; all stars brighter than this value will be subtracted",
        default=18,
    )
    minValidAnnulusFraction = Field[float](
        doc="Minimum number of valid pixels that must fall within the annulus for the bright star to be "
        "saved for subsequent generation of a PSF.",
        default=0.0,
    )
    numSigmaClip = Field[float](
        doc="Sigma for outlier rejection; ignored if annularFluxStatistic != 'MEANCLIP'.",
        default=4,
    )
    numIter = Field[int](
        doc="Number of iterations of outlier rejection; ignored if annularFluxStatistic != 'MEANCLIP'.",
        default=3,
    )
    warpingKernelName = ChoiceField[str](
        doc="Warping kernel",
        default="lanczos5",
        allowed={
            "bilinear": "bilinear interpolation",
            "lanczos3": "Lanczos kernel of order 3",
            "lanczos4": "Lanczos kernel of order 4",
            "lanczos5": "Lanczos kernel of order 5",
            "lanczos6": "Lanczos kernel of order 6",
            "lanczos7": "Lanczos kernel of order 7",
        },
    )
    scalingType = ChoiceField[str](
        doc="How the model should be scaled to each bright star; implemented options are "
        "`annularFlux` to reuse the annular flux of each stamp, or `leastSquare` to perform "
        "least square fitting on each pixel with no bad mask plane set.",
        default="leastSquare",
        allowed={
            "annularFlux": "reuse BrightStarStamp annular flux measurement",
            "leastSquare": "find least square scaling factor",
        },
    )
    annularFluxStatistic = ChoiceField[str](
        doc="Type of statistic to use to compute annular flux.",
        default="MEANCLIP",
        allowed={
            "MEAN": "mean",
            "MEDIAN": "median",
            "MEANCLIP": "clipped mean",
        },
    )
    badMaskPlanes = ListField[str](
        doc="Mask planes that, if set, lead to associated pixels not being included in the computation of "
        "the scaling factor (`BAD` should always be included). Ignored if scalingType is `annularFlux`, "
        "as the stamps are expected to already be normalized.",
        # Note that `BAD` should always be included, as secondary detected
        # sources (i.e., detected sources other than the primary source of
        # interest) also get set to `BAD`.
        default=("BAD", "CR", "CROSSTALK", "EDGE", "NO_DATA", "SAT", "SUSPECT", "UNMASKEDNAN"),
    )
    subtractionBox = ListField[int](
        doc="Size of the stamps to be extracted, in pixels.",
        default=(250, 250),
    )
    subtractionBoxBuffer = Field[float](
        doc=(
            "'Buffer' (multiplicative) factor to be applied to determine the size of the stamp the "
            "processed stars will be saved in. This is also the size of the extended PSF model. The buffer "
            "region is masked and contain no data and subtractionBox determines the region where contains "
            "the data."
        ),
        default=1.1,
    )
    doApplySkyCorr = Field[bool](
        doc="Apply full focal plane sky correction before extracting stars?",
        default=True,
    )
    refObjLoader = ConfigField[LoadReferenceObjectsConfig](
        doc="Reference object loader for astrometric calibration.",
    )


class SubtractBrightStarsTask(PipelineTask):
ConfigClass = SubtractBrightStarsConfig
_DefaultName = "subtractBrightStars"

def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)
    # Placeholders to set up Statistics if scalingType is leastSquare.
    self.statsControl, self.statsFlag = None, None
    # Warping control; only contains shiftingALg provided in config.
    self.warpControl = WarpingControl(self.config.warpingKernelName)

def runQuantum(self, butlerQC, inputRefs, outputRefs):
    # Docstring inherited.
    inputs = butlerQC.get(inputRefs)
    if inputs["inputExtendedPsf"].default_extended_psf is None:
        if not self._detectorInRegions(inputs["inputExposure"], inputs["inputExtendedPsf"]):
            self.log.warn(
                "Extended PSF model is not available for detector %i. Skipping withouth processing this "
                "exposure.",
                inputs["inputExposure"].detector.getId(),
            )
            return None
    dataId = butlerQC.quantum.dataId
    refObjLoader = ReferenceObjectLoader(
        dataIds=[ref.datasetRef.dataId for ref in inputRefs.refCat],
        refCats=inputs.pop("refCat"),
        name=self.config.connections.refCat,
        config=self.config.refObjLoader,
    )
    subtractor, _, badStamps = self.run(**inputs, dataId=dataId, refObjLoader=refObjLoader)
    if self.config.doWriteSubtractedExposure:
        outputExposure = inputs["inputExposure"].clone()
        outputExposure.image -= subtractor.image
    else:
        outputExposure = None
    outputBackgroundExposure = subtractor if self.config.doWriteSubtractor else None
    # In its current state, the code produces outputBadStamps which are the
    # stamps of stars that have not been subtracted from the image for any
    # reason. If all the stars are subtracted from the calexp, the output
    # is an empty fits file.
    output = Struct(
        outputExposure=outputExposure,
        outputBackgroundExposure=outputBackgroundExposure,
        outputBadStamps=badStamps,
    )
    butlerQC.put(output, outputRefs)

def run(
    self, inputExposure, inputBrightStarStamps, inputExtendedPsf, dataId, skyCorr=None, refObjLoader=None
):

Definition at line 291 of file subtractBrightStars.py.

◆ inputExtendedPsf

lsst.pipe.tasks.subtractBrightStars.inputExtendedPsf : `~lsst.pipe.tasks.extended_psf.ExtendedPsf`

Definition at line 298 of file subtractBrightStars.py.

◆ invImage

lsst.pipe.tasks.subtractBrightStars.invImage : `~lsst.afw.image.MaskedImageF`
self.inputExpBBox = inputExposure.getBBox()
if self.config.doApplySkyCorr and (skyCorr is not None):
    self.log.info(
        "Applying sky correction to exposure %s (exposure will be modified in-place).", dataId
    )
    self.applySkyCorr(inputExposure, skyCorr)

# Create an empty image the size of the exposure.
# TODO: DM-31085 (set mask planes).
subtractorExp = ExposureF(bbox=inputExposure.getBBox())
subtractor = subtractorExp.maskedImage

# Make a copy of the input model.
self.model = inputExtendedPsf(dataId["detector"]).clone()
self.modelStampSize = self.model.getDimensions()
# Number of 90 deg. rotations to reverse each stamp's rotation.
self.inv90Rots = 4 - inputBrightStarStamps.nb90Rots % 4
self.model = rotateImageBy90(self.model, self.inv90Rots)

brightStarList = self.makeBrightStarList(inputBrightStarStamps, inputExposure, refObjLoader)
invImages = []
subtractor, invImages = self.buildSubtractor(
    inputBrightStarStamps, subtractor, invImages, multipleAnnuli=False
)
if brightStarList:
    self.setMissedStarsStatsControl()
    # This may change when multiple star bins are used for PSF
    # creation.
    innerRadius = inputBrightStarStamps._innerRadius
    outerRadius = inputBrightStarStamps._outerRadius
    brightStarStamps, badStamps = BrightStarStamps.initAndNormalize(
        brightStarList,
        innerRadius=innerRadius,
        outerRadius=outerRadius,
        nb90Rots=self.warpOutputs.nb90Rots,
        imCenter=self.warper.modelCenter,
        use_archive=True,
        statsControl=self.missedStatsControl,
        statsFlag=self.missedStatsFlag,
        badMaskPlanes=self.warper.config.badMaskPlanes,
        discardNanFluxObjects=False,
        forceFindFlux=True,
    )

    self.psf_annular_fluxes = self.findPsfAnnularFluxes(brightStarStamps)
    subtractor, invImages = self.buildSubtractor(
        brightStarStamps, subtractor, invImages, multipleAnnuli=True
    )
else:
    badStamps = []
badStamps = BrightStarStamps(badStamps)

return subtractorExp, invImages, badStamps

def _detectorInRegions(self, inputExposure, inputExtendedPsf):

Definition at line 775 of file subtractBrightStars.py.

◆ invImages

list lsst.pipe.tasks.subtractBrightStars.invImages : `list` [`~lsst.afw.image.MaskedImageF`]

Definition at line 317 of file subtractBrightStars.py.

◆ logger

lsst.pipe.tasks.subtractBrightStars.logger = logging.getLogger(__name__)

Definition at line 49 of file subtractBrightStars.py.

◆ multipleAnnuli

bool lsst.pipe.tasks.subtractBrightStars.multipleAnnuli , optional

Definition at line 816 of file subtractBrightStars.py.

◆ refObjLoader

lsst.pipe.tasks.subtractBrightStars.refObjLoader : `~lsst.meas.algorithms.ReferenceObjectLoader`, optional

Definition at line 308 of file subtractBrightStars.py.

◆ skyCorr

lsst.pipe.tasks.subtractBrightStars.skyCorr : `~lsst.afw.math.backgroundList.BackgroundList`, optional

Definition at line 304 of file subtractBrightStars.py.

◆ subtractor

lsst.pipe.tasks.subtractBrightStars.subtractor : `~lsst.afw.image.MaskedImageF`

Definition at line 810 of file subtractBrightStars.py.

◆ subtractorExp

lsst.pipe.tasks.subtractBrightStars.subtractorExp : `~lsst.afw.image.ExposureF`

Definition at line 313 of file subtractBrightStars.py.