scilpy.tracking package

scilpy.tracking.propagator module

class scilpy.tracking.propagator.AbstractPropagator(datavolume, step_size, rk_order, space, origin)[source]

Bases: object

Abstract class for propagator object. “Propagation” means continuing the streamline a step further. The propagator is thus responsible for sampling the next direction at current step through Runge-Kutta integration (whereas the tracker using this propagator will be responsible for the processing parameters, number of streamlines, stopping criteria, etc.).

Propagation depends on the type of data (ex, DTI, fODF) and the way to get a direction from it (ex, det, prob).

finalize_streamline(last_pos, v_in)[source]

Return the last position of the streamline.

Parameters:
  • last_pos (ndarray (3,)) – Last propagated position. Important, position must be in the same space and origin as self.space, self.origin!

  • v_in (TrackingDirection) – Last propagated direction.

Returns:

final_pos – Position of the final point of the streamline. Return None, or last_pos, if no last step is wished.

Return type:

ndarray (3,)

prepare_backward(line, forward_dir)[source]

Called at the beginning of backward tracking, in case we need to reset some parameters

Parameters:
  • line (List) – Result from the forward tracking, reversed.

  • forward_dir (ndarray (3,)) – v_in chosen at the forward step.

Returns:

v_in – Last direction of the streamline. If the streamline contains only the seeding point (forward tracking failed), simply inverse the forward direction.

Return type:

ndarray (3,)

prepare_forward(seeding_pos, random_generator)[source]

Prepare information necessary at the first point of the streamline for forward propagation: v_in and any other information necessary for the self.propagate method.

Parameters:
  • seeding_pos (tuple(x,y,z)) – The seeding position. Important, position must be in the same space and origin as self.space, self.origin!

  • random_generator (numpy Generator.)

Returns:

tracking_info – Any tracking information necessary for the propagation. Return PropagationStatus.ERROR if no good tracking direction can be set at current seeding position.

Return type:

Any

propagate(line, v_in)[source]

Given the current position and direction, computes the next position and direction using Runge-Kutta integration method. If no valid tracking direction is available, v_in is chosen.

Parameters:
  • line (list[ndarrray (3,)]) – Current position.

  • v_in (ndarray (3,) or TrackingDirection) – Previous tracking direction.

Returns:

  • new_pos (ndarray (3,)) – The new segment position, expressed in propagator’s space and origin.

  • new_dir (ndarray (3,) or TrackingDirection) – The new segment direction.

  • is_direction_valid (bool) – True if new_dir is valid.

reset_data(new_data=None)[source]

Reset data before starting a new process. In current implementation, we reset the internal data to None before starting a multiprocess, then load it back when process has started.

Parameters:

new_data (Any) – Will replace self.datavolume.data.

class scilpy.tracking.propagator.ODFPropagator(datavolume, step_size, rk_order, algo, basis, sf_threshold, sf_threshold_init, theta, dipy_sphere='symmetric724', sub_sphere=0, min_separation_angle=0.19634954084936207, space=Space.VOX, origin=Origin.NIFTI, is_legacy=True)[source]

Bases: PropagatorOnSphere

Propagator on ODFs/fODFs. Algo can be det or prob.

prepare_forward(seeding_pos, random_generator)[source]

Prepare information necessary at the first point of the streamline for forward propagation: v_in and any other information necessary for the self.propagate method.

About v_in, it is used for two things:

  • To sample the next direction based on _sample_next_direction method.

    Ex, with fODF, it defines a cone theta of accepable directions.

  • If no valid next dir are found, continue straight.

Parameters:
  • seeding_pos (tuple(x,y,z)) – The seeding position. Important, position must be in the same space and origin as self.space, self.origin!

  • random_generator (numpy Generator)

Returns:

v_in – The “fake” previous direction at first step. Could be None if your propagator can propagate without knowledge of previous direction. Return PropagationStatus.Error if no good tracking direction can be set at current seeding position.

Return type:

TrackingDirection

class scilpy.tracking.propagator.PropagationStatus(value)[source]

Bases: Enum

An enumeration.

ERROR = 1
class scilpy.tracking.propagator.PropagatorOnSphere(datavolume, step_size, rk_order, dipy_sphere, sub_sphere, space, origin)[source]

Bases: AbstractPropagator

prepare_backward(line, forward_dir)[source]

Called at the beginning of backward tracking, in case we need to reset some parameters

Parameters:
  • line (List) – Result from the forward tracking, reversed.

  • forward_dir (ndarray (3,)) – v_in chosen at the forward step.

Returns:

v_in – Last direction of the streamline, of if it contains only the seeding point (forward tracking failed), simply inverse the forward direction.

Return type:

ndarray (3,)

scilpy.tracking.seed module

class scilpy.tracking.seed.SeedGenerator(data, voxres, space=Space.VOX, origin=Origin.NIFTI, n_repeats=1)[source]

