620 catalog_ref: pd.DataFrame,
621 catalog_target: pd.DataFrame,
622 catalog_match_ref: pd.DataFrame,
623 catalog_match_target: pd.DataFrame,
624 wcs: afwGeom.SkyWcs =
None,
625 ) -> pipeBase.Struct:
626 """Load matched reference and target (measured) catalogs, measure summary statistics, and output
627 a combined matched catalog with columns from both inputs.
631 catalog_ref : `pandas.DataFrame`
632 A reference catalog to diff objects/sources from.
633 catalog_target : `pandas.DataFrame`
634 A target catalog to diff reference objects/sources to.
635 catalog_match_ref : `pandas.DataFrame`
636 A catalog with match indices of target sources and selection flags
637 for each reference source.
638 catalog_match_target : `pandas.DataFrame`
639 A catalog with selection flags for each target source.
640 wcs : `lsst.afw.image.SkyWcs`
641 A coordinate system to convert catalog positions to sky coordinates,
646 retStruct : `lsst.pipe.base.Struct`
647 A struct with output_ref and output_target attribute containing the
648 output matched catalogs.
651 config: DiffMatchedTractCatalogConfig = self.config
653 select_ref = catalog_match_ref[
'match_candidate'].values
656 select_target = (catalog_match_target[
'match_candidate'].values
657 if 'match_candidate' in catalog_match_target.columns
658 else np.ones(len(catalog_match_target), dtype=bool))
659 for column
in config.columns_target_select_true:
660 select_target &= catalog_target[column].values
661 for column
in config.columns_target_select_false:
662 select_target &= ~catalog_target[column].values
664 ref, target = config.coord_format.format_catalogs(
665 catalog_ref=catalog_ref, catalog_target=catalog_target,
666 select_ref=
None, select_target=select_target, wcs=wcs, radec_to_xy_func=radec_to_xy,
667 return_converted_columns=config.coord_format.coords_ref_to_convert
is not None,
669 cat_ref = ref.catalog
670 cat_target = target.catalog
671 n_target = len(cat_target)
673 if config.include_unmatched:
674 for cat_add, cat_match
in ((cat_ref, catalog_match_ref), (cat_target, catalog_match_target)):
675 cat_add[
'match_candidate'] = cat_match[
'match_candidate'].values
677 match_row = catalog_match_ref[
'match_row'].values
678 matched_ref = match_row >= 0
679 matched_row = match_row[matched_ref]
680 matched_target = np.zeros(n_target, dtype=bool)
681 matched_target[matched_row] =
True
684 coord1_target_err, coord2_target_err = config.columns_target_coord_err
685 column_dist, column_dist_err =
'match_distance',
'match_distanceErr'
686 dist = np.full(n_target, np.nan)
688 dist[matched_row] = np.hypot(
689 target.coord1[matched_row] - ref.coord1[matched_ref],
690 target.coord2[matched_row] - ref.coord2[matched_ref],
692 dist_err = np.full(n_target, np.nan)
693 dist_err[matched_row] = np.hypot(cat_target.iloc[matched_row][coord1_target_err].values,
694 cat_target.iloc[matched_row][coord2_target_err].values)
695 cat_target[column_dist], cat_target[column_dist_err] = dist, dist_err
698 cat_left = cat_target.iloc[matched_row]
699 has_index_left = cat_left.index.name
is not None
700 cat_right = cat_ref[matched_ref].reset_index()
701 cat_right.columns = [f
'{config.column_matched_prefix_ref}{col}' for col
in cat_right.columns]
702 cat_matched = pd.concat(objs=(cat_left.reset_index(drop=
not has_index_left), cat_right), axis=1)
704 if config.include_unmatched:
708 cat_right = cat_ref[~matched_ref & select_ref].reset_index(drop=
False)
709 cat_right.columns = (f
'{config.column_matched_prefix_ref}{col}' for col
in cat_right.columns)
710 match_row_target = catalog_match_target[
'match_row'].values
711 cat_left = cat_target[~(match_row_target >= 0) & select_target].reset_index(
712 drop=
not has_index_left)
717 for cat_i
in (cat_left, cat_right):
718 for colname
in cat_i.columns:
719 column = cat_i[colname]
720 dtype = str(column.dtype)
722 cat_i[colname] = column.astype(
"boolean")
723 elif dtype.startswith(
"int"):
724 cat_i[colname] = column.astype(f
"Int{dtype[3:]}")
725 elif dtype.startswith(
"uint"):
726 cat_i[colname] = column.astype(f
"UInt{dtype[3:]}")
727 cat_unmatched = pd.concat(objs=(cat_left, cat_right))
729 for columns_convert_base, prefix
in (
730 (config.columns_ref_mag_to_nJy, config.column_matched_prefix_ref),
731 (config.columns_target_mag_to_nJy,
""),
733 if columns_convert_base:
735 f
"{prefix}{k}": f
"{prefix}{v}" for k, v
in columns_convert_base.items()
736 }
if prefix
else columns_convert_base
737 for cat_convert
in (cat_matched, cat_unmatched):
738 cat_convert.rename(columns=columns_convert, inplace=
True)
739 for column_flux
in columns_convert.values():
740 cat_convert[column_flux] = u.ABmag.to(u.nJy, cat_convert[column_flux])
745 column_dummy =
'dummy'
746 cat_ref[column_dummy] = np.zeros_like(ref.coord1)
750 extended_ref = cat_ref[config.column_ref_extended] == (
not config.column_ref_extended_inverted)
752 extended_target = cat_target[config.column_target_extended].values >= config.extendedness_cut
755 suffixes = {MeasurementType.DIFF:
'diff', MeasurementType.CHI:
'chi'}
757 suffixes_flux = {MeasurementType.CHI: suffixes[MeasurementType.CHI]}
759 suffixes_mag = {MeasurementType.DIFF: suffixes[MeasurementType.DIFF]}
760 stats = {stat.name_short(): stat()
for stat
in (Median, SigmaIQR, SigmaMAD)}
762 for percentile
in self.config.percentiles:
763 stat =
Percentile(percentile=float(Decimal(percentile)))
764 stats[stat.name_short()] = stat
768 bands_columns=config.columns_flux,
770 suffixes_flux=suffixes_flux,
771 suffixes_mag=suffixes_mag,
774 column_dist=column_dist,
778 n_bins = config.mag_num_bins
779 data = np.zeros((n_bins,), dtype=[(key, value)
for key, value
in columns.items()])
780 data[
'bin'] = np.arange(n_bins)
783 bins_mag = np.linspace(start=config.mag_brightest_ref, stop=config.mag_faintest_ref,
785 data[
'mag_min'] = bins_mag[:-1]
786 data[
'mag_max'] = bins_mag[1:]
787 bins_mag = tuple((bins_mag[idx], bins_mag[idx + 1])
for idx
in range(n_bins))
790 column_mag_temp =
'mag_temp'
791 column_color_temp =
'color_temp'
792 column_color_err_temp =
'colorErr_temp'
793 flux_err_frac_prev = [
None]*n_models
794 mag_prev = [
None]*n_models
797 target.column_coord1: (
798 ref.column_coord1, target.column_coord1, coord1_target_err,
False,
800 target.column_coord2: (
801 ref.column_coord2, target.column_coord2, coord2_target_err,
False,
803 column_dist: (column_dummy, column_dist, column_dist_err,
False),
808 band_fluxes = [(band, config_flux)
for (band, config_flux)
in config.columns_flux.items()]
809 n_bands = len(band_fluxes)
811 band_fluxes.append(band_fluxes[0])
812 flux_err_frac_first =
None
817 for idx_band, (band, config_flux)
in enumerate(band_fluxes):
818 if idx_band == n_bands:
820 mag_ref = mag_ref_first
821 flux_err_frac = flux_err_frac_first
822 mag_model = mag_first
824 mag_ref = -2.5*np.log10(cat_ref[config_flux.column_ref_flux]) + config.mag_zeropoint_ref
825 flux_err_frac = [
None]*n_models
826 mag_model = [
None]*n_models
829 cat_ref[column_color_temp] = cat_ref[column_mag_temp] - mag_ref
831 cat_ref[column_mag_temp] = mag_ref
833 select_ref_bins = [select_ref & (mag_ref > mag_lo) & (mag_ref < mag_hi)
834 for idx_bin, (mag_lo, mag_hi)
in enumerate(bins_mag)]
837 for idx_model
in range(n_models):
838 column_target_flux = config_flux.columns_target_flux[idx_model]
839 column_target_flux_err = config_flux.columns_target_flux_err[idx_model]
841 flux_target = cat_target[column_target_flux]
842 mag_target = -2.5*np.log10(flux_target) + config.mag_zeropoint_target
843 if config.mag_ceiling_target
is not None:
844 mag_target[mag_target > config.mag_ceiling_target] = config.mag_ceiling_target
845 mag_model[idx_model] = mag_target
848 flux_err_frac[idx_model] = cat_target[column_target_flux_err]/flux_target
853 column_mag_temp_model = f
'{column_mag_temp}{idx_model}'
854 cat_target[column_mag_temp_model] = mag_target
856 columns_target[f
'flux_{column_target_flux}'] = (
857 config_flux.column_ref_flux,
859 column_target_flux_err,
863 columns_target[f
'mag_{column_target_flux}'] = (
864 column_mag_temp, column_mag_temp_model,
None,
False,
869 skip_color = (idx_band == n_bands)
and (n_bands <= 2)
871 column_color_temp_model = f
'{column_color_temp}{idx_model}'
872 column_color_err_temp_model = f
'{column_color_err_temp}{idx_model}'
875 cat_target[column_color_temp_model] = mag_prev[idx_model] - mag_model[idx_model]
878 cat_target[column_color_err_temp_model] = 2.5/np.log(10)*np.hypot(
879 flux_err_frac[idx_model], flux_err_frac_prev[idx_model])
880 columns_target[f
'color_{band_prev}_m_{band}_{column_target_flux}'] = (
882 column_color_temp_model,
883 column_color_err_temp_model,
887 for idx_bin, (mag_lo, mag_hi)
in enumerate(bins_mag):
891 select_ref_bin = select_ref_bins[idx_bin]
892 select_target_bin = select_target & (mag_target > mag_lo) & (mag_target < mag_hi)
894 for sourcetype
in SourceType:
895 sourcetype_info = sourcetype.value
896 is_extended = sourcetype_info.is_extended
898 select_ref_sub = select_ref_bin.copy()
899 select_target_sub = select_target_bin.copy()
900 if is_extended
is not None:
901 is_extended_ref = (extended_ref == is_extended)
902 select_ref_sub &= is_extended_ref
904 n_ref_sub = np.count_nonzero(select_ref_sub)
906 MatchType.ALL.value)] = n_ref_sub
907 select_target_sub &= (extended_target == is_extended)
908 n_target_sub = np.count_nonzero(select_target_sub)
910 MatchType.ALL.value)] = n_target_sub
913 match_row_bin = match_row.copy()
914 match_row_bin[~select_ref_sub] = -1
915 match_good = match_row_bin >= 0
917 n_match = np.count_nonzero(match_good)
922 rows_matched = match_row_bin[match_good]
923 subset_target = cat_target.iloc[rows_matched]
924 if (is_extended
is not None)
and (idx_model == 0):
925 right_type = extended_target[rows_matched] == is_extended
926 n_total = len(right_type)
927 n_right = np.count_nonzero(right_type)
929 MatchType.MATCH_RIGHT.value)] = n_right
932 sourcetype_info.label,
934 MatchType.MATCH_WRONG.value,
935 )] = n_total - n_right
938 for column, (column_ref, column_target, column_err_target, skip_diff) \
939 in columns_target.items():
940 values_ref = cat_ref[column_ref][match_good].values
942 subset_target[column_err_target].values
943 if column_err_target
is not None
948 subset_target[column_target].values,
953 prefix=f
'{band}_{sourcetype_info.label}_{column}',
961 select_target_sub &= matched_target
963 if is_extended
is not None and (np.count_nonzero(select_target_sub) > 0):
964 n_total = np.count_nonzero(select_target_sub)
965 right_type = np.zeros(n_target, dtype=bool)
966 right_type[match_row[matched_ref & is_extended_ref]] =
True
967 right_type &= select_target_sub
968 n_right = np.count_nonzero(right_type)
970 MatchType.MATCH_RIGHT.value)] = n_right
972 MatchType.MATCH_WRONG.value)] = n_total - n_right
975 for prefix
in (
'flux',
'mag'):
976 del columns_target[f
'{prefix}_{column_target_flux}']
978 del columns_target[f
'color_{band_prev}_m_{band}_{column_target_flux}']
981 flux_err_frac_prev = flux_err_frac
985 flux_err_frac_first = flux_err_frac
986 mag_first = mag_model
987 mag_ref_first = mag_ref
989 if config.include_unmatched:
990 cat_matched = pd.concat((cat_matched, cat_unmatched))
992 retStruct = pipeBase.Struct(cat_matched=cat_matched, diff_matched=pd.DataFrame(data))