Skip to content

Commit

Permalink
update remaining docstrings, and remove MetaHandler
Browse files Browse the repository at this point in the history
  • Loading branch information
rettigl committed Feb 29, 2024
1 parent 171fc29 commit 2bc3c39
Show file tree
Hide file tree
Showing 6 changed files with 119 additions and 258 deletions.
1 change: 0 additions & 1 deletion docs/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ Concept description. TODO
specsanalyzer/convert
specsanalyzer/img_tools
specsanalyzer/io
specsanalyzer/metadata
specsanalyzer/config

.. toctree::
Expand Down
5 changes: 0 additions & 5 deletions docs/specsanalyzer/metadata.rst

This file was deleted.

51 changes: 23 additions & 28 deletions specsanalyzer/core.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
"""This is the specsanalyzer core class
"""
from __future__ import annotations

import os
from typing import Any
from typing import Dict
from typing import Generator
from typing import Tuple
from typing import Union

import imutils
import ipywidgets as ipw
Expand All @@ -22,34 +21,38 @@
from specsanalyzer.convert import physical_unit_data
from specsanalyzer.img_tools import crop_xarray
from specsanalyzer.img_tools import fourier_filter_2d
from specsanalyzer.metadata import MetaHandler

package_dir = os.path.dirname(__file__)


class SpecsAnalyzer: # pylint: disable=dangerous-default-value
class SpecsAnalyzer:
"""SpecsAnalyzer: A class to convert photoemission data from a SPECS Phoibos analyzer from
camera image coordinates into physical units (energy, angle, position).
Args:
metadata (dict, optional): Metadata dictionary. Defaults to {}.
config (dict | str, optional): Metadata dictionary or file path. Defaults to {}.
**kwds: Keyword arguments passed to ``parse_config``.
"""

def __init__(
self,
metadata: Dict[Any, Any] = {},
config: Union[Dict[Any, Any], str] = {},
metadata: dict[Any, Any] = {},
config: dict[Any, Any] | str = {},
**kwds,
):
"""SpecsAnalyzer constructor.
Args:
metadata (dict, optional): Metadata dictionary. Defaults to {}.
config (Union[dict, str], optional): Metadata dictionary or file path. Defaults to {}.
config (dict | str, optional): Metadata dictionary or file path. Defaults to {}.
**kwds: Keyword arguments passed to ``parse_config``.
"""
self._config = parse_config(
config,
**kwds,
)
self._attributes = MetaHandler(meta=metadata)
self.metadata = metadata
self._data_array = None
self.print_msg = True
try:
Expand All @@ -62,9 +65,8 @@ def __init__(
os.path.join(package_dir, self._config["calib2d_file"]),
)

self._correction_matrix_dict: Dict[Any, Any] = {}
self._correction_matrix_dict: dict[Any, Any] = {}

# pylint: disable=duplicate-code
def __repr__(self):
if self._config is None:
pretty_str = "No configuration available"
Expand All @@ -81,7 +83,7 @@ def config(self):
return self._config

@config.setter
def config(self, config: Union[dict, str]):
def config(self, config: dict | str):
"""Set config"""
self._config = parse_config(config)

Expand Down Expand Up @@ -113,18 +115,12 @@ def convert_image(
xr.DataArray: xarray containg the corrected data and kinetic and angle axis
"""

apply_fft_filter = kwds.pop(
"apply_fft_filter",
self._config.get("apply_fft_filter", False),
)
apply_fft_filter = kwds.pop("apply_fft_filter", self._config.get("apply_fft_filter", False))
binning = kwds.pop("binning", self._config.get("binning", 1))

if apply_fft_filter:
try:
fft_filter_peaks = kwds.pop(
"fft_filter_peaks",
self._config["fft_filter_peaks"],
)
fft_filter_peaks = kwds.pop("fft_filter_peaks", self._config["fft_filter_peaks"])
img = fourier_filter_2d(raw_img, fft_filter_peaks)
except KeyError:
img = raw_img
Expand Down Expand Up @@ -165,7 +161,7 @@ def convert_image(

except KeyError:
old_matrix_check = False
( # pylint: disable=duplicate-code
(
ek_axis,
angle_axis,
angular_correction_matrix,
Expand Down Expand Up @@ -329,20 +325,19 @@ def crop_tool(
Args:
raw_img (np.ndarray): Raw image data, numpy 2d matrix
lens_mode (str): analzser lens mode, check calib2d for a list
of modes Camelcase naming convention e.g. "WideAngleMode"
of modes CamelCase naming convention e.g. "WideAngleMode"
kinetic_energy (float): set analyser kinetic energy
pass_energy (float): set analyser pass energy
work_function (float): set analyser work function
apply (bool, optional): Option to directly apply the pre-selected cropping parameters.
Defaults to False.
**kwds: Keyword parameters for the crop tool:
-ek_range_min
-ek_range_max
-ang_range_min
-ang_range_max
- ek_range_min
- ek_range_max
- ang_range_min
- ang_range_max
"""

data_array = self.convert_image(
raw_img=raw_img,
lens_mode=lens_mode,
Expand Down Expand Up @@ -534,7 +529,7 @@ def cropit(val): # pylint: disable=unused-argument
def mergedicts(
dict1: dict,
dict2: dict,
) -> Generator[Tuple[Any, Any], None, None]:
) -> Generator[tuple[Any, Any], None, None]:
"""Merge two dictionaries, overwriting only existing values and retaining
previously present values
Expand Down
61 changes: 32 additions & 29 deletions specsanalyzer/img_tools.py
Original file line number Diff line number Diff line change
@@ -1,35 +1,36 @@
"""This module contains image manipulation tools for the specsanalyzer package
"""
from __future__ import annotations

from typing import Sequence
from typing import Union

import numpy as np
import xarray as xr


def gauss2d(
# pylint: disable=invalid-name, too-many-arguments
x: Union[float, np.ndarray],
y: Union[float, np.ndarray],
x: float | np.ndarray,
y: float | np.ndarray,
mx: float,
my: float,
sx: float,
sy: float,
) -> Union[float, np.ndarray]:
"""Function to calculate a 2-dimensional Gaussian peak function without
correlation, and amplitude 1.
) -> float | np.ndarray:
"""Function to calculate a 2-dimensional Gaussian peak function without correlation, and
amplitude 1.
Args:
x: independent x-variable
y: independent y-variable
mx: x-center of the 2D Gaussian
my: y-center of the 2D Gaussian
sx: Sigma in y direction
sy: Sigma in x direction
x (float | np.ndarray): independent x-variable
y (float | np.ndarray): independent y-variable
mx (float): x-center of the 2D Gaussian
my (float): y-center of the 2D Gaussian
sx (float): Sigma in y direction
sy (float): Sigma in x direction
Returns:
peak intensity at the given (x, y) coordinates.
float | np.ndarray: peak intensity at the given (x, y) coordinates.
"""

return np.exp(
Expand All @@ -39,24 +40,26 @@ def gauss2d(

def fourier_filter_2d(
image: np.ndarray,
peaks: Sequence,
peaks: Sequence[dict],
ret: str = "filtered",
) -> np.ndarray:
"""Function to Fourier filter an image for removal of regular pattern artefacts,
e.g. grid lines.
Args:
image: the input image
peaks: list of dicts containing the following information about a "peak" in the
Fourier image:
'pos_x', 'pos_y', sigma_x', sigma_y', 'amplitude'. Define one entry for
each feature you want to suppress in the Fourier image, where amplitude
1 corresponds to full suppression.
ret: flag to indicate which data to return. Possible values are:
'filtered', 'fft', 'mask', 'filtered_fft'
image (np.ndarray): the input image
peaks (Sequence[dict]): list of dicts containing the following information about a "peak"
in the Fourier image:
'pos_x', 'pos_y', sigma_x', sigma_y', 'amplitude'.
Define one entry for each feature you want to suppress in the Fourier image, where
amplitude 1 corresponds to full suppression.
ret (str, optional): flag to indicate which data to return. Possible values are:
'filtered', 'fft', 'mask', 'filtered_fft'. Defaults to "filtered"
Returns:
The chosen image data. Default is the filtered real image.
np.ndarray: The chosen image data. Default is the filtered real image.
"""

# Do Fourier Transform of the (real-valued) image
Expand Down Expand Up @@ -109,14 +112,14 @@ def crop_xarray(
"""Crops an xarray according to the provided coordinate boundaries.
Args:
data_array: the input xarray DataArray
x_min: the minimum position along the first element in the x-array dims list.
x_max: the maximum position along the first element in the x-array dims list.
y_min: the minimum position along the second element in the x-array dims list.
y_max: the maximum position along the second element in the x-array dims list.
data_array (xr.DataArray): the input xarray DataArray
x_min (float): the minimum position along the first element in the x-array dims list.
x_max (float): the maximum position along the first element in the x-array dims list.
y_min (float): the minimum position along the second element in the x-array dims list.
y_max (float): the maximum position along the second element in the x-array dims list.
Returns:
The cropped xarray DataArray.
xr.DataArray: The cropped xarray DataArray.
"""

x_axis = data_array.coords[data_array.dims[0]]
Expand Down
Loading

0 comments on commit 2bc3c39

Please sign in to comment.