Skip to content

ruff fixes #196

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 45 commits into from
Sep 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
45 commits
Select commit Hold shift + click to select a range
23bf98e
ruff fixes
DanielYang59 Sep 1, 2024
2a9ac7e
fix s101 use of assert
DanielYang59 Sep 1, 2024
3009cb4
globally ignore SLF001, access private class member
DanielYang59 Sep 1, 2024
aa69640
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Sep 1, 2024
10829ce
add todo tag
DanielYang59 Sep 1, 2024
2d1ecbb
put docstring and global ignore on top
DanielYang59 Sep 1, 2024
f25d6b9
Merge branch 'ruff-pmv' of github.com:janosh/pymatviz into ruff-pmv
DanielYang59 Sep 1, 2024
920303a
fix py017, properly capture exception
DanielYang59 Sep 1, 2024
f6f3057
Fix PT011, exception capture without match
DanielYang59 Sep 1, 2024
31e8364
add TODO tag for https://github.com/janosh/pymatviz/pull/195#issuecom…
DanielYang59 Sep 1, 2024
49809a1
fix NPY201, np trapz
DanielYang59 Sep 1, 2024
337eb12
use warn over print to fix T201
DanielYang59 Sep 1, 2024
46b2400
add comments for globally ignored ruff rules
DanielYang59 Sep 1, 2024
90eb61a
guard type check only import when possible
DanielYang59 Sep 1, 2024
0ccfd1b
remove ISC001 from ignore
DanielYang59 Sep 1, 2024
c6b7245
add todo tag
DanielYang59 Sep 1, 2024
d5c91b8
reduce duration items shown to 20
DanielYang59 Sep 1, 2024
7de6327
import Self from typing extension
DanielYang59 Sep 1, 2024
35e37b2
remove global ignore of S311 as there're only 2 violation
DanielYang59 Sep 1, 2024
2d70feb
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Sep 1, 2024
d9f152a
replace random with numpy, which also fixes S311
DanielYang59 Sep 2, 2024
d6475b8
fix "PT006", # pytest-parametrize-names-wrong-type
DanielYang59 Sep 2, 2024
476560b
guard type check only import
DanielYang59 Sep 2, 2024
5ab3390
fix "COM812", # trailing comma missing
DanielYang59 Sep 2, 2024
8bbbafd
remove no type check mark
DanielYang59 Sep 2, 2024
dc5fc56
Revert "fix "COM812", # trailing comma missing"
DanielYang59 Sep 2, 2024
3e95a83
fix unit test of io
DanielYang59 Sep 2, 2024
acef88d
NEED confirm: change width from 457 to 458
DanielYang59 Sep 2, 2024
10c56c4
clean up branch condition
DanielYang59 Sep 2, 2024
49cbdeb
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Sep 2, 2024
6fa85a2
use native array size arg
DanielYang59 Sep 2, 2024
9c8cfa3
revert accidental elem -> element rename
DanielYang59 Sep 2, 2024
4e7904d
fix random array generation
DanielYang59 Sep 2, 2024
e10efa7
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Sep 2, 2024
b747012
fix random array generate in asset maker
DanielYang59 Sep 2, 2024
93003af
revert test_io value to 457, reason unknown
DanielYang59 Sep 2, 2024
c12804a
skip eslint for now #197
DanielYang59 Sep 2, 2024
ec270ea
format pre-commit config
DanielYang59 Sep 2, 2024
50ba9c7
remove eslint skip mark in CI
DanielYang59 Sep 2, 2024
4f3826c
fix indentation in pyproject.toml
DanielYang59 Sep 2, 2024
566f6d3
drop quotes in test.yml string
DanielYang59 Sep 2, 2024
28d7f44
fix typo in filename
DanielYang59 Sep 2, 2024
882622e
fix shaded_ys type
DanielYang59 Sep 2, 2024
dfa5194
remove overwriting pytest duration
DanielYang59 Sep 2, 2024
e2f199d
pyproject whitespace
janosh Sep 2, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
ci:
autoupdate_schedule: quarterly
skip: [pyright, eslint]
skip: [pyright]

