Coverage for python/lsst/meas/base/plugins.py: 45%

366 statements  

« prev     ^ index     » next       coverage.py v7.6.10, created at 2025-01-27 23:43 +0000

1# This file is part of meas_base. 

2# 

3# Developed for the LSST Data Management System. 

4# This product includes software developed by the LSST Project 

5# (https://www.lsst.org). 

6# See the COPYRIGHT file at the top-level directory of this distribution 

7# for details of code ownership. 

8# 

9# This program is free software: you can redistribute it and/or modify 

10# it under the terms of the GNU General Public License as published by 

11# the Free Software Foundation, either version 3 of the License, or 

12# (at your option) any later version. 

13# 

14# This program is distributed in the hope that it will be useful, 

15# but WITHOUT ANY WARRANTY; without even the implied warranty of 

16# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 

17# GNU General Public License for more details. 

18# 

19# You should have received a copy of the GNU General Public License 

20# along with this program. If not, see <https://www.gnu.org/licenses/>. 

21 

22"""Definition of measurement plugins. 

23 

24This module defines and registers a series of pure-Python measurement plugins 

25which have trivial implementations. It also wraps measurement algorithms 

26defined in C++ to expose them to the measurement framework. 

27""" 

28 

29import logging 

30import numpy as np 

31 

32import lsst.pex.exceptions 

33import lsst.geom 

34import lsst.afw.detection 

35import lsst.afw.geom 

36 

37from deprecated.sphinx import deprecated 

38from ._measBaseLib import (ApertureFluxControl, ApertureFluxTransform, 

39 BaseTransform, BlendednessAlgorithm, 

40 BlendednessControl, CircularApertureFluxAlgorithm, 

41 GaussianFluxAlgorithm, GaussianFluxControl, 

42 GaussianFluxTransform, LocalBackgroundAlgorithm, 

43 LocalBackgroundControl, LocalBackgroundTransform, 

44 MeasurementError, 

45 # Remove these three on DM-41701 

46 NaiveCentroidAlgorithm, NaiveCentroidControl, NaiveCentroidTransform, 

47 PeakLikelihoodFluxAlgorithm, 

48 PeakLikelihoodFluxControl, 

49 PeakLikelihoodFluxTransform, PixelFlagsAlgorithm, 

50 PixelFlagsControl, PsfFluxAlgorithm, PsfFluxControl, 

51 PsfFluxTransform, ScaledApertureFluxAlgorithm, 

52 ScaledApertureFluxControl, 

53 ScaledApertureFluxTransform, SdssCentroidAlgorithm, 

54 SdssCentroidControl, SdssCentroidTransform, 

55 SdssShapeAlgorithm, SdssShapeControl, 

56 SdssShapeTransform) 

57 

58from .baseMeasurement import BaseMeasurementPluginConfig 

59from .forcedMeasurement import ForcedPlugin, ForcedPluginConfig 

60from .pluginRegistry import register 

61from .pluginsBase import BasePlugin 

62from .sfm import SingleFramePlugin, SingleFramePluginConfig 

63from .transforms import SimpleCentroidTransform 

64from .wrappers import GenericPlugin, wrapSimpleAlgorithm, wrapTransform 

65 

66__all__ = ( 

67 "SingleFrameFPPositionConfig", "SingleFrameFPPositionPlugin", 

68 "SingleFrameJacobianConfig", "SingleFrameJacobianPlugin", 

69 "VarianceConfig", "SingleFrameVariancePlugin", "ForcedVariancePlugin", 

70 "InputCountConfig", "SingleFrameInputCountPlugin", "ForcedInputCountPlugin", 

71 "SingleFramePeakCentroidConfig", "SingleFramePeakCentroidPlugin", 

72 "SingleFrameSkyCoordConfig", "SingleFrameSkyCoordPlugin", 

73 "SingleFrameMomentsClassifierConfig", "SingleFrameMomentsClassifierPlugin", # TODO: Remove in DM-47494. 

74 "SingleFrameClassificationSizeExtendednessConfig", 

75 "SingleFrameClassificationSizeExtendednessPlugin", 

76 "ForcedPeakCentroidConfig", "ForcedPeakCentroidPlugin", 

77 "ForcedTransformedCentroidConfig", "ForcedTransformedCentroidPlugin", 

78 "ForcedTransformedCentroidFromCoordConfig", 

79 "ForcedTransformedCentroidFromCoordPlugin", 

80 "ForcedTransformedShapeConfig", "ForcedTransformedShapePlugin", 

81 "EvaluateLocalPhotoCalibPlugin", "EvaluateLocalPhotoCalibPluginConfig", 

82 "EvaluateLocalWcsPlugin", "EvaluateLocalWcsPluginConfig", 

83) 

84 

85 

86wrapSimpleAlgorithm(PsfFluxAlgorithm, Control=PsfFluxControl, 

87 TransformClass=PsfFluxTransform, executionOrder=BasePlugin.FLUX_ORDER, 

88 shouldApCorr=True, hasLogName=True) 

89wrapSimpleAlgorithm(PeakLikelihoodFluxAlgorithm, Control=PeakLikelihoodFluxControl, 

90 TransformClass=PeakLikelihoodFluxTransform, executionOrder=BasePlugin.FLUX_ORDER) 

91wrapSimpleAlgorithm(GaussianFluxAlgorithm, Control=GaussianFluxControl, 

92 TransformClass=GaussianFluxTransform, executionOrder=BasePlugin.FLUX_ORDER, 

93 shouldApCorr=True) 

94# Remove this line on DM-41701 

95wrapSimpleAlgorithm(NaiveCentroidAlgorithm, Control=NaiveCentroidControl, 

96 TransformClass=NaiveCentroidTransform, executionOrder=BasePlugin.CENTROID_ORDER, 

97 deprecated="Plugin 'NaiveCentroid' is deprecated and will be removed after v27.") 

98wrapSimpleAlgorithm(SdssCentroidAlgorithm, Control=SdssCentroidControl, 

99 TransformClass=SdssCentroidTransform, executionOrder=BasePlugin.CENTROID_ORDER) 

100wrapSimpleAlgorithm(PixelFlagsAlgorithm, Control=PixelFlagsControl, 

101 executionOrder=BasePlugin.FLUX_ORDER) 

102wrapSimpleAlgorithm(SdssShapeAlgorithm, Control=SdssShapeControl, 

103 TransformClass=SdssShapeTransform, executionOrder=BasePlugin.SHAPE_ORDER) 

104wrapSimpleAlgorithm(ScaledApertureFluxAlgorithm, Control=ScaledApertureFluxControl, 

105 TransformClass=ScaledApertureFluxTransform, executionOrder=BasePlugin.FLUX_ORDER) 

106 

107wrapSimpleAlgorithm(CircularApertureFluxAlgorithm, needsMetadata=True, Control=ApertureFluxControl, 

108 TransformClass=ApertureFluxTransform, executionOrder=BasePlugin.FLUX_ORDER) 

109wrapSimpleAlgorithm(BlendednessAlgorithm, Control=BlendednessControl, 

110 TransformClass=BaseTransform, executionOrder=BasePlugin.SHAPE_ORDER) 

111 

112wrapSimpleAlgorithm(LocalBackgroundAlgorithm, Control=LocalBackgroundControl, 

113 TransformClass=LocalBackgroundTransform, executionOrder=BasePlugin.FLUX_ORDER) 

114 

115wrapTransform(PsfFluxTransform) 

116wrapTransform(PeakLikelihoodFluxTransform) 

117wrapTransform(GaussianFluxTransform) 

118# Remove this on DM-41701 

119wrapTransform(NaiveCentroidTransform) 

120wrapTransform(SdssCentroidTransform) 

121wrapTransform(SdssShapeTransform) 

122wrapTransform(ScaledApertureFluxTransform) 

123wrapTransform(ApertureFluxTransform) 

124wrapTransform(LocalBackgroundTransform) 

125 

126log = logging.getLogger(__name__) 

127 

128 

129class SingleFrameFPPositionConfig(SingleFramePluginConfig): 

130 """Configuration for the focal plane position measurment algorithm. 

131 """ 

132 

133 

134@register("base_FPPosition") 

135class SingleFrameFPPositionPlugin(SingleFramePlugin): 

136 """Algorithm to calculate the position of a centroid on the focal plane. 

137 

138 Parameters 

139 ---------- 

140 config : `SingleFrameFPPositionConfig` 

141 Plugin configuraion. 

142 name : `str` 

143 Plugin name. 

144 schema : `lsst.afw.table.Schema` 

145 The schema for the measurement output catalog. New fields will be 

146 added to hold measurements produced by this plugin. 

147 metadata : `lsst.daf.base.PropertySet` 

148 Plugin metadata that will be attached to the output catalog 

149 """ 

150 

151 ConfigClass = SingleFrameFPPositionConfig 

152 

153 @classmethod 

154 def getExecutionOrder(cls): 

155 return cls.SHAPE_ORDER 

156 

157 def __init__(self, config, name, schema, metadata): 

158 SingleFramePlugin.__init__(self, config, name, schema, metadata) 

159 self.focalValue = lsst.afw.table.Point2DKey.addFields(schema, name, "Position on the focal plane", 

160 "mm") 

161 self.focalFlag = schema.addField(name + "_flag", type="Flag", doc="Set to True for any fatal failure") 

162 self.detectorFlag = schema.addField(name + "_missingDetector_flag", type="Flag", 

163 doc="Set to True if detector object is missing") 

164 

165 def measure(self, measRecord, exposure): 

166 det = exposure.getDetector() 

167 if not det: 

168 measRecord.set(self.detectorFlag, True) 

169 fp = lsst.geom.Point2D(np.nan, np.nan) 

170 else: 

171 center = measRecord.getCentroid() 

172 fp = det.transform(center, lsst.afw.cameraGeom.PIXELS, lsst.afw.cameraGeom.FOCAL_PLANE) 

173 measRecord.set(self.focalValue, fp) 

174 

175 def fail(self, measRecord, error=None): 

176 measRecord.set(self.focalFlag, True) 

177 

178 

179class SingleFrameJacobianConfig(SingleFramePluginConfig): 

180 """Configuration for the Jacobian calculation plugin. 

181 """ 

182 

183 pixelScale = lsst.pex.config.Field(dtype=float, default=0.5, doc="Nominal pixel size (arcsec)") 

184 

185 

186@register("base_Jacobian") 

187class SingleFrameJacobianPlugin(SingleFramePlugin): 

188 """Compute the Jacobian and its ratio with a nominal pixel area. 

189 

190 This enables one to compare relative, rather than absolute, pixel areas. 

191 

192 Parameters 

193 ---------- 

194 config : `SingleFrameJacobianConfig` 

195 Plugin configuraion. 

196 name : `str` 

197 Plugin name. 

198 schema : `lsst.afw.table.Schema` 

199 The schema for the measurement output catalog. New fields will be 

200 added to hold measurements produced by this plugin. 

201 metadata : `lsst.daf.base.PropertySet` 

202 Plugin metadata that will be attached to the output catalog 

203 """ 

204 

205 ConfigClass = SingleFrameJacobianConfig 

206 

207 @classmethod 

208 def getExecutionOrder(cls): 

209 return cls.SHAPE_ORDER 

210 

211 def __init__(self, config, name, schema, metadata): 

212 SingleFramePlugin.__init__(self, config, name, schema, metadata) 

213 self.jacValue = schema.addField(name + '_value', type="D", doc="Jacobian correction") 

214 self.jacFlag = schema.addField(name + '_flag', type="Flag", doc="Set to 1 for any fatal failure") 

