Skip to content

Commit

Permalink
Merge pull request #455 from theislab/fix/centroid_space_adata_annota…
Browse files Browse the repository at this point in the history
…tion

CentroidSpace AnnData Annotations
  • Loading branch information
Lilly-May authored Dec 8, 2023
2 parents 4dade6c + a56dde8 commit e0ce61d
Showing 1 changed file with 15 additions and 0 deletions.
15 changes: 15 additions & 0 deletions pertpy/tools/_perturbation_space/_simple.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ def compute(
target_col: str = "perturbations",
layer_key: str = None,
embedding_key: str = "X_umap",
keep_obs: bool = True,
) -> AnnData: # type: ignore
"""Computes the centroids of a pre-computed embedding such as UMAP.
Expand All @@ -26,6 +27,8 @@ def compute(
target_col: .obs column that stores the label of the perturbation applied to each cell.
layer_key: If specified pseudobulk computation is done by using the specified layer. Otherwise, computation is done with .X
embedding_key: `obsm` key of the AnnData embedding to use for computation. Defaults to the 'X' matrix otherwise.
keep_obs: Whether .obs columns in the input AnnData should be kept in the output pseudobulk AnnData. Only .obs columns with the same value for
each cell of one perturbation are kept. Defaults to True.
Examples:
Compute the centroids of a UMAP embedding of the papalexi_2021 dataset:
Expand Down Expand Up @@ -84,6 +87,18 @@ def compute(

ps_adata = AnnData(X=X)
ps_adata.obs_names = index
ps_adata.obs[target_col] = index

if embedding_key is not None:
ps_adata.obsm[embedding_key] = X

if keep_obs: # Save the values of the obs columns of interest in the ps_adata object
obs_df = adata.obs
obs_df = obs_df.groupby(target_col).agg(lambda x: np.nan if len(set(x)) != 1 else list(set(x))[0])
for obs_name in obs_df.columns:
if not obs_df[obs_name].isnull().values.any():
mapping = {pert: obs_df.loc[pert][obs_name] for pert in index}
ps_adata.obs[obs_name] = ps_adata.obs[target_col].map(mapping)

return ps_adata

Expand Down

0 comments on commit e0ce61d

Please sign in to comment.