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 part 2 #2284

Merged
merged 3 commits into from
Aug 7, 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
4 changes: 2 additions & 2 deletions mantidimaging/core/io/instrument_log_implmentations.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,15 +100,15 @@ def read_imat_date(time_stamp: str) -> datetime:
locale.setlocale(locale.LC_TIME, lc)

@staticmethod
def _has_imat_header(line: str):
def _has_imat_header(line: str) -> bool:
HEADERS = [
"TIME STAMP,IMAGE TYPE,IMAGE COUNTER,COUNTS BM3 before image,COUNTS BM3 after image",
"TIME STAMP IMAGE TYPE IMAGE COUNTER COUNTS BM3 before image COUNTS BM3 after image",
]
return line.strip() in HEADERS

@classmethod
def _has_imat_data_line(cls, line: str):
def _has_imat_data_line(cls, line: str) -> bool:
try:
_ = cls.read_imat_date(line[:24])
except ValueError:
Expand Down
21 changes: 12 additions & 9 deletions mantidimaging/core/io/saver.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,17 +36,20 @@
package_version = CheckVersion().get_version()


def write_fits(data: np.ndarray, filename: str, overwrite: bool = False, description: str | None = ""):
def write_fits(data: np.ndarray, filename: str, overwrite: bool = False, description: str | None = "") -> None:
hdu = fits.PrimaryHDU(data)
hdulist = fits.HDUList([hdu])
hdulist.writeto(filename, overwrite=overwrite)


def write_img(data: np.ndarray, filename: str, overwrite: bool = False, description: str | None = ""):
def write_img(data: np.ndarray, filename: str, overwrite: bool = False, description: str | None = "") -> None:
tifffile.imwrite(filename, data, description=description, metadata=None, software="Mantid Imaging")


def write_nxs(data: np.ndarray, filename: str, projection_angles: np.ndarray | None = None, overwrite: bool = False):
def write_nxs(data: np.ndarray,
filename: str,
projection_angles: np.ndarray | None = None,
overwrite: bool = False) -> None:
import h5py
nxs = h5py.File(filename, 'w')

