Coverage for python/lsst/pipe/tasks/multiBand.py: 66%

Shortcuts on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

398 statements  

1#!/usr/bin/env python 

2# 

3# LSST Data Management System 

4# Copyright 2008-2015 AURA/LSST. 

5# 

6# This product includes software developed by the 

7# LSST Project (http://www.lsst.org/). 

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 LSST License Statement and 

20# the GNU General Public License along with this program. If not, 

21# see <https://www.lsstcorp.org/LegalNotices/>. 

22# 

23import numpy as np 

24 

25from lsst.coadd.utils.coaddDataIdContainer import ExistingCoaddDataIdContainer 

26from lsst.coadd.utils.getGen3CoaddExposureId import getGen3CoaddExposureId 

27from lsst.pipe.base import (CmdLineTask, Struct, ArgumentParser, ButlerInitializedTaskRunner, 

28 PipelineTask, PipelineTaskConfig, PipelineTaskConnections) 

29import lsst.pipe.base.connectionTypes as cT 

30from lsst.pex.config import Config, Field, ConfigurableField 

31from lsst.meas.algorithms import DynamicDetectionTask, ReferenceObjectLoader 

32from lsst.meas.base import SingleFrameMeasurementTask, ApplyApCorrTask, CatalogCalculationTask 

33from lsst.meas.deblender import SourceDeblendTask 

34from lsst.meas.extensions.scarlet import ScarletDeblendTask 

35from lsst.pipe.tasks.coaddBase import getSkyInfo 

36from lsst.pipe.tasks.scaleVariance import ScaleVarianceTask 

37from lsst.meas.astrom import DirectMatchTask, denormalizeMatches 

38from lsst.pipe.tasks.fakes import BaseFakeSourcesTask 

39from lsst.pipe.tasks.setPrimaryFlags import SetPrimaryFlagsTask 

40from lsst.pipe.tasks.propagateVisitFlags import PropagateVisitFlagsTask 

41import lsst.afw.image as afwImage 

42import lsst.afw.table as afwTable 

43import lsst.afw.math as afwMath 

44from lsst.daf.base import PropertyList 

45from lsst.skymap import BaseSkyMap 

46from lsst.obs.base import ExposureIdInfo 

47 

48# NOTE: these imports are a convenience so multiband users only have to import this file. 

49from .mergeDetections import MergeDetectionsConfig, MergeDetectionsTask # noqa: F401 

50from .mergeMeasurements import MergeMeasurementsConfig, MergeMeasurementsTask # noqa: F401 

51from .multiBandUtils import MergeSourcesRunner, CullPeaksConfig, _makeGetSchemaCatalogs # noqa: F401 

52from .multiBandUtils import getInputSchema, readCatalog, _makeMakeIdFactory # noqa: F401 

53from .deblendCoaddSourcesPipeline import DeblendCoaddSourcesSingleConfig # noqa: F401 

54from .deblendCoaddSourcesPipeline import DeblendCoaddSourcesSingleTask # noqa: F401 

55from .deblendCoaddSourcesPipeline import DeblendCoaddSourcesMultiConfig # noqa: F401 

56from .deblendCoaddSourcesPipeline import DeblendCoaddSourcesMultiTask # noqa: F401 

57 

58 

59""" 

60New set types: 

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. 

66 

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 

70""" 

71 

72 

73############################################################################################################## 

74class DetectCoaddSourcesConnections(PipelineTaskConnections, 

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", 

81 ) 

82 exposure = cT.Input( 

83 doc="Exposure on which detections are to be performed", 

84 name="{inputCoaddName}Coadd", 

85 storageClass="ExposureF", 

86 dimensions=("tract", "patch", "band", "skymap") 

87 ) 

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") 

93 ) 

94 outputSources = cT.Output( 

95 doc="Detected sources catalog", 

96 name="{outputCoaddName}Coadd_det", 

97 storageClass="SourceCatalog", 

98 dimensions=("tract", "patch", "band", "skymap") 

99 ) 

100 outputExposure = cT.Output( 

101 doc="Exposure post detection", 

102 name="{outputCoaddName}Coadd_calexp", 

103 storageClass="ExposureF", 

104 dimensions=("tract", "patch", "band", "skymap") 

105 ) 

106 

107 

108class DetectCoaddSourcesConfig(PipelineTaskConfig, pipelineConnections=DetectCoaddSourcesConnections): 

109 """! 

110 @anchor DetectCoaddSourcesConfig_ 

111 

112 @brief Configuration parameters for the DetectCoaddSourcesTask 

113 """ 

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)") 

123 hasFakes = Field( 

124 dtype=bool, 

125 default=False, 

126 doc="Should be set to True if fake sources have been inserted into the input data." 

127 ) 

128 

129 def setDefaults(self): 

130 super().setDefaults() 

131 self.detection.thresholdType = "pixel_stdev" 

132 self.detection.isotropicGrow = True 

133 # Coadds are made from background-subtracted CCDs, so any background subtraction should be very basic 

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 # Suppress large footprints that overwhelm the deblender 

139 

140## @addtogroup LSST_task_documentation 

141## @{ 

142## @page DetectCoaddSourcesTask 

143## @ref DetectCoaddSourcesTask_ "DetectCoaddSourcesTask" 

144## @copybrief DetectCoaddSourcesTask 

145## @} 

146 

147 

148class DetectCoaddSourcesTask(PipelineTask, CmdLineTask): 