215 # Calculate one over the area of a nominal reference pixel, where area 

216 # is in arcsec^2. 

217 self.scale = pow(self.config.pixelScale, -2) 

218 

219 def measure(self, measRecord, exposure): 

220 center = measRecord.getCentroid() 

221 # Compute the area of a pixel at a source record's centroid, and take 

222 # the ratio of that with the defined reference pixel area. 

223 result = np.abs(self.scale*exposure.getWcs().linearizePixelToSky( 

224 center, 

225 lsst.geom.arcseconds).getLinear().computeDeterminant()) 

226 measRecord.set(self.jacValue, result) 

227 

228 def fail(self, measRecord, error=None): 

229 measRecord.set(self.jacFlag, True) 

230 

231 

232class VarianceConfig(BaseMeasurementPluginConfig): 

233 """Configuration for the variance calculation plugin. 

234 """ 

235 scale = lsst.pex.config.Field(dtype=float, default=5.0, optional=True, 

236 doc="Scale factor to apply to shape for aperture") 

237 mask = lsst.pex.config.ListField(doc="Mask planes to ignore", dtype=str, 

238 default=["DETECTED", "DETECTED_NEGATIVE", "BAD", "SAT"]) 

239 

240 

241class VariancePlugin(GenericPlugin): 

242 """Compute the median variance corresponding to a footprint. 

243 

244 The aim here is to measure the background variance, rather than that of 

245 the object itself. In order to achieve this, the variance is calculated 

246 over an area scaled up from the shape of the input footprint. 

247 

248 Parameters 

249 ---------- 

250 config : `VarianceConfig` 

251 Plugin configuraion. 

252 name : `str` 

253 Plugin name. 

254 schema : `lsst.afw.table.Schema` 

255 The schema for the measurement output catalog. New fields will be 

256 added to hold measurements produced by this plugin. 

257 metadata : `lsst.daf.base.PropertySet` 

258 Plugin metadata that will be attached to the output catalog 

259 """ 

260 

261 ConfigClass = VarianceConfig 

262 

263 FAILURE_BAD_CENTROID = 1 

264 """Denotes failures due to bad centroiding (`int`). 

265 """ 

266 

267 FAILURE_EMPTY_FOOTPRINT = 2 

268 """Denotes failures due to a lack of usable pixels (`int`). 

269 """ 

270 

271 @classmethod 

272 def getExecutionOrder(cls): 

273 return BasePlugin.FLUX_ORDER 

274 

275 def __init__(self, config, name, schema, metadata): 

276 GenericPlugin.__init__(self, config, name, schema, metadata) 

277 self.varValue = schema.addField(name + '_value', type="D", doc="Variance at object position") 

278 self.emptyFootprintFlag = schema.addField(name + '_flag_emptyFootprint', type="Flag", 

279 doc="Set to True when the footprint has no usable pixels") 

280 

281 # Alias the badCentroid flag to that which is defined for the target 

282 # of the centroid slot. We do not simply rely on the alias because 

283 # that could be changed post-measurement. 

284 schema.getAliasMap().set(name + '_flag_badCentroid', schema.getAliasMap().apply("slot_Centroid_flag")) 

285 

286 def measure(self, measRecord, exposure, center): 

287 # Create an aperture and grow it by scale value defined in config to 

288 # ensure there are enough pixels around the object to get decent 

289 # statistics 

290 if not np.all(np.isfinite(measRecord.getCentroid())): 

291 raise MeasurementError("Bad centroid and/or shape", self.FAILURE_BAD_CENTROID) 

292 aperture = lsst.afw.geom.Ellipse(measRecord.getShape(), measRecord.getCentroid()) 

293 aperture.scale(self.config.scale) 

294 ellipse = lsst.afw.geom.SpanSet.fromShape(aperture) 

295 foot = lsst.afw.detection.Footprint(ellipse) 

296 foot.clipTo(exposure.getBBox(lsst.afw.image.PARENT)) 

297 # Filter out any pixels which have mask bits set corresponding to the 

298 # planes to be excluded (defined in config.mask) 

299 maskedImage = exposure.getMaskedImage() 

300 pixels = lsst.afw.detection.makeHeavyFootprint(foot, maskedImage) 

301 maskBits = maskedImage.getMask().getPlaneBitMask(self.config.mask) 

302 logicalMask = np.logical_not(pixels.getMaskArray() & maskBits) 

303 # Compute the median variance value for each pixel not excluded by the 

304 # mask and write the record. Numpy median is used here instead of 

305 # afw.math makeStatistics because of an issue with data types being 

306 # passed into the C++ layer (DM-2379). 

307 if np.any(logicalMask): 

308 medVar = np.median(pixels.getVarianceArray()[logicalMask]) 

309 measRecord.set(self.varValue, medVar) 

310 else: 

311 raise MeasurementError("Footprint empty, or all pixels are masked, can't compute median", 

312 self.FAILURE_EMPTY_FOOTPRINT) 

313 

314 def fail(self, measRecord, error=None): 

315 # Check that we have an error object and that it is of type 

316 # MeasurementError 

317 if isinstance(error, MeasurementError): 

318 assert error.getFlagBit() in (self.FAILURE_BAD_CENTROID, self.FAILURE_EMPTY_FOOTPRINT) 

319 # FAILURE_BAD_CENTROID handled by alias to centroid record. 

320 if error.getFlagBit() == self.FAILURE_EMPTY_FOOTPRINT: 

321 measRecord.set(self.emptyFootprintFlag, True) 

322 measRecord.set(self.varValue, np.nan) 

323 GenericPlugin.fail(self, measRecord, error) 

324 

325 

326SingleFrameVariancePlugin = VariancePlugin.makeSingleFramePlugin("base_Variance") 

327"""Single-frame version of `VariancePlugin`. 

328""" 

329 

330ForcedVariancePlugin = VariancePlugin.makeForcedPlugin("base_Variance") 

331"""Forced version of `VariancePlugin`. 

332""" 

333 

334 

335class InputCountConfig(BaseMeasurementPluginConfig): 

336 """Configuration for the input image counting plugin. 

337 """ 

338 

339 

340class InputCountPlugin(GenericPlugin): 

341 """Count the number of input images which contributed to a source. 

342 

343 Parameters 

344 ---------- 

345 config : `InputCountConfig` 

346 Plugin configuration. 

347 name : `str` 

348 Plugin name. 

349 schema : `lsst.afw.table.Schema` 

350 The schema for the measurement output catalog. New fields will be 

351 added to hold measurements produced by this plugin. 

352 metadata : `lsst.daf.base.PropertySet` 

353 Plugin metadata that will be attached to the output catalog 

354 

355 Notes 

356 ----- 

357 Information is derived from the image's `~lsst.afw.image.CoaddInputs`. 

358 Note these limitation: 

359 

360 - This records the number of images which contributed to the pixel in the 

361 center of the source footprint, rather than to any or all pixels in the 

362 source. 

363 - Clipping in the coadd is not taken into account. 

364 """ 

365 

366 ConfigClass = InputCountConfig 

367 

368 FAILURE_BAD_CENTROID = 1 

369 """Denotes failures due to bad centroiding (`int`). 

370 """ 

371 

372 FAILURE_NO_INPUTS = 2 

373 """Denotes failures due to the image not having coadd inputs. (`int`) 

374 """ 

375 

376 @classmethod 

377 def getExecutionOrder(cls): 

378 return BasePlugin.SHAPE_ORDER 

379 

380 def __init__(self, config, name, schema, metadata): 

381 GenericPlugin.__init__(self, config, name, schema, metadata) 

382 self.numberKey = schema.addField(name + '_value', type="I", 

383 doc="Number of images contributing at center, not including any" 

384 "clipping") 

385 self.noInputsFlag = schema.addField(name + '_flag_noInputs', type="Flag", 

386 doc="No coadd inputs available") 

387 # Alias the badCentroid flag to that which is defined for the target of 

388 # the centroid slot. We do not simply rely on the alias because that 

389 # could be changed post-measurement. 

390 schema.getAliasMap().set(name + '_flag_badCentroid', schema.getAliasMap().apply("slot_Centroid_flag")) 

391 

392 def measure(self, measRecord, exposure, center): 

393 if not exposure.getInfo().getCoaddInputs(): 

394 raise MeasurementError("No coadd inputs defined.", self.FAILURE_NO_INPUTS) 

395 if not np.all(np.isfinite(center)): 

396 raise MeasurementError("Source has a bad centroid.", self.FAILURE_BAD_CENTROID) 

397 

398 ccds = exposure.getInfo().getCoaddInputs().ccds 

399 measRecord.set(self.numberKey, len(ccds.subsetContaining(center, exposure.getWcs()))) 

400 

401 def fail(self, measRecord, error=None): 

402 if error is not None: 

403 assert error.getFlagBit() in (self.FAILURE_BAD_CENTROID, self.FAILURE_NO_INPUTS) 

404 # FAILURE_BAD_CENTROID handled by alias to centroid record. 

405 if error.getFlagBit() == self.FAILURE_NO_INPUTS: 

406 measRecord.set(self.noInputsFlag, True) 

407 GenericPlugin.fail(self, measRecord, error) 

408 

409 

410SingleFrameInputCountPlugin = InputCountPlugin.makeSingleFramePlugin("base_InputCount") 

411"""Single-frame version of `InputCoutPlugin`. 

412""" 

413 

414ForcedInputCountPlugin = InputCountPlugin.makeForcedPlugin("base_InputCount") 

415"""Forced version of `InputCoutPlugin`. 

416""" 

417 

418 

419class EvaluateLocalPhotoCalibPluginConfig(BaseMeasurementPluginConfig): 

420 """Configuration for the variance calculation plugin. 

421 """ 

422 

423 

424class EvaluateLocalPhotoCalibPlugin(GenericPlugin): 

425 """Evaluate the local value of the Photometric Calibration in the exposure. 

426 

427 The aim is to store the local calib value within the catalog for later 

428 use in the Science Data Model functors. 

429 """ 

430 ConfigClass = EvaluateLocalPhotoCalibPluginConfig 

431 

432 @classmethod 

433 def getExecutionOrder(cls): 

434 return BasePlugin.FLUX_ORDER 

435 

436 def __init__(self, config, name, schema, metadata): 

437 GenericPlugin.__init__(self, config, name, schema, metadata) 

438 self.photoKey = schema.addField( 

439 name, 

440 type="D", 

441 doc="Local approximation of the PhotoCalib calibration factor at " 

442 "the location of the src.") 

443 self.photoErrKey = schema.addField( 

444 "%sErr" % name, 

445 type="D", 

446 doc="Error on the local approximation of the PhotoCalib " 

447 "calibration factor at the location of the src.") 

448 

449 def measure(self, measRecord, exposure, center): 

450 photoCalib = exposure.getPhotoCalib() 

451 if photoCalib is None: 

452 log.debug( 

453 "%s: photoCalib is None. Setting localPhotoCalib to NaN for record %d", 

454 self.name, 

455 measRecord.getId(), 

456 ) 

457 calib = np.nan 

458 calibErr = np.nan 

459 measRecord.set(self._failKey, True) 

460 else: 

461 calib = photoCalib.getLocalCalibration(center) 

462 calibErr = photoCalib.getCalibrationErr() 

463 measRecord.set(self.photoKey, calib) 

464 measRecord.set(self.photoErrKey, calibErr) 

465 

466 

467SingleFrameEvaluateLocalPhotoCalibPlugin = EvaluateLocalPhotoCalibPlugin.makeSingleFramePlugin( 

468 "base_LocalPhotoCalib") 