default_stages: [commit]

Expand Down Expand Up @@ -76,6 +76,7 @@ repos:
rev: v9.9.1
hooks:
- id: eslint
stages: [manual] # TODO: skip eslint for now
types: [file]
args: [--fix, --config, site/eslint.config.js]
files: \.(js|ts|svelte)$
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
# ruff: noqa: RUF001
"""Unprocessed data in data/carrier_transport.json.gz obtained from https://git.io/JOMwY."""

# %%
import pandas as pd
from matminer.datasets import load_dataset
Expand All @@ -6,12 +9,6 @@
from pymatviz.enums import Key


"""
Unprocessed data in data/carrier_transport.json.gz obtained from https://git.io/JOMwY.
"""
# ruff: noqa: RUF001


# %%
df_carrier = load_dataset("ricci_boltztrap_mp_tabular")

Expand Down
1 change: 1 addition & 0 deletions examples/make_assets/phonons.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from pymatviz.enums import Key


# TODO: ffonons not working properly (see #195)
try:
import ffonons # noqa: F401
except ImportError:
Expand Down
7 changes: 2 additions & 5 deletions examples/make_assets/ptable/ptable_matplotlib.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
# %%
import random

import numpy as np
from matminer.datasets import load_dataset
from pymatgen.core.periodic_table import Element
Expand Down Expand Up @@ -137,11 +135,10 @@


# %% Evenly-split tile plots laid out as a periodic table
rng = np.random.default_rng()
for n_splits in (2, 3, 4):
data_dict = {
elem.symbol: [
random.randint(10 * n_splits, 20 * (n_splits + 1)) for _ in range(n_splits)
]
elem.symbol: rng.integers(10 * n_splits, 20 * (n_splits + 1), size=n_splits)
for elem in Element
}

Expand Down
6 changes: 5 additions & 1 deletion pymatviz/bar.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from __future__ import annotations

from collections.abc import Sequence
from typing import Any, Literal, cast
from typing import TYPE_CHECKING, cast

import matplotlib.pyplot as plt
import numpy as np
Expand All @@ -19,6 +19,10 @@
from pymatviz.utils import PLOTLY, Backend, crystal_sys_from_spg_num, si_fmt_int


if TYPE_CHECKING:
from typing import Any, Literal


