Skip to content

Commit

Permalink
* Tidy up
Browse files Browse the repository at this point in the history
  🔥  - Remove the class and functions in corrections/**init**.py (HashableDict, reference_key, correc…
  ➕  add dependency about notebook (v7 or later is required.)
  • Loading branch information
arafune committed Feb 13, 2024
1 parent be92a00 commit 8bca442
Show file tree
Hide file tree
Showing 25 changed files with 63 additions and 90 deletions.
2 changes: 2 additions & 0 deletions Changes.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,8 @@ Major Changes from 3.0.1
- Remove condensed_attrs: We should not enfoce camelcase on attributes, while original version did. Rather, the snake_case would be better from the modern pythonic viewpoint.
- Remove `trace` arg for debugging. This technique may be sharp, but not so well fitted the current python trend; typing oriented.

- Remove the class and functions in corrections/**init**.py (HashableDict, reference_key, correction_from_reference_set), which have not used.

Fix from 3.0.1

- bug of concatenating in broadcast_model
Expand Down
13 changes: 7 additions & 6 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -68,19 +68,17 @@ If you use PyARPES in your work, please support the development of scientific so
Installation
============

PyARPES can be installed from source. Python version 3.11 or newer is strongly recommmended.
PyARPES (>= V.4.0) can be installed from source. Python version 3.11 or newer is strongly recommmended.

The current version has been largely revised from the original version which are in PyPI and conda site.
Unfortunately, I don't have the right the updated version to these site, and I would not like to take over it from the original author.
The current version has been largely revised from the original version which are in PyPI and conda site.
Unfortunately, I don't have the right the upload the current version to these site, and I would not like to take over it from the original author.

The main purpose of revision of the package is to make this be reliable. Actually, the original version outputs wrong results in many
The main purpose of revision of the package is to make this be reliable for us. Actually, the original version outputs the wrong results in many
case, especially for angle-momentum conversion.


Thus, the current package can be installed only through the github.



Pip installation
----------------

Expand All @@ -96,6 +94,7 @@ If you want to modify the source for PyARPES as you use it, you might prefer a l
Details can be found on `the documentation site`_.



Suggested steps
---------------

Expand All @@ -108,6 +107,8 @@ Suggested steps
Contact
=======

Very unfortunately, we cannot get any responses from the original author. The comment below does not make sense at present.

Questions, difficulties, and suggestions can be directed to Conrad Stansbury ([email protected])
or added to the repository as an issue. In the case of trouble, also check the `FAQ`_.

Expand Down
5 changes: 3 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ readme = "README.rst"
requires-python = ">= 3.10"

dependencies = [
"holoviews",
"holoviews>=1.16.0",
"astropy>=5.3",
"xarray>=2023.5.0",
"lmfit>=1.2.1",
Expand All @@ -28,6 +28,7 @@ dependencies = [
"scikit-image>=0.20.0",
"netcdf4>=1.6.4",
"rx>=3.2.0",
"notebook>=7.0",
"ipywidgets",
]

Expand Down Expand Up @@ -94,8 +95,8 @@ lint.ignore = [
#
"NPY201", # Numpy 2.0,
]
target-version = "py310"
lint.select = ["ALL"]
target-version = "py310"
line-length = 100

exclude = ["scripts", "docs", "conda"]
Expand Down
3 changes: 2 additions & 1 deletion src/arpes/analysis/decomposition.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,14 @@
from functools import wraps
from typing import TYPE_CHECKING

import xarray as xr

from arpes.constants import TWO_DIMENSION
from arpes.provenance import PROVENANCE, provenance
from arpes.utilities import normalize_to_spectrum

if TYPE_CHECKING:
import sklearn
import xarray as xr
from _typeshed import Incomplete

__all__ = (
Expand Down
2 changes: 1 addition & 1 deletion src/arpes/analysis/mask.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@
from typing import TYPE_CHECKING

import numpy as np
import xarray as xr
from matplotlib.path import Path

from arpes.provenance import update_provenance
from arpes.utilities import normalize_to_spectrum

if TYPE_CHECKING:
import xarray as xr
from _typeshed import Incomplete
from numpy.typing import NDArray

Expand Down
5 changes: 3 additions & 2 deletions src/arpes/analysis/moire.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
All of the moirés discussed here are on hexagonal crystal systems.
"""

from __future__ import annotations

from typing import TYPE_CHECKING, Any
Expand Down Expand Up @@ -119,7 +120,7 @@ def calculate_bz_vertices_from_direct_cell(cell: NDArray[np.float_]) -> list:
assert all(abs(cell[2][0:2]) < RTOL)
assert all(abs(cell.T[2][0:2]) < RTOL)
else:
cell = [[*list(c), 0] for c in cell] + [[0, 0, 1]]
cell = np.array([[*list(c), 0] for c in cell] + [[0, 0, 1]])

icell = np.linalg.inv(cell).T
try:
Expand Down Expand Up @@ -167,7 +168,7 @@ def calc_commensurate_moire_cell(
if swap_angle:
moire_angle = -moire_angle

moire_cell = hex_cell_2d(moire_a)
moire_cell = hex_cell_2d(float(moire_a))
moire_cell = [[*list(c), 0] for c in moire_cell] + [[0, 0, 1]]
moire_cell = Rotation.from_rotvec([0, 0, moire_angle]).apply(moire_cell)
moire_icell = np.linalg.inv(moire_cell).T
Expand Down
44 changes: 0 additions & 44 deletions src/arpes/corrections/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,6 @@

from __future__ import annotations

from collections import OrderedDict
from typing import TYPE_CHECKING

import xarray as xr

from arpes.utilities import deep_equals, normalize_to_dataset

from .fermi_edge_corrections import (
apply_direct_fermi_edge_correction,
apply_photon_energy_fermi_edge_correction,
Expand All @@ -27,40 +20,3 @@
build_quadratic_fermi_edge_correction,
find_e_fermi_linear_dos,
)

if TYPE_CHECKING:
from arpes._typing import XrTypes

__all__ = (
"reference_key",
"correction_from_reference_set",
)


class HashableDict(OrderedDict):
"""Implements hashing for ordered dictionaries.
The dictionary must be ordered for the hash to be stable.
"""

def __hash__(self):
return hash(frozenset(self.items()))


def reference_key(data: xr.DataArray) -> HashableDict:
"""Calculates a key/hash for data determining reference/correction equality."""
data_array = data if isinstance(data, xr.DataArray) else normalize_to_dataset(data)
assert isinstance(data_array, xr.DataArray)
return HashableDict(data_array.S.reference_settings)


def correction_from_reference_set(data: xr.DataArray, reference_set):
"""Determines which correction to use from a set of references."""
data_array = data if isinstance(data, xr.DataArray) else normalize_to_dataset(data)
correction = None
for k, corr in reference_set.items():
if deep_equals(dict(reference_key(data_array)), dict(k)):
correction = corr
break

return correction
2 changes: 1 addition & 1 deletion src/arpes/endstations/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
import warnings
from logging import DEBUG, INFO, Formatter, StreamHandler, getLogger
from pathlib import Path
from typing import TYPE_CHECKING, ClassVar, Literal, TypedDict, reveal_type
from typing import TYPE_CHECKING, ClassVar, Literal, TypedDict

import h5py
import numpy as np
Expand Down
16 changes: 15 additions & 1 deletion src/arpes/endstations/nexus_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@
Currently we assume that the raw file format is actually HDF.
"""

from __future__ import annotations

import contextlib
from dataclasses import dataclass, field
from logging import DEBUG, INFO, Formatter, StreamHandler, getLogger
from typing import TYPE_CHECKING, Any

import numpy as np
Expand All @@ -17,6 +19,18 @@

__all__ = ["read_data_attributes_from"]

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


def read_group_data(group: dict, attribute_name: str = "") -> xr.Dataset:
if attribute_name:
Expand Down Expand Up @@ -65,7 +79,7 @@ class DebugTarget(Target):
name = "debug"

def read_h5(self, g, path) -> None:
print(path, self.read(read_group_data(g)))
logger.info(f"path {path}, group_data {self.read(read_group_data(g))}")


@dataclass
Expand Down
4 changes: 2 additions & 2 deletions src/arpes/plotting/fermi_surface.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,10 +98,10 @@ def magnify_circular_regions_plot(
data: [TODO:description]
magnified_points: [TODO:description]
mag: [TODO:description]
radius: [TODO:description]
radius (float): [TODO:description]
cmap: [TODO:description]
color: [TODO:description]
edgecolor: [TODO:description]
edgecolor (ColorType): [TODO:description]
out: [TODO:description]
ax: [TODO:description]
kwargs: [TODO:description]
Expand Down
3 changes: 2 additions & 1 deletion src/arpes/utilities/conversion/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,7 @@ def slice_along_path( # noqa: PLR0913
for x in interpolation_points
]

logger.debug(f"parsed_interpolation_points: {parsed_interpolation_points}")
free_coordinates = list(arr.dims)
seen_coordinates = collections.defaultdict(set)
for point in parsed_interpolation_points:
Expand Down Expand Up @@ -659,7 +660,7 @@ def _extract_symmetry_point(
arr: xr.DataArray,
*,
extend_to_edge: bool = False,
) -> dict:
) -> dict[Hashable, float]:
"""[TODO:summary].
Args:
Expand Down
29 changes: 18 additions & 11 deletions src/arpes/utilities/excepthook.py
Original file line number Diff line number Diff line change
@@ -1,30 +1,37 @@
"""A utility excepthook for Qt applications which ensures errors are visible in Jupyter."""

from __future__ import annotations

import traceback
from collections import namedtuple
from typing import TYPE_CHECKING, NamedTuple

if TYPE_CHECKING:
from types import FrameType, TracebackType

__all__ = ("patched_excepthook",)


def patched_excepthook(exc_type, exc_value, exc_tb) -> None:
def patched_excepthook(
exc_type: type[BaseException] | None,
exc_value: BaseException | None,
exc_tb: TracebackType | FakeTB | None,
) -> None:
"""Prints the traceback instead of dying silently. Useful for debugging Qt apps in Jupyter."""
enriched_tb = _add_missing_frames(exc_tb) if exc_tb else exc_tb
traceback.print_exception(exc_type, exc_value, enriched_tb)


def _add_missing_frames(tb):
result = fake_tb(tb.tb_frame, tb.tb_lasti, tb.tb_lineno, tb.tb_next)
def _add_missing_frames(tb: TracebackType | FakeTB) -> FakeTB:
result = FakeTB(tb.tb_frame, tb.tb_lasti, tb.tb_lineno, tb.tb_next)
frame = tb.tb_frame.f_back
while frame:
result = fake_tb(frame, frame.f_lasti, frame.f_lineno, result)
result = FakeTB(frame, frame.f_lasti, frame.f_lineno, result)
frame = frame.f_back
return result


fake_tb = namedtuple("fake_tb", ("tb_frame", "tb_lasti", "tb_lineno", "tb_next"))
# class fake_tb(NamedTuple):
# tb_frame
# tb_lasti
# tb_lineno
# tb_next
class FakeTB(NamedTuple):
tb_frame: FrameType
tb_lasti: int
tb_lineno: int
tb_next: TracebackType | FakeTB | None
2 changes: 1 addition & 1 deletion src/arpes/utilities/qt/windows.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,4 +149,4 @@ def toggle_help(self, event: QKeyEvent) -> None:

def window_print(self, *args: Incomplete, **kwargs: Incomplete) -> None:
"""Forward prints to the application instance so they end up in Jupyter."""
print(*args, **kwargs)
logger.info(f"args: {args}, kwargs: {kwargs}")
5 changes: 2 additions & 3 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,16 @@
from pathlib import Path
from typing import TYPE_CHECKING, TypedDict

import pytest

import arpes.config
import arpes.endstations
import pytest

from tests.utils import cache_loader

if TYPE_CHECKING:
from collections.abc import Callable, Generator

import xarray as xr

from arpes._typing import SCANINFO, WORKSPACETYPE


Expand Down
3 changes: 1 addition & 2 deletions tests/test_basic_data_loading.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,10 @@
import contextlib
from typing import TYPE_CHECKING, Any, ClassVar

import arpes.xarray_extensions # pylint: disable=unused-import, redefined-outer-name # noqa: F401
import numpy as np
import pytest
import xarray as xr

import arpes.xarray_extensions # pylint: disable=unused-import, redefined-outer-name # noqa: F401
from arpes.utilities.conversion import convert_to_kspace

if TYPE_CHECKING:
Expand Down
1 change: 0 additions & 1 deletion tests/test_bz.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
"""Test for utilitiy.bz."""

import numpy as np

from arpes.utilities import bz


Expand Down
1 change: 0 additions & 1 deletion tests/test_bz_spec.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
"""Test for utilitiy.bz."""
import numpy as np

from arpes.utilities import bz_spec


Expand Down
1 change: 0 additions & 1 deletion tests/test_curve_fitting.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
"""Unit test for curve fitting."""

import numpy as np

from arpes.analysis import rebin
from arpes.fits import AffineBroadenedFD, broadcast_model
from arpes.io import example_data
Expand Down
1 change: 0 additions & 1 deletion tests/test_derivative_analysis.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@

import numpy as np
import pytest

from arpes.analysis.derivative import dn_along_axis
from arpes.analysis.filters import gaussian_filter_arr

Expand Down
1 change: 0 additions & 1 deletion tests/test_direct_and_example_data_loading.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@

import numpy as np
import xarray as xr

from arpes.endstations.plugin.ALG_main import ALGMainChamber
from arpes.io import load_data, load_example_data

Expand Down
Loading

0 comments on commit 8bca442

Please sign in to comment.