Bases: object

Class to get seeding positions.

Generated seeds are in voxmm space, origin=corner. Ex: a seed sampled exactly at voxel i,j,k = (0,1,2), with resolution 3x3x3mm will have coordinates x,y,z = (0, 3, 6).

Using get_next_pos, seeds are placed randomly within the voxel. In the same example as above, seed sampled in voxel i,j,k = (0,1,2) will be somewhere in the range x = [0, 3], y = [3, 6], z = [6, 9].

get_next_n_pos(random_generator, shuffled_indices, which_seed_start, n)[source]

Generate the next n seed positions. Intended for GPU usage. Equivalent to: >>> for s in range(which_seed_start, which_seed_start + nb_seeds): >>> self.get_next_pos(…, s)

See description of get_next_pos for more information.

To be used with self.n_repeats, we suppose that sequential get_next_n_pos calls are used with sequential values of which_seed_start (with steps of nb_seeds).

Parameters:
  • random_generator (numpy random generator) – Initialized numpy number generator.

  • shuffled_indices (np.array) – Indices of current seeding map.

  • which_seed_start (int) – First seed numbers to be processed. (which_seed_start // self.n_repeats corresponds to the index of the chosen seed in the flattened seeding mask).

  • n (int) – Number of seeds to get.

Returns:

seeds – Positions of next seeds expressed seed_generator’s space and origin.

Return type:

List[List]

get_next_pos(random_generator, shuffled_indices, which_seed)[source]

Generate the next seed position (Space=voxmm, origin=corner). See self.init()_generator to get the generator and shuffled_indices.

To be used with self.n_repeats, we suppose that sequential get_next_pos calls are used with sequentials values of which_seed.

Parameters:
  • random_generator (numpy random generator) – Initialized numpy number generator.

  • shuffled_indices (np.array) – Indices of current seeding map.

  • which_seed (int) – Seed number to be processed. (which_seed // self.n_repeats corresponds to the index of the chosen seed in the flattened seeding mask).

Returns:

seed_pos – Position of next seed expressed in mm.

Return type:

tuple

init_generator(rng_seed, numbers_to_skip)[source]

Initialize a numpy number generator according to user’s parameters. Returns also the suffled index of all voxels.

The values are not stored in this classed, but are returned to the user, who should add them as arguments in the methods self.get_next_pos() self.get_next_n_pos() The use of this is that with multiprocessing, each process may have its own generator, with less risk of using the wrong one when they are managed by the user.

Parameters:
  • rng_seed (int) – The “seed” for the random generator.

  • numbers_to_skip (int) – Number of seeds (i.e. voxels) to skip. Useful if you want to continue sampling from the same generator as in a first experiment (with a fixed rng_seed).

Returns:

  • random_generator (numpy random generator) – Initialized numpy number generator.

  • indices (ndarray) – Shuffled indices of current seeding map, shuffled with current generator.

scilpy.tracking.tracker module

class scilpy.tracking.tracker.GPUTacker(sh, mask, seeds, step_size, max_nbr_pts, theta=20.0, sf_threshold=0.1, sh_interp='trilinear', sh_basis='descoteaux07', is_legacy=True, batch_size=100000, forward_only=False, rng_seed=None, sphere=None)[source]

Bases: object

Perform probabilistic tracking on a ODF field inside a binary mask. The tracking is executed on the GPU using the OpenCL API. Tracking is performed in voxel space with origin corner.

Streamlines are interrupted as soon as they reach maximum length and returned even if they end inside the tracking mask. The ODF image is interpolated using nearest neighbor interpolation. No backward tracking is performed.

Parameters:
  • sh (ndarray) – Spherical harmonics volume. Ex: ODF or fODF.

  • mask (ndarray) – Tracking mask. Tracking stops outside the mask.

  • seeds (ndarray (n_seeds, 3)) – Seed positions in voxel space with origin center.

  • step_size (float) – Step size in voxel space.

  • max_nbr_pts (int) – Maximum length of a streamline in voxel space.

  • theta (float or list of float, optional) – Maximum angle (degrees) between 2 steps. If a list, a theta is randomly drawn from the list for each streamline.

  • sh_basis (str, optional) – Spherical harmonics basis.

  • is_legacy (bool, optional) – Whether or not the SH basis is in its legacy form.

  • batch_size (int, optional) – Approximate size of GPU batches.

  • forward_only (bool, optional) – If True, only forward tracking is performed.

  • rng_seed (int, optional) – Seed for random number generator.

  • sphere (int, optional) – Sphere to use for the tracking.

class scilpy.tracking.tracker.Tracker(propagator: AbstractPropagator, mask: DataVolume, seed_generator: SeedGenerator, nbr_seeds, min_nbr_pts, max_nbr_pts, max_invalid_dirs, compression_th=0.1, nbr_processes=1, save_seeds=False, mmap_mode: str | None = None, rng_seed=1234, track_forward_only=False, skip=0, verbose=False, append_last_point=True)[source]

Bases: object

track()[source]

Generate a set of streamline from seed, mask and odf files.

Returns:

  • streamlines (list of numpy.array) – List of streamlines, represented as an array of positions.

  • seeds (list of numpy.array) – List of seeding positions, one 3-dimensional position per streamline.

scilpy.tracking.utils module

class scilpy.tracking.utils.TrackingDirection(cartesian, index=None)[source]

Bases: list

Tracking direction use as 3D cartesian direction (list(x,y,z)) and has an index to work with discrete sphere.

scilpy.tracking.utils.add_mandatory_options_tracking(p)[source]

Args that are required in both scil_tracking_local and scil_tracking_local_dev scripts.

scilpy.tracking.utils.add_out_options(p)[source]

Options that are available in both scil_tracking_local and scil_tracking_local_dev scripts.

scilpy.tracking.utils.add_seeding_options(p)[source]

Options that are available in both scil_tracking_local and scil_tracking_local_dev scripts.

scilpy.tracking.utils.add_tracking_options(p)[source]

Options that are available in both scil_tracking_local and scil_tracking_local_dev scripts.

scilpy.tracking.utils.add_tracking_ptt_options(p)[source]
scilpy.tracking.utils.get_direction_getter(in_img, algo, sphere, sub_sphere, theta, sh_basis, voxel_size, sf_threshold, sh_to_pmf, probe_length, probe_radius, probe_quality, probe_count, support_exponent, is_legacy=True)[source]

Return the direction getter object.

Parameters:
  • in_img (str) – Path to the input odf file.

  • algo (str) – Algorithm to use for tracking. Can be ‘det’, ‘prob’, ‘ptt’ or ‘eudx’.

  • sphere (str) – Name of the sphere to use for tracking.

  • sub_sphere (int) – Number of subdivisions to use for the sphere.

  • theta (float) – Angle threshold for tracking.

  • sh_basis (str) – Name of the sh basis to use for tracking.

  • voxel_size (float) – Voxel size of the input data.

  • sf_threshold (float) – Spherical function-amplitude threshold for tracking.

  • sh_to_pmf (bool) – Map sherical harmonics to spherical function (pmf) before tracking (faster, requires more memory).

  • probe_length (float) – The length of the probes. Shorter probe_length yields more dispersed fibers.

  • probe_radius (float) – The radius of the probe. A large probe_radius helps mitigate noise in the pmf but it might make it harder to sample thin and intricate connections, also the boundary of fiber bundles might be eroded.

  • probe_quality (int) – The quality of the probe. This parameter sets the number of segments to split the cylinder along the length of the probe (minimum=2).

  • probe_count (int) – The number of probes. This parameter sets the number of parallel lines used to model the cylinder (minimum=1).

  • support_exponent (float) – Data support exponent, used for rejection sampling.

  • is_legacy (bool, optional) – Whether or not the SH basis is in its legacy form.

Returns:

dg – The direction getter object.

Return type:

dipy.direction.DirectionGetter

scilpy.tracking.utils.get_theta(requested_theta, tracking_type)[source]
scilpy.tracking.utils.sample_distribution(dist, random_generator: Generator)[source]
Parameters:
  • dist (numpy.array) – The empirical distribution to sample from.

  • random_generator (numpy Generator)

Returns:

ind – The index of the sampled element.

Return type:

int

scilpy.tracking.utils.save_tractogram(streamlines_generator, tracts_format, ref_img, total_nb_seeds, out_tractogram, min_length, max_length, compress, save_seeds, verbose)[source]

Save the streamlines on-the-fly using a generator. Tracts are filtered according to their length and compressed if requested. Seeds are saved if requested. The tractogram is shifted and scaled according to the file format.

Parameters:
  • streamlines_generator (generator) – Streamlines generator.

  • tracts_format (TrkFile or TckFile) – Tractogram format.

  • ref_img (nibabel.Nifti1Image) – Image used as reference.

  • total_nb_seeds (int) – Total number of seeds.

  • out_tractogram (str) – Output tractogram filename.

  • min_length (float) – Minimum length of a streamline in mm.

  • max_length (float) – Maximum length of a streamline in mm.

  • compress (float) – Distance threshold for compressing streamlines in mm.

  • save_seeds (bool) – If True, save the seeds used for the tracking in the data_per_streamline property.

  • verbose (bool) – If True, display progression bar.

scilpy.tracking.utils.tqdm_if_verbose(generator: Iterable, verbose: bool, *args, **kwargs)[source]
scilpy.tracking.utils.verify_seed_options(parser, args)[source]
scilpy.tracking.utils.verify_streamline_length_options(parser, args)[source]