Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Type Annotation Enhancement in mantidimaging/core/ Directory #2283

Merged
merged 7 commits into from
Jul 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion mantidimaging/core/utility/close_enough_point.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,5 +20,5 @@ def __init__(self, points: Sequence[int] | Sequence[float]):
self.y = int(points[1])
self.x = int(points[0])

def __str__(self):
def __str__(self) -> str:
return f"({self.x}, {self.y})"
5 changes: 3 additions & 2 deletions mantidimaging/core/utility/command_line_arguments.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,18 @@
from __future__ import annotations
from logging import getLogger
import os
from typing import NoReturn

from mantidimaging.core.operations.loader import load_filter_packages

logger = getLogger(__name__)


def _get_filter_names():
def _get_filter_names() -> dict[str, str]:
return {package.filter_name.replace(" ", "-").lower(): package.filter_name for package in load_filter_packages()}


def _log_and_exit(msg: str):
def _log_and_exit(msg: str) -> NoReturn:
"""
Log an error message and exit.
:param msg: The log message.
Expand Down
2 changes: 1 addition & 1 deletion mantidimaging/core/utility/cor_interpolate.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import numpy as np


def execute(data_length, slice_ids, cors_for_sinograms):
def execute(data_length: int, slice_ids: np.ndarray, cors_for_sinograms: np.ndarray) -> np.ndarray:
"""
Interpolates the Centers of Rotation for the sinograms that are not
provided.
Expand Down
4 changes: 2 additions & 2 deletions mantidimaging/core/utility/cuda_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ class CudaChecker:
_instance = None
_cuda_is_present = False

def __new__(cls):
def __new__(cls) -> CudaChecker:
"""
Creates a singleton for storing the result of the Cuda check.
"""
Expand All @@ -56,7 +56,7 @@ def cuda_is_present(cls) -> bool:
return cls._cuda_is_present

@classmethod
def clear_instance(cls):
def clear_instance(cls) -> None:
"""
Resets the instance. Used for making sure mocks don't leak in tests.
"""
Expand Down
4 changes: 2 additions & 2 deletions mantidimaging/core/utility/data_containers.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ class ScalarCoR(SingleValue):
__slots__ = 'value'
value: float

def to_vec(self, detector_width):
def to_vec(self, detector_width: float) -> VectorCoR:
return VectorCoR(detector_width / 2 - self.value)


Expand All @@ -57,7 +57,7 @@ class VectorCoR(SingleValue):
__slots__ = 'value'
value: float

def to_scalar(self, detector_width):
def to_scalar(self, detector_width: float) -> ScalarCoR:
return ScalarCoR(detector_width / 2 + self.value)


Expand Down
16 changes: 8 additions & 8 deletions mantidimaging/core/utility/execution_timer.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,27 +35,27 @@ def __init__(self, msg: str = 'Elapsed time', logger: Logger = perf_logger):
self.time_start: float | None = None
self.time_end: float | None = None

def __str__(self):
def __str__(self) -> str:
prefix = f'{self.msg}: ' if self.msg else ''
sec = self.total_seconds
return f'{prefix}{sec if sec else "unknown"} seconds'

def __enter__(self):
def __enter__(self) -> None:
self.time_start = time.monotonic()
self.time_end = None

def __exit__(self, *args):
def __exit__(self, *args) -> None:
self.time_end = time.monotonic()
self.logger.info(str(self))

@property
def total_seconds(self):
def total_seconds(self) -> float:
"""
Gets the total number of seconds the timer was running for, returns
None if the timer has not been run or is still running.
"""
return self.time_end - self.time_start if \
self.time_start and self.time_end else None
self.time_start and self.time_end else 0


class ExecutionProfiler:
Expand All @@ -77,18 +77,18 @@ def __init__(self,

self.pr = cProfile.Profile()

def __str__(self):
def __str__(self) -> str:
out = StringIO()
out.write(f'{self.msg}: \n' if self.msg else '')

ps = Stats(self.pr, stream=out).sort_stats(self.sort_by)
ps.print_stats()
return out.getvalue()

def __enter__(self):
def __enter__(self) -> None:
self.pr.enable()

def __exit__(self, *args):
def __exit__(self, *args) -> None:
self.pr.disable()
if perf_logger.isEnabledFor(1):
for line in str(self).split("\n")[:self.max_lines]:
Expand Down
4 changes: 2 additions & 2 deletions mantidimaging/core/utility/histogram.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
DEFAULT_NUM_BINS = 2048


def set_histogram_log_scale(histogram: HistogramLUTItem):
def set_histogram_log_scale(histogram: HistogramLUTItem) -> None:
"""
Sets the y-values of a histogram to use a log scale.
:param histogram: The HistogramLUTItem of an image.
Expand All @@ -20,7 +20,7 @@ def set_histogram_log_scale(histogram: HistogramLUTItem):
histogram.plot.setData(x_data, np.log(y_data + 1))


def generate_histogram_from_image(image_data, num_bins=DEFAULT_NUM_BINS):
def generate_histogram_from_image(image_data: np.ndarray, num_bins: int = DEFAULT_NUM_BINS) -> tuple:
histogram, bins = np.histogram(image_data.flatten(), num_bins)
center = (bins[:-1] + bins[1:]) / 2
return center, histogram, bins
3 changes: 2 additions & 1 deletion mantidimaging/core/utility/imat_log_file_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from typing import TYPE_CHECKING

import numpy
import numpy as np

from mantidimaging.core.utility.data_containers import Counts, ProjectionAngles

Expand Down Expand Up @@ -210,7 +211,7 @@ def get_seperator(first_row: str) -> bool:
def source_file(self) -> Path:
return self._source_file

def projection_numbers(self):
def projection_numbers(self) -> np.ndarray:
proj_nums = numpy.zeros(len(self._data[IMATLogColumn.PROJECTION_NUMBER]), dtype=numpy.uint32)
proj_nums[:] = self._data[IMATLogColumn.PROJECTION_NUMBER]
return proj_nums
Expand Down
4 changes: 2 additions & 2 deletions mantidimaging/core/utility/optional_imports.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,9 @@ def safe_import(name):
return module


def check_availability(name):
def check_availability(name: str) -> bool:
return safe_import(name) is not None


def tomopy_available():
def tomopy_available() -> bool:
return check_availability('tomopy')
2 changes: 1 addition & 1 deletion mantidimaging/core/utility/sensible_roi.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ def __iter__(self) -> Iterator[int]:
"""
return iter((self.left, self.top, self.right, self.bottom))

def __str__(self):
def __str__(self) -> str:
return f"Left: {self.left}, Top: {self.top}, Right: {self.right}, Bottom: {self.bottom}"

def to_list_string(self) -> str:
Expand Down
8 changes: 4 additions & 4 deletions mantidimaging/core/utility/size_calculator.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,17 +30,17 @@ def full_size(shape: Iterable[int]) -> int:
return math.prod(shape)


def full_size_bytes(shape: Iterable[int], dtype: npt.DTypeLike):
def full_size_bytes(shape: Iterable[int], dtype: npt.DTypeLike) -> int:
return full_size(shape) * _determine_dtype_size(dtype)


def full_size_KB(shape: Iterable[int], dtype: npt.DTypeLike):
def full_size_KB(shape: Iterable[int], dtype: npt.DTypeLike) -> float:
return full_size_bytes(shape, dtype) / 1024


def full_size_MB(shape: Iterable[int], dtype: npt.DTypeLike):
def full_size_MB(shape: Iterable[int], dtype: npt.DTypeLike) -> float:
return full_size_KB(shape, dtype) / 1024


def number_of_images_from_indices(start, end, increment):
def number_of_images_from_indices(start: int, end: int, increment: int) -> int:
return int((end - start) / increment) if increment != 0 else 0
4 changes: 2 additions & 2 deletions mantidimaging/core/utility/test/execution_timer_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,11 @@ class ExecutionTimerTest(unittest.TestCase):

def test_execute(self):
t = ExecutionTimer()
self.assertEqual(t.total_seconds, None)
self.assertEqual(t.total_seconds, 0.0)
self.assertEqual(str(t), 'Elapsed time: unknown seconds')

with t:
self.assertEqual(t.total_seconds, None)
self.assertEqual(t.total_seconds, 0.0)

time.sleep(0.1)

Expand Down