Skip to content

Commit fad4825

Browse files
flying-sheepNISMAMJAD
authored andcommitted
Catch all warnings (scverse#3724)
1 parent b6343a0 commit fad4825

50 files changed

Lines changed: 695 additions & 547 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

.github/workflows/ci.yml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,9 @@ env:
1212
FORCE_COLOR: "1"
1313
MPLBACKEND: agg
1414
UV_CONSTRAINT: ci/constraints.txt
15+
# It’s impossible to ignore SyntaxWarnings for a single module,
16+
# so because leidenalg 0.10.0 has them, we pre-compile things: https://github.com/vtraag/leidenalg/issues/173
17+
UV_COMPILE_BYTECODE: "1"
1518

1619
defaults:
1720
run:

docs/installation.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ After installing installing e.g. [Miniconda][], run:
2424
$ conda install -c conda-forge scanpy python-igraph leidenalg
2525
```
2626

27-
Pull Scanpy [from PyPI][] (consider using `pip3` to access Python 3):
27+
Pull Scanpy [from PyPI][]:
2828

2929
```console
3030
$ pip install scanpy

docs/release-notes/3724.bugfix.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Raise fewer redundant warnings, mainly in {mod}`scanpy.pl` and {mod}`scanpy.datasets` functions {smaller}`P Angerer`

pyproject.toml

Lines changed: 14 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -170,26 +170,20 @@ markers = [
170170
"anndata_dask_support: tests that require dask support in anndata",
171171
]
172172
filterwarnings = [
173-
# legacy-api-wrap: internal use of positional API
174-
"error:The specified parameters:FutureWarning",
175-
# When calling `.show()` in tests, this is raised
176-
"ignore:FigureCanvasAgg is non-interactive:UserWarning",
177-
178-
# We explicitly handle the below errors in tests
179-
"error:`anndata.read` is deprecated:FutureWarning",
180-
"error:Observation names are not unique:UserWarning",
181-
"error:The dtype argument is deprecated and will be removed:FutureWarning",
182-
"error:The behavior of DataFrame\\.sum with axis=None is deprecated:FutureWarning",
183-
"error:The default of observed=False is deprecated:FutureWarning",
184-
"error:Series\\.__getitem__ treating keys as positions is deprecated:FutureWarning",
185-
"error:The default value of 'ignore' for the `na_action` parameter in pandas\\.Categorical\\.map:FutureWarning",
186-
"error:The provided callable.* is currently using:FutureWarning",
187-
"error:The behavior of DataFrame concatenation with empty or all-NA entries is deprecated:FutureWarning",
188-
"error:A value is trying to be set on a copy of a slice from a DataFrame",
189-
"error:No data for colormapping provided via 'c'",
190-
"error:\\n*The `scale` parameter has been renamed and will be removed",
191-
"error:\\n*Passing `palette` without assigning `hue` is deprecated",
192-
"error:\\n*Setting a gradient palette using color= is deprecated",
173+
'error',
174+
# Umap warns when tensorflow isn’t installed.
175+
'ignore::ImportWarning:umap',
176+
# seaborn≤0.13.2 causes some matplotlib warnings
177+
'ignore::PendingDeprecationWarning:seaborn',
178+
# matplotlib<3.10.4 causes a Pillow warning
179+
'ignore:.*Pillow:DeprecationWarning',
180+
# networkx 2.x warns about scipy.sparse changes
181+
'ignore:\n*.*scipy\.sparse array:DeprecationWarning:networkx',
182+
# h5py <3.9 uses deprecated np.product
183+
'ignore:.*product.*deprecated.*NumPy:DeprecationWarning',
184+
# we want to see and eventually fix these
185+
'default::numba.core.errors.NumbaPerformanceWarning',
186+
'default:.*TSNE.*random.*to.*pca:FutureWarning', # we should set init=obsm["X_pca"] or so
193187
]
194188

195189
[tool.coverage.run]

src/scanpy/_utils/__init__.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ def ensure_igraph() -> None:
8484
msg = (
8585
"Please install the igraph package: "
8686
"`conda install -c conda-forge python-igraph` or "
87-
"`pip3 install igraph`."
87+
"`pip install igraph`."
8888
)
8989
raise ImportError(msg)
9090

@@ -127,6 +127,7 @@ def renamed_arg(old_name, new_name, *, pos_0: bool = False):
127127
def decorator(func):
128128
@wraps(func)
129129
def wrapper(*args, **kwargs):
130+
__tracebackhide__ = True
130131
if old_name in kwargs:
131132
f_name = func.__name__
132133
pos_str = (
@@ -832,8 +833,8 @@ def warn_with_traceback( # noqa: PLR0917
832833
settings.write(warnings.formatwarning(message, category, filename, lineno, line))
833834

834835

835-
def warn_once(msg: str, category: type[Warning], stacklevel: int = 1):
836-
warnings.warn(msg, category, stacklevel=stacklevel)
836+
def warn_once(msg: str, category: type[Warning], stacklevel: int = 0) -> None:
837+
warnings.warn(msg, category, stacklevel=stacklevel + 1)
837838
# You'd think `'once'` works, but it doesn't at the repl and in notebooks
838839
warnings.filterwarnings("ignore", category=category, message=re.escape(msg))
839840

src/scanpy/datasets/_datasets.py

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,14 @@
66

77
import numpy as np
88
import pandas as pd
9-
from anndata import AnnData
9+
from anndata import AnnData, OldFormatWarning
1010

1111
from .. import _utils
1212
from .._compat import deprecated, old_positionals
1313
from .._settings import settings
1414
from .._utils._doctests import doctest_internet, doctest_needs
1515
from ..readwrite import read, read_visium
16-
from ._utils import check_datasetdir_exists, filter_oldformatwarning
16+
from ._utils import check_datasetdir_exists
1717

1818
if TYPE_CHECKING:
1919
from typing import Literal
@@ -123,6 +123,8 @@ def burczynski06() -> AnnData:
123123
--------
124124
>>> import scanpy as sc
125125
>>> sc.datasets.burczynski06()
126+
UserWarning: Variable names are not unique. To make them unique, call `.var_names_make_unique`.
127+
utils.warn_names_duplicates("var")
126128
AnnData object with n_obs × n_vars = 127 × 22283
127129
obs: 'groups'
128130
@@ -196,6 +198,8 @@ def moignard15() -> AnnData:
196198
--------
197199
>>> import scanpy as sc
198200
>>> sc.datasets.moignard15()
201+
UserWarning: Unknown extension is not supported and will be removed
202+
warn(msg)
199203
AnnData object with n_obs × n_vars = 3934 × 42
200204
obs: 'exp_groups'
201205
uns: 'iroot', 'exp_groups_colors'
@@ -318,7 +322,6 @@ def toggleswitch() -> AnnData:
318322
return adata
319323

320324

321-
@filter_oldformatwarning
322325
def pbmc68k_reduced() -> AnnData:
323326
r"""Subsampled and processed 68k PBMCs.
324327
@@ -354,12 +357,12 @@ def pbmc68k_reduced() -> AnnData:
354357
"""
355358
filename = HERE / "10x_pbmc68k_reduced.h5ad"
356359
with warnings.catch_warnings():
360+
warnings.filterwarnings("ignore", category=OldFormatWarning, module="anndata")
357361
warnings.filterwarnings("ignore", category=FutureWarning, module="anndata")
358362
return read(filename)
359363

360364

361365
@doctest_internet
362-
@filter_oldformatwarning
363366
@check_datasetdir_exists
364367
def pbmc3k() -> AnnData:
365368
r"""3k PBMCs from 10x Genomics.
@@ -406,12 +409,13 @@ def pbmc3k() -> AnnData:
406409
407410
"""
408411
url = "https://falexwolf.de/data/pbmc3k_raw.h5ad"
409-
adata = read(settings.datasetdir / "pbmc3k_raw.h5ad", backup_url=url)
412+
with warnings.catch_warnings():
413+
warnings.filterwarnings("ignore", category=OldFormatWarning, module="anndata")
414+
adata = read(settings.datasetdir / "pbmc3k_raw.h5ad", backup_url=url)
410415
return adata
411416

412417

413418
@doctest_internet
414-
@filter_oldformatwarning
415419
@check_datasetdir_exists
416420
def pbmc3k_processed() -> AnnData:
417421
"""Processed 3k PBMCs from 10x Genomics.
@@ -447,6 +451,7 @@ def pbmc3k_processed() -> AnnData:
447451
url = "https://raw.githubusercontent.com/chanzuckerberg/cellxgene/main/example-dataset/pbmc3k.h5ad"
448452

449453
with warnings.catch_warnings():
454+
warnings.filterwarnings("ignore", category=OldFormatWarning, module="anndata")
450455
warnings.filterwarnings("ignore", category=FutureWarning, module="anndata")
451456
return read(settings.datasetdir / "pbmc3k_processed.h5ad", backup_url=url)
452457

@@ -540,6 +545,10 @@ def visium_sge(
540545
--------
541546
>>> import scanpy as sc
542547
>>> sc.datasets.visium_sge(sample_id="V1_Breast_Cancer_Block_A_Section_1")
548+
FutureWarning: Use `squidpy.datasets.visium` instead.
549+
sc.datasets.visium_sge(sample_id="V1_Breast_Cancer_Block_A_Section_1")
550+
UserWarning: Variable names are not unique. To make them unique, call `.var_names_make_unique`.
551+
utils.warn_names_duplicates("var")
543552
AnnData object with n_obs × n_vars = 3798 × 36601
544553
obs: 'in_tissue', 'array_row', 'array_col'
545554
var: 'gene_ids', 'feature_types', 'genome'
@@ -552,4 +561,6 @@ def visium_sge(
552561
sample_id, spaceranger_version, download_image=include_hires_tiff
553562
)
554563
source_image_path = sample_dir / "image.tif" if include_hires_tiff else None
555-
return read_visium(sample_dir, source_image_path=source_image_path)
564+
with warnings.catch_warnings():
565+
warnings.filterwarnings("ignore", r".*squidpy\.read", FutureWarning)
566+
return read_visium(sample_dir, source_image_path=source_image_path)

src/scanpy/datasets/_utils.py

Lines changed: 0 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,8 @@
11
from __future__ import annotations
22

3-
import warnings
43
from functools import wraps
54
from typing import TYPE_CHECKING
65

7-
import anndata as ad
8-
from packaging.version import Version
9-
106
from .._settings import settings
117

128
if TYPE_CHECKING:
@@ -24,18 +20,3 @@ def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
2420
return f(*args, **kwargs)
2521

2622
return wrapper
27-
28-
29-
def filter_oldformatwarning(f: Callable[P, R]) -> Callable[P, R]:
30-
"""Filter anndata.OldFormatWarning from being thrown by the wrapped function."""
31-
32-
@wraps(f)
33-
def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
34-
with warnings.catch_warnings():
35-
if Version(ad.__version__).release >= (0, 8):
36-
warnings.filterwarnings(
37-
"ignore", category=ad.OldFormatWarning, module="anndata"
38-
)
39-
return f(*args, **kwargs)
40-
41-
return wrapper

src/scanpy/logging.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -78,11 +78,12 @@ def _set_log_file(settings: SettingsMeta) -> None:
7878
file = settings.logfile
7979
name = settings.logpath
8080
root = settings._root_logger
81+
for handler in list(root.handlers):
82+
root.removeHandler(handler)
83+
handler.close()
8184
h = logging.StreamHandler(file) if name is None else logging.FileHandler(name)
8285
h.setFormatter(_LogFormatter())
8386
h.setLevel(root.level)
84-
for handler in list(root.handlers):
85-
root.removeHandler(handler)
8687
root.addHandler(h)
8788

8889

src/scanpy/plotting/_tools/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1325,7 +1325,7 @@ def rank_genes_groups_violin( # noqa: PLR0913
13251325
_ax.set_title(f"{group_name} vs. {reference}")
13261326
_ax.legend_.remove()
13271327
_ax.set_ylabel("expression")
1328-
_ax.set_xticklabels(new_gene_names, rotation="vertical")
1328+
_ax.set_xticks(range(len(new_gene_names)), new_gene_names, rotation="vertical")
13291329
writekey = (
13301330
f"rank_genes_groups_{adata.uns[key]['params']['groupby']}_{group_name}"
13311331
)

src/scanpy/plotting/_tools/paga.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1289,7 +1289,7 @@ def moving_average(a):
12891289
),
12901290
)
12911291
if show_yticks:
1292-
groups_axis.set_yticklabels(["", xlabel, ""], fontsize=ytick_fontsize)
1292+
groups_axis.set_yticks(range(3), [xlabel, "", ""], fontsize=ytick_fontsize)
12931293
else:
12941294
groups_axis.set_yticks([])
12951295
groups_axis.set_frame_on(False)
@@ -1331,7 +1331,7 @@ def moving_average(a):
13311331
cmap=color_map_anno,
13321332
)
13331333
if show_yticks:
1334-
anno_axis.set_yticklabels(["", anno, ""], fontsize=ytick_fontsize)
1334+
anno_axis.set_yticks(range(3), [anno, "", ""], fontsize=ytick_fontsize)
13351335
anno_axis.tick_params(axis="both", which="both", length=0)
13361336
else:
13371337
anno_axis.set_yticks([])

0 commit comments

Comments
 (0)