Skip to content

Commit

Permalink
🔧 Devops: Switch to ruff for linting/formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
mbercx authored Oct 18, 2024
1 parent cf00438 commit f447512
Show file tree
Hide file tree
Showing 11 changed files with 259 additions and 226 deletions.
8 changes: 6 additions & 2 deletions .github/workflows/validate_release_tag.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# -*- coding: utf-8 -*-
"""Validate that the version in the tag label matches the version of the package."""

import argparse
import ast
from pathlib import Path
Expand All @@ -17,8 +18,11 @@ def get_version_from_module(content: str) -> str:

try:
return next(
ast.literal_eval(statement.value) for statement in module.body if isinstance(statement, ast.Assign)
for target in statement.targets if isinstance(target, ast.Name) and target.id == '__version__'
ast.literal_eval(statement.value)
for statement in module.body
if isinstance(statement, ast.Assign)
for target in statement.targets
if isinstance(target, ast.Name) and target.id == '__version__'
)
except StopIteration as exception:
raise IOError('Unable to find the `__version__` attribute in the module.') from exception
Expand Down
43 changes: 9 additions & 34 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -1,50 +1,25 @@
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: 'v4.2.0'
rev: v4.2.0
hooks:
- id: double-quote-string-fixer
- id: end-of-file-fixer
- id: fix-encoding-pragma
- id: mixed-line-ending
- id: trailing-whitespace

- repo: https://github.com/ikamensh/flynt/
rev: '0.76'
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.5.5
hooks:
- id: flynt
- id: ruff
args: [ --fix ]
- id: ruff-format

- repo: https://github.com/pycqa/isort
rev: '5.12.0'
- repo: https://github.com/pre-commit/mirrors-mypy
rev: 'v1.11.0'
hooks:
- id: isort

- repo: https://github.com/pre-commit/mirrors-yapf
rev: 'v0.32.0'
hooks:
- id: yapf
name: yapf
- id: mypy
types: [python]
args: ['-i']
additional_dependencies: ['toml']