469"""Single-frame version of `EvaluatePhotoCalibPlugin`. 

470""" 

471 

472ForcedEvaluateLocalPhotoCalibPlugin = EvaluateLocalPhotoCalibPlugin.makeForcedPlugin( 

473 "base_LocalPhotoCalib") 

474"""Forced version of `EvaluatePhotoCalibPlugin`. 

475""" 

476 

477 

478class EvaluateLocalWcsPluginConfig(BaseMeasurementPluginConfig): 

479 """Configuration for the variance calculation plugin. 

480 """ 

481 

482 

483class EvaluateLocalWcsPlugin(GenericPlugin): 

484 """Evaluate the local, linear approximation of the Wcs. 

485 

486 The aim is to store the local calib value within the catalog for later 

487 use in the Science Data Model functors. 

488 """ 

489 ConfigClass = EvaluateLocalWcsPluginConfig 

490 _scale = (1.0 * lsst.geom.arcseconds).asDegrees() 

491 

492 @classmethod 

493 def getExecutionOrder(cls): 

494 return BasePlugin.FLUX_ORDER 

495 

496 def __init__(self, config, name, schema, metadata): 

497 GenericPlugin.__init__(self, config, name, schema, metadata) 

498 self.cdMatrix11Key = schema.addField( 

499 f"{name}_CDMatrix_1_1", 

500 type="D", 

501 doc="(1, 1) element of the CDMatrix for the linear approximation " 

502 "of the WCS at the src location. Gives units in radians.") 

503 self.cdMatrix12Key = schema.addField( 

504 f"{name}_CDMatrix_1_2", 

505 type="D", 

506 doc="(1, 2) element of the CDMatrix for the linear approximation " 

507 "of the WCS at the src location. Gives units in radians.") 

508 self.cdMatrix21Key = schema.addField( 

509 f"{name}_CDMatrix_2_1", 

510 type="D", 

511 doc="(2, 1) element of the CDMatrix for the linear approximation " 

512 "of the WCS at the src location. Gives units in radians.") 

513 self.cdMatrix22Key = schema.addField( 

514 f"{name}_CDMatrix_2_2", 

515 type="D", 

516 doc="(2, 2) element of the CDMatrix for the linear approximation " 

517 "of the WCS at the src location. Gives units in radians.") 

518 

519 def measure(self, measRecord, exposure, center): 

520 wcs = exposure.getWcs() 

521 if wcs is None: 

522 log.debug( 

523 "%s: WCS is None. Setting localWcs matrix values to NaN for record %d", 

524 self.name, 

525 measRecord.getId(), 

526 ) 

527 localMatrix = np.array([[np.nan, np.nan], [np.nan, np.nan]]) 

528 measRecord.set(self._failKey, True) 

529 else: 

530 localMatrix = self.makeLocalTransformMatrix(wcs, center) 

531 measRecord.set(self.cdMatrix11Key, localMatrix[0, 0]) 

532 measRecord.set(self.cdMatrix12Key, localMatrix[0, 1]) 

533 measRecord.set(self.cdMatrix21Key, localMatrix[1, 0]) 

534 measRecord.set(self.cdMatrix22Key, localMatrix[1, 1]) 

535 

536 def makeLocalTransformMatrix(self, wcs, center): 

537 """Create a local, linear approximation of the wcs transformation 

538 matrix. 

539 

540 The approximation is created as if the center is at RA=0, DEC=0. All 

541 comparing x,y coordinate are relative to the position of center. Matrix 

542 is initially calculated with units arcseconds and then converted to 

543 radians. This yields higher precision results due to quirks in AST. 

544 

545 Parameters 

546 ---------- 

547 wcs : `lsst.afw.geom.SkyWcs` 

548 Wcs to approximate 

549 center : `lsst.geom.Point2D` 

550 Point at which to evaluate the LocalWcs. 

551 

552 Returns 

553 ------- 

554 localMatrix : `numpy.ndarray` 

555 Matrix representation the local wcs approximation with units 

556 radians. 

557 """ 

558 skyCenter = wcs.pixelToSky(center) 

559 localGnomonicWcs = lsst.afw.geom.makeSkyWcs( 

560 center, skyCenter, np.diag((self._scale, self._scale))) 

561 measurementToLocalGnomonic = wcs.getTransform().then( 

562 localGnomonicWcs.getTransform().inverted() 

563 ) 

564 localMatrix = measurementToLocalGnomonic.getJacobian(center) 

565 return np.radians(localMatrix / 3600) 

566 

567 

568SingleFrameEvaluateLocalWcsPlugin = EvaluateLocalWcsPlugin.makeSingleFramePlugin("base_LocalWcs") 

569"""Single-frame version of `EvaluateLocalWcsPlugin`. 

570""" 

571 

572ForcedEvaluateLocalWcsPlugin = EvaluateLocalWcsPlugin.makeForcedPlugin("base_LocalWcs") 

573"""Forced version of `EvaluateLocalWcsPlugin`. 

574""" 

575 

576 

577class SingleFramePeakCentroidConfig(SingleFramePluginConfig): 

578 """Configuration for the single frame peak centroiding algorithm. 

579 """ 

580 

581 

582@register("base_PeakCentroid") 

583class SingleFramePeakCentroidPlugin(SingleFramePlugin): 

584 """Record the highest peak in a source footprint as its centroid. 

585 

586 This is of course a relatively poor measure of the true centroid of the 

587 object; this algorithm is provided mostly for testing and debugging. 

588 

589 Parameters 

590 ---------- 

591 config : `SingleFramePeakCentroidConfig` 

592 Plugin configuraion. 

593 name : `str` 

594 Plugin name. 

595 schema : `lsst.afw.table.Schema` 

596 The schema for the measurement output catalog. New fields will be 

597 added to hold measurements produced by this plugin. 

598 metadata : `lsst.daf.base.PropertySet` 

599 Plugin metadata that will be attached to the output catalog 

600 """ 

601 

602 ConfigClass = SingleFramePeakCentroidConfig 

603 

604 @classmethod 

605 def getExecutionOrder(cls): 

606 return cls.CENTROID_ORDER 

607 

608 def __init__(self, config, name, schema, metadata): 

609 SingleFramePlugin.__init__(self, config, name, schema, metadata) 

610 self.keyX = schema.addField(name + "_x", type="D", doc="peak centroid", units="pixel") 

611 self.keyY = schema.addField(name + "_y", type="D", doc="peak centroid", units="pixel") 

612 self.flag = schema.addField(name + "_flag", type="Flag", doc="Centroiding failed") 

613 

614 def measure(self, measRecord, exposure): 

615 peak = measRecord.getFootprint().getPeaks()[0] 

616 measRecord.set(self.keyX, peak.getFx()) 

617 measRecord.set(self.keyY, peak.getFy()) 

618 

619 def fail(self, measRecord, error=None): 

620 measRecord.set(self.flag, True) 

621 

622 @staticmethod 

623 def getTransformClass(): 

624 return SimpleCentroidTransform 

625 

626 

627class SingleFrameSkyCoordConfig(SingleFramePluginConfig): 

628 """Configuration for the sky coordinates algorithm. 

629 """ 

630 

631 

632@register("base_SkyCoord") 

633class SingleFrameSkyCoordPlugin(SingleFramePlugin): 

634 """Record the sky position of an object based on its centroid slot and WCS. 

635 

636 The position is record in the ``coord`` field, which is part of the 

637 `~lsst.afw.table.SourceCatalog` minimal schema. 

638 

639 Parameters 

640 ---------- 

641 config : `SingleFrameSkyCoordConfig` 

642 Plugin configuraion. 

643 name : `str` 

644 Plugin name. 

645 schema : `lsst.afw.table.Schema` 

646 The schema for the measurement output catalog. New fields will be 

647 added to hold measurements produced by this plugin. 

648 metadata : `lsst.daf.base.PropertySet` 

649 Plugin metadata that will be attached to the output catalog 

650 """ 

651 

652 ConfigClass = SingleFrameSkyCoordConfig 

653 

654 @classmethod 

655 def getExecutionOrder(cls): 

656 return cls.SHAPE_ORDER 

657 

658 def measure(self, measRecord, exposure): 

659 # There should be a base class method for handling this exception. Put 

660 # this on a later ticket. Also, there should be a python Exception of 

661 # the appropriate type for this error 

662 if not exposure.hasWcs(): 

663 raise RuntimeError("Wcs not attached to exposure. Required for " + self.name + " algorithm") 

664 measRecord.updateCoord(exposure.getWcs()) 

665 

666 def fail(self, measRecord, error=None): 

667 # Override fail() to do nothing in the case of an exception: this is 

668 # not ideal, but we don't have a place to put failures because we 

669 # don't allocate any fields. Should consider fixing as part of 

670 # DM-1011 

671 pass 

672 

673 

674class SingleFrameClassificationSizeExtendednessConfig(SingleFramePluginConfig): 

675 """Configuration for moments-based star-galaxy classifier.""" 

676 

677 exponent = lsst.pex.config.Field[float]( 

678 doc="Exponent to raise the PSF size squared (Ixx + Iyy) to, " 

679 "in the likelihood normalization", 

680 default=0.5, 

681 ) 

682 

683 

684@register("base_ClassificationSizeExtendedness") 

685class SingleFrameClassificationSizeExtendednessPlugin(SingleFramePlugin): 

686 """Classify objects by comparing their moments-based trace radius to PSF's. 

687 

688 The plugin computes chi^2 as ((T_obj - T_psf)/T_psf^exponent)^2, where 

689 T_obj is the sum of Ixx and Iyy moments of the object, and T_psf is the 

690 sum of Ixx and Iyy moments of the PSF. The exponent is configurable. 

691 The measure of being a galaxy is then 1 - exp(-0.5*chi^2). 

692 

693 Parameters 

694 ---------- 

695 config : `SingleFrameClassificationSizeExtendednessConfig` 

696 Plugin configuration. 

697 name : `str` 

698 Plugin name. 

699 schema : `~lsst.afw.table.Schema` 

700 The schema for the measurement output catalog. New fields will be 

701 added to hold measurements produced by this plugin. 

702 metadata : `~lsst.daf.base.PropertySet` 

703 Plugin metadata that will be attached to the output catalog. 

704 

705 Notes 

706 ----- 

707 The ``measure`` method of the plugin requires a value for the ``exposure`` 

708 argument to maintain consistent API, but it is not used in the measurement. 

709 """ 

710 

711 ConfigClass = SingleFrameClassificationSizeExtendednessConfig 

712 

713 FAILURE_BAD_SHAPE = 1 

714 """Denotes failures due to bad shape (`int`). 

715 """ 

716 

717 @classmethod 

718 def getExecutionOrder(cls): 

719 return cls.FLUX_ORDER 

720 

721 def __init__(self, config, name, schema, metadata): 

722 SingleFramePlugin.__init__(self, config, name, schema, metadata) 

723 self.key = schema.addField(name + "_value", 

724 type="D", 

725 doc="Measure of being a galaxy based on trace of second order moments", 

726 ) 

727 self.flag = schema.addField(name + "_flag", type="Flag", doc="Moments-based classification failed") 

728 

729 def measure(self, measRecord, exposure) -> None: 

730 # Docstring inherited. 

731 

732 if measRecord.getShapeFlag(): 

733 raise MeasurementError( 

734 "Shape flag is set. Required for " + self.name + " algorithm", 

735 self.FAILURE_BAD_SHAPE, 

736 ) 

737 

738 shape = measRecord.getShape() 

739 psf_shape = measRecord.getPsfShape() 

740 

