Skip to content

Implement sc.get.summarized_expression_df - #1390

Open
gokceneraslan wants to merge 18 commits into
mainfrom
gokceneraslan-prepare-dataframe-multiindex
Open

gokceneraslan wants to merge 18 commits into
mainfrom
gokceneraslan-prepare-dataframe-multiindex

Conversation

@gokceneraslan

@gokceneraslan gokceneraslan commented Aug 25, 2020 •

Copy link
Copy Markdown
Contributor

This pr moves the (in)famous _prepare_dataframe function from scanpy.plotting._anndata to sc.get as _indexed_expression_df (bcs why would it be in plotting anyway) and implements a simple public interface called sc.get.summarized_expresion_df which simply provides nonzero mean/var and fraction using _indexed_expression_df function.

As discussed here (#1388 (comment)) we can use this in rank_genes_groups_df.

@gokceneraslan gokceneraslan changed the title Implement sc.get.grouped_expression_df Implement sc.get.summarized_expression_df Aug 25, 2020
@gokceneraslan
gokceneraslan requested a review from ivirshup August 25, 2020 16:59

@ivirshup ivirshup left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for looking into this!

I like what summarized_expression_df does, and think the operations could definitely be expanded. I'm realizing I'm not actually quite sure what I expect this to return, especially when groupby is passed. Can you write out some examples of use cases where you show the output?

However, I'm not sure I see the usefulness of _indexed_expression_df. I think _prepare_dataframe has been a bit overused in the codebase, particularly where it's pretty close to adata.to_df(). Instead of moving that function here directly, can we look at what the use cases are for it, and replace it on a case by case basis? We should avoid densify sparse arrays as much as possible, and I don't think it's worth it here.

Comment thread scanpy/get.py
Comment on lines +491 to +501
if layer is not None:
if layer not in adata.layers.keys():
raise KeyError(
f'Selected layer: {layer} is not in the layers list. '
f'The list of valid layers is: {adata.layers.keys()}'
)
matrix = adata[:, var_names].layers[layer]
elif use_raw:
matrix = adata.raw[:, var_names].X
else:
matrix = adata[:, var_names].X

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We've got a function for this:

Suggested change
if layer is not None:
if layer not in adata.layers.keys():
raise KeyError(
f'Selected layer: {layer} is not in the layers list. '
f'The list of valid layers is: {adata.layers.keys()}'
)
matrix = adata[:, var_names].layers[layer]
elif use_raw:
matrix = adata.raw[:, var_names].X
else:
matrix = adata[:, var_names].X
matrix = sc.get._get_obs_rep(adata[:, var_names], use_raw=use_raw, layers=layer)

Comment thread scanpy/get.py
Comment on lines +448 to +449
if use_raw is None and adata.raw is not None:
use_raw = True

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can this just default to False? I think the behavior around acting differently depending on whether raw is present is confusing, and makes it hard to reason about what code is going to do.

Comment thread scanpy/get.py
Comment on lines +462 to +467
for group in groupby:
if group not in adata.obs_keys():
raise ValueError(
'groupby has to be a valid observation. '
f'Given {group}, is not in observations: {adata.obs_keys()}'
)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is this error better than what pandas would throw?

Comment thread scanpy/get.py
Comment on lines +481 to +485
logg.error(
f"Gene symbol {symbol!r} not found in given "
f"gene_symbols column: {gene_symbols!r}"
)
return

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Probably just throw a value error?

Comment thread scanpy/get.py
Comment on lines +469 to +478
if gene_symbols is not None and gene_symbols in adata.var.columns:
# translate gene_symbols to var_names
# slow method but gives a meaningful error if no gene symbol is found:
translated_var_names = []
# if we're using raw to plot, we should also do gene symbol translations
# using raw
if use_raw:
adata_or_raw = adata.raw
else:
adata_or_raw = adata

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There's already some very similar logic to this in sc.get.obs_df. Could that be re-used here? If not, could a more similar solution be used?

Also, doesn't this conflict with how var_names is being set if no values are passed?

Comment thread scanpy/get.py
Comment on lines +532 to +533
obs_tidy_idx = [adata.obs[group] for group in groupby] # keep as multiindex
idx_categories = [x.cat.categories for x in obs_tidy_idx]

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this the current behavior?

Comment thread scanpy/get.py
ops = ['mean_expressed', 'var_expressed', 'fraction']
if isinstance(ops, str):
ops = [ops]
assert all(np.isin(ops, ['mean_expressed', 'var_expressed', 'fraction'])), 'Undefined op'

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should this also include normal mean and variance?

Comment thread scanpy/get.py
Comment on lines +330 to +337
if 'mean_expressed' in ops or 'var_expressed' in ops:
nonzero_group = df.mask(df<=threshold).groupby(level=df.index.names, observed=True)
if 'mean_expressed' in ops:
res['mean_expressed'] = nonzero_group.mean()
if 'var_expressed' in ops:
res['var_expressed'] = nonzero_group.var()
if 'fraction' in ops:
res['fraction'] = (df>threshold).groupby(level=df.index.names, observed=True).mean()

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Calculations should happen on the matrix from anndata, not on a dataframe. This would be much more efficient since it wouldn't require densifying sparse arrays.

@gokceneraslan
gokceneraslan force-pushed the gokceneraslan-prepare-dataframe-multiindex branch from 0556fbd to 6e77082 Compare December 7, 2020 19:58
gokceneraslan pushed a commit to gokceneraslan/sctoolkit that referenced this pull request Dec 7, 2020

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants