From ba61469a0518af72edd05517dec655a811089436 Mon Sep 17 00:00:00 2001 From: Ryuichi Arafune Date: Wed, 18 Oct 2023 15:01:25 +0900 Subject: [PATCH 1/2] =?UTF-8?q?=F0=9F=92=AC=20=20update=20type=20hints?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- arpes/xarray_extensions.py | 6 +++--- tests/test_xarray_extensions.py | 11 +++++++++++ 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/arpes/xarray_extensions.py b/arpes/xarray_extensions.py index 39b87901..dc657019 100644 --- a/arpes/xarray_extensions.py +++ b/arpes/xarray_extensions.py @@ -706,7 +706,7 @@ def iter_symmetry_points(self) -> Generator[tuple[str, float], None, None]: yield from self.iter_projected_symmetry_points @property - def history(self): + def history(self) -> list[dict[str, dict[str, str] | str | list[str]]]: provenance_recorded = self._obj.attrs.get("provenance", None) def unlayer(prov: dict[str, Incomplete] | None) -> tuple[list[Incomplete], Incomplete]: @@ -1702,7 +1702,7 @@ def analyzer_detail(self) -> dict[str, str | float | None]: } @property - def temp(self) -> float: + def temp(self) -> float | Literal["RT", "LT"]: """The temperature at which an experiment was performed.""" prefered_attrs = [ "TA", @@ -1722,7 +1722,7 @@ def temp(self) -> float: ] for attr in prefered_attrs: if attr in self._obj.attrs: - return float(self._obj.attrs[attr]) + return self._obj.attrs[attr] msg = "Could not read temperature off any standard attr" raise AttributeError(msg) diff --git a/tests/test_xarray_extensions.py b/tests/test_xarray_extensions.py index dbe1e033..faf64969 100644 --- a/tests/test_xarray_extensions.py +++ b/tests/test_xarray_extensions.py @@ -101,6 +101,17 @@ def test_location_and_endstation(self, dataset_cut: xr.Dataset) -> None: """Test for property endstation property.""" assert dataset_cut.S.endstation == "ALG-MC" + def test_history(self, dataarray_cut: xr.DataArray) -> None: + """Test for S.history.""" + history = dataarray_cut.S.history + assert history[0]["record"]["what"] == "Loaded MC dataset from FITS." + + def test_short_history(self, dataarray_cut: xr.DataArray) -> None: + """Test for S.short_history.""" + history = dataarray_cut.S.short_history() + assert history[0] == "load_MC" + assert history[1] == "filesystem" + def test_find(dataarray_cut: xr.DataArray) -> None: """Test for S.find.""" From fe42f5c6ca37048cdaeb991a6572b6774d36140f Mon Sep 17 00:00:00 2001 From: Ryuichi Arafune Date: Thu, 19 Oct 2023 13:55:03 +0900 Subject: [PATCH 2/2] =?UTF-8?q?=F0=9F=90=9B=20=20fix=20bug=20in=20xarray?= =?UTF-8?q?=5Fextensions=20occuring=20when=20temperature=20is=20not=20nume?= =?UTF-8?q?ric,=20such=20as=20"RT",=20"LT".?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 💬 update type hints --- arpes/_typing.py | 9 +++++-- arpes/endstations/__init__.py | 5 ++-- arpes/io.py | 2 +- arpes/plotting/annotations.py | 46 ++++++++++++++++++++++++++++------- arpes/plotting/bz.py | 13 ++++++++-- arpes/xarray_extensions.py | 18 +++++++++++--- pyproject.toml | 2 +- 7 files changed, 74 insertions(+), 21 deletions(-) diff --git a/arpes/_typing.py b/arpes/_typing.py index af5bd430..72bdf01a 100644 --- a/arpes/_typing.py +++ b/arpes/_typing.py @@ -217,8 +217,13 @@ class SCANINFO(TypedDict, total=False): sample: str | None -class EXPERIMENTALINFO(TypedDict, total=False): - temperature: float | None +class ExperimentalConditions(TypedDict, total=True): + hv: float + polarization: float | str + temperature: float | str + + +class EXPERIMENTALINFO(ExperimentalConditions, total=False): temperature_cryotip: float | None pressure: float | None polarization: float | tuple[float | None, float | None] | str diff --git a/arpes/endstations/__init__.py b/arpes/endstations/__init__.py index 0f963ecd..874dd680 100644 --- a/arpes/endstations/__init__.py +++ b/arpes/endstations/__init__.py @@ -46,7 +46,7 @@ ] LOGLEVELS = (DEBUG, INFO) -LOGLEVEL = LOGLEVELS[0] +LOGLEVEL = LOGLEVELS[1] logger = getLogger(__name__) fmt = "%(asctime)s %(levelname)s %(name)s :%(message)s" formatter = Formatter(fmt) @@ -1061,11 +1061,12 @@ def resolve_endstation(*, retry: bool = True, **kwargs: Incomplete) -> type: if endstation_name is None: warnings.warn("Endstation not provided. Using `fallback` plugin.", stacklevel=2) endstation_name = "fallback" - + logger.debug(f"_ENDSTATION_ALIASES is : {_ENDSTATION_ALIASES}") try: return endstation_from_alias(endstation_name) except KeyError: if retry: + logger.debug("KeyError occurred") import arpes.config # pylint: disable=redefined-outer-name arpes.config.load_plugins() diff --git a/arpes/io.py b/arpes/io.py index e62a9839..b5bd5e9c 100644 --- a/arpes/io.py +++ b/arpes/io.py @@ -38,7 +38,7 @@ LOGLEVELS = (DEBUG, INFO) -LOGLEVEL = LOGLEVELS[0] +LOGLEVEL = LOGLEVELS[1] logger = getLogger(__name__) fmt = "%(asctime)s %(levelname)s %(name)s :%(message)s" formatter = Formatter(fmt) diff --git a/arpes/plotting/annotations.py b/arpes/plotting/annotations.py index 0e44e018..ea9fdba4 100644 --- a/arpes/plotting/annotations.py +++ b/arpes/plotting/annotations.py @@ -1,10 +1,11 @@ """Annotations onto plots for experimental conditions or locations.""" from __future__ import annotations -from typing import TYPE_CHECKING, Unpack +from typing import TYPE_CHECKING, Literal, Unpack import numpy as np import xarray as xr +import matplotlib as mpl from matplotlib.axes import Axes from mpl_toolkits.mplot3d import Axes3D @@ -18,7 +19,7 @@ from _typeshed import Incomplete from numpy.typing import NDArray - from arpes._typing import DataType, MPLTextParam + from arpes._typing import DataType, ExperimentalConditions, MPLTextParam __all__ = ( "annotate_cuts", @@ -37,7 +38,7 @@ def annotate_experimental_conditions( desc: list[str | float] | float | str, *, show: bool = False, - orientation: str = "top", + orientation: Literal["top", "bottom"] = "top", **kwargs: Unpack[MPLTextParam], ) -> None: """Renders information about the experimental conditions onto a set of axes. @@ -65,20 +66,47 @@ def annotate_experimental_conditions( ax.set_axis_off() ax.patch.set_alpha(0) - delta = -1 + delta: float = -1 current = 100.0 if orientation == "bottom": delta = 1 current = 0 - fontsize = kwargs.get("fontsize", 16) + fontsize_keyword = kwargs.get("fontsize", 16) + if isinstance(fontsize_keyword, float): + fontsize = fontsize_keyword + elif fontsize_keyword in ( + "xx-small", + "x-small", + "small", + "medium", + "large", + "x-large", + "xx-large", + ): + font_scalings = { # see matplotlib.font_manager + "xx-small": 0.579, + "x-small": 0.694, + "small": 0.833, + "medium": 1.0, + "large": 1.200, + "x-large": 1.440, + "xx-large": 1.728, + "larger": 1.2, + "smaller": 0.833, + } + fontsize = mpl.rc_params["font.size"] * font_scalings[fontsize_keyword] + else: + err_msg = "Incorrect font size setting" + raise RuntimeError(err_msg) delta = fontsize * delta - conditions = data.S.experimental_conditions + conditions: ExperimentalConditions = data.S.experimental_conditions renderers = { "temp": lambda c: "\\textbf{T = " + "{:.3g}".format(c["temp"]) + " K}", "photon": _render_photon, + "hv": _render_photon, "photon polarization": lambda c: _render_photon(c) + ", " + _render_polarization(c), "polarization": _render_polarization, } @@ -88,9 +116,9 @@ def annotate_experimental_conditions( current += item + delta continue - item = item.replace("_", " ").lower() + item_replaced = item.replace("_", " ").lower() - ax.text(0, current, renderers[item](conditions), **kwargs) + ax.text(0, current, renderers[item_replaced](conditions), **kwargs) current += delta @@ -118,7 +146,7 @@ def _render_polarization(conditions: dict[str, str]) -> str: def _render_photon(c: dict[str, float]) -> str: - return "\\textbf{" + str(c["hv"]) + " eV" + return "\\textbf{" + str(c["hv"]) + " eV}" def annotate_cuts( diff --git a/arpes/plotting/bz.py b/arpes/plotting/bz.py index 2c4e5865..e2b3484e 100644 --- a/arpes/plotting/bz.py +++ b/arpes/plotting/bz.py @@ -215,7 +215,11 @@ def plot_plane_to_bz( ax.add_collection3d(collection, zs="z") -def plot_data_to_bz(data: DataType, cell: Sequence[Sequence[float]], **kwargs: Incomplete): +def plot_data_to_bz( + data: DataType, + cell: Sequence[Sequence[float]], + **kwargs: Incomplete, +): """A dimension agnostic tool used to plot ARPES data onto a Brillouin zone.""" if len(data) == 3: # noqa: PLR2004 return plot_data_to_bz3d(data, cell, **kwargs) @@ -307,6 +311,11 @@ def plot_data_to_bz3d( ) -> None: """Plots ARPES data onto a 3D Brillouin zone.""" msg = "plot_data_to_bz3d is not implemented yet." + logger.debug(f"id of data: {data.attrs.get('id', None)}") + logger.debug(f"cell: {cell}") + if kwargs: + for k, v in kwargs.items(): + logger.debug(f"kwargs; k: {k}, v: {v}") raise NotImplementedError(msg) @@ -674,7 +683,7 @@ def bz2d_plot( logger.debug(f"paths: {paths}") logger.debug(f"points: {points}") logger.debug(f"repeat: {repeat}") - logger.debug(f"transfomations: {transformations}") + logger.debug(f"transformations: {transformations}") logger.debug(f"hide_ax: {hide_ax}") logger.debug(f"vectors: {vectors}") logger.debug(f"set_equal_aspect: {set_equal_aspect}") diff --git a/arpes/xarray_extensions.py b/arpes/xarray_extensions.py index dc657019..17ccf449 100644 --- a/arpes/xarray_extensions.py +++ b/arpes/xarray_extensions.py @@ -92,7 +92,13 @@ from matplotlib.typing import RGBColorType from numpy.typing import DTypeLike, NDArray - from arpes._typing import ANGLE, SPECTROMETER, DataType, PColorMeshKwargs + from arpes._typing import ( + ANGLE, + SPECTROMETER, + DataType, + ExperimentalConditions, + PColorMeshKwargs, + ) IncompleteMPL: TypeAlias = Incomplete @@ -103,7 +109,7 @@ ANGLE_VARS = ("alpha", "beta", "chi", "psi", "phi", "theta") LOGLEVELS = (DEBUG, INFO) -LOGLEVEL = LOGLEVELS[0] +LOGLEVEL = LOGLEVELS[1] logger = getLogger(__name__) fmt = "%(asctime)s %(levelname)s %(name)s :%(message)s" formatter = Formatter(fmt) @@ -160,7 +166,7 @@ def sherman_function(self) -> Incomplete: raise ValueError(msg) @property - def experimental_conditions(self) -> dict[str, str | float | None]: + def experimental_conditions(self) -> ExperimentalConditions: """Return experimental condition: hv, polarization, temperature. Use this property in plotting/annotations.py/conditions @@ -190,6 +196,8 @@ def polarization(self) -> str | None: }.get(int(self._obj.attrs["epu_pol"])) except ValueError: return self._obj.attrs["epu_pol"] + if "pol" in self._obj.attrs: + return self._obj.attrs["pol"] return None @property @@ -1820,6 +1828,7 @@ def _repr_html_spectrometer_info(self) -> str: @staticmethod def _repr_html_experimental_conditions(conditions: dict[str, str | float | None]) -> str: + logger.debug(f"conditions: {conditions}") transforms = { "polarization": lambda p: { "p": "Linear Horizontal", @@ -1842,9 +1851,10 @@ def no_change(x: str | float) -> str | float: for k, v in conditions.items(): if v is None: continue - if np.isnan(v): + if isinstance(v, float) and np.isnan(v): continue transformed_dict[str(k)] = transforms.get(k, no_change)(v) + logger.debug(f"transformed_dict: {transformed_dict}") return ARPESAccessorBase.dict_to_html(transformed_dict) def _repr_html_(self) -> str: diff --git a/pyproject.toml b/pyproject.toml index bf79f990..38467220 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -66,7 +66,7 @@ omit = [ exclude_lines = ["raise NotImplementedError", "pragma: no cover"] [tool.pyright] -typeCheckingMode = "basic" +typeCheckingMode = "off" pythonVersion = "3.11" pythonPlatform = "All"