Skip to content

Add calculate_qc_metrics function - #316

Merged
falexwolf merged 11 commits into
scverse:masterfrom
ivirshup:qcmetrics
Nov 5, 2018
Merged

falexwolf merged 11 commits into
scverse:masterfrom
ivirshup:qcmetrics

Conversation

@ivirshup

@ivirshup ivirshup commented Oct 22, 2018 •

Copy link
Copy Markdown
Member

I like the calculateQCMetrics function from scater, and have had a half finished python version drifting between my notebooks for a while. Is there is interest in adding this to scanpy?

I'm aiming to mostly copy the interface of calculateQCMetrics while being memory efficient, since this is likely run before filtering.

Todo

  • Figure out how I want to deal with more types of sparse matrix
  • Add feature_control argument, possibly variable_control
  • Clean up and expand tests
  • Expand documentation

Questions

  • What's up with sparse matrix choice in scanpy? Is adata.X expected to be any of the matrix types, or is it more limited? Just trying to figure out how much effort I should put into that.
  • Are there any additional metrics that could be useful?

@falexwolf

Copy link
Copy Markdown
Member

Cool!

Just the first question for now: any sparse matrix is allowed for adata.X, but typically this is csr or csc.

@falexwolf

Copy link
Copy Markdown
Member

All of this looks really good! Awesome! 😄

Most important thing that misses: making use of it already in a tutorial? Do you think it fits in the standard clustering tutorial?

I just think that you should probably also add the top-level function to the qc.py file in preprocessing.

@ivirshup

ivirshup commented Oct 24, 2018 •

Copy link
Copy Markdown
Member Author
  • I think it fits the standard tutorial, I calculate these things all the time. All the tutorials are in the scanpy_usage repo, right?
  • Do you mean the top_segment_proportions and/ or top_proportions functions?

Sparse matrix support

I took the easy way out for calculations on other sparse matrices types – just converted them to a CSR – so there's room for improvement. I'm considering writing a more involved implementation, but I'd have to benchmark it against conversion.

I'd probably try an online sort (insertion?) for each cell, keeping only the top max(ns) expression values, while iterating through the COO or CSC matrix.

Numba

This currently throws a lot of warnings about np.partition not being implemented in numba. This should change with their next release, and give some speedup here.

cell_controls

I'm trying to decide on including this. I haven't used data with control wells, so I don't know how common it is. It could be nice to implement it a bit differently, and have able to get something like.var["mean_counts_in_sampletype-CD8"], but I'm already returning a lot of values. Any thoughts?

f-strings

Just noticed this is why my builds are failing. This might get ugly.

@ivirshup
ivirshup force-pushed the qcmetrics branch 2 times, most recently from 718296c to 6a53d01 Compare October 24, 2018 06:56
Comment thread .travis_install.sh

conda create -n testenv --yes python=$TRAVIS_PYTHON_VERSION pip pytest hdf5 \
numpy=$NUMPY_VERSION scipy=$SCIPY_VERSION numba scikit-learn statsmodels
conda create -n testenv --yes python=$TRAVIS_PYTHON_VERSION pip pytest

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.

Well, pip doesn't install them a second time but already sees the latest versions, doesn't it? Anyways, if numba installs fine with pip these days, there is no reason to install it with conda; so this is good.

@ivirshup ivirshup Oct 26, 2018 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I think that's the case most of the time, but not always.

Since conda wasn't following the versioning in requirements.txt, it was installing numba v0.39.0 for python v3.5. This made pip install a different version, but not remove the old one. I think the older numba was being imported, causing the errors.

Here're the relevant lines from the build for a2c0d2b:

numba-0.39.0         | 2.4 MB    | ##################################### | 100%  # Line 589
Collecting numba>=0.40.0 (from -r requirements.txt (line 13)) # Line 706

I tried specifying the numba version a bit higher for conda, but was getting conflicts in dependency resolution. I figured if everything could be installed by pip, I knew the requirements.txt would be followed.

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.

Got it! Makes sense!

@falexwolf

Copy link
Copy Markdown
Member
  • I think it fits the standard tutorial, I calculate these things all the time. All the tutorials are in the scanpy_usage repo, right?
  • Do you mean the top_segment_proportions and/ or top_proportions functions?

Yes to both! :)

Let me know when I should merge this.