149 r"""! 

150 @anchor DetectCoaddSourcesTask_ 

151 

152 @brief Detect sources on a coadd 

153 

154 @section pipe_tasks_multiBand_Contents Contents 

155 

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 

162 

163 @section pipe_tasks_multiBand_DetectCoaddSourcesTask_Purpose Description 

164 

165 Command-line task that detects sources on a coadd of exposures obtained with a single filter. 

166 

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. 

171 

172 After scaling the variance plane, we detect sources and generate footprints by delegating to the @ref 

173 SourceDetectionTask_ "detection" subtask. 

174 

175 @par Inputs: 

176 deepCoadd{tract,patch,filter}: ExposureF 

177 @par Outputs: 

178 deepCoadd_det{tract,patch,filter}: SourceCatalog (only parent Footprints) 

179 @n deepCoadd_calexp{tract,patch,filter}: Variance scaled, background-subtracted input 

180 exposure (ExposureF) 

181 @n deepCoadd_calexp_background{tract,patch,filter}: BackgroundList 

182 @par Data Unit: 

183 tract, patch, filter 

184 

185 DetectCoaddSourcesTask delegates most of its work to the @ref SourceDetectionTask_ "detection" subtask. 

186 You can retarget this subtask if you wish. 

187 

188 @section pipe_tasks_multiBand_DetectCoaddSourcesTask_Initialize Task initialization 

189 

190 @copydoc \_\_init\_\_ 

191 

192 @section pipe_tasks_multiBand_DetectCoaddSourcesTask_Run Invoking the Task 

193 

194 @copydoc run 

195 

196 @section pipe_tasks_multiBand_DetectCoaddSourcesTask_Config Configuration parameters 

197 

198 See @ref DetectCoaddSourcesConfig_ "DetectSourcesConfig" 

199 

200 @section pipe_tasks_multiBand_DetectCoaddSourcesTask_Debug Debug variables 

201 

202 The @link lsst.pipe.base.cmdLineTask.CmdLineTask command line task@endlink 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 

204 files. 

205 

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. 

209 

210 @section pipe_tasks_multiband_DetectCoaddSourcesTask_Example A complete example 

211 of using DetectCoaddSourcesTask 

212 

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: 

219 @code 

220 detectCoaddSources.py --help 

221 @endcode 

222 

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: 

226 @code 

227 detectCoaddSources.py $CI_HSC_DIR/DATA --id patch=5,4 tract=0 filter=HSC-I 

228 @endcode 

229 that will process the HSC-I band data. The results are written to 

230 `$CI_HSC_DIR/DATA/deepCoadd-results/HSC-I`. 

231 

232 It is also necessary to run: 

233 @code 

234 detectCoaddSources.py $CI_HSC_DIR/DATA --id patch=5,4 tract=0 filter=HSC-R 

235 @endcode 

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". 

238 """ 

239 _DefaultName = "detectCoaddSources" 

240 ConfigClass = DetectCoaddSourcesConfig 

241 getSchemaCatalogs = _makeGetSchemaCatalogs("det") 

242 makeIdFactory = _makeMakeIdFactory("CoaddId") 

243 

244 @classmethod 

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) 

249 return parser 

250 

251 def __init__(self, schema=None, **kwargs): 

252 """! 

253 @brief Initialize the task. Create the @ref SourceDetectionTask_ "detection" subtask. 

254 

255 Keyword arguments (in addition to those forwarded to CmdLineTask.__init__): 

256 

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__ 

260 """ 

261 # N.B. Super is used here to handle the multiple inheritance of PipelineTasks, the init tree 

262 # call structure has been reviewed carefully to be sure super will work as intended. 

263 super().__init__(**kwargs) 

264 if schema is None: 264 ↛ 266line 264 didn't jump to line 266, because the condition on line 264 was never false

265 schema = afwTable.SourceTable.makeMinimalSchema() 

266 if self.config.doInsertFakes: 266 ↛ 267line 266 didn't jump to line 267, because the condition on line 266 was never true

267 self.makeSubtask("insertFakes") 

268 self.schema = schema 

269 self.makeSubtask("detection", schema=self.schema) 

270 if self.config.doScaleVariance: 270 ↛ 273line 270 didn't jump to line 273, because the condition on line 270 was never false

271 self.makeSubtask("scaleVariance") 

272 

273 self.detectionSchema = afwTable.SourceCatalog(self.schema) 

274 

275 def runDataRef(self, patchRef): 

276 """! 

277 @brief Run detection on a coadd. 

278 

279 Invokes @ref run and then uses @ref write to output the 

280 results. 

281 

282 @param[in] patchRef: data reference for patch 

283 """ 

284 if self.config.hasFakes: 284 ↛ 285line 284 didn't jump to line 285, because the condition on line 284 was never true

285 exposure = patchRef.get("fakes_" + self.config.coaddName + "Coadd", immediate=True) 

286 else: 

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) 

291 return results 

292 

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) 

300 

301 def run(self, exposure, idFactory, expId): 

302 """! 

303 @brief Run detection on an exposure. 

304 

305 First scale the variance plane to match the observed variance 

306 using @ref ScaleVarianceTask. Then invoke the @ref SourceDetectionTask_ "detection" subtask to 

307 detect sources. 

308 

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 

313 

314 @return a pipe.base.Struct with fields 

315 - sources: catalog of detections 

316 - backgrounds: list of backgrounds 

317 """ 

318 if self.config.doScaleVariance: 318 ↛ 321line 318 didn't jump to line 321, because the condition on line 318 was never false

319 varScale = self.scaleVariance.run(exposure.maskedImage) 

320 exposure.getMetadata().add("VARIANCE_SCALE", varScale) 

321 backgrounds = afwMath.BackgroundList() 

322 if self.config.doInsertFakes: 322 ↛ 323line 322 didn't jump to line 323, because the condition on line 322 was never true

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: 328 ↛ 331line 328 didn't jump to line 331, because the condition on line 328 was never false

329 for bg in fpSets.background: 

330 backgrounds.append(bg) 

331 return Struct(outputSources=sources, outputBackgrounds=backgrounds, outputExposure=exposure) 

332 

333 def write(self, results, patchRef): 

334 """! 

335 @brief Write out results from runDetection. 

336 

337 @param[in] exposure: Exposure to write out 

338 @param[in] results: Struct returned from runDetection 

339 @param[in] patchRef: data reference for patch 

340 """ 

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: 344 ↛ 345line 344 didn't jump to line 345, because the condition on line 344 was never true

345 patchRef.put(results.outputExposure, "fakes_" + coaddName + "_calexp") 

346 else: 

347 patchRef.put(results.outputExposure, coaddName + "_calexp") 

348 

349############################################################################################################## 

350 

351 

352class DeblendCoaddSourcesConfig(Config): 

353 """DeblendCoaddSourcesConfig 

354 

355 Configuration parameters for the `DeblendCoaddSourcesTask`. 

356 """ 

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, 

362 default=True, 

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, 

367 default=False, 

368 doc="Should be set to True if fake sources have been inserted into the input data.") 

369 

370 def setDefaults(self): 

371 Config.setDefaults(self) 

372 self.singleBandDeblend.propagateAllPeaks = True 

373 

374 

375class DeblendCoaddSourcesRunner(MergeSourcesRunner): 

