Project: s41467-024-44757-7 | Function: filter (python)

system: You are an expert Python programmer implementing algorithms from scientific papers.
Complete the masked function based on the algorithm description.
Follow Python best practices and maintain consistent code style.
Return **only** the complete Python function code.

user: Complete this Python function:

**DESCRIPTION:** Core filtering function that subtracts the projection of the kernel from the expression matrix to remove unwanted biological signals and reveal hidden processes

**KEY TERMS:** {
  "kernel": "cell-cell similarity kernel",
  "projection": "portion of expression associated with signal",
  "embedding_key": "expression matrix key",
  "pseudocount": "avoid negative values"
}

**CONTEXT CODE:**     ) -> st.ArrayLike:
        """Mask the kernel.

        Parameters
        ----------
        kernel_input_idx
            Dictionary with index for kernel input.

        Returns
        -------
        The materialized kernel after masking, if :attr:`_kernel_mask` is present.

        Notes
        -----
        This operation can result in out-of-memory (OOM) error.
        """
        if kernel_input_idx is not None:
            x = self._kernel_containers["x"][kernel_input_idx["x"], :]
            y = self._kernel_containers["y"][kernel_input_idx["y"], :]
            kernel_mask = (
                self._kernel_mask[kernel_input_idx["x"], kernel_input_idx["y"]]
                if self._mask_key
                else None
            )
        else:
            x = self._kernel_containers["x"]
            y = self._kernel_containers["y"]
            kernel_mask = self._kernel_mask if self._mask_key else None

        if self._mask_key is not None:
            if self._backend == Backend.TORCH and not issparse(self.kernel):
                k = (
                    self._materialize_kernel(
                        k=self._kernel(x=x, y=y, materialize=True), to_cpu=False
                    )
                    * kernel_mask
                )
            elif issparse(self.kernel) and self._mask_key is not None:
                k = self.kernel.multiply(kernel_mask)
            else:
                k = (
                    self._materialize_kernel(
                        k=self._kernel(materialize=True, **self._kernel_containers)
                    )
                    * kernel_mask
                )
        else:
            k = self._kernel(x=x, y=y)
        return k

    def filter(
        self,
        embedding_key: Optional[str] = None,
        use_raw: Optional[bool] = False,
        pseudocount: bool = False,
        key_added: Optional[str] = None,
    ) -> Optional[AnnData]:
        """Perform filtering, subtract the projection of the kernel from the expression.

        Parameters
        ----------
        embedding_key
            Key in :attr:`anndata.AnnData.obsm` for which to compute the projection on.
            If `None`, use :attr:`anndata.AnnData.X`.
        use_raw
            Whether to use :attr:`anndata.AnnData.raw`, if present.
        pseudocount
            If `True`, add a pseudocount to filtered expression to avoid negative values
        key_added
            Key used when saving the result. If `None`, use ``'{embedding_key}_sift'``.
            The result is saved to :attr:`anndata.AnnData.X`, :attr:`anndata.AnnData.layers` or
            :attr:`anndata.AnnData.obsm`, depending on the ``embedding_key``.

        Returns
        -------
        The filtered data matrix.
        """
        # MASKED: Core filtering function implementation
        raise NotImplementedError("This function is masked for testing purposes.")

    def plot_kernel(
        self, save_path: Optional[os.PathLike] = None, show: bool = True, **kwargs: Any
    ) -> Optional[plt.Axes]:
        """Visualize the cell-cell similarity kernel.

        Parameters
        ----------
        save_path
            Path where to save the figure.
        show
            If `False`, return :class:`matplotlib.axes.Axes`.
        kwargs
            Additional keyword arguments to :func:`sift._utils.plot_kernel()`.

        Returns
        -------
        The axes object, if ``show = False``, otherwise `None`.
        """
        kernel_containers = kwargs.pop("kernel_containers", self._kernel_containers)
        groupby = kwargs.pop("groupby", None)
        if self._kernel_metric == KernelType.MAPPING:
            groupby = self._kernel_key
        return _plot_kernel(
            kernel=self.materialize_kernel(
                kernel_containers=kernel_containers, to_cpu=True
            ),
            adata=self.adata,
            src_key=self._src_key,
            tgt_key=self._tgt_key,
            groupby=groupby,
            save_path=save_path,
            show=show,
            **kwargs,
        )


def sifter(
    adata: AnnData,
    kernel_key: Optional[str] = None,
    metric: st.Kernel_t = KernelType.RBF,
    src_key: Optional[str] = None,
    tgt_key: Optional[str] = None,
    knn_key: Optional[str] = None,
    batch_key: Optional[str] = None,
    embedding_key: Optional[str] = None,
    use_raw: Optional[bool] = False,
    pseudocount: bool = False,
    key_added: Optional[str] = None,
    copy: bool = False,
    **kwargs: Any,
) -> AnnData:
    """Perform filtering, subtract the projection of the kernel from the expression.

    Parameters
    ----------
    adata
        Annotated data object.
    kernel_key
        Key in :class:`anndata.AnnData` where information for distance is stored.
    metric
        Metric to use.
    src_key
        Mask for the source space of the kernel.
    tgt_key
        Mask for the target space of the kernel.
    knn_key
        Key in :attr:`anndata.AnnData.obs` for k-NN masking.
    batch_key
        Key in :attr:`anndata.AnnData.obs` for batch masking.
    embedding_key


Complete the function implementation replacing "raise NotImplementedError".