Skip to content

Commit

Permalink
ENH: Make type hinting compatible with Python 3.9
Browse files Browse the repository at this point in the history
Make type hinting compatible with Python 3.9: use `Union` instead of the
pipe operator `|` to support type hints in Python 3.9. The pipe operator
was overloaded for writing union types starting Python 3.10:
https://peps.python.org/pep-0604/
https://docs.python.org/3.9/library/typing.html
https://docs.python.org/3.10/library/typing.html

Inadvertently let go through in commits 44d0ff6 and 8c18471.
  • Loading branch information
jhlegarreta committed Dec 27, 2024
1 parent e89ab63 commit 41ed328
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 16 deletions.
10 changes: 5 additions & 5 deletions nireports/reportlets/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ def robust_set_limits(


def _get_limits(
nifti_file: str | npt.NDArray,
nifti_file: ty.Union[str, npt.NDArray],
only_plot_noise: bool = False,
) -> tuple[float, float]:
if isinstance(nifti_file, str):
Expand All @@ -91,7 +91,7 @@ def _get_limits(
return vmin, vmax


def svg_compress(image: str, compress: bool | L["auto"] = "auto") -> str:
def svg_compress(image: str, compress: ty.Union[bool, L["auto"]] = "auto") -> str:
"""Generate a blob SVG from a matplotlib figure, may perform compression."""
# Check availability of svgo and cwebp
has_compress = all((which("svgo"), which("cwebp")))
Expand Down Expand Up @@ -239,7 +239,7 @@ def combine_svg(svg_list: list[SVGFigure], axis="vertical") -> SVGFigure:
def extract_svg(
display_object: DisplayObject,
dpi: int = 300,
compress: bool | L["auto"] = "auto",
compress: ty.Union[bool, L["auto"]] = "auto",
) -> str:
"""Remove the preamble of the svg files generated with nilearn."""
image_svg = svg2str(display_object, dpi)
Expand Down Expand Up @@ -316,7 +316,7 @@ def cuts_from_bbox(mask_nii: nb.Nifti1Image, cuts: int = 3) -> dict[str, list[fl


def _3d_in_file(
in_file: nb.Nifti1Image | str | os.PathLike | list[str | os.PathLike],
in_file: ty.Union[nb.Nifti1Image, str, os.PathLike, list[ty.Union[str, os.PathLike]]],
) -> nb.Nifti1Image:
"""if self.inputs.in_file is 3d, return it.
if 4d, pick an arbitrary volume and return that.
Expand All @@ -342,7 +342,7 @@ def compose_view(
bg_svgs: list[SVGFigure],
fg_svgs: list[SVGFigure],
ref: int = 0,
out_file: str | os.PathLike[str] = "report.svg",
out_file: ty.Union[str, os.PathLike[str]] = "report.svg",
) -> str:
"""
Compose svgs into one standalone svg with CSS flickering animation.
Expand Down
10 changes: 5 additions & 5 deletions nireports/tools/ndimage.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@
Mat = npt.NDArray[np.float64]


def rotation2canonical(img: SpatialImage) -> Mat | None:
def rotation2canonical(img: SpatialImage) -> ty.Union[Mat, None]:
"""Calculate the rotation w.r.t. cardinal axes of input image."""
img = nb.as_closest_canonical(img)
# XXX: SpatialImage.affine needs to be typed
Expand All @@ -52,7 +52,7 @@ def rotation2canonical(img: SpatialImage) -> Mat | None:
return r


def rotate_affine(img: SpatImgT, rot: Mat | None = None) -> SpatImgT:
def rotate_affine(img: SpatImgT, rot: ty.Union[Mat, None] = None) -> SpatImgT:
"""Rewrite the affine of a spatial image."""
if rot is None:
return img
Expand All @@ -63,16 +63,16 @@ def rotate_affine(img: SpatImgT, rot: Mat | None = None) -> SpatImgT:
return img.__class__(img.dataobj, affine, img.header)


def load_api(path: str | os.PathLike[str], api: type[ImgT]) -> ImgT:
def load_api(path: ty.Union[str, os.PathLike[str]], api: type[ImgT]) -> ImgT:
img = nb.load(path)
if not isinstance(img, api):
raise TypeError(f"File {path} does not implement {api} interface")
return img


def _get_values_inside_a_mask(
main_file: str | os.PathLike[str],
mask_file: str | os.PathLike[str],
main_file: ty.Union[str, os.PathLike[str]],
mask_file: ty.Union[str, os.PathLike[str]],
) -> npt.NDArray[np.float64]:
main_nii = load_api(main_file, SpatialImage)
main_data = main_nii.get_fdata()
Expand Down
13 changes: 7 additions & 6 deletions nireports/tools/timeseries.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
# niworkflows/utils/timeseries.py
"""Extracting signals from NIfTI and CIFTI2 files."""

import typing as ty
from collections.abc import Sequence

import nibabel as nb
Expand All @@ -36,7 +37,7 @@
from .ndimage import load_api


def get_tr(img: nb.Nifti1Image | nb.Cifti2Image) -> float:
def get_tr(img: ty.Union[nb.Nifti1Image, nb.Cifti2Image]) -> float:
"""
Attempt to extract repetition time from NIfTI/CIFTI header.
Expand All @@ -62,7 +63,7 @@ def get_tr(img: nb.Nifti1Image | nb.Cifti2Image) -> float:


def cifti_timeseries(
dataset: str | nb.Cifti2Image,
dataset: ty.Union[str, nb.Cifti2Image],
) -> tuple[npt.NDArray[np.float32], dict[str, list[int]]]:
"""Extract timeseries from CIFTI2 dataset."""
dataset = load_api(dataset, nb.Cifti2Image) if isinstance(dataset, str) else dataset
Expand All @@ -86,12 +87,12 @@ def cifti_timeseries(


def nifti_timeseries(
dataset: str | nb.Nifti1Image,
segmentation: str | nb.Nifti1Image | None = None,
dataset: ty.Union[str, nb.Nifti1Image],
segmentation: ty.Union[str, nb.Nifti1Image, None] = None,
labels: Sequence[str] = ("Ctx GM", "dGM", "WM+CSF", "Cb", "Crown"),
remap_rois: bool = False,
lut: npt.NDArray[np.uint8] | None = None,
) -> tuple[npt.NDArray[np.float32], dict[str, list[int]] | None]:
lut: ty.Union[npt.NDArray[np.uint8], None] = None,
) -> tuple[npt.NDArray[np.float32], ty.Union[dict[str, list[int]], None]]:
"""Extract timeseries from NIfTI1/2 datasets."""
dataset = load_api(dataset, nb.Nifti1Image) if isinstance(dataset, str) else dataset
data: npt.NDArray[np.float32] = dataset.get_fdata(dtype="float32").reshape(
Expand Down

0 comments on commit 41ed328

Please sign in to comment.