Skip to content

Commit

Permalink
Merge branch 'master' of github.com:scilus/scilpy
Browse files Browse the repository at this point in the history
  • Loading branch information
arnaudbore committed Feb 10, 2025
2 parents e613c3e + 8778f77 commit 10ade43
Show file tree
Hide file tree
Showing 26 changed files with 91 additions and 74 deletions.
2 changes: 1 addition & 1 deletion docs/source/fake_files/uncompress.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-


def uncompress():
def streamlines_to_voxel_coordinates():
pass
2 changes: 1 addition & 1 deletion scilpy/denoise/asym_filtering.py
Original file line number Diff line number Diff line change
Expand Up @@ -523,7 +523,7 @@ def cosine_filtering(in_sh, sh_order=8, sh_basis='descoteaux07',
Filtered signal as SH coefficients in full SH basis.
"""
# Load the sphere used for projection of SH
sphere = get_sphere(sphere_str)
sphere = get_sphere(name=sphere_str)

# Normalized filter for each sf direction
weights = _get_cosine_weights(sphere, dot_sharpness, sigma)
Expand Down
6 changes: 4 additions & 2 deletions scilpy/image/volume_operations.py
Original file line number Diff line number Diff line change
Expand Up @@ -284,14 +284,16 @@ def register_image(static, static_grid2world, moving, moving_grid2world,
# Then, rigid transformation (translation + rotation)
transform = RigidTransform3D()
rigid = reg_obj.optimize(static, moving, transform, params0,
static_grid2world, moving_grid2world,
static_grid2world=static_grid2world,
moving_grid2world=moving_grid2world,
starting_affine=c_of_mass.affine)

if transformation_type == 'affine':
# Finally, affine transformation (translation + rotation + scaling)
transform = AffineTransform3D()
affine = reg_obj.optimize(static, moving, transform, params0,
static_grid2world, moving_grid2world,
static_grid2world=static_grid2world,
moving_grid2world=moving_grid2world,
starting_affine=rigid.affine)

mapper = affine
Expand Down
2 changes: 1 addition & 1 deletion scilpy/io/btensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ def generate_btensor_input(in_dwis, in_bvals, in_bvecs, in_bdeltas,
ub_deltas_full = np.take_along_axis(np.asarray(ub_deltas_full),
sorted_indices, axis=0)
# Creating the corresponding gtab
gtab_full = gradient_table(bvals_full, bvecs_full,
gtab_full = gradient_table(bvals_full, bvecs=bvecs_full,
b0_threshold=bvals_full.min(),
btens=b_shapes)

Expand Down
3 changes: 2 additions & 1 deletion scilpy/io/deprecator.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,8 @@ def deprecate_script(script, message, from_version):
def _deprecation_decorator(func):
@wraps(func)
def _wrapper(*args, **kwargs):
if cmp_pkg_version(current_version, expiration_version) >= 0:
if cmp_pkg_version(current_version,
pkg_version_str=expiration_version) >= 0:
footer = f"""\
{message}
{EXPIRATION_FOOTER.format(
Expand Down
4 changes: 2 additions & 2 deletions scilpy/tracking/propagator.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

import numpy as np

import dipy
from dipy.data import get_sphere
from dipy.io.stateful_tractogram import Space, Origin
from dipy.reconst.shm import sh_to_sf_matrix

Expand Down Expand Up @@ -278,7 +278,7 @@ def __init__(self, datavolume, step_size, rk_order, dipy_sphere,
"""
super().__init__(datavolume, step_size, rk_order, space, origin)

self.sphere = dipy.data.get_sphere(dipy_sphere).subdivide(n=sub_sphere)
self.sphere = get_sphere(name=dipy_sphere).subdivide(n=sub_sphere)
self.dirs = np.zeros(len(self.sphere.vertices), dtype=np.ndarray)
for i in range(len(self.sphere.vertices)):
self.dirs[i] = TrackingDirection(self.sphere.vertices[i], i)
Expand Down
5 changes: 1 addition & 4 deletions scilpy/tracking/tracker.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,15 @@
import itertools
import logging
import multiprocessing
from operator import mod
import os
import sys
from tempfile import TemporaryDirectory
from time import perf_counter
import traceback
from typing import Union
from tqdm import tqdm

import numpy as np
from dipy.data import get_sphere
from dipy.core.sphere import HemiSphere
from dipy.io.stateful_tractogram import Space
from dipy.reconst.shm import sh_to_sf_matrix
from dipy.tracking.streamlinespeed import compress_streamlines
Expand Down Expand Up @@ -535,7 +532,7 @@ def __init__(self, sh, mask, seeds, step_size, max_nbr_pts,
np.array_split(seeds + 0.5, np.ceil(len(seeds)/batch_size))

if sphere is None:
self.sphere = get_sphere("repulsion724")
self.sphere = get_sphere(name="repulsion724")
else:
self.sphere = sphere

Expand Down
2 changes: 1 addition & 1 deletion scilpy/tracking/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -322,7 +322,7 @@ def get_direction_getter(in_img, algo, sphere, sub_sphere, theta, sh_basis,
img_data = nib.load(in_img).get_fdata(dtype=np.float32)

sphere = HemiSphere.from_sphere(
get_sphere(sphere)).subdivide(n=sub_sphere)
get_sphere(name=sphere)).subdivide(n=sub_sphere)

# Theta depends on user choice and algorithm
theta = get_theta(theta, algo)
Expand Down
7 changes: 4 additions & 3 deletions scilpy/tractanalysis/connectivity_segmentation.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,8 @@ def compute_connectivity(indices, atlas_data, real_labels, segmenting_func):
----------
indices: ArraySequence
The list of 3D indices [i, j, k] of all voxels traversed by all
streamlines. This is the output of our uncompress function.
streamlines. This is the output of the
streamlines_to_voxel_coordinates function.
atlas_data: np.ndarray
The loaded image containing the labels.
real_labels: np.ndarray
Expand Down Expand Up @@ -155,9 +156,9 @@ def construct_hdf5_from_connectivity(
sft: StatefulTractogram
The tractogram.
indices: ArraySequence
Results from uncompress.
Results from streamlines_to_voxel_coordinates.
points_to_idx: ArraySequence
Results from uncompress.
Results from streamlines_to_voxel_coordinates.
real_labels: np.ndarray
The labels.
con_info: dict
Expand Down
8 changes: 4 additions & 4 deletions scilpy/tractanalysis/fibertube_scoring.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
dist_segment_segment,
dist_point_segment)
from scilpy.tracking.utils import tqdm_if_verbose
from scilpy.tractograms.uncompress import uncompress
from scilpy.tractograms.uncompress import streamlines_to_voxel_coordinates


def fibertube_density(sft, samples_per_voxel_axis, verbose=False):
Expand Down Expand Up @@ -61,10 +61,10 @@ def fibertube_density(sft, samples_per_voxel_axis, verbose=False):
len(sft.streamlines))
max_diameter = np.max(diameters)

# Everything will be in vox and corner for uncompress.
# Everything will be in vox and corner for streamlines_to_voxel_coordinates.
sft.to_vox()
sft.to_corner()
vox_idx_for_streamline = uncompress(sft.streamlines)
vox_idx_for_streamline = streamlines_to_voxel_coordinates(sft.streamlines)
mask_idx = np.concatenate(vox_idx_for_streamline)
mask = np.zeros((sft.dimensions), dtype=np.uint8)
# Numpy array indexing in 3D works like this
Expand Down Expand Up @@ -222,7 +222,7 @@ def min_external_distance(sft, verbose):
min_external_distance = external_distance
min_external_distance_vec = (
get_external_vector_from_centerline_vector(vector, rp, rq)
)
)

return min_external_distance, min_external_distance_vec

Expand Down
2 changes: 1 addition & 1 deletion scilpy/tractanalysis/todi.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ def __init__(self, img_shape, sphere_type='repulsion724'):
"""
assert len(img_shape) == 3

self.sphere = get_sphere(sphere_type)
self.sphere = get_sphere(name=sphere_type)
self.nb_sphere_vts = len(self.sphere.vertices)

self.img_shape = img_shape
Expand Down
34 changes: 17 additions & 17 deletions scilpy/tractograms/streamline_and_mask_operations.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

from scipy.ndimage import map_coordinates

from scilpy.tractograms.uncompress import uncompress
from scilpy.tractograms.uncompress import streamlines_to_voxel_coordinates
from scilpy.tractograms.streamline_operations import \
resample_streamlines_step_size

Expand Down Expand Up @@ -87,8 +87,8 @@ def get_head_tail_density_maps(sft, point_to_select=1, to_millimeters=False):
streamlines = sft.streamlines

dimensions = sft.dimensions
# Uncompress the streamlines to get the indices of the voxels intersected
list_indices, points_to_indices = uncompress(
# Get the indices of the voxels intersected
list_indices, points_to_indices = streamlines_to_voxel_coordinates(
streamlines, return_mapping=True)

# Initialize the endpoints maps
Expand Down Expand Up @@ -292,13 +292,16 @@ def cut_streamlines_with_mask(
sft.to_vox()
sft.to_corner()

# Uncompress the streamlines to get the indices of the voxels
# Get the indices of the voxels
# intersected by the streamlines and the mapping from points to indices
indices, points_to_idx = uncompress(sft.streamlines,
return_mapping=True)
indices, points_to_idx = streamlines_to_voxel_coordinates(
sft.streamlines,
return_mapping=True
)

if len(sft.streamlines[0]) != len(points_to_idx[0]):
raise ValueError("Error in the uncompress function. Try running the "
raise ValueError("Error in the streamlines_to_voxel_coordinates "
"function. Try running the "
"scil_tractogram_remove_invalid.py script with the \n"
"--remove_single_point and "
"--remove_overlapping_points options.")
Expand Down Expand Up @@ -383,10 +386,14 @@ def cut_streamlines_between_labels(
mask = label_data_2 != unique_vals[1]
label_data_2[mask] = 0

(indices, points_to_idx) = uncompress(sft.streamlines, return_mapping=True)
(indices, points_to_idx) = streamlines_to_voxel_coordinates(
sft.streamlines,
return_mapping=True
)

if len(sft.streamlines[0]) != len(points_to_idx[0]):
raise ValueError("Error in the uncompress function. Try running the "
raise ValueError("Error in the streamlines_to_voxel_coordinates "
"function. Try running the "
"scil_tractogram_remove_invalid.py script with the \n"
"--remove_single_point and "
"--remove_overlapping_points options.")
Expand Down Expand Up @@ -624,15 +631,8 @@ def compute_streamline_segment(orig_strl, inter_vox, in_vox_idx, out_vox_idx,
nb_points = nb_points_orig_strl + nb_add_points
orig_segment_len = len(orig_strl[in_strl_point:out_strl_point + 1])

# TODO: Fix the bug in `uncompress` and remove this
# There is a bug with `uncompress` where the number of `points_to_indices`
# is not the same as the number of points in the streamline. This is
# a temporary fix.
segment_len = min(
nb_points,
orig_segment_len + nb_add_points)
# Initialize the new streamline segment
segment = np.zeros((segment_len, 3))
segment = np.zeros((nb_points, 3))
# offset for indexing in case there are new points
offset = 0

Expand Down
47 changes: 30 additions & 17 deletions scilpy/tractograms/tests/test_streamline_and_mask_operations.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
get_head_tail_density_maps,
CuttingStyle)
from scilpy.image.labels import get_labels_from_mask
from scilpy.tractograms.uncompress import uncompress
from scilpy.tractograms.uncompress import streamlines_to_voxel_coordinates


fetch_data(get_testing_files_dict(), keys=['tractograms.zip'])
Expand Down Expand Up @@ -147,12 +147,15 @@ def test_trim_streamline_in_mask():
sft.to_vox()
sft.to_corner()

idices, points_to_idx = uncompress(sft.streamlines, return_mapping=True)
strl_indices = idices[0]
points_to_idices = points_to_idx[0]
indices, points_to_idx = streamlines_to_voxel_coordinates(
sft.streamlines,
return_mapping=True
)
strl_indices = indices[0]
points_to_indices = points_to_idx[0]

cut = _trim_streamline_in_mask(
strl_indices, sft.streamlines[0], points_to_idices, center_roi)
strl_indices, sft.streamlines[0], points_to_indices, center_roi)

in_result = os.path.join(SCILPY_HOME, 'tractograms',
'streamline_and_mask_operations',
Expand Down Expand Up @@ -200,12 +203,15 @@ def test_trim_streamline_in_mask_keep_longest():
sft.to_vox()
sft.to_corner()

idices, points_to_idx = uncompress(sft.streamlines, return_mapping=True)
strl_indices = idices[0]
points_to_idices = points_to_idx[0]
indices, points_to_idx = streamlines_to_voxel_coordinates(
sft.streamlines,
return_mapping=True
)
strl_indices = indices[0]
points_to_indices = points_to_idx[0]

cut = _trim_streamline_in_mask_keep_longest(
strl_indices, sft.streamlines[0], points_to_idices, center_roi)
strl_indices, sft.streamlines[0], points_to_indices, center_roi)

in_result = os.path.join(SCILPY_HOME, 'tractograms',
'streamline_and_mask_operations',
Expand Down Expand Up @@ -250,12 +256,15 @@ def test_trim_streamline_endpoints_in_mask():
sft.to_vox()
sft.to_corner()

idices, points_to_idx = uncompress(sft.streamlines, return_mapping=True)
strl_indices = idices[0]
points_to_idices = points_to_idx[0]
indices, points_to_idx = streamlines_to_voxel_coordinates(
sft.streamlines,
return_mapping=True
)
strl_indices = indices[0]
points_to_indices = points_to_idx[0]

cut = _trim_streamline_endpoints_in_mask(
strl_indices, sft.streamlines[0], points_to_idices,
strl_indices, sft.streamlines[0], points_to_indices,
head_tail_offset_rois)

in_result = os.path.join(SCILPY_HOME, 'tractograms',
Expand Down Expand Up @@ -334,10 +343,14 @@ def test_compute_streamline_segment():

# Split head and tail from mask
roi_data_1, roi_data_2 = split_mask_blobs_kmeans(
head_tail_offset_rois, nb_clusters=2)

(indices, points_to_idx) = uncompress(one_sft.streamlines,
return_mapping=True)
head_tail_offset_rois,
nb_clusters=2
)

(indices, points_to_idx) = streamlines_to_voxel_coordinates(
one_sft.streamlines,
return_mapping=True
)

strl_indices = indices[0]
# Find the first and last "voxels" of the streamline that are in the
Expand Down
8 changes: 5 additions & 3 deletions scilpy/tractograms/uncompress.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ cdef struct Pointers:

@cython.boundscheck(False)
@cython.cdivision(True)
def uncompress(streamlines, return_mapping=False):
def streamlines_to_voxel_coordinates(streamlines, return_mapping=False):
"""
Get the indices of the voxels traversed by each streamline; then returns
an ArraySequence of indices, i.e. [i, j, k] coordinates.
Expand Down Expand Up @@ -102,7 +102,9 @@ def uncompress(streamlines, return_mapping=False):
pointers.points_to_index_out = &points_to_index_view_out[0]

while 1:
at_point = _uncompress(&pointers, at_point, max_points - 1)
at_point = _streamlines_to_voxel_coordinates(&pointers,
at_point,
max_points - 1)
if pointers.lengths_in == pointers.lengths_in_end:
# Job finished, we can return the streamlines
break
Expand Down Expand Up @@ -147,7 +149,7 @@ cdef inline void c_get_closest_edge(double *p,

@cython.boundscheck(False)
@cython.cdivision(True)
cdef cnp.npy_intp _uncompress(
cdef cnp.npy_intp _streamlines_to_voxel_coordinates(
Pointers* pointers,
cnp.npy_intp at_point,
cnp.npy_intp max_points) nogil:
Expand Down
2 changes: 1 addition & 1 deletion scripts/scil_aodf_metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ def main():
sh_img = nib.load(args.in_sh)
sh = sh_img.get_fdata()

sphere = get_sphere(args.sphere)
sphere = get_sphere(name=args.sphere)

sh_basis, is_legacy = parse_sh_basis_arg(args)
sh_order, full_basis = get_sh_order_and_fullness(sh.shape[-1])
Expand Down
2 changes: 1 addition & 1 deletion scripts/scil_bids_validate.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ def get_data(layout, nSub, dwis, t1s, fs, default_readout, clean):
Default readout time
clean: Boolean
If set, if some critical files are missing it will
If True, if some critical files are missing it will
remove this specific subject/session/run
Returns
Expand Down
2 changes: 1 addition & 1 deletion scripts/scil_fodf_metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ def main():
mask = get_data_as_mask(nib.load(args.mask),
dtype=bool) if args.mask else None

sphere = get_sphere(args.sphere)
sphere = get_sphere(name=args.sphere)
sh_basis, is_legacy = parse_sh_basis_arg(args)

# Computing peaks
Expand Down
3 changes: 1 addition & 2 deletions scripts/scil_mti_maps_MT.py
Original file line number Diff line number Diff line change
Expand Up @@ -182,8 +182,7 @@ def main():
contrast_names_og = contrast_names

# check data
input_maps_flat_list = [m for _list in input_maps_lists for m in _list]
assert_inputs_exist(parser, args.in_mtoff_pd + input_maps_flat_list,
assert_inputs_exist(parser, args.in_mtoff_pd + input_maps_lists,
optional=args.in_mtoff_t1 or [] + [args.mask])

# Define reference image for saving maps
Expand Down
Loading

0 comments on commit 10ade43

Please sign in to comment.