Expand Down Expand Up @@ -177,7 +180,7 @@ def image_save(images: ImageStack,
return names


def nexus_save(dataset: StrictDataset, path: str, sample_name: str, save_as_float: bool):
def nexus_save(dataset: StrictDataset, path: str, sample_name: str, save_as_float: bool) -> None:
"""
Uses information from a StrictDataset to create a NeXus file.
:param dataset: The dataset to save as a NeXus file.
Expand All @@ -199,7 +202,7 @@ def nexus_save(dataset: StrictDataset, path: str, sample_name: str, save_as_floa
nexus_file.close()


def _nexus_save(nexus_file: h5py.File, dataset: StrictDataset, sample_name: str, save_as_float: bool):
def _nexus_save(nexus_file: h5py.File, dataset: StrictDataset, sample_name: str, save_as_float: bool) -> None:
"""
Takes a NeXus file and writes the StrictDataset information to it.
:param nexus_file: The NeXus file.
Expand Down Expand Up @@ -252,7 +255,7 @@ def _nexus_save(nexus_file: h5py.File, dataset: StrictDataset, sample_name: str,


def _save_processed_data_to_nexus(nexus_file: h5py.File, dataset: StrictDataset, rotation_angle: h5py.Dataset,
image_key: h5py.Dataset, save_as_float: bool):
image_key: h5py.Dataset, save_as_float: bool) -> None:
data = nexus_file.create_group(NEXUS_PROCESSED_DATA_PATH)
data["rotation_angle"] = rotation_angle
data["image_key"] = image_key
Expand All @@ -266,7 +269,7 @@ def _save_processed_data_to_nexus(nexus_file: h5py.File, dataset: StrictDataset,
process.create_dataset("version", data=np.bytes_(package_version))


def _save_image_stacks_to_nexus(dataset: StrictDataset, data_group: h5py.Group, save_as_float: bool):
def _save_image_stacks_to_nexus(dataset: StrictDataset, data_group: h5py.Group, save_as_float: bool) -> None:
combined_data_shape = (sum([len(arr) for arr in dataset.nexus_arrays]), ) + dataset.nexus_arrays[0].shape[1:]

index = 0
Expand Down Expand Up @@ -305,7 +308,7 @@ def scale_row(row):
return converted, factors


def _save_recon_to_nexus(nexus_file: h5py.File, recon: ImageStack, sample_path: str):
def _save_recon_to_nexus(nexus_file: h5py.File, recon: ImageStack, sample_path: str) -> None:
"""
Saves a recon to a NeXus file.
:param nexus_file: The NeXus file.
Expand Down Expand Up @@ -369,7 +372,7 @@ def _create_pixel_size_arrays(recon: ImageStack) -> tuple[np.ndarray, np.ndarray
return x_arr, y_arr, z_arr


def _set_nx_class(group: h5py.Group, class_name: str):
def _set_nx_class(group: h5py.Group, class_name: str) -> None:
"""
Sets the NX_class attribute of data in a NeXus file.
:param group: The h5py group.
Expand Down
4 changes: 2 additions & 2 deletions mantidimaging/core/net/help_pages.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,13 @@
SECTION_USER_GUIDE = f"{DOCS_BASE}/user_guide/"


def open_user_operation_docs(operation_name: str):
def open_user_operation_docs(operation_name: str) -> None:
page_url = "operations/index"
section = operation_name.lower().replace(" ", "-")
open_help_webpage(SECTION_USER_GUIDE, page_url, section)


def open_help_webpage(section_url: str, page_url: str, section: str | None = None):
def open_help_webpage(section_url: str, page_url: str, section: str | None = None) -> None:
if section is not None:
url = f"{section_url}{page_url}.html#{section}"
else:
Expand Down
2 changes: 1 addition & 1 deletion mantidimaging/core/parallel/shared.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ def run_compute_func(func: ComputeFuncType,
num_operations: int,
arrays: list[pu.SharedArray] | pu.SharedArray,
params: dict[str, Any],
progress=None):
progress=None) -> None:
if isinstance(arrays, pu.SharedArray):
arrays = [arrays]
all_data_in_shared_memory, data = _check_shared_mem_and_get_data(arrays)
Expand Down
6 changes: 3 additions & 3 deletions mantidimaging/core/parallel/utility.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
LOG = getLogger(__name__)


def enough_memory(shape, dtype):
def enough_memory(shape, dtype) -> bool:
return full_size_KB(shape=shape, dtype=dtype) < system_free_memory().kb()


Expand Down Expand Up @@ -103,7 +103,7 @@ def multiprocessing_necessary(shape: int, is_shared_data: bool) -> bool:
return True


def execute_impl(img_num: int, partial_func: partial, is_shared_data: bool, progress: Progress, msg: str):
def execute_impl(img_num: int, partial_func: partial, is_shared_data: bool, progress: Progress, msg: str) -> None:
task_name = f"{msg}"
progress = Progress.ensure_instance(progress, num_steps=img_num, task_name=task_name)
indices_list = range(img_num)
Expand All @@ -128,7 +128,7 @@ def run_compute_func_impl(worker_func: Callable[[int], None],
num_operations: int,
is_shared_data: bool,
progress=None,
msg: str = ""):
msg: str = "") -> None:
task_name = f"{msg}"
progress = Progress.ensure_instance(progress, num_steps=num_operations, task_name=task_name)
indices_list = range(num_operations)
Expand Down
4 changes: 2 additions & 2 deletions mantidimaging/core/reconstruct/astra_recon.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,11 @@
# Full credit for following code to Daniil Kazantzev
# Source:
# https://github.com/dkazanc/ToMoBAR/blob/5990aaa264e2f08bd9b0069c8847e5021fbf2ee2/src/Python/tomobar/supp/astraOP.py#L20-L70
def rotation_matrix2d(theta: float):
def rotation_matrix2d(theta: float) -> np.ndarray:
return np.array([[np.cos(theta), -np.sin(theta)], [np.sin(theta), np.cos(theta)]])


