Skip to content

sc.pp.highly_variable_genes with flavor='seurat_v3' and batch_key: conflict with documentation #1733

Open

Description

@jlause
  • I have checked that this issue has not already been reported.
  • I have confirmed this bug exists on the latest version of scanpy.
  • (optional) I have confirmed this bug exists on the master branch of scanpy.

Hey, I've noticed another potential problem within the seurat_v3 flavor of sc.pp.highly_variable_genes(). The documentation of the batch_key argument says on how the genes are ranked

For all flavors, genes are first sorted by how many batches they are a HVG. For dispersion-based flavors ties are broken by normalized dispersion. If flavor = 'seurat_v3', ties are broken by the median (across batches) rank based on within-batch normalized variance.

However, when genes are sorted after computing everything, the seurat_v3 method sorts first by the median ranks and then by how many batches a gene is highly variable (contrary to what the docstring says):

https://github.com/theislab/scanpy/blob/da66e15eee137b51868a6fb85603cfca9de557a7/scanpy/preprocessing/_highly_variable_genes.py#L139-L144

For comparison, the other flavors sort the other way around (as the docstring says):

https://github.com/theislab/scanpy/blob/da66e15eee137b51868a6fb85603cfca9de557a7/scanpy/preprocessing/_highly_variable_genes.py#L505-L510

Not sure which sorting would be correct here to make seurat_v3 match the original behavior in Seurat, but I found these comments by @adamgayoso in #1204 that mention that when using batch_key in the current implementation, results don't match Seurat.. maybe the sorting order is the problem here?

#1204 (comment)
#1204 (comment)

Here is a piece of code that shows the top5 genes after seurat_v3 gene selection and sorting by highly_variable_nbatches (which should then all be HVG, but they are not)

Details
import numpy as np
import scanpy as sc
import anndata 

import sys
sys.path.append("scanpy/preprocessing")
from _utils import _get_mean_var

np.random.seed(42)
adata = anndata.AnnData(np.random.randint(0,5,(100,100)))
adata.obs['batch'] = np.random.randint(0,5,(100))
adata.obs['batch'] = adata.obs['batch'].astype('category')
n_top_genes = 50

adata = adata.copy()
sc.pp.highly_variable_genes(adata,n_top_genes=n_top_genes,flavor='seurat_v3',inplace=True,batch_key='batch')

adata.var.sort_values(['highly_variable_nbatches'], ascending=[False]).iloc[:5,:]
    highly_variable  highly_variable_rank  means  variances  variances_norm  highly_variable_nbatches
87             True                   8.0   1.76   2.446869        1.232373                         5
9             False                  28.0   1.96   2.281212        1.159891                         5
78             True                  24.0   1.95   2.209596        1.124666                         5
30             True                  19.0   2.00   2.202020        1.134560                         4
14            False                  25.0   2.14   2.162020        1.088266                         4

Versions

Details

sc.logging.print_versions()
WARNING: If you miss a compact list, please try print_header!


anndata 0.7.5
scanpy 1.7.1.dev2+g8c469411
sinfo 0.3.1

PIL 8.1.0
anndata 0.7.5
cffi 1.14.4
constants NA
cycler 0.10.0
cython_runtime NA
dateutil 2.8.1
get_version 2.1
google NA
h5py 2.10.0
highs_wrapper NA
joblib 1.0.0
kiwisolver 1.3.1
legacy_api_wrap 1.2
llvmlite 0.35.0
matplotlib 3.3.3
mpl_toolkits NA
natsort 7.1.0
numba 0.52.0
numexpr 2.7.2
numpy 1.19.5
packaging 20.8
pandas 1.2.0
pkg_resources NA
pyparsing 2.4.7
pytz 2020.5
scanpy 1.7.1.dev2+g8c469411
scipy 1.6.0
sinfo 0.3.1
sitecustomize NA
six 1.15.0
sklearn 0.24.0
skmisc 0.1.3
tables 3.6.1
typing_extensions NA
yaml 5.3.1

Python 3.8.0 (default, Oct 28 2019, 16:14:01) [GCC 8.3.0]
Linux-3.10.0-957.el7.x86_64-x86_64-with-glibc2.27
40 logical CPU cores, x86_64

Session information updated at 2021-03-10 17:37

Activity

  1. adamgayoso commented on Mar 13, 2021

    @adamgayoso
    Member

    I think the solution here is for someone to figure out the Seurat sorting heuristic (didn't have bandwidth to really dig into the R code, and I don't do any R programming), and then correct the docstring based on what Seurat does.

  2. jlause commented on Mar 18, 2021

    @jlause
    ContributorAuthor

    Hey, thanks for your reply!

    I looked a bit around, and here is what the Seurat 3.1.4 docs say:

    Choose the features to use when integrating multiple datasets. This function ranks features by the number of datasets they appear in, breaking ties by the median rank across datasets. It returns the highest features by this ranking.

    from https://www.rdocumentation.org/packages/Seurat/versions/3.1.4/topics/SelectIntegrationFeatures

    From this, I'd conclude that the current docs are correct, but in the sorting order of _highly_variable_genes_seurat_v3 has it the wrong way around.

    Also, the test for the _highly_variable_genes_seurat_v3() method seems to assume that the method sorts the other way around than it currently does:

    From within the method:

    https://github.com/theislab/scanpy/blob/ca07fc12bbcd87e4cf67da56f52525a1e519711b/scanpy/preprocessing/_highly_variable_genes.py#L139-L144

    From the test:

    https://github.com/theislab/scanpy/blob/ca07fc12bbcd87e4cf67da56f52525a1e519711b/scanpy/tests/test_highly_variable_genes.py#L138-L151

    So from this it seems save to say that the sorting order should be reversed in _highly_variable_genes_seurat_v3()..?!

  3. adamgayoso commented on Mar 18, 2021

    @adamgayoso
    Member

    Very good catch! It does indeed look like in the function itself it should be

     df.sort_values( 
         ['highly_variable_nbatches', 'highly_variable_rank'], 
         ascending=[False, True], 
         na_position='last', 
         inplace=True, 
     ) 
    

    However, as the test sorting order was correct (though not testing the code the right way), it would still be great to figure out why there is a discrepancy at all.

    For reference, here's the seurat code:

    https://github.com/satijalab/seurat/blob/4e868fcde49dc0a3df47f94f5fb54a421bfdf7bc/R/integration.R#L2244-L2308

  4. jlause commented on Mar 18, 2021

    @jlause
    ContributorAuthor

    Thanks for digging up the seurat code! Somehow failed to find it when I looked for it..

    Should I add the correction to PR #1732, which fixes another little issue in the same function?
    And should the test also be changed? Currently only the intersection of the hvgs is checked between scanpy and seurat, so instead of sorting the output again and take the top4000 manually (as done now), one could just take df['highly_variable'] directly for comparison:

        df = sc.pp.highly_variable_genes(
            pbmc, n_top_genes=4000, flavor='seurat_v3', batch_key="batch", inplace=False
        )
    
        df = df.loc[df['highly_variable'],:]
        seurat_hvg_info_batch = pd.read_csv(
            FILE_V3_BATCH, sep=' ', dtype={"variances_norm": np.float64}
        )
    
        # ranks might be slightly different due to many genes having same normalized var
        seu = pd.Index(seurat_hvg_info_batch['x'].values)
        assert len(seu.intersection(df.index)) / 4000 > 0.95
    

    Unfortunately I have no lead where to start with the remaining discrepancy and not enough time at the moment to look into this.. :(

  5. ivirshup commented on Mar 19, 2021

    @ivirshup
    Member

    @jlause, thanks for figuring this out as well!

    A separate PR for this fix would be great. There should definitely be tests targeting this, since changing how the sort is done doesn't seem to break anything.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions