Source code for lsdb.core.crossmatch.abstract_crossmatch_algorithm

from __future__ import annotations

from abc import ABC
from typing import TYPE_CHECKING, cast

import nested_pandas as npd
import numpy as np
import numpy.typing as npt
import pandas as pd
from hats.pixel_math.spatial_index import SPATIAL_INDEX_COLUMN, compute_spatial_index

from lsdb.core.crossmatch.crossmatch_args import CrossmatchArgs
from lsdb.operations.functions.merge_catalog_functions import apply_suffixes

if TYPE_CHECKING:
    from lsdb.catalog import Catalog


def _na_series_for_dtype(dtype, length):
    """Return a Series with the right NA type for the given dtype and length.
    Used for building NA rows for unmatched entries in left-joins.
    All dtypes will be PyArrow based, even for catalogs imported using
    `lsdb.from_dataframe`.
    """
    # Can rely on Pandas to handle NA values correctly for all PyArrow dtypes
    return pd.Series([None] * length, dtype=dtype)


# pylint: disable=too-many-instance-attributes, too-many-arguments
[docs] class AbstractCrossmatchAlgorithm(ABC): """Abstract class used to write a crossmatch algorithm. To specify a custom algorithm, write a class that subclasses the `AbstractCrossmatchAlgorithm` class, and either overwrite the `crossmatch` or the `perform_crossmatch` function. The function should be able to perform a crossmatch on two pandas DataFrames from a partition from each catalog. It should return two 1d numpy arrays of equal lengths with the indices of the matching rows from the left and right dataframes, and a dataframe with any extra columns generated by the crossmatch algorithm, also with the same length. These columns are specified in {AbstractCrossmatchAlgorithm.extra_columns}, with their respective data types, by means of an empty pandas dataframe. As an example, the KdTreeCrossmatch algorithm outputs a "_dist_arcsec" column with the distance between data points. Its extra_columns attribute is specified as follows:: pd.DataFrame({"_dist_arcsec": pd.Series(dtype=np.dtype("float64"))}) The `crossmatch`/`perform_crossmatch` methods will receive an instance of `CrossmatchArgs` which includes the partitions and respective pixel information:: - left_df: npd.NestedFrame - right_df: npd.NestedFrame - left_order: int - left_pixel: int - right_order: int - right_pixel: int - left_catalog_info: hc.catalog.TableProperties - right_catalog_info: hc.catalog.TableProperties - right_margin_catalog_info: hc.catalog.TableProperties Include any algorithm-specific parameters in the initialization of your object. These parameters should be validated in `AbstractCrossmatchAlgorithm.validate`, by overwriting the method. """ extra_columns: pd.DataFrame | None = None """The metadata for the columns generated by the crossmatch algorithm""" def crossmatch( self, crossmatch_args: CrossmatchArgs, how: str, suffixes: tuple[str, str], suffix_method: str = "all_columns", ) -> npd.NestedFrame: """Perform a crossmatch. Parameters ---------- crossmatch_args : CrossmatchArgs The partitions and respective pixel information. how : str One of {'inner', 'left', 'outer'} suffixes : tuple[str,str] A pair of suffixes to be appended to the end of each column name, with the first appended to the left columns and the second to the right columns. suffix_method : str, default 'all_columns' The suffix method to use. Returns ------- npd.NestedFrame The dataframe containing the results of the crossmatch. """ right_empty = crossmatch_args.right_df is None or len(crossmatch_args.right_df) == 0 left_empty = crossmatch_args.left_df is None or len(crossmatch_args.left_df) == 0 if right_empty or (how == "outer" and left_empty): l_inds = np.array([], dtype=np.int64) r_inds = np.array([], dtype=np.int64) extra_cols = self.extra_columns.copy() if self.extra_columns is not None else pd.DataFrame() else: l_inds, r_inds, extra_cols = self.perform_crossmatch(crossmatch_args) if not len(l_inds) == len(r_inds) == len(extra_cols): raise ValueError( "Crossmatch algorithm must return left and right indices and extra columns with same length" ) left_df = crossmatch_args.left_df right_matched_mask = None if how == "outer" and crossmatch_args.left_native_len is not None: native_len = crossmatch_args.left_native_len visitor = l_inds >= native_len if visitor.any(): right_matched_mask = np.zeros(len(crossmatch_args.right_df), dtype=bool) right_matched_mask[r_inds] = True l_inds = l_inds[~visitor] r_inds = r_inds[~visitor] extra_cols = extra_cols[~visitor] left_df = left_df.iloc[:native_len] return self._create_crossmatch_df( left_df, crossmatch_args.right_df, l_inds, r_inds, extra_cols, how, suffixes, suffix_method, right_native_mask=crossmatch_args.right_native_mask, right_matched_mask=right_matched_mask, left_coordinates=( crossmatch_args.left_catalog_info.ra_column, crossmatch_args.left_catalog_info.dec_column, ), right_coordinates=( crossmatch_args.right_catalog_info.ra_column, crossmatch_args.right_catalog_info.dec_column, ), ) def crossmatch_nested( self, crossmatch_args: CrossmatchArgs, nested_column_name: str, how: str ) -> npd.NestedFrame: """Perform a crossmatch and store results in nested column. Parameters ---------- crossmatch_args : CrossmatchArgs The partitions and respective pixel information. nested_column_name : str The name of the column where the matches should be stored. how : str How to handle the crossmatch of the two catalogs. One of {'left', 'inner'}. Returns ------- npd.NestedFrame The dataframe containing the results of the crossmatch. """ l_inds, r_inds, extra_cols = self.perform_crossmatch(crossmatch_args) if not len(l_inds) == len(r_inds) == len(extra_cols): raise ValueError( "Crossmatch algorithm must return left and right indices and extra columns with same length" ) return self._create_nested_crossmatch_df( crossmatch_args.left_df, crossmatch_args.right_df, l_inds, r_inds, extra_cols, nested_column_name, how, ) def perform_crossmatch( self, crossmatch_args: CrossmatchArgs ) -> tuple[np.ndarray, np.ndarray, pd.DataFrame]: """Performs a crossmatch to get the indices of the matching rows and any extra columns Parameters ---------- crossmatch_args : CrossmatchArgs The partitions and respective pixel information. Returns ------- tuple[np.ndarray, np.ndarray, pd.DataFrame] - a numpy array with the indices of the matching rows from the left table - a numpy array with the indices of the matching rows from the right table - a pandas dataframe with any additional columns generated by the algorithm These all must have the same lengths. """ raise NotImplementedError( "Crossmatch algorithm must either implement `perform_crossmatch` or overwrite `crossmatch`" ) # pylint: disable=protected-access def validate(self, left: Catalog, right: Catalog): """Validate the metadata and arguments. This method will be called **once**, after the algorithm object has been initialized, during the lazy construction of the execution graph. This can be used to catch simple errors without waiting for an expensive ``.compute()`` call. This should validate any parameters used to initialize the crossmatching algorithm. Parameters ---------- left: Catalog The left catalog for the crossmatch. right: Catalog The right catalog for the crossmatch. """ # Check that we have the appropriate columns in our dataset. column_names = left.columns if left.hc_structure.catalog_info.ra_column not in column_names: raise ValueError( f"left table '{left.name}' must have column '{left.hc_structure.catalog_info.ra_column}'" ) if left.hc_structure.catalog_info.dec_column not in column_names: raise ValueError( f"left table '{left.name}' must have column '{left.hc_structure.catalog_info.dec_column}'" ) column_names = right.columns if right.hc_structure.catalog_info.ra_column not in column_names: raise ValueError( f"right table '{right.name}' must have column '{right.hc_structure.catalog_info.ra_column}'" ) if right.hc_structure.catalog_info.dec_column not in column_names: raise ValueError( f"right table '{right.name}' must have column '{right.hc_structure.catalog_info.dec_column}'" ) @staticmethod def _rename_columns_with_suffix(dataframe, suffix): columns_renamed = {name: name + suffix for name in dataframe.columns} dataframe.rename(columns=columns_renamed, inplace=True) @classmethod def _append_extra_columns(cls, dataframe: npd.NestedFrame, extra_columns: pd.DataFrame | None = None): """Adds crossmatch extra columns to the resulting Dataframe.""" if cls.extra_columns is None: return if extra_columns is None: raise ValueError("No extra column values were provided") # Check if the provided columns are in the specification for col in extra_columns.columns: if col not in cls.extra_columns.columns: raise ValueError(f"Provided extra column '{col}' not found in definition") # Update columns according to crossmatch algorithm specification columns_to_update = [] for extra_col, col_type in cls.extra_columns.dtypes.items(): if extra_col not in extra_columns: raise ValueError(f"Missing extra column '{extra_col} of type {col_type}'") if col_type != extra_columns[extra_col].dtype: raise ValueError(f"Invalid type '{col_type}' for extra column '{extra_col}'") columns_to_update.append(extra_col) for update_col in columns_to_update: new_col = extra_columns[update_col] new_col.index = dataframe.index dataframe[update_col] = new_col # pylint: disable=too-many-locals,too-many-arguments def _create_crossmatch_df( self, left_df: npd.NestedFrame, right_df: npd.NestedFrame, left_idx: npt.NDArray[np.int64], right_idx: npt.NDArray[np.int64], extra_cols: pd.DataFrame, how: str, suffixes: tuple[str, str], suffix_method: str = "all_columns", right_native_mask: npt.NDArray[np.bool_] | None = None, right_matched_mask: npt.NDArray[np.bool_] | None = None, left_coordinates: tuple[str | None, str | None] | None = None, right_coordinates: tuple[str | None, str | None] | None = None, ) -> npd.NestedFrame: """Create a dataframe containing matched and requested unmatched rows. Parameters ---------- left_df : npd.NestedFrame The left partition. right_df : npd.NestedFrame The right partition and its margin rows. left_idx : np.ndarray Positional indices of matching rows from the left table. right_idx : np.ndarray Positional indices of matching rows from the right table. extra_cols : pd.DataFrame Additional columns generated by the crossmatch. how : str One of {'inner', 'left', 'outer'}. suffixes : tuple[str,str] Suffixes appended to left and right columns. suffix_method : str, default 'all_columns' The suffix method to use. right_native_mask : np.ndarray or None Rows from the primary right partition that belong to the aligned pixel. Required for outer joins so margin rows are not emitted independently. right_matched_mask : np.ndarray or None Additional right rows treated as matched when emitting unmatched right rows. left_coordinates : tuple[str or None, str or None] or None Original left RA and declination column names. right_coordinates : tuple[str or None, str or None] or None Original right RA and declination column names. Returns ------- npd.NestedFrame The assembled crossmatch rows. """ left_column_names = list(left_df.columns) right_column_names = list(right_df.columns) left_df, right_df = apply_suffixes(left_df, right_df, suffixes, suffix_method, log_changes=False) left_name_map = dict(zip(left_column_names, left_df.columns, strict=True)) right_name_map = dict(zip(right_column_names, right_df.columns, strict=True)) index_name = left_df.index.name if left_df.index.name is not None else "index" left_matched = left_df.iloc[left_idx].reset_index() right_matched = right_df.iloc[right_idx].reset_index(drop=True) blocks: list[pd.DataFrame] = [pd.concat([left_matched, right_matched], axis=1)] if how in ("left", "outer"): matched_left = np.zeros(len(left_df), dtype=bool) matched_left[left_idx] = True left_unmatched = left_df.iloc[~matched_left].reset_index() null_right = right_df.iloc[:0].reindex(left_unmatched.index, fill_value=None) blocks.append(pd.concat([left_unmatched, null_right], axis=1)) if how == "outer": if right_native_mask is None or len(right_native_mask) != len(right_df): raise ValueError("Outer crossmatch requires a native-right mask matching right_df") matched_right = np.zeros(len(right_df), dtype=bool) matched_right[right_idx] = True if right_matched_mask is not None: matched_right |= right_matched_mask right_unmatched = right_df.iloc[right_native_mask & ~matched_right].reset_index(names=index_name) null_left = left_df.iloc[:0].reindex(right_unmatched.index, fill_value=None) blocks.append(pd.concat([null_left, right_unmatched], axis=1)) out = cast(npd.NestedFrame, pd.concat(blocks, axis=0, ignore_index=True)) out.set_index(index_name, inplace=True) if not extra_cols.columns.empty: n_unmatched = len(out) - len(extra_cols) assert n_unmatched >= 0, ( f"Logic error: extra_cols ({len(extra_cols)} rows) cannot exceed output ({len(out)} rows). " "This indicates a bug in the crossmatch algorithm or the join logic." ) if n_unmatched > 0: null_extra = pd.DataFrame( {col: _na_series_for_dtype(extra_cols[col].dtype, n_unmatched) for col in extra_cols} ) extra_cols = pd.concat([extra_cols.reset_index(drop=True), null_extra], ignore_index=True) extra_cols.index = out.index self._append_extra_columns(out, extra_cols) if how == "outer" and left_coordinates is not None and right_coordinates is not None: for output_coord, left_coord, right_coord in zip( ("_ra", "_dec"), left_coordinates, right_coordinates, strict=True ): if left_coord is not None and right_coord is not None: left_values = cast(pd.Series, out[left_name_map[left_coord]]) right_values = cast(pd.Series, out[right_name_map[right_coord]]) out[output_coord] = left_values.combine_first(right_values) spatial_index = compute_spatial_index( out["_ra"].to_numpy(), out["_dec"].to_numpy() # type: ignore[arg-type] ) out.index = pd.Index(pd.Series(spatial_index, dtype=out.index.dtype), name=SPATIAL_INDEX_COLUMN) out.sort_index(kind="stable", inplace=True) return npd.NestedFrame(out) def _create_nested_crossmatch_df( self, left_df: npd.NestedFrame, right_df: npd.NestedFrame, left_idx: npt.NDArray[np.int64], right_idx: npt.NDArray[np.int64], extra_cols: pd.DataFrame, nested_column_name: str, how: str, ) -> npd.NestedFrame: """Creates a df containing the crossmatch result from matching indices and additional columns Parameters ---------- left_df : npd.NestedFrame The left partition. right_df : npd.NestedFrame The right partition. left_idx : np.ndarray Indices of the matching rows from the left table right_idx : np.ndarray Indices of the matching rows from the right table extra_cols : pd.DataFrame Dataframe containing additional columns from crossmatching nested_column_name : str The name of the column where the matches should be stored. how : str How to handle the crossmatch of the two catalogs. One of {'left', 'inner'}. Returns ------- npd.NestedFrame A dataframe with the matching rows from the left and right table concatenated together, with the additional columns added. """ # concat dataframes together index_name = left_df.index.name if left_df.index.name is not None else "index" left_join_part = left_df.reset_index() right_join_part = right_df.iloc[right_idx].copy() right_join_part["new_index_col"] = left_idx right_join_part = right_join_part.set_index("new_index_col") self._append_extra_columns(right_join_part, extra_cols) out = left_join_part.join_nested(right_join_part, nested_column_name, how=how) out.set_index(index_name, inplace=True) return out