432 catalog_ref: pd.DataFrame,
433 catalog_target: pd.DataFrame,
434 select_ref: np.array =
None,
435 select_target: np.array =
None,
436 logger: logging.Logger =
None,
437 logging_n_rows: int =
None,
444 catalog_ref : `pandas.DataFrame`
445 A reference catalog to match in order of a given column (i.e. greedily).
446 catalog_target : `pandas.DataFrame`
447 A target catalog for matching sources from `catalog_ref`. Must contain measurements with errors.
448 select_ref : `numpy.array`
449 A boolean array of the same length as `catalog_ref` selecting the sources that can be matched.
450 select_target : `numpy.array`
451 A boolean array of the same length as `catalog_target` selecting the sources that can be matched.
452 logger : `logging.Logger`
453 A Logger for logging.
454 logging_n_rows : `int`
455 The number of sources to match before printing a log message.
457 Additional keyword arguments to pass to `format_catalogs`.
461 catalog_out_ref : `pandas.DataFrame`
462 A catalog of identical length to `catalog_ref`, containing match information for rows selected by
463 `select_ref` (including the matching row index in `catalog_target`).
464 catalog_out_target : `pandas.DataFrame`
465 A catalog of identical length to `catalog_target`, containing the indices of matching rows in
467 exceptions : `dict` [`int`, `Exception`]
468 A dictionary keyed by `catalog_target` row number of the first exception caught when matching.
471 logger = logger_default
483 ref, target = config.coord_format.format_catalogs(
484 catalog_ref=catalog_ref, catalog_target=catalog_target,
485 select_ref=select_ref, select_target=select_target,
495 catalog_ref.loc[ref.extras.select, config.column_ref_order]
496 if config.column_ref_order
is not None else
497 np.nansum(catalog_ref.loc[ref.extras.select, config.columns_ref_flux], axis=1)
499 order = np.argsort(column_order
if config.order_ascending
else -column_order)
501 n_ref_select = len(ref.extras.indices)
503 match_dist_max = config.match_dist_max
504 coords_spherical = config.coord_format.coords_spherical
506 match_dist_max = np.radians(match_dist_max / 3600.)
509 func_convert = _radec_to_xyz
if coords_spherical
else np.vstack
510 vec_ref, vec_target = (
511 func_convert(cat.coord1[cat.extras.select], cat.coord2[cat.extras.select])
512 for cat
in (ref, target)
516 logger.info(
'Generating cKDTree with match_n_max=%d', config.match_n_max)
517 tree_obj = cKDTree(vec_target)
519 scores, idxs_target_select = tree_obj.query(
521 distance_upper_bound=match_dist_max,
522 k=config.match_n_max,
525 n_target_select = len(target.extras.indices)
526 n_matches = np.sum(idxs_target_select != n_target_select, axis=1)
527 n_matched_max = np.sum(n_matches == config.match_n_max)
528 if n_matched_max > 0:
530 '%d/%d (%.2f%%) selected true objects have n_matches=n_match_max(%d)',
531 n_matched_max, n_ref_select, 100.*n_matched_max/n_ref_select, config.match_n_max
535 target_row_match = np.full(target.extras.n, np.nan, dtype=np.int64)
536 ref_candidate_match = np.zeros(ref.extras.n, dtype=bool)
537 ref_row_match = np.full(ref.extras.n, np.nan, dtype=np.int64)
538 ref_match_count = np.zeros(ref.extras.n, dtype=np.int32)
539 ref_match_meas_finite = np.zeros(ref.extras.n, dtype=np.int32)
540 ref_chisq = np.full(ref.extras.n, np.nan, dtype=float)
543 idx_orig_ref, idx_orig_target = (np.argwhere(cat.extras.select)
for cat
in (ref, target))
546 columns_convert = config.coord_format.coords_ref_to_convert
547 if columns_convert
is None:
549 data_ref = ref.catalog[
550 [columns_convert.get(column, column)
for column
in config.columns_ref_meas]
551 ].iloc[ref.extras.indices[order]]
552 data_target = target.catalog[config.columns_target_meas][target.extras.select]
553 errors_target = target.catalog[config.columns_target_err][target.extras.select]
557 matched_target = {n_target_select, }
559 t_begin = time.process_time()
561 logger.info(
'Matching n_indices=%d/%d', len(order), len(ref.catalog))
562 for index_n, index_row_select
in enumerate(order):
563 index_row = idx_orig_ref[index_row_select]
564 ref_candidate_match[index_row] =
True
565 found = idxs_target_select[index_row_select, :]
570 found = [x
for x
in found
if x
not in matched_target]
575 (data_target.iloc[found].values - data_ref.iloc[index_n].values)
576 / errors_target.iloc[found].values
578 finite = np.isfinite(chi)
579 n_finite = np.sum(finite, axis=1)
581 chisq_good = n_finite >= config.match_n_finite_min
582 if np.any(chisq_good):
584 chisq_sum = np.zeros(n_found, dtype=float)
585 chisq_sum[chisq_good] = np.nansum(chi[chisq_good, :] ** 2, axis=1)
586 idx_chisq_min = np.nanargmin(chisq_sum / n_finite)
587 ref_match_meas_finite[index_row] = n_finite[idx_chisq_min]
588 ref_match_count[index_row] = len(chisq_good)
589 ref_chisq[index_row] = chisq_sum[idx_chisq_min]
590 idx_match_select = found[idx_chisq_min]
591 row_target = target.extras.indices[idx_match_select]
592 ref_row_match[index_row] = row_target
594 target_row_match[row_target] = index_row
595 matched_target.add(idx_match_select)
596 except Exception
as error:
599 exceptions[index_row] = error
601 if logging_n_rows
and ((index_n + 1) % logging_n_rows == 0):
602 t_elapsed = time.process_time() - t_begin
604 'Processed %d/%d in %.2fs at sort value=%.3f',
605 index_n + 1, n_ref_select, t_elapsed, column_order[order[index_n]],
609 'match_candidate': ref_candidate_match,
610 'match_row': ref_row_match,
611 'match_count': ref_match_count,
612 'match_chisq': ref_chisq,
613 'match_n_chisq_finite': ref_match_meas_finite,
616 'match_candidate': target.extras.select
if target.extras.select
is not None else (
617 np.ones(target.extras.n, dtype=bool)),
618 'match_row': target_row_match,
621 for (columns, out_original, out_matched, in_original, in_matched, matches)
in (
639 matched = matches >= 0
640 idx_matched = matches[matched]
642 for column
in columns:
643 values = in_original.catalog[column]
644 out_original[column] = values
645 dtype = in_original.catalog[column].dtype
649 types = list(
set((type(x)
for x
in values)))
651 raise RuntimeError(f
'Column {column} dtype={dtype} has multiple types={types}')
658 dtype = f
'<U{max(len(x) for x in values)}'
660 column_match = np.full(in_matched.extras.n, value_fill, dtype=dtype)
661 column_match[matched] = in_original.catalog[column][idx_matched]
662 out_matched[f
'match_{column}'] = column_match
664 catalog_out_ref = pd.DataFrame(data_ref)
665 catalog_out_target = pd.DataFrame(data_target)
667 return catalog_out_ref, catalog_out_target, exceptions