465 catalog_ref: astropy.table.Table,
466 catalog_target: astropy.table.Table,
467 select_ref: np.array =
None,
468 select_target: np.array =
None,
469 logger: logging.Logger =
None,
470 logging_n_rows: int =
None,
477 catalog_ref : `astropy.table.Table`
478 A reference catalog to match in order of a given column (i.e. greedily).
479 catalog_target : `astropy.table.Table`
480 A target catalog for matching sources from `catalog_ref`. Must contain measurements with errors.
481 select_ref : `numpy.array`
482 A boolean array of the same length as `catalog_ref` selecting the sources that can be matched.
483 select_target : `numpy.array`
484 A boolean array of the same length as `catalog_target` selecting the sources that can be matched.
485 logger : `logging.Logger`
486 A Logger for logging.
487 logging_n_rows : `int`
488 The number of sources to match before printing a log message.
490 Additional keyword arguments to pass to `format_catalogs`.
494 catalog_out_ref : `astropy.table.Table`
495 A catalog of identical length to `catalog_ref`, containing match information for rows selected by
496 `select_ref` (including the matching row index in `catalog_target`).
497 catalog_out_target : `astropy.table.Table`
498 A catalog of identical length to `catalog_target`, containing the indices of matching rows in
500 exceptions : `dict` [`int`, `Exception`]
501 A dictionary keyed by `catalog_target` row number of the first exception caught when matching.
504 logger = logger_default
506 t_init = time.process_time()
517 with warnings.catch_warnings():
519 warnings.filterwarnings(action=
"ignore", category=FutureWarning)
520 ref, target = config.coord_format.format_catalogs(
521 catalog_ref=catalog_ref, catalog_target=catalog_target,
522 select_ref=select_ref, select_target=select_target,
530 catalog_ref[config.column_ref_order][ref.extras.select]
531 if config.column_ref_order
is not None else
532 np.nansum([catalog_ref[col][ref.extras.select]
for col
in config.columns_ref_flux], axis=0)
534 order = np.argsort(column_order
if config.order_ascending
else -column_order)
536 n_ref_select = len(ref.extras.indices)
538 coords_spherical = config.coord_format.coords_spherical
539 coords_ref, coords_target = (
540 (cat.coord1[cat.extras.select], cat.coord2[cat.extras.select])
541 for cat
in (ref, target)
545 logger.info(
'Generating cKDTree with match_n_max=%d', config.match_n_max)
548 match_dist_max = config.match_dist_max/3600.
549 with Matcher(coords_target[0], coords_target[1])
as matcher:
550 idxs_target_select = matcher.query_knn(
551 coords_ref[0], coords_ref[1],
552 distance_upper_bound=match_dist_max,
553 k=config.match_n_max,
558 match_dist_max = np.radians(config.match_dist_max/3600.)
560 func_convert = _radec_to_xyz
if coords_spherical
else np.vstack
561 vec_ref, vec_target = (
562 func_convert(coords[0], coords[1])
563 for coords
in (coords_ref, coords_target)
565 tree_obj = cKDTree(vec_target)
566 _, idxs_target_select = tree_obj.query(
568 distance_upper_bound=match_dist_max,
569 k=config.match_n_max,
572 n_target_select = len(target.extras.indices)
573 n_matches = np.sum(idxs_target_select != n_target_select, axis=1)
574 n_matched_max = np.sum(n_matches == config.match_n_max)
575 if n_matched_max > 0:
577 '%d/%d (%.2f%%) selected true objects have n_matches=n_match_max(%d)',
578 n_matched_max, n_ref_select, 100.*n_matched_max/n_ref_select, config.match_n_max
582 target_row_match = np.full(target.extras.n, np.iinfo(np.int64).min, dtype=np.int64)
583 ref_candidate_match = np.zeros(ref.extras.n, dtype=bool)
584 ref_row_match = np.full(ref.extras.n, np.iinfo(np.int64).min, dtype=np.int64)
585 ref_match_count = np.zeros(ref.extras.n, dtype=np.int32)
586 ref_match_meas_finite = np.zeros(ref.extras.n, dtype=np.int32)
587 ref_chisq = np.full(ref.extras.n, np.nan, dtype=float)
590 idx_orig_ref, idx_orig_target = (np.argwhere(cat.extras.select)[:, 0]
for cat
in (ref, target))
593 columns_convert = config.coord_format.coords_ref_to_convert
594 if columns_convert
is None:
596 data_ref = np.array([
597 ref.catalog[columns_convert.get(column, column)][ref.extras.indices[order]]
598 for column
in config.columns_ref_meas
600 data_target = np.array([
601 target.catalog[col][target.extras.select]
for col
in config.columns_target_meas
603 errors_target = np.array([
604 target.catalog[col][target.extras.select]
for col
in config.columns_target_err
609 matched_target = {n_target_select, }
610 index_ref = idx_orig_ref[order]
612 ref_candidate_match[index_ref] =
True
615 t_begin = time.process_time()
618 matched_ref = idxs_target_select[order, 0] != n_target_select
619 order = order[matched_ref]
620 idx_first = idxs_target_select[order, 0]
621 data_ref_matched = data_ref[:, matched_ref]
622 chi_0 = (data_target[:, idx_first] - data_ref_matched)/errors_target[:, idx_first]
623 chi_finite_0 = np.isfinite(chi_0)
624 n_finite_0 = np.sum(chi_finite_0, axis=0)
625 chi_0[~chi_finite_0] = 0
626 chisq_sum_0 = np.sum(chi_0*chi_0, axis=0)
627 n_meas = len(config.columns_ref_meas)
630 logger.info(
'Disambiguating %d/%d matches/targets', len(order), len(ref.catalog))
631 for index_n, index_row_select
in enumerate(order):
632 index_row = idx_orig_ref[index_row_select]
633 found = idxs_target_select[index_row_select, :]
635 if (found[1] == n_target_select)
and (found[0]
not in matched_target):
636 n_finite = n_finite_0[index_n]
637 if not (n_finite >= config.match_n_finite_min):
641 chisq_sum = chisq_sum_0[index_n]
647 found = [x
for x
in found
if x
not in matched_target]
653 data_target[:, found] - data_ref_matched[:, index_n].reshape((n_meas, 1))
654 )/errors_target[:, found]
655 finite = np.isfinite(chi)
656 n_finite = np.sum(finite, axis=0)
658 chisq_good = n_finite >= config.match_n_finite_min
659 if not any(chisq_good):
662 chisq_sum = np.zeros(n_found, dtype=float)
663 chisq_sum[chisq_good] = np.nansum(chi[:, chisq_good] ** 2, axis=0)
664 idx_chisq_min = np.nanargmin(chisq_sum / n_finite)
665 n_finite = n_finite[idx_chisq_min]
666 n_matched = len(chisq_good)
667 chisq_sum = chisq_sum[idx_chisq_min]
669 except Exception
as error:
672 exceptions[index_row] = error
673 ref_match_meas_finite[index_row] = n_finite
674 ref_match_count[index_row] = n_matched
675 ref_chisq[index_row] = chisq_sum
676 idx_match_select = found[idx_chisq_min]
677 row_target = target.extras.indices[idx_match_select]
678 ref_row_match[index_row] = row_target
680 target_row_match[row_target] = index_row
681 matched_target.add(idx_match_select)
683 if logging_n_rows
and ((index_n + 1) % logging_n_rows == 0):
684 t_elapsed = time.process_time() - t_begin
686 'Processed %d/%d in %.2fs at sort value=%.3f',
687 index_n + 1, n_ref_select, t_elapsed, column_order[order[index_n]],
691 'match_candidate': ref_candidate_match,
692 'match_row': ref_row_match,
693 'match_count': ref_match_count,
694 'match_chi2': ref_chisq,
695 'match_n_chi2_finite': ref_match_meas_finite,
698 'match_candidate': target.extras.select
if target.extras.select
is not None else (
699 np.ones(target.extras.n, dtype=bool)),
700 'match_row': target_row_match,
703 for (columns, out_original, out_matched, in_original, in_matched, matches, name_cat)
in (
705 self.
config.columns_ref_copy,
714 self.
config.columns_target_copy,
723 matched = matches >= 0
724 idx_matched = matches[matched]
725 logger.info(
'Matched %d/%d %s sources', np.sum(matched), len(matched), name_cat)
727 for column
in columns:
728 values = in_original.catalog[column]
729 out_original[column] = values
730 dtype = in_original.catalog[column].dtype
734 types = list(set((type(x)
for x
in values)))
736 raise RuntimeError(f
'Column {column} dtype={dtype} has multiple types={types}')
743 dtype = f
'<U{max(len(x) for x in values)}'
745 column_match = np.full(in_matched.extras.n, value_fill, dtype=dtype)
746 column_match[matched] = in_original.catalog[column][idx_matched]
747 out_matched[f
'match_{column}'] = column_match
750 'Completed match disambiguating in %.2fs (total %.2fs) with %d disambiguated',
751 time.process_time() - t_begin,
752 time.process_time() - t_init,
756 catalog_out_ref = astropy.table.Table(data_ref)
757 for column, description
in {
758 'match_candidate':
'Whether the object was selected as a candidate for matching',
759 'match_row':
'The index of the best matched row in the target table, if any',
760 'match_count':
'The number of candidate matching target objects, i.e. those within the match'
761 ' distance but excluding objects already matched to a ref object',
762 'match_chi2':
'The sum of all finite reduced chi-squared values over all match columns',
763 'match_n_chi2_finite':
'The number of match columns with finite chi-squared',
765 catalog_out_ref[column].description = description
766 catalog_out_target = astropy.table.Table(data_target)
768 return catalog_out_ref, catalog_out_target, exceptions