376 """Task runner for the `MergeSourcesTask` 

377 

378 Required because the run method requires a list of 

379 dataRefs rather than a single dataRef. 

380 """ 

381 @staticmethod 

382 def getTargetList(parsedCmd, **kwargs): 

383 """Provide a list of patch references for each patch, tract, filter combo. 

384 

385 Parameters 

386 ---------- 

387 parsedCmd: 

388 The parsed command 

389 kwargs: 

390 Keyword arguments passed to the task 

391 

392 Returns 

393 ------- 

394 targetList: list 

395 List of tuples, where each tuple is a (dataRef, kwargs) pair. 

396 """ 

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()] 

400 

401 

402class DeblendCoaddSourcesTask(CmdLineTask): 

403 """Deblend the sources in a merged catalog 

404 

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 

413 from the deblender. 

414 

415 `pipe.tasks.multiband.DeblendCoaddSourcesTask Description 

416 --------------------------------------------------------- 

417 ` 

418 

419 Parameters 

420 ---------- 

421 butler: `Butler` 

422 Butler used to read the input schemas from disk or 

423 construct the reference catalog loader, if `schema` or `peakSchema` or 

424 schema: `Schema` 

425 The schema of the merged detection catalog as an input to this task. 

426 peakSchema: `Schema` 

427 The schema of the `PeakRecord`s in the `Footprint`s in the merged detection catalog 

428 """ 

429 ConfigClass = DeblendCoaddSourcesConfig 

430 RunnerClass = DeblendCoaddSourcesRunner 

431 _DefaultName = "deblendCoaddSources" 

432 makeIdFactory = _makeMakeIdFactory("MergedCoaddId", includeBand=False) 

433 

434 @classmethod 

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") 

441 return parser 

442 

443 def __init__(self, butler=None, schema=None, peakSchema=None, **kwargs): 

444 CmdLineTask.__init__(self, **kwargs) 

445 if schema is None: 445 ↛ 448line 445 didn't jump to line 448, because the condition on line 445 was never false

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: 451 ↛ 455line 451 didn't jump to line 455, because the condition on line 451 was never false

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 

454 

455 if self.config.simultaneous: 455 ↛ 458line 455 didn't jump to line 458, because the condition on line 455 was never false

456 self.makeSubtask("multiBandDeblend", schema=self.schema, peakSchema=peakSchema) 

457 else: 

458 self.makeSubtask("singleBandDeblend", schema=self.schema, peakSchema=peakSchema) 

459 

460 def getSchemaCatalogs(self): 

461 """Return a dict of empty catalogs for each catalog dataset produced by this task. 

462 

463 Returns 

464 ------- 

465 result: dict 

466 Dictionary of empty catalogs, with catalog names as keys. 

467 """ 

468 catalog = afwTable.SourceCatalog(self.schema) 

469 return {self.config.coaddName + "Coadd_deblendedFlux": catalog, 

470 self.config.coaddName + "Coadd_deblendedModel": catalog} 

471 

472 def runDataRef(self, patchRefList, psfCache=100): 

473 """Deblend the patch 

474 

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. 

480 

481 Parameters 

482 ---------- 

483 patchRefList: list 

484 List of data references for each filter 

485 """ 

486 

487 if self.config.hasFakes: 487 ↛ 488line 487 didn't jump to line 488, because the condition on line 487 was never true

488 coaddType = "fakes_" + self.config.coaddName 

489 else: 

490 coaddType = self.config.coaddName 

491 

492 if self.config.simultaneous: 492 ↛ 513line 492 didn't jump to line 513, because the condition on line 492 was never false

493 # Use SCARLET to simultaneously deblend across filters 

494 filters = [] 

495 exposures = [] 

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) 

501 # Sort inputs by band to match Gen3 order of inputs 

502 exposures = [exposure for _, exposure in sorted(zip(filters, exposures))] 

503 patchRefList = [patchRef for _, patchRef in sorted(zip(filters, patchRefList))] 

504 filters.sort() 

505 # The input sources are the same for all bands, since it is a merged catalog 

506 sources = self.readSources(patchRef) 

507 exposure = afwImage.MultibandExposure.fromExposures(filters, exposures) 

508 templateCatalogs = self.multiBandDeblend.run(exposure, sources) 

509 for n in range(len(patchRefList)): 

510 self.write(patchRefList[n], templateCatalogs[filters[n]]) 

511 else: 

512 # Use the singeband deblender to deblend each band separately 

513 for patchRef in patchRefList: 

514 exposure = patchRef.get(coaddType + "Coadd_calexp", immediate=True) 

515 exposure.getPsf().setCacheCapacity(psfCache) 

516 sources = self.readSources(patchRef) 

517 self.singleBandDeblend.run(exposure, sources) 

518 self.write(patchRef, sources) 

519 

520 def readSources(self, dataRef): 

521 """Read merged catalog 

522 

523 Read the catalog of merged detections and create a catalog 

524 in a single band. 

525 

526 Parameters 

527 ---------- 

528 dataRef: data reference 

529 Data reference for catalog of merged detections 

530 

531 Returns 

532 ------- 

533 sources: `SourceCatalog` 

534 List of sources in merged catalog 

535 

536 We also need to add columns to hold the measurements we're about to make 

537 so we can measure in-place. 

538 """ 

539 merged = dataRef.get(self.config.coaddName + "Coadd_mergeDet", immediate=True) 

540 self.log.info("Read %d detections: %s", len(merged), dataRef.dataId) 

541 idFactory = self.makeIdFactory(dataRef) 

542 # There may be gaps in the mergeDet catalog, which will cause the 

543 # source ids to be inconsistent. So we update the id factory 

544 # with the largest id already in the catalog. 

545 maxId = np.max(merged["id"]) 

546 idFactory.notify(maxId) 

547 table = afwTable.SourceTable.make(self.schema, idFactory) 

548 sources = afwTable.SourceCatalog(table) 

549 sources.extend(merged, self.schemaMapper) 

550 return sources 

551 

552 def write(self, dataRef, sources): 

553 """Write the source catalog(s) 

554 

555 Parameters 

556 ---------- 

557 dataRef: Data Reference 

558 Reference to the output catalog. 

559 sources: `SourceCatalog` 

560 Flux conserved sources to write to file. 

561 If using the single band deblender, this is the catalog 

562 generated. 

563 template_sources: `SourceCatalog` 

564 Source catalog using the multiband template models 

565 as footprints. 

566 """ 