def spacegroup_bar(
data: Sequence[int | str | Structure] | pd.Series,
*,
Expand Down
4 changes: 3 additions & 1 deletion pymatviz/cumulative.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@

from __future__ import annotations

from typing import TYPE_CHECKING, Any
from typing import TYPE_CHECKING

import matplotlib.pyplot as plt
import numpy as np


if TYPE_CHECKING:
from typing import Any

from numpy.typing import ArrayLike


Expand Down
5 changes: 4 additions & 1 deletion pymatviz/enums.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,11 @@


if TYPE_CHECKING:
from typing import Any, Self
from typing import Any

from typing_extensions import Self

# TODO: remove following definition of StrEnum once Python 3.11+
if sys.version_info >= (3, 11):
from enum import StrEnum
else:
Expand Down
10 changes: 7 additions & 3 deletions pymatviz/histogram.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@

from __future__ import annotations

from typing import TYPE_CHECKING, Any, Literal
import warnings
from typing import TYPE_CHECKING

import matplotlib.pyplot as plt
import numpy as np
Expand All @@ -17,15 +18,18 @@

if TYPE_CHECKING:
from collections.abc import Sequence
from typing import Any, Literal

from pymatviz.utils import ElemValues


def spacegroup_hist(*args: Any, **kwargs: Any) -> plt.Axes | go.Figure:
"""Alias for spacegroup_bar."""
print( # noqa: T201
warnings.warn(
"spacegroup_hist() is deprecated and will be removed in a future version. "
"use pymatviz.bar.spacegroup_bar() instead."
"use pymatviz.bar.spacegroup_bar() instead.",
category=DeprecationWarning,
stacklevel=2,
)
return spacegroup_bar(*args, **kwargs)

Expand Down
15 changes: 11 additions & 4 deletions pymatviz/io.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,11 @@
import copy
import os
import subprocess
import warnings
from pathlib import Path
from shutil import which
from time import sleep
from typing import TYPE_CHECKING, Any, Final, Literal
from typing import TYPE_CHECKING

import matplotlib.pyplot as plt
import numpy as np
Expand All @@ -26,6 +27,7 @@
if TYPE_CHECKING:
from collections.abc import Callable, Sequence
from pathlib import Path
from typing import Any, Final, Literal

import pandas as pd
from pandas.io.formats.style import Styler
Expand Down Expand Up @@ -313,7 +315,10 @@ def normalize_and_crop_pdf(
if on_gs_not_found == "ignore":
return
if on_gs_not_found == "warn":
print("Ghostscript not found, skipping PDF normalization and cropping") # noqa: T201
warnings.warn(
"Ghostscript not found, skipping PDF normalization and cropping",
stacklevel=2,
)
return
raise RuntimeError("Ghostscript not found in PATH")
try:
Expand All @@ -337,7 +342,7 @@ def normalize_and_crop_pdf(
)

if stderr:
print(f"pdfCropMargins {stderr=}") # noqa: T201
warnings.warn(f"pdfCropMargins {stderr=}", stacklevel=2)
# something went wrong, remove the cropped PDF
os.remove(cropped_file_path)
else:
Expand Down Expand Up @@ -643,6 +648,8 @@ def print_table(
[svgo, "--multipass", "--final-newline", str(file_path)], check=True
)
else:
print("svgo not found in PATH. SVG compression skipped.") # noqa: T201
warnings.warn(
"svgo not found in PATH. SVG compression skipped.", stacklevel=2
)

return fig
30 changes: 17 additions & 13 deletions pymatviz/phonons.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

import sys
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, Literal, get_args, no_type_check
from typing import TYPE_CHECKING, Literal, get_args

import plotly.express as px
import plotly.graph_objects as go
Expand All @@ -18,12 +18,16 @@

if TYPE_CHECKING:
from collections.abc import Sequence
from typing import Any, TypeAlias

import numpy as np
from pymatgen.core import Structure
from typing_extensions import Self

AnyBandStructure = BandStructureSymmLine | PhononBands
AnyBandStructure: TypeAlias = BandStructureSymmLine | PhononBands
YMin: TypeAlias = float | Literal["y_min"]
YMax: TypeAlias = float | Literal["y_max"]
BranchMode: TypeAlias = Literal["union", "intersection"]


@dataclass
Expand Down Expand Up @@ -121,21 +125,22 @@ def get_band_xaxis_ticks(
return ticks_x_pos, tick_labels


YMin = float | Literal["y_min"]
YMax = float | Literal["y_max"]


@no_type_check
def _shaded_range(
fig: go.Figure, shaded_ys: dict[tuple[YMin, YMax], dict[str, Any]] | bool | None
fig: go.Figure,
shaded_ys: dict[tuple[YMin | YMax, YMin | YMax], dict[str, Any]] | bool | None,
) -> go.Figure:
if shaded_ys is False:
return fig

shade_defaults = dict(layer="below", row="all", col="all")
y_lim = dict(zip(("y_min", "y_max"), fig.layout.yaxis.range, strict=True))
y_lim: dict[float | Literal["y_min", "y_max"], Any] = dict(
zip(("y_min", "y_max"), fig.layout.yaxis.range, strict=True),
)

shaded_ys = shaded_ys or {(0, "y_min"): dict(fillcolor="gray", opacity=0.07)}
if not isinstance(shaded_ys, dict):
raise TypeError(f"expect shaded_ys as dict, got {type(shaded_ys).__name__}")

for (y0, y1), kwds in shaded_ys.items():
for y_val in (y0, y1):
if isinstance(y_val, str) and y_val not in y_lim:
Expand All @@ -147,15 +152,14 @@ def _shaded_range(
return fig


BranchMode = Literal["union", "intersection"]


def phonon_bands(
band_structs: PhononBands | dict[str, PhononBands],
line_kwargs: dict[str, Any] | None = None,
branches: Sequence[str] = (),
branch_mode: BranchMode = "union",
shaded_ys: dict[tuple[YMin, YMax], dict[str, Any]] | bool | None = None,
shaded_ys: dict[tuple[YMin | YMax, YMin | YMax], dict[str, Any]]
| bool
| None = None,
**kwargs: Any,
) -> go.Figure:
"""Plot single or multiple pymatgen band structures using Plotly, focusing on the
Expand Down
8 changes: 5 additions & 3 deletions pymatviz/powerups/both.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from __future__ import annotations

import warnings
from typing import TYPE_CHECKING, Any

import matplotlib.pyplot as plt
Expand Down Expand Up @@ -177,7 +178,7 @@ def add_identity_line(
xy_min_min = min(x_min, y_min)
xy_max_min = min(x_max, y_max)

if fig._grid_ref is not None: # noqa: SLF001
if fig._grid_ref is not None:
kwargs.setdefault("row", "all")
kwargs.setdefault("col", "all")

Expand Down Expand Up @@ -264,10 +265,11 @@ def add_best_fit_line(
if n_traces > 1 and warn and not is_faceted:
# for a faceted plot, multiple traces are expected so doesn't make sense to
# warn even if user may have wanted to specify trace_idx. we can't know
print( # noqa: T201
warnings.warn(
f"add_best_fit_line Warning: {trace_idx=} but figure has {n_traces}"
" traces, defaulting to trace_idx=0. Check fig.data[0] to make sure"
" this is the expected trace."
" this is the expected trace.",
stacklevel=2,
)
trace_idx = 0

Expand Down
4 changes: 2 additions & 2 deletions pymatviz/powerups/plotly.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ def add_ecdf_line(
ecdf_trace = px.ecdf(values).data[0]

# if fig has facets, add ECDF to all subplots
fig_add_trace_defaults = {} if fig._grid_ref is None else dict(row="all", col="all") # noqa: SLF001
fig_add_trace_defaults = {} if fig._grid_ref is None else dict(row="all", col="all")
fig.add_trace(ecdf_trace, **fig_add_trace_defaults | kwargs)

# get xlabel falling back on 'x' if not set
Expand Down Expand Up @@ -129,7 +129,7 @@ def add_ecdf_line(
yaxis2_layout = getattr(fig.layout, "yaxis2", {})
if yaxis2_layout:
# convert to dict
yaxis2_layout = yaxis2_layout._props # type: ignore[union-attr] # noqa: SLF001
yaxis2_layout = yaxis2_layout._props # type: ignore[union-attr]
fig.layout.yaxis2 = yaxis_defaults | yaxis2_layout

return fig
Expand Down
4 changes: 2 additions & 2 deletions pymatviz/ptable/_process_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

import warnings
from collections.abc import Iterable, Sequence
from typing import TYPE_CHECKING, Literal, TypeAlias, get_args
from typing import TYPE_CHECKING, get_args

import numpy as np
import pandas as pd
Expand All @@ -15,7 +15,7 @@

if TYPE_CHECKING:
from collections.abc import Callable
from typing import Any
from typing import Any, Literal, TypeAlias

from numpy.typing import NDArray

Expand Down
4 changes: 3 additions & 1 deletion pymatviz/sankey.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,14 @@

from __future__ import annotations

from typing import TYPE_CHECKING, Any, Literal
from typing import TYPE_CHECKING

import plotly.graph_objects as go


if TYPE_CHECKING:
from typing import Any, Literal

import pandas as pd


Expand Down
Loading
Loading