Coverage for python/lsst/ip/isr/crosstalk.py: 77%

489 statements  

« prev     ^ index     » next       coverage.py v7.17.5, created at 2026-11-26 20:25 +0000

1# 

2# LSST Data Management System 

3# Copyright 2008-2017 AURA/LSST. 

4# 

5# This product includes software developed by the 

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

7# 

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

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

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

11# (at your option) any later version. 

12# 

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

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

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

16# GNU General Public License for more details. 

17# 

18# You should have received a copy of the LSST License Statement and 

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

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

21# 

22""" 

23Apply intra-detector crosstalk corrections 

24""" 

25 

26__all__ = ["CrosstalkCalib", "CrosstalkConfig", "CrosstalkTask", 

27 "NullCrosstalkTask"] 

28 

29import numpy as np 

30import warnings 

31from astropy.table import Table 

32from threadpoolctl import threadpool_limits 

33 

34import lsst.afw.math 

35import lsst.afw.detection 

36import lsst.daf.butler 

37from lsst.pex.config import Config, Field, ChoiceField, ListField 

38from lsst.pipe.base import Task 

39 

40from .calibType import IsrCalib 

41from .isrFunctions import gainContext, isTrimmedImage 

42 

43 

44class CrosstalkCalib(IsrCalib): 

45 """Calibration of amp-to-amp crosstalk coefficients. 

46 

47 Parameters 

48 ---------- 

49 detector : `lsst.afw.cameraGeom.Detector`, optional 

50 Detector to use to pull coefficients from. 

51 nAmp : `int`, optional 

52 Number of amplifiers to initialize. 

53 log : `logging.Logger`, optional 

54 Log to write messages to. 

55 **kwargs : 

56 Parameters to pass to parent constructor. 

57 

58 Notes 

59 ----- 

60 The crosstalk attributes stored are: 

61 

62 hasCrosstalk : `bool` 

63 Whether there is crosstalk defined for this detector. 

64 nAmp : `int` 

65 Number of amplifiers in this detector. 

66 crosstalkShape : `tuple` [`int`, `int`] 

67 A tuple containing the shape of the ``coeffs`` matrix. This 

68 should be equivalent to (``nAmp``, ``nAmp``). 

69 coeffs : `numpy.ndarray` 

70 A matrix containing the crosstalk coefficients. coeff[i][j] 

71 contains the coefficients to calculate the contribution 

72 amplifier_j has on amplifier_i (each row[i] contains the 

73 corrections for detector_i). 

74 coeffErr : `numpy.ndarray`, optional 

75 A matrix (as defined by ``coeffs``) containing the standard 

76 distribution of the crosstalk measurements. 

77 coeffNum : `numpy.ndarray`, optional 

78 A matrix containing the number of pixel pairs used to measure 

79 the ``coeffs`` and ``coeffErr``. 

80 coeffValid : `numpy.ndarray`, optional 

81 A matrix of Boolean values indicating if the coefficient is 

82 valid, defined as abs(coeff) > coeffErr / sqrt(coeffNum). 

83 coeffsSqr : `numpy.ndarray`, optional 

84 A matrix containing potential quadratic crosstalk coefficients 

85 (see e.g., Snyder+21, 2001.03223). coeffsSqr[i][j] 

86 contains the coefficients to calculate the contribution 

87 amplifier_j has on amplifier_i (each row[i] contains the 

88 corrections for detector_i). 

89 coeffErrSqr : `numpy.ndarray`, optional 

90 A matrix (as defined by ``coeffsSqr``) containing the standard 

91 distribution of the quadratic term of the crosstalk measurements. 

92 interChip : `dict` [`numpy.ndarray`] 

93 A dictionary keyed by detectorName containing ``coeffs`` 

94 matrices used to correct for inter-chip crosstalk with a 

95 source on the detector indicated. 

96 

97 Version 1.1 adds quadratic coefficients, a matrix with the ratios 

98 of amplifiers gains per detector, and a field to indicate the units 

99 of the numerator and denominator of the source and target signals, with 

100 "adu" meaning "ADU / ADU" and "electron" meaning "e- / e-". 

101 

102 Version 1.2 adds the original gains used in the crosstalk fit. 

103 """ 

104 _OBSTYPE = 'CROSSTALK' 

105 _SCHEMA = 'Gen3 Crosstalk' 

106 _VERSION = 1.2 

107 

108 def __init__(self, detector=None, nAmp=0, **kwargs): 

109 self.hasCrosstalk = False 

110 self.nAmp = nAmp if nAmp else 0 

111 self.crosstalkShape = (self.nAmp, self.nAmp) 

112 

113 self.coeffs = np.zeros(self.crosstalkShape) if self.nAmp else None 

114 self.coeffErr = np.zeros(self.crosstalkShape) if self.nAmp else None 

115 self.coeffNum = np.zeros(self.crosstalkShape, 

116 dtype=int) if self.nAmp else None 

117 self.coeffValid = np.ones(self.crosstalkShape, 

118 dtype=bool) if self.nAmp else None 

119 # Quadratic terms, if any. 

120 self.coeffsSqr = np.zeros(self.crosstalkShape) if self.nAmp else None 

121 self.coeffErrSqr = np.zeros(self.crosstalkShape) if self.nAmp else None 

122 

123 # Gain ratios 

124 self.ampGainRatios = np.zeros(self.crosstalkShape) if self.nAmp else None 

125 

126 # Gains used for fit. 

127 self.fitGains = np.zeros(self.nAmp) if self.nAmp else None 

128 

129 # Units 

130 self.crosstalkRatiosUnits = 'adu' if self.nAmp else None 

131 

132 self.interChip = {} 

133 

134 super().__init__(**kwargs) 

135 self.requiredAttributes.update(['hasCrosstalk', 'nAmp', 'coeffs', 

136 'coeffErr', 'coeffNum', 'coeffValid', 

137 'coeffsSqr', 'coeffErrSqr', 

138 'ampGainRatios', 'crosstalkRatiosUnits', 

139 'fitGains', 'interChip']) 

140 if detector: 140 ↛ 141line 140 didn't jump to line 141 because the condition on line 140 was never true

141 self.fromDetector(detector) 

142 

143 def updateMetadata(self, setDate=False, **kwargs): 

144 """Update calibration metadata. 

145 

146 This calls the base class's method after ensuring the required 

147 calibration keywords will be saved. 

148 

149 Parameters 

150 ---------- 

151 setDate : `bool`, optional 

152 Update the CALIBDATE fields in the metadata to the current 

153 time. Defaults to False. 

154 kwargs : 

155 Other keyword parameters to set in the metadata. 

156 """ 

157 kwargs['DETECTOR'] = self._detectorId 

158 kwargs['DETECTOR_NAME'] = self._detectorName 

159 kwargs['DETECTOR_SERIAL'] = self._detectorSerial 

160 kwargs['HAS_CROSSTALK'] = self.hasCrosstalk 

161 kwargs['NAMP'] = self.nAmp 

162 self.crosstalkShape = (self.nAmp, self.nAmp) 

163 kwargs['CROSSTALK_SHAPE'] = self.crosstalkShape 

164 kwargs['CROSSTALK_RATIOS_UNITS'] = self.crosstalkRatiosUnits 

165 

166 super().updateMetadata(setDate=setDate, **kwargs) 

167 

168 def fromDetector(self, detector, coeffVector=None, coeffSqrVector=None): 

169 """Set calibration parameters from the detector. 

170 

171 Parameters 

172 ---------- 

173 detector : `lsst.afw.cameraGeom.Detector` 

174 Detector to use to set parameters from. 

175 coeffVector : `numpy.array`, optional 

176 Use the detector geometry (bounding boxes and flip 

177 information), but use ``coeffVector`` instead of the 

178 output of ``detector.getCrosstalk()``. 

179 coeffSqrVector : `numpy.array`, optional 

180 Quadratic crosstalk coefficients. 

181 

182 Returns 

183 ------- 

184 calib : `lsst.ip.isr.CrosstalkCalib` 

185 The calibration constructed from the detector. 

186 

187 """ 

188 self._detectorId = detector.getId() 

189 self._detectorName = detector.getName() 

190 self._detectorSerial = detector.getSerial() 

191 

192 self.nAmp = len(detector) 

193 self.crosstalkShape = (self.nAmp, self.nAmp) 

194 

