LSST Applications g0f08755f38+82efc23009,g12f32b3c4e+e7bdf1200e,g1653933729+a8ce1bb630,g1a0ca8cf93+50eff2b06f,g28da252d5a+52db39f6a5,g2bbee38e9b+37c5a29d61,g2bc492864f+37c5a29d61,g2cdde0e794+c05ff076ad,g3156d2b45e+41e33cbcdc,g347aa1857d+37c5a29d61,g35bb328faa+a8ce1bb630,g3a166c0a6a+37c5a29d61,g3e281a1b8c+fb992f5633,g414038480c+7f03dfc1b0,g41af890bb2+11b950c980,g5fbc88fb19+17cd334064,g6b1c1869cb+12dd639c9a,g781aacb6e4+a8ce1bb630,g80478fca09+72e9651da0,g82479be7b0+04c31367b4,g858d7b2824+82efc23009,g9125e01d80+a8ce1bb630,g9726552aa6+8047e3811d,ga5288a1d22+e532dc0a0b,gae0086650b+a8ce1bb630,gb58c049af0+d64f4d3760,gc28159a63d+37c5a29d61,gcf0d15dbbd+2acd6d4d48,gd7358e8bfb+778a810b6e,gda3e153d99+82efc23009,gda6a2b7d83+2acd6d4d48,gdaeeff99f8+1711a396fd,ge2409df99d+6b12de1076,ge79ae78c31+37c5a29d61,gf0baf85859+d0a5978c5a,gf3967379c6+4954f8c433,gfb92a5be7c+82efc23009,gfec2e1e490+2aaed99252,w.2024.46
LSST Data Management Base Package
Loading...
Searching...
No Matches
calibrateImage.py
Go to the documentation of this file.
1# This file is part of pipe_tasks.
2#
3# Developed for the LSST Data Management System.
4# This product includes software developed by the LSST Project
5# (https://www.lsst.org).
6# See the COPYRIGHT file at the top-level directory of this distribution
7# for details of code ownership.
8#
9# This program is free software: you can redistribute it and/or modify
10# it under the terms of the GNU General Public License as published by
11# the Free Software Foundation, either version 3 of the License, or
12# (at your option) any later version.
13#
14# This program is distributed in the hope that it will be useful,
15# but WITHOUT ANY WARRANTY; without even the implied warranty of
16# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17# GNU General Public License for more details.
18#
19# You should have received a copy of the GNU General Public License
20# along with this program. If not, see <https://www.gnu.org/licenses/>.
21
22__all__ = ["CalibrateImageTask", "CalibrateImageConfig", "NoPsfStarsToStarsMatchError"]
23
24import numpy as np
25
26import lsst.afw.table as afwTable
27import lsst.afw.image as afwImage
28from lsst.ip.diffim.utils import evaluateMaskFraction
33import lsst.meas.base
36import lsst.meas.extensions.shapeHSM
37import lsst.pex.config as pexConfig
38import lsst.pipe.base as pipeBase
39from lsst.pipe.base import connectionTypes
40from lsst.utils.timer import timeMethod
41
42from . import measurePsf, repair, photoCal, computeExposureSummaryStats, snapCombine
43
44
45class NoPsfStarsToStarsMatchError(pipeBase.AlgorithmError):
46 """Raised when there are no matches between the psf_stars and stars
47 catalogs.
48 """
49 def __init__(self, *, n_psf_stars, n_stars):
50 msg = (f"No psf stars out of {n_psf_stars} matched {n_stars} calib stars."
51 " Downstream processes probably won't have useful stars in this case."
52 " Is `star_source_selector` too strict or is this a bad image?")
53 super().__init__(msg)
54 self.n_psf_stars = n_psf_stars
55 self.n_stars = n_stars
56
57 @property
58 def metadata(self):
59 return {"n_psf_stars": self.n_psf_stars,
60 "n_stars": self.n_stars
61 }
62
63
64class CalibrateImageConnections(pipeBase.PipelineTaskConnections,
65 dimensions=("instrument", "visit", "detector")):
66
67 astrometry_ref_cat = connectionTypes.PrerequisiteInput(
68 doc="Reference catalog to use for astrometric calibration.",
69 name="gaia_dr3_20230707",
70 storageClass="SimpleCatalog",
71 dimensions=("skypix",),
72 deferLoad=True,
73 multiple=True,
74 )
75 photometry_ref_cat = connectionTypes.PrerequisiteInput(
76 doc="Reference catalog to use for photometric calibration.",
77 name="ps1_pv3_3pi_20170110",
78 storageClass="SimpleCatalog",
79 dimensions=("skypix",),
80 deferLoad=True,
81 multiple=True
82 )
83
84 exposures = connectionTypes.Input(
85 doc="Exposure (or two snaps) to be calibrated, and detected and measured on.",
86 name="postISRCCD",
87 storageClass="Exposure",
88 multiple=True, # to handle 1 exposure or 2 snaps
89 dimensions=["instrument", "exposure", "detector"],
90 )
91
92 # outputs
93 initial_stars_schema = connectionTypes.InitOutput(
94 doc="Schema of the output initial stars catalog.",
95 name="initial_stars_schema",
96 storageClass="SourceCatalog",
97 )
98
99 # TODO DM-38732: We want some kind of flag on Exposures/Catalogs to make
100 # it obvious which components had failed to be computed/persisted.
101 exposure = connectionTypes.Output(
102 doc="Photometrically calibrated, background-subtracted exposure with fitted calibrations and "
103 "summary statistics. To recover the original exposure, first add the background "
104 "(`initial_pvi_background`), and then uncalibrate (divide by `initial_photoCalib_detector`).",
105 name="initial_pvi",
106 storageClass="ExposureF",
107 dimensions=("instrument", "visit", "detector"),
108 )
109 stars = connectionTypes.Output(
110 doc="Catalog of unresolved sources detected on the calibrated exposure.",
111 name="initial_stars_detector",
112 storageClass="ArrowAstropy",
113 dimensions=["instrument", "visit", "detector"],
114 )
115 stars_footprints = connectionTypes.Output(
116 doc="Catalog of unresolved sources detected on the calibrated exposure; "
117 "includes source footprints.",
118 name="initial_stars_footprints_detector",
119 storageClass="SourceCatalog",
120 dimensions=["instrument", "visit", "detector"],
121 )
122 applied_photo_calib = connectionTypes.Output(
123 doc=(
124 "Photometric calibration that was applied to exposure's pixels. "
125 "This connection is disabled when do_calibrate_pixels=False."
126 ),
127 name="initial_photoCalib_detector",
128 storageClass="PhotoCalib",
129 dimensions=("instrument", "visit", "detector"),
130 )
131 background = connectionTypes.Output(
132 doc="Background models estimated during calibration task; calibrated to be in nJy units.",
133 name="initial_pvi_background",
134 storageClass="Background",
135 dimensions=("instrument", "visit", "detector"),
136 )
137
138 # Optional outputs
139 psf_stars_footprints = connectionTypes.Output(
140 doc="Catalog of bright unresolved sources detected on the exposure used for PSF determination; "
141 "includes source footprints.",
142 name="initial_psf_stars_footprints_detector",
143 storageClass="SourceCatalog",
144 dimensions=["instrument", "visit", "detector"],
145 )
146 psf_stars = connectionTypes.Output(
147 doc="Catalog of bright unresolved sources detected on the exposure used for PSF determination.",
148 name="initial_psf_stars_detector",
149 storageClass="ArrowAstropy",
150 dimensions=["instrument", "visit", "detector"],
151 )
152 astrometry_matches = connectionTypes.Output(
153 doc="Source to reference catalog matches from the astrometry solver.",
154 name="initial_astrometry_match_detector",
155 storageClass="Catalog",
156 dimensions=("instrument", "visit", "detector"),
157 )
158 photometry_matches = connectionTypes.Output(
159 doc="Source to reference catalog matches from the photometry solver.",
160 name="initial_photometry_match_detector",
161 storageClass="Catalog",
162 dimensions=("instrument", "visit", "detector"),
163 )
164
165 def __init__(self, *, config=None):
166 super().__init__(config=config)
167 if config.optional_outputs is None or "psf_stars" not in config.optional_outputs:
168 del self.psf_stars
169 if config.optional_outputs is None or "psf_stars_footprints" not in config.optional_outputs:
170 del self.psf_stars_footprints
171 if config.optional_outputs is None or "astrometry_matches" not in config.optional_outputs:
172 del self.astrometry_matches
173 if config.optional_outputs is None or "photometry_matches" not in config.optional_outputs:
174 del self.photometry_matches
175 if not config.do_calibrate_pixels:
176 del self.applied_photo_calib
177
178
179class CalibrateImageConfig(pipeBase.PipelineTaskConfig, pipelineConnections=CalibrateImageConnections):
180 optional_outputs = pexConfig.ListField(
181 doc="Which optional outputs to save (as their connection name)?"
182 " If None, do not output any of these datasets.",
183 dtype=str,
184 # TODO: note somewhere to disable this for benchmarking, but should
185 # we always have it on for production runs?
186 default=["psf_stars", "psf_stars_footprints", "astrometry_matches", "photometry_matches"],
187 optional=True
188 )
189
190 # To generate catalog ids consistently across subtasks.
191 id_generator = lsst.meas.base.DetectorVisitIdGeneratorConfig.make_field()
192
193 snap_combine = pexConfig.ConfigurableField(
195 doc="Task to combine two snaps to make one exposure.",
196 )
197
198 # subtasks used during psf characterization
199 install_simple_psf = pexConfig.ConfigurableField(
201 doc="Task to install a simple PSF model into the input exposure to use "
202 "when detecting bright sources for PSF estimation.",
203 )
204 psf_repair = pexConfig.ConfigurableField(
205 target=repair.RepairTask,
206 doc="Task to repair cosmic rays on the exposure before PSF determination.",
207 )
208 psf_subtract_background = pexConfig.ConfigurableField(
210 doc="Task to perform intial background subtraction, before first detection pass.",
211 )
212 psf_detection = pexConfig.ConfigurableField(
214 doc="Task to detect sources for PSF determination."
215 )
216 psf_source_measurement = pexConfig.ConfigurableField(
218 doc="Task to measure sources to be used for psf estimation."
219 )
220 psf_measure_psf = pexConfig.ConfigurableField(
222 doc="Task to measure the psf on bright sources."
223 )
224 psf_normalized_calibration_flux = pexConfig.ConfigurableField(
226 doc="Task to normalize the calibration flux (e.g. compensated tophats) "
227 "for the bright stars used for psf estimation.",
228 )
229
230 # TODO DM-39203: we can remove aperture correction from this task once we are
231 # using the shape-based star/galaxy code.
232 measure_aperture_correction = pexConfig.ConfigurableField(
234 doc="Task to compute the aperture correction from the bright stars."
235 )
236
237 # subtasks used during star measurement
238 star_detection = pexConfig.ConfigurableField(
240 doc="Task to detect stars to return in the output catalog."
241 )
242 star_sky_sources = pexConfig.ConfigurableField(
244 doc="Task to generate sky sources ('empty' regions where there are no detections).",
245 )
246 star_deblend = pexConfig.ConfigurableField(
248 doc="Split blended sources into their components."
249 )
250 star_measurement = pexConfig.ConfigurableField(
252 doc="Task to measure stars to return in the output catalog."
253 )
254 star_normalized_calibration_flux = pexConfig.ConfigurableField(
256 doc="Task to apply the normalization for calibration fluxes (e.g. compensated tophats) "
257 "for the final output star catalog.",
258 )
259 star_apply_aperture_correction = pexConfig.ConfigurableField(
261 doc="Task to apply aperture corrections to the selected stars."
262 )
263 star_catalog_calculation = pexConfig.ConfigurableField(
265 doc="Task to compute extendedness values on the star catalog, "
266 "for the star selector to remove extended sources."
267 )
268 star_set_primary_flags = pexConfig.ConfigurableField(
270 doc="Task to add isPrimary to the catalog."
271 )
272 star_selector = lsst.meas.algorithms.sourceSelectorRegistry.makeField(
273 default="science",
274 doc="Task to select reliable stars to use for calibration."
275 )
276
277 # final calibrations and statistics
278 astrometry = pexConfig.ConfigurableField(
280 doc="Task to perform astrometric calibration to fit a WCS.",
281 )
282 astrometry_ref_loader = pexConfig.ConfigField(
284 doc="Configuration of reference object loader for astrometric fit.",
285 )
286 photometry = pexConfig.ConfigurableField(
288 doc="Task to perform photometric calibration to fit a PhotoCalib.",
289 )
290 photometry_ref_loader = pexConfig.ConfigField(
292 doc="Configuration of reference object loader for photometric fit.",
293 )
294
295 compute_summary_stats = pexConfig.ConfigurableField(
297 doc="Task to to compute summary statistics on the calibrated exposure."
298 )
299
300 do_calibrate_pixels = pexConfig.Field(
301 dtype=bool,
302 default=True,
303 doc=(
304 "If True, apply the photometric calibration to the image pixels "
305 "and background model, and attach an identity PhotoCalib to "
306 "the output image to reflect this. If False`, leave the image "
307 "and background uncalibrated and attach the PhotoCalib that maps "
308 "them to physical units."
309 )
310 )
311
312 def setDefaults(self):
313 super().setDefaults()
314
315 # Use a very broad PSF here, to throughly reject CRs.
316 # TODO investigation: a large initial psf guess may make stars look
317 # like CRs for very good seeing images.
318 self.install_simple_psf.fwhm = 4
319
320 # S/N>=50 sources for PSF determination, but detection to S/N=5.
321 # The thresholdValue sets the minimum flux in a pixel to be included in the
322 # footprint, while peaks are only detected when they are above
323 # thresholdValue * includeThresholdMultiplier. The low thresholdValue
324 # ensures that the footprints are large enough for the noise replacer
325 # to mask out faint undetected neighbors that are not to be measured.
326 self.psf_detection.thresholdValue = 5.0
327 self.psf_detection.includeThresholdMultiplier = 10.0
328 # TODO investigation: Probably want False here, but that may require
329 # tweaking the background spatial scale, to make it small enough to
330 # prevent extra peaks in the wings of bright objects.
331 self.psf_detection.doTempLocalBackground = False
332 # NOTE: we do want reEstimateBackground=True in psf_detection, so that
333 # each measurement step is done with the best background available.
334
335 # Minimal measurement plugins for PSF determination.
336 # TODO DM-39203: We can drop GaussianFlux and PsfFlux, if we use
337 # shapeHSM/moments for star/galaxy separation.
338 # TODO DM-39203: we can remove aperture correction from this task once
339 # we are using the shape-based star/galaxy code.
340 self.psf_source_measurement.plugins = ["base_PixelFlags",
341 "base_SdssCentroid",
342 "ext_shapeHSM_HsmSourceMoments",
343 "base_CircularApertureFlux",
344 "base_GaussianFlux",
345 "base_PsfFlux",
346 "base_CompensatedTophatFlux",
347 ]
348 self.psf_source_measurement.slots.shape = "ext_shapeHSM_HsmSourceMoments"
349 # Only measure apertures we need for PSF measurement.
350 self.psf_source_measurement.plugins["base_CircularApertureFlux"].radii = [12.0]
351 self.psf_source_measurement.plugins["base_CompensatedTophatFlux"].apertures = [12]
352 # TODO DM-40843: Remove this line once this is the psfex default.
353 self.psf_measure_psf.psfDeterminer["psfex"].photometricFluxField = \
354 "base_CircularApertureFlux_12_0_instFlux"
355
356 # No extendeness information available: we need the aperture
357 # corrections to determine that.
358 self.measure_aperture_correction.sourceSelector["science"].doUnresolved = False
359 self.measure_aperture_correction.sourceSelector["science"].flags.good = ["calib_psf_used"]
360 self.measure_aperture_correction.sourceSelector["science"].flags.bad = []
361
362 # Detection for good S/N for astrometry/photometry and other
363 # downstream tasks; detection mask to S/N>=5, but S/N>=10 peaks.
364 self.star_detection.thresholdValue = 5.0
365 self.star_detection.includeThresholdMultiplier = 2.0
366 self.star_measurement.plugins = ["base_PixelFlags",
367 "base_SdssCentroid",
368 "ext_shapeHSM_HsmSourceMoments",
369 "ext_shapeHSM_HsmPsfMoments",
370 "base_GaussianFlux",
371 "base_PsfFlux",
372 "base_CircularApertureFlux",
373 "base_ClassificationSizeExtendedness",
374 "base_CompensatedTophatFlux",
375 ]
376 self.star_measurement.slots.psfShape = "ext_shapeHSM_HsmPsfMoments"
377 self.star_measurement.slots.shape = "ext_shapeHSM_HsmSourceMoments"
378 # Only measure the apertures we need for star selection.
379 self.star_measurement.plugins["base_CircularApertureFlux"].radii = [12.0]
380 self.star_measurement.plugins["base_CompensatedTophatFlux"].apertures = [12]
381
382 # We measure and apply the normalization aperture correction with the
383 # psf_normalized_calibration_flux task, and we only apply the normalization
384 # aperture correction for the full list of stars.
385 self.star_normalized_calibration_flux.do_measure_ap_corr = False
386
387 # Select stars with reliable measurements and no bad flags.
388 self.star_selector["science"].doFlags = True
389 self.star_selector["science"].doUnresolved = True
390 self.star_selector["science"].doSignalToNoise = True
391 self.star_selector["science"].signalToNoise.minimum = 10.0
392 # Keep sky sources in the output catalog, even though they aren't
393 # wanted for calibration.
394 self.star_selector["science"].doSkySources = True
395
396 # Use the affine WCS fitter (assumes we have a good camera geometry).
397 self.astrometry.wcsFitter.retarget(lsst.meas.astrom.FitAffineWcsTask)
398 # phot_g_mean is the primary Gaia band for all input bands.
399 self.astrometry_ref_loader.anyFilterMapsToThis = "phot_g_mean"
400
401 # Only reject sky sources; we already selected good stars.
402 self.astrometry.sourceSelector["science"].doFlags = True
403 self.astrometry.sourceSelector["science"].flags.bad = ["sky_source"]
404 self.photometry.match.sourceSelection.doFlags = True
405 self.photometry.match.sourceSelection.flags.bad = ["sky_source"]
406 # Unset the (otherwise reasonable, but we've already made the
407 # selections we want above) selection settings in PhotoCalTask.
408 self.photometry.match.sourceSelection.doRequirePrimary = False
409 self.photometry.match.sourceSelection.doUnresolved = False
410
411 # All sources should be good for PSF summary statistics.
412 # TODO: These should both be changed to calib_psf_used with DM-41640.
413 self.compute_summary_stats.starSelection = "calib_photometry_used"
414 self.compute_summary_stats.starSelector.flags.good = ["calib_photometry_used"]
415
416 def validate(self):
417 super().validate()
418
419 # Ensure that the normalization calibration flux tasks
420 # are configured correctly.
421 if not self.psf_normalized_calibration_flux.do_measure_ap_corr:
422 msg = ("psf_normalized_calibration_flux task must be configured with do_measure_ap_corr=True "
423 "or else the normalization and calibration flux will not be properly measured.")
424 raise pexConfig.FieldValidationError(
425 CalibrateImageConfig.psf_normalized_calibration_flux, self, msg,
426 )
427 if self.star_normalized_calibration_flux.do_measure_ap_corr:
428 msg = ("star_normalized_calibration_flux task must be configured with do_measure_ap_corr=False "
429 "to apply the previously measured normalization to the full catalog of calibration "
430 "fluxes.")
431 raise pexConfig.FieldValidationError(
432 CalibrateImageConfig.star_normalized_calibration_flux, self, msg,
433 )
434
435
436class CalibrateImageTask(pipeBase.PipelineTask):
437 """Compute the PSF, aperture corrections, astrometric and photometric
438 calibrations, and summary statistics for a single science exposure, and
439 produce a catalog of brighter stars that were used to calibrate it.
440
441 Parameters
442 ----------
443 initial_stars_schema : `lsst.afw.table.Schema`
444 Schema of the initial_stars output catalog.
445 """
446 _DefaultName = "calibrateImage"
447 ConfigClass = CalibrateImageConfig
448
449 def __init__(self, initial_stars_schema=None, **kwargs):
450 super().__init__(**kwargs)
451
452 self.makeSubtask("snap_combine")
453
454 # PSF determination subtasks
455 self.makeSubtask("install_simple_psf")
456 self.makeSubtask("psf_repair")
457 self.makeSubtask("psf_subtract_background")
458 self.psf_schema = afwTable.SourceTable.makeMinimalSchema()
459 self.makeSubtask("psf_detection", schema=self.psf_schema)
460 self.makeSubtask("psf_source_measurement", schema=self.psf_schema)
461 self.makeSubtask("psf_measure_psf", schema=self.psf_schema)
462 self.makeSubtask("psf_normalized_calibration_flux", schema=self.psf_schema)
463
464 self.makeSubtask("measure_aperture_correction", schema=self.psf_schema)
465
466 # star measurement subtasks
467 if initial_stars_schema is None:
468 initial_stars_schema = afwTable.SourceTable.makeMinimalSchema()
469
470 # These fields let us track which sources were used for psf and
471 # aperture correction calculations.
472 self.psf_fields = ("calib_psf_candidate", "calib_psf_used", "calib_psf_reserved",
473 # TODO DM-39203: these can be removed once apcorr is gone.
474 "apcorr_slot_CalibFlux_used", "apcorr_base_GaussianFlux_used",
475 "apcorr_base_PsfFlux_used")
476 for field in self.psf_fields:
477 item = self.psf_schema.find(field)
478 initial_stars_schema.addField(item.getField())
479
480 afwTable.CoordKey.addErrorFields(initial_stars_schema)
481 self.makeSubtask("star_detection", schema=initial_stars_schema)
482 self.makeSubtask("star_sky_sources", schema=initial_stars_schema)
483 self.makeSubtask("star_deblend", schema=initial_stars_schema)
484 self.makeSubtask("star_measurement", schema=initial_stars_schema)
485 self.makeSubtask("star_normalized_calibration_flux", schema=initial_stars_schema)
486
487 self.makeSubtask("star_apply_aperture_correction", schema=initial_stars_schema)
488 self.makeSubtask("star_catalog_calculation", schema=initial_stars_schema)
489 self.makeSubtask("star_set_primary_flags", schema=initial_stars_schema, isSingleFrame=True)
490 self.makeSubtask("star_selector")
491
492 self.makeSubtask("astrometry", schema=initial_stars_schema)
493 self.makeSubtask("photometry", schema=initial_stars_schema)
494
495 self.makeSubtask("compute_summary_stats")
496
497 # For the butler to persist it.
498 self.initial_stars_schema = afwTable.SourceCatalog(initial_stars_schema)
499
500 def runQuantum(self, butlerQC, inputRefs, outputRefs):
501 inputs = butlerQC.get(inputRefs)
502 exposures = inputs.pop("exposures")
503
504 id_generator = self.config.id_generator.apply(butlerQC.quantum.dataId)
505
507 dataIds=[ref.datasetRef.dataId for ref in inputRefs.astrometry_ref_cat],
508 refCats=inputs.pop("astrometry_ref_cat"),
509 name=self.config.connections.astrometry_ref_cat,
510 config=self.config.astrometry_ref_loader, log=self.log)
511 self.astrometry.setRefObjLoader(astrometry_loader)
512
514 dataIds=[ref.datasetRef.dataId for ref in inputRefs.photometry_ref_cat],
515 refCats=inputs.pop("photometry_ref_cat"),
516 name=self.config.connections.photometry_ref_cat,
517 config=self.config.photometry_ref_loader, log=self.log)
518 self.photometry.match.setRefObjLoader(photometry_loader)
519
520 # This should not happen with a properly configured execution context.
521 assert not inputs, "runQuantum got more inputs than expected"
522
523 # Specify the fields that `annotate` needs below, to ensure they
524 # exist, even as None.
525 result = pipeBase.Struct(exposure=None,
526 stars_footprints=None,
527 psf_stars_footprints=None,
528 )
529 try:
530 self.run(exposures=exposures, result=result, id_generator=id_generator)
531 except pipeBase.AlgorithmError as e:
532 error = pipeBase.AnnotatedPartialOutputsError.annotate(
533 e,
534 self,
535 result.exposure,
536 result.psf_stars_footprints,
537 result.stars_footprints,
538 log=self.log
539 )
540 butlerQC.put(result, outputRefs)
541 raise error from e
542
543 butlerQC.put(result, outputRefs)
544
545 @timeMethod
546 def run(self, *, exposures, id_generator=None, result=None):
547 """Find stars and perform psf measurement, then do a deeper detection
548 and measurement and calibrate astrometry and photometry from that.
549
550 Parameters
551 ----------
552 exposures : `lsst.afw.image.Exposure` or `list` [`lsst.afw.image.Exposure`]
553 Post-ISR exposure(s), with an initial WCS, VisitInfo, and Filter.
554 Modified in-place during processing if only one is passed.
555 If two exposures are passed, treat them as snaps and combine
556 before doing further processing.
557 id_generator : `lsst.meas.base.IdGenerator`, optional
558 Object that generates source IDs and provides random seeds.
559 result : `lsst.pipe.base.Struct`, optional
560 Result struct that is modified to allow saving of partial outputs
561 for some failure conditions. If the task completes successfully,
562 this is also returned.
563
564 Returns
565 -------
566 result : `lsst.pipe.base.Struct`
567 Results as a struct with attributes:
568
569 ``exposure``
570 Calibrated exposure, with pixels in nJy units.
571 (`lsst.afw.image.Exposure`)
572 ``stars``
573 Stars that were used to calibrate the exposure, with
574 calibrated fluxes and magnitudes.
575 (`astropy.table.Table`)
576 ``stars_footprints``
577 Footprints of stars that were used to calibrate the exposure.
578 (`lsst.afw.table.SourceCatalog`)
579 ``psf_stars``
580 Stars that were used to determine the image PSF.
581 (`astropy.table.Table`)
582 ``psf_stars_footprints``
583 Footprints of stars that were used to determine the image PSF.
584 (`lsst.afw.table.SourceCatalog`)
585 ``background``
586 Background that was fit to the exposure when detecting
587 ``stars``. (`lsst.afw.math.BackgroundList`)
588 ``applied_photo_calib``
589 Photometric calibration that was fit to the star catalog and
590 applied to the exposure. (`lsst.afw.image.PhotoCalib`)
591 This is `None` if ``config.do_calibrate_pixels`` is `False`.
592 ``astrometry_matches``
593 Reference catalog stars matches used in the astrometric fit.
594 (`list` [`lsst.afw.table.ReferenceMatch`] or `lsst.afw.table.BaseCatalog`)
595 ``photometry_matches``
596 Reference catalog stars matches used in the photometric fit.
597 (`list` [`lsst.afw.table.ReferenceMatch`] or `lsst.afw.table.BaseCatalog`)
598 """
599 if result is None:
600 result = pipeBase.Struct()
601 if id_generator is None:
602 id_generator = lsst.meas.base.IdGenerator()
603
604 result.exposure = self.snap_combine.run(exposures).exposure
605 self._recordMaskedPixelFractions(result.exposure)
606
607 result.psf_stars_footprints, result.background, candidates = self._compute_psf(result.exposure,
608 id_generator)
609 self._measure_aperture_correction(result.exposure, result.psf_stars_footprints)
610
611 result.psf_stars = result.psf_stars_footprints.asAstropy()
612
613 result.stars_footprints = self._find_stars(result.exposure, result.background, id_generator)
614 self._match_psf_stars(result.psf_stars_footprints, result.stars_footprints)
615 result.stars = result.stars_footprints.asAstropy()
616 self.metadata["star_count"] = np.sum(~result.stars["sky_source"])
617
618 astrometry_matches, astrometry_meta = self._fit_astrometry(result.exposure, result.stars_footprints)
619 self.metadata["astrometry_matches_count"] = len(astrometry_matches)
620 if self.config.optional_outputs is not None and "astrometry_matches" in self.config.optional_outputs:
621 result.astrometry_matches = lsst.meas.astrom.denormalizeMatches(astrometry_matches,
622 astrometry_meta)
623
624 result.stars_footprints, photometry_matches, \
625 photometry_meta, photo_calib = self._fit_photometry(result.exposure, result.stars_footprints)
626 self.metadata["photometry_matches_count"] = len(photometry_matches)
627 # fit_photometry returns a new catalog, so we need a new astropy table view.
628 result.stars = result.stars_footprints.asAstropy()
629 if self.config.optional_outputs is not None and "photometry_matches" in self.config.optional_outputs:
630 result.photometry_matches = lsst.meas.astrom.denormalizeMatches(photometry_matches,
631 photometry_meta)
632
633 self._summarize(result.exposure, result.stars_footprints, result.background)
634 if self.config.do_calibrate_pixels:
635 self._apply_photometry(result.exposure, result.background)
636 result.applied_photo_calib = photo_calib
637 else:
638 result.applied_photo_calib = None
639 return result
640
641 def _compute_psf(self, exposure, id_generator):
642 """Find bright sources detected on an exposure and fit a PSF model to
643 them, repairing likely cosmic rays before detection.
644
645 Repair, detect, measure, and compute PSF twice, to ensure the PSF
646 model does not include contributions from cosmic rays.
647
648 Parameters
649 ----------
650 exposure : `lsst.afw.image.Exposure`
651 Exposure to detect and measure bright stars on.
652 id_generator : `lsst.meas.base.IdGenerator`, optional
653 Object that generates source IDs and provides random seeds.
654
655 Returns
656 -------
657 sources : `lsst.afw.table.SourceCatalog`
658 Catalog of detected bright sources.
659 background : `lsst.afw.math.BackgroundList`
660 Background that was fit to the exposure during detection.
661 cell_set : `lsst.afw.math.SpatialCellSet`
662 PSF candidates returned by the psf determiner.
663 """
664 def log_psf(msg, addToMetadata=False):
665 """Log the parameters of the psf and background, with a prepended
666 message. There is also the option to add the PSF sigma to the task
667 metadata.
668
669 Parameters
670 ----------
671 msg : `str`
672 Message to prepend the log info with.
673 addToMetadata : `bool`, optional
674 Whether to add the final psf sigma value to the task metadata
675 (the default is False).
676 """
677 position = exposure.psf.getAveragePosition()
678 sigma = exposure.psf.computeShape(position).getDeterminantRadius()
679 dimensions = exposure.psf.computeImage(position).getDimensions()
680 median_background = np.median(background.getImage().array)
681 self.log.info("%s sigma=%0.4f, dimensions=%s; median background=%0.2f",
682 msg, sigma, dimensions, median_background)
683 if addToMetadata:
684 self.metadata["final_psf_sigma"] = sigma
685
686 self.log.info("First pass detection with Guassian PSF FWHM=%s pixels",
687 self.config.install_simple_psf.fwhm)
688 self.install_simple_psf.run(exposure=exposure)
689
690 background = self.psf_subtract_background.run(exposure=exposure).background
691 log_psf("Initial PSF:")
692 self.psf_repair.run(exposure=exposure, keepCRs=True)
693
694 table = afwTable.SourceTable.make(self.psf_schema, id_generator.make_table_id_factory())
695 # Re-estimate the background during this detection step, so that
696 # measurement uses the most accurate background-subtraction.
697 detections = self.psf_detection.run(table=table, exposure=exposure, background=background)
698 self.metadata["initial_psf_positive_footprint_count"] = detections.numPos
699 self.metadata["initial_psf_negative_footprint_count"] = detections.numNeg
700 self.metadata["initial_psf_positive_peak_count"] = detections.numPosPeaks
701 self.metadata["initial_psf_negative_peak_count"] = detections.numNegPeaks
702 self.psf_source_measurement.run(detections.sources, exposure)
703 psf_result = self.psf_measure_psf.run(exposure=exposure, sources=detections.sources)
704 # Replace the initial PSF with something simpler for the second
705 # repair/detect/measure/measure_psf step: this can help it converge.
706 self.install_simple_psf.run(exposure=exposure)
707
708 log_psf("Rerunning with simple PSF:")
709 # TODO investigation: Should we only re-run repair here, to use the
710 # new PSF? Maybe we *do* need to re-run measurement with PsfFlux, to
711 # use the fitted PSF?
712 # TODO investigation: do we need a separate measurement task here
713 # for the post-psf_measure_psf step, since we only want to do PsfFlux
714 # and GaussianFlux *after* we have a PSF? Maybe that's not relevant
715 # once DM-39203 is merged?
716 self.psf_repair.run(exposure=exposure, keepCRs=True)
717 # Re-estimate the background during this detection step, so that
718 # measurement uses the most accurate background-subtraction.
719 detections = self.psf_detection.run(table=table, exposure=exposure, background=background)
720 self.metadata["simple_psf_positive_footprint_count"] = detections.numPos
721 self.metadata["simple_psf_negative_footprint_count"] = detections.numNeg
722 self.metadata["simple_psf_positive_peak_count"] = detections.numPosPeaks
723 self.metadata["simple_psf_negative_peak_count"] = detections.numNegPeaks
724 self.psf_source_measurement.run(detections.sources, exposure)
725 psf_result = self.psf_measure_psf.run(exposure=exposure, sources=detections.sources)
726
727 log_psf("Final PSF:", addToMetadata=True)
728
729 # Final repair with final PSF, removing cosmic rays this time.
730 self.psf_repair.run(exposure=exposure)
731 # Final measurement with the CRs removed.
732 self.psf_source_measurement.run(detections.sources, exposure)
733
734 # PSF is set on exposure; candidates are returned to use for
735 # calibration flux normalization and aperture corrections.
736 return detections.sources, background, psf_result.cellSet
737
738 def _measure_aperture_correction(self, exposure, bright_sources):
739 """Measure and set the ApCorrMap on the Exposure, using
740 previously-measured bright sources.
741
742 This function first normalizes the calibration flux and then
743 the full set of aperture corrections are measured relative
744 to this normalized calibration flux.
745
746 Parameters
747 ----------
748 exposure : `lsst.afw.image.Exposure`
749 Exposure to set the ApCorrMap on.
750 bright_sources : `lsst.afw.table.SourceCatalog`
751 Catalog of detected bright sources; modified to include columns
752 necessary for point source determination for the aperture correction
753 calculation.
754 """
755 norm_ap_corr_map = self.psf_normalized_calibration_flux.run(
756 exposure=exposure,
757 catalog=bright_sources,
758 ).ap_corr_map
759
760 ap_corr_map = self.measure_aperture_correction.run(exposure, bright_sources).apCorrMap
761
762 # Need to merge the aperture correction map from the normalization.
763 for key in norm_ap_corr_map:
764 ap_corr_map[key] = norm_ap_corr_map[key]
765
766 exposure.info.setApCorrMap(ap_corr_map)
767
768 def _find_stars(self, exposure, background, id_generator):
769 """Detect stars on an exposure that has a PSF model, and measure their
770 PSF, circular aperture, compensated gaussian fluxes.
771
772 Parameters
773 ----------
774 exposure : `lsst.afw.image.Exposure`
775 Exposure to detect and measure stars on.
776 background : `lsst.afw.math.BackgroundList`
777 Background that was fit to the exposure during detection;
778 modified in-place during subsequent detection.
779 id_generator : `lsst.meas.base.IdGenerator`
780 Object that generates source IDs and provides random seeds.
781
782 Returns
783 -------
784 stars : `SourceCatalog`
785 Sources that are very likely to be stars, with a limited set of
786 measurements performed on them.
787 """
788 table = afwTable.SourceTable.make(self.initial_stars_schema.schema,
789 id_generator.make_table_id_factory())
790 # Re-estimate the background during this detection step, so that
791 # measurement uses the most accurate background-subtraction.
792 detections = self.star_detection.run(table=table, exposure=exposure, background=background)
793 sources = detections.sources
794 self.star_sky_sources.run(exposure.mask, id_generator.catalog_id, sources)
795
796 # TODO investigation: Could this deblender throw away blends of non-PSF sources?
797 self.star_deblend.run(exposure=exposure, sources=sources)
798 # The deblender may not produce a contiguous catalog; ensure
799 # contiguity for subsequent tasks.
800 if not sources.isContiguous():
801 sources = sources.copy(deep=True)
802
803 # Measure everything, and use those results to select only stars.
804 self.star_measurement.run(sources, exposure)
805 self.metadata["post_deblend_source_count"] = np.sum(~sources["sky_source"])
806 self.metadata["saturated_source_count"] = np.sum(sources["base_PixelFlags_flag_saturated"])
807 self.metadata["bad_source_count"] = np.sum(sources["base_PixelFlags_flag_bad"])
808
809 # Run the normalization calibration flux task to apply the
810 # normalization correction to create normalized
811 # calibration fluxes.
812 self.star_normalized_calibration_flux.run(exposure=exposure, catalog=sources)
813 self.star_apply_aperture_correction.run(sources, exposure.apCorrMap)
814 self.star_catalog_calculation.run(sources)
815 self.star_set_primary_flags.run(sources)
816
817 result = self.star_selector.run(sources)
818 # The star selector may not produce a contiguous catalog.
819 if not result.sourceCat.isContiguous():
820 return result.sourceCat.copy(deep=True)
821 else:
822 return result.sourceCat
823
824 def _match_psf_stars(self, psf_stars, stars):
825 """Match calibration stars to psf stars, to identify which were psf
826 candidates, and which were used or reserved during psf measurement.
827
828 Parameters
829 ----------
830 psf_stars : `lsst.afw.table.SourceCatalog`
831 PSF candidate stars that were sent to the psf determiner. Used to
832 populate psf-related flag fields.
833 stars : `lsst.afw.table.SourceCatalog`
834 Stars that will be used for calibration; psf-related fields will
835 be updated in-place.
836
837 Notes
838 -----
839 This code was adapted from CalibrateTask.copyIcSourceFields().
840 """
841 control = afwTable.MatchControl()
842 # Return all matched objects, to separate blends.
843 control.findOnlyClosest = False
844 matches = afwTable.matchXy(psf_stars, stars, 3.0, control)
845 deblend_key = stars.schema["deblend_nChild"].asKey()
846 matches = [m for m in matches if m[1].get(deblend_key) == 0]
847
848 # Because we had to allow multiple matches to handle parents, we now
849 # need to prune to the best (closest) matches.
850 # Closest matches is a dict of psf_stars source ID to Match record
851 # (psf_stars source, sourceCat source, distance in pixels).
852 best = {}
853 for match_psf, match_stars, d in matches:
854 match = best.get(match_psf.getId())
855 if match is None or d <= match[2]:
856 best[match_psf.getId()] = (match_psf, match_stars, d)
857 matches = list(best.values())
858 # We'll use this to construct index arrays into each catalog.
859 ids = np.array([(match_psf.getId(), match_stars.getId()) for match_psf, match_stars, d in matches]).T
860
861 if (n_matches := len(matches)) == 0:
862 raise NoPsfStarsToStarsMatchError(n_psf_stars=len(psf_stars), n_stars=len(stars))
863
864 self.log.info("%d psf stars out of %d matched %d calib stars", n_matches, len(psf_stars), len(stars))
865 self.metadata["matched_psf_star_count"] = n_matches
866
867 # Check that no stars sources are listed twice; we already know
868 # that each match has a unique psf_stars id, due to using as the key
869 # in best above.
870 n_unique = len(set(m[1].getId() for m in matches))
871 if n_unique != n_matches:
872 self.log.warning("%d psf_stars matched only %d stars", n_matches, n_unique)
873
874 # The indices of the IDs, so we can update the flag fields as arrays.
875 idx_psf_stars = np.searchsorted(psf_stars["id"], ids[0])
876 idx_stars = np.searchsorted(stars["id"], ids[1])
877 for field in self.psf_fields:
878 result = np.zeros(len(stars), dtype=bool)
879 result[idx_stars] = psf_stars[field][idx_psf_stars]
880 stars[field] = result
881
882 def _fit_astrometry(self, exposure, stars):
883 """Fit an astrometric model to the data and return the reference
884 matches used in the fit, and the fitted WCS.
885
886 Parameters
887 ----------
888 exposure : `lsst.afw.image.Exposure`
889 Exposure that is being fit, to get PSF and other metadata from.
890 Modified to add the fitted skyWcs.
891 stars : `SourceCatalog`
892 Good stars selected for use in calibration, with RA/Dec coordinates
893 computed from the pixel positions and fitted WCS.
894
895 Returns
896 -------
897 matches : `list` [`lsst.afw.table.ReferenceMatch`]
898 Reference/stars matches used in the fit.
899 """
900 result = self.astrometry.run(stars, exposure)
901 return result.matches, result.matchMeta
902
903 def _fit_photometry(self, exposure, stars):
904 """Fit a photometric model to the data and return the reference
905 matches used in the fit, and the fitted PhotoCalib.
906
907 Parameters
908 ----------
909 exposure : `lsst.afw.image.Exposure`
910 Exposure that is being fit, to get PSF and other metadata from.
911 Has the fit `lsst.afw.image.PhotoCalib` attached, with pixel values
912 unchanged.
913 stars : `lsst.afw.table.SourceCatalog`
914 Good stars selected for use in calibration.
915
916 Returns
917 -------
918 calibrated_stars : `lsst.afw.table.SourceCatalog`
919 Star catalog with flux/magnitude columns computed from the fitted
920 photoCalib (instFlux columns are retained as well).
921 matches : `list` [`lsst.afw.table.ReferenceMatch`]
922 Reference/stars matches used in the fit.
923 matchMeta : `lsst.daf.base.PropertyList`
924 Metadata needed to unpersist matches, as returned by the matcher.
925 photo_calib : `lsst.afw.image.PhotoCalib`
926 Photometric calibration that was fit to the star catalog.
927 """
928 result = self.photometry.run(exposure, stars)
929 calibrated_stars = result.photoCalib.calibrateCatalog(stars)
930 exposure.setPhotoCalib(result.photoCalib)
931 return calibrated_stars, result.matches, result.matchMeta, result.photoCalib
932
933 def _apply_photometry(self, exposure, background):
934 """Apply the photometric model attached to the exposure to the
935 exposure's pixels and an associated background model.
936
937 Parameters
938 ----------
939 exposure : `lsst.afw.image.Exposure`
940 Exposure with the target `lsst.afw.image.PhotoCalib` attached.
941 On return, pixel values will be calibrated and an identity
942 photometric transform will be attached.
943 background : `lsst.afw.math.BackgroundList`
944 Background model to convert to nanojansky units in place.
945 """
946 photo_calib = exposure.getPhotoCalib()
947 exposure.maskedImage = photo_calib.calibrateImage(exposure.maskedImage)
948 identity = afwImage.PhotoCalib(1.0,
949 photo_calib.getCalibrationErr(),
950 bbox=exposure.getBBox())
951 exposure.setPhotoCalib(identity)
952 exposure.metadata["BUNIT"] = "nJy"
953
954 assert photo_calib._isConstant, \
955 "Background calibration assumes a constant PhotoCalib; PhotoCalTask should always return that."
956 for bg in background:
957 # The statsImage is a view, but we can't assign to a function call in python.
958 binned_image = bg[0].getStatsImage()
959 binned_image *= photo_calib.getCalibrationMean()
960
961 def _summarize(self, exposure, stars, background):
962 """Compute summary statistics on the exposure and update in-place the
963 calibrations attached to it.
964
965 Parameters
966 ----------
967 exposure : `lsst.afw.image.Exposure`
968 Exposure that was calibrated, to get PSF and other metadata from.
969 Should be in instrumental units with the photometric calibration
970 attached.
971 Modified to contain the computed summary statistics.
972 stars : `SourceCatalog`
973 Good stars selected used in calibration.
974 background : `lsst.afw.math.BackgroundList`
975 Background that was fit to the exposure during detection of the
976 above stars. Should be in instrumental units.
977 """
978 summary = self.compute_summary_stats.run(exposure, stars, background)
979 exposure.info.setSummaryStats(summary)
980
981 def _recordMaskedPixelFractions(self, exposure):
982 """Record the fraction of all the pixels in an exposure
983 that are masked with a given flag. Each fraction is
984 recorded in the task metadata. One record per flag type.
985
986 Parameters
987 ----------
988 exposure : `lsst.afw.image.ExposureF`
989 The target exposure to calculate masked pixel fractions for.
990 """
991
992 mask = exposure.mask
993 maskPlanes = list(mask.getMaskPlaneDict().keys())
994 for maskPlane in maskPlanes:
995 self.metadata[f"{maskPlane.lower()}_mask_fraction"] = (
996 evaluateMaskFraction(mask, maskPlane)
997 )
The photometric calibration of an exposure.
Definition PhotoCalib.h:114
Pass parameters to algorithms that match list of sources.
Definition Match.h:45
runQuantum(self, butlerQC, inputRefs, outputRefs)
run(self, *exposures, id_generator=None, result=None)
_measure_aperture_correction(self, exposure, bright_sources)
_find_stars(self, exposure, background, id_generator)
__init__(self, initial_stars_schema=None, **kwargs)
_summarize(self, exposure, stars, background)
SourceMatchVector matchXy(SourceCatalog const &cat1, SourceCatalog const &cat2, double radius, MatchControl const &mc=MatchControl())
Compute all tuples (s1,s2,d) where s1 belings to cat1, s2 belongs to cat2 and d, the distance between...
Definition Match.cc:305