Coverage for python/lsst/ap/association/transformDiaSourceCatalog.py: 20%

168 statements  

« prev     ^ index     » next       coverage.py v7.2.7, created at 2023-06-22 11:02 +0000

1# This file is part of ap_association 

2# 

3# Developed for the LSST Data Management System. 

4# This product includes software developed by the LSST Project 

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

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

7# for details of code ownership. 

8# 

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

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

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

12# (at your option) any later version. 

13# 

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

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

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

17# GNU General Public License for more details. 

18# 

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

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

21 

22__all__ = ("TransformDiaSourceCatalogConnections", 

23 "TransformDiaSourceCatalogConfig", 

24 "TransformDiaSourceCatalogTask", 

25 "UnpackApdbFlags") 

26 

27import numpy as np 

28import os 

29import yaml 

30import pandas as pd 

31 

32from lsst.daf.base import DateTime 

33import lsst.pex.config as pexConfig 

34import lsst.pipe.base as pipeBase 

35import lsst.pipe.base.connectionTypes as connTypes 

36from lsst.meas.base import DetectorVisitIdGeneratorConfig 

37from lsst.pipe.tasks.postprocess import TransformCatalogBaseTask, TransformCatalogBaseConfig 

38from lsst.pipe.tasks.functors import Column 

39from lsst.utils.timer import timeMethod 

40 

41 

42class TransformDiaSourceCatalogConnections(pipeBase.PipelineTaskConnections, 

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

44 defaultTemplates={"coaddName": "deep", "fakesType": ""}): 

45 diaSourceSchema = connTypes.InitInput( 

46 doc="Schema for DIASource catalog output by ImageDifference.", 

47 storageClass="SourceCatalog", 

48 name="{fakesType}{coaddName}Diff_diaSrc_schema", 

49 ) 

50 diaSourceCat = connTypes.Input( 

51 doc="Catalog of DiaSources produced during image differencing.", 

52 name="{fakesType}{coaddName}Diff_diaSrc", 

53 storageClass="SourceCatalog", 

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

55 ) 

56 diffIm = connTypes.Input( 

57 doc="Difference image on which the DiaSources were detected.", 

58 name="{fakesType}{coaddName}Diff_differenceExp", 

59 storageClass="ExposureF", 

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

61 ) 

62 reliability = connTypes.Input( 

63 doc="Reliability (e.g. real/bogus) classificiation of diaSourceCat sources (optional).", 

64 name="{fakesType}{coaddName}RealBogusSources", 

65 storageClass="Catalog", 

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

67 ) 

68 diaSourceTable = connTypes.Output( 

69 doc=".", 

70 name="{fakesType}{coaddName}Diff_diaSrcTable", 

71 storageClass="DataFrame", 

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

73 ) 

74 

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

76 super().__init__(config=config) 

77 if not self.config.doIncludeReliability: 

78 self.inputs.remove("reliability") 

79 

80 

81class TransformDiaSourceCatalogConfig(TransformCatalogBaseConfig, 

82 pipelineConnections=TransformDiaSourceCatalogConnections): 

83 flagMap = pexConfig.Field( 

84 dtype=str, 

85 doc="Yaml file specifying SciencePipelines flag fields to bit packs.", 

86 default=os.path.join("${AP_ASSOCIATION_DIR}", 

87 "data", 

88 "association-flag-map.yaml"), 

89 ) 

90 flagRenameMap = pexConfig.Field( 

91 dtype=str, 

92 doc="Yaml file specifying specifying rules to rename flag names", 

93 default=os.path.join("${AP_ASSOCIATION_DIR}", 

94 "data", 

95 "flag-rename-rules.yaml"), 

96 ) 

97 doRemoveSkySources = pexConfig.Field( 

98 dtype=bool, 

99 default=False, 

100 doc="Input DiaSource catalog contains SkySources that should be " 

101 "removed before storing the output DiaSource catalog." 

102 ) 

103 doPackFlags = pexConfig.Field( 

104 dtype=bool, 

105 default=True, 

106 doc="Do pack the flags into one integer column named 'flags'." 

107 "If False, instead produce one boolean column per flag." 

108 ) 

109 doIncludeReliability = pexConfig.Field( 

110 dtype=bool, 

111 default=False, 

112 doc="Include the reliability (e.g. real/bogus) classifications in the output." 

113 ) 

114 

115 idGenerator = DetectorVisitIdGeneratorConfig.make_field() 

116 

117 def setDefaults(self): 

118 super().setDefaults() 

119 self.functorFile = os.path.join("${AP_ASSOCIATION_DIR}", 

120 "data", 

121 "DiaSource.yaml") 