195 if coeffVector is not None: 195 ↛ 198line 195 didn't jump to line 198 because the condition on line 195 was always true

196 crosstalkCoeffs = coeffVector 

197 else: 

198 crosstalkCoeffs = detector.getCrosstalk() 

199 if coeffSqrVector is not None: 

200 self.coeffsSqr = coeffSqrVector 

201 else: 

202 self.coeffsSqr = np.zeros(self.crosstalkShape) 

203 if len(crosstalkCoeffs) == 1 and crosstalkCoeffs[0] == 0.0: 

204 return self 

205 self.coeffs = np.array(crosstalkCoeffs).reshape(self.crosstalkShape) 

206 

207 if self.coeffs.shape != self.crosstalkShape: 207 ↛ 208line 207 didn't jump to line 208 because the condition on line 207 was never true

208 raise RuntimeError("Crosstalk coefficients do not match detector shape. " 

209 f"{self.crosstalkShape} {self.nAmp}") 

210 # Set default as in __init__ 

211 self.coeffErr = np.zeros(self.crosstalkShape) 

212 self.coeffNum = np.zeros(self.crosstalkShape, dtype=int) 

213 self.coeffValid = np.ones(self.crosstalkShape, dtype=bool) 

214 self.coeffErrSqr = np.zeros(self.crosstalkShape) 

215 self.ampGainRatios = np.zeros(self.crosstalkShape) 

216 self.fitGains = np.zeros(self.nAmp) 

217 self.crosstalkRatiosUnits = 'adu' 

218 

219 self.interChip = {} 

220 

221 self.hasCrosstalk = True 

222 self.updateMetadata() 

223 

224 return self 

225 

226 @classmethod 

227 def fromDict(cls, dictionary): 

228 """Construct a calibration from a dictionary of properties. 

229 

230 Must be implemented by the specific calibration subclasses. 

231 

232 Parameters 

233 ---------- 

234 dictionary : `dict` 

235 Dictionary of properties. 

236 

237 Returns 

238 ------- 

239 calib : `lsst.ip.isr.CalibType` 

240 Constructed calibration. 

241 

242 Raises 

243 ------ 

244 RuntimeError 

245 Raised if the supplied dictionary is for a different 

246 calibration. 

247 """ 

248 calib = cls() 

249 

250 if calib._OBSTYPE != dictionary['metadata']['OBSTYPE']: 250 ↛ 251line 250 didn't jump to line 251 because the condition on line 250 was never true

251 raise RuntimeError(f"Incorrect crosstalk supplied. Expected {calib._OBSTYPE}, " 

252 f"found {dictionary['metadata']['OBSTYPE']}") 

253 

254 calib.setMetadata(dictionary['metadata']) 

255 

256 if 'detectorName' in dictionary: 256 ↛ 257line 256 didn't jump to line 257 because the condition on line 256 was never true

257 calib._detectorName = dictionary.get('detectorName') 

258 elif 'DETECTOR_NAME' in dictionary: 258 ↛ 259line 258 didn't jump to line 259 because the condition on line 258 was never true

259 calib._detectorName = dictionary.get('DETECTOR_NAME') 

260 elif 'DET_NAME' in dictionary['metadata']: 260 ↛ 263line 260 didn't jump to line 263 because the condition on line 260 was always true

261 calib._detectorName = dictionary['metadata']['DET_NAME'] 

262 else: 

263 calib._detectorName = None 

264 

265 if 'detectorSerial' in dictionary: 265 ↛ 266line 265 didn't jump to line 266 because the condition on line 265 was never true

266 calib._detectorSerial = dictionary.get('detectorSerial') 

267 elif 'DETECTOR_SERIAL' in dictionary: 267 ↛ 268line 267 didn't jump to line 268 because the condition on line 267 was never true

268 calib._detectorSerial = dictionary.get('DETECTOR_SERIAL') 

269 elif 'DET_SER' in dictionary['metadata']: 269 ↛ 272line 269 didn't jump to line 272 because the condition on line 269 was always true

270 calib._detectorSerial = dictionary['metadata']['DET_SER'] 

271 else: 

272 calib._detectorSerial = None 

273 

274 if 'detectorId' in dictionary: 274 ↛ 275line 274 didn't jump to line 275 because the condition on line 274 was never true

275 calib._detectorId = dictionary.get('detectorId') 

276 elif 'DETECTOR' in dictionary: 276 ↛ 277line 276 didn't jump to line 277 because the condition on line 276 was never true

277 calib._detectorId = dictionary.get('DETECTOR') 

278 elif 'DETECTOR' in dictionary['metadata']: 278 ↛ 280line 278 didn't jump to line 280 because the condition on line 278 was always true

279 calib._detectorId = dictionary['metadata']['DETECTOR'] 

280 elif calib._detectorSerial: 

281 calib._detectorId = calib._detectorSerial 

282 else: 

283 calib._detectorId = None 

284 

285 if 'instrument' in dictionary: 285 ↛ 286line 285 didn't jump to line 286 because the condition on line 285 was never true

286 calib._instrument = dictionary.get('instrument') 

287 elif 'INSTRUME' in dictionary['metadata']: 287 ↛ 290line 287 didn't jump to line 290 because the condition on line 287 was always true

288 calib._instrument = dictionary['metadata']['INSTRUME'] 

289 else: 

290 calib._instrument = None 

291 

292 calib.hasCrosstalk = dictionary.get('hasCrosstalk', 

293 dictionary['metadata'].get('HAS_CROSSTALK', False)) 

294 if calib.hasCrosstalk: 294 ↛ 343line 294 didn't jump to line 343 because the condition on line 294 was always true

295 calib.nAmp = dictionary.get('nAmp', dictionary['metadata'].get('NAMP', 0)) 

296 calib.crosstalkShape = (calib.nAmp, calib.nAmp) 

297 calib.coeffs = np.array(dictionary['coeffs']).reshape(calib.crosstalkShape) 

298 calib.crosstalkRatiosUnits = dictionary.get( 

299 'crosstalkRatiosUnits', 

300 dictionary['metadata'].get('CROSSTALK_RATIOS_UNITS', 'adu')) 

301 if 'coeffErr' in dictionary: 301 ↛ 304line 301 didn't jump to line 304 because the condition on line 301 was always true

302 calib.coeffErr = np.array(dictionary['coeffErr']).reshape(calib.crosstalkShape) 

303 else: 

304 calib.coeffErr = np.zeros_like(calib.coeffs) 

305 if 'coeffNum' in dictionary: 305 ↛ 308line 305 didn't jump to line 308 because the condition on line 305 was always true

306 calib.coeffNum = np.array(dictionary['coeffNum']).reshape(calib.crosstalkShape) 

307 else: 

308 calib.coeffNum = np.zeros_like(calib.coeffs, dtype=int) 

309 if 'coeffValid' in dictionary: 309 ↛ 312line 309 didn't jump to line 312 because the condition on line 309 was always true

310 calib.coeffValid = np.array(dictionary['coeffValid']).reshape(calib.crosstalkShape) 

311 else: 

312 calib.coeffValid = np.ones_like(calib.coeffs, dtype=bool) 

313 if 'coeffsSqr' in dictionary: 313 ↛ 316line 313 didn't jump to line 316 because the condition on line 313 was always true

314 calib.coeffsSqr = np.array(dictionary['coeffsSqr']).reshape(calib.crosstalkShape) 

315 else: 

316 calib.coeffsSqr = np.zeros_like(calib.coeffs) 

317 if 'coeffErrSqr' in dictionary: 317 ↛ 320line 317 didn't jump to line 320 because the condition on line 317 was always true

318 calib.coeffErrSqr = np.array(dictionary['coeffErrSqr']).reshape(calib.crosstalkShape) 

319 else: 

320 calib.coeffErrSqr = np.zeros_like(calib.coeffs) 

321 if 'ampGainRatios' in dictionary: 321 ↛ 324line 321 didn't jump to line 324 because the condition on line 321 was always true

322 calib.ampGainRatios = np.array(dictionary['ampGainRatios']).reshape(calib.crosstalkShape) 

323 else: 

324 calib.ampGainRatios = np.zeros_like(calib.coeffs) 

325 if 'fitGains' in dictionary: 325 ↛ 335line 325 didn't jump to line 335 because the condition on line 325 was always true

326 # Compatibility for matrices that were stored with fitGains 

327 # of length 1. 

