Skip to content

Commit

Permalink
🧰👌 Switch tooling to ruff (#197)
Browse files Browse the repository at this point in the history
This PR updates the tooling to use
[ruff](https://github.com/astral-sh/ruff) instead of multiple tools

Have a look at the [ruff docs for an explanation of all the
rules](https://beta.ruff.rs/docs/rules/)

### Change summary

- 🧰✨ Added docformatter to pre-commit
- 🧹 Formatted docstrings
- 🧰👌 Replaced darglint with pydoclint
- 🩹 Fixed docstring issues
- 🧰✨ Added actionlint to pre-commit
- 🧰👌 Replaced flake8 with ruff 
- 👌 Activated D ruff rule and fixed violations 
- 👌 Fix E741 (Ambiguous variable name: l) Error
- 👌 Activated YTT, BLE, C4, T10, FA, ISC, INP, PIE, RSE, RET, ARG, PTH,…
- 👌 Activated RUF ruff rule and fixed violations
- 👌 Activated ERA ruff rule and fixed violations
- 👌 Activated EM ruff rule and fixed violations
- 👌 Activated PD ruff rule and fixed violations
- 👌 Activated SIM ruff rule and fixed violations
- 👌 Activated TCH ruff rule and fixed violations
- 👌 Activated T20 ruff rule and fixed violations
- 👌 Activated PT ruff rule and fixed violations
- 👌 Activated PGH ruff rule and fixed violations
- 👌 Activated N ruff rule and fixed violations
- 👌 Activated B ruff rule and fixed violations
- 👌 Activated UP ruff rule, fixed violations and removed pyupgrade hook
- 🧹 Removed yesqa hook since this is handeled by RUF007 
- 🧰 Pin and update pydoclint
- 🧹 Updated pre-commit config and fixed issues
- 🧰⬆️ Update pydoclint from 0.0.10 to 0.0.16 and fixed issues
- 🩹🧪 Fix exception test to use new typing syntax
- 🧹 Use modern typing after rebase
- 🧰⬆️ Update pre-commit config to use latest versions
- 📚👌 Added ruff and isort badges to readme
- 🚇 Add py311 to CI unittest matrix

### Checklist

- [x] ✔️ Passing the tests (mandatory for all PR's)
  • Loading branch information
s-weigand authored Aug 9, 2023
1 parent 1833b22 commit 60b74fe
Show file tree
Hide file tree
Showing 36 changed files with 524 additions and 398 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ jobs:
strategy:
matrix:
os: [ubuntu-latest, windows-latest, macOS-latest]
python-version: ["3.10"]
python-version: ["3.10", "3.11"]

steps:
- name: Check out repo
Expand Down
57 changes: 33 additions & 24 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -15,19 +15,25 @@ repos:
- id: fix-encoding-pragma
args: [--remove]

- repo: https://github.com/PyCQA/docformatter
rev: v1.7.5
hooks:
- id: docformatter
additional_dependencies: [tomli]
args: [--in-place, --config, ./pyproject.toml]

- repo: https://github.com/tox-dev/pyproject-fmt
rev: "0.13.0"
hooks:
- id: pyproject-fmt

- repo: https://github.com/MarcoGorelli/absolufy-imports
rev: v0.3.1
hooks:
- id: absolufy-imports

- repo: https://github.com/asottile/pyupgrade
rev: v3.8.0
hooks:
- id: pyupgrade
args: [--py38-plus]

- repo: https://github.com/psf/black
rev: 23.3.0
rev: 23.7.0
hooks:
- id: black
language_version: python3
Expand All @@ -38,19 +44,13 @@ repos:
- id: isort
minimum_pre_commit_version: 2.9.0

- repo: https://github.com/asottile/yesqa
rev: v1.5.0
hooks:
- id: yesqa
additional_dependencies: [flake8-docstrings, darglint==1.8.0]

- repo: https://github.com/asottile/setup-cfg-fmt
rev: v2.4.0
hooks:
- id: setup-cfg-fmt

- repo: https://github.com/pre-commit/mirrors-prettier
rev: v3.0.0-alpha.9-for-vscode # Use the sha or tag you want to point at
rev: v3.0.1 # Use the sha or tag you want to point at
hooks:
- id: prettier

Expand All @@ -65,15 +65,15 @@ repos:
rev: 1.7.0
hooks:
- id: nbqa-black
additional_dependencies: [black==22.6.0]
additional_dependencies: [black==23.7.0]
args: [--nbqa-mutate]
- id: nbqa-pyupgrade
additional_dependencies: [pyupgrade==2.37.2]
args: [--nbqa-mutate, --py38-plus]
- id: nbqa-flake8
- id: nbqa-check-ast
- id: nbqa-isort
additional_dependencies: [isort==5.10.1]
additional_dependencies: [isort==5.12.0]
args: [--nbqa-mutate]

# Linters
Expand All @@ -93,23 +93,27 @@ repos:
pass_filenames: false
additional_dependencies: [click<8]

- repo: https://github.com/PyCQA/flake8
rev: 6.0.0
- repo: https://github.com/astral-sh/ruff-pre-commit
# Ruff version.
rev: v0.0.282
hooks:
- id: flake8
args:
- "--max-line-length=99"
- id: ruff

- repo: https://github.com/PyCQA/flake8
rev: 6.0.0
rev: 6.1.0
hooks:
- id: flake8
alias: flake8-docs
args:
- "--select=D,DAR"
- "--select=DOC"
- "--extend-ignore=DOC502"
- "--color=always"
- "--require-return-section-when-returning-none=False"
- "--allow-init-docstring=True"
- "--skip-checking-short-docstrings=False"
name: "flake8 lint docstrings"
exclude: "^(docs/|setup.py$|tests?/)"
additional_dependencies: [flake8-docstrings, darglint==1.8.0]
additional_dependencies: [pydoclint==0.1.4]

- repo: https://github.com/rstcheck/rstcheck
rev: "v6.1.2"
Expand All @@ -130,3 +134,8 @@ repos:
types: [file]
types_or: [python, pyi, markdown, rst, jupyter]
args: ["--ignore-words-list=doas"]

- repo: https://github.com/rhysd/actionlint
rev: "v1.6.25"
hooks:
- id: actionlint
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@
[![Documentation Status](https://readthedocs.org/projects/pyglotaran-extras/badge/?version=latest)](https://pyglotaran-extras.readthedocs.io/en/latest/?badge=latest)
[![Binder](https://static.mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/glotaran/pyglotaran-extras.git/main?urlpath=lab%2Ftree%2Fdocs%2Fsource%2Fnotebooks)

[![codecov](https://codecov.io/gh/glotaran/pyglotaran-extras/branch/main/graph/badge.svg?token=I6F412Y390)](https://codecov.io/gh/glotaran/pyglotaran-extras)
[![Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff)
[![Code style Python: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)
[![Imports: isort](https://img.shields.io/badge/%20imports-isort-%231674b1?style=flat&labelColor=ef8336)](https://pycqa.github.io/isort/)
[![codecov](https://codecov.io/gh/glotaran/pyglotaran-extras/branch/main/graph/badge.svg?token=I6F412Y390)](https://codecov.io/gh/glotaran/pyglotaran-extras)
[![Discord](https://img.shields.io/discord/883443835135475753.svg?label=&logo=discord&logoColor=ffffff&color=7389D8&labelColor=6A7EC2)](https://discord.gg/KfnEYRSTJx)

Supplementary package for pyglotaran with (example) plotting code for use with the pyglotaran package.
Expand Down
14 changes: 6 additions & 8 deletions pyglotaran_extras/deprecation/deprecation_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
)


class OverDueDeprecation(Exception):
class OverDueDeprecationError(Exception):
"""Error thrown when a deprecation should have been removed.
See Also
Expand Down Expand Up @@ -104,11 +104,12 @@ def check_overdue(deprecated_qual_name_usage: str, to_be_removed_in_version: str
parse_version(pyglotaran_extras_version()) >= parse_version(to_be_removed_in_version)
and "dev" not in pyglotaran_extras_version()
):
raise OverDueDeprecation(
f"Support for {deprecated_qual_name_usage.partition('(')[0]!r} was "
f"supposed to be dropped in version: {to_be_removed_in_version!r}.\n"
msg = (
f"Support for {deprecated_qual_name_usage.partition('(')[0]!r} "
f"was supposed to be dropped in version: {to_be_removed_in_version!r}.\n"
f"Current version is: {pyglotaran_extras_version()!r}"
)
raise OverDueDeprecationError(msg)


def warn_deprecated(
Expand All @@ -133,16 +134,13 @@ def warn_deprecated(
to_be_removed_in_version : str
Version the support for this usage will be removed.
stacklevel: int
stacklevel : int
Stack at which the warning should be shown as raise. Default: 2
Raises
------
OverDueDeprecation
If the current version is greater or equal to ``to_be_removed_in_version``.
-- noqa: DAR402
"""
check_overdue(deprecated_qual_name_usage, to_be_removed_in_version)
warn(
Expand Down
41 changes: 23 additions & 18 deletions pyglotaran_extras/inspect/a_matrix.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,21 @@

from __future__ import annotations

from typing import TYPE_CHECKING

import numpy as np
import xarray as xr
from glotaran.utils.ipython import MarkdownStr
from tabulate import tabulate

from pyglotaran_extras.inspect.utils import pretty_format_numerical
from pyglotaran_extras.inspect.utils import pretty_format_numerical_iterable
from pyglotaran_extras.inspect.utils import wrap_in_details_tag
from pyglotaran_extras.io.utils import result_dataset_mapping
from pyglotaran_extras.types import ResultLike

if TYPE_CHECKING:
import xarray as xr

from pyglotaran_extras.types import ResultLike


def a_matrix_to_html_table(
Expand All @@ -25,26 +30,26 @@ def a_matrix_to_html_table(
Parameters
----------
a_matrix: xr.DataArray
a_matrix : xr.DataArray
DataArray containing the a-matrix values and coordinates.
megacomplex_suffix: str
megacomplex_suffix : str
Megacomplex suffix used for the a-matrix data variable and coordinate names.
normalize_initial_concentration: bool
normalize_initial_concentration : bool
Whether or not to normalize the initial concentration. Defaults to False.
decimal_places: int
decimal_places : int
Decimal places to display. Defaults to 3.
Returns
-------
str
Multi header HTML table representing the a-matrix.
"""
species = a_matrix.coords[f"species_{megacomplex_suffix}"].values
species = a_matrix.coords[f"species_{megacomplex_suffix}"].to_numpy()
# Crete a copy so normalization does not mutate the original values
initial_concentration = np.array(
a_matrix.coords[f"initial_concentration_{megacomplex_suffix}"].values
a_matrix.coords[f"initial_concentration_{megacomplex_suffix}"].to_numpy()
)
lifetime = a_matrix.coords[f"lifetime_{megacomplex_suffix}"].values
lifetime = a_matrix.coords[f"lifetime_{megacomplex_suffix}"].to_numpy()

if normalize_initial_concentration is True:
initial_concentration /= initial_concentration.sum()
Expand All @@ -53,7 +58,7 @@ def a_matrix_to_html_table(
["species<br>initial concentration<br>lifetime↓"]
+ [
f"{sp}<br>{pretty_format_numerical(ic,decimal_places)}<br>&nbsp;"
for sp, ic in zip(species, initial_concentration)
for sp, ic in zip(species, initial_concentration, strict=True)
]
+ ["Sum"]
)
Expand All @@ -62,11 +67,11 @@ def a_matrix_to_html_table(
pretty_format_numerical_iterable(
(lifetime, *amps, amps.sum()), decimal_places=decimal_places
)
for lifetime, amps in zip(lifetime, a_matrix.values)
for lifetime, amps in zip(lifetime, a_matrix.values, strict=True)
]
data.append(
pretty_format_numerical_iterable(
("Sum", *a_matrix.values.sum(axis=0), a_matrix.values.sum()),
("Sum", *a_matrix.to_numpy().sum(axis=0), a_matrix.to_numpy().sum()),
decimal_places=decimal_places,
)
)
Expand Down Expand Up @@ -96,18 +101,18 @@ def show_a_matrixes(
Parameters
----------
result: ResultLike
result : ResultLike
Result or result dataset.
normalize_initial_concentration: bool
normalize_initial_concentration : bool
Whether or not to normalize the initial concentration. Defaults to False.
decimal_places: int
decimal_places : int
Decimal places to display. Defaults to 3.
a_matrix_min_size: int
a_matrix_min_size : int | None
Defaults to None.
expanded_datasets: tuple[str, ...]
expanded_datasets : tuple[str, ...]
Names of dataset to expand the details view for. Defaults to empty tuple () which means no
dataset is expanded.
heading_offset: int
heading_offset : int
Number of heading level to offset the headings. Defaults to 2 which means that the
first/top most heading is h3.
Expand Down
25 changes: 14 additions & 11 deletions pyglotaran_extras/inspect/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,14 @@

from __future__ import annotations

from collections.abc import Generator
from collections.abc import Iterable
from typing import TYPE_CHECKING

import numpy as np

if TYPE_CHECKING:
from collections.abc import Generator
from collections.abc import Iterable


def wrap_in_details_tag(
details_content: str,
Expand All @@ -19,13 +22,13 @@ def wrap_in_details_tag(
Parameters
----------
details_content: str
details_content : str
Markdown string that should be displayed when the details are expanded.
summary_content: str | None
summary_content : str | None
Summary test that should be displayed. Defaults to None so the summary is ``Details``.
summary_heading_level: int | None
summary_heading_level : int | None
Level of the heading wrapping the ``summary`` if it is not None. Defaults to None.
is_open: bool
is_open : bool
Whether or not the details tag should be initially opened. Defaults to False.
Returns
Expand Down Expand Up @@ -55,14 +58,14 @@ def pretty_format_numerical(value: float | int, decimal_places: int = 1) -> str:
Used to format values like the t-value.
TODO: remove after raise pyglotaran dependency to 0.7.0
TODO : remove after raise pyglotaran dependency to 0.7.0
Forward port of https://github.com/glotaran/pyglotaran/pull/1192
Parameters
----------
value: float | int
value : float | int
Numerical value to format.
decimal_places: int
decimal_places : int
Decimal places to display. Defaults to 1.
Returns
Expand Down Expand Up @@ -93,9 +96,9 @@ def pretty_format_numerical_iterable(
Parameters
----------
input_values: Iterable[str | float]
input_values : Iterable[str | float]
Values that should be formatted.
decimal_places: int | None
decimal_places : int | None
Number of decimal places a value should have, if None the original value will be used.
Defaults to 3.
Expand Down
9 changes: 5 additions & 4 deletions pyglotaran_extras/io/load_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,10 @@ def load_data(
----------
result : DatasetConvertible | Result
Result class instance, xarray Dataset or path to a dataset file.
dataset_name : str, optional
dataset_name : str | None
Name of a specific dataset contained in ``result``, if not provided
the first dataset will be extracted. Defaults to None.
_stacklevel: int
_stacklevel : int
Stacklevel of the warning which is raised when ``result`` is of class ``Result``,
contains multiple datasets and no ``dataset_name`` is provided. Changing this value is
only required if you use this function inside of another function. Defaults to 2
Expand Down Expand Up @@ -56,6 +56,7 @@ def load_data(
stacklevel=_stacklevel,
)
return result.data[keys[0]]
if isinstance(result, (str, Path)):
if isinstance(result, str | Path):
return load_data(load_dataset(result))
raise TypeError(f"Result needs to be of type {DatasetConvertible!r}, but was {result!r}.")
msg = f"Result needs to be of type {DatasetConvertible!r}, but was {result!r}."
raise TypeError(msg)
Loading

0 comments on commit 60b74fe

Please sign in to comment.