@ivirshup

ivirshup commented Oct 26, 2018 •

Copy link
Copy Markdown
Member Author

I've pretty much just gotta write the docs and rebase on my other PR, and this should be good to go.

For adding top_segment_proportions and top_proportions to preprocessing, should they get a wrapper to work on AnnData objects? Also, I'm not super happy with the name top_segment_proportions, and am open to suggestions for a better name.

@falexwolf

Copy link
Copy Markdown
Member

I'd say that if the user is supposed to work with top_segment_proportions and top_proportions on a regular base, it should also accept AnnDatas. Many Scanpy functions in the preprocessing module do both. In the beginning, I did this via recursive call, these days, I'd wouldn't recommend it but simply do:

X = data
if isinstance(data, AnnData):
    X = data.X

or if you don't like X then passed_data or something...

If you provide examples for your stuff here on this PR (simply paste a few pictures with a few lines of code), then we can discuss on a better name. Maybe @fidelram also has some opinion on this.

@falexwolf

Copy link
Copy Markdown
Member

As mentioned before, can you move everything you currently have in /preprocessing/simple.py to qc.py? We shouldn't grow that file even larger...

Initial commit for adding `calculate_qc_metrics` based on functionality
from `scater`.
Bump numba version to change errors to warnings. Install more
dependencies with pip to avoid having conflicts between conda and pip
installed packages.
This has been done the easy way, with converting sparse matrix types to
csr. Alternative, more specialized method possible, but would take more
work.
Probably should be two commits, but the code was kinda intertwinned by
the time I got there.

First, I've added support for COO sparse matrices, which required
converting them, as they can't be subsetted, which means they raise a
lot of errors.

Next, I've added a bunch of features. This includes setting
`feature_controls` and including log scaling for a few metrics.
Sadly, this makes for ugly code.
@ivirshup

Copy link
Copy Markdown
Member Author

Oh, I think I misunderstood earlier when you said:

I just think that you should probably also add the top-level function to the qc.py file in preprocessing.

I wasn't sure if you meant move calculate_qc_metrics to qc.py or add top_proportions and top_segment_proportions to the preprocessing module. If you're not asking for that, I'm not sure if they're important enough to go there. I use top_proportions to make a plotScater kind of plot, but that's about it.

Otherwise, I think this might be good for now. I was thinking I'd update the tutorial to use this function after the PR is merged. Once that's done, is there a script to update the tests under notebooks or is that done manually?

@falexwolf

Copy link
Copy Markdown
Member

Thank you, great! I meant moving calculate_qc_metrics to qc.py.

Updating the tutorial after this is good!

The tests under notebooks/ are currently updated manually.

😄

@falexwolf

Copy link
Copy Markdown
Member

Would you mind adding a note to the release notes and adding the function to the docs to complete the whole PR: https://github.com/theislab/scanpy/blob/master/docs/release_notes.rst?

* `pct_counts_mito` was being calculated wrong
* Now running `calculate_qc_metrics` again will overwrite previous values, not throw error
@ivirshup

Copy link
Copy Markdown
Member Author

I think I got the docs right, let me know if there are any issues.

I'm noticing some conflict with convention for metric names. I'm copying scater, and using labels like total_counts and total_features_by_counts. filter_genes, filter_cells, spring_project, and a couple of the recipes use n_counts or n_cells. My preference is for the scater way, since formatting allows it to be bit more flexible.

It'd be nice for there to be a consistent default key for these features. For example, while updating the clustering tutorial, I ended up with both n_counts and total_counts in the same adata.obs.

As changing the defaults could break some code, what's the right path forward? When scater updated their metric names, I think they used both the old and new keys with a deprecation warning. They talk about it a bit under the documentation for scatter::calcuateQCMetrics.

@falexwolf

Copy link
Copy Markdown
Member

Hm, n_counts and total_counts is of course non-sense. Scanpy tries to adapt the n_... convention in scikit-learn and statsmodels for anything that is a number. We'll soon expose the quantile normalization preprocessing function to the users in a proper way. Then we'll have 95%-quantile counts vs. total counts. Then it starts making sense to use the notion total_. So, in the light of that, we could think about moving there.

Yes, we'd deprecate old names and output a warning, too.

@falexwolf

Copy link
Copy Markdown
Member

So, this is really awesome! Thank you so much! Added you to the author list just before... 😄

@falexwolf
falexwolf merged commit 683b965 into scverse:master Nov 5, 2018
@falexwolf

Copy link
Copy Markdown
Member

Thanks for the tutorial!

Let's get most of this right now that no one has still used the function. We don't want to be consistent with Scater, we want to be consistent with the rest of Scanpy and the other python ecosystem.

  • Can we replace all occurances of features with variables? We had quite some discussions whether an AnnData is samples of features or observations of variables, and throughout, we stick with the latter convention. It's a very simple change.
  • Can we replace exprs_values with expr_type or something more suggestive of the fact that it's just a string denoting the kind of expression values?
  • Can we replace total_features_by_counts with n_genes? Why so complicated? And in contrast to total_counts, features does not suggest that it's a number, so there has to be an n_... before it, otherwise it completely breaks the convention.
  • Can we call feature_controls, control_variables, which would be a much more intuitive name?
  • Why is n_cells_by_{expr_values} not simply n_cells? Am I missing something?

Regarding n_counts versus total_counts, I mentioned already that I see that total_counts has some advantages when starting to compare with quantile counts, etc. Also, it doesn't require an n_ as it's clear that it's a number. But for all the rest that I mentioned above, I don't see these arguments. What do you think?

I really like that you use an inplace parameter instead of the usual copy, we might have exaggerated it in some places.

@ivirshup

ivirshup commented Nov 6, 2018

Copy link
Copy Markdown
Member Author

No problem!

  • features sounds more natural to me, but variables is fine. Maybe we could do vars instead of variables for reduced verbosity?
  • expr_type would work. Maybe vars_type?
  • How about n_genes_by_{exprs_type/vars_type}? n works great for this, since it's integer valued. I might like vars over genes since the variables could be transcripts or surface markers, but I'm not sure on this. I like the by_{vars_type} convention for a couple reasons, which also apply to your last point:
    • It allows recording at multiple steps in the process. You could imagine: n_{vars/genes}_by_counts and n_{vars/genes}_by_imputed_counts or n_{vars/genes}_by_normed_expression
    • The convention allows for multi-omic measurements on a gene, n_{vars/genes}_by_fluorescence for example. This is a case where genes makes more sense than vars.
  • control_variables does sound more natural. I'd possibly like to replace control as well, since these aren't necessarily controlled variables.
  • Largely similar thoughts as the third point, e.g.
    • Recording at multiple steps: n_cells_by_counts and n_cells_by_imputed_counts
    • Multi-omic measurements: n_cells_by_fluorescence

I think total can be more widely used than n, allowing more consistency. To me, total_cells or total_vars make sense while n_fluorescence or n_log_counts don't. It's also totally fine to have a mix.

Yeah, I figured I didn't want to make a whole copy of the object if I didn't want update or add all the metrics.

About places in the codebase where naming would need to change, I'd argue the default shouldn't be to use a pre-computed value. I hadn't realized that n_counts fields were being stored or used until I started looking around. Since summing over a matrix is likely a pretty light computation compared to what follows, I don't think there's a strong performance argument for keeping it as the default.

@falexwolf

Copy link
Copy Markdown
Member

thank you for your thoughts and suggestions! great! 😄

  • vars is fine, genes is also fine as this is a function that will predominantly used for RNA-seq, I guess, features would be fine if we had adopted a different convention
  • expr_type is better than vars_type; we could do values_type, which is suggestive and anticipates that at some point, .X might get deprecated and replaced by .values; but maybe a simple suffix parameter is better?
  • why not simply n_genes and n_genes_{suffix} if suffix is not None? if people want to distinguish between different processing steps or parts of the data matrix? but right now, the canonical use would only complete these things once for the raw data; I hardly imagine computing this stuff on imputed counts or normed expression... if people want, ok, they have the suffix argument for... if people do multi-omics with anndata (we're starting to do this a lot), yes, they should also be able to do it, but a suffix would be fine in this case, too; regarding by_{suffix}: I usually associate conditioning on something when I read by and I guess many people do, are we sure we want this here?
  • control_variables is more clear than the super-generic variables argument, which usually indicates in scanpy that you want a function to restrict to a set of variables; but here, it's different
  • largely similar thoughts on n_cells vs n_cells_{suffix}
  • n_... versus total_...; sure you're absolutely right, total_vars is much easier to swallow than n_fluorescence; so, I'm ok with total_... if you like to move forward with that; on the other hand, having n_... for things that are numbers and counted and sum_... for things that are simply sums within columns or rows would be even clearer, I imagine; but maybe confusing to implement; your decision! 😄

@falexwolf

Copy link
Copy Markdown
Member

PS: I like your use of inplace so much that I think that it should become the canonical way of triggering inplace computations in all function calls of scanpy, completely replacing copy; in most cases, though, it should default to inplace=True, I'd say... something to consider for Scanpy 2, I guess... or, we could have that in addition to copy and deprecate that at some point...

@ivirshup

ivirshup commented Nov 7, 2018

Copy link
Copy Markdown
Member Author
  • How about a var_type argument which defaults to "genes"? Could even replace occurrences of cells with a obs_type variable
  • Agreed, expr_type it is.
  • I'd considered an option of a suffix argument, but I think there are some issues with it being a string. If suffix=None, expr_type="counts" is it still total_counts? If suffix="_by_counts" is it still total_counts? A possible solution to this is making suffix a boolean argument, where True adds _by_{expr_type} as appropriate.
    • Additionally n_genes in particular is already an overloaded term, as it's already used with multiple different meanings in the codebase (typically number of genes to consider, or number of columns in the data matrix).
    • Could you say a bit more about the conditioning? I'm not sure I follow how it would be confusing here.
  • control_variables definitely makes more sense here than variables, I was just wondering if there's a better word than control.
    • If there was an equivalent for observations (something like mean_counts_in_donor1), what would be a good name for that argument?
  • I think I'm happy with n_... for some things, total_... for others.
  • On other convention I'm unsure about, should the range of the pct_... values be 0-100 or 0-1?

Here's what I'm thinking it'll look like right now (pending suffix decision)

For obs:

current proposed
total_features_by_{expr_values} n_{var_type}_by_{expr_type}
total_{expr_values} total_{expr_type}
pct_{expr_values}_in_top_{n}_features pct_{expr_type}_in_top_{n}_{var_type}
total_{expr_values}_{feature_control} total_{expr_type}_{control_var}
pct_{expr_values}_{feature_control} pct_{expr_type}_{control_var}

For var:

current proposed
total_{expr_values} total_{expr_type}
mean_{expr_values} mean_{expr_type}
n_cells_by_{expr_values} n_cells_by_{expr_type}
pct_dropout_by_{expr_values} pct_dropout_by_{expr_type}

@falexwolf

Copy link
Copy Markdown
Member

How about a var_type argument which defaults to "genes"? Could even replace occurrences of cells with a obs_type variable

Sorry about the late response. The week passes so quickly and depending on how it goes, I can only go back to Scanpy during the weekends these days...

I like your new table much better than the previous one. If you'd put that forward in a PR, I'd be super happy!

PS: I think control_variables is fine, maybe focus_variables better reflects that it's not only about "control", but just a subset of variables (or observations) of interest. Let's not move forward on the suffix argument, your imposed structure will make things cleaner for people! 😄 pct is ok if in 0 - 100. No obs_type needed right now...

ivirshup added a commit to ivirshup/scanpy that referenced this pull request Nov 12, 2018
Metrics were renamed following discussion in scverse#316. Additionally, I've fixed some bugs I caused while optimizing for sparse matrices. Pretty much all that's changed is there are sparse and dense specific methods for calculating nonzero genes, and mean expression.
@ivirshup

Copy link
Copy Markdown
Member Author

No problem, gave a chance to optimize the code a bit (peak memory was about 3x AnnData size, now down to about 2x).

@ivirshup ivirshup mentioned this pull request Nov 12, 2018
Koncopd pushed a commit that referenced this pull request Nov 16, 2018
Metrics were renamed following discussion in #316. Additionally, I've fixed some bugs I caused while optimizing for sparse matrices. Pretty much all that's changed is there are sparse and dense specific methods for calculating nonzero genes, and mean expression.
@ivirshup ivirshup mentioned this pull request Feb 11, 2019
8 of 15 tasks
@flying-sheep flying-sheep changed the title [WIP] Add calculate_qc_metrics function Add calculate_qc_metrics function Jan 9, 2020
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.

5 participants