From 2337f564f4d24c56ff9b3c922970159bb510cfc8 Mon Sep 17 00:00:00 2001 From: Simon Shen Date: Wed, 5 Jul 2023 22:39:29 -0400 Subject: [PATCH 1/2] safe get log1p base --- scanpy/preprocessing/_highly_variable_genes.py | 2 +- scanpy/tools/_rank_genes_groups.py | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/scanpy/preprocessing/_highly_variable_genes.py b/scanpy/preprocessing/_highly_variable_genes.py index 7378b6889e..ce61c54894 100644 --- a/scanpy/preprocessing/_highly_variable_genes.py +++ b/scanpy/preprocessing/_highly_variable_genes.py @@ -194,7 +194,7 @@ def _highly_variable_genes_single_batch( """ X = adata.layers[layer] if layer is not None else adata.X if flavor == 'seurat': - if 'log1p' in adata.uns_keys() and adata.uns['log1p']['base'] is not None: + if 'log1p' in adata.uns_keys() and adata.uns['log1p'].get('base') is not None: X *= np.log(adata.uns['log1p']['base']) X = np.expm1(X) diff --git a/scanpy/tools/_rank_genes_groups.py b/scanpy/tools/_rank_genes_groups.py index 026806ecb3..716f7efc21 100644 --- a/scanpy/tools/_rank_genes_groups.py +++ b/scanpy/tools/_rank_genes_groups.py @@ -88,7 +88,7 @@ def __init__( layer=None, comp_pts=False, ): - if 'log1p' in adata.uns_keys() and adata.uns['log1p']['base'] is not None: + if 'log1p' in adata.uns_keys() and adata.uns['log1p'].get('base') is not None: self.expm1_func = lambda x: np.expm1(x * np.log(adata.uns['log1p']['base'])) else: self.expm1_func = np.expm1 @@ -751,7 +751,7 @@ def filter_rank_genes_groups( index=gene_names.index, ) - if 'log1p' in adata.uns_keys() and adata.uns['log1p']['base'] is not None: + if 'log1p' in adata.uns_keys() and adata.uns['log1p'].get('base') is not None: expm1_func = lambda x: np.expm1(x * np.log(adata.uns['log1p']['base'])) else: expm1_func = np.expm1 From 8d278bdb7ecb0c35ab9213caa61d7bae56189247 Mon Sep 17 00:00:00 2001 From: Philipp A Date: Fri, 7 Jul 2023 14:36:28 +0200 Subject: [PATCH 2/2] add test --- scanpy/tests/test_rank_genes_groups.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/scanpy/tests/test_rank_genes_groups.py b/scanpy/tests/test_rank_genes_groups.py index fcf73d9256..d8de03aa54 100644 --- a/scanpy/tests/test_rank_genes_groups.py +++ b/scanpy/tests/test_rank_genes_groups.py @@ -248,6 +248,21 @@ def test_emptycat(): rank_genes_groups(pbmc, groupby='louvain') +def test_log1p_save_restore(tmp_path): + """tests the sequence log1p→save→load→rank_genes_groups""" + from anndata import read + + pbmc = pbmc68k_reduced() + sc.pp.log1p(pbmc) + + path = tmp_path / 'test.h5ad' + pbmc.write(path) + + pbmc = read(path) + + sc.tl.rank_genes_groups(pbmc, groupby='bulk_labels', use_raw=True) + + def test_wilcoxon_symmetry(): pbmc = pbmc68k_reduced()