741 ixx = shape.getIxx() 

742 iyy = shape.getIyy() 

743 ixx_psf = psf_shape.getIxx() 

744 iyy_psf = psf_shape.getIyy() 

745 

746 object_t = ixx + iyy 

747 psf_t = ixx_psf + iyy_psf 

748 

749 chi_sq = ((object_t - psf_t)/(psf_t**self.config.exponent))**2. 

750 likelihood = 1. - np.exp(-0.5*chi_sq) 

751 measRecord.set(self.key, likelihood) 

752 

753 def fail(self, measRecord, error=None) -> None: 

754 # Docstring inherited. 

755 measRecord.set(self.key, np.nan) 

756 measRecord.set(self.flag, True) 

757 

758 

759@deprecated(reason="Use SingleFrameClassificationSizeExtendednessConfig instead", version="v29.0.0", 

760 category=FutureWarning) 

761class SingleFrameMomentsClassifierConfig(SingleFrameClassificationSizeExtendednessConfig): 

762 pass 

763 

764 

765@deprecated(reason="Use SingleFrameClassificationSizeExtendednessPlugin instead", version="v29.0.0", 

766 category=FutureWarning) 

767class SingleFrameMomentsClassifierPlugin(SingleFrameClassificationSizeExtendednessPlugin): 

768 ConfigClass = SingleFrameMomentsClassifierConfig 

769 

770 

771class ForcedPeakCentroidConfig(ForcedPluginConfig): 

772 """Configuration for the forced peak centroid algorithm. 

773 """ 

774 

775 

776@register("base_PeakCentroid") 

777class ForcedPeakCentroidPlugin(ForcedPlugin): 

778 """Record the highest peak in a source footprint as its centroid. 

779 

780 This is of course a relatively poor measure of the true centroid of the 

781 object; this algorithm is provided mostly for testing and debugging. 

782 

783 This is similar to `SingleFramePeakCentroidPlugin`, except that transforms 

784 the peak coordinate from the original (reference) coordinate system to the 

785 coordinate system of the exposure being measured. 

786 

787 Parameters 

788 ---------- 

789 config : `ForcedPeakCentroidConfig` 

790 Plugin configuraion. 

791 name : `str` 

792 Plugin name. 

793 schemaMapper : `lsst.afw.table.SchemaMapper` 

794 A mapping from reference catalog fields to output 

795 catalog fields. Output fields are added to the output schema. 

796 metadata : `lsst.daf.base.PropertySet` 

797 Plugin metadata that will be attached to the output catalog. 

798 """ 

799 

800 ConfigClass = ForcedPeakCentroidConfig 

801 

802 @classmethod 

803 def getExecutionOrder(cls): 

804 return cls.CENTROID_ORDER 

805 

806 def __init__(self, config, name, schemaMapper, metadata): 

807 ForcedPlugin.__init__(self, config, name, schemaMapper, metadata) 

808 schema = schemaMapper.editOutputSchema() 

809 self.keyX = schema.addField(name + "_x", type="D", doc="peak centroid", units="pixel") 

810 self.keyY = schema.addField(name + "_y", type="D", doc="peak centroid", units="pixel") 

811 

812 def measure(self, measRecord, exposure, refRecord, refWcs): 

813 targetWcs = exposure.getWcs() 

814 peak = refRecord.getFootprint().getPeaks()[0] 

815 result = lsst.geom.Point2D(peak.getFx(), peak.getFy()) 

816 result = targetWcs.skyToPixel(refWcs.pixelToSky(result)) 

817 measRecord.set(self.keyX, result.getX()) 

818 measRecord.set(self.keyY, result.getY()) 

819 

820 @staticmethod 

821 def getTransformClass(): 

822 return SimpleCentroidTransform 

823 

824 

825class ForcedTransformedCentroidConfig(ForcedPluginConfig): 

826 """Configuration for the forced transformed centroid algorithm. 

827 """ 

828 

829 

830@register("base_TransformedCentroid") 

831class ForcedTransformedCentroidPlugin(ForcedPlugin): 

832 """Record the transformation of the reference catalog centroid. 

833 

834 The centroid recorded in the reference catalog is tranformed to the 

835 measurement coordinate system and stored. 

836 

837 Parameters 

838 ---------- 

839 config : `ForcedTransformedCentroidConfig` 

840 Plugin configuration 

841 name : `str` 

842 Plugin name 

843 schemaMapper : `lsst.afw.table.SchemaMapper` 

844 A mapping from reference catalog fields to output 

845 catalog fields. Output fields are added to the output schema. 

846 metadata : `lsst.daf.base.PropertySet` 

847 Plugin metadata that will be attached to the output catalog. 

848 

849 Notes 

850 ----- 

851 This is used as the slot centroid by default in forced measurement, 

852 allowing subsequent measurements to simply refer to the slot value just as 

853 they would in single-frame measurement. 

854 """ 

855 

856 ConfigClass = ForcedTransformedCentroidConfig 

857 

858 @classmethod 

859 def getExecutionOrder(cls): 

860 return cls.CENTROID_ORDER 

861 

862 def __init__(self, config, name, schemaMapper, metadata): 

863 ForcedPlugin.__init__(self, config, name, schemaMapper, metadata) 

864 schema = schemaMapper.editOutputSchema() 

865 # Allocate x and y fields, join these into a single FunctorKey for 

866 # ease-of-use. 

867 xKey = schema.addField(name + "_x", type="D", doc="transformed reference centroid column", 

868 units="pixel") 

869 yKey = schema.addField(name + "_y", type="D", doc="transformed reference centroid row", 

870 units="pixel") 

871 self.centroidKey = lsst.afw.table.Point2DKey(xKey, yKey) 

872 # Because we're taking the reference position as given, we don't bother 

873 # transforming its uncertainty and reporting that here, so there are no 

874 # sigma or cov fields. We do propagate the flag field, if it exists. 

875 if "slot_Centroid_flag" in schemaMapper.getInputSchema(): 

876 self.flagKey = schema.addField(name + "_flag", type="Flag", 

877 doc="whether the reference centroid is marked as bad") 

878 else: 

879 self.flagKey = None 

880 

881 def measure(self, measRecord, exposure, refRecord, refWcs): 

882 targetWcs = exposure.getWcs() 

883 if not refWcs == targetWcs: 

884 targetPos = targetWcs.skyToPixel(refWcs.pixelToSky(refRecord.getCentroid())) 

885 measRecord.set(self.centroidKey, targetPos) 

886 else: 

887 measRecord.set(self.centroidKey, refRecord.getCentroid()) 

888 if self.flagKey is not None: 

889 measRecord.set(self.flagKey, refRecord.getCentroidFlag()) 

890 

891 

892class ForcedTransformedCentroidFromCoordConfig(ForcedTransformedCentroidConfig): 

893 """Configuration for the forced transformed coord algorithm. 

894 """ 

895 

896 

897@register("base_TransformedCentroidFromCoord") 

898class ForcedTransformedCentroidFromCoordPlugin(ForcedTransformedCentroidPlugin): 

899 """Record the transformation of the reference catalog coord. 

900 

901 The coord recorded in the reference catalog is tranformed to the 

902 measurement coordinate system and stored. 

903 

904 Parameters 

905 ---------- 

906 config : `ForcedTransformedCentroidFromCoordConfig` 

907 Plugin configuration 

908 name : `str` 

909 Plugin name 

910 schemaMapper : `lsst.afw.table.SchemaMapper` 

911 A mapping from reference catalog fields to output 

912 catalog fields. Output fields are added to the output schema. 

913 metadata : `lsst.daf.base.PropertySet` 

914 Plugin metadata that will be attached to the output catalog. 

915 

916 Notes 

917 ----- 

918 This can be used as the slot centroid in forced measurement when only a 

919 reference coord exist, allowing subsequent measurements to simply refer to 

920 the slot value just as they would in single-frame measurement. 

921 """ 

922 

923 ConfigClass = ForcedTransformedCentroidFromCoordConfig 

924 

925 def measure(self, measRecord, exposure, refRecord, refWcs): 

926 targetWcs = exposure.getWcs() 

927 

928 targetPos = targetWcs.skyToPixel(refRecord.getCoord()) 

929 measRecord.set(self.centroidKey, targetPos) 

930 

931 if self.flagKey is not None: 

932 measRecord.set(self.flagKey, refRecord.getCentroidFlag()) 

933 

934 

935class ForcedTransformedShapeConfig(ForcedPluginConfig): 

936 """Configuration for the forced transformed shape algorithm. 

937 """ 

938 

939 

940@register("base_TransformedShape") 

941class ForcedTransformedShapePlugin(ForcedPlugin): 

942 """Record the transformation of the reference catalog shape. 

943 

944 The shape recorded in the reference catalog is tranformed to the 

945 measurement coordinate system and stored. 

946 

947 Parameters 

948 ---------- 

949 config : `ForcedTransformedShapeConfig` 

950 Plugin configuration 

951 name : `str` 

952 Plugin name 

953 schemaMapper : `lsst.afw.table.SchemaMapper` 

954 A mapping from reference catalog fields to output 

955 catalog fields. Output fields are added to the output schema. 

956 metadata : `lsst.daf.base.PropertySet` 

957 Plugin metadata that will be attached to the output catalog. 

958 

959 Notes 

960 ----- 

961 This is used as the slot shape by default in forced measurement, allowing 

962 subsequent measurements to simply refer to the slot value just as they 

963 would in single-frame measurement. 

964 """ 

965 

966 ConfigClass = ForcedTransformedShapeConfig 

967 

968 @classmethod 

969 def getExecutionOrder(cls): 

970 return cls.SHAPE_ORDER 

971 

972 def __init__(self, config, name, schemaMapper, metadata): 

973 ForcedPlugin.__init__(self, config, name, schemaMapper, metadata) 

974 schema = schemaMapper.editOutputSchema() 

975 # Allocate xx, yy, xy fields, join these into a single FunctorKey for 

976 # ease-of-use. 

977 xxKey = schema.addField(name + "_xx", type="D", doc="transformed reference shape x^2 moment", 

978 units="pixel^2") 

979 yyKey = schema.addField(name + "_yy", type="D", doc="transformed reference shape y^2 moment", 

980 units="pixel^2") 

981 xyKey = schema.addField(name + "_xy", type="D", doc="transformed reference shape xy moment", 

982 units="pixel^2") 

983 self.shapeKey = lsst.afw.table.QuadrupoleKey(xxKey, yyKey, xyKey) 

984 # Because we're taking the reference position as given, we don't bother 

985 # transforming its uncertainty and reporting that here, so there are no 

986 # sigma or cov fields. We do propagate the flag field, if it exists. 

987 if "slot_Shape_flag" in schemaMapper.getInputSchema(): 

988 self.flagKey = schema.addField(name + "_flag", type="Flag", 

989 doc="whether the reference shape is marked as bad") 

990 else: 

991 self.flagKey = None 

992 

993 def measure(self, measRecord, exposure, refRecord, refWcs): 

994 targetWcs = exposure.getWcs() 

995 if not refWcs == targetWcs: 

996 fullTransform = lsst.afw.geom.makeWcsPairTransform(refWcs, targetWcs) 

997 localTransform = lsst.afw.geom.linearizeTransform(fullTransform, refRecord.getCentroid()) 

998 measRecord.set(self.shapeKey, refRecord.getShape().transform(localTransform.getLinear())) 

999 else: 

1000 measRecord.set(self.shapeKey, refRecord.getShape()) 

1001 if self.flagKey is not None: 

1002 measRecord.set(self.flagKey, refRecord.getShapeFlag())