Skip to content

Commit

Permalink
🚨 Remove ruff warnings:
Browse files Browse the repository at this point in the history
   * BLE001
   * ANN001 by setting "Imcomplete" (This is really ad-hoc, but ...)
  • Loading branch information
arafune committed Mar 18, 2024
1 parent 7fa7231 commit e228924
Show file tree
Hide file tree
Showing 17 changed files with 108 additions and 70 deletions.
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ convention = "google"
"nexus_utils.py" = ["ALL"]
"fits_utils.py" = ["ALL"]
"tests/*" = ["PLR2004", "ERA001"]

"resources/*" = ["INP001"]

[tool.mypy]
ignore_missing_imports = true
Expand Down
12 changes: 9 additions & 3 deletions src/arpes/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@

import warnings

import igor

# Use both version conventions for people's sanity.
VERSION = "4.0.0 beta1"
__version__ = VERSION
Expand All @@ -13,6 +15,12 @@
__all__ = ["check", "__version__"]


def _check_igor_version() -> bool:
if igor.__version__ <= "0.3":
raise ValueError
return True


def check() -> None:
"""Verifies certain aspects of the installation and provides guidance broken installations."""

Expand Down Expand Up @@ -42,9 +50,7 @@ def verify_igor_pro() -> str | None:
try:
import igor

if igor.__version__ <= "0.3":
msg = "Not using patched version of igorpy."
raise ValueError(msg)
_check_igor_version()

except ValueError:
return warning_incompatible
Expand Down
20 changes: 13 additions & 7 deletions src/arpes/analysis/band_analysis.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
from arpes.utilities.jupyter import wrap_tqdm

if TYPE_CHECKING:
from collections.abc import Generator
from collections.abc import Generator, Hashable

import lmfit as lf
from _typeshed import Incomplete
Expand Down Expand Up @@ -433,10 +433,12 @@ def fit_bands(
"""Fits bands and determines dispersion in some region of a spectrum.
Args:
arr(xr.DataArray):
arr(xr.DataArray): ARPES data for fit.
band_description: A description of the bands to fit in the region
background
direction
direction: fit direction (along the enegy or momentum),
default is "mdc" (Momentum Distribution Curve).
preferred_k_direction: #TODO: NEED to consider is this is required.
step: if "Initial" is set, ....
Returns:
Fitted bands.
Expand Down Expand Up @@ -543,7 +545,11 @@ def fit_bands(
return band_results, unpacked_bands, residual # Memo bunt_result is xr.DataArray


def _interpolate_intersecting_fragments(coord, coord_index, points):
def _interpolate_intersecting_fragments(
coord: Incomplete,
coord_index: int,
points: Incomplete,
) -> Incomplete:
"""Finds all consecutive pairs of points in `points`.
[TODO:description]
Expand Down Expand Up @@ -581,8 +587,8 @@ def _interpolate_intersecting_fragments(coord, coord_index, points):

def _iterate_marginals(
arr: xr.DataArray,
iterate_directions: list[str] | None = None,
) -> Generator[tuple[xr.DataArray, dict[str, Any], None, None]]:
iterate_directions: list[Hashable] | None = None,
) -> Generator[tuple[xr.DataArray, dict[str, Any]], None, None]:
if iterate_directions is None:
iterate_directions = [str(dim) for dim in arr.dims]
iterate_directions.remove("eV")
Expand Down
12 changes: 6 additions & 6 deletions src/arpes/analysis/mask.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,8 @@ def raw_poly_to_mask(poly: Incomplete) -> dict[str, Incomplete]:

def polys_to_mask(
mask_dict: dict[str, Incomplete],
coords,
shape,
coords: Incomplete,
shape: Incomplete,
radius: float = 0,
*,
invert: bool = False,
Expand All @@ -66,9 +66,9 @@ def polys_to_mask(
waypoints are given in unitful values rather than index values.
Args:
mask_dict
coords
shape
mask_dict:
coords:
shape:
radius (float): Additional margin on the path in coordinates of *points*.
invert (bool):
Expand Down Expand Up @@ -139,7 +139,7 @@ def apply_mask(
data: xr.DataArray,
mask: dict[str, Incomplete],
replace: float = np.nan,
radius=None,
radius: Incomplete = None,
*,
invert: bool = False,
) -> xr.DataArray:
Expand Down
2 changes: 1 addition & 1 deletion src/arpes/corrections/fermi_edge_corrections.py
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ def build_direct_fermi_edge_correction(
others = [d for d in arr.dims if d not in exclude_axes]
edge_fit = broadcast_model(GStepBModel, arr.sum(others).sel(eV=energy_range), along).results

def sieve(_, v) -> bool:
def sieve(_: Incomplete, v: Incomplete) -> bool:
return v.item().params["center"].stderr < 0.001 # noqa: PLR2004

corrections = edge_fit.G.filter_coord(along, sieve).G.map(
Expand Down
2 changes: 1 addition & 1 deletion src/arpes/deep_learning/interpret.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ def items(self) -> list[InterpretationItem]:
def top_losses(self, *, ascending: bool = False) -> list[InterpretationItem]:
"""Orders the items by loss."""

def key(item):
def key(item: Incomplete):
return item.loss if ascending else -item.loss

return sorted(self.items, key=key)
Expand Down
3 changes: 3 additions & 0 deletions src/arpes/endstations/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -939,6 +939,9 @@ def clean_key_name(k: str) -> str:
try:
resized_data = data_for_resize.reshape(column_shape)
except Exception:
logger.exception(
"Found an error in resized_data=data_for_resize.rechape(column_shape)",
)
# sometimes for whatever reason FITS errors and cannot read the data
continue

Expand Down
4 changes: 2 additions & 2 deletions src/arpes/load_pxt.py
Original file line number Diff line number Diff line change
Expand Up @@ -267,8 +267,8 @@ def read_single_pxt(
try:
loaded = igor.load(reference_path, initial_byte_order=try_byte_order)
break
except Exception as err:
logger.info(f"Exception occurs. {err=}, {type(err)=}")
except Exception:
logger.exception("Exception occurs")
else:
loaded = igor.load(reference_path, initial_byte_order=byte_order)
if raw:
Expand Down
5 changes: 2 additions & 3 deletions src/arpes/plotting/basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,5 @@ def make_reference_plots(df: pd.DataFrame, *, with_kspace: bool = False) -> None
pattern="k_{}_norm_kp.png",
)

except Exception as e:
logger.debug(str(e))
warnings.warn(f"Cannot make plots for {index}", stacklevel=2)
except Exception:
logger.exception(f"Cannot make plots for {index}")
18 changes: 7 additions & 11 deletions src/arpes/plotting/bz.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
from __future__ import annotations

import itertools
import warnings
from logging import DEBUG, INFO, Formatter, StreamHandler, getLogger
from typing import TYPE_CHECKING, TypeAlias

Expand Down Expand Up @@ -363,12 +362,9 @@ def bz3d_plot(
try:
from ase.dft.bz import bz_vertices # dynamic because we do not require ase
except ImportError:
warnings.warn(
logger.exception(
"You will need to install ASE (Atomic Simulation Environment) to use this feature.",
stacklevel=2,
)
msg = "You will need to install ASE before using Brillouin Zone plotting"
raise ImportError(msg)

class Arrow3D(FancyArrowPatch):
def __init__(
Expand All @@ -382,7 +378,7 @@ def __init__(
FancyArrowPatch.__init__(self, (0, 0), (0, 0), *args, **kwargs)
self._verts3d = xs, ys, zs

def draw(self, renderer) -> None:
def draw(self, renderer: Incomplete) -> None:
xs3d, ys3d, zs3d = self._verts3d
xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)
self.set_positions((xs[0], ys[0]), (xs[1], ys[1]))
Expand Down Expand Up @@ -537,7 +533,7 @@ def annotate_special_paths(
cell: NDArray[np.float_] | Sequence[Sequence[float]] | None = None,
offset: dict[str, Sequence[float]] | None = None,
special_points: dict[str, NDArray[np.float_]] | None = None,
labels=None,
labels: Incomplete = None,
**kwargs: Incomplete,
) -> None:
"""Annotates user indicated paths in k-space by plotting lines (or points) over the BZ."""
Expand Down Expand Up @@ -641,16 +637,16 @@ def bz2d_segments(
segments_x = []
segments_y = []

for points, _normal in twocell_to_bz1(cell)[0]:
points = apply_transformations(points, transformations)
x, y, z = np.concatenate([points, points[:1]]).T
for points, _normal in twocell_to_bz1(np.array(cell))[0]:
transformed_points = apply_transformations(points, transformations)
x, y, z = np.concatenate([transformed_points, transformed_points[:1]]).T
segments_x.append(x)
segments_y.append(y)

return segments_x, segments_y


def twocell_to_bz1(cell: NDArray[np.float_]):
def twocell_to_bz1(cell: NDArray[np.float_]) -> Incomplete:
from ase.dft.bz import bz_vertices

# 2d in x-y plane
Expand Down
18 changes: 16 additions & 2 deletions src/arpes/plotting/bz_tool/RangeOrSingleValueWidget.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from __future__ import annotations

from functools import partial
from logging import DEBUG, INFO, Formatter, StreamHandler, getLogger
from typing import TYPE_CHECKING

from PySide6 import QtWidgets
Expand All @@ -16,6 +17,19 @@

from . import BZTool

LOGLEVELS = (DEBUG, INFO)
LOGLEVEL = LOGLEVELS[1]
logger = getLogger(__name__)
fmt = "%(asctime)s %(levelname)s %(name)s :%(message)s"
formatter = Formatter(fmt)
handler = StreamHandler()
handler.setLevel(LOGLEVEL)
logger.setLevel(LOGLEVEL)
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.propagate = False


__all__ = ["RangeOrSingleValueWidget"]


Expand Down Expand Up @@ -61,10 +75,10 @@ def __init__(

self.recompute()

def mode_changed(self, event, source) -> None:
def mode_changed(self, event: Incomplete, source: Incomplete) -> None:
"""Unused, currently."""

def value_changed(self, event, source) -> None:
def value_changed(self, event: Incomplete, source: Incomplete) -> None:
"""Responds to changes in the internal value."""
if self._prevent_change_events:
return
Expand Down
4 changes: 2 additions & 2 deletions src/arpes/plotting/dynamic_tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,8 +87,8 @@ def update_data(self) -> None:
try:
mapped_data = self._function(self.data, **self.current_arguments)
self.views["f(xy)"].setImage(mapped_data.fillna(0))
except Exception as err:
logger.debug(f"Exception occurs. {err=}, {type(err)=}")
except Exception:
logger.exception("Exception occurs")

def add_controls(self) -> None:
specification = self.calculate_control_specification()
Expand Down
10 changes: 5 additions & 5 deletions src/arpes/plotting/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -1102,8 +1102,8 @@ def remove_colorbars(fig: Figure | None = None) -> None:
ax.remove()
else:
remove_colorbars(plt.gcf())
except Exception as err:
logger.debug(f"Exception occurs: {err=}, {type(err)=}")
except Exception:
logger.exception("Exception occurs")


def generic_colorbarmap_for_data(
Expand Down Expand Up @@ -1242,7 +1242,7 @@ def savefig(
desired_path: str | Path,
dpi: int = 400,
data: list[XrTypes] | tuple[XrTypes, ...] | set[XrTypes] | None = None,
save_data=None,
save_data: Incomplete | None = None,
*,
paper: bool = False,
**kwargs: Incomplete,
Expand Down Expand Up @@ -1374,8 +1374,8 @@ def path_for_plot(desired_path: str | Path) -> Path:
if exc.errno != errno.EEXIST:
raise
return filename
except Exception as e:
warnings.warn(f"Misconfigured FIGURE_PATH saving locally: {e}", stacklevel=2)
except Exception:
logger.exception("Misconfigured FIGURE_PATH saving locally")
return Path.cwd() / desired_path


Expand Down
8 changes: 4 additions & 4 deletions src/arpes/utilities/bz.py
Original file line number Diff line number Diff line change
Expand Up @@ -400,7 +400,7 @@ def build_2dbz_poly(
return raw_poly_to_mask(points_2d)


def bz_symmetry(flat_symmetry_points) -> Literal["rect", "square", "hex"] | None:
def bz_symmetry(flat_symmetry_points: dict | None) -> Literal["rect", "square", "hex"] | None:
"""Determines symmetry from a list of the symmetry points.
Args:
Expand Down Expand Up @@ -701,7 +701,7 @@ def reduced_bz_selection(data: DataType) -> DataType:
return data


def bz_cutter(symmetry_points, *, reduced: bool = True):
def bz_cutter(symmetry_points: Incomplete, *, reduced: bool = True):
"""Cuts data so that it areas outside the Brillouin zone are masked away.
Args:
Expand All @@ -711,7 +711,7 @@ def bz_cutter(symmetry_points, *, reduced: bool = True):
TODO: UNFINISHED, Test
"""

def build_bz_mask(data) -> None:
def build_bz_mask(data: Incomplete) -> None:
"""[TODO:summary].
Args:
Expand All @@ -721,7 +721,7 @@ def build_bz_mask(data) -> None:
[TODO:description]
"""

def cutter(data, cut_value: float = np.nan):
def cutter(data: Incomplete, cut_value: float = np.nan) -> Incomplete:
"""[TODO:summary].
Args:
Expand Down
Loading

0 comments on commit e228924

Please sign in to comment.