262 input_handle_dict = butlerQC.get(inputRefs)
264 band = butlerQC.quantum.dataId[
'band']
265 visit = butlerQC.quantum.dataId[
'visit']
267 src_dict_temp = {handle.dataId[
'detector']: handle
268 for handle
in input_handle_dict[
'srcs']}
269 calexp_dict_temp = {handle.dataId[
'detector']: handle
270 for handle
in input_handle_dict[
'calexps']}
271 isolated_star_cat_dict_temp = {handle.dataId[
'tract']: handle
272 for handle
in input_handle_dict[
'isolated_star_cats']}
273 isolated_star_source_dict_temp = {handle.dataId[
'tract']: handle
274 for handle
in input_handle_dict[
'isolated_star_sources']}
277 src_dict = {detector: src_dict_temp[detector]
for
278 detector
in sorted(src_dict_temp.keys())}
279 calexp_dict = {detector: calexp_dict_temp[detector]
for
280 detector
in sorted(calexp_dict_temp.keys())}
281 isolated_star_cat_dict = {tract: isolated_star_cat_dict_temp[tract]
for
282 tract
in sorted(isolated_star_cat_dict_temp.keys())}
283 isolated_star_source_dict = {tract: isolated_star_source_dict_temp[tract]
for
284 tract
in sorted(isolated_star_source_dict_temp.keys())}
286 struct = self.
run(visit,
288 isolated_star_cat_dict,
289 isolated_star_source_dict,
293 butlerQC.put(struct.psf_ap_corr_cat,
294 outputRefs.finalized_psf_ap_corr_cat)
295 butlerQC.put(pd.DataFrame(struct.output_table),
296 outputRefs.finalized_src_table)
298 def run(self, visit, band, isolated_star_cat_dict, isolated_star_source_dict, src_dict, calexp_dict):
300 Run the FinalizeCharacterizationTask.
305 Visit number. Used in the output catalogs.
307 Band name. Used to select reserved stars.
308 isolated_star_cat_dict : `dict`
309 Per-tract dict of isolated star catalog handles.
310 isolated_star_source_dict : `dict`
311 Per-tract dict of isolated star source catalog handles.
313 Per-detector dict of src catalog handles.
315 Per-detector dict of calibrated exposure handles.
319 struct : `lsst.pipe.base.struct`
320 Struct with outputs for persistence.
325 Raised if the selector returns no good sources.
331 isolated_star_cat_dict,
332 isolated_star_source_dict
335 exposure_cat_schema = afwTable.ExposureTable.makeMinimalSchema()
336 exposure_cat_schema.addField(
'visit', type=
'L', doc=
'Visit number')
338 metadata = dafBase.PropertyList()
339 metadata.add(
"COMMENT",
"Catalog id is detector id, sorted.")
340 metadata.add(
"COMMENT",
"Only detectors with data have entries.")
342 psf_ap_corr_cat = afwTable.ExposureCatalog(exposure_cat_schema)
343 psf_ap_corr_cat.setMetadata(metadata)
345 measured_src_tables = []
346 measured_src_table =
None
348 for detector
in src_dict:
349 src = src_dict[detector].get()
350 exposure = calexp_dict[detector].get()
357 isolated_source_table
361 if measured_src
is not None:
362 record = psf_ap_corr_cat.addNew()
363 record[
'id'] = int(detector)
364 record[
'visit'] = visit
367 if ap_corr_map
is not None:
368 record.setApCorrMap(ap_corr_map)
370 measured_src[
'visit'][:] = visit
371 measured_src[
'detector'][:] = detector
373 measured_src_tables.append(measured_src.asAstropy().as_array())
375 if len(measured_src_tables) > 0:
376 measured_src_table = np.concatenate(measured_src_tables)
378 if measured_src_table
is None:
379 raise pipeBase.NoWorkFound(f
'No good sources found for any detectors in visit {visit}')
381 return pipeBase.Struct(psf_ap_corr_cat=psf_ap_corr_cat,
382 output_table=measured_src_table)
385 """Make the schema mapper from the input schema to the output schema.
389 input_schema : `lsst.afw.table.Schema`
394 mapper : `lsst.afw.table.SchemaMapper`
396 output_schema : `lsst.afw.table.Schema`
397 Output schema (with alias map)
399 mapper = afwTable.SchemaMapper(input_schema)
400 mapper.addMinimalSchema(afwTable.SourceTable.makeMinimalSchema())
401 mapper.addMapping(input_schema[
'slot_Centroid_x'].asKey())
402 mapper.addMapping(input_schema[
'slot_Centroid_y'].asKey())
405 aper_fields = input_schema.extract(
'base_CircularApertureFlux_*')
406 for field, item
in aper_fields.items():
407 mapper.addMapping(item.key)
410 apflux_fields = input_schema.extract(
'slot_ApFlux_*')
411 for field, item
in apflux_fields.items():
412 mapper.addMapping(item.key)
414 calibflux_fields = input_schema.extract(
'slot_CalibFlux_*')
415 for field, item
in calibflux_fields.items():
416 mapper.addMapping(item.key)
419 input_schema[self.config.source_selector.active.signalToNoise.fluxField].asKey(),
420 'calib_psf_selection_flux')
422 input_schema[self.config.source_selector.active.signalToNoise.errField].asKey(),
423 'calib_psf_selection_flux_err')
425 output_schema = mapper.getOutputSchema()
427 output_schema.addField(
428 'calib_psf_candidate',
430 doc=(
'set if the source was a candidate for PSF determination, '
431 'as determined from FinalizeCharacterizationTask.'),
433 output_schema.addField(
434 'calib_psf_reserved',
436 doc=(
'set if source was reserved from PSF determination by '
437 'FinalizeCharacterizationTask.'),
439 output_schema.addField(
442 doc=(
'set if source was used in the PSF determination by '
443 'FinalizeCharacterizationTask.'),
445 output_schema.addField(
448 doc=
'Visit number for the sources.',
450 output_schema.addField(
453 doc=
'Detector number for the sources.',
456 alias_map = input_schema.getAliasMap()
457 alias_map_output = afwTable.AliasMap()
458 alias_map_output.set(
'slot_Centroid', alias_map.get(
'slot_Centroid'))
459 alias_map_output.set(
'slot_ApFlux', alias_map.get(
'slot_ApFlux'))
460 alias_map_output.set(
'slot_CalibFlux', alias_map.get(
'slot_CalibFlux'))
462 output_schema.setAliasMap(alias_map_output)
464 return mapper, output_schema
492 Concatenate isolated star catalogs and make reserve selection.
497 Band name. Used to select reserved stars.
498 isolated_star_cat_dict : `dict`
499 Per-tract dict of isolated star catalog handles.
500 isolated_star_source_dict : `dict`
501 Per-tract dict of isolated star source catalog handles.
505 isolated_table : `np.ndarray` (N,)
506 Table of isolated stars, with indexes to isolated sources.
507 isolated_source_table : `np.ndarray` (M,)
508 Table of isolated sources, with indexes to isolated stars.
511 isolated_sources = []
512 merge_cat_counter = 0
513 merge_source_counter = 0
515 for tract
in isolated_star_cat_dict:
516 df_cat = isolated_star_cat_dict[tract].get()
517 table_cat = df_cat.to_records()
519 df_source = isolated_star_source_dict[tract].get(
520 parameters={
'columns': [self.config.id_column,
523 table_source = df_source.to_records()
526 (use_band,) = (table_cat[f
'nsource_{band}'] > 0).nonzero()
528 if len(use_band) == 0:
530 self.log.info(
"No sources found in %s band in tract %d.", band, tract)
535 obj_index = table_source[
'obj_index'][:]
536 a, b = esutil.numpy_util.match(use_band, obj_index)
539 table_source[
'obj_index'][b] = a
540 _, index_new = np.unique(a, return_index=
True)
541 table_cat[f
'source_cat_index_{band}'][use_band] = index_new
552 table_source = table_source[b]
553 table_cat = table_cat[use_band]
556 table_cat = np.lib.recfunctions.append_fields(
559 np.zeros(table_cat.size, dtype=bool),
562 table_source = np.lib.recfunctions.append_fields(
565 np.zeros(table_source.size, dtype=bool),
570 table_cat[
'reserved'][:] = self.reserve_selection.run(
572 extra=f
'{band}_{tract}',
574 table_source[
'reserved'][:] = table_cat[
'reserved'][table_source[
'obj_index']]
577 table_cat[f
'source_cat_index_{band}'] += merge_source_counter
578 table_source[
'obj_index'] += merge_cat_counter
580 isolated_tables.append(table_cat)
581 isolated_sources.append(table_source)
583 merge_cat_counter += len(table_cat)
584 merge_source_counter += len(table_source)
586 isolated_table = np.concatenate(isolated_tables)
587 isolated_source_table = np.concatenate(isolated_sources)
589 return isolated_table, isolated_source_table
592 """Compute psf model and aperture correction map for a single exposure.
597 Visit number (for logging).
599 Detector number (for logging).
600 exposure : `lsst.afw.image.ExposureF`
601 src : `lsst.afw.table.SourceCatalog`
602 isolated_source_table : `np.ndarray`
606 psf : `lsst.meas.algorithms.ImagePsf`
608 ap_corr_map : `lsst.afw.image.ApCorrMap`
609 Aperture correction map.
610 measured_src : `lsst.afw.table.SourceCatalog`
611 Updated source catalog with measurements, flags and aperture corrections.
614 good_src = self.source_selector.selectSources(src)
615 if sum(good_src.selected) == 0:
616 self.log.warning(
'No good sources remain after cuts for visit %d, detector %d',
618 return None,
None,
None
627 selected_src = afwTable.SourceCatalog(selection_schema)
628 selected_src.reserve(good_src.selected.sum())
629 selected_src.extend(src[good_src.selected], mapper=selection_mapper)
633 selected_src[
'calib_psf_candidate'] = np.zeros(len(selected_src), dtype=bool)
634 selected_src[
'calib_psf_used'] = np.zeros(len(selected_src), dtype=bool)
635 selected_src[
'calib_psf_reserved'] = np.zeros(len(selected_src), dtype=bool)
638 matched_src, matched_iso = esutil.numpy_util.match(
640 isolated_source_table[self.config.id_column]
643 matched_arr = np.zeros(len(selected_src), dtype=bool)
644 matched_arr[matched_src] =
True
645 selected_src[
'calib_psf_candidate'] = matched_arr
647 reserved_arr = np.zeros(len(selected_src), dtype=bool)
648 reserved_arr[matched_src] = isolated_source_table[
'reserved'][matched_iso]
649 selected_src[
'calib_psf_reserved'] = reserved_arr
651 selected_src = selected_src[selected_src[
'calib_psf_candidate']].copy(deep=
True)
654 measured_src = afwTable.SourceCatalog(self.
schema)
655 measured_src.reserve(len(selected_src))
659 measured_src[
'calib_psf_candidate'] = selected_src[
'calib_psf_candidate']
660 measured_src[
'calib_psf_reserved'] = selected_src[
'calib_psf_reserved']
664 psf_selection_result = self.make_psf_candidates.run(selected_src, exposure=exposure)
665 except Exception
as e:
666 self.log.warning(
'Failed to make psf candidates for visit %d, detector %d: %s',
668 return None,
None, measured_src
670 psf_cand_cat = psf_selection_result.goodStarCat
674 psf_determiner_list = [cand
for cand, use
675 in zip(psf_selection_result.psfCandidates,
676 ~psf_cand_cat[
'calib_psf_reserved'])
if use]
677 flag_key = psf_cand_cat.schema[
'calib_psf_used'].asKey()
679 psf, cell_set = self.psf_determiner.determinePsf(exposure,
683 except Exception
as e:
684 self.log.warning(
'Failed to determine psf for visit %d, detector %d: %s',
686 return None,
None, measured_src
693 matched_selected, matched_measured = esutil.numpy_util.match(
697 measured_used = np.zeros(len(measured_src), dtype=bool)
698 measured_used[matched_measured] = selected_src[
'calib_psf_used'][matched_selected]
699 measured_src[
'calib_psf_used'] = measured_used
703 self.measurement.run(measCat=measured_src, exposure=exposure)
704 except Exception
as e:
705 self.log.warning(
'Failed to make measurements for visit %d, detector %d: %s',
707 return psf,
None, measured_src
711 ap_corr_map = self.measure_ap_corr.run(exposure=exposure,
712 catalog=measured_src).apCorrMap
713 except Exception
as e:
714 self.log.warning(
'Failed to compute aperture corrections for visit %d, detector %d: %s',
716 return psf,
None, measured_src
718 self.apply_ap_corr.run(catalog=measured_src, apCorrMap=ap_corr_map)
720 return psf, ap_corr_map, measured_src