567 dataRef.put(sources, self.config.coaddName + "Coadd_deblendedFlux") 

568 self.log.info("Wrote %d sources: %s", len(sources), dataRef.dataId) 

569 

570 def writeMetadata(self, dataRefList): 

571 """Write the metadata produced from processing the data. 

572 Parameters 

573 ---------- 

574 dataRefList 

575 List of Butler data references used to write the metadata. 

576 The metadata is written to dataset type `CmdLineTask._getMetadataName`. 

577 """ 

578 for dataRef in dataRefList: 

579 try: 

580 metadataName = self._getMetadataName() 

581 if metadataName is not None: 

582 dataRef.put(self.getFullMetadata(), metadataName) 

583 except Exception as e: 

584 self.log.warning("Could not persist metadata for dataId=%s: %s", dataRef.dataId, e) 

585 

586 

587class MeasureMergedCoaddSourcesConnections(PipelineTaskConnections, 

588 dimensions=("tract", "patch", "band", "skymap"), 

589 defaultTemplates={"inputCoaddName": "deep", 

590 "outputCoaddName": "deep"}): 

591 inputSchema = cT.InitInput( 

592 doc="Input schema for measure merged task produced by a deblender or detection task", 

593 name="{inputCoaddName}Coadd_deblendedFlux_schema", 

594 storageClass="SourceCatalog" 

595 ) 

596 outputSchema = cT.InitOutput( 

597 doc="Output schema after all new fields are added by task", 

598 name="{inputCoaddName}Coadd_meas_schema", 

599 storageClass="SourceCatalog" 

600 ) 

601 refCat = cT.PrerequisiteInput( 

602 doc="Reference catalog used to match measured sources against known sources", 

603 name="ref_cat", 

604 storageClass="SimpleCatalog", 

605 dimensions=("skypix",), 

606 deferLoad=True, 

607 multiple=True 

608 ) 

609 exposure = cT.Input( 

610 doc="Input coadd image", 

611 name="{inputCoaddName}Coadd_calexp", 

612 storageClass="ExposureF", 

613 dimensions=("tract", "patch", "band", "skymap") 

614 ) 

615 skyMap = cT.Input( 

616 doc="SkyMap to use in processing", 

617 name=BaseSkyMap.SKYMAP_DATASET_TYPE_NAME, 

618 storageClass="SkyMap", 

619 dimensions=("skymap",), 

620 ) 

621 visitCatalogs = cT.Input( 

622 doc="Source catalogs for visits which overlap input tract, patch, band. Will be " 

623 "further filtered in the task for the purpose of propagating flags from image calibration " 

624 "and characterization to codd objects", 

625 name="src", 

626 dimensions=("instrument", "visit", "detector"), 

627 storageClass="SourceCatalog", 

628 multiple=True 

629 ) 

630 inputCatalog = cT.Input( 

631 doc=("Name of the input catalog to use." 

632 "If the single band deblender was used this should be 'deblendedFlux." 

633 "If the multi-band deblender was used this should be 'deblendedModel, " 

634 "or deblendedFlux if the multiband deblender was configured to output " 

635 "deblended flux catalogs. If no deblending was performed this should " 

636 "be 'mergeDet'"), 

637 name="{inputCoaddName}Coadd_deblendedFlux", 

638 storageClass="SourceCatalog", 

639 dimensions=("tract", "patch", "band", "skymap"), 

640 ) 

641 outputSources = cT.Output( 

642 doc="Source catalog containing all the measurement information generated in this task", 

643 name="{outputCoaddName}Coadd_meas", 

644 dimensions=("tract", "patch", "band", "skymap"), 

645 storageClass="SourceCatalog", 

646 ) 

647 matchResult = cT.Output( 

648 doc="Match catalog produced by configured matcher, optional on doMatchSources", 

649 name="{outputCoaddName}Coadd_measMatch", 

650 dimensions=("tract", "patch", "band", "skymap"), 

651 storageClass="Catalog", 

652 ) 

653 denormMatches = cT.Output( 

654 doc="Denormalized Match catalog produced by configured matcher, optional on " 

655 "doWriteMatchesDenormalized", 

656 name="{outputCoaddName}Coadd_measMatchFull", 

657 dimensions=("tract", "patch", "band", "skymap"), 

658 storageClass="Catalog", 

659 ) 

660 

661 def __init__(self, *, config=None): 

662 super().__init__(config=config) 

663 if config.doPropagateFlags is False: 

664 self.inputs -= set(("visitCatalogs",)) 

665 

666 if config.doMatchSources is False: 

667 self.outputs -= set(("matchResult",)) 

668 

669 if config.doWriteMatchesDenormalized is False: 

670 self.outputs -= set(("denormMatches",)) 

671 

672 

673class MeasureMergedCoaddSourcesConfig(PipelineTaskConfig, 

674 pipelineConnections=MeasureMergedCoaddSourcesConnections): 

675 """! 

676 @anchor MeasureMergedCoaddSourcesConfig_ 

677 

678 @brief Configuration parameters for the MeasureMergedCoaddSourcesTask 

679 """ 

680 inputCatalog = Field(dtype=str, default="deblendedFlux", 

681 doc=("Name of the input catalog to use." 

682 "If the single band deblender was used this should be 'deblendedFlux." 

683 "If the multi-band deblender was used this should be 'deblendedModel." 

684 "If no deblending was performed this should be 'mergeDet'")) 

685 measurement = ConfigurableField(target=SingleFrameMeasurementTask, doc="Source measurement") 

686 setPrimaryFlags = ConfigurableField(target=SetPrimaryFlagsTask, doc="Set flags for primary tract/patch") 

687 doPropagateFlags = Field( 

688 dtype=bool, default=True, 

689 doc="Whether to match sources to CCD catalogs to propagate flags (to e.g. identify PSF stars)" 

690 ) 

691 propagateFlags = ConfigurableField(target=PropagateVisitFlagsTask, doc="Propagate visit flags to coadd") 

692 doMatchSources = Field(dtype=bool, default=True, doc="Match sources to reference catalog?") 

693 match = ConfigurableField(target=DirectMatchTask, doc="Matching to reference catalog") 

694 doWriteMatchesDenormalized = Field( 

695 dtype=bool, 

696 default=False, 

697 doc=("Write reference matches in denormalized format? " 

698 "This format uses more disk space, but is more convenient to read."), 

699 ) 

700 coaddName = Field(dtype=str, default="deep", doc="Name of coadd") 

701 psfCache = Field(dtype=int, default=100, doc="Size of psfCache") 

702 checkUnitsParseStrict = Field( 

703 doc="Strictness of Astropy unit compatibility check, can be 'raise', 'warn' or 'silent'", 

704 dtype=str, 

705 default="raise", 

706 ) 

707 doApCorr = Field( 

708 dtype=bool, 

709 default=True, 

710 doc="Apply aperture corrections" 

711 ) 

712 applyApCorr = ConfigurableField( 

713 target=ApplyApCorrTask, 

714 doc="Subtask to apply aperture corrections" 

715 ) 

716 doRunCatalogCalculation = Field( 

717 dtype=bool, 

718 default=True, 

719 doc='Run catalogCalculation task' 

720 ) 

721 catalogCalculation = ConfigurableField( 

722 target=CatalogCalculationTask, 

723 doc="Subtask to run catalogCalculation plugins on catalog" 

724 ) 

725 

726 hasFakes = Field( 

727 dtype=bool, 

728 default=False, 

729 doc="Should be set to True if fake sources have been inserted into the input data." 

730 ) 

731 

732 @property 

733 def refObjLoader(self): 

734 return self.match.refObjLoader 

735 

736 def setDefaults(self): 

737 super().setDefaults() 

738 self.measurement.plugins.names |= ['base_InputCount', 

739 'base_Variance', 

740 'base_LocalPhotoCalib', 

741 'base_LocalWcs'] 

742 self.measurement.plugins['base_PixelFlags'].masksFpAnywhere = ['CLIPPED', 'SENSOR_EDGE', 

743 'INEXACT_PSF'] 

744 self.measurement.plugins['base_PixelFlags'].masksFpCenter = ['CLIPPED', 'SENSOR_EDGE', 

745 'INEXACT_PSF'] 

746 

747 def validate(self): 

748 super().validate() 

749 refCatGen2 = getattr(self.refObjLoader, "ref_dataset_name", None) 

750 if refCatGen2 is not None and refCatGen2 != self.connections.refCat: 

751 raise ValueError( 

752 f"Gen2 ({refCatGen2}) and Gen3 ({self.connections.refCat}) reference catalogs " 

753 f"are different. These options must be kept in sync until Gen2 is retired." 

754 ) 

755 

756 

757## @addtogroup LSST_task_documentation 

758## @{ 

759## @page MeasureMergedCoaddSourcesTask 

760## @ref MeasureMergedCoaddSourcesTask_ "MeasureMergedCoaddSourcesTask" 

761## @copybrief MeasureMergedCoaddSourcesTask 

762## @} 

763 

764 

765class MeasureMergedCoaddSourcesRunner(ButlerInitializedTaskRunner): 

766 """Get the psfCache setting into MeasureMergedCoaddSourcesTask""" 

767 @staticmethod 

768 def getTargetList(parsedCmd, **kwargs): 

769 return ButlerInitializedTaskRunner.getTargetList(parsedCmd, psfCache=parsedCmd.psfCache) 

770 

771 

772class MeasureMergedCoaddSourcesTask(PipelineTask, CmdLineTask): 

773 r"""! 

774 @anchor MeasureMergedCoaddSourcesTask_ 

775 

776 @brief Deblend sources from master catalog in each coadd seperately and measure. 

777 

778 @section pipe_tasks_multiBand_Contents Contents 

779 

780 - @ref pipe_tasks_multiBand_MeasureMergedCoaddSourcesTask_Purpose 

781 - @ref pipe_tasks_multiBand_MeasureMergedCoaddSourcesTask_Initialize 

782 - @ref pipe_tasks_multiBand_MeasureMergedCoaddSourcesTask_Run 

783 - @ref pipe_tasks_multiBand_MeasureMergedCoaddSourcesTask_Config 

784 - @ref pipe_tasks_multiBand_MeasureMergedCoaddSourcesTask_Debug 

785 - @ref pipe_tasks_multiband_MeasureMergedCoaddSourcesTask_Example 

786 

787 @section pipe_tasks_multiBand_MeasureMergedCoaddSourcesTask_Purpose Description 

788 

789 Command-line task that uses peaks and footprints from a master catalog to perform deblending and 

790 measurement in each coadd. 

791 

792 Given a master input catalog of sources (peaks and footprints) or deblender outputs 

793 (including a HeavyFootprint in each band), measure each source on the 

794 coadd. Repeating this procedure with the same master catalog across multiple coadds will generate a 

795 consistent set of child sources. 

796 

797 The deblender retains all peaks and deblends any missing peaks (dropouts in that band) as PSFs. Source 

798 properties are measured and the @c is-primary flag (indicating sources with no children) is set. Visit 

799 flags are propagated to the coadd sources. 

800 

801 Optionally, we can match the coadd sources to an external reference catalog. 

802 

803 @par Inputs: 

804 deepCoadd_mergeDet{tract,patch} or deepCoadd_deblend{tract,patch}: SourceCatalog 

805 @n deepCoadd_calexp{tract,patch,filter}: ExposureF 

806 @par Outputs: 

807 deepCoadd_meas{tract,patch,filter}: SourceCatalog 

808 @par Data Unit: 

809 tract, patch, filter 

810 

811 MeasureMergedCoaddSourcesTask delegates most of its work to a set of sub-tasks: 

812 

813 <DL> 

814 <DT> @ref SingleFrameMeasurementTask_ "measurement" 

815 <DD> Measure source properties of deblended sources.</DD> 

816 <DT> @ref SetPrimaryFlagsTask_ "setPrimaryFlags" 

817 <DD> Set flag 'is-primary' as well as related flags on sources. 'is-primary' is set for sources that are 

818 not at the edge of the field and that have either not been deblended or are the children of deblended 

819 sources</DD> 

820 <DT> @ref PropagateVisitFlagsTask_ "propagateFlags" 

821 <DD> Propagate flags set in individual visits to the coadd.</DD> 

822 <DT> @ref DirectMatchTask_ "match" 

823 <DD> Match input sources to a reference catalog (optional). 

824 </DD> 

825 </DL> 

826 These subtasks may be retargeted as required. 

827 

828 @section pipe_tasks_multiBand_MeasureMergedCoaddSourcesTask_Initialize Task initialization 

829 

830 @copydoc \_\_init\_\_ 

831 

832 @section pipe_tasks_multiBand_MeasureMergedCoaddSourcesTask_Run Invoking the Task 

833 

834 @copydoc run 

835 

836 @section pipe_tasks_multiBand_MeasureMergedCoaddSourcesTask_Config Configuration parameters 

837 

838 See @ref MeasureMergedCoaddSourcesConfig_ 

839 

840 @section pipe_tasks_multiBand_MeasureMergedCoaddSourcesTask_Debug Debug variables 

841 

842 The @link lsst.pipe.base.cmdLineTask.CmdLineTask command line task@endlink interface supports a 

843 flag @c -d to import @b debug.py from your @c PYTHONPATH; see @ref baseDebug for more about @b debug.py 

844 files. 

845 

846 MeasureMergedCoaddSourcesTask has no debug variables of its own because it delegates all the work to 

847 the various sub-tasks. See the documetation for individual sub-tasks for more information. 

848 

849 @section pipe_tasks_multiband_MeasureMergedCoaddSourcesTask_Example A complete example of using 

850 MeasureMergedCoaddSourcesTask 

851 

852 After MeasureMergedCoaddSourcesTask has been run on multiple coadds, we have a set of per-band catalogs. 

853 The next stage in the multi-band processing procedure will merge these measurements into a suitable 

854 catalog for driving forced photometry. 

855 

856 Command-line usage of MeasureMergedCoaddSourcesTask expects a data reference to the coadds 

857 to be processed. 

858 A list of the available optional arguments can be obtained by calling measureCoaddSources.py with the 

859 `--help` command line argument: 

860 @code 

861 measureCoaddSources.py --help 

862 @endcode 

863 

864 To demonstrate usage of the DetectCoaddSourcesTask in the larger context of multi-band processing, we 

865 will process HSC data in the [ci_hsc](https://github.com/lsst/ci_hsc) package. Assuming one has finished 

866 step 6 at @ref pipeTasks_multiBand, one may perform deblending and measure sources in the HSC-I band 

867 coadd as follows: 

868 @code 

869 measureCoaddSources.py $CI_HSC_DIR/DATA --id patch=5,4 tract=0 filter=HSC-I 

870 @endcode 

871 This will process the HSC-I band data. The results are written in 

872 `$CI_HSC_DIR/DATA/deepCoadd-results/HSC-I/0/5,4/meas-HSC-I-0-5,4.fits 

873 

874 It is also necessary to run 

875 @code 

876 measureCoaddSources.py $CI_HSC_DIR/DATA --id patch=5,4 tract=0 filter=HSC-R 

877 @endcode 

878 to generate the sources catalogs for the HSC-R band required by the next step in the multi-band 

879 procedure: @ref MergeMeasurementsTask_ "MergeMeasurementsTask". 

880 """ 

