105.2. Detect and measure sources#
105.2. Detect and measure sources¶
For the Rubin Science Platform at data.lsst.cloud.
Data Release: Data Preview 2
Container Size: Large
LSST Science Pipelines version: r30.0.11
Last verified to run: 2026-11-16
Repository: github.com/lsst/tutorial-notebooks
DOI: 10.11578/rubin/dc.20250909.20
Learning objective: How to run source detection, deblending, and measurement tasks on a deep coadd image.
LSST data products: deep_coadd
Packages: lsst.meas.algorithms, lsst.meas.deblender, lsst.meas.base, lsst.images, lsst.daf.butler, lsst.afw.table
Credit: Originally developed by Alex Drlica-Wagner and Imran Hasan in the context of the LSST Stack Club and later refined by the Rubin Community Science team. Please consider acknowledging them if this notebook is used for the preparation of journal articles, software releases, or other notebooks.
Get Support: Everyone is encouraged to ask questions or raise issues in the Support Category of the Rubin Community Forum. Rubin staff will respond to all questions posted there.
Warning: This tutorial works with the
deep_coaddas anlsst.imagesCellCoaddobject (https://images.lsst.io/). However, the source detection, deblending, and measurement tasks demonstrated here require anExposureFobject, which is being deprecated in favor oflsst.imagesobjects. Thedeep_coaddis therefore converted to anExposureFonly for running those tasks (Section 2.4).
1. Introduction¶
The lsst.meas.algorithms, lsst.meas.deblender, and lsst.meas.base packages provide the high-level pipeline tasks useful for source detection, deblending, and measurement. Of particular importance for this tutorial are the SourceDetectionTask, the SourceDeblendTask, and the SingleFrameMeasurementTask.
Documentation related to the source detection, deblending, and measurement tasks:
- LSST Science Pipelines main page
- SourceDetectionTask page
- SourceDeblendTask page
- SingleFrameMeasurementTask page
This tutorial provides a brief introduction to running the LSST Science Pipelines source detection, deblending, and measurement tasks on a deep_coadd image.
Related tutorials: The first 100-level tutorial in this series provides a basic introduction to using the LSST Science Pipelines; later tutorials in this series demonstrate other image analysis techniques available with the LSST Science Pipelines.
1.1. Import packages¶
Import matplotlib, a comprehensive library for data visualization
(matplotlib.org).
Tools from Astropy will be used to work with sky coordinates and units.
From the LSST Science Pipelines, import modules for butler data access (lsst.daf.butler), for image display (lsst.afw.display), for table handling (lsst.afw.table), and for various tasks for source detection (lsst.meas.algorithms.detection), deblending (lsst.meas.deblender), and measurement (lsst.meas.base).
import matplotlib.pyplot as plt
from astropy.coordinates import SkyCoord, Angle
import astropy.units as u
import lsst.daf.base as dafBase
from lsst.daf.butler import Butler
import lsst.afw.display as afwDisplay
import lsst.afw.table as afwTable
from lsst.meas.algorithms.detection import SourceDetectionTask
from lsst.meas.deblender import SourceDeblendTask
from lsst.meas.base import SingleFrameMeasurementTask
1.2. Define parameters and functions¶
Create an instance of the butler with the repository and collection for DP2, and assert that it exists.
butler = Butler("dp2", collections="dp2")
assert butler is not None
Define the approximate central coordinates of the Extended Chandra Deep Field South (ECDFS) field (in degrees).
ra = 53.13
dec = -28.10
Set afwDisplay to use matplotlib, so that images are displayed directly within this notebook.
afwDisplay.setDefaultBackend("matplotlib")
2. Source detection, deblending, and measurement¶
Learn how to perform source detection, deblending, and measurement on a deep_coadd.
A deep_coadd is built by stacking visit images that have been warped onto a common pixel grid.
Several of its properties matter for detection, deblending, and measurement:
- dataId and geometry: Coadds are divided into tracts and patches of a
skymap, so thedataIdhastract,patch,band, andskymap. The pixel coordinates are those of the whole tract, so a patch's bounding box typically does not start at (0, 0). - Depth: The coadd is much deeper than any single visit, so many faint sources are detected, and blending of neighboring sources is common.
- Background: The input images were background-subtracted before coaddition, so only a minimal (or no) re-estimation of the background is necessary.
- Noise: Warping correlates the noise between neighboring pixels, and the depth varies across the patch depending on how many visits contributed to each location.
- PSF: DP2 coadds are cell-based: each patch is divided into cells, and each cell has its own PSF model built from the visits that contributed to it. These are combined into a single PSF object (a
CellPointSpreadFunctioninlsst.images), so the PSF can change slightly from one cell to the next.
Note: The production Rubin pipeline processes coadds with dedicated tasks (
DetectCoaddSourcesTask, the multi-band Scarlet deblender,MeasureMergedCoaddSourcesTask, and forced photometry) to create theObjecttable. The single-band processing here is a simplified analog meant to show the basic building blocks; the results will not match theObjecttable exactly.
The LSST Science Pipelines' source detection, deblending, and measurement tasks were imported in the first code cell.
2.1. Select a deep coadd¶
Using the approximate coordinates of the center of the ECDFS field as declared in Section 1.2, identify an r-band deep_coadd patch that contains that position.
First, prepare the query and bind parameters.
query = "band.name = band AND patch.region OVERLAPS POINT(ra, dec)"
print(query)
bind_params = {"band": 'r', "ra": ra, "dec": dec}
print(bind_params)
band.name = band AND patch.region OVERLAPS POINT(ra, dec)
{'band': 'r', 'ra': 53.13, 'dec': -28.1}
Next, perform the query for datasets with the butler. Neighboring patches overlap slightly, so a position can fall in more than one patch. Limit the number of patches returned to 1. Save the dataId.
dataset_refs = butler.query_datasets("deep_coadd",
where=query,
bind=bind_params,
limit=1)
assert len(dataset_refs) == 1
ref = dataset_refs[0]
dataId = ref.dataId
print(dataId)
del dataset_refs
{band: 'r', skymap: 'lsst_cells_v2', tract: 5063, patch: 14}
Retrieve the deep_coadd for this dataId from the butler.
By default, the butler returns a deep_coadd as an lsst.images CellCoadd object.
Print its type and its pixel units.
deep_coadd = butler.get('deep_coadd', dataId=dataId)
print(type(deep_coadd))
print('Pixel units: ', deep_coadd.unit)
<class 'lsst.images.cells._coadd.CellCoadd'> Pixel units: nJy
Print the bounding box (bbox) and the type of PSF. The minimum corner of the bounding box is not (0, 0), because the patch's pixels are positioned within the larger tract.
print('deep_coadd bbox:', deep_coadd.bbox)
print('deep_coadd PSF type:', type(deep_coadd.psf).__name__)
deep_coadd bbox: [y=2850:6150, x=11850:15150] deep_coadd PSF type: CellPointSpreadFunction
Print the names of the mask planes.
The DETECTED plane marks pixels that were part of sources detected when the coadd was processed by the production pipeline.
Source detection is re-done in this notebook, so this plane is cleared before detection in Section 2.4.
print(sorted(deep_coadd.mask.schema.names))
['CLIPPED', 'COSMIC_RAY', 'DETECTED', 'DETECTION_EDGE', 'INEXACT_PSF', 'INTERPOLATED', 'NO_DATA', 'REJECTED', 'SATURATED']
2.2. Source table schema¶
The schema describes the output properties that will be measured for each source. The schema needs to be passed to all of the tasks, each of which will add columns to the schema when it runs.
Create a minimal schema for a source table.
schema = afwTable.SourceTable.makeMinimalSchema()
print(schema)
Schema(
(Field['L'](name="id", doc="unique ID"), Key<L>(offset=0, nElements=1)),
(Field['Angle'](name="coord_ra", doc="position in ra/dec"), Key<Angle>(offset=8, nElements=1)),
(Field['Angle'](name="coord_dec", doc="position in ra/dec"), Key<Angle>(offset=16, nElements=1)),
(Field['L'](name="parent", doc="unique ID of parent source"), Key<L>(offset=24, nElements=1)),
)
Add coord_raErr and coord_decErr to the minimal schema to avoid warnings
from sourceMeasurementTask in Section 2.5, which expects these columns to exist.
raerr = schema.addField("coord_raErr", type="F")
decerr = schema.addField("coord_decErr", type="F")
Create a container which will be used to record metadata about algorithm execution.
algMetadata = dafBase.PropertyList()
2.3. Configure the tasks¶
Each task possesses an associated configuration class. The properties of these configuration classes can be determined from the classes themselves.
Option: uncomment the following line to view the help documentation for the SourceDetectionTask configuration.
Replace SourceDetectionTask with another task name to view its help documentation.
# help(SourceDetectionTask.ConfigClass())
Set the basic configuration parameters and instantiate each task in turn.
SourceDetectionTask detects sources.
Set the configuration for the detection threshold to 4 (the default for LSST coadds is 5) in order to detect sub-threshold (faint) sources. Some of the faint detections will be spurious due to pixel noise.
Set the detection threshold type to be pixel_stdev, which means the threshold is applied to each pixel's own standard deviation, taken from the coadd's variance plane.
This tracks the varying depth across the patch better than the stdev option, which applies the threshold to a single standard deviation for the whole image.
In other words, this configuration using pixel_stdev will detect sources at $4\sigma$ relative to the local noise.
Two further settings, similar to those used for coadds in the production pipeline, are also applied:
reEstimateBackground = False: the background was already subtracted from the input visits.isotropicGrow = True: grow footprints isotropically, which gives better footprint shapes for extended sources.
config = SourceDetectionTask.ConfigClass()
config.thresholdValue = 4
config.thresholdType = "pixel_stdev"
config.reEstimateBackground = False
config.isotropicGrow = True
sourceDetectionTask = SourceDetectionTask(schema=schema, config=config)
del config
SourceDeblendTask deblends overlapping sources into "parent" and "child" sources. The parent record represents the whole blend, and the children are the deblender's estimates of the individual objects within it.
No configuration changes are needed for this tutorial. When no config argument is passed, a task uses its default configuration, so there is no need to create a configuration object explicitly unless some of its defaults are to be changed.
sourceDeblendTask = SourceDeblendTask(schema=schema)
SingleFrameMeasurementTask measures the properties of the deblended sources.
No special configuration is needed for this tutorial. Note that SingleFrameMeasurementTask is indeed the correct task to run on a coadded image, in that the single coadd image is being analyzed on its own rather than in a forced photometry or multi-image manner.
sourceMeasurementTask = SingleFrameMeasurementTask(schema=schema,
algMetadata=algMetadata)
Create a SourceTable called tab using the minimal schema. It will hold the output of the analysis in the following section.
tab = afwTable.SourceTable.make(schema)
2.3.1. Re-configure tasks and explore methods¶
The configuration parameters cannot be changed after the task is constructed. To change a configuration parameter, redefine it and then also redefine the task.
For example, to change the detection threshold value used by source detection:
config.thresholdValue = 10
sourceDetectionTask = SourceDetectionTask(schema=schema, config=config)
Option: To explore a task, use the help function on the task or any of its methods.
# help(SourceDetectionTask)
# help(SourceDetectionTask.getPsf)
Option: To see a pop-up list of all methods for a given task, uncomment this line, place the cursor after the period, and press tab. Then re-comment the line. Do not execute the cell.
# SourceDetectionTask.
Now, as schema is no longer needed, delete it.
del schema
2.4. Source detection¶
The detection, deblending, and measurement tasks require their input image as an ExposureF.
Use the to_legacy method of the CellCoadd to create an ExposureF version of the deep_coadd, which carries the coadd's PSF (as a StitchedPsf, the legacy counterpart of the CellPointSpreadFunction), WCS, and photometric calibration.
The tasks modify their input image: detection sets the DETECTED mask plane, and measurement temporarily replaces neighboring sources with noise while measuring each source.
Setting copy=True makes the ExposureF an independent copy of the pixel data, so that the original deep_coadd, which is used for display in Section 2.6, is not affected.
legacy_coadd = deep_coadd.to_legacy(copy=True)
print(type(legacy_coadd))
<class 'lsst.afw.image._exposure.ExposureF'>
Clear the DETECTED information from the mask of the ExposureF, as source detection is re-done below.
legacy_coadd.mask.removeAndClearMaskPlane('DETECTED')
Run source detection by calling the run method of the SourceDetectionTask, which takes in-memory objects (here, the SourceTable and the ExposureF version of the coadd) and returns its results directly. The deblending and measurement tasks are run the same way in Section 2.5.
Calling run directly is convenient for running a single task interactively in a notebook, but it is not how tasks are run in production. There, tasks are combined into pipelines and executed by the pipeline framework, which reads each task’s inputs from the Butler and writes its outputs back to it.
result = sourceDetectionTask.run(tab, legacy_coadd)
lsst.sourceDetection INFO: Threshold scaling factor for positive detections is: 1.000. For negative detections it is: 1.000
lsst.sourceDetection INFO: Detected 8051 positive peaks in 4448 footprints to 4 +ve and 4 -ve sigma
Print the number of positive peaks detected.
result.numPosPeaks
8051
Create sources to hold the detected sources from the results.
sources = result.sources
print(len(sources))
4448
With thresholdValue set to 4, roughly 4,400 sources are detected, containing roughly 8,000 positive peaks.
Each source is a footprint: a connected region of pixels above the threshold. A footprint can contain more than one peak, and those that do are candidates for deblending in Section 2.5.
Had the thresholdValue been set instead to 5, there would have been only roughly 3,900 sources detected, about 12% fewer.
Option: Display sources to see that most of the columns are NaN at first.
# sources
2.5. Source deblending and measurement¶
Run the SourceDeblendTask and SingleFrameMeasurementTask. Both run methods require the image (here, the ExposureF version of the coadd) and the catalog of detected sources; note that the two tasks take them in a different order.
As in Section 2.3.1, use help to see the required and optional inputs of each method, for example help(SourceDeblendTask.run) or help(SourceMeasurementTask.run).
sourceDeblendTask.run(legacy_coadd, sources)
lsst.sourceDeblend INFO: Deblending 4448 sources
lsst.sourceDeblend INFO: Deblended: of 4448 sources, 1404 were deblended, creating 4436 children, total 8884 sources
sourceMeasurementTask.run(measCat=sources, exposure=legacy_coadd)
lsst.measurement INFO: Measuring 8884 sources
lsst.measurement.base_PsfFlux WARNING: Exception in base_PsfFlux.measure on record 9: File "src/PsfFlux.cc", line 120, in virtual void lsst::meas::base::PsfFluxAlgorithm::measure(lsst::afw::table::SourceRecord&, const lsst::afw::image::Exposure<float>&) const Invalid pixel value detected in image. {0} lsst::meas::base::PixelValueError: 'Invalid pixel value detected in image.'
lsst.measurement.base_PsfFlux WARNING: Exception in base_PsfFlux.measure on record 4449: File "src/PsfFlux.cc", line 120, in virtual void lsst::meas::base::PsfFluxAlgorithm::measure(lsst::afw::table::SourceRecord&, const lsst::afw::image::Exposure<float>&) const Invalid pixel value detected in image. {0} lsst::meas::base::PixelValueError: 'Invalid pixel value detected in image.'
lsst.measurement.base_PsfFlux WARNING: Exception in base_PsfFlux.measure on record 4450: File "src/PsfFlux.cc", line 120, in virtual void lsst::meas::base::PsfFluxAlgorithm::measure(lsst::afw::table::SourceRecord&, const lsst::afw::image::Exposure<float>&) const Invalid pixel value detected in image. {0} lsst::meas::base::PixelValueError: 'Invalid pixel value detected in image.'
lsst.measurement.base_PsfFlux WARNING: Exception in base_PsfFlux.measure on record 7103: File "src/PsfFlux.cc", line 120, in virtual void lsst::meas::base::PsfFluxAlgorithm::measure(lsst::afw::table::SourceRecord&, const lsst::afw::image::Exposure<float>&) const Invalid pixel value detected in image. {0} lsst::meas::base::PixelValueError: 'Invalid pixel value detected in image.'
lsst.measurement.base_PsfFlux WARNING: Exception in base_PsfFlux.measure on record 7104: File "src/PsfFlux.cc", line 120, in virtual void lsst::meas::base::PsfFluxAlgorithm::measure(lsst::afw::table::SourceRecord&, const lsst::afw::image::Exposure<float>&) const Invalid pixel value detected in image. {0} lsst::meas::base::PixelValueError: 'Invalid pixel value detected in image.'
The measurement step logs a few WARNING messages from the base_PsfFlux plugin about an invalid pixel value.
These are expected: they occur when pixels without valid data (for example, near the patch edges or in masked areas) fall under the PSF model of a source.
When a measurement plugin fails, the measurement framework catches the error, sets a flag for that source (here, base_PsfFlux_flag), and continues; the source's other measurements, and all other sources, are unaffected.
Ensure that the sources catalog is contiguous (sequential) in memory by making a copy.
sources = sources.copy(True)
Count the number of isolated sources, blend parents, and deblended children.
n_isolated = ((sources['parent'] == 0) & (sources['deblend_nChild'] == 0)).sum()
n_blend = (sources['deblend_nChild'] > 0).sum()
n_child = (sources['parent'] != 0).sum()
print(f'{n_isolated} isolated sources, {n_blend} blend parents, {n_child} deblended children')
print(f'{n_isolated + n_child} objects (isolated sources plus deblended children)')
3044 isolated sources, 1404 blend parents, 4436 deblended children 7480 objects (isolated sources plus deblended children)
Blend parents are left out of the object count because each one describes a whole blend whose objects already appear as its children.
Option: Display the sources catalog as an astropy table, which has a nice, human-readable output format.
# sources.asAstropy()
Option: Write the sources to a FITS table, or save the deep_coadd as a FITS file, in the current directory.
# sources.writeFits("NB_105_2_sources.fits")
# deep_coadd.write("NB_105_2_deep_coadd.fits")
2.6. Visualize sources on an image cutout¶
Overplot the detected sources on a cutout image of the deep_coadd using afwDisplay.
Use the bbox_from_sky_circle method of the CellCoadd to compute the bounding box of a circle on the sky, centered on the ECDFS coordinates from Section 1.2, with a radius of 30 arcseconds (150 pixels).
This gives a cutout about 300 pixels wide and 300 pixels high.
Setting clip=True clips the bounding box to the patch, in case the circle extends past the patch edge.
The bounding box is in the tract's pixel coordinates.
center = SkyCoord(ra=ra, dec=dec, unit='deg')
bbox = deep_coadd.bbox_from_sky_circle(center, Angle(30, u.arcsec), clip=True)
print(bbox)
[y=4420:4721, x=14175:14476]
Option: Display the bbox information.
# bbox
Generate the cutout.
Indexing an lsst.images image with a bounding box (e.g., deep_coadd.image[bbox]) interprets the box in the image's own pixel coordinates, here those of the tract, and returns a new Image covering that region.
cutout = deep_coadd.image[bbox]
Get the centroid pixel coordinates of all sources from the sources catalog, and use the contains method of the bounding box to select those that lie within the cutout.
The source positions are in the tract's pixel coordinates, the same as bbox, so they can be compared directly.
Then select isolated sources, deblended children, and blend parents.
xs = sources['slot_Centroid_x']
ys = sources['slot_Centroid_y']
in_cutout = bbox.contains(x=xs, y=ys)
isolated = in_cutout & (sources['parent'] == 0) & (sources['deblend_nChild'] == 0)
child = in_cutout & (sources['parent'] != 0)
blend = in_cutout & (sources['deblend_nChild'] > 0)
Display the cutout with afwDisplay.
afwDisplay accepts lsst.images objects directly, and uses the image's sky projection as its WCS, so the axes are labeled in RA and Dec.
Mark isolated sources with orange circles, deblended children with cyan circles, and blend parents with magenta plus marks, at their pixel positions from the sources catalog.
fig = plt.figure(figsize=(7, 7))
display = afwDisplay.Display(frame=fig)
display.scale('asinh', 'zscale')
display.mtv(cutout)
for x, y in zip(xs[isolated], ys[isolated]):
display.dot('o', x, y, size=8, ctype='orange')
for x, y in zip(xs[child], ys[child]):
display.dot('o', x, y, size=8, ctype='cyan')
for x, y in zip(xs[blend], ys[blend]):
display.dot('+', x, y, size=6, ctype='magenta')
plt.title('deep_coadd')
plt.show()
Figure 1: Sources found via running detection and deblending on the deep coadd, marked with orange circles (isolated sources), cyan circles (deblended children), and magenta plus marks (blend parents). Only a small subregion of the full deep coadd is shown here. Many of the faint sources revealed by the depth of the coadd lie close to other sources, and have been split into deblended children.