328 fitGains = np.array(dictionary['fitGains']) 

329 if len(fitGains) == 1: 

330 # Expand to the correct number of amps, all zero (unknown). 

331 calib.fitGains = np.zeros(calib.nAmp) 

332 else: 

333 calib.fitGains = np.array(dictionary['fitGains']).reshape(calib.nAmp) 

334 else: 

335 calib.fitGains = np.zeros(calib.nAmp) 

336 

337 calib.interChip = dictionary.get('interChip', None) 

338 if calib.interChip: 338 ↛ 343line 338 didn't jump to line 343 because the condition on line 338 was always true

339 for detector in calib.interChip: 

340 coeffVector = calib.interChip[detector] 

341 calib.interChip[detector] = np.array(coeffVector).reshape(calib.crosstalkShape) 

342 

343 calib.updateMetadata() 

344 return calib 

345 

346 def toDict(self): 

347 """Return a dictionary containing the calibration properties. 

348 

349 The dictionary should be able to be round-tripped through 

350 `fromDict`. 

351 

352 Returns 

353 ------- 

354 dictionary : `dict` 

355 Dictionary of properties. 

356 """ 

357 self.updateMetadata() 

358 

359 outDict = {} 

360 metadata = self.getMetadata() 

361 outDict['metadata'] = metadata 

362 

363 outDict['hasCrosstalk'] = self.hasCrosstalk 

364 outDict['nAmp'] = self.nAmp 

365 outDict['crosstalkShape'] = self.crosstalkShape 

366 outDict['crosstalkRatiosUnits'] = self.crosstalkRatiosUnits 

367 

368 ctLength = self.nAmp*self.nAmp 

369 outDict['coeffs'] = self.coeffs.reshape(ctLength).tolist() 

370 

371 if self.coeffErr is not None: 371 ↛ 373line 371 didn't jump to line 373 because the condition on line 371 was always true

372 outDict['coeffErr'] = self.coeffErr.reshape(ctLength).tolist() 

373 if self.coeffNum is not None: 373 ↛ 375line 373 didn't jump to line 375 because the condition on line 373 was always true

374 outDict['coeffNum'] = self.coeffNum.reshape(ctLength).tolist() 

375 if self.coeffValid is not None: 375 ↛ 377line 375 didn't jump to line 377 because the condition on line 375 was always true

376 outDict['coeffValid'] = self.coeffValid.reshape(ctLength).tolist() 

377 if self.coeffsSqr is not None: 377 ↛ 379line 377 didn't jump to line 379 because the condition on line 377 was always true

378 outDict['coeffsSqr'] = self.coeffsSqr.reshape(ctLength).tolist() 

379 if self.coeffErrSqr is not None: 379 ↛ 381line 379 didn't jump to line 381 because the condition on line 379 was always true

380 outDict['coeffErrSqr'] = self.coeffErrSqr.reshape(ctLength).tolist() 

381 if self.ampGainRatios is not None: 381 ↛ 383line 381 didn't jump to line 383 because the condition on line 381 was always true

382 outDict['ampGainRatios'] = self.ampGainRatios.reshape(ctLength).tolist() 

383 if self.fitGains is not None: 383 ↛ 386line 383 didn't jump to line 386 because the condition on line 383 was always true

384 outDict['fitGains'] = self.fitGains.tolist() 

385 

386 if self.interChip: 

387 outDict['interChip'] = dict() 

388 for detector in self.interChip: 

389 outDict['interChip'][detector] = self.interChip[detector].reshape(ctLength).tolist() 

390 

391 return outDict 

392 

393 @classmethod 

394 def fromTable(cls, tableList): 

395 """Construct calibration from a list of tables. 

396 

397 This method uses the `fromDict` method to create the 

398 calibration, after constructing an appropriate dictionary from 

399 the input tables. 

400 

401 Parameters 

402 ---------- 

403 tableList : `list` [`lsst.afw.table.Table`] 

404 List of tables to use to construct the crosstalk 

405 calibration. 

406 

407 Returns 

408 ------- 

409 calib : `lsst.ip.isr.CrosstalkCalib` 

410 The calibration defined in the tables. 

411 

412 """ 

413 coeffTable = tableList[0] 

414 

415 metadata = coeffTable.meta 

416 inDict = dict() 

417 inDict['metadata'] = metadata 

418 inDict['hasCrosstalk'] = metadata['HAS_CROSSTALK'] 

419 inDict['nAmp'] = metadata['NAMP'] 

420 calibVersion = metadata['CROSSTALK_VERSION'] 

421 if calibVersion < 1.1: 421 ↛ 422line 421 didn't jump to line 422 because the condition on line 421 was never true

422 inDict['crosstalkRatiosUnits'] = 'adu' 

423 else: 

424 inDict['crosstalkRatiosUnits'] = metadata['CROSSTALK_RATIOS_UNITS'] 

425 inDict['coeffs'] = coeffTable['CT_COEFFS'] 

426 if 'CT_ERRORS' in coeffTable.columns: 426 ↛ 428line 426 didn't jump to line 428 because the condition on line 426 was always true

427 inDict['coeffErr'] = coeffTable['CT_ERRORS'] 

428 if 'CT_COUNTS' in coeffTable.columns: 428 ↛ 430line 428 didn't jump to line 430 because the condition on line 428 was always true

429 inDict['coeffNum'] = coeffTable['CT_COUNTS'] 

430 if 'CT_VALID' in coeffTable.columns: 430 ↛ 432line 430 didn't jump to line 432 because the condition on line 430 was always true

431 inDict['coeffValid'] = coeffTable['CT_VALID'] 

432 if 'CT_COEFFS_SQR' in coeffTable.columns: 432 ↛ 434line 432 didn't jump to line 434 because the condition on line 432 was always true

433 inDict['coeffsSqr'] = coeffTable['CT_COEFFS_SQR'] 

434 if 'CT_ERRORS_SQR' in coeffTable.columns: 434 ↛ 436line 434 didn't jump to line 436 because the condition on line 434 was always true

435 inDict['coeffErrSqr'] = coeffTable['CT_ERRORS_SQR'] 

436 if 'CT_AMP_GAIN_RATIOS' in coeffTable.columns: 436 ↛ 438line 436 didn't jump to line 438 because the condition on line 436 was always true

437 inDict['ampGainRatios'] = coeffTable['CT_AMP_GAIN_RATIOS'] 

438 if 'CT_FIT_GAINS' in coeffTable.columns: 438 ↛ 441line 438 didn't jump to line 441 because the condition on line 438 was always true

439 inDict['fitGains'] = coeffTable['CT_FIT_GAINS'] 

440 

441 if len(tableList) > 1: 441 ↛ 447line 441 didn't jump to line 447 because the condition on line 441 was always true

442 inDict['interChip'] = dict() 

443 interChipTable = tableList[1] 

444 for record in interChipTable: 

445 inDict['interChip'][record['IC_SOURCE_DET']] = record['IC_COEFFS'] 

446 

447 return cls().fromDict(inDict) 

448 

449 def toTable(self): 

450 """Construct a list of tables containing the information in this 

451 calibration. 

452 

453 The list of tables should create an identical calibration 

454 after being passed to this class's fromTable method. 

455 

456 Returns 

457 ------- 

458 tableList : `list` [`lsst.afw.table.Table`] 

459 List of tables containing the crosstalk calibration 

460 information. 

461 

462 """ 

463 tableList = [] 

464 self.updateMetadata() 

465 catalog = Table([{'CT_COEFFS': self.coeffs.reshape(self.nAmp*self.nAmp), 

466 'CT_ERRORS': self.coeffErr.reshape(self.nAmp*self.nAmp), 

467 'CT_COUNTS': self.coeffNum.reshape(self.nAmp*self.nAmp), 

468 'CT_VALID': self.coeffValid.reshape(self.nAmp*self.nAmp), 

469 'CT_COEFFS_SQR': self.coeffsSqr.reshape(self.nAmp*self.nAmp), 

470 'CT_ERRORS_SQR': self.coeffErrSqr.reshape(self.nAmp*self.nAmp), 

471 'CT_AMP_GAIN_RATIOS': self.ampGainRatios.reshape(self.nAmp*self.nAmp), 

472 'CT_FIT_GAINS': self.fitGains, 

473 }]) 

474 # filter None, because astropy can't deal. 

475 inMeta = self.getMetadata().toDict() 

476 outMeta = {k: v for k, v in inMeta.items() if v is not None} 

477 outMeta.update({k: "" for k, v in inMeta.items() if v is None}) 

478 catalog.meta = outMeta 

479 tableList.append(catalog) 

480 

481 if self.interChip: 481 ↛ 486line 481 didn't jump to line 486 because the condition on line 481 was always true

482 interChipTable = Table([{'IC_SOURCE_DET': sourceDet, 

483 'IC_COEFFS': self.interChip[sourceDet].reshape(self.nAmp*self.nAmp)} 

484 for sourceDet in self.interChip.keys()]) 

485 tableList.append(interChipTable) 

486 return tableList 

487 

488 # Implementation methods. 

489 @staticmethod 

490 def extractAmp(image, ampToFlip, ampTarget, isTrimmed=False, fullAmplifier=False, parallelOverscan=None): 

491 """Extract the image data from an amp, flipped to match ampTarget. 

492 

493 Parameters 

494 ---------- 

495 image : `lsst.afw.image.Image` or `lsst.afw.image.MaskedImage` 

496 Image containing the amplifier of interest. 

497 amp : `lsst.afw.cameraGeom.Amplifier` 

498 Amplifier on image to extract. 

499 ampTarget : `lsst.afw.cameraGeom.Amplifier` 

500 Target amplifier that the extracted image will be flipped 

501 to match. 

502 isTrimmed : `bool`, optional 

503 The image is already trimmed. 

504 fullAmplifier : `bool`, optional 

505 Use full amplifier and not just imaging region. 

506 parallelOverscan : `bool`, optional 

507 This has been deprecated and is unused, and will be removed 

508 after v29. 

509 

510 Returns 

511 ------- 

512 output : `lsst.afw.image.Image` 

513 Amplifier from image, flipped to desired configuration. 

514 This will always return a copy of the original data. 

515 """ 

516 if parallelOverscan is not None: 516 ↛ 517line 516 didn't jump to line 517 because the condition on line 516 was never true

517 warnings.warn( 

518 "The parallelOverscan option has been deprecated and will be removed after v29.", 

519 FutureWarning, 

520 ) 

521 

522 X_FLIP = {lsst.afw.cameraGeom.ReadoutCorner.LL: False, 

523 lsst.afw.cameraGeom.ReadoutCorner.LR: True, 

524 lsst.afw.cameraGeom.ReadoutCorner.UL: False, 

525 lsst.afw.cameraGeom.ReadoutCorner.UR: True} 

526 Y_FLIP = {lsst.afw.cameraGeom.ReadoutCorner.LL: False, 

527 lsst.afw.cameraGeom.ReadoutCorner.LR: False, 

528 lsst.afw.cameraGeom.ReadoutCorner.UL: True, 

529 lsst.afw.cameraGeom.ReadoutCorner.UR: True} 

530 

531 bbox = CrosstalkCalib._getAppropriateBBox(ampToFlip, isTrimmed, fullAmplifier) 

532 output = image[bbox] 

533 

534 sourceAmpCorner = ampToFlip.getReadoutCorner() 

535 targetAmpCorner = ampTarget.getReadoutCorner() 

536 

537 # Flipping is necessary only if the desired configuration doesn't match 

538 # what we currently have. 

539 xFlip = X_FLIP[targetAmpCorner] ^ X_FLIP[sourceAmpCorner] 

540 yFlip = Y_FLIP[targetAmpCorner] ^ Y_FLIP[sourceAmpCorner] 

541 # This always makes a copy of the image. 

542 return lsst.afw.math.flipImage(output, xFlip, yFlip) 

543 

544 @staticmethod 

545 def _getAppropriateBBox(amp, isTrimmed, fullAmplifier): 

546 """Get the appropriate bounding box from an amplifier. 

547 

548 Parameters 

549 ---------- 

550 amp : `lsst.afw.cameraGeom.Amplifier` 

551 Amplifier to get bounding box. 

552 isTrimmed : `bool` 

553 Is this a trimmed image? 

554 fullAmplifier : `bool` 

555 Extract full amplifier for an untrimmed image? 

556 """ 

557 if isTrimmed: 

558 return amp.getBBox() 

559 elif fullAmplifier and not isTrimmed: 

560 return amp.getRawBBox() 

561 else: 

562 return amp.getRawDataBBox() 

563 

564 @staticmethod 

565 def calculateBackground(mi, badPixels=["BAD"]): 

566 """Estimate median background in image. 

567 

568 Getting a great background model isn't important for crosstalk 

569 correction, since the crosstalk is at a low level. The median should 

570 be sufficient. 

571 

572 Parameters 

573 ---------- 

574 mi : `lsst.afw.image.MaskedImage` 

575 MaskedImage for which to measure background. 

576 badPixels : `list` of `str` 

577 Mask planes to ignore. 

578 Returns 

579 ------- 

580 bg : `float` 

581 Median background level. 

582 """ 

583 mask = mi.getMask() 

584 stats = lsst.afw.math.StatisticsControl() 

585 stats.setAndMask(mask.getPlaneBitMask(badPixels)) 

586 return lsst.afw.math.makeStatistics(mi, lsst.afw.math.MEDIAN, stats).getValue() 

587 

588 def subtractCrosstalk(self, thisExposure, sourceExposure=None, crosstalkCoeffs=None, 

589 crosstalkCoeffsSqr=None, crosstalkCoeffsValid=None, 

590 badPixels=["BAD"], minPixelToMask=45000, doSubtrahendMasking=False, 

591 doCrosstalkMask=True, crosstalkStr="CROSSTALK", isTrimmed=None, 

592 backgroundMethod="None", doSqrCrosstalk=False, fullAmplifier=False, 

593 parallelOverscan=None, detectorConfig=None, badAmpDict=None, 

594 ignoreVariance=False, doUseFastPath=True): 

595 """Subtract the crosstalk from thisExposure, optionally using a 

596 different source. 

597 

598 We set the mask plane indicated by ``crosstalkStr`` in a 

599 target amplifier for pixels in a source amplifier that exceed 

600 ``minPixelToMask``, if ``doSubtrahendMasking`` is False. With 

601 that enabled, the mask is only set if the absolute value of 

602 the correction applied exceeds ``minPixelToMask``. Note that 

603 the correction is applied to all pixels in the amplifier, but 

604 only those that have a substantial crosstalk are masked with 

605 ``crosstalkStr``. 

606 

607 The uncorrected image is used as a template for correction. This is 

608 good enough if the crosstalk is small (e.g., coefficients < ~ 1e-3), 

609 but if it's larger you may want to iterate. 

610 

611 Parameters 

612 ---------- 

613 thisExposure : `lsst.afw.image.Exposure` 

614 Exposure for which to subtract crosstalk. 

615 sourceExposure : `lsst.afw.image.Exposure`, optional 

616 Exposure to use as the source of the crosstalk. If not set, 

617 thisExposure is used as the source (intra-detector crosstalk). 

618 crosstalkCoeffs : `numpy.ndarray`, optional. 

619 Coefficients to use to correct crosstalk. 

620 crosstalkCoeffsSqr : `numpy.ndarray`, optional. 

621 Quadratic coefficients to use to correct crosstalk. 

622 crosstalkCoeffsValid : `numpy.ndarray`, optional 

623 Boolean array that is True where coefficients are valid. 

624 badPixels : `list` of `str`, optional 

625 Mask planes to ignore. 

626 minPixelToMask : `float`, optional 

627 Minimum pixel value to set the ``crosstalkStr`` mask 

628 plane. If doSubtrahendMasking is True, this is calculated 

629 from the absolute magnitude of the subtrahend image. 

630 Otherwise, this sets the minimum source value to use to 

631 set that mask. 

632 doCrosstalkMask : `bool`, optional 

633 If true, the crosstalk mask will be computed. Otherwise, 

634 no crosstalk mask will be computed which is slightly faster. 

635 doSubtrahendMasking : `bool`, optional 

636 If true, the mask is calculated from the properties of the 

637 subtrahend image, not from the brightness of the source 

638 pixel. Not used if doCrosstalkMask is False. 

639 crosstalkStr : `str`, optional 

640 Mask plane name for pixels greatly modified by crosstalk 

641 (above minPixelToMask). 

642 isTrimmed : `bool`, optional 

643 This option has been deprecated and does not do anything. 

644 It will be removed after v29. 

645 backgroundMethod : `str`, optional 

646 Method used to subtract the background. "AMP" uses 

647 amplifier-by-amplifier background levels, "DETECTOR" uses full 

648 exposure/maskedImage levels. Any other value results in no 

649 background subtraction. 

650 doSqrCrosstalk: `bool`, optional 

651 Should the quadratic crosstalk coefficients be used for the 

652 crosstalk correction? 

653 fullAmplifier : `bool`, optional 

654 Use full amplifier and not just imaging region. 

655 parallelOverscan : `bool`, optional 

656 This option is deprecated and will be removed after v29. 

657 detectorConfig : `lsst.ip.isr.overscanDetectorConfig`, optional 

658 Per-amplifier configs to use if parallelOverscan is True. 

659 This option is deprecated and will be removed after v29. 

660 badAmpDict : `dict` [`str`, `bool`], optional 

661 Dictionary to identify bad amplifiers that should not be 

662 source or target for crosstalk correction. 

663 ignoreVariance : `bool`, optional 

664 Ignore the variance plane when doing crosstalk correction? 

665 doUseFastPath : `bool`, optional 

666 Use the fast-path crosstalk processing if ignoring variance 

667 and no background subtraction? 

668 

669 Notes 

670 ----- 

671 

672 For a given image I, we want to find the crosstalk subtrahend 

673 image CT, such that 

674 I_corrected = I - CT 

675 The subtrahend image is the sum of all crosstalk contributions 

676 that appear in I, so we can build it up by amplifier. Each 

677 amplifier A in image I sees the contributions from all other 

678 amplifiers B_v != A. For the current linear model, we set `sImage` 

679 equal to the segment of the subtrahend image CT corresponding to 

680 amplifier A, and then build it up as: 

681 simage_linear = sum_v coeffsA_v * (B_v - bkg_v) where coeffsA_v 

682 is the vector of crosstalk coefficients for sources that cause 

683 images in amplifier A. The bkg_v term in this equation is 

684 identically 0.0 for all cameras except obs_subaru (and is only 

685 non-zero there for historical reasons). 

686 To include the non-linear term, we can again add to the subtrahend 

687 image using the same loop, as: 

688 

689 simage_nonlinear = sum_v (coeffsA_v * B_v) + (NLcoeffsA_v * B_v * B_v) 

690 = sum_v linear_term_v + nonlinear_term_v 

691 

692 where coeffsA_v is the linear term, and NLcoeffsA_v are the quadratic 

693 component. For LSSTCam, it has been observed that the linear_term_v >> 

694 nonlinear_term_v. 

695 """ 

696 targetMaskedImage = thisExposure.maskedImage 

697 targetDetector = thisExposure.getDetector() 

698 if self.hasCrosstalk is False: 

699 self.fromDetector(targetDetector, coeffVector=crosstalkCoeffs) 

700 

701 # TODO: Remove on DM-48394 

702 if isTrimmed is not None: 702 ↛ 703line 702 didn't jump to line 703 because the condition on line 702 was never true

703 warnings.warn( 

704 "The isTrimmed option has been deprecated and will be removed after v29.", 

705 FutureWarning, 

706 ) 

707 isTrimmed = isTrimmedImage(targetMaskedImage, targetDetector) 

708 

709 # TODO: Remove on DM-48394 

710 if parallelOverscan is not None: 710 ↛ 711line 710 didn't jump to line 711 because the condition on line 710 was never true

711 warnings.warn( 

712 "The parallelOverscan option has been deprecated and will be removed after v29.", 

713 FutureWarning, 

714 ) 

715 if detectorConfig is not None: 715 ↛ 716line 715 didn't jump to line 716 because the condition on line 715 was never true

716 warnings.warn( 

717 "The detectorConfig option has been deprecated and will be removed after v29.", 

718 FutureWarning, 

719 ) 

720 

721 numAmps = len(targetDetector) 

722 if numAmps != self.nAmp: 722 ↛ 723line 722 didn't jump to line 723 because the condition on line 722 was never true

723 raise RuntimeError(f"Crosstalk built for {self.nAmp} in {self._detectorName}, received " 

724 f"{numAmps} in {targetDetector.getName()}") 

725 

726 if doSqrCrosstalk and crosstalkCoeffsSqr is None: 726 ↛ 727line 726 didn't jump to line 727 because the condition on line 726 was never true

727 raise RuntimeError("Attempted to perform NL crosstalk correction without NL " 

728 "crosstalk coefficients.") 

729 

730 if fullAmplifier and (backgroundMethod != "None"): 730 ↛ 731line 730 didn't jump to line 731 because the condition on line 730 was never true

731 raise RuntimeError("Cannot do full amplifier with background subtraction.") 

732 

733 if sourceExposure: 

734 sourceMaskedImage = sourceExposure.maskedImage 

735 sourceDetector = sourceExposure.getDetector() 

736 else: 

737 sourceMaskedImage = targetMaskedImage 

738 sourceDetector = targetDetector 

739 

740 if crosstalkCoeffs is not None: 740 ↛ 743line 740 didn't jump to line 743 because the condition on line 740 was always true

741 coeffs = np.asarray(crosstalkCoeffs).copy() 

742 else: 

743 coeffs = np.asarray(self.coeffs).copy() 

744 self.log.debug("CT COEFF: %s", coeffs) 

745 

746 if doSqrCrosstalk: 

747 coeffsSqr = np.asarray(crosstalkCoeffsSqr).copy() 

748 self.log.debug("CT COEFF SQR: %s", coeffsSqr) 

749 else: 

750 coeffsSqr = np.zeros_like(coeffs) 

751 

752 # Check for valid values; set to 0 otherwise. 

753 badCoeffs = ~np.isfinite(coeffs) | (coeffs == 0.0) 

754 coeffs[badCoeffs] = 0.0 

755 coeffsSqr[badCoeffs] = 0.0 

756 if crosstalkCoeffsValid is not None: 

757 coeffs[~crosstalkCoeffsValid] = 0.0 

758 coeffsSqr[~crosstalkCoeffsValid] = 0.0 

759 

760 if badAmpDict: 

761 for index, amp in enumerate(sourceDetector): 

762 if badAmpDict[amp.getName()]: 

763 coeffs[index, :] = 0.0 

764 coeffs[:, index] = 0.0 

765 

766 # Compute backgrounds if requested. 

767 backgrounds = {amp.getName(): 0.0 for amp in sourceDetector} 

768 useBackgrounds = False 

769 if backgroundMethod == "AMP": 769 ↛ 770line 769 didn't jump to line 770 because the condition on line 769 was never true

770 useBackgrounds = True 

771 backgrounds = { 

772 amp.getName(): self.calculateBackground( 

773 sourceMaskedImage[self._getAppropriateBBox( 

774 amp, 

775 isTrimmed, 

776 False, 

777 )], badPixels) 

778 for amp in sourceDetector 

779 } 

780 elif backgroundMethod == "DETECTOR": 780 ↛ 781line 780 didn't jump to line 781 because the condition on line 780 was never true

781 useBackgrounds = True 

782 background = self.calculateBackground(sourceMaskedImage, badPixels) 

783 backgrounds = {amp.getName(): background for amp in sourceDetector} 

784 

785 # Add the crosstalk mask plane to the target mask. 

786 sourceCrosstalkPlane = sourceMaskedImage.mask.addMaskPlane(crosstalkStr) 

787 if sourceExposure is not None: 

788 targetCrosstalkPlane = targetMaskedImage.mask.addMaskPlane(crosstalkStr) 

789 else: 

790 targetCrosstalkPlane = sourceCrosstalkPlane 

791 

792 # If we are not doing subtrahend masking, the CROSSTALK mask bit 

793 # is set according to the counts in the source pixel (above 

794 # background), regardless of the crosstalk coefficient value. 

795 if doCrosstalkMask and not doSubtrahendMasking: 

796 # When we are not using subtrahend masking, we set the mask. 

797 thresholdBackground = self.calculateBackground(sourceMaskedImage, badPixels) 

798 toMask = (sourceMaskedImage.image.array >= (minPixelToMask + thresholdBackground)) 

799 sourceMaskedImage.mask.array[toMask] |= sourceMaskedImage.mask.getPlaneBitMask(crosstalkStr) 

800 

801 crosstalk = sourceMaskedImage.mask.getPlaneBitMask(crosstalkStr) 

802 