def vec_geom_init2d(angles_rad: ProjectionAngles, detector_spacing_x: float, center_rot_offset: float):
def vec_geom_init2d(angles_rad: ProjectionAngles, detector_spacing_x: float, center_rot_offset: float) -> np.ndarray:
angles_value = angles_rad.value
s0 = [0.0, -1.0] # source
u0 = [detector_spacing_x, 0.0] # detector coordinates
Expand Down
2 changes: 1 addition & 1 deletion mantidimaging/core/reconstruct/base_recon.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ def find_cor(images: ImageStack, slice_idx: int, start_cor: float, recon_params:
raise NotImplementedError("Base class call")

@staticmethod
def prepare_sinogram(data: np.ndarray, recon_params: ReconstructionParameters):
def prepare_sinogram(data: np.ndarray, recon_params: ReconstructionParameters) -> np.ndarray:
logged_data = BaseRecon.negative_log(data)
if recon_params.beam_hardening_coefs is not None:
coefs = np.array([0.0, 1.0] + recon_params.beam_hardening_coefs)
Expand Down
2 changes: 1 addition & 1 deletion mantidimaging/core/reconstruct/tomopy_recon.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ def single_sino(sino: np.ndarray,
cor: ScalarCoR,
proj_angles: ProjectionAngles,
recon_params: ReconstructionParameters,
progress: Progress | None = None):
progress: Progress | None = None) -> np.ndarray:
sino = BaseRecon.prepare_sinogram(sino, recon_params)
volume = tomopy.recon(tomo=[sino],
sinogram_order=True,
Expand Down
8 changes: 4 additions & 4 deletions mantidimaging/core/rotation/data_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,19 +130,19 @@ def angle_in_degrees(self) -> Degrees:
return Degrees(-np.rad2deg(np.arctan(self.gradient.value)))

@property
def has_results(self):
def has_results(self) -> bool:
return self._cached_gradient is not None and self._cached_cor is not None

@property
def empty(self):
def empty(self) -> bool:
return not self._points

@property
def num_points(self):
def num_points(self) -> int:
return len(self._points)

@property
def stack_properties(self):
def stack_properties(self) -> dict:
return {
# TODO remove float casts
const.COR_TILT_ROTATION_CENTRE: float(self.cor.value),
Expand Down
7 changes: 4 additions & 3 deletions mantidimaging/core/rotation/polyfit_correlation.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@


def do_calculate_correlation_err(store: np.ndarray, search_index: int, p0_and_180: tuple[np.ndarray, np.ndarray],
image_width: int):
image_width: int) -> None:
"""
Calculates squared sum error in the difference between the projection at 0 degrees, and the one at 180 degrees
"""
Expand Down Expand Up @@ -68,7 +68,7 @@ def find_center(images: ImageStack, progress: Progress) -> tuple[ScalarCoR, Degr
return ScalarCoR(images.h_middle + -offset), theta


def compute_correlation_error(index: int, arrays: list[Any], params: dict[str, Any]):
def compute_correlation_error(index: int, arrays: list[Any], params: dict[str, Any]) -> None:
min_correlation_error = arrays[0]
shared_projections = arrays[1]
shared_search_range = arrays[2]
Expand All @@ -79,7 +79,8 @@ def compute_correlation_error(index: int, arrays: list[Any], params: dict[str, A
(shared_projections[0], shared_projections[1]), image_width)


def _find_shift(images: ImageStack, search_range: range, min_correlation_error: np.ndarray, shift: np.ndarray):
def _find_shift(images: ImageStack, search_range: range, min_correlation_error: np.ndarray,
shift: np.ndarray) -> np.ndarray:
# Then we just find the index of the minimum one (minimum error)
min_correlation_error = np.transpose(min_correlation_error)
# argmin returns a list of where the minimum argument is found
Expand Down