881 _DefaultName = "measureCoaddSources" 

882 ConfigClass = MeasureMergedCoaddSourcesConfig 

883 RunnerClass = MeasureMergedCoaddSourcesRunner 

884 getSchemaCatalogs = _makeGetSchemaCatalogs("meas") 

885 # The IDs we already have are of this type 

886 makeIdFactory = _makeMakeIdFactory("MergedCoaddId", includeBand=False) 

887 

888 @classmethod 

889 def _makeArgumentParser(cls): 

890 parser = ArgumentParser(name=cls._DefaultName) 

891 parser.add_id_argument("--id", "deepCoadd_calexp", 

892 help="data ID, e.g. --id tract=12345 patch=1,2 filter=r", 

893 ContainerClass=ExistingCoaddDataIdContainer) 

894 parser.add_argument("--psfCache", type=int, default=100, help="Size of CoaddPsf cache") 

895 return parser 

896 

897 def __init__(self, butler=None, schema=None, peakSchema=None, refObjLoader=None, initInputs=None, 

898 **kwargs): 

899 """! 

900 @brief Initialize the task. 

901 

902 Keyword arguments (in addition to those forwarded to CmdLineTask.__init__): 

903 @param[in] schema: the schema of the merged detection catalog used as input to this one 

904 @param[in] peakSchema: the schema of the PeakRecords in the Footprints in the merged detection catalog 

905 @param[in] refObjLoader: an instance of LoadReferenceObjectsTasks that supplies an external reference 

906 catalog. May be None if the loader can be constructed from the butler argument or all steps 

907 requiring a reference catalog are disabled. 

908 @param[in] butler: a butler used to read the input schemas from disk or construct the reference 

909 catalog loader, if schema or peakSchema or refObjLoader is None 

910 

911 The task will set its own self.schema attribute to the schema of the output measurement catalog. 

912 This will include all fields from the input schema, as well as additional fields for all the 

913 measurements. 

914 """ 

915 super().__init__(**kwargs) 

916 self.deblended = self.config.inputCatalog.startswith("deblended") 

917 self.inputCatalog = "Coadd_" + self.config.inputCatalog 

918 if initInputs is not None: 918 ↛ 919line 918 didn't jump to line 919, because the condition on line 918 was never true

919 schema = initInputs['inputSchema'].schema 

920 if schema is None: 920 ↛ 923line 920 didn't jump to line 923, because the condition on line 920 was never false

921 assert butler is not None, "Neither butler nor schema is defined" 

922 schema = butler.get(self.config.coaddName + self.inputCatalog + "_schema", immediate=True).schema 

923 self.schemaMapper = afwTable.SchemaMapper(schema) 

924 self.schemaMapper.addMinimalSchema(schema) 

925 self.schema = self.schemaMapper.getOutputSchema() 

926 self.algMetadata = PropertyList() 

927 self.makeSubtask("measurement", schema=self.schema, algMetadata=self.algMetadata) 

928 self.makeSubtask("setPrimaryFlags", schema=self.schema) 

929 if self.config.doMatchSources: 929 ↛ 930line 929 didn't jump to line 930, because the condition on line 929 was never true

930 self.makeSubtask("match", butler=butler, refObjLoader=refObjLoader) 

931 if self.config.doPropagateFlags: 931 ↛ 933line 931 didn't jump to line 933, because the condition on line 931 was never false

932 self.makeSubtask("propagateFlags", schema=self.schema) 

933 self.schema.checkUnits(parse_strict=self.config.checkUnitsParseStrict) 

