Skip to content

Commit

Permalink
STYLE: Use the same alias consistently to import nibabel
Browse files Browse the repository at this point in the history
Use the same alias consistently to import `nibabel`: prefer using `nib`
over `nb` as it is more descriptive.
  • Loading branch information
jhlegarreta committed Dec 23, 2024
1 parent 6b6ba70 commit 5b84043
Show file tree
Hide file tree
Showing 10 changed files with 59 additions and 59 deletions.
16 changes: 8 additions & 8 deletions docs/notebooks/bold_realignment.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
"from shutil import copy, move\n",
"\n",
"import nest_asyncio\n",
"import nibabel as nb\n",
"import nibabel as nib\n",
"import nitransforms as nt\n",
"import numpy as np\n",
"from nipreps.synthstrip.wrappers.nipype import SynthStrip\n",
Expand Down Expand Up @@ -62,7 +62,7 @@
" avg_path = OUTPUT_DIR / bold_run.parent / f\"{bold_run.name.rsplit('_', 1)[0]}_boldref.nii.gz\"\n",
"\n",
" if not avg_path.exists():\n",
" nii = nb.load(DATA_PATH / bold_run)\n",
" nii = nib.load(DATA_PATH / bold_run)\n",
" average = nii.get_fdata().mean(-1)\n",
" avg_path.parent.mkdir(exist_ok=True, parents=True)\n",
" nii.__class__(average, nii.affine, nii.header).to_filename(avg_path)\n",
Expand All @@ -82,7 +82,7 @@
" )\n",
"\n",
" if not dilmask_path.exists():\n",
" niimsk = nb.load(bmask_path)\n",
" niimsk = nib.load(bmask_path)\n",
" niimsk.__class__(\n",
" binary_dilation(niimsk.get_fdata() > 0.0, ball(4)).astype(\"uint8\"),\n",
" niimsk.affine,\n",
Expand Down Expand Up @@ -178,7 +178,7 @@
"def plot_profile(image_path, axis=None, indexing=None, cmap=\"gray\", label=None, figsize=(15, 1.7)):\n",
" \"\"\"Plots a single image slice on a given axis or a new figure if axis is None.\"\"\"\n",
" # Load the image\n",
" image_data = nb.load(image_path).get_fdata()\n",
" image_data = nib.load(image_path).get_fdata()\n",
"\n",
" # Define default indexing if not provided\n",
" if indexing is None:\n",
Expand Down Expand Up @@ -322,7 +322,7 @@
}
],
"source": [
"datashape = nb.load(DATA_PATH / bold_runs[15]).shape\n",
"datashape = nib.load(DATA_PATH / bold_runs[15]).shape\n",
"plot_profile(\n",
" DATA_PATH / bold_runs[15],\n",
" afni_realigned[15],\n",
Expand Down Expand Up @@ -455,7 +455,7 @@
" OUTPUT_DIR / bold_run.parent / f\"{bold_run.name.rsplit('_', 1)[0]}_label-brain_mask.nii.gz\"\n",
" )\n",
"\n",
" nii = nb.load(data_path)\n",
" nii = nib.load(data_path)\n",
" hdr = nii.header.copy()\n",
" hdr.set_sform(nii.affine, code=1)\n",
" hdr.set_qform(nii.affine, code=1)\n",
Expand Down Expand Up @@ -501,7 +501,7 @@
" for t in range(n_timepoints)\n",
" ]\n",
"\n",
" nii = nb.load(DATA_PATH / bold_run)\n",
" nii = nib.load(DATA_PATH / bold_run)\n",
" nitransforms_fd[str(bold_run)] = np.array([displacement_framewise(nii, xfm) for xfm in xfms])\n",
"\n",
" hmc_xfm = nt.linear.LinearTransformsMapping(xfms)\n",
Expand Down Expand Up @@ -1724,7 +1724,7 @@
" / f\"{bold_run.name.rsplit('_', 1)[0]}_desc-realigned_bold.nii.gz\"\n",
" )\n",
"\n",
" datashape = nb.load(original).shape\n",
" datashape = nib.load(original).shape\n",
"\n",
" fig = plot_combined_profile(\n",
" (afni, original, nitransforms),\n",
Expand Down
12 changes: 6 additions & 6 deletions scripts/optimize_registration.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
from pathlib import Path
from shutil import rmtree

import nibabel as nb
import nibabel as nib
import nitransforms as nt
import numpy as np
from ConfigSpace import Configuration, ConfigurationSpace
Expand Down Expand Up @@ -91,7 +91,7 @@ async def ants(cmd, cwd, stdout, stderr, semaphore):
(rng.uniform(-0.4, 0.4, size=(60, 3)), rng.uniform(-2.0, 2.0, size=(60, 3)))
)
CONVERSIONS = [
nb.affines.from_matvec(nb.eulerangles.euler2mat(*parameters[:3]), parameters[3:])
nib.affines.from_matvec(nib.eulerangles.euler2mat(*parameters[:3]), parameters[3:])
for parameters in MOTION_PARAMETERS
]

