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

486 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-14 10:00 +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 N = len(sourceDetector) 

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

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

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

831 srcArr = sourceMaskedImage.image.array 

832 A = np.empty((2*N, ny*nx), dtype=np.float32) 

833 for s, amp in enumerate(sourceDetector): 

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

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

836 if np.any(coeffsSqr): 

837 np.multiply(A[:N], A[:N], out=A[N:]) 

838 M = np.concatenate([coeffs, coeffsSqr]).T.astype(np.float32) 

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

840 C = M @ A 

841 else: 

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

843 C = coeffs.T.astype(np.float32) @ A[:N] 

844 

845 subArr = subtrahend.image.array 

846 for t, amp in enumerate(targetDetector): 

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

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

849 

850 else: 

851 for sourceIndex, sourceAmp in enumerate(sourceDetector): 

852 for targetIndex, targetAmp in enumerate(targetDetector): 

853 coeff = coeffs[sourceIndex, targetIndex] 

854 coeffSqr = coeffsSqr[sourceIndex, targetIndex] 

855 

856 if coeff == 0.0: 

857 continue 

858 

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

860 

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

862 # source amplifier data. 

863 if imageOnly: 

864 sourceImage = self.extractAmp( 

865 sourceMaskedImage.image, 

866 sourceAmp, 

867 targetAmp, 

868 isTrimmed=isTrimmed, 

869 fullAmplifier=fullAmplifier, 

870 ) 

871 

872 targetImage = subtrahend[targetBBox].image 

873 else: 

874 sourceImage = self.extractAmp( 

875 sourceMaskedImage, 

876 sourceAmp, 

877 targetAmp, 

878 isTrimmed=isTrimmed, 

879 fullAmplifier=fullAmplifier, 

880 ) 

881 targetImage = subtrahend[targetBBox] 

882 

883 # Remove all other masks from copied sourceImage. 

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

885 

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

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

888 

889 # This operation will also transfer the CROSSTALK mask bit 

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

891 # using a masked image. 

892 targetImage.scaledPlus(coeff, sourceImage) 

893 if coeffSqr != 0.0: 

894 sourceImage.scaledMultiplies(1.0, sourceImage) 

895 targetImage.scaledPlus(coeffSqr, sourceImage) 

896 

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

898 # contains the crosstalk mask. 

899 sourceMaskedImage.mask.clearMaskPlane(sourceCrosstalkPlane) 

900 if sourceExposure is not None: 

901 targetMaskedImage.mask.clearMaskPlane(targetCrosstalkPlane) 

902 

903 if doCrosstalkMask and doSubtrahendMasking: 

904 # Set crosstalkStr bit only for those pixels that have 

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

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

907 # originally. 

908 

909 # The existing mask in the subtrahend comes from the 

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

911 # recalculate it. 

912 subtrahend.mask.clearMaskPlane(targetCrosstalkPlane) 

913 

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

915 # correction is significantly different than the median 

916 # value on that amplifier (which includes the contribution 

917 # of every other amplifier background that crosstalks onto 

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

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

920 # that background, but still include that contribution in 

921 # the correction we're applying. 

922 subtrahendBackgrounds = {} 

923 for amp in targetDetector: 

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

925 # calculations. 

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

927 ampData = subtrahend[bbox] 

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

929 subtrahendBackgrounds[amp.getName()] = background 

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

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

932 

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

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

935 

936 # Put the backgrounds back. 

937 for amp in targetDetector: 

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

939 ampData = subtrahend[bbox] 

940 background = subtrahendBackgrounds[amp.getName()] 

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

942 

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

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

945 # bit where applicable. 

946 

947 targetMaskedImage -= subtrahend 

948 

949 

950class CrosstalkConfig(Config): 

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

952 minPixelToMask = Field( 

953 dtype=float, 

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

955 default=45000 

956 ) 

957 crosstalkMaskPlane = Field( 

958 dtype=str, 

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

960 default="CROSSTALK" 

961 ) 

962 doCrosstalkMask = Field( 

963 dtype=bool, 

964 doc="Compute the crosstalk mask?", 

965 default=True, 

966 ) 

967 doSubtrahendMasking = Field( 

968 dtype=bool, 

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

970 "Not used if doCrosstalkMask is False.", 

971 default=False, 

972 ) 

973 crosstalkBackgroundMethod = ChoiceField( 

974 dtype=str, 

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

976 default="None", 

977 allowed={ 

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

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

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

981 }, 

982 ) 

983 useConfigCoefficients = Field( 

984 dtype=bool, 

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

986 default=False, 

987 ) 

988 crosstalkValues = ListField( 

989 dtype=float, 

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

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

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

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

994 default=[0.0], 

995 ) 

996 crosstalkShape = ListField( 

997 dtype=int, 

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

999 default=[1], 

1000 ) 

1001 doQuadraticCrosstalkCorrection = Field( 

1002 dtype=bool, 

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

1004 default=False, 

1005 ) 

1006 doUseFastPath = Field( 

1007 dtype=bool, 

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

1009 default=True, 

1010 ) 

1011 

1012 def getCrosstalk(self, detector=None): 

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

1014 shape. 

1015 

1016 Parameters 

1017 ---------- 

1018 detector : `lsst.afw.cameraGeom.detector` 

1019 Detector that is to be crosstalk corrected. 

1020 

1021 Returns 

1022 ------- 

1023 coeffs : `numpy.ndarray` 

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

1025 

1026 Raises 

1027 ------ 

1028 RuntimeError 

1029 Raised if no coefficients could be generated from this 

1030 detector/configuration. 

1031 """ 

1032 if self.useConfigCoefficients is True: 

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

1034 if detector is not None: 

1035 nAmp = len(detector) 

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

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

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

1039 return coeffs 

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

1041 # Assume the detector defines itself consistently. 

1042 return detector.getCrosstalk() 

1043 else: 

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

1045 

1046 def hasCrosstalk(self, detector=None): 

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

1048 

1049 Parameters 

1050 ---------- 

1051 detector : `lsst.afw.cameraGeom.detector` 

1052 Detector that is to be crosstalk corrected. 

1053 

1054 Returns 

1055 ------- 

1056 hasCrosstalk : `bool` 

1057 True if this detector/configuration has crosstalk coefficients 

1058 defined. 

1059 """ 

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

1061 return True 

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

1063 return True 

1064 else: 

1065 return False 

1066 

1067 

1068class CrosstalkTask(Task): 

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

1070 ConfigClass = CrosstalkConfig 

1071 _DefaultName = 'isrCrosstalk' 

1072 

1073 def run( 

1074 self, 

1075 exposure, 

1076 crosstalk=None, 

1077 crosstalkSources=None, 

1078 isTrimmed=None, 

1079 camera=None, 

1080 parallelOverscanRegion=None, 

1081 detectorConfig=None, 

1082 fullAmplifier=False, 

1083 gains=None, 

1084 badAmpDict=None, 

1085 ignoreVariance=False, 

1086 doUseFastPath=True, 

1087 ): 

1088 """Apply intra-detector crosstalk correction 

1089 

1090 Parameters 

1091 ---------- 

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

1093 Exposure for which to remove crosstalk. 

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

1095 External crosstalk calibration to apply. Constructed from 

1096 detector if not found. 

1097 crosstalkSources : `defaultdict`, optional 

1098 Image data for other detectors that are sources of 

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

1100 of the other detectors, with the values containing 

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

1102 as ``exposure``. 

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

1104 isTrimmed : `bool`, optional 

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

1106 It will be removed after v29. 

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

1108 Camera associated with this exposure. Only used for 

1109 inter-chip matching. 

1110 parallelOverscanRegion : `bool`, optional 

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

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

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

1114 fullAmplifier : `bool`, optional 

1115 Use full amplifier and not just imaging region. 

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

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

1118 mismatch between the exposure and the crosstalk matrix. 

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

1120 Dictionary to identify bad amplifiers that should not be 

1121 source or target for crosstalk correction. 

1122 ignoreVariance : `bool`, optional 

1123 Ignore variance plane when applying crosstalk? 

1124 doUseFastPath : `bool`, optional 

1125 Use the fast-path crosstalk processing if ignoring variance 

1126 and no background subtraction? 

1127 

1128 Raises 

1129 ------ 

1130 RuntimeError 

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

1132 crosstalk correction. Also raised if the crosstalkSource 

1133 is not an expected type. 

1134 """ 

1135 # TODO: Remove on DM-48394 

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

1137 warnings.warn( 

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

1139 FutureWarning, 

1140 ) 

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

1142 

1143 # TODO: Remove on DM-48394 

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

1145 warnings.warn( 

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

1147 FutureWarning, 

1148 ) 

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

1150 warnings.warn( 

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

1152 FutureWarning, 

1153 ) 

1154 

1155 if not crosstalk: 

1156 crosstalk = CrosstalkCalib(log=self.log) 

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

1158 coeffVector=self.config.crosstalkValues) 

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

1160 crosstalk.log = self.log 

1161 

1162 doSqrCrosstalk = self.config.doQuadraticCrosstalkCorrection 

1163 

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

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

1166 "crosstalk coefficients.") 

1167 if doSqrCrosstalk: 

1168 crosstalkCoeffsSqr = crosstalk.coeffsSqr 

1169 else: 

1170 crosstalkCoeffsSqr = None 

1171 

1172 if not crosstalk.hasCrosstalk: 

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

1174 

1175 # Get the exposure units; defaults to adu. 

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

1177 invertGains = False 

1178 gainApply = False 

1179 if crosstalk.crosstalkRatiosUnits != exposureUnits: 

1180 detector = exposure.getDetector() 

1181 

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

1183 raise RuntimeError( 

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

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

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

1187 ) 

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

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

1190 gains = {} 

1191 for i, amp in enumerate(detector): 

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

1193 

1194 # Check individual gains for finite-ness. 

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

1196 for i, amp in enumerate(detector): 

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

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

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

1200 if np.all(badGains): 

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

1202 

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

1204 

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

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

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

1208 gainArray[badGains] = medGain 

1209 for i, amp in enumerate(detector): 

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

1211 

1212 gainApply = True 

1213 

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

1215 invertGains = True 

1216 

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

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

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

1220 "adu units.") 

1221 else: 

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

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

1224 "electron units.") 

1225 

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

1227 

1228 with gainContext( 

1229 exposure, 

1230 exposure.image, 

1231 gainApply, 

1232 gains=gains, 

1233 invert=invertGains, 

1234 isTrimmed=isTrimmed, 

1235 ): 

1236 crosstalk.subtractCrosstalk( 

1237 exposure, 

1238 crosstalkCoeffs=crosstalk.coeffs, 

1239 crosstalkCoeffsSqr=crosstalkCoeffsSqr, 

1240 crosstalkCoeffsValid=crosstalk.coeffValid, 

1241 minPixelToMask=self.config.minPixelToMask, 

1242 doCrosstalkMask=self.config.doCrosstalkMask, 

1243 doSubtrahendMasking=self.config.doSubtrahendMasking, 

1244 crosstalkStr=self.config.crosstalkMaskPlane, 

1245 backgroundMethod=self.config.crosstalkBackgroundMethod, 

1246 doSqrCrosstalk=doSqrCrosstalk, 

1247 fullAmplifier=fullAmplifier, 

1248 badAmpDict=badAmpDict, 

1249 ignoreVariance=ignoreVariance, 

1250 doUseFastPath=self.config.doUseFastPath, 

1251 ) 

1252 

1253 if crosstalk.interChip: 

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

1255 # Parse crosstalkSources: Identify which detectors we have 

1256 # available 

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

1258 # Received afwImage.Exposure 

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

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

1261 # Received dafButler.DeferredDatasetHandle 

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

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

1264 else: 

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

1266 type(crosstalkSources[0])) 

1267 

1268 for detName in crosstalk.interChip: 

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

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

1271 detName, sourceNames) 

1272 continue 

1273 # Get the coefficients. 

1274 interChipCoeffs = crosstalk.interChip[detName] 

1275 

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

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

1278 # Dereference the dafButler.DeferredDatasetHandle. 

1279 sourceExposure = sourceExposure.get() 

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

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

1282 type(sourceExposure)) 

1283 

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

1285 raise RuntimeError( 

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

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

1288 ) 

1289 

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

1291 exposure.getDetector().getName(), 

1292 sourceExposure.getDetector().getName()) 

1293 crosstalk.subtractCrosstalk( 

1294 exposure, 

1295 sourceExposure=sourceExposure, 

1296 crosstalkCoeffs=interChipCoeffs, 

1297 minPixelToMask=self.config.minPixelToMask, 

1298 crosstalkStr=self.config.crosstalkMaskPlane, 

1299 backgroundMethod=self.config.crosstalkBackgroundMethod, 

1300 ignoreVariance=ignoreVariance, 

1301 ) 

1302 else: 

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

1304 

1305 

1306class NullCrosstalkTask(CrosstalkTask): 

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

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