934 if self.config.doApCorr: 934 ↛ 936line 934 didn't jump to line 936, because the condition on line 934 was never false

935 self.makeSubtask("applyApCorr", schema=self.schema) 

936 if self.config.doRunCatalogCalculation: 936 ↛ 939line 936 didn't jump to line 939, because the condition on line 936 was never false

937 self.makeSubtask("catalogCalculation", schema=self.schema) 

938 

939 self.outputSchema = afwTable.SourceCatalog(self.schema) 

940 

941 def runQuantum(self, butlerQC, inputRefs, outputRefs): 

942 inputs = butlerQC.get(inputRefs) 

943 

944 refObjLoader = ReferenceObjectLoader([ref.datasetRef.dataId for ref in inputRefs.refCat], 

945 inputs.pop('refCat'), config=self.config.refObjLoader, 

946 log=self.log) 

947 self.match.setRefObjLoader(refObjLoader) 

948 

949 # Set psfcache 

950 # move this to run after gen2 deprecation 

951 inputs['exposure'].getPsf().setCacheCapacity(self.config.psfCache) 

952 

953 # Get unique integer ID for IdFactory and RNG seeds 

954 exposureIdInfo = ExposureIdInfo.fromDataId(butlerQC.quantum.dataId, "tract_patch") 

955 inputs['exposureId'] = exposureIdInfo.expId 

956 idFactory = exposureIdInfo.makeSourceIdFactory() 

957 # Transform inputCatalog 

958 table = afwTable.SourceTable.make(self.schema, idFactory) 

959 sources = afwTable.SourceCatalog(table) 

960 sources.extend(inputs.pop('inputCatalog'), self.schemaMapper) 

961 table = sources.getTable() 

962 table.setMetadata(self.algMetadata) # Capture algorithm metadata to write out to the source catalog. 

963 inputs['sources'] = sources 

964 

965 skyMap = inputs.pop('skyMap') 

966 tractNumber = inputRefs.inputCatalog.dataId['tract'] 

967 tractInfo = skyMap[tractNumber] 

968 patchInfo = tractInfo.getPatchInfo(inputRefs.inputCatalog.dataId['patch']) 

969 skyInfo = Struct( 

970 skyMap=skyMap, 

971 tractInfo=tractInfo, 

972 patchInfo=patchInfo, 

973 wcs=tractInfo.getWcs(), 

974 bbox=patchInfo.getOuterBBox() 

975 ) 

976 inputs['skyInfo'] = skyInfo 

977 

978 if self.config.doPropagateFlags: 

979 # Filter out any visit catalog that is not coadd inputs 

980 ccdInputs = inputs['exposure'].getInfo().getCoaddInputs().ccds 

981 visitKey = ccdInputs.schema.find("visit").key 

982 ccdKey = ccdInputs.schema.find("ccd").key 

983 inputVisitIds = set() 

984 ccdRecordsWcs = {} 

985 for ccdRecord in ccdInputs: 

986 visit = ccdRecord.get(visitKey) 

987 ccd = ccdRecord.get(ccdKey) 

988 inputVisitIds.add((visit, ccd)) 

989 ccdRecordsWcs[(visit, ccd)] = ccdRecord.getWcs() 

990 

991 inputCatalogsToKeep = [] 

992 inputCatalogWcsUpdate = [] 

993 for i, dataRef in enumerate(inputRefs.visitCatalogs): 

994 key = (dataRef.dataId['visit'], dataRef.dataId['detector']) 

995 if key in inputVisitIds: 

996 inputCatalogsToKeep.append(inputs['visitCatalogs'][i]) 

997 inputCatalogWcsUpdate.append(ccdRecordsWcs[key]) 

998 inputs['visitCatalogs'] = inputCatalogsToKeep 

999 inputs['wcsUpdates'] = inputCatalogWcsUpdate 

1000 inputs['ccdInputs'] = ccdInputs 

1001 

1002 outputs = self.run(**inputs) 

1003 butlerQC.put(outputs, outputRefs) 

1004 

1005 def runDataRef(self, patchRef, psfCache=100): 

1006 """! 

1007 @brief Deblend and measure. 

1008 

1009 @param[in] patchRef: Patch reference. 

1010 

1011 Set 'is-primary' and related flags. Propagate flags 

1012 from individual visits. Optionally match the sources to a reference catalog and write the matches. 

1013 Finally, write the deblended sources and measurements out. 

1014 """ 

1015 if self.config.hasFakes: 1015 ↛ 1016line 1015 didn't jump to line 1016, because the condition on line 1015 was never true

1016 coaddType = "fakes_" + self.config.coaddName 

1017 else: 

1018 coaddType = self.config.coaddName 

1019 exposure = patchRef.get(coaddType + "Coadd_calexp", immediate=True) 

1020 exposure.getPsf().setCacheCapacity(psfCache) 

1021 sources = self.readSources(patchRef) 

1022 table = sources.getTable() 

1023 table.setMetadata(self.algMetadata) # Capture algorithm metadata to write out to the source catalog. 

1024 skyInfo = getSkyInfo(coaddName=self.config.coaddName, patchRef=patchRef) 

1025 

1026 if self.config.doPropagateFlags: 1026 ↛ 1029line 1026 didn't jump to line 1029, because the condition on line 1026 was never false

1027 ccdInputs = self.propagateFlags.getCcdInputs(exposure) 

1028 else: 

1029 ccdInputs = None 

1030 

1031 expId = getGen3CoaddExposureId(patchRef, coaddName=self.config.coaddName, includeBand=False, 

1032 log=self.log) 

1033 results = self.run(exposure=exposure, sources=sources, skyInfo=skyInfo, exposureId=expId, 

1034 ccdInputs=ccdInputs, butler=patchRef.getButler()) 

1035 

1036 if self.config.doMatchSources: 1036 ↛ 1037line 1036 didn't jump to line 1037, because the condition on line 1036 was never true

1037 self.writeMatches(patchRef, results) 

1038 self.write(patchRef, results.outputSources) 

1039 

1040 def run(self, exposure, sources, skyInfo, exposureId, ccdInputs=None, visitCatalogs=None, wcsUpdates=None, 

1041 butler=None): 

1042 """Run measurement algorithms on the input exposure, and optionally populate the 

1043 resulting catalog with extra information. 

1044 

1045 Parameters 

1046 ---------- 

1047 exposure : `lsst.afw.exposure.Exposure` 

1048 The input exposure on which measurements are to be performed 

1049 sources : `lsst.afw.table.SourceCatalog` 

1050 A catalog built from the results of merged detections, or 

1051 deblender outputs. 

1052 skyInfo : `lsst.pipe.base.Struct` 

1053 A struct containing information about the position of the input exposure within 

1054 a `SkyMap`, the `SkyMap`, its `Wcs`, and its bounding box 

1055 exposureId : `int` or `bytes` 

1056 packed unique number or bytes unique to the input exposure 

1057 ccdInputs : `lsst.afw.table.ExposureCatalog` 

1058 Catalog containing information on the individual visits which went into making 

1059 the exposure 

1060 visitCatalogs : list of `lsst.afw.table.SourceCatalogs` or `None` 

1061 A list of source catalogs corresponding to measurements made on the individual 

1062 visits which went into the input exposure. If None and butler is `None` then 

1063 the task cannot propagate visit flags to the output catalog. 

1064 wcsUpdates : list of `lsst.afw.geom.SkyWcs` or `None` 

1065 If visitCatalogs is not `None` this should be a list of wcs objects which correspond 

1066 to the input visits. Used to put all coordinates to common system. If `None` and 

1067 butler is `None` then the task cannot propagate visit flags to the output catalog. 

1068 butler : `lsst.daf.butler.Butler` or `lsst.daf.persistence.Butler` 

1069 Either a gen2 or gen3 butler used to load visit catalogs 

1070 

1071 Returns 

1072 ------- 

1073 results : `lsst.pipe.base.Struct` 

1074 Results of running measurement task. Will contain the catalog in the 

1075 sources attribute. Optionally will have results of matching to a 

1076 reference catalog in the matchResults attribute, and denormalized 

1077 matches in the denormMatches attribute. 

1078 """ 

1079 self.measurement.run(sources, exposure, exposureId=exposureId) 

1080 

1081 if self.config.doApCorr: 1081 ↛ 1091line 1081 didn't jump to line 1091, because the condition on line 1081 was never false

1082 self.applyApCorr.run( 

1083 catalog=sources, 

1084 apCorrMap=exposure.getInfo().getApCorrMap() 

1085 ) 

1086 

1087 # TODO DM-11568: this contiguous check-and-copy could go away if we 

1088 # reserve enough space during SourceDetection and/or SourceDeblend. 

1089 # NOTE: sourceSelectors require contiguous catalogs, so ensure 

1090 # contiguity now, so views are preserved from here on. 

1091 if not sources.isContiguous(): 1091 ↛ 1092line 1091 didn't jump to line 1092, because the condition on line 1091 was never true

1092 sources = sources.copy(deep=True) 

1093 

1094 if self.config.doRunCatalogCalculation: 1094 ↛ 1097line 1094 didn't jump to line 1097, because the condition on line 1094 was never false

1095 self.catalogCalculation.run(sources) 

1096 

1097 self.setPrimaryFlags.run(sources, skyMap=skyInfo.skyMap, tractInfo=skyInfo.tractInfo, 

1098 patchInfo=skyInfo.patchInfo) 

1099 if self.config.doPropagateFlags: 1099 ↛ 1102line 1099 didn't jump to line 1102, because the condition on line 1099 was never false

1100 self.propagateFlags.run(butler, sources, ccdInputs, exposure.getWcs(), visitCatalogs, wcsUpdates) 

1101 

1102 results = Struct() 

1103 

1104 if self.config.doMatchSources: 1104 ↛ 1105line 1104 didn't jump to line 1105, because the condition on line 1104 was never true

1105 matchResult = self.match.run(sources, exposure.getInfo().getFilterLabel().bandLabel) 

1106 matches = afwTable.packMatches(matchResult.matches) 

1107 matches.table.setMetadata(matchResult.matchMeta) 

1108 results.matchResult = matches 

1109 if self.config.doWriteMatchesDenormalized: 

1110 if matchResult.matches: 

1111 denormMatches = denormalizeMatches(matchResult.matches, matchResult.matchMeta) 

1112 else: 

1113 self.log.warning("No matches, so generating dummy denormalized matches file") 

1114 denormMatches = afwTable.BaseCatalog(afwTable.Schema()) 

1115 denormMatches.setMetadata(PropertyList()) 

1116 denormMatches.getMetadata().add("COMMENT", 

1117 "This catalog is empty because no matches were found.") 

1118 results.denormMatches = denormMatches 

1119 results.denormMatches = denormMatches 

1120 

1121 results.outputSources = sources 

1122 return results 

1123 

1124 def readSources(self, dataRef): 

1125 """! 

1126 @brief Read input sources. 

1127 

1128 @param[in] dataRef: Data reference for catalog of merged detections 

1129 @return List of sources in merged catalog 

1130 

1131 We also need to add columns to hold the measurements we're about to make 

1132 so we can measure in-place. 

1133 """ 

1134 merged = dataRef.get(self.config.coaddName + self.inputCatalog, immediate=True) 

1135 self.log.info("Read %d detections: %s", len(merged), dataRef.dataId) 

1136 idFactory = self.makeIdFactory(dataRef) 

1137 for s in merged: 

1138 idFactory.notify(s.getId()) 

1139 table = afwTable.SourceTable.make(self.schema, idFactory) 

1140 sources = afwTable.SourceCatalog(table) 

1141 sources.extend(merged, self.schemaMapper) 

1142 return sources 

1143 

1144 def writeMatches(self, dataRef, results): 

1145 """! 

1146 @brief Write matches of the sources to the astrometric reference catalog. 

1147 

1148 @param[in] dataRef: data reference 

1149 @param[in] results: results struct from run method 

1150 """ 

1151 if hasattr(results, "matchResult"): 

1152 dataRef.put(results.matchResult, self.config.coaddName + "Coadd_measMatch") 

1153 if hasattr(results, "denormMatches"): 

1154 dataRef.put(results.denormMatches, self.config.coaddName + "Coadd_measMatchFull") 

1155 

1156 def write(self, dataRef, sources): 

1157 """! 

1158 @brief Write the source catalog. 

1159 

1160 @param[in] dataRef: data reference 

1161 @param[in] sources: source catalog 

1162 """ 

1163 dataRef.put(sources, self.config.coaddName + "Coadd_meas") 

1164 self.log.info("Wrote %d sources: %s", len(sources), dataRef.dataId)