Expand All @@ -118,7 +118,7 @@ async def train_coro(
for j in (0, 1):
fixed_path = REFERENCES[j]
brainmask_path = DATASET_PATH / fixed_path.name.replace("desc-avg", "desc-brain_mask")
refnii = nb.load(fixed_path)
refnii = nib.load(fixed_path)
xfm = nt.linear.Affine(T, reference=refnii)
ref_xfms.append(xfm)

Expand Down Expand Up @@ -157,8 +157,8 @@ async def train_coro(
fixed_path = REFERENCES[j]
brainmask_path = DATASET_PATH / fixed_path.name.replace("desc-avg", "desc-brain_mask")

fixednii = nb.load(fixed_path)
movingnii = nb.load(tmp_folder / f"test-{i:04d}.nii.gz")
fixednii = nib.load(fixed_path)
movingnii = nib.load(tmp_folder / f"test-{i:04d}.nii.gz")
xform = nt.linear.Affine(
nt.io.itk.ITKLinearTransform.from_filename(
tmp_folder / f"conversion-{i:04d}0GenericAffine.mat"
Expand All @@ -168,7 +168,7 @@ async def train_coro(
),
)

masknii = nb.load(brainmask_path)
masknii = nib.load(brainmask_path)
initial_error = utils.displacements_within_mask(
masknii,
ref_xfms[i],
Expand Down
14 changes: 7 additions & 7 deletions src/nifreeze/data/dmri.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@

import attr
import h5py
import nibabel as nb
import nibabel as nib
import numpy as np
from nitransforms.linear import Affine

Expand Down Expand Up @@ -109,7 +109,7 @@ def set_transform(self, index, affine, order=3):
dwframe = np.asanyarray(root["dataobj"][..., index])
bvec = np.asanyarray(root["gradients"][:3, index])

dwmoving = nb.Nifti1Image(dwframe, self.affine, None)
dwmoving = nib.Nifti1Image(dwframe, self.affine, None)

# resample and update orientation at index
self.dataobj[..., index] = np.asanyarray(
Expand Down Expand Up @@ -162,7 +162,7 @@ def to_nifti(self, filename, **kwargs):
if not insert_b0
else np.concatenate((self.bzero[..., np.newaxis], self.dataobj), axis=-1)
)
nii = nb.Nifti1Image(data, self.affine, None)
nii = nib.Nifti1Image(data, self.affine, None)
nii.header.set_xyzt_units("mm")
nii.to_filename(filename)

Expand Down Expand Up @@ -226,7 +226,7 @@ def load(
else:
raise RuntimeError("A gradients file is necessary")

img = nb.load(filename)
img = nib.load(filename)
fulldata = img.get_fdata(dtype="float32")
retval = DWI(
affine=img.affine,
Expand All @@ -236,17 +236,17 @@ def load(
retval.dataobj = fulldata[..., gradmsk]

if b0_file:
b0img = nb.load(b0_file)
b0img = nib.load(b0_file)
retval.bzero = np.asanyarray(b0img.dataobj)
elif not np.all(gradmsk):
retval.bzero = np.median(fulldata[..., ~gradmsk], axis=3)

if brainmask_file:
mask = nb.load(brainmask_file)
mask = nib.load(brainmask_file)
retval.brainmask = np.asanyarray(mask.dataobj)

if fmap_file:
fmapimg = nb.load(fmap_file)
fmapimg = nib.load(fmap_file)
retval.fieldmap = fmapimg.get_fdata(dtype="float32")

return retval
10 changes: 5 additions & 5 deletions src/nifreeze/data/pet.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@

import attr
import h5py
import nibabel as nb
import nibabel as nib
import numpy as np
from nitransforms.linear import Affine

Expand Down Expand Up @@ -84,7 +84,7 @@ def set_transform(self, index, affine, order=3):
root = in_file["/0"]
dframe = np.asanyarray(root["dataobj"][..., index])

dmoving = nb.Nifti1Image(dframe, self.affine, None)
dmoving = nib.Nifti1Image(dframe, self.affine, None)

Check warning on line 87 in src/nifreeze/data/pet.py

View check run for this annotation

Codecov / codecov/patch

src/nifreeze/data/pet.py#L87

Added line #L87 was not covered by tests

# resample and update orientation at index
self.dataobj[..., index] = np.asanyarray(
Expand Down Expand Up @@ -124,7 +124,7 @@ def to_filename(self, filename, compression=None, compression_opts=None):

def to_nifti(self, filename, *_):
"""Write a NIfTI 1.0 file to disk."""
nii = nb.Nifti1Image(self.dataobj, self.affine, None)
nii = nib.Nifti1Image(self.dataobj, self.affine, None)

Check warning on line 127 in src/nifreeze/data/pet.py

View check run for this annotation

Codecov / codecov/patch

src/nifreeze/data/pet.py#L127

Added line #L127 was not covered by tests
nii.header.set_xyzt_units("mm")
nii.to_filename(filename)

Expand All @@ -148,7 +148,7 @@ def load(
if filename.name.endswith(".h5"):
return PET.from_filename(filename)

img = nb.load(filename)
img = nib.load(filename)

Check warning on line 151 in src/nifreeze/data/pet.py

View check run for this annotation

Codecov / codecov/patch

src/nifreeze/data/pet.py#L151

Added line #L151 was not covered by tests
retval = PET(
dataobj=img.get_fdata(dtype="float32"),
affine=img.affine,
Expand All @@ -172,7 +172,7 @@ def load(
assert len(retval.frame_time) == retval.dataobj.shape[-1]

if brainmask_file:
mask = nb.load(brainmask_file)
mask = nib.load(brainmask_file)

Check warning on line 175 in src/nifreeze/data/pet.py

View check run for this annotation

Codecov / codecov/patch

src/nifreeze/data/pet.py#L175

Added line #L175 was not covered by tests
retval.brainmask = np.asanyarray(mask.dataobj)

return retval
4 changes: 2 additions & 2 deletions src/nifreeze/estimator.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
from pathlib import Path
from tempfile import TemporaryDirectory, mkstemp

import nibabel as nb
import nibabel as nib
from tqdm import tqdm

from nifreeze import utils as eutils
Expand Down Expand Up @@ -215,7 +215,7 @@ def _prepare_brainmask_data(brainmask, affine):
bmask_img = None
if brainmask is not None:
_, bmask_img = mkstemp(suffix="_bmask.nii.gz")
nb.Nifti1Image(brainmask.astype("uint8"), affine, None).to_filename(bmask_img)
nib.Nifti1Image(brainmask.astype("uint8"), affine, None).to_filename(bmask_img)
return bmask_img


Expand Down
8 changes: 4 additions & 4 deletions src/nifreeze/registration/ants.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
from pathlib import Path
from warnings import warn

import nibabel as nb
import nibabel as nib
import nitransforms as nt
import numpy as np
from nipype.interfaces.ants.registration import Registration
Expand Down Expand Up @@ -81,7 +81,7 @@ def _to_nifti(
from nifreeze.data.filtering import advanced_clip

data = advanced_clip(data)
nii = nb.Nifti1Image(
nii = nib.Nifti1Image(
data,
affine,
None,
Expand Down Expand Up @@ -404,12 +404,12 @@ def generate_command(
def _run_registration(
fixed: Path,
moving: Path,
bmask_img: nb.spatialimages.SpatialImage,
bmask_img: nib.spatialimages.SpatialImage,
em_affines: np.ndarray,
affine: np.ndarray,
shape: tuple[int, int, int],
bval: int,
fieldmap: nb.spatialimages.SpatialImage,
fieldmap: nib.spatialimages.SpatialImage,
i_iter: int,
vol_idx: int,
dirname: Path,
Expand Down
10 changes: 5 additions & 5 deletions src/nifreeze/registration/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,13 @@

from itertools import product

import nibabel as nb
import nibabel as nib
import nitransforms as nt
import numpy as np


def displacements_within_mask(
mask_img: nb.spatialimages.SpatialImage,
mask_img: nib.spatialimages.SpatialImage,
test_xfm: nt.base.BaseTransform,
reference_xfm: nt.base.BaseTransform | None = None,
) -> np.ndarray:
Expand Down Expand Up @@ -67,7 +67,7 @@ def displacements_within_mask(
# Mask data as boolean (True for voxels inside the mask)
maskdata = np.asanyarray(mask_img.dataobj) > 0
# Convert voxel coordinates to world coordinates using affine transform
xyz = nb.affines.apply_affine(
xyz = nib.affines.apply_affine(
mask_img.affine,
np.argwhere(maskdata),
)
Expand All @@ -80,7 +80,7 @@ def displacements_within_mask(


def displacement_framewise(
img: nb.spatialimages.SpatialImage,
img: nib.spatialimages.SpatialImage,
test_xfm: nt.base.BaseTransform,
radius: float = 50.0,
):
Expand All @@ -107,7 +107,7 @@ def displacement_framewise(
# Compute the center of the image in voxel space
center_ijk = 0.5 * (np.array(img.shape[:3]) - 1)
# Convert to world coordinates
center_xyz = nb.affines.apply_affine(affine, center_ijk)
center_xyz = nib.affines.apply_affine(affine, center_ijk)

Check warning on line 110 in src/nifreeze/registration/utils.py

View check run for this annotation

Codecov / codecov/patch

src/nifreeze/registration/utils.py#L110

Added line #L110 was not covered by tests
# Generate coordinates of points at radius distance from center
fd_coords = np.array(list(product(*((radius, -radius),) * 3))) + center_xyz
# Compute the average displacement from the test transformation
Expand Down
18 changes: 9 additions & 9 deletions test/test_dmri.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
#
"""Unit tests exercising the dMRI data structure."""

import nibabel as nb
import nibabel as nib
import numpy as np
import pytest

Expand Down Expand Up @@ -69,10 +69,10 @@ def _create_dwi_random_data(
b0_dataobj,
fieldmap_dataobj,
):
dwi = nb.Nifti1Image(dwi_dataobj, affine)
brainmask = nb.Nifti1Image(brainmask_dataobj, affine)
b0 = nb.Nifti1Image(b0_dataobj, affine)
fieldmap = nb.Nifti1Image(fieldmap_dataobj, affine)
dwi = nib.Nifti1Image(dwi_dataobj, affine)
brainmask = nib.Nifti1Image(brainmask_dataobj, affine)
b0 = nib.Nifti1Image(b0_dataobj, affine)
fieldmap = nib.Nifti1Image(fieldmap_dataobj, affine)

return dwi, brainmask, b0, fieldmap

Expand All @@ -91,11 +91,11 @@ def _serialize_dwi_data(
gradients_fname = _tmp_path / "gradients.txt"
fieldmap_fname = _tmp_path / "fieldmap.nii.gz"

nb.save(dwi, dwi_fname)
nb.save(brainmask, brainmask_fname)
nb.save(b0, b0_fname)
nib.save(dwi, dwi_fname)
nib.save(brainmask, brainmask_fname)
nib.save(b0, b0_fname)
np.savetxt(gradients_fname, gradients.T)
nb.save(fieldmap, fieldmap_fname)
nib.save(fieldmap, fieldmap_fname)

return (
dwi_fname,
Expand Down
20 changes: 10 additions & 10 deletions test/test_integration.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@

from os import cpu_count

import nibabel as nb
import nibabel as nib
import nitransforms as nt
import numpy as np

Expand All @@ -37,19 +37,19 @@ def test_proximity_estimator_trivial_model(datadir, tmp_path):
"""Check the proximity of transforms estimated by the estimator with a trivial B0 model."""

dwdata = DWI.from_filename(datadir / "dwi.h5")
b0nii = nb.Nifti1Image(dwdata.bzero, dwdata.affine, None)
masknii = nb.Nifti1Image(dwdata.brainmask.astype(np.uint8), dwdata.affine, None)
b0nii = nib.Nifti1Image(dwdata.bzero, dwdata.affine, None)
masknii = nib.Nifti1Image(dwdata.brainmask.astype(np.uint8), dwdata.affine, None)

# Generate a list of large-yet-plausible bulk-head motion.
xfms = nt.linear.LinearTransformsMapping(
[
nb.affines.from_matvec(nb.eulerangles.euler2mat(x=0.03, z=0.005), (0.8, 0.2, 0.2)),
nb.affines.from_matvec(nb.eulerangles.euler2mat(x=0.02, z=0.005), (0.8, 0.2, 0.2)),
nb.affines.from_matvec(nb.eulerangles.euler2mat(x=0.02, z=0.02), (0.4, 0.2, 0.2)),
nb.affines.from_matvec(nb.eulerangles.euler2mat(x=-0.02, z=0.02), (0.4, 0.2, 0.2)),
nb.affines.from_matvec(nb.eulerangles.euler2mat(x=-0.02, z=0.002), (0.0, 0.2, 0.2)),
nb.affines.from_matvec(nb.eulerangles.euler2mat(y=-0.02, z=0.002), (0.0, 0.2, 0.2)),
nb.affines.from_matvec(nb.eulerangles.euler2mat(y=-0.01, z=0.002), (0.0, 0.4, 0.2)),
nib.affines.from_matvec(nib.eulerangles.euler2mat(x=0.03, z=0.005), (0.8, 0.2, 0.2)),
nib.affines.from_matvec(nib.eulerangles.euler2mat(x=0.02, z=0.005), (0.8, 0.2, 0.2)),
nib.affines.from_matvec(nib.eulerangles.euler2mat(x=0.02, z=0.02), (0.4, 0.2, 0.2)),
nib.affines.from_matvec(nib.eulerangles.euler2mat(x=-0.02, z=0.02), (0.4, 0.2, 0.2)),
nib.affines.from_matvec(nib.eulerangles.euler2mat(x=-0.02, z=0.002), (0.0, 0.2, 0.2)),
nib.affines.from_matvec(nib.eulerangles.euler2mat(y=-0.02, z=0.002), (0.0, 0.2, 0.2)),
nib.affines.from_matvec(nib.eulerangles.euler2mat(y=-0.01, z=0.002), (0.0, 0.4, 0.2)),
],
reference=b0nii,
)
Expand Down
Loading

0 comments on commit 5b84043

Please sign in to comment.