Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_odf_slicer(interactive=False):
sphere = get_sphere('symmetric362')
shape = (11, 11, 11, sphere.vertices.shape[0])
fid, fname = mkstemp(suffix='_odf_slicer.mmap')
print(fid)
print(fname)
odfs = np.memmap(fname, dtype=np.float64, mode='w+',
shape=shape)
odfs[:] = 1
affine = np.eye(4)
renderer = window.Renderer()
mask = np.ones(odfs.shape[:3])
def test_tensor_slicer(interactive=False):
evals = np.array([1.4, .35, .35]) * 10 ** (-3)
evecs = np.eye(3)
mevals = np.zeros((3, 2, 4, 3))
mevecs = np.zeros((3, 2, 4, 3, 3))
mevals[..., :] = evals
mevecs[..., :, :] = evecs
from dipy.data import get_sphere
sphere = get_sphere('symmetric724')
affine = np.eye(4)
renderer = window.Renderer()
tensor_actor = actor.tensor_slicer(mevals, mevecs, affine=affine,
sphere=sphere, scale=.3)
I, J, K = mevals.shape[:3]
renderer.add(tensor_actor)
renderer.reset_camera()
renderer.reset_clipping_range()
tensor_actor.display_extent(0, 1, 0, J, 0, K)
tensor_actor.GetProperty().SetOpacity(1.0)
if interactive:
window.show(renderer, reset_camera=False)
ccBox = numpy.array(ccBox)
brainCenter = numpy.floor(numpy.mean(brainBox, 0))
ccCenter = numpy.floor(numpy.mean(ccBox, 0))
shift = numpy.subtract(brainBox[1], brainBox[0]) / 6
xmin = ccCenter[0] - shift[0]
xmax = ccCenter[0] + shift[0]
ymin = ccCenter[1]
ymax = ccCenter[1] + 1
zmin = ccCenter[2] - shift[0]
zmax = ccCenter[2] + shift[0]
#Visualization
sphere = dipy.data.get_sphere('symmetric724')
ren = dipy.viz.fvtk.ren()
if model == 'tensor':
fa = dipy.reconst.dti.fractional_anisotropy(data.evals)
rgbData = dipy.reconst.dti.color_fa(fa, data.evecs)
evals = data.evals[xmin:xmax, ymin:ymax, zmin:zmax]
evecs = data.evecs[xmin:xmax, ymin:ymax, zmin:zmax]
cfa = rgbData[xmin:xmax, ymin:ymax, zmin:zmax]
cfa /= cfa.max()
cfa *= 2
dipy.viz.fvtk.add(ren, dipy.viz.fvtk.tensor(evals, evecs, cfa, sphere))
elif model == 'hardi_odf':
data_small = data['dwiData'][xmin:xmax, ymin:ymax, zmin:zmax]
csdodfs = data['csdModel'].fit(data_small).odf(sphere)
csdodfs = numpy.clip(csdodfs, 0, numpy.max(csdodfs, -1)[..., None])
dipy.viz.fvtk.add(ren,dipy.viz.fvtk.sphere_funcs(
>>> fvtk.add(r, fvtk.tensor(evals, evecs, sphere=sphere))
>>> #fvtk.show(r)
"""
evals = np.asarray(evals)
if evals.ndim > 4:
raise ValueError("Wrong shape")
evals = _makeNd(evals, 4)
evecs = _makeNd(evecs, 5)
grid_shape = np.array(evals.shape[:3])
if sphere is None:
from dipy.data import get_sphere
sphere = get_sphere('symmetric724')
faces = np.asarray(sphere.faces, dtype=int)
vertices = sphere.vertices
colors = vtk.vtkUnsignedCharArray()
colors.SetNumberOfComponents(3)
colors.SetName("Colors")
if scalar_colors is None:
from dipy.reconst.dti import color_fa, fractional_anisotropy
cfa = color_fa(fractional_anisotropy(evals), evecs)
else:
cfa = _makeNd(scalar_colors, 4)
list_sq = []
list_cols = []
todi_obj.smooth_todi_spatial(sigma=args.todi_sigma)
# Fancy masking of 1d indices to limit spatial dilation to WM
sub_mask_3d = np.logical_and(img_mask.get_data(),
todi_obj.reshape_to_3d(todi_obj.get_mask()))
sub_mask_1d = sub_mask_3d.flatten()[todi_obj.get_mask()]
todi_sf = todi_obj.get_todi()[sub_mask_1d] ** 2
# The priors should always be between 0 and 1
# A minimum threshold is set to prevent misaligned FOD from disappearing
todi_sf /= np.max(todi_sf, axis=-1, keepdims=True)
todi_sf[todi_sf < args.sf_threshold] = args.sf_threshold
# Memory friendly saving, as soon as possible saving then delete
priors_3d = np.zeros(sh_shape)
sphere = get_sphere('repulsion724')
priors_3d[sub_mask_3d] = sf_to_sh(todi_sf, sphere,
sh_order=sh_order,
basis_type=args.sh_basis)
nib.save(nib.Nifti1Image(priors_3d, img_mask.affine), out_priors)
del priors_3d
input_sh_3d = img_sh.get_data().astype(np.float)
input_sf_1d = sh_to_sf(input_sh_3d[sub_mask_3d],
sphere, sh_order=sh_order, basis_type=args.sh_basis)
# Creation of the enhanced-FOD (direction-wise multiplication)
mult_sf_1d = input_sf_1d * todi_sf
del todi_sf
input_max_value = np.max(input_sf_1d, axis=-1, keepdims=True)
mult_max_value = np.max(mult_sf_1d, axis=-1, keepdims=True)
import numpy as np
from dipy.data import get_sphere, HemiSphere
from dipy.reconst.shm import real_sym_sh_mrtrix
from dipy.utils.optpkg import optional_package
from dipy.reconst.shm import sph_harm_ind_list
cvxpy, have_cvxpy, _ = optional_package("cvxpy")
sphere = get_sphere('symmetric724')
__all__ = [
'CsdCvxpyOptimizer'
]
class CsdCvxpyOptimizer:
"""
Generalized multi-compartment constrained spherical deconvolution (MC-CSD)
optimizer. The algorithm follows the formulation of Multi-Tissue (MT)-CSD
[1]_, but is completely generalized in that it can take any number or type
of convolution kernels, have static or voxel-varying kernels parameters,
and can have fixed volume fractions or estimate them. The algorithm is
implemented using CVXPY [2]_.
Notes
-----
This is an implementation of the SFM, described in [Rokem2015]_.
.. [Rokem2014] Ariel Rokem, Jason D. Yeatman, Franco Pestilli, Kendrick
N. Kay, Aviv Mezer, Stefan van der Walt, Brian A. Wandell
(2014). Evaluating the accuracy of diffusion MRI models in white
matter. PLoS ONE 10(4): e0123272. doi:10.1371/journal.pone.0123272
.. [Zou2005] Zou H, Hastie T (2005). Regularization and variable
selection via the elastic net. J R Stat Soc B:301-320
"""
ReconstModel.__init__(self, gtab)
if sphere is None:
sphere = dpd.get_sphere()
self.sphere = sphere
self.response = np.asarray(response)
if isotropic is None:
isotropic = IsotropicModel
self.isotropic = isotropic
if solver == 'ElasticNet':
self.solver = lm.ElasticNet(l1_ratio=l1_ratio, alpha=alpha,
positive=True, warm_start=True)
elif solver == 'NNLS' or solver == 'nnls':
self.solver = opt.NonNegativeLeastSquares()
elif (isinstance(solver, opt.SKLearnLinearSolver) or
has_sklearn and isinstance(solver, sklearn.base.RegressorMixin)):
self.solver = solver
def _get_direction_getter(args, mask_data):
sh_data = nib.load(args.sh_file).get_data().astype('float64')
sphere = HemiSphere.from_sphere(get_sphere(args.sphere))
theta = get_theta(args.theta, 0, args.step_size, args.algo)
if args.algo in [DETERMINISTIC, PROBABILISTIC]:
if args.algo == DETERMINISTIC:
dg_class = DeterministicMaximumDirectionGetter
else:
dg_class = ProbabilisticDirectionGetter
return dg_class.from_shcoeff(
shcoeff=sh_data, max_angle=theta, sphere=sphere,
basis_type=args.sh_basis,
relative_peak_threshold=args.sf_threshold)
# Code for type EUDX. We don't use peaks_from_model
# because we want the peaks from the provided sh.
sh_shape_3d = sh_data.shape[:-1]
npeaks = 5
"""
.. figure:: simulated_signal.png
:align: center
**Simulated MultiTensor signal**
"""
"""
For the ODF simulation we will need a sphere. Because we are interested in a
simulation of only a single voxel, we can use a sphere with very high
resolution. We generate that by subdividing the triangles of one of DIPY_'s
cached spheres, which we can read in the following way.
"""
sphere = get_sphere('repulsion724')
sphere = sphere.subdivide(2)
odf = multi_tensor_odf(sphere.vertices, mevals, angles, fractions)
from dipy.viz import window, actor
# Enables/disables interactive visualization
interactive = False
ren = window.Renderer()
odf_actor = actor.odf_slicer(odf[None, None, None, :], sphere=sphere, colormap='plasma')
odf_actor.RotateX(90)
ren.add(odf_actor)
# Checking if we will use parallel processing
parallel = True
if nbr_processes is not None:
if nbr_processes == 0: # Will use all processed
nbr_processes = None
elif nbr_processes == 1:
parallel = False
elif nbr_processes < 0:
raise ValueError('nbr_processes should be positive.')
# Checking sh basis
validate_sh_basis_choice(sh_basis)
# Loading the spheres
reg_sphere = get_sphere('symmetric362')
peaks_sphere = get_sphere('symmetric724')
# Computing CSD
csd_model = ConstrainedSphericalDeconvModel(
gtab, (frf, mean_b0_val),
reg_sphere=reg_sphere,
sh_order=sh_order)
# Computing peaks. Run in parallel, using the default number of processes
# (default: CPU count)
peaks_csd = peaks_from_model(model=csd_model,
data=data,
sphere=peaks_sphere,
relative_peak_threshold=.5,
min_separation_angle=25,
mask=mask,