803 # Define a subtrahend image to contain all the scaled crosstalk 

804 # signals. These will be applied to the target image. 

805 subtrahend = targetMaskedImage.Factory(targetMaskedImage.getBBox()) 

806 subtrahend.set((0, 0, 0)) 

807 

808 # If we are ignoring variance and doing subtrahend masking, then 

809 # we can work on only the image plane (3x speed increase). 

810 imageOnly = ignoreVariance and (doSubtrahendMasking or not doCrosstalkMask) 

811 

812 if imageOnly and not useBackgrounds and doUseFastPath: 

813 # Special fast path 

814 def _flip(a, amp): 

815 X_FLIP = {lsst.afw.cameraGeom.ReadoutCorner.LL: False, 

816 lsst.afw.cameraGeom.ReadoutCorner.LR: True, 

817 lsst.afw.cameraGeom.ReadoutCorner.UL: False, 

818 lsst.afw.cameraGeom.ReadoutCorner.UR: True} 

819 Y_FLIP = {lsst.afw.cameraGeom.ReadoutCorner.LL: False, 

820 lsst.afw.cameraGeom.ReadoutCorner.LR: False, 

821 lsst.afw.cameraGeom.ReadoutCorner.UL: True, 

822 lsst.afw.cameraGeom.ReadoutCorner.UR: True} 

823 

824 c = amp.getReadoutCorner() 

825 return a[::-1 if Y_FLIP[c] else 1, ::-1 if X_FLIP[c] else 1] 

826 

827 # Use the first amp to get the amp size. 

828 bbox = self._getAppropriateBBox(sourceDetector[0], isTrimmed, fullAmplifier) 

829 ny, nx = bbox.getHeight(), bbox.getWidth() 

830 srcArr = sourceMaskedImage.image.array 

831 

832 active = np.flatnonzero(np.any(coeffs != 0.0, axis=1)) 

833 nA = len(active) 

834 

835 A = np.empty((2*nA, ny*nx), dtype=np.float32) 

836 for i, s in enumerate(active): 

837 amp = sourceDetector[s] 

838 bbox = self._getAppropriateBBox(amp, isTrimmed, fullAmplifier) 

839 A[i].reshape(ny, nx)[:] = _flip(srcArr[bbox.slices], amp) 

840 

841 cLin = coeffs[active].T.astype(np.float32) 

842 if np.any(coeffsSqr[active]): 

843 np.multiply(A[:nA], A[:nA], out=A[nA:]) 

844 M = np.concatenate([cLin, coeffsSqr[active].T.astype(np.float32)], axis=1) 

845 with threadpool_limits(limits=1, user_api="blas"): 

846 C = M @ A 

847 else: 

848 with threadpool_limits(limits=1, user_api="blas"): 

849 C = cLin @ A[:nA] 

850 

851 subArr = subtrahend.image.array 

852 for t, amp in enumerate(targetDetector): 

853 bbox = self._getAppropriateBBox(amp, isTrimmed, fullAmplifier) 

854 subArr[bbox.slices] = _flip(C[t].reshape(ny, nx), amp) 

855 

856 else: 

857 for sourceIndex, sourceAmp in enumerate(sourceDetector): 

858 for targetIndex, targetAmp in enumerate(targetDetector): 

859 coeff = coeffs[sourceIndex, targetIndex] 

860 coeffSqr = coeffsSqr[sourceIndex, targetIndex] 

861 

862 if coeff == 0.0: 

863 continue 

864 

865 targetBBox = self._getAppropriateBBox(targetAmp, isTrimmed, fullAmplifier) 

866 

867 # The extractAmp() method will always make a copy of the 

868 # source amplifier data. 

869 if imageOnly: 

870 sourceImage = self.extractAmp( 

871 sourceMaskedImage.image, 

872 sourceAmp, 

873 targetAmp, 

874 isTrimmed=isTrimmed, 

875 fullAmplifier=fullAmplifier, 

876 ) 

877 

878 targetImage = subtrahend[targetBBox].image 

879 else: 

880 sourceImage = self.extractAmp( 

881 sourceMaskedImage, 

882 sourceAmp, 

883 targetAmp, 

884 isTrimmed=isTrimmed, 

885 fullAmplifier=fullAmplifier, 

886 ) 

887 targetImage = subtrahend[targetBBox] 

888 

889 # Remove all other masks from copied sourceImage. 

890 sourceImage.mask.array[:] &= crosstalk 

891 

892 if backgrounds[sourceAmp.getName()] != 0.0: 892 ↛ 893line 892 didn't jump to line 893 because the condition on line 892 was never true

893 sourceImage -= backgrounds[sourceAmp.getName()] 

894 

895 # This operation will also transfer the CROSSTALK mask bit 

896 # from above to the target (subtrahend) image if we are 

897 # using a masked image. 

898 targetImage.scaledPlus(coeff, sourceImage) 

899 if coeffSqr != 0.0: 

900 sourceImage.scaledMultiplies(1.0, sourceImage) 

901 targetImage.scaledPlus(coeffSqr, sourceImage) 

902 

903 # Clear the mask in the target image, because the subtrahend image 

904 # contains the crosstalk mask. 

905 sourceMaskedImage.mask.clearMaskPlane(sourceCrosstalkPlane) 

906 if sourceExposure is not None: 

907 targetMaskedImage.mask.clearMaskPlane(targetCrosstalkPlane) 

908 

909 if doCrosstalkMask and doSubtrahendMasking: 

910 # Set crosstalkStr bit only for those pixels that have 

911 # been significantly modified (i.e., those masked as such 

912 # in 'subtrahend'), not necessarily those that are bright 

913 # originally. 

914 

915 # The existing mask in the subtrahend comes from the 

916 # threshold set above. It should be cleared so we can 

917 # recalculate it. 

918 subtrahend.mask.clearMaskPlane(targetCrosstalkPlane) 

919 

920 # For masking purposes, we only really care when the 

921 # correction is significantly different than the median 

922 # value on that amplifier (which includes the contribution 

923 # of every other amplifier background that crosstalks onto 

924 # that amplifier). Subtract and save this "background" 

925 # level, so we can threshold to set the mask relative to 

926 # that background, but still include that contribution in 

927 # the correction we're applying. 

928 subtrahendBackgrounds = {} 

929 for amp in targetDetector: 

930 # Note that we never want the full amplifier for background 

931 # calculations. 

932 bbox = self._getAppropriateBBox(amp, isTrimmed, False) 

933 ampData = subtrahend[bbox] 

934 background = np.median(ampData.image.array[::4, ::4]) 

935 subtrahendBackgrounds[amp.getName()] = background 

936 ampData.image.array[:, :] -= background 

937 self.log.debug(f"Subtrahend background level: {amp.getName()} {background}") 

938 

939 toMask = (subtrahend.image.array >= minPixelToMask) | (subtrahend.image.array <= -minPixelToMask) 

940 subtrahend.mask.array[toMask] |= subtrahend.mask.getPlaneBitMask(crosstalkStr) 

941 

942 # Put the backgrounds back. 

943 for amp in targetDetector: 

944 bbox = self._getAppropriateBBox(amp, isTrimmed, False) 

945 ampData = subtrahend[bbox] 

946 background = subtrahendBackgrounds[amp.getName()] 

947 ampData.image.array[:, :] += background 

948 

949 # Subtract subtrahend from input. The mask plane is fully 

950 # populated, so this operation also sets the ``crosstalkStr`` 

951 # bit where applicable. 

952 

953 targetMaskedImage -= subtrahend 

954 

955 

956class CrosstalkConfig(Config): 

957 """Configuration for intra-detector crosstalk removal.""" 

958 minPixelToMask = Field( 

959 dtype=float, 

960 doc="Set crosstalk mask plane for pixels over this value.", 

961 default=45000 

962 ) 

963 crosstalkMaskPlane = Field( 

964 dtype=str, 

965 doc="Name for crosstalk mask plane.", 

966 default="CROSSTALK" 

967 ) 

968 doCrosstalkMask = Field( 

969 dtype=bool, 

970 doc="Compute the crosstalk mask?", 

971 default=True, 

972 ) 

973 doSubtrahendMasking = Field( 

974 dtype=bool, 

975 doc="Use subtrahend image thresholding instead of input image thesholding to set crosstalk mask? " 

976 "Not used if doCrosstalkMask is False.", 

977 default=False, 

978 ) 

979 crosstalkBackgroundMethod = ChoiceField( 

980 dtype=str, 

981 doc="Type of background subtraction to use when applying correction.", 

982 default="None", 

983 allowed={ 

984 "None": "Do no background subtraction.", 

985 "AMP": "Subtract amplifier-by-amplifier background levels.", 

986 "DETECTOR": "Subtract detector level background." 

987 }, 

988 ) 

989 useConfigCoefficients = Field( 

990 dtype=bool, 

991 doc="Ignore the detector crosstalk information in favor of CrosstalkConfig values?", 

992 default=False, 

993 ) 

994 crosstalkValues = ListField( 

995 dtype=float, 

996 doc=("Amplifier-indexed crosstalk coefficients to use. This should be arranged as a 1 x nAmp**2 " 

997 "list of coefficients, such that when reshaped by crosstalkShape, the result is nAmp x nAmp. " 

998 "This matrix should be structured so CT * [amp0 amp1 amp2 ...]^T returns the column " 

999 "vector [corr0 corr1 corr2 ...]^T."), 

1000 default=[0.0], 

1001 ) 

1002 crosstalkShape = ListField( 

1003 dtype=int, 

1004 doc="Shape of the coefficient array. This should be equal to [nAmp, nAmp].", 

1005 default=[1], 

1006 ) 

1007 doQuadraticCrosstalkCorrection = Field( 

1008 dtype=bool, 

1009 doc="Use quadratic crosstalk coefficients in the crosstalk correction", 

1010 default=False, 

1011 ) 

1012 doUseFastPath = Field( 

1013 dtype=bool, 

1014 doc="Use fast-path crosstalk correction when available (image only; no backgrounds)?", 

1015 default=True, 

1016 ) 

1017 

1018 def getCrosstalk(self, detector=None): 

1019 """Return a 2-D numpy array of crosstalk coefficients in the proper 

1020 shape. 

1021 

1022 Parameters 

1023 ---------- 

1024 detector : `lsst.afw.cameraGeom.detector` 

1025 Detector that is to be crosstalk corrected. 

1026 

1027 Returns 

1028 ------- 

1029 coeffs : `numpy.ndarray` 

1030 Crosstalk coefficients that can be used to correct the detector. 

1031 

1032 Raises 

1033 ------ 

1034 RuntimeError 

1035 Raised if no coefficients could be generated from this 

1036 detector/configuration. 

1037 """ 

1038 if self.useConfigCoefficients is True: 

1039 coeffs = np.array(self.crosstalkValues).reshape(self.crosstalkShape) 

1040 if detector is not None: 

1041 nAmp = len(detector) 

1042 if coeffs.shape != (nAmp, nAmp): 

1043 raise RuntimeError("Constructed crosstalk coeffients do not match detector shape. " 

1044 f"{coeffs.shape} {nAmp}") 

1045 return coeffs 

1046 elif detector is not None and detector.hasCrosstalk() is True: 

1047 # Assume the detector defines itself consistently. 

1048 return detector.getCrosstalk() 

1049 else: 

1050 raise RuntimeError("Attempted to correct crosstalk without crosstalk coefficients") 

1051 

1052 def hasCrosstalk(self, detector=None): 

1053 """Return a boolean indicating if crosstalk coefficients exist. 

1054 

1055 Parameters 

1056 ---------- 

1057 detector : `lsst.afw.cameraGeom.detector` 

1058 Detector that is to be crosstalk corrected. 

1059 

1060 Returns 

1061 ------- 

1062 hasCrosstalk : `bool` 

1063 True if this detector/configuration has crosstalk coefficients 

1064 defined. 

1065 """ 

1066 if self.useConfigCoefficients is True and self.crosstalkValues is not None: 

1067 return True 

1068 elif detector is not None and detector.hasCrosstalk() is True: 

1069 return True 

1070 else: 

1071 return False 

1072 

1073 

1074class CrosstalkTask(Task): 

1075 """Apply intra-detector crosstalk correction.""" 

1076 ConfigClass = CrosstalkConfig 

1077 _DefaultName = 'isrCrosstalk' 

1078 

1079 def run( 

1080 self, 

1081 exposure, 

1082 crosstalk=None, 

1083 crosstalkSources=None, 

1084 isTrimmed=None, 

1085 camera=None, 

1086 parallelOverscanRegion=None, 

1087 detectorConfig=None, 

1088 fullAmplifier=False, 

1089 gains=None, 

1090 badAmpDict=None, 

1091 ignoreVariance=False, 

1092 doUseFastPath=True, 

1093 ): 

1094 """Apply intra-detector crosstalk correction 

1095 

1096 Parameters 

1097 ---------- 

1098 exposure : `lsst.afw.image.Exposure` 

1099 Exposure for which to remove crosstalk. 

1100 crosstalkCalib : `lsst.ip.isr.CrosstalkCalib`, optional 

1101 External crosstalk calibration to apply. Constructed from 

1102 detector if not found. 

1103 crosstalkSources : `defaultdict`, optional 

1104 Image data for other detectors that are sources of 

1105 crosstalk in exposure. The keys are expected to be names 

1106 of the other detectors, with the values containing 

1107 `lsst.afw.image.Exposure` at the same level of processing 

1108 as ``exposure``. 

1109 The default for intra-detector crosstalk here is None. 

1110 isTrimmed : `bool`, optional 

1111 This option has been deprecated and does not do anything. 

1112 It will be removed after v29. 

1113 camera : `lsst.afw.cameraGeom.Camera`, optional 

1114 Camera associated with this exposure. Only used for 

1115 inter-chip matching. 

1116 parallelOverscanRegion : `bool`, optional 

1117 This option has been deprecated and will be removed after v29. 

1118 detectorConfig : `lsst.ip.isr.OverscanDetectorConfig`, optional 

1119 This option has been deprecated and will be removed after v29. 

1120 fullAmplifier : `bool`, optional 

1121 Use full amplifier and not just imaging region. 

1122 gains : `dict` [`str`, `float`], optional 

1123 Dictionary of amp name to gain. Required if there is a unit 

1124 mismatch between the exposure and the crosstalk matrix. 

1125 badAmpDict : `dict` [`str`, `bool`], optional 

1126 Dictionary to identify bad amplifiers that should not be 

1127 source or target for crosstalk correction. 

1128 ignoreVariance : `bool`, optional 

1129 Ignore variance plane when applying crosstalk? 

1130 doUseFastPath : `bool`, optional 

1131 Use the fast-path crosstalk processing if ignoring variance 

1132 and no background subtraction? 

1133 

1134 Raises 

1135 ------ 

1136 RuntimeError 

1137 Raised if called for a detector that does not have a 

1138 crosstalk correction. Also raised if the crosstalkSource 

1139 is not an expected type. 

1140 """ 

1141 # TODO: Remove on DM-48394 

1142 if isTrimmed is not None: 1142 ↛ 1143line 1142 didn't jump to line 1143 because the condition on line 1142 was never true

1143 warnings.warn( 

1144 "The isTrimmed option has been deprecated and will be removed after v29.", 

1145 FutureWarning, 

1146 ) 

1147 isTrimmed = isTrimmedImage(exposure.maskedImage, exposure.getDetector()) 

1148 

1149 # TODO: Remove on DM-48394 

1150 if parallelOverscanRegion is not None: 1150 ↛ 1151line 1150 didn't jump to line 1151 because the condition on line 1150 was never true

1151 warnings.warn( 

1152 "The parallelOverscanRegion option has been deprecated and will be removed after v29.", 

1153 FutureWarning, 

1154 ) 

1155 if detectorConfig is not None: 1155 ↛ 1156line 1155 didn't jump to line 1156 because the condition on line 1155 was never true

1156 warnings.warn( 

1157 "The detectorConfig option has been deprecated and will be removed after v29.", 

1158 FutureWarning, 

1159 ) 

1160 

1161 if not crosstalk: 

1162 crosstalk = CrosstalkCalib(log=self.log) 

1163 crosstalk = crosstalk.fromDetector(exposure.getDetector(), 

1164 coeffVector=self.config.crosstalkValues) 

1165 if not crosstalk.log: 1165 ↛ 1166line 1165 didn't jump to line 1166 because the condition on line 1165 was never true

1166 crosstalk.log = self.log 

1167 

1168 doSqrCrosstalk = self.config.doQuadraticCrosstalkCorrection 

1169 

1170 if doSqrCrosstalk and crosstalk.coeffsSqr is None: 1170 ↛ 1171line 1170 didn't jump to line 1171 because the condition on line 1170 was never true

1171 raise RuntimeError("Attempted to perform NL crosstalk correction without NL " 

1172 "crosstalk coefficients.") 

1173 if doSqrCrosstalk: 

1174 crosstalkCoeffsSqr = crosstalk.coeffsSqr 

1175 else: 

1176 crosstalkCoeffsSqr = None 

1177 

1178 if not crosstalk.hasCrosstalk: 

1179 raise RuntimeError("Attempted to correct crosstalk without crosstalk coefficients.") 

1180 

1181 # Get the exposure units; defaults to adu. 

1182 exposureUnits = exposure.metadata.get("LSST ISR UNITS", "adu") 

1183 invertGains = False 

1184 gainApply = False 

1185 if crosstalk.crosstalkRatiosUnits != exposureUnits: 

1186 detector = exposure.getDetector() 

1187 

1188 if gains is None and np.all(crosstalk.fitGains == 0.0): 1188 ↛ 1189line 1188 didn't jump to line 1189 because the condition on line 1188 was never true

1189 raise RuntimeError( 

1190 f"Unit mismatch between exposure ({exposureUnits}) and " 

1191 f"crosstalk ratios ({crosstalk.crosstalkRatiosUnits}) and " 

1192 "no gains were supplied or available in crosstalk calibration.", 

1193 ) 

1194 elif gains is None: 1194 ↛ 1201line 1194 didn't jump to line 1201 because the condition on line 1194 was always true

1195 self.log.info("Using crosstalk calib fitGains for gain corrections.") 

1196 gains = {} 

1197 for i, amp in enumerate(detector): 

1198 gains[amp.getName()] = crosstalk.fitGains[i] 

1199 

1200 # Check individual gains for finite-ness. 

1201 gainArray = np.zeros(len(detector)) 

1202 for i, amp in enumerate(detector): 

1203 gainArray[i] = gains[amp.getName()] 

1204 badGains = (~np.isfinite(gainArray) | (gainArray == 0.0)) 

1205 if np.any(badGains): 1205 ↛ 1206line 1205 didn't jump to line 1206 because the condition on line 1205 was never true

1206 if np.all(badGains): 

1207 raise RuntimeError("No valid (finite, non-zero) gains found for crosstalk correction.") 

1208 

1209 badAmpNames = [amp.getName() for i, amp in enumerate(detector) if badGains[i]] 

1210 

1211 self.log.warning("Illegal gain value found for %d amplifiers %r in crosstalk correction; " 

1212 "substituting with median gain.", badGains.sum(), badAmpNames) 

1213 medGain = np.median(gainArray[~badGains]) 

1214 gainArray[badGains] = medGain 

1215 for i, amp in enumerate(detector): 

1216 gains[amp.getName()] = gainArray[i] 

1217 

1218 gainApply = True 

1219 

1220 if crosstalk.crosstalkRatiosUnits == "adu": 1220 ↛ 1221line 1220 didn't jump to line 1221 because the condition on line 1220 was never true

1221 invertGains = True 

1222 

1223 if exposureUnits == "adu": 1223 ↛ 1228line 1223 didn't jump to line 1228 because the condition on line 1223 was always true

1224 self.log.info("Temporarily applying gains to perform crosstalk correction " 

1225 "because crosstalk is in electron units and exposure is in " 

1226 "adu units.") 

1227 else: 

1228 self.log.info("Temporarily un-applying gains to perform crosstalk correction " 

1229 "because crosstalk is in adu units and exposure is in " 

1230 "electron units.") 

1231 

1232 self.log.info("Applying crosstalk correction.") 

1233 

1234 with gainContext( 

1235 exposure, 

1236 exposure.image, 

1237 gainApply, 

1238 gains=gains, 

1239 invert=invertGains, 

1240 isTrimmed=isTrimmed, 

1241 ): 

1242 crosstalk.subtractCrosstalk( 

1243 exposure, 

1244 crosstalkCoeffs=crosstalk.coeffs, 

1245 crosstalkCoeffsSqr=crosstalkCoeffsSqr, 

1246 crosstalkCoeffsValid=crosstalk.coeffValid, 

1247 minPixelToMask=self.config.minPixelToMask, 

1248 doCrosstalkMask=self.config.doCrosstalkMask, 

1249 doSubtrahendMasking=self.config.doSubtrahendMasking, 

1250 crosstalkStr=self.config.crosstalkMaskPlane, 

1251 backgroundMethod=self.config.crosstalkBackgroundMethod, 

1252 doSqrCrosstalk=doSqrCrosstalk, 

1253 fullAmplifier=fullAmplifier, 

1254 badAmpDict=badAmpDict, 

1255 ignoreVariance=ignoreVariance, 

1256 doUseFastPath=self.config.doUseFastPath, 

1257 ) 

1258 

1259 if crosstalk.interChip: 

1260 if crosstalkSources: 1260 ↛ 1309line 1260 didn't jump to line 1309 because the condition on line 1260 was always true

1261 # Parse crosstalkSources: Identify which detectors we have 

1262 # available 

1263 if isinstance(crosstalkSources[0], lsst.afw.image.Exposure): 1263 ↛ 1266line 1263 didn't jump to line 1266 because the condition on line 1263 was always true

1264 # Received afwImage.Exposure 

1265 sourceNames = [exp.getDetector().getName() for exp in crosstalkSources] 

1266 elif isinstance(crosstalkSources[0], lsst.daf.butler.DeferredDatasetHandle): 

1267 # Received dafButler.DeferredDatasetHandle 

1268 detectorList = [source.dataId['detector'] for source in crosstalkSources] 

1269 sourceNames = [camera[detectorId].getName() for detectorId in detectorList] 

1270 else: 

1271 raise RuntimeError("Unknown object passed as crosstalk sources.", 

1272 type(crosstalkSources[0])) 

1273 

1274 for detName in crosstalk.interChip: 

1275 if detName not in sourceNames: 1275 ↛ 1276line 1275 didn't jump to line 1276 because the condition on line 1275 was never true

1276 self.log.warning("Crosstalk lists %s, not found in sources: %s", 

1277 detName, sourceNames) 

1278 continue 

1279 # Get the coefficients. 

1280 interChipCoeffs = crosstalk.interChip[detName] 

1281 

1282 sourceExposure = crosstalkSources[sourceNames.index(detName)] 

1283 if isinstance(sourceExposure, lsst.daf.butler.DeferredDatasetHandle): 1283 ↛ 1285line 1283 didn't jump to line 1285 because the condition on line 1283 was never true

1284 # Dereference the dafButler.DeferredDatasetHandle. 

1285 sourceExposure = sourceExposure.get() 

1286 if not isinstance(sourceExposure, lsst.afw.image.Exposure): 1286 ↛ 1287line 1286 didn't jump to line 1287 because the condition on line 1286 was never true

1287 raise RuntimeError("Unknown object passed as crosstalk sources.", 

1288 type(sourceExposure)) 

1289 

1290 if sourceExposure.getBBox() != exposure.getBBox(): 1290 ↛ 1291line 1290 didn't jump to line 1291 because the condition on line 1290 was never true

1291 raise RuntimeError( 

1292 "Mis-match between exposure bounding box and crosstalk source " 

1293 "exposure bounding box. Were these run with the same trim state?", 

1294 ) 

1295 

1296 self.log.info("Correcting detector %s with ctSource %s", 

1297 exposure.getDetector().getName(), 

1298 sourceExposure.getDetector().getName()) 

1299 crosstalk.subtractCrosstalk( 

1300 exposure, 

1301 sourceExposure=sourceExposure, 

1302 crosstalkCoeffs=interChipCoeffs, 

1303 minPixelToMask=self.config.minPixelToMask, 

1304 crosstalkStr=self.config.crosstalkMaskPlane, 

1305 backgroundMethod=self.config.crosstalkBackgroundMethod, 

1306 ignoreVariance=ignoreVariance, 

1307 ) 

1308 else: 

1309 self.log.warning("Crosstalk contains interChip coefficients, but no sources found!") 

1310 

1311 

1312class NullCrosstalkTask(CrosstalkTask): 

1313 def run(self, exposure, crosstalkSources=None): 

1314 self.log.info("Not performing any crosstalk correction")