Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
# of their trajector and/or length.
print("Cleaning fiber groups...")
for bundle in bundles:
print(f"Cleaning {bundle}")
print(f"Before cleaning: {len(fiber_groups[bundle]['sl'])} streamlines")
new_fibers, idx_in_bundle = seg.clean_bundle(
fiber_groups[bundle]['sl'],
return_idx=True)
print(f"Afer cleaning: {len(new_fibers)} streamlines")
idx_in_global = fiber_groups[bundle]['idx'][idx_in_bundle]
np.save(f'{bundle}_idx.npy', idx_in_global)
sft = StatefulTractogram(new_fibers.streamlines,
img,
Space.VOX)
sft.to_rasmm()
save_tractogram(sft, f'./{bundle}_afq.trk',
bbox_valid_check=False)
##########################################################################
# Bundle profiles
# ---------------
# Streamlines are represented in the original diffusion space (`Space.VOX`) and
# scalar properties along the length of each bundle are queried from this scalar
# data. Here, the contribution of each streamline is weighted according to how
# representative this streamline is of the bundle overall.
print("Extracting tract profiles...")
for bundle in bundles:
sft = load_tractogram(f'./{bundle}_afq.trk', img, to_space=Space.VOX)
The Fiber Orientation Distribution (FOD) of the CSD model estimates the
distribution of small fiber bundles within each voxel. This distribution
can be used for deterministic fiber tracking. As for probabilistic tracking,
there are many ways to provide those distributions to the deterministic maximum
direction getter. Here, the spherical harmonic representation of the FOD
is used.
"""
detmax_dg = DeterministicMaximumDirectionGetter.from_shcoeff(
csd_fit.shm_coeff, max_angle=30., sphere=default_sphere)
streamline_generator = LocalTracking(detmax_dg, stopping_criterion, seeds,
affine, step_size=.5)
streamlines = Streamlines(streamline_generator)
sft = StatefulTractogram(streamlines, hardi_img, Space.RASMM)
save_trk(sft, "tractogram_deterministic_dg.trk")
if has_fury:
r = window.Renderer()
r.add(actor.line(streamlines, colormap.line_colors(streamlines)))
window.record(r, out_path='tractogram_deterministic_dg.png',
size=(800, 800))
if interactive:
window.show(r)
"""
.. figure:: tractogram_deterministic_dg.png
:align: center
**Corpus Callosum using deterministic maximum direction getter**
"""
The Fiber Orientation Distribution (FOD) of the CSD model estimates the
distribution of small fiber bundles within each voxel. This distribution
can be used for deterministic fiber tracking. As for probabilistic tracking,
there are many ways to provide those distributions to the deterministic maximum
direction getter. Here, the spherical harmonic representation of the FOD
is used.
"""
detmax_dg = DeterministicMaximumDirectionGetter.from_shcoeff(
csd_fit.shm_coeff, max_angle=30., sphere=default_sphere)
streamline_generator = LocalTracking(detmax_dg, stopping_criterion, seeds,
affine, step_size=.5)
streamlines = Streamlines(streamline_generator)
sft = StatefulTractogram(streamlines, hardi_img, Space.RASMM)
save_trk(sft, "tractogram_deterministic_dg.trk")
if has_fury:
r = window.Renderer()
r.add(actor.line(streamlines, colormap.line_colors(streamlines)))
window.record(r, out_path='tractogram_deterministic_dg.png',
size=(800, 800))
if interactive:
window.show(r)
"""
.. figure:: tractogram_deterministic_dg.png
:align: center
**Corpus Callosum using deterministic maximum direction getter**
"""
It is recommended to re-create a new StatefulTractogram object and
explicitly specify in which space the streamlines are. Be careful to follow
the order of operations.
If the tractogram was from a Trk file with metadata, this will be lost.
If you wish to keep metadata while manipulating the number or the order
look at the function StatefulTractogram.remove_invalid_streamlines() for more
details
It is important to mention that once the object is created in a consistent state
the ``save_tractogram`` function will save a valid file. And then the function
``load_tractogram`` will load them in a valid state.
"""
cc_sft = StatefulTractogram(cc_streamlines_vox, reference_anatomy, Space.VOX)
laf_sft = StatefulTractogram(laf_streamlines_vox, reference_anatomy, Space.VOX)
raf_sft = StatefulTractogram(raf_streamlines_vox, reference_anatomy, Space.VOX)
lpt_sft = StatefulTractogram(lpt_streamlines_vox, reference_anatomy, Space.VOX)
rpt_sft = StatefulTractogram(rpt_streamlines_vox, reference_anatomy, Space.VOX)
print(len(cc_sft), len(laf_sft), len(raf_sft), len(lpt_sft), len(rpt_sft))
save_tractogram(cc_sft, 'cc_1000.trk')
save_tractogram(laf_sft, 'laf_1000.trk')
save_tractogram(raf_sft, 'raf_1000.trk')
save_tractogram(lpt_sft, 'lpt_1000.trk')
save_tractogram(rpt_sft, 'rpt_1000.trk')
nib.save(nib.Nifti1Image(cc_density, affine, nifti_header),
'cc_density.nii.gz')
nib.save(nib.Nifti1Image(laf_density, affine, nifti_header),
'laf_density.nii.gz')
nib.save(nib.Nifti1Image(raf_density, affine, nifti_header),
def to_space(self, target_space):
""" Safe function to transform streamlines to a particular space using
an enum and update state """
if target_space == Space.VOX:
self.to_vox()
elif target_space == Space.VOXMM:
self.to_voxmm()
elif target_space == Space.RASMM:
self.to_rasmm()
else:
logger.error('Unsupported target space, please use Enum in '
'dipy.io.stateful_tractogram')
and np.allclose(hdf5_file.attrs['dimensions'], dwi_img.shape[0:3])):
parser.error('{} does not have a compatible header with {}'.format(
args.in_tractogram, args.in_dwi))
# Keep track of the order of connections/streamlines in relation to the
# tractogram as well as the number of streamlines for each connection.
hdf5_keys = list(hdf5_file.keys())
for key in hdf5_keys:
tmp_streamlines = reconstruct_streamlines_from_hdf5(hdf5_file,
key)
len_list.append(len(tmp_streamlines))
streamlines.extend(tmp_streamlines)
len_list = np.cumsum(len_list)
sft = StatefulTractogram(streamlines, args.in_dwi,
Space.VOX, origin=Origin.TRACKVIS)
tmp_tractogram_filename = os.path.join(tmp_dir.name, 'tractogram.trk')
# Keeping the input variable, saving trk file for COMMIT internal use
save_tractogram(sft, tmp_tractogram_filename)
initial_hdf5_filename = args.in_tractogram
args.in_tractogram = tmp_tractogram_filename
tmp_scheme_filename = os.path.join(tmp_dir.name, 'gradients.scheme')
tmp_bval_filename = os.path.join(tmp_dir.name, 'bval')
bvals, _ = read_bvals_bvecs(args.in_bval, args.in_bvec)
shells_centroids, indices_shells = identify_shells(bvals,
args.b_thr,
roundCentroids=True)
np.savetxt(tmp_bval_filename, shells_centroids[indices_shells],
newline=' ', fmt='%i')
fsl2mrtrix(tmp_bval_filename, args.in_bvec, tmp_scheme_filename)
same set of streamlines.
"""
"""
Example #2: Closest peak direction getter with CSD Model
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""
pmf = csd_fit.odf(small_sphere).clip(min=0)
peak_dg = ClosestPeakDirectionGetter.from_pmf(pmf, max_angle=30.,
sphere=small_sphere)
peak_streamline_generator = LocalTracking(peak_dg, stopping_criterion, seeds,
affine, step_size=.5)
streamlines = Streamlines(peak_streamline_generator)
sft = StatefulTractogram(streamlines, hardi_img, Space.RASMM)
save_trk(sft, "closest_peak_dg_CSD.trk")
if has_fury:
r = window.Renderer()
r.add(actor.line(streamlines, colormap.line_colors(streamlines)))
window.record(r, out_path='tractogram_closest_peak_dg.png',
size=(800, 800))
if interactive:
window.show(r)
"""
.. figure:: tractogram_closest_peak_dg.png
:align: center
**Corpus Callosum Closest Peak Deterministic Direction Getter**
def _clean_bundles(self, row):
clean_bundles_file = self._get_fname(
row,
'-clean_tractography.trk',
include_track=True,
include_seg=True)
if self.force_recompute or not op.exists(clean_bundles_file):
bundles_file = self._segment(row)
sft = load_tractogram(bundles_file,
row['dwi_img'],
Space.VOX)
tgram = nib.streamlines.Tractogram([], {'bundle': []})
if self.clean_params['return_idx']:
return_idx = {}
for b in self.bundle_dict.keys():
if b != "whole_brain":
idx = np.where(sft.data_per_streamline['bundle']
== self.bundle_dict[b]['uid'])[0]
this_tg = StatefulTractogram(
sft.streamlines[idx],
row['dwi_img'],
Space.VOX)
this_tg = seg.clean_bundle(this_tg, **self.clean_params)
if self.clean_params['return_idx']:
this_tg, this_idx = this_tg
assert_outputs_exist(parser, args, args.out_tractogram)
sft = load_tractogram_with_reference(parser, args, args.in_moving_tractogram,
bbox_check=False)
deformation = nib.load(args.in_deformation)
deformation_data = np.squeeze(deformation.get_fdata(dtype=np.float32))
if not is_header_compatible(sft, deformation):
parser.error('Input tractogram/reference do not have the same spatial '
'attribute as the deformation field.')
# Warning: Apply warp in-place
moved_streamlines = warp_streamlines(sft, deformation_data)
new_sft = StatefulTractogram(moved_streamlines, args.in_target_file,
Space.RASMM,
data_per_point=sft.data_per_point,
data_per_streamline=sft.data_per_streamline)
if args.cut_invalid:
new_sft, _ = cut_invalid_streamlines(new_sft)
save_tractogram(new_sft, args.out_tractogram)
elif args.remove_invalid:
ori_len = len(new_sft)
new_sft.remove_invalid_streamlines()
logging.warning('Removed {} invalid streamlines.'.format(
ori_len - len(new_sft)))
save_tractogram(new_sft, args.out_tractogram)
elif args.keep_invalid:
if not new_sft.is_bbox_in_vox_valid():
logging.warning('Saving tractogram with invalid streamlines.')
save_tractogram(new_sft, args.out_tractogram, bbox_valid_check=False)
metadata. Default: bundles are either not identified, or identified
only as unique integers in the metadata.
colors : dict or list
If this is a dict, keys are bundle names and values are RGB tuples.
If this is a list, each item is an RGB tuple. Defaults to a list
with Tableau 20 RGB values
Returns
-------
Statefule Tractogram streamlines, RGB numpy array, str
"""
if isinstance(sft, str):
viz_logger.info("Loading Stateful Tractogram...")
sft = load_tractogram(sft, 'same', Space.VOX, bbox_valid_check=False)
if affine is not None:
viz_logger.info("Transforming Stateful Tractogram...")
sft = StatefulTractogram.from_sft(
transform_tracking_output(sft.streamlines, affine),
sft,
data_per_streamline=sft.data_per_streamline)
streamlines = sft.streamlines
viz_logger.info("Generating colorful lines from tractography...")
if colors is None:
# Use the color dict provided
colors = COLOR_DICT
if list(sft.data_per_streamline.keys()) == []: