27from lsst.pipe.base import (CmdLineTask, Struct, ArgumentParser, ButlerInitializedTaskRunner,
28 PipelineTask, PipelineTaskConfig, PipelineTaskConnections)
29import lsst.pipe.base.connectionTypes
as cT
32from lsst.meas.base import SingleFrameMeasurementTask, ApplyApCorrTask, CatalogCalculationTask
34from lsst.meas.extensions.scarlet
import ScarletDeblendTask
46from lsst.obs.base
import ExposureIdInfo
49from .mergeDetections
import MergeDetectionsConfig, MergeDetectionsTask
50from .mergeMeasurements
import MergeMeasurementsConfig, MergeMeasurementsTask
51from .multiBandUtils
import MergeSourcesRunner, CullPeaksConfig, _makeGetSchemaCatalogs
52from .multiBandUtils
import getInputSchema, readCatalog, _makeMakeIdFactory
53from .deblendCoaddSourcesPipeline
import DeblendCoaddSourcesSingleConfig
54from .deblendCoaddSourcesPipeline
import DeblendCoaddSourcesSingleTask
55from .deblendCoaddSourcesPipeline
import DeblendCoaddSourcesMultiConfig
56from .deblendCoaddSourcesPipeline
import DeblendCoaddSourcesMultiTask
61* deepCoadd_det: detections from what used to be processCoadd (tract, patch, filter)
62* deepCoadd_mergeDet: merged detections (tract, patch)
63* deepCoadd_meas: measurements of merged detections (tract, patch, filter)
64* deepCoadd_ref: reference sources (tract, patch)
65All of these have associated *_schema catalogs that require no data ID and hold no records.
67In addition, we have a schema-only dataset, which saves the schema for the PeakRecords in
68the mergeDet, meas, and ref dataset Footprints:
69* deepCoadd_peak_schema
75 dimensions=(
"tract",
"patch",
"band",
"skymap"),
76 defaultTemplates={
"inputCoaddName":
"deep",
"outputCoaddName":
"deep"}):
77 detectionSchema = cT.InitOutput(
78 doc=
"Schema of the detection catalog",
79 name=
"{outputCoaddName}Coadd_det_schema",
80 storageClass=
"SourceCatalog",
83 doc=
"Exposure on which detections are to be performed",
84 name=
"{inputCoaddName}Coadd",
85 storageClass=
"ExposureF",
86 dimensions=(
"tract",
"patch",
"band",
"skymap")
88 outputBackgrounds = cT.Output(
89 doc=
"Output Backgrounds used in detection",
90 name=
"{outputCoaddName}Coadd_calexp_background",
91 storageClass=
"Background",
92 dimensions=(
"tract",
"patch",
"band",
"skymap")
94 outputSources = cT.Output(
95 doc=
"Detected sources catalog",
96 name=
"{outputCoaddName}Coadd_det",
97 storageClass=
"SourceCatalog",
98 dimensions=(
"tract",
"patch",
"band",
"skymap")
100 outputExposure = cT.Output(
101 doc=
"Exposure post detection",
102 name=
"{outputCoaddName}Coadd_calexp",
103 storageClass=
"ExposureF",
104 dimensions=(
"tract",
"patch",
"band",
"skymap")
108class DetectCoaddSourcesConfig(PipelineTaskConfig, pipelineConnections=DetectCoaddSourcesConnections):
110 @anchor DetectCoaddSourcesConfig_
112 @brief Configuration parameters
for the DetectCoaddSourcesTask
114 doScaleVariance = Field(dtype=bool, default=True, doc=
"Scale variance plane using empirical noise?")
115 scaleVariance = ConfigurableField(target=ScaleVarianceTask, doc=
"Variance rescaling")
116 detection = ConfigurableField(target=DynamicDetectionTask, doc=
"Source detection")
117 coaddName = Field(dtype=str, default=
"deep", doc=
"Name of coadd")
118 doInsertFakes = Field(dtype=bool, default=
False,
119 doc=
"Run fake sources injection task")
120 insertFakes = ConfigurableField(target=BaseFakeSourcesTask,
121 doc=
"Injection of fake sources for testing "
122 "purposes (must be retargeted)")
126 doc=
"Should be set to True if fake sources have been inserted into the input data."
129 def setDefaults(self):
130 super().setDefaults()
131 self.detection.thresholdType =
"pixel_stdev"
132 self.detection.isotropicGrow =
True
134 self.detection.reEstimateBackground =
False
135 self.detection.background.useApprox =
False
136 self.detection.background.binSize = 4096
137 self.detection.background.undersampleStyle =
'REDUCE_INTERP_ORDER'
138 self.detection.doTempWideBackground =
True
148class DetectCoaddSourcesTask(PipelineTask, CmdLineTask):
150 @anchor DetectCoaddSourcesTask_
152 @brief Detect sources on a coadd
154 @section pipe_tasks_multiBand_Contents Contents
156 -
@ref pipe_tasks_multiBand_DetectCoaddSourcesTask_Purpose
157 -
@ref pipe_tasks_multiBand_DetectCoaddSourcesTask_Initialize
158 -
@ref pipe_tasks_multiBand_DetectCoaddSourcesTask_Run
159 -
@ref pipe_tasks_multiBand_DetectCoaddSourcesTask_Config
160 -
@ref pipe_tasks_multiBand_DetectCoaddSourcesTask_Debug
161 -
@ref pipe_tasks_multiband_DetectCoaddSourcesTask_Example
163 @section pipe_tasks_multiBand_DetectCoaddSourcesTask_Purpose Description
165 Command-line task that detects sources on a coadd of exposures obtained
with a single filter.
167 Coadding individual visits requires each exposure to be warped. This introduces covariance
in the noise
168 properties across pixels. Before detection, we correct the coadd variance by scaling the variance plane
169 in the coadd to match the observed variance. This
is an approximate approach -- strictly, we should
170 propagate the full covariance matrix -- but it
is simple
and works well
in practice.
172 After scaling the variance plane, we detect sources
and generate footprints by delegating to the
@ref
173 SourceDetectionTask_
"detection" subtask.
176 deepCoadd{tract,patch,filter}: ExposureF
178 deepCoadd_det{tract,patch,filter}: SourceCatalog (only parent Footprints)
179 @n deepCoadd_calexp{tract,patch,filter}: Variance scaled, background-subtracted input
181 @n deepCoadd_calexp_background{tract,patch,filter}: BackgroundList
185 DetectCoaddSourcesTask delegates most of its work to the
@ref SourceDetectionTask_
"detection" subtask.
186 You can retarget this subtask
if you wish.
188 @section pipe_tasks_multiBand_DetectCoaddSourcesTask_Initialize Task initialization
190 @copydoc \_\_init\_\_
192 @section pipe_tasks_multiBand_DetectCoaddSourcesTask_Run Invoking the Task
196 @section pipe_tasks_multiBand_DetectCoaddSourcesTask_Config Configuration parameters
198 See
@ref DetectCoaddSourcesConfig_
"DetectSourcesConfig"
200 @section pipe_tasks_multiBand_DetectCoaddSourcesTask_Debug Debug variables
202 The command line task interface supports a
203 flag
@c -d to
import @b debug.py
from your
@c PYTHONPATH; see
@ref baseDebug
for more about
@b debug.py
206 DetectCoaddSourcesTask has no debug variables of its own because it relegates all the work to
207 @ref SourceDetectionTask_
"SourceDetectionTask"; see the documetation
for
208 @ref SourceDetectionTask_
"SourceDetectionTask" for further information.
210 @section pipe_tasks_multiband_DetectCoaddSourcesTask_Example A complete example
211 of using DetectCoaddSourcesTask
213 DetectCoaddSourcesTask
is meant to be run after assembling a coadded image
in a given band. The purpose of
214 the task
is to update the background, detect all sources
in a single band
and generate a set of parent
215 footprints. Subsequent tasks
in the multi-band processing procedure will merge sources across bands
and,
216 eventually, perform forced photometry. Command-line usage of DetectCoaddSourcesTask expects a data
217 reference to the coadd to be processed. A list of the available optional arguments can be obtained by
218 calling detectCoaddSources.py
with the `--help` command line argument:
220 detectCoaddSources.py --help
223 To demonstrate usage of the DetectCoaddSourcesTask
in the larger context of multi-band processing, we
224 will process HSC data
in the [ci_hsc](https://github.com/lsst/ci_hsc) package. Assuming one has followed
225 steps 1 - 4 at
@ref pipeTasks_multiBand, one may detect all the sources
in each coadd
as follows:
227 detectCoaddSources.py $CI_HSC_DIR/DATA --id patch=5,4 tract=0 filter=HSC-I
229 that will process the HSC-I band data. The results are written to
230 `$CI_HSC_DIR/DATA/deepCoadd-results/HSC-I`.
232 It
is also necessary to run:
234 detectCoaddSources.py $CI_HSC_DIR/DATA --id patch=5,4 tract=0 filter=HSC-R
236 to generate the sources catalogs
for the HSC-R band required by the next step
in the multi-band
237 processing procedure:
@ref MergeDetectionsTask_
"MergeDetectionsTask".
239 _DefaultName = "detectCoaddSources"
240 ConfigClass = DetectCoaddSourcesConfig
241 getSchemaCatalogs = _makeGetSchemaCatalogs(
"det")
242 makeIdFactory = _makeMakeIdFactory(
"CoaddId")
245 def _makeArgumentParser(cls):
246 parser = ArgumentParser(name=cls._DefaultName)
247 parser.add_id_argument(
"--id",
"deepCoadd", help=
"data ID, e.g. --id tract=12345 patch=1,2 filter=r",
248 ContainerClass=ExistingCoaddDataIdContainer)
251 def __init__(self, schema=None, **kwargs):
253 @brief Initialize the task. Create the
@ref SourceDetectionTask_
"detection" subtask.
255 Keyword arguments (
in addition to those forwarded to CmdLineTask.__init__):
257 @param[
in] schema: initial schema
for the output catalog, modified-
in place to include all
258 fields set by this task. If
None, the source minimal schema will be used.
259 @param[
in] **kwargs: keyword arguments to be passed to lsst.pipe.base.task.Task.__init__
263 super().__init__(**kwargs)
265 schema = afwTable.SourceTable.makeMinimalSchema()
266 if self.config.doInsertFakes:
267 self.makeSubtask(
"insertFakes")
269 self.makeSubtask(
"detection", schema=self.schema)
270 if self.config.doScaleVariance:
271 self.makeSubtask(
"scaleVariance")
273 self.detectionSchema = afwTable.SourceCatalog(self.schema)
275 def runDataRef(self, patchRef):
277 @brief Run detection on a coadd.
279 Invokes
@ref run
and then uses
@ref write to output the
282 @param[
in] patchRef: data reference
for patch
284 if self.config.hasFakes:
285 exposure = patchRef.get(
"fakes_" + self.config.coaddName +
"Coadd", immediate=
True)
287 exposure = patchRef.get(self.config.coaddName +
"Coadd", immediate=
True)
288 expId = getGen3CoaddExposureId(patchRef, coaddName=self.config.coaddName, log=self.log)
289 results = self.run(exposure, self.makeIdFactory(patchRef), expId=expId)
290 self.write(results, patchRef)
293 def runQuantum(self, butlerQC, inputRefs, outputRefs):
294 inputs = butlerQC.get(inputRefs)
295 exposureIdInfo = ExposureIdInfo.fromDataId(butlerQC.quantum.dataId,
"tract_patch_band")
296 inputs[
"idFactory"] = exposureIdInfo.makeSourceIdFactory()
297 inputs[
"expId"] = exposureIdInfo.expId
298 outputs = self.run(**inputs)
299 butlerQC.put(outputs, outputRefs)
301 def run(self, exposure, idFactory, expId):
303 @brief Run detection on an exposure.
305 First scale the variance plane to match the observed variance
306 using
@ref ScaleVarianceTask. Then invoke the
@ref SourceDetectionTask_
"detection" subtask to
309 @param[
in,out] exposure: Exposure on which to detect (may be backround-subtracted
and scaled,
310 depending on configuration).
311 @param[
in] idFactory: IdFactory to set source identifiers
312 @param[
in] expId: Exposure identifier (integer)
for RNG seed
314 @return a pipe.base.Struct
with fields
315 - sources: catalog of detections
316 - backgrounds: list of backgrounds
318 if self.config.doScaleVariance:
319 varScale = self.scaleVariance.run(exposure.maskedImage)
320 exposure.getMetadata().add(
"VARIANCE_SCALE", varScale)
321 backgrounds = afwMath.BackgroundList()
322 if self.config.doInsertFakes:
323 self.insertFakes.run(exposure, background=backgrounds)
324 table = afwTable.SourceTable.make(self.schema, idFactory)
325 detections = self.detection.run(table, exposure, expId=expId)
326 sources = detections.sources
327 fpSets = detections.fpSets
328 if hasattr(fpSets,
"background")
and fpSets.background:
329 for bg
in fpSets.background:
330 backgrounds.append(bg)
331 return Struct(outputSources=sources, outputBackgrounds=backgrounds, outputExposure=exposure)
333 def write(self, results, patchRef):
335 @brief Write out results
from runDetection.
337 @param[
in] exposure: Exposure to write out
338 @param[
in] results: Struct returned
from runDetection
339 @param[
in] patchRef: data reference
for patch
341 coaddName = self.config.coaddName + "Coadd"
342 patchRef.put(results.outputBackgrounds, coaddName +
"_calexp_background")
343 patchRef.put(results.outputSources, coaddName +
"_det")
344 if self.config.hasFakes:
345 patchRef.put(results.outputExposure,
"fakes_" + coaddName +
"_calexp")
347 patchRef.put(results.outputExposure, coaddName +
"_calexp")
352class DeblendCoaddSourcesConfig(Config):
353 """DeblendCoaddSourcesConfig
355 Configuration parameters for the `DeblendCoaddSourcesTask`.
357 singleBandDeblend = ConfigurableField(target=SourceDeblendTask,
358 doc="Deblend sources separately in each band")
359 multiBandDeblend = ConfigurableField(target=ScarletDeblendTask,
360 doc=
"Deblend sources simultaneously across bands")
361 simultaneous = Field(dtype=bool,
363 doc=
"Simultaneously deblend all bands? "
364 "True uses `multibandDeblend` while False uses `singleBandDeblend`")
365 coaddName = Field(dtype=str, default=
"deep", doc=
"Name of coadd")
366 hasFakes = Field(dtype=bool,
368 doc=
"Should be set to True if fake sources have been inserted into the input data.")
370 def setDefaults(self):
371 Config.setDefaults(self)
372 self.singleBandDeblend.propagateAllPeaks =
True
376 """Task runner for the `MergeSourcesTask`
378 Required because the run method requires a list of
379 dataRefs rather than a single dataRef.
382 def getTargetList(parsedCmd, **kwargs):
383 """Provide a list of patch references for each patch, tract, filter combo.
390 Keyword arguments passed to the task
395 List of tuples, where each tuple is a (dataRef, kwargs) pair.
397 refDict = MergeSourcesRunner.buildRefDict(parsedCmd)
398 kwargs["psfCache"] = parsedCmd.psfCache
399 return [(list(p.values()), kwargs)
for t
in refDict.values()
for p
in t.values()]
402class DeblendCoaddSourcesTask(CmdLineTask):
403 """Deblend the sources in a merged catalog
405 Deblend sources from master catalog
in each coadd.
406 This can either be done separately
in each band using the HSC-SDSS deblender
407 (`DeblendCoaddSourcesTask.config.simultaneous==
False`)
408 or use SCARLET to simultaneously fit the blend
in all bands
409 (`DeblendCoaddSourcesTask.config.simultaneous==
True`).
410 The task will set its own `self.schema` atribute to the `Schema` of the
411 output deblended catalog.
412 This will include all fields
from the input `Schema`,
as well
as additional fields
415 `pipe.tasks.multiband.DeblendCoaddSourcesTask Description
416 ---------------------------------------------------------
422 Butler used to read the input schemas
from disk
or
423 construct the reference catalog loader,
if `schema`
or `peakSchema`
or
425 The schema of the merged detection catalog
as an input to this task.
427 The schema of the `PeakRecord`s
in the `Footprint`s
in the merged detection catalog
429 ConfigClass = DeblendCoaddSourcesConfig
430 RunnerClass = DeblendCoaddSourcesRunner
431 _DefaultName = "deblendCoaddSources"
432 makeIdFactory = _makeMakeIdFactory(
"MergedCoaddId", includeBand=
False)
435 def _makeArgumentParser(cls):
436 parser = ArgumentParser(name=cls._DefaultName)
437 parser.add_id_argument(
"--id",
"deepCoadd_calexp",
438 help=
"data ID, e.g. --id tract=12345 patch=1,2 filter=g^r^i",
439 ContainerClass=ExistingCoaddDataIdContainer)
440 parser.add_argument(
"--psfCache", type=int, default=100, help=
"Size of CoaddPsf cache")
443 def __init__(self, butler=None, schema=None, peakSchema=None, **kwargs):
444 CmdLineTask.__init__(self, **kwargs)
446 assert butler
is not None,
"Neither butler nor schema is defined"
447 schema = butler.get(self.config.coaddName +
"Coadd_mergeDet_schema", immediate=
True).schema
448 self.schemaMapper = afwTable.SchemaMapper(schema)
449 self.schemaMapper.addMinimalSchema(schema)
450 self.schema = self.schemaMapper.getOutputSchema()
451 if peakSchema
is None:
452 assert butler
is not None,
"Neither butler nor peakSchema is defined"
453 peakSchema = butler.get(self.config.coaddName +
"Coadd_peak_schema", immediate=
True).schema
455 if self.config.simultaneous:
456 self.makeSubtask(
"multiBandDeblend", schema=self.schema, peakSchema=peakSchema)
458 self.makeSubtask(
"singleBandDeblend", schema=self.schema, peakSchema=peakSchema)
460 def getSchemaCatalogs(self):
461 """Return a dict of empty catalogs for each catalog dataset produced by this task.
466 Dictionary of empty catalogs, with catalog names
as keys.
468 catalog = afwTable.SourceCatalog(self.schema)
469 return {self.config.coaddName +
"Coadd_deblendedFlux": catalog,
470 self.config.coaddName +
"Coadd_deblendedModel": catalog}
472 def runDataRef(self, patchRefList, psfCache=100):
475 Deblend each source simultaneously or separately
476 (depending on `DeblendCoaddSourcesTask.config.simultaneous`).
477 Set `
is-primary`
and related flags.
478 Propagate flags
from individual visits.
479 Write the deblended sources out.
484 List of data references
for each filter
487 if self.config.hasFakes:
488 coaddType =
"fakes_" + self.config.coaddName
490 coaddType = self.config.coaddName
492 if self.config.simultaneous:
496 for patchRef
in patchRefList:
497 exposure = patchRef.get(coaddType +
"Coadd_calexp", immediate=
True)
498 filter = patchRef.get(coaddType +
"Coadd_filterLabel", immediate=
True)
499 filters.append(filter.bandLabel)
500 exposures.append(exposure)
502 exposures = [exposure
for _, exposure
in sorted(zip(filters, exposures))]
503 patchRefList = [patchRef
for _, patchRef
in sorted(zip(filters, patchRefList))]
506 sources = self.readSources(patchRef)
507 exposure = afwImage.MultibandExposure.fromExposures(filters, exposures)
508 templateCatalogs, fluxCatalogs = self.multiBandDeblend.run(exposure, sources)
509 for n
in range(len(patchRefList)):
510 self.write(patchRefList[n], templateCatalogs[filters[n]],
"Model")
511 if filters[n]
in fluxCatalogs:
512 self.write(patchRefList[n], fluxCatalogs[filters[n]],
"Flux")
515 for patchRef
in patchRefList:
516 exposure = patchRef.get(coaddType +
"Coadd_calexp", immediate=
True)
517 exposure.getPsf().setCacheCapacity(psfCache)
518 sources = self.readSources(patchRef)
519 self.singleBandDeblend.run(exposure, sources)
520 self.write(patchRef, sources)
522 def readSources(self, dataRef):
523 """Read merged catalog
525 Read the catalog of merged detections and create a catalog
530 dataRef: data reference
531 Data reference
for catalog of merged detections
535 sources: `SourceCatalog`
536 List of sources
in merged catalog
538 We also need to add columns to hold the measurements we
're about to make so we can measure in-place.
540 merged = dataRef.get(self.config.coaddName + "Coadd_mergeDet", immediate=
True)
541 self.log.info(
"Read %d detections: %s", len(merged), dataRef.dataId)
542 idFactory = self.makeIdFactory(dataRef)
546 maxId = np.max(merged[
"id"])
547 idFactory.notify(maxId)
548 table = afwTable.SourceTable.make(self.schema, idFactory)
549 sources = afwTable.SourceCatalog(table)
550 sources.extend(merged, self.schemaMapper)
553 def write(self, dataRef, sources, catalogType):
554 """Write the source catalog(s)
558 dataRef: Data Reference
559 Reference to the output catalog.
560 sources: `SourceCatalog`
561 Flux conserved sources to write to file.
562 If using the single band deblender, this is the catalog
564 template_sources: `SourceCatalog`
565 Source catalog using the multiband template models
568 dataRef.put(sources, self.config.coaddName + f"Coadd_deblended{catalogType}")
569 self.log.info(
"Wrote %d sources: %s", len(sources), dataRef.dataId)
572 """Write the metadata produced from processing the data.
576 List of Butler data references used to write the metadata.
577 The metadata is written to dataset type `CmdLineTask._getMetadataName`.
579 for dataRef
in dataRefList:
581 metadataName = self._getMetadataName()
582 if metadataName
is not None:
583 dataRef.put(self.getFullMetadata(), metadataName)
584 except Exception
as e:
585 self.log.warning(
"Could not persist metadata for dataId=%s: %s", dataRef.dataId, e)
588class MeasureMergedCoaddSourcesConnections(PipelineTaskConnections,
589 dimensions=(
"tract",
"patch",
"band",
"skymap"),
590 defaultTemplates={
"inputCoaddName":
"deep",
591 "outputCoaddName":
"deep",
592 "deblendedCatalog":
"deblendedFlux"}):
593 inputSchema = cT.InitInput(
594 doc=
"Input schema for measure merged task produced by a deblender or detection task",
595 name=
"{inputCoaddName}Coadd_deblendedFlux_schema",
596 storageClass=
"SourceCatalog"
598 outputSchema = cT.InitOutput(
599 doc=
"Output schema after all new fields are added by task",
600 name=
"{inputCoaddName}Coadd_meas_schema",
601 storageClass=
"SourceCatalog"
603 refCat = cT.PrerequisiteInput(
604 doc=
"Reference catalog used to match measured sources against known sources",
606 storageClass=
"SimpleCatalog",
607 dimensions=(
"skypix",),
612 doc=
"Input coadd image",
613 name=
"{inputCoaddName}Coadd_calexp",
614 storageClass=
"ExposureF",
615 dimensions=(
"tract",
"patch",
"band",
"skymap")
618 doc=
"SkyMap to use in processing",
619 name=BaseSkyMap.SKYMAP_DATASET_TYPE_NAME,
620 storageClass=
"SkyMap",
621 dimensions=(
"skymap",),
623 visitCatalogs = cT.Input(
624 doc=
"Source catalogs for visits which overlap input tract, patch, band. Will be "
625 "further filtered in the task for the purpose of propagating flags from image calibration "
626 "and characterization to coadd objects. Only used in legacy PropagateVisitFlagsTask.",
628 dimensions=(
"instrument",
"visit",
"detector"),
629 storageClass=
"SourceCatalog",
632 sourceTableHandles = cT.Input(
633 doc=(
"Source tables that are derived from the ``CalibrateTask`` sources. "
634 "These tables contain astrometry and photometry flags, and optionally "
636 name=
"sourceTable_visit",
637 storageClass=
"DataFrame",
638 dimensions=(
"instrument",
"visit"),
642 finalizedSourceTableHandles = cT.Input(
643 doc=(
"Finalized source tables from ``FinalizeCalibrationTask``. These "
644 "tables contain PSF flags from the finalized PSF estimation."),
645 name=
"finalized_src_table",
646 storageClass=
"DataFrame",
647 dimensions=(
"instrument",
"visit"),
651 inputCatalog = cT.Input(
652 doc=(
"Name of the input catalog to use."
653 "If the single band deblender was used this should be 'deblendedFlux."
654 "If the multi-band deblender was used this should be 'deblendedModel, "
655 "or deblendedFlux if the multiband deblender was configured to output "
656 "deblended flux catalogs. If no deblending was performed this should "
658 name=
"{inputCoaddName}Coadd_{deblendedCatalog}",
659 storageClass=
"SourceCatalog",
660 dimensions=(
"tract",
"patch",
"band",
"skymap"),
662 outputSources = cT.Output(
663 doc=
"Source catalog containing all the measurement information generated in this task",
664 name=
"{outputCoaddName}Coadd_meas",
665 dimensions=(
"tract",
"patch",
"band",
"skymap"),
666 storageClass=
"SourceCatalog",
668 matchResult = cT.Output(
669 doc=
"Match catalog produced by configured matcher, optional on doMatchSources",
670 name=
"{outputCoaddName}Coadd_measMatch",
671 dimensions=(
"tract",
"patch",
"band",
"skymap"),
672 storageClass=
"Catalog",
674 denormMatches = cT.Output(
675 doc=
"Denormalized Match catalog produced by configured matcher, optional on "
676 "doWriteMatchesDenormalized",
677 name=
"{outputCoaddName}Coadd_measMatchFull",
678 dimensions=(
"tract",
"patch",
"band",
"skymap"),
679 storageClass=
"Catalog",
682 def __init__(self, *, config=None):
683 super().__init__(config=config)
684 if config.doPropagateFlags
is False:
685 self.inputs -= set((
"visitCatalogs",))
686 self.inputs -= set((
"sourceTableHandles",))
687 self.inputs -= set((
"finalizedSourceTableHandles",))
688 elif config.propagateFlags.target == PropagateSourceFlagsTask:
690 self.inputs -= set((
"visitCatalogs",))
692 if not config.propagateFlags.source_flags:
693 self.inputs -= set((
"sourceTableHandles",))
694 if not config.propagateFlags.finalized_source_flags:
695 self.inputs -= set((
"finalizedSourceTableHandles",))
698 self.inputs -= set((
"sourceTableHandles",))
699 self.inputs -= set((
"finalizedSourceTableHandles",))
701 if config.doMatchSources
is False:
702 self.outputs -= set((
"matchResult",))
704 if config.doWriteMatchesDenormalized
is False:
705 self.outputs -= set((
"denormMatches",))
708class MeasureMergedCoaddSourcesConfig(PipelineTaskConfig,
709 pipelineConnections=MeasureMergedCoaddSourcesConnections):
711 @anchor MeasureMergedCoaddSourcesConfig_
713 @brief Configuration parameters
for the MeasureMergedCoaddSourcesTask
715 inputCatalog = Field(dtype=str, default="deblendedFlux",
716 doc=(
"Name of the input catalog to use."
717 "If the single band deblender was used this should be 'deblendedFlux."
718 "If the multi-band deblender was used this should be 'deblendedModel."
719 "If no deblending was performed this should be 'mergeDet'"))
720 measurement = ConfigurableField(target=SingleFrameMeasurementTask, doc=
"Source measurement")
721 setPrimaryFlags = ConfigurableField(target=SetPrimaryFlagsTask, doc=
"Set flags for primary tract/patch")
722 doPropagateFlags = Field(
723 dtype=bool, default=
True,
724 doc=
"Whether to match sources to CCD catalogs to propagate flags (to e.g. identify PSF stars)"
726 propagateFlags = ConfigurableField(target=PropagateSourceFlagsTask, doc=
"Propagate source flags to coadd")
727 doMatchSources = Field(dtype=bool, default=
True, doc=
"Match sources to reference catalog?")
728 match = ConfigurableField(target=DirectMatchTask, doc=
"Matching to reference catalog")
729 doWriteMatchesDenormalized = Field(
732 doc=(
"Write reference matches in denormalized format? "
733 "This format uses more disk space, but is more convenient to read."),
735 coaddName = Field(dtype=str, default=
"deep", doc=
"Name of coadd")
736 psfCache = Field(dtype=int, default=100, doc=
"Size of psfCache")
737 checkUnitsParseStrict = Field(
738 doc=
"Strictness of Astropy unit compatibility check, can be 'raise', 'warn' or 'silent'",
745 doc=
"Apply aperture corrections"
747 applyApCorr = ConfigurableField(
748 target=ApplyApCorrTask,
749 doc=
"Subtask to apply aperture corrections"
751 doRunCatalogCalculation = Field(
754 doc=
'Run catalogCalculation task'
756 catalogCalculation = ConfigurableField(
757 target=CatalogCalculationTask,
758 doc=
"Subtask to run catalogCalculation plugins on catalog"
764 doc=
"Should be set to True if fake sources have been inserted into the input data."
768 def refObjLoader(self):
769 return self.match.refObjLoader
771 def setDefaults(self):
772 super().setDefaults()
773 self.measurement.plugins.names |= [
'base_InputCount',
775 'base_LocalPhotoCalib',
777 self.measurement.plugins[
'base_PixelFlags'].masksFpAnywhere = [
'CLIPPED',
'SENSOR_EDGE',
779 self.measurement.plugins[
'base_PixelFlags'].masksFpCenter = [
'CLIPPED',
'SENSOR_EDGE',
784 refCatGen2 = getattr(self.refObjLoader,
"ref_dataset_name",
None)
785 if refCatGen2
is not None and refCatGen2 != self.connections.refCat:
787 f
"Gen2 ({refCatGen2}) and Gen3 ({self.connections.refCat}) reference catalogs "
788 f
"are different. These options must be kept in sync until Gen2 is retired."
800class MeasureMergedCoaddSourcesRunner(ButlerInitializedTaskRunner):
801 """Get the psfCache setting into MeasureMergedCoaddSourcesTask"""
803 def getTargetList(parsedCmd, **kwargs):
804 return ButlerInitializedTaskRunner.getTargetList(parsedCmd, psfCache=parsedCmd.psfCache)
807class MeasureMergedCoaddSourcesTask(PipelineTask, CmdLineTask):
809 @anchor MeasureMergedCoaddSourcesTask_
811 @brief Deblend sources
from master catalog
in each coadd seperately
and measure.
813 @section pipe_tasks_multiBand_Contents Contents
815 -
@ref pipe_tasks_multiBand_MeasureMergedCoaddSourcesTask_Purpose
816 -
@ref pipe_tasks_multiBand_MeasureMergedCoaddSourcesTask_Initialize
817 -
@ref pipe_tasks_multiBand_MeasureMergedCoaddSourcesTask_Run
818 -
@ref pipe_tasks_multiBand_MeasureMergedCoaddSourcesTask_Config
819 -
@ref pipe_tasks_multiBand_MeasureMergedCoaddSourcesTask_Debug
820 -
@ref pipe_tasks_multiband_MeasureMergedCoaddSourcesTask_Example
822 @section pipe_tasks_multiBand_MeasureMergedCoaddSourcesTask_Purpose Description
824 Command-line task that uses peaks
and footprints
from a master catalog to perform deblending
and
825 measurement
in each coadd.
827 Given a master input catalog of sources (peaks
and footprints)
or deblender outputs
828 (including a HeavyFootprint
in each band), measure each source on the
829 coadd. Repeating this procedure
with the same master catalog across multiple coadds will generate a
830 consistent set of child sources.
832 The deblender retains all peaks
and deblends any missing peaks (dropouts
in that band)
as PSFs. Source
833 properties are measured
and the
@c is-primary flag (indicating sources
with no children)
is set. Visit
834 flags are propagated to the coadd sources.
836 Optionally, we can match the coadd sources to an external reference catalog.
839 deepCoadd_mergeDet{tract,patch}
or deepCoadd_deblend{tract,patch}: SourceCatalog
840 @n deepCoadd_calexp{tract,patch,filter}: ExposureF
842 deepCoadd_meas{tract,patch,filter}: SourceCatalog
846 MeasureMergedCoaddSourcesTask delegates most of its work to a set of sub-tasks:
849 <DT>
@ref SingleFrameMeasurementTask_
"measurement"
850 <DD> Measure source properties of deblended sources.</DD>
851 <DT>
@ref SetPrimaryFlagsTask_
"setPrimaryFlags"
852 <DD> Set flag
'is-primary' as well
as related flags on sources.
'is-primary' is set
for sources that are
853 not at the edge of the field
and that have either
not been deblended
or are the children of deblended
855 <DT>
@ref PropagateVisitFlagsTask_
"propagateFlags"
856 <DD> Propagate flags set
in individual visits to the coadd.</DD>
857 <DT>
@ref DirectMatchTask_
"match"
858 <DD> Match input sources to a reference catalog (optional).
861 These subtasks may be retargeted
as required.
863 @section pipe_tasks_multiBand_MeasureMergedCoaddSourcesTask_Initialize Task initialization
865 @copydoc \_\_init\_\_
867 @section pipe_tasks_multiBand_MeasureMergedCoaddSourcesTask_Run Invoking the Task
871 @section pipe_tasks_multiBand_MeasureMergedCoaddSourcesTask_Config Configuration parameters
873 See
@ref MeasureMergedCoaddSourcesConfig_
875 @section pipe_tasks_multiBand_MeasureMergedCoaddSourcesTask_Debug Debug variables
877 The command line task interface supports a
878 flag
@c -d to
import @b debug.py
from your
@c PYTHONPATH; see
@ref baseDebug
for more about
@b debug.py
881 MeasureMergedCoaddSourcesTask has no debug variables of its own because it delegates all the work to
882 the various sub-tasks. See the documetation
for individual sub-tasks
for more information.
884 @section pipe_tasks_multiband_MeasureMergedCoaddSourcesTask_Example A complete example of using
885 MeasureMergedCoaddSourcesTask
887 After MeasureMergedCoaddSourcesTask has been run on multiple coadds, we have a set of per-band catalogs.
888 The next stage
in the multi-band processing procedure will merge these measurements into a suitable
889 catalog
for driving forced photometry.
891 Command-line usage of MeasureMergedCoaddSourcesTask expects a data reference to the coadds
893 A list of the available optional arguments can be obtained by calling measureCoaddSources.py
with the
894 `--help` command line argument:
896 measureCoaddSources.py --help
899 To demonstrate usage of the DetectCoaddSourcesTask
in the larger context of multi-band processing, we
900 will process HSC data
in the [ci_hsc](https://github.com/lsst/ci_hsc) package. Assuming one has finished
901 step 6 at
@ref pipeTasks_multiBand, one may perform deblending
and measure sources
in the HSC-I band
904 measureCoaddSources.py $CI_HSC_DIR/DATA --id patch=5,4 tract=0 filter=HSC-I
906 This will process the HSC-I band data. The results are written
in
907 `$CI_HSC_DIR/DATA/deepCoadd-results/HSC-I/0/5,4/meas-HSC-I-0-5,4.fits
909 It
is also necessary to run
911 measureCoaddSources.py $CI_HSC_DIR/DATA --id patch=5,4 tract=0 filter=HSC-R
913 to generate the sources catalogs
for the HSC-R band required by the next step
in the multi-band
914 procedure:
@ref MergeMeasurementsTask_
"MergeMeasurementsTask".
916 _DefaultName = "measureCoaddSources"
917 ConfigClass = MeasureMergedCoaddSourcesConfig
918 RunnerClass = MeasureMergedCoaddSourcesRunner
919 getSchemaCatalogs = _makeGetSchemaCatalogs(
"meas")
921 makeIdFactory = _makeMakeIdFactory(
"MergedCoaddId", includeBand=
False)
924 def _makeArgumentParser(cls):
925 parser = ArgumentParser(name=cls._DefaultName)
926 parser.add_id_argument(
"--id",
"deepCoadd_calexp",
927 help=
"data ID, e.g. --id tract=12345 patch=1,2 filter=r",
928 ContainerClass=ExistingCoaddDataIdContainer)
929 parser.add_argument(
"--psfCache", type=int, default=100, help=
"Size of CoaddPsf cache")
932 def __init__(self, butler=None, schema=None, peakSchema=None, refObjLoader=None, initInputs=None,
935 @brief Initialize the task.
937 Keyword arguments (
in addition to those forwarded to CmdLineTask.__init__):
938 @param[
in] schema: the schema of the merged detection catalog used
as input to this one
939 @param[
in] peakSchema: the schema of the PeakRecords
in the Footprints
in the merged detection catalog
940 @param[
in] refObjLoader: an instance of LoadReferenceObjectsTasks that supplies an external reference
941 catalog. May be
None if the loader can be constructed
from the butler argument
or all steps
942 requiring a reference catalog are disabled.
943 @param[
in] butler: a butler used to read the input schemas
from disk
or construct the reference
944 catalog loader,
if schema
or peakSchema
or refObjLoader
is None
946 The task will set its own self.schema attribute to the schema of the output measurement catalog.
947 This will include all fields
from the input schema,
as well
as additional fields
for all the
950 super().__init__(**kwargs)
951 self.deblended = self.config.inputCatalog.startswith("deblended")
952 self.inputCatalog =
"Coadd_" + self.config.inputCatalog
953 if initInputs
is not None:
954 schema = initInputs[
'inputSchema'].schema
956 assert butler
is not None,
"Neither butler nor schema is defined"
957 schema = butler.get(self.config.coaddName + self.inputCatalog +
"_schema", immediate=
True).schema
958 self.schemaMapper = afwTable.SchemaMapper(schema)
959 self.schemaMapper.addMinimalSchema(schema)
960 self.schema = self.schemaMapper.getOutputSchema()
962 self.makeSubtask(
"measurement", schema=self.schema, algMetadata=self.algMetadata)
963 self.makeSubtask(
"setPrimaryFlags", schema=self.schema)
964 if self.config.doMatchSources:
965 self.makeSubtask(
"match", butler=butler, refObjLoader=refObjLoader)
966 if self.config.doPropagateFlags:
967 self.makeSubtask(
"propagateFlags", schema=self.schema)
968 self.schema.checkUnits(parse_strict=self.config.checkUnitsParseStrict)
969 if self.config.doApCorr:
970 self.makeSubtask(
"applyApCorr", schema=self.schema)
971 if self.config.doRunCatalogCalculation:
972 self.makeSubtask(
"catalogCalculation", schema=self.schema)
974 self.outputSchema = afwTable.SourceCatalog(self.schema)
976 def runQuantum(self, butlerQC, inputRefs, outputRefs):
977 inputs = butlerQC.get(inputRefs)
979 refObjLoader = ReferenceObjectLoader([ref.datasetRef.dataId
for ref
in inputRefs.refCat],
980 inputs.pop(
'refCat'), config=self.config.refObjLoader,
982 self.match.setRefObjLoader(refObjLoader)
986 inputs[
'exposure'].getPsf().setCacheCapacity(self.config.psfCache)
989 exposureIdInfo = ExposureIdInfo.fromDataId(butlerQC.quantum.dataId,
"tract_patch")
990 inputs[
'exposureId'] = exposureIdInfo.expId
991 idFactory = exposureIdInfo.makeSourceIdFactory()
993 table = afwTable.SourceTable.make(self.schema, idFactory)
994 sources = afwTable.SourceCatalog(table)
995 sources.extend(inputs.pop(
'inputCatalog'), self.schemaMapper)
996 table = sources.getTable()
997 table.setMetadata(self.algMetadata)
998 inputs[
'sources'] = sources
1000 skyMap = inputs.pop(
'skyMap')
1001 tractNumber = inputRefs.inputCatalog.dataId[
'tract']
1002 tractInfo = skyMap[tractNumber]
1003 patchInfo = tractInfo.getPatchInfo(inputRefs.inputCatalog.dataId[
'patch'])
1006 tractInfo=tractInfo,
1007 patchInfo=patchInfo,
1008 wcs=tractInfo.getWcs(),
1009 bbox=patchInfo.getOuterBBox()
1011 inputs[
'skyInfo'] = skyInfo
1013 if self.config.doPropagateFlags:
1014 if self.config.propagateFlags.target == PropagateSourceFlagsTask:
1016 ccdInputs = inputs[
"exposure"].getInfo().getCoaddInputs().ccds
1017 inputs[
"ccdInputs"] = ccdInputs
1019 if "sourceTableHandles" in inputs:
1020 sourceTableHandles = inputs.pop(
"sourceTableHandles")
1021 sourceTableHandleDict = {handle.dataId[
"visit"]: handle
1022 for handle
in sourceTableHandles}
1023 inputs[
"sourceTableHandleDict"] = sourceTableHandleDict
1024 if "finalizedSourceTableHandles" in inputs:
1025 finalizedSourceTableHandles = inputs.pop(
"finalizedSourceTableHandles")
1026 finalizedSourceTableHandleDict = {handle.dataId[
"visit"]: handle
1027 for handle
in finalizedSourceTableHandles}
1028 inputs[
"finalizedSourceTableHandleDict"] = finalizedSourceTableHandleDict
1032 ccdInputs = inputs[
'exposure'].getInfo().getCoaddInputs().ccds
1033 visitKey = ccdInputs.schema.find(
"visit").key
1034 ccdKey = ccdInputs.schema.find(
"ccd").key
1035 inputVisitIds = set()
1037 for ccdRecord
in ccdInputs:
1038 visit = ccdRecord.get(visitKey)
1039 ccd = ccdRecord.get(ccdKey)
1040 inputVisitIds.add((visit, ccd))
1041 ccdRecordsWcs[(visit, ccd)] = ccdRecord.getWcs()
1043 inputCatalogsToKeep = []
1044 inputCatalogWcsUpdate = []
1045 for i, dataRef
in enumerate(inputRefs.visitCatalogs):
1046 key = (dataRef.dataId[
'visit'], dataRef.dataId[
'detector'])
1047 if key
in inputVisitIds:
1048 inputCatalogsToKeep.append(inputs[
'visitCatalogs'][i])
1049 inputCatalogWcsUpdate.append(ccdRecordsWcs[key])
1050 inputs[
'visitCatalogs'] = inputCatalogsToKeep
1051 inputs[
'wcsUpdates'] = inputCatalogWcsUpdate
1052 inputs[
'ccdInputs'] = ccdInputs
1054 outputs = self.run(**inputs)
1055 butlerQC.put(outputs, outputRefs)
1057 def runDataRef(self, patchRef, psfCache=100):
1059 @brief Deblend
and measure.
1061 @param[
in] patchRef: Patch reference.
1063 Set
'is-primary' and related flags. Propagate flags
1064 from individual visits. Optionally match the sources to a reference catalog
and write the matches.
1065 Finally, write the deblended sources
and measurements out.
1067 if self.config.hasFakes:
1068 coaddType =
"fakes_" + self.config.coaddName
1070 coaddType = self.config.coaddName
1071 exposure = patchRef.get(coaddType +
"Coadd_calexp", immediate=
True)
1072 exposure.getPsf().setCacheCapacity(psfCache)
1073 sources = self.readSources(patchRef)
1074 table = sources.getTable()
1075 table.setMetadata(self.algMetadata)
1076 skyInfo =
getSkyInfo(coaddName=self.config.coaddName, patchRef=patchRef)
1078 if self.config.doPropagateFlags:
1079 ccdInputs = self.propagateFlags.getCcdInputs(exposure)
1083 expId = getGen3CoaddExposureId(patchRef, coaddName=self.config.coaddName, includeBand=
False,
1085 results = self.run(exposure=exposure, sources=sources, skyInfo=skyInfo, exposureId=expId,
1086 ccdInputs=ccdInputs, butler=patchRef.getButler())
1088 if self.config.doMatchSources:
1089 self.writeMatches(patchRef, results)
1090 self.write(patchRef, results.outputSources)
1092 def run(self, exposure, sources, skyInfo, exposureId, ccdInputs=None, visitCatalogs=None, wcsUpdates=None,
1093 butler=None, sourceTableHandleDict=None, finalizedSourceTableHandleDict=None):
1094 """Run measurement algorithms on the input exposure, and optionally populate the
1095 resulting catalog with extra information.
1099 exposure : `lsst.afw.exposure.Exposure`
1100 The input exposure on which measurements are to be performed
1102 A catalog built
from the results of merged detections,
or
1104 skyInfo : `lsst.pipe.base.Struct`
1105 A struct containing information about the position of the input exposure within
1106 a `SkyMap`, the `SkyMap`, its `Wcs`,
and its bounding box
1107 exposureId : `int`
or `bytes`
1108 packed unique number
or bytes unique to the input exposure
1110 Catalog containing information on the individual visits which went into making
1112 sourceTableHandleDict : `dict` [`int`: `lsst.daf.butler.DeferredDatasetHandle`]
1113 Dict
for sourceTable_visit handles (key
is visit)
for propagating flags.
1114 These tables are derived
from the ``CalibrateTask`` sources,
and contain
1115 astrometry
and photometry flags,
and optionally PSF flags.
1116 finalizedSourceTableHandleDict : `dict` [`int`: `lsst.daf.butler.DeferredDatasetHandle`], optional
1117 Dict
for finalized_src_table handles (key
is visit)
for propagating flags.
1118 These tables are derived
from ``FinalizeCalibrationTask``
and contain
1119 PSF flags
from the finalized PSF estimation.
1120 visitCatalogs : list of `lsst.afw.table.SourceCatalogs`
1121 A list of source catalogs corresponding to measurements made on the individual
1122 visits which went into the input exposure. If
None and butler
is `
None` then
1123 the task cannot propagate visit flags to the output catalog.
1124 Deprecated, to be removed
with PropagateVisitFlagsTask.
1126 If visitCatalogs
is not `
None` this should be a list of wcs objects which correspond
1127 to the input visits. Used to put all coordinates to common system. If `
None`
and
1128 butler
is `
None` then the task cannot propagate visit flags to the output catalog.
1129 Deprecated, to be removed
with PropagateVisitFlagsTask.
1130 butler : `lsst.daf.persistence.Butler`
1131 A gen2 butler used to load visit catalogs.
1132 Deprecated, to be removed
with Gen2.
1136 results : `lsst.pipe.base.Struct`
1137 Results of running measurement task. Will contain the catalog
in the
1138 sources attribute. Optionally will have results of matching to a
1139 reference catalog
in the matchResults attribute,
and denormalized
1140 matches
in the denormMatches attribute.
1142 self.measurement.run(sources, exposure, exposureId=exposureId)
1144 if self.config.doApCorr:
1145 self.applyApCorr.run(
1147 apCorrMap=exposure.getInfo().getApCorrMap()
1154 if not sources.isContiguous():
1155 sources = sources.copy(deep=
True)
1157 if self.config.doRunCatalogCalculation:
1158 self.catalogCalculation.run(sources)
1160 self.setPrimaryFlags.run(sources, skyMap=skyInfo.skyMap, tractInfo=skyInfo.tractInfo,
1161 patchInfo=skyInfo.patchInfo)
1162 if self.config.doPropagateFlags:
1163 if self.config.propagateFlags.target == PropagateSourceFlagsTask:
1165 self.propagateFlags.run(
1168 sourceTableHandleDict,
1169 finalizedSourceTableHandleDict
1173 self.propagateFlags.run(
1184 if self.config.doMatchSources:
1185 matchResult = self.match.run(sources, exposure.getInfo().getFilterLabel().bandLabel)
1186 matches = afwTable.packMatches(matchResult.matches)
1187 matches.table.setMetadata(matchResult.matchMeta)
1188 results.matchResult = matches
1189 if self.config.doWriteMatchesDenormalized:
1190 if matchResult.matches:
1191 denormMatches = denormalizeMatches(matchResult.matches, matchResult.matchMeta)
1193 self.log.warning(
"No matches, so generating dummy denormalized matches file")
1194 denormMatches = afwTable.BaseCatalog(afwTable.Schema())
1196 denormMatches.getMetadata().add(
"COMMENT",
1197 "This catalog is empty because no matches were found.")
1198 results.denormMatches = denormMatches
1199 results.denormMatches = denormMatches
1201 results.outputSources = sources
1204 def readSources(self, dataRef):
1206 @brief Read input sources.
1208 @param[
in] dataRef: Data reference
for catalog of merged detections
1209 @return List of sources
in merged catalog
1211 We also need to add columns to hold the measurements we
're about to make so we can measure in-place.
1213 merged = dataRef.get(self.config.coaddName + self.inputCatalog, immediate=True)
1214 self.log.info(
"Read %d detections: %s", len(merged), dataRef.dataId)
1215 idFactory = self.makeIdFactory(dataRef)
1217 idFactory.notify(s.getId())
1218 table = afwTable.SourceTable.make(self.schema, idFactory)
1219 sources = afwTable.SourceCatalog(table)
1220 sources.extend(merged, self.schemaMapper)
1223 def writeMatches(self, dataRef, results):
1225 @brief Write matches of the sources to the astrometric reference catalog.
1227 @param[
in] dataRef: data reference
1228 @param[
in] results: results struct
from run method
1230 if hasattr(results,
"matchResult"):
1231 dataRef.put(results.matchResult, self.config.coaddName +
"Coadd_measMatch")
1232 if hasattr(results,
"denormMatches"):
1233 dataRef.put(results.denormMatches, self.config.coaddName +
"Coadd_measMatchFull")
1235 def write(self, dataRef, sources):
1237 @brief Write the source catalog.
1239 @param[
in] dataRef: data reference
1240 @param[
in] sources: source catalog
1242 dataRef.put(sources, self.config.coaddName + "Coadd_meas")
1243 self.log.info(
"Wrote %d sources: %s", len(sources), dataRef.dataId)
1244
def getSkyInfo(coaddName, patchRef)
Return the SkyMap, tract and patch information, wcs, and outer bbox of the patch to be coadded.
def writeMetadata(self, dataRefList)
No metadata to write, and not sure how to write it for a list of dataRefs.