122 

123 

124class TransformDiaSourceCatalogTask(TransformCatalogBaseTask): 

125 """Transform a DiaSource catalog by calibrating and renaming columns to 

126 produce a table ready to insert into the Apdb. 

127 

128 Parameters 

129 ---------- 

130 initInputs : `dict` 

131 Must contain ``diaSourceSchema`` as the schema for the input catalog. 

132 """ 

133 ConfigClass = TransformDiaSourceCatalogConfig 

134 _DefaultName = "transformDiaSourceCatalog" 

135 # Needed to create a valid TransformCatalogBaseTask, but unused 

136 inputDataset = "deepDiff_diaSrc" 

137 outputDataset = "deepDiff_diaSrcTable" 

138 

139 def __init__(self, initInputs, **kwargs): 

140 super().__init__(**kwargs) 

141 self.funcs = self.getFunctors() 

142 self.inputSchema = initInputs['diaSourceSchema'].schema 

143 self._create_bit_pack_mappings() 

144 

145 if not self.config.doPackFlags: 

146 # get the flag rename rules 

147 with open(os.path.expandvars(self.config.flagRenameMap)) as yaml_stream: 

148 self.rename_rules = list(yaml.safe_load_all(yaml_stream)) 

149 

150 def _create_bit_pack_mappings(self): 

151 """Setup all flag bit packings. 

152 """ 

153 self.bit_pack_columns = [] 

154 flag_map_file = os.path.expandvars(self.config.flagMap) 

155 with open(flag_map_file) as yaml_stream: 

156 table_list = list(yaml.safe_load_all(yaml_stream)) 

157 for table in table_list: 

158 if table['tableName'] == 'DiaSource': 

159 self.bit_pack_columns = table['columns'] 

160 break 

161 

162 # Test that all flags requested are present in the input schemas. 

163 # Output schemas are flexible, however if names are not specified in 

164 # the Apdb schema, flag columns will not be persisted. 

165 for outputFlag in self.bit_pack_columns: 

166 bitList = outputFlag['bitList'] 

167 for bit in bitList: 

168 try: 

169 self.inputSchema.find(bit['name']) 

170 except KeyError: 

171 raise KeyError( 

172 "Requested column %s not found in input DiaSource " 

173 "schema. Please check that the requested input " 

174 "column exists." % bit['name']) 

175 

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

177 inputs = butlerQC.get(inputRefs) 

178 idGenerator = self.config.idGenerator.apply(butlerQC.quantum.dataId) 

179 inputs["ccdVisitId"] = idGenerator.catalog_id 

180 inputs["band"] = butlerQC.quantum.dataId["band"] 

181 

182 outputs = self.run(**inputs) 

183 

184 butlerQC.put(outputs, outputRefs) 

185 

186 @timeMethod 

187 def run(self, 

188 diaSourceCat, 

189 diffIm, 

190 band, 

191 ccdVisitId, 

192 reliability=None): 

193 """Convert input catalog to ParquetTable/Pandas and run functors. 

194 

195 Additionally, add new columns for stripping information from the 

196 exposure and into the DiaSource catalog. 

197 

198 Parameters 

199 ---------- 

200 diaSourceCat : `lsst.afw.table.SourceCatalog` 

201 Catalog of sources measured on the difference image. 

202 diffIm : `lsst.afw.image.Exposure` 

203 Result of subtracting template and science images. 

204 band : `str` 

205 Filter band of the science image. 

206 ccdVisitId : `int` 

207 Identifier for this detector+visit. 

208 reliability : `lsst.afw.table.SourceCatalog` 

209 Reliability (e.g. real/bogus) scores, row-matched to 

210 ``diaSourceCat``. 

211 

212 Returns 

213 ------- 

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

215 Results struct with components. 

216 

217 - ``diaSourceTable`` : Catalog of DiaSources with calibrated values 

218 and renamed columns. 

219 (`lsst.pipe.tasks.ParquetTable` or `pandas.DataFrame`) 

220 """ 

221 self.log.info( 

222 "Transforming/standardizing the DiaSource table ccdVisitId: %i", 

223 ccdVisitId) 

224 

225 diaSourceDf = diaSourceCat.asAstropy().to_pandas() 

226 if self.config.doRemoveSkySources: 

227 diaSourceDf = diaSourceDf[~diaSourceDf["sky_source"]] 

228 diaSourceCat = diaSourceCat[~diaSourceCat["sky_source"]] 

229 

230 diaSourceDf["time_processed"] = DateTime.now().toPython() 

231 diaSourceDf["snr"] = getSignificance(diaSourceCat) 

232 diaSourceDf["bboxSize"] = self.computeBBoxSizes(diaSourceCat) 

233 diaSourceDf["ccdVisitId"] = ccdVisitId 

234 diaSourceDf["band"] = band 

235 diaSourceDf["midpointMjdTai"] = diffIm.visitInfo.date.get(system=DateTime.MJD) 

236 diaSourceDf["diaObjectId"] = 0 

237 diaSourceDf["ssObjectId"] = 0 

238 

239 if self.config.doIncludeReliability: 

240 reliabilityDf = reliability.asAstropy().to_pandas() 

241 # This uses the pandas index to match scores with diaSources 

242 # but it will silently fill with NaNs if they don't match. 

243 diaSourceDf = pd.merge(diaSourceDf, reliabilityDf, 

244 how="left", on="id", validate="1:1") 

245 diaSourceDf = diaSourceDf.rename(columns={"score": "reliability"}) 

246 if np.sum(diaSourceDf["reliability"].isna()) == len(diaSourceDf): 

247 self.log.warning("Reliability identifiers did not match diaSourceIds") 

248 else: 

249 diaSourceDf["reliability"] = np.float32(np.nan) 

250 

251 if self.config.doPackFlags: 

252 # either bitpack the flags 

253 self.bitPackFlags(diaSourceDf) 

254 else: 

255 # or add the individual flag functors 

256 self.addUnpackedFlagFunctors() 

257 # and remove the packed flag functor 

258 if 'flags' in self.funcs.funcDict: 

259 del self.funcs.funcDict['flags'] 

260 

261 df = self.transform(band, 

262 diaSourceDf, 

263 self.funcs, 

264 dataId=None).df 

265 

266 return pipeBase.Struct( 

267 diaSourceTable=df, 

268 ) 

269 

270 def addUnpackedFlagFunctors(self): 

271 """Add Column functor for each of the flags to the internal functor 

272 dictionary. 

273 """ 

274 for flag in self.bit_pack_columns[0]['bitList']: 

275 flagName = flag['name'] 

276 targetName = self.funcs.renameCol(flagName, self.rename_rules[0]['flag_rename_rules']) 

277 self.funcs.update({targetName: Column(flagName)}) 

278 

279 def computeBBoxSizes(self, inputCatalog): 

280 """Compute the size of a square bbox that fully contains the detection 

281 footprint. 

282 

283 Parameters 

284 ---------- 

285 inputCatalog : `lsst.afw.table.SourceCatalog` 

286 Catalog containing detected footprints. 

287 

288 Returns 

289 ------- 

290 outputBBoxSizes : `np.ndarray`, (N,) 

291 Array of bbox sizes. 

292 """ 

293 # Schema validation requires that this field is int. 

294 outputBBoxSizes = np.empty(len(inputCatalog), dtype=int) 

295 for i, record in enumerate(inputCatalog): 

296 footprintBBox = record.getFootprint().getBBox() 

297 # Compute twice the size of the largest dimension of the footprint 

298 # bounding box. This is the largest footprint we should need to cover 

299 # the complete DiaSource assuming the centroid is within the bounding 

300 # box. 

301 maxSize = 2 * np.max([footprintBBox.getWidth(), 

302 footprintBBox.getHeight()]) 

303 recX = record.getCentroid().x 

304 recY = record.getCentroid().y 

305 bboxSize = int( 

306 np.ceil(2 * np.max(np.fabs([footprintBBox.maxX - recX, 

307 footprintBBox.minX - recX, 

308 footprintBBox.maxY - recY, 

309 footprintBBox.minY - recY])))) 

310 if bboxSize > maxSize: 

311 bboxSize = maxSize 

312 outputBBoxSizes[i] = bboxSize 

313 

314 return outputBBoxSizes 

315 

316 def bitPackFlags(self, df): 

317 """Pack requested flag columns in inputRecord into single columns in 

318 outputRecord. 

319 

320 Parameters 

321 ---------- 

322 df : `pandas.DataFrame` 

323 DataFrame to read bits from and pack them into. 

324 """ 

325 for outputFlag in self.bit_pack_columns: 

326 bitList = outputFlag['bitList'] 

327 value = np.zeros(len(df), dtype=np.uint64) 

328 for bit in bitList: 

329 # Hard type the bit arrays. 

330 value += (df[bit['name']]*2**bit['bit']).to_numpy().astype(np.uint64) 

331 df[outputFlag['columnName']] = value 

332 

333 

334class UnpackApdbFlags: 

335 """Class for unpacking bits from integer flag fields stored in the Apdb. 

336 

337 Attributes 

338 ---------- 

339 flag_map_file : `str` 

340 Absolute or relative path to a yaml file specifiying mappings of flags 

341 to integer bits. 

342 table_name : `str` 

343 Name of the Apdb table the integer bit data are coming from. 

344 """ 

345 

346 def __init__(self, flag_map_file, table_name): 

347 self.bit_pack_columns = [] 

348 flag_map_file = os.path.expandvars(flag_map_file) 

349 with open(flag_map_file) as yaml_stream: 

350 table_list = list(yaml.safe_load_all(yaml_stream)) 

351 for table in table_list: 

352 if table['tableName'] == table_name: 

353 self.bit_pack_columns = table['columns'] 

354 break 

355 

356 self.output_flag_columns = {} 

357 

358 for column in self.bit_pack_columns: 

359 names = [] 

360 for bit in column["bitList"]: 

361 names.append((bit["name"], bool)) 

362 self.output_flag_columns[column["columnName"]] = names 

363 

364 def unpack(self, input_flag_values, flag_name): 

365 """Determine individual boolean flags from an input array of unsigned 

366 ints. 

367 

368 Parameters 

369 ---------- 

370 input_flag_values : array-like of type uint 

371 Array of integer flags to unpack. 

372 flag_name : `str` 

373 Apdb column name of integer flags to unpack. Names of packed int 

374 flags are given by the flag_map_file. 

375 

376 Returns 

377 ------- 

378 output_flags : `numpy.ndarray` 

379 Numpy named tuple of booleans. 

380 """ 

381 bit_names_types = self.output_flag_columns[flag_name] 

382 output_flags = np.zeros(len(input_flag_values), dtype=bit_names_types) 

383 

384 for bit_idx, (bit_name, dtypes) in enumerate(bit_names_types): 

385 masked_bits = np.bitwise_and(input_flag_values, 2**bit_idx) 

386 output_flags[bit_name] = masked_bits 

387 

388 return output_flags 

389 

390 def flagExists(self, flagName, columnName='flags'): 

391 """Check if named flag is in the bitpacked flag set. 

392 

393 Parameters: 

394 ---------- 

395 flagName : `str` 

396 Flag name to search for. 

397 columnName : `str`, optional 

398 Name of bitpacked flag column to search in. 

399 

400 Returns 

401 ------- 

402 flagExists : `bool` 

403 `True` if `flagName` is present in `columnName`. 

404 

405 Raises 

406 ------ 

407 ValueError 

408 Raised if `columnName` is not defined. 

409 """ 

410 if columnName not in self.output_flag_columns: 

411 raise ValueError(f'column {columnName} not in flag map: {self.output_flag_columns}') 

412 

413 return flagName in [c[0] for c in self.output_flag_columns[columnName]] 

414 

415 def makeFlagBitMask(self, flagNames, columnName='flags'): 

416 """Return a bitmask corresponding to the supplied flag names. 

417 

418 Parameters: 

419 ---------- 

420 flagNames : `list` [`str`] 

421 Flag names to include in the bitmask. 

422 columnName : `str`, optional 

423 Name of bitpacked flag column. 

424 

425 Returns 

426 ------- 

427 bitmask : `np.unit64` 

428 Bitmask corresponding to the supplied flag names given the loaded configuration. 

429 

430 Raises 

431 ------ 

432 ValueError 

433 Raised if a flag in `flagName` is not included in `columnName`. 

434 """ 

435 bitmask = np.uint64(0) 

436 

437 for flag in flagNames: 

438 if not self.flagExists(flag, columnName=columnName): 

439 raise ValueError(f"flag '{flag}' not included in '{columnName}' flag column") 

440 

441 for outputFlag in self.bit_pack_columns: 

442 if outputFlag['columnName'] == columnName: 

443 bitList = outputFlag['bitList'] 

444 for bit in bitList: 

445 if bit['name'] in flagNames: 

446 bitmask += np.uint64(2**bit['bit']) 

447 

448 return bitmask 

449 

450 

451def getSignificance(catalog): 

452 """Return the significance value of the first peak in each source 

453 footprint, or NaN for peaks without a significance field. 

454 

455 Parameters 

456 ---------- 

457 catalog : `lsst.afw.table.SourceCatalog` 

458 Catalog to process. 

459 

460 Returns 

461 ------- 

462 significance : `np.ndarray`, (N,) 

463 Signficance of the first peak in each source footprint. 

464 """ 

465 result = np.full(len(catalog), np.nan) 

466 for i, record in enumerate(catalog): 

467 peaks = record.getFootprint().peaks 

468 if "significance" in peaks.schema: 

469 result[i] = peaks[0]["significance"] 

470 return result