- repo: local
hooks:
- id: mypy
name: mypy
entry: mypy
args: [--config-file=pyproject.toml]
language: python
types: [python]
require_serial: true
pass_filenames: true
files: >-
(?x)^(
src/.*py|
)$
- id: pylint
name: pylint
entry: pylint
language: system
types: [python]
exclude: "^(doc/)|(.utils/)"
64 changes: 12 additions & 52 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,9 @@ Source = 'https://github.com/aiidateam/qe-tools'
[project.optional-dependencies]
dev = [
'codecov',
'mypy==0.930',
'mypy~=1.11',
'pre-commit',
'timeout-decorator',
'pylint~=2.16.0',
'pytest~=7.0',
'pytest-cov',
'pytest-cases~=3.2',
Expand All @@ -60,10 +59,6 @@ exclude = [
'.pre-commit-config.yaml',
]

[tool.flynt]
line-length = 120
fail-on-change = true

[tool.isort]
force_sort_within_sections = true
include_trailing_comma = true
Expand All @@ -78,54 +73,28 @@ warn_unused_ignores = true
warn_redundant_casts = true
no_warn_no_return = true
show_traceback = true

[[tool.mypy.overrides]]
module = 'qe_tools.*'
follow_imports = 'skip'
check_untyped_defs = true

[[tool.mypy.overrides]]
module = [
'scipy.*',
'numpy.*'
]
ignore_errors = true
ignore_missing_imports = true

[tool.pylint.format]
max-line-length = 120
[tool.ruff]
line-length = 120
indent-width = 4
target-version = "py38"

[tool.pylint.basic]
good-names = [
'a',
'b',
'c',
'e',
'f',
'i',
'i',
'j',
'k',
's',
'u',
'v',
'tx',
'ty',
'tz',
'v1',
'v2',
[tool.ruff.lint]
ignore = [
'E731'
]


[tool.pylint.messages_control]
disable = [
'fixme',
'import-error',
'missing-function-docstring',
'missing-module-docstring',
'too-few-public-methods',
'too-many-public-methods',
'use-dict-literal',
'unnecessary-lambda-assignment',
]
[tool.ruff.format]
quote-style = 'single'

[tool.pytest.ini_options]
testpaths = [
Expand All @@ -134,12 +103,3 @@ testpaths = [
filterwarnings = [
'ignore:WARNING the new order is not taken into account !!:UserWarning',
]

[tool.yapf]
align_closing_bracket_with_visual_indent = true
based_on_style = 'google'
coalesce_brackets = true
column_limit = 120
dedent_closing_brackets = true
indent_dictionary_value = false
split_arguments_when_comma_terminated = true
1 change: 1 addition & 0 deletions src/qe_tools/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# -*- coding: utf-8 -*-
"""A set of useful tools to manage Quantum ESPRESSO files."""

from ._constants import DEFAULT as CONSTANTS # isort:skip
from . import converters, exceptions, parsers, extractors # isort:skip

Expand Down
13 changes: 6 additions & 7 deletions src/qe_tools/_constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,14 @@
## These have been put here from the one of QE, taken directly from
## those in aiida.common.constants
bohr_to_ang=0.52917720859,
ang_to_m=1.e-10,
ang_to_m=1.0e-10,
ry_to_ev=13.6056917253,
ry_si=4.35974394 / 2. * 10**(-18),
ry_si=4.35974394 / 2.0 * 10 ** (-18),
timeau_to_sec=2.418884326155573e-17,
invcm_to_THz=0.0299792458,

## Values taken from https://gitlab.com/QEF/q-e/-/blob/develop/Modules/constants.f90
ha_si=4.3597447222071e-18, # J
bohr_si=0.529177210903e-10, # m
ha_si=4.3597447222071e-18, # J
bohr_si=0.529177210903e-10, # m
# From the definition of Quantum ESPRESSO, conversion from atomic mass
# units to Rydberg units:
# REAL(DP), PARAMETER :: AMU_SI = 1.660538782E-27_DP ! Kg
Expand All @@ -35,6 +34,6 @@
amu_Ry=911.4442421323,
)

DEFAULT.hartree_to_ev = DEFAULT.ry_to_ev * 2.
DEFAULT.hartree_to_ev = DEFAULT.ry_to_ev * 2.0
DEFAULT.bohr_si = DEFAULT.bohr_to_ang * DEFAULT.ang_to_m
DEFAULT.au_gpa = DEFAULT.ha_si / (DEFAULT.bohr_si**3.) / 1.0e9
DEFAULT.au_gpa = DEFAULT.ha_si / (DEFAULT.bohr_si**3.0) / 1.0e9
3 changes: 2 additions & 1 deletion src/qe_tools/_qe_version.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ class _LatestVersionImpl:
The object is implemented as a singleton, meaning it can only be
instantiated once.
"""

__instance_count = 0

def __init__(self):
Expand All @@ -40,7 +41,7 @@ def __gt__(self, other):


def parse_version(
qe_version: Optional[Union[str, _LatestVersionImpl, Version]] = None
qe_version: Optional[Union[str, _LatestVersionImpl, Version]] = None,
) -> Union[_LatestVersionImpl, Version]:
"""Parse the QE version string to a comparable object.
Expand Down
27 changes: 19 additions & 8 deletions src/qe_tools/converters/_structure.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

__all__ = ('get_parameters_from_cell',)

from typing import Dict, Iterable, Optional, Union
from typing import Dict, Iterable, Optional

import numpy as np
import scipy.linalg as la
Expand All @@ -20,7 +20,7 @@ def get_parameters_from_cell(
cell: CellT,
tolerance: float = 1e-4,
using_celldm: bool = False,
qe_version: Optional[str] = None
qe_version: Optional[str] = None,
) -> ParametersT:
"""
Get the cell parameters from a given `ibrav` and cell. Only the
Expand Down Expand Up @@ -67,7 +67,13 @@ def get_parameters_from_cell(

parameters = _get_parameters_from_cell_bare(ibrav=ibrav, cell=cell)

_check_parameters(ibrav=ibrav, cell=cell, parameters=parameters, tolerance=tolerance, qe_version=qe_version)
_check_parameters(
ibrav=ibrav,
cell=cell,
parameters=parameters,
tolerance=tolerance,
qe_version=qe_version,
)

if using_celldm:
parameters = _convert_to_celldm(parameters, ibrav=ibrav)
Expand Down Expand Up @@ -98,7 +104,7 @@ def _get_parameters_from_cell_bare( # pylint: disable=too-many-branches
parameters = {A: la.norm(v1), C: la.norm(v3)}
elif ibrav in [5, -5]:
parameters = {A: la.norm(v1)}
parameters[cosAB] = np.dot(v1, v2) / parameters[A]**2
parameters[cosAB] = np.dot(v1, v2) / parameters[A] ** 2
elif ibrav == 6:
parameters = {A: la.norm(v1), C: la.norm(v3)}
elif ibrav == 7:
Expand Down Expand Up @@ -136,20 +142,25 @@ def _get_parameters_from_cell_bare( # pylint: disable=too-many-branches


def _check_parameters(
*, ibrav: int, parameters: ParametersT, cell: CellT, tolerance: float, qe_version: Optional[str] = None
*,
ibrav: int,
parameters: ParametersT,
cell: CellT,
tolerance: float,
qe_version: Optional[str] = None,
) -> None:
"""
Check that the parameters describe the given cell.
"""
system_dict = {'ibrav': ibrav, **parameters} # type: Dict[str, Union[int, float]]
system_dict = {'ibrav': ibrav, **parameters}
cell_reconstructed = _get_cell_from_parameters(
cell_parameters=None, # this is only used for ibrav=0
system_dict=system_dict,
alat=parameters['a'],
using_celldm=False,
qe_version=qe_version
qe_version=qe_version,
)
if not np.allclose(cell_reconstructed, cell, rtol=0, atol=tolerance): # type: ignore[arg-type]
if not np.allclose(cell_reconstructed, cell, rtol=0, atol=tolerance):
raise ValueError(
f'The cell {cell_reconstructed} constructed with ibrav={ibrav}, parameters={parameters} does not match '
f'the input cell{cell}.'
Expand Down
Loading

0 comments on commit f447512

Please sign in to comment.