Skip to content

Commit

Permalink
Add autodoc typehints; enable ruff pydocstyle (#170)
Browse files Browse the repository at this point in the history
Fixes #169
  • Loading branch information
oerc0122 authored Oct 9, 2024
1 parent 5899c35 commit f97ebc4
Show file tree
Hide file tree
Showing 32 changed files with 386 additions and 368 deletions.
4 changes: 1 addition & 3 deletions castep_outputs/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
"""
Module to parse miscellaneous castep files
"""
"""Module to parse miscellaneous castep files."""

__author__ = "Jacob Wilkins"
__version__ = "0.1.7"
Expand Down
4 changes: 1 addition & 3 deletions castep_outputs/__main__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
"""
Run main castep parser.
"""
"""Run main castep parser."""

from .cli.castep_outputs_main import main

Expand Down
8 changes: 3 additions & 5 deletions castep_outputs/cli/args.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
"""
Module containing argument parser and processing.
"""
"""Module containing argument parser and processing."""
from __future__ import annotations

import argparse
Expand Down Expand Up @@ -53,7 +51,7 @@ def parse_args(to_parse: Sequence[str] = ()) -> argparse.Namespace:
Parameters
----------
to_parse : Sequence[str]
to_parse
Arguments to handle in this call.
Returns
Expand Down Expand Up @@ -101,7 +99,7 @@ def extract_parsables(args: argparse.Namespace) -> dict[str, list[str]]:
Parameters
----------
args : argparse.Namespace
args
Namespace to process.
Returns
Expand Down
28 changes: 12 additions & 16 deletions castep_outputs/cli/castep_outputs_main.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
"""
Main castep parser access routines.
"""
"""Main castep parser access routines."""
from __future__ import annotations

import io
Expand Down Expand Up @@ -28,15 +26,15 @@ def parse_single(in_file: str | Path | TextIO,
Parameters
----------
in_file : str or Path or TextIO
in_file
Input file to parse.
parser : Parser, optional
parser
Castep parser to use. If `None` will be determined from extension.
out_format : OutFormats, optional
out_format
Format to dump as.
loglevel : int, optional
loglevel
Logging level.
testing : bool, optional
testing
Whether used for test suite (disable processing fragile properties).
Returns
Expand Down Expand Up @@ -99,15 +97,15 @@ def parse_all(
Parameters
----------
output : str or Path or TextIO
output
Filepath or handle to dump output to.
out_format : OutFormats
out_format
Format to dump as.
loglevel : int, optional
loglevel
Logging level.
testing : bool, optional
testing
Whether used for test suite (disable processing fragile properties).
**files : dict[str, Sequence[Path]]
**files
Dictionary of {parser needed: Sequence of paths to parse}.
"""
file_dumper = get_dumpers(out_format)
Expand All @@ -132,9 +130,7 @@ def parse_all(


def main():
"""
Run the main program from command line.
"""
"""Run the main program from command line."""
args = parse_args()
dict_args = extract_parsables(args)

Expand Down
4 changes: 1 addition & 3 deletions castep_outputs/parsers/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
"""
List of parsers for file formats.
"""
"""List of parsers for file formats."""
from __future__ import annotations

from collections.abc import Callable
Expand Down
19 changes: 6 additions & 13 deletions castep_outputs/parsers/bands_file_parser.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,4 @@
"""
Parse the following castep outputs:
- .bands
"""
"""Parse castep .bands files."""
from __future__ import annotations

import re
Expand All @@ -17,9 +13,8 @@


class BandsQData(TypedDict, total=False):
"""
Per k-point info of band.
"""
"""Per k-point info of band."""

#: List of band eigenvalues.
band: ThreeVector
#: List of eigenvalues for up component of band.
Expand All @@ -35,9 +30,8 @@ class BandsQData(TypedDict, total=False):


class BandsFileInfo(TypedDict, total=False):
"""
Bands eigenvalue info of a bands calculation.
"""
"""Bands eigenvalue info of a bands calculation."""

#: Bands info in file.
bands: list[BandsQData]

Expand All @@ -48,15 +42,14 @@ def parse_bands_file(bands_file: TextIO) -> BandsFileInfo:
Parameters
----------
bands_file : ~typing.TextIO
bands_file
Open handle to file to parse.
Returns
-------
BandsFileInfo
Parsed info.
"""

bands_info: BandsFileInfo = defaultdict(list)
qdata = {}

Expand Down
58 changes: 37 additions & 21 deletions castep_outputs/parsers/castep_file_parser.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
# pylint: disable=too-many-lines, too-many-branches, too-many-statements, too-many-locals
"""
Extract results from .castep file for comparison and further processing
Extract results from .castep file for comparison and further processing.
Notes
-----
Port of extract_results.pl
"""
from __future__ import annotations
Expand Down Expand Up @@ -79,9 +81,8 @@


class Filters(Flag):
"""
Enum of possible filters for CASTEP file parsing
"""
"""Enum of possible filters for CASTEP file parsing."""

BS = auto()
CELL = auto()
CHEM_SHIELDING = auto()
Expand Down Expand Up @@ -137,7 +138,26 @@ class Filters(Flag):

def parse_castep_file(castep_file_in: TextIO,
filters: Filters = Filters.HIGH) -> list[dict[str, Any]]:
""" Parse castep file into lists of dicts ready to JSONise """
"""
Parse castep file into lists of dicts ready to JSONise.
Parameters
----------
castep_file_in
File to parse.
filters
Parameters to parse.
Returns
-------
list[dict[str, Any]]
Parsed data.
Raises
------
ValueError
On invalid top-level blocks.
"""
# pylint: disable=redefined-outer-name

runs: list[dict[str, Any]] = []
Expand Down Expand Up @@ -1438,15 +1458,15 @@ def _process_elf(block: Block) -> list[float]:


def _process_hirshfeld(block: Block) -> dict[AtomIndex, float]:
""" Process Hirshfeld block to dict of charges """
"""Process Hirshfeld block to dict of charges."""
return {
atreg_to_index(match): float(match["charge"]) for line in block
if (match := re.match(rf"\s+{REs.ATREG}\s+(?P<charge>{REs.FNUMBER_RE})", line))
}


def _process_thermodynamics(block: Block) -> Thermodynamics:
""" Process a thermodynamics block into a dict of lists """
"""Process a thermodynamics block into a dict of lists."""
accum: Thermodynamics = defaultdict(list)
for line in block:
if "Zero-point energy" in line:
Expand All @@ -1464,7 +1484,7 @@ def _process_thermodynamics(block: Block) -> Thermodynamics:


def _process_atom_disp(block: Block) -> dict[str, dict[AtomIndex, SixVector]]:
""" Process a atom disp block into a dict of lists """
"""Process a atom disp block into a dict of lists."""
accum: dict[str, dict[AtomIndex, SixVector]] = defaultdict(dict)
for line in block:
if match := REs.ATOMIC_DISP_RE.match(line):
Expand All @@ -1479,7 +1499,7 @@ def _process_atom_disp(block: Block) -> dict[str, dict[AtomIndex, SixVector]]:
def _process_3_6_matrix(
block: Block, *, split: bool,
) -> tuple[ThreeByThreeMatrix, ThreeByThreeMatrix | None]:
""" Process a single or pair of 3x3 matrices or 3x6 matrix """
"""Process a single or pair of 3x3 matrices or 3x6 matrix."""
parsed = tuple(to_type(vals, float) for line in block
if (vals := get_numbers(line)) and len(vals) in (3, 6))

Expand All @@ -1494,8 +1514,7 @@ def _process_3_6_matrix(


def _process_params(block: Block) -> dict[str, dict[str, str | tuple[Any, ...]]]:
""" Process a parameters block into a dict of params """

"""Process a parameters block into a dict of params."""
opt: dict[str, Any] = {}
curr_opt: dict[str, str | tuple[Any, ...]] = {}
curr_group = ""
Expand Down Expand Up @@ -1667,7 +1686,7 @@ def _process_stresses(block: Block) -> tuple[str, SixVector]:


def _process_initial_spins(block: Block) -> dict[AtomIndex, InitialSpin]:
""" Process a set of initial spins into appropriate dict """
"""Process a set of initial spins into appropriate dict."""
accum: dict[AtomIndex, InitialSpin] = {}
for line in block:
if match := re.match(rf"\s*\|\s*{REs.ATREG}\s*"
Expand All @@ -1682,8 +1701,7 @@ def _process_initial_spins(block: Block) -> dict[AtomIndex, InitialSpin]:


def _process_born(block: Block) -> dict[AtomIndex, ThreeByThreeMatrix]:
""" Process a Born block into a dict of charges """

"""Process a Born block into a dict of charges."""
born_accum = {}
for line in block:
if match := REs.BORN_RE.match(line):
Expand All @@ -1699,8 +1717,7 @@ def _process_born(block: Block) -> dict[AtomIndex, ThreeByThreeMatrix]:


def _process_raman(block: Block) -> list[RamanReport]:
""" Process a Mulliken block into a list of modes """

"""Process a Mulliken block into a list of modes."""
next(block) # Skip first captured line
modes = []
curr_mode: RamanReport = {}
Expand Down Expand Up @@ -1735,7 +1752,7 @@ def _process_raman(block: Block) -> list[RamanReport]:


def _process_mulliken(block: Block) -> dict[AtomIndex, MullikenInfo]:
""" Process a mulliken block into a dict of points """
"""Process a mulliken block into a dict of points."""
accum = {}

for line in block:
Expand Down Expand Up @@ -1769,7 +1786,7 @@ def _process_mulliken(block: Block) -> dict[AtomIndex, MullikenInfo]:


def _process_band_structure(block: Block) -> list[BandStructure]:
""" Process a band structure into a list of kpts"""
"""Process a band structure into a list of kpts."""

def fdt(qdat):
fix_data_types(qdat, {"spin": int,
Expand Down Expand Up @@ -1802,7 +1819,7 @@ def fdt(qdat):


def _process_qdata(qdata: dict[str, str | list[str]]) -> QData:
""" Special parse for phonon qdata """
"""Parse phonon qdata into components."""
qdata = {key: val
for key, val in qdata.items()
if any(val) or key == "qpt"}
Expand All @@ -1818,8 +1835,7 @@ def _process_qdata(qdata: dict[str, str | list[str]]) -> QData:

def _parse_magres_block(task: int, inp: Block) -> dict[str | AtomIndex,
str | dict[str, float | None]]:
""" Parse MagRes data tables from inp according to task """

"""Parse MagRes data tables from inp according to task."""
data: dict[str | AtomIndex, str | dict[str, float | None]] = {}
data["task"] = REs.MAGRES_TASK[task]
curr_re = REs.MAGRES_RE[task]
Expand Down
Loading

0 comments on commit f97ebc4

Please sign in to comment.