本文整理汇总了Python中dipy.reconst.csdeconv.ConstrainedSphericalDeconvModel类的典型用法代码示例。如果您正苦于以下问题:Python ConstrainedSphericalDeconvModel类的具体用法?Python ConstrainedSphericalDeconvModel怎么用?Python ConstrainedSphericalDeconvModel使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ConstrainedSphericalDeconvModel类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: constrained_spherical_deconvolution
def constrained_spherical_deconvolution(dir_src, dir_out, verbose=False):
# Load data
fbval = pjoin(dir_src, 'bvals_' + par_b_tag)
fbvec = pjoin(dir_src, 'bvecs_' + par_b_tag)
fdwi = pjoin(dir_src, 'data_' + par_b_tag + '_' + par_dim_tag + '.nii.gz')
#fmask = pjoin(dir_src, 'nodif_brain_mask_' + par_dim_tag + '.nii.gz')
fmask = pjoin(dir_src, 'wm_mask_' + par_b_tag + '_' + par_dim_tag + '.nii.gz')
bvals, bvecs = read_bvals_bvecs(fbval, fbvec)
gtab = gradient_table(bvals, bvecs, b0_threshold=par_b0_threshold)
data, affine = load_nifti(fdwi, verbose)
mask, _ = load_nifti(fmask, verbose)
sphere = get_sphere('symmetric724')
response, ratio = auto_response(gtab, data, roi_radius=par_ar_radius,
fa_thr=par_ar_fa_th)
# print('Response function', response)
# Model fitting
csd_model = ConstrainedSphericalDeconvModel(gtab, response)
csd_fit = csd_model.fit(data, mask=mask)
# Saving Spherical Harmonic Coefficient
out_peaks = 'sh_' + par_b_tag + '_' + par_dim_tag + '.nii.gz'
save_nifti(pjoin(dir_out, out_peaks), csd_fit.shm_coeff, affine)
示例2: test_sphere_scaling_csdmodel
def test_sphere_scaling_csdmodel():
"""Check that mirroring regularization sphere does not change the result of
the model"""
_, fbvals, fbvecs = get_data('small_64D')
bvals = np.load(fbvals)
bvecs = np.load(fbvecs)
gtab = gradient_table(bvals, bvecs)
mevals = np.array(([0.0015, 0.0003, 0.0003],
[0.0015, 0.0003, 0.0003]))
angles = [(0, 0), (60, 0)]
S, sticks = multi_tensor(gtab, mevals, 100., angles=angles,
fractions=[50, 50], snr=None)
hemi = small_sphere
sphere = hemi.mirror()
response = (np.array([0.0015, 0.0003, 0.0003]), 100)
model_full = ConstrainedSphericalDeconvModel(gtab, response,
reg_sphere=sphere)
model_hemi = ConstrainedSphericalDeconvModel(gtab, response,
reg_sphere=hemi)
csd_fit_full = model_full.fit(S)
csd_fit_hemi = model_hemi.fit(S)
assert_array_almost_equal(csd_fit_full.shm_coeff, csd_fit_hemi.shm_coeff)
示例3: test_csd_superres
def test_csd_superres():
""" Check the quality of csdfit with high SH order. """
_, fbvals, fbvecs = get_data('small_64D')
bvals = np.load(fbvals)
bvecs = np.load(fbvecs)
gtab = gradient_table(bvals, bvecs)
# img, gtab = read_stanford_hardi()
evals = np.array([[1.5, .3, .3]]) * [[1.], [1.]] / 1000.
S, sticks = multi_tensor(gtab, evals, snr=None, fractions=[55., 45.])
model16 = ConstrainedSphericalDeconvModel(gtab, (evals[0], 3.),
sh_order=16)
fit16 = model16.fit(S)
# print local_maxima(fit16.odf(default_sphere), default_sphere.edges)
d, v, ind = peak_directions(fit16.odf(default_sphere), default_sphere,
relative_peak_threshold=.2,
min_separation_angle=0)
# Check that there are two peaks
assert_equal(len(d), 2)
# Check that peaks line up with sticks
cos_sim = abs((d * sticks).sum(1)) ** .5
assert_(all(cos_sim > .99))
示例4: csd
def csd(training, category, snr, denoised, odeconv, tv, method, weight=0.1):
data, affine, gtab, mask, evals, S0, prefix = prepare(training,
category,
snr,
denoised,
odeconv,
tv,
method)
if category == 'dti':
csd_model = ConstrainedSphericalDeconvModel(gtab, (evals, S0), sh_order=6)
if category == 'hardi':
csd_model = ConstrainedSphericalDeconvModel(gtab, (evals, S0), sh_order=8)
csd_fit = csd_model.fit(data, mask)
sphere = get_sphere('symmetric724')
odf = csd_fit.odf(sphere)
if tv == True:
odf = tv_denoise_4d(odf, weight=0.1)
save_odfs_peaks(training, odf, affine, sphere, dres, prefix)
示例5: get_csd_gfa
def get_csd_gfa(nii_data,gtab):
from dipy.reconst.csdeconv import ConstrainedSphericalDeconvModel
csd_model = ConstrainedSphericalDeconvModel(gtab, None, sh_order=6)
GFA=csd_model.fit(data,mask).gfa
print ('csd_gfa ok')
示例6: test_csd_predict
def test_csd_predict():
"""
"""
SNR = 100
S0 = 1
_, fbvals, fbvecs = get_data('small_64D')
bvals = np.load(fbvals)
bvecs = np.load(fbvecs)
gtab = gradient_table(bvals, bvecs)
mevals = np.array(([0.0015, 0.0003, 0.0003],
[0.0015, 0.0003, 0.0003]))
angles = [(0, 0), (60, 0)]
S, sticks = multi_tensor(gtab, mevals, S0, angles=angles,
fractions=[50, 50], snr=SNR)
sphere = get_sphere('symmetric362')
odf_gt = multi_tensor_odf(sphere.vertices, mevals, angles, [50, 50])
response = (np.array([0.0015, 0.0003, 0.0003]), S0)
csd = ConstrainedSphericalDeconvModel(gtab, response)
csd_fit = csd.fit(S)
prediction = csd_predict(csd_fit.shm_coeff, gtab, response=response, S0=S0)
npt.assert_equal(prediction.shape[0], S.shape[0])
model_prediction = csd.predict(csd_fit.shm_coeff)
assert_array_almost_equal(prediction, model_prediction)
# Roundtrip tests (quite inaccurate, because of regularization):
assert_array_almost_equal(csd_fit.predict(gtab, S0=S0),S,decimal=1)
assert_array_almost_equal(csd.predict(csd_fit.shm_coeff, S0=S0),S,decimal=1)
示例7: test_csdeconv
def test_csdeconv():
SNR = 100
S0 = 1
_, fbvals, fbvecs = get_data('small_64D')
bvals = np.load(fbvals)
bvecs = np.load(fbvecs)
gtab = gradient_table(bvals, bvecs)
mevals = np.array(([0.0015, 0.0003, 0.0003],
[0.0015, 0.0003, 0.0003]))
S, sticks = multi_tensor(gtab, mevals, S0, angles=[(0, 0), (60, 0)],
fractions=[50, 50], snr=SNR)
sphere = get_sphere('symmetric724')
mevecs = [all_tensor_evecs(sticks[0]).T,
all_tensor_evecs(sticks[1]).T]
odf_gt = multi_tensor_odf(sphere.vertices, [0.5, 0.5], mevals, mevecs)
response = (np.array([0.0015, 0.0003, 0.0003]), S0)
csd = ConstrainedSphericalDeconvModel(gtab, response)
csd_fit = csd.fit(S)
assert_equal(csd_fit.shm_coeff[0] > 0, True)
fodf = csd_fit.odf(sphere)
directions, _, _ = peak_directions(odf_gt, sphere)
directions2, _, _ = peak_directions(fodf, sphere)
ang_sim = angular_similarity(directions, directions2)
assert_equal(ang_sim > 1.9, True)
assert_equal(directions.shape[0], 2)
assert_equal(directions2.shape[0], 2)
with warnings.catch_warnings(record=True) as w:
ConstrainedSphericalDeconvModel(gtab, response, sh_order=10)
assert_equal(len(w) > 0, True)
with warnings.catch_warnings(record=True) as w:
ConstrainedSphericalDeconvModel(gtab, response, sh_order=8)
assert_equal(len(w) > 0, False)
示例8: _run_interface
def _run_interface(self, runtime):
from dipy.reconst.csdeconv import ConstrainedSphericalDeconvModel
from dipy.data import get_sphere
# import marshal as pickle
import pickle as pickle
import gzip
img = nb.load(self.inputs.in_file)
imref = nb.four_to_three(img)[0]
affine = img.get_affine()
if isdefined(self.inputs.in_mask):
msk = nb.load(self.inputs.in_mask).get_data()
else:
msk = np.ones(imref.get_shape())
data = img.get_data().astype(np.float32)
hdr = imref.get_header().copy()
gtab = self._get_gradient_table()
resp_file = np.loadtxt(self.inputs.response)
response = (np.array(resp_file[0:3]), resp_file[-1])
ratio = response[0][1] / response[0][0]
if abs(ratio - 0.2) > 0.1:
IFLOGGER.warn(('Estimated response is not prolate enough. '
'Ratio=%0.3f.') % ratio)
csd_model = ConstrainedSphericalDeconvModel(
gtab, response, sh_order=self.inputs.sh_order)
IFLOGGER.info('Fitting CSD model')
csd_fit = csd_model.fit(data, msk)
f = gzip.open(self._gen_filename('csdmodel', ext='.pklz'), 'wb')
pickle.dump(csd_model, f, -1)
f.close()
if self.inputs.save_fods:
sphere = get_sphere('symmetric724')
fods = csd_fit.odf(sphere)
nb.Nifti1Image(fods.astype(np.float32), img.get_affine(),
None).to_filename(self._gen_filename('fods'))
return runtime
示例9: test_csd_predict_multi
def test_csd_predict_multi():
"""
Check that we can predict reasonably from multi-voxel fits:
"""
S0 = 123.
_, fbvals, fbvecs = get_data('small_64D')
bvals = np.load(fbvals)
bvecs = np.load(fbvecs)
gtab = gradient_table(bvals, bvecs)
response = (np.array([0.0015, 0.0003, 0.0003]), S0)
csd = ConstrainedSphericalDeconvModel(gtab, response)
coeff = np.random.random(45) - .5
coeff[..., 0] = 10.
S = csd.predict(coeff, S0=123.)
multi_S = np.array([[S, S], [S, S]])
csd_fit_multi = csd.fit(multi_S)
S0_multi = np.mean(multi_S[..., gtab.b0s_mask], -1)
pred_multi = csd_fit_multi.predict(S0=S0_multi)
npt.assert_array_almost_equal(pred_multi, multi_S)
示例10: test_csd_predict
def test_csd_predict():
"""
Test prediction API
"""
SNR = 100
S0 = 1
_, fbvals, fbvecs = get_data('small_64D')
bvals = np.load(fbvals)
bvecs = np.load(fbvecs)
gtab = gradient_table(bvals, bvecs)
mevals = np.array(([0.0015, 0.0003, 0.0003],
[0.0015, 0.0003, 0.0003]))
angles = [(0, 0), (60, 0)]
S, sticks = multi_tensor(gtab, mevals, S0, angles=angles,
fractions=[50, 50], snr=SNR)
sphere = small_sphere
odf_gt = multi_tensor_odf(sphere.vertices, mevals, angles, [50, 50])
response = (np.array([0.0015, 0.0003, 0.0003]), S0)
csd = ConstrainedSphericalDeconvModel(gtab, response)
csd_fit = csd.fit(S)
# Predicting from a fit should give the same result as predicting from a
# model, S0 is 1 by default
prediction1 = csd_fit.predict()
prediction2 = csd.predict(csd_fit.shm_coeff)
npt.assert_array_equal(prediction1, prediction2)
npt.assert_array_equal(prediction1[..., gtab.b0s_mask], 1.)
# Same with a different S0
prediction1 = csd_fit.predict(S0=123.)
prediction2 = csd.predict(csd_fit.shm_coeff, S0=123.)
npt.assert_array_equal(prediction1, prediction2)
npt.assert_array_equal(prediction1[..., gtab.b0s_mask], 123.)
# For "well behaved" coefficients, the model should be able to find the
# coefficients from the predicted signal.
coeff = np.random.random(csd_fit.shm_coeff.shape) - .5
coeff[..., 0] = 10.
S = csd.predict(coeff)
csd_fit = csd.fit(S)
npt.assert_array_almost_equal(coeff, csd_fit.shm_coeff)
# Test predict on nd-data set
S_nd = np.zeros((2, 3, 4, S.size))
S_nd[:] = S
fit = csd.fit(S_nd)
predict1 = fit.predict()
predict2 = csd.predict(fit.shm_coeff)
npt.assert_array_almost_equal(predict1, predict2)
示例11: ConstrainedSphericalDeconvModel
.. figure:: csd_recursive_response.png
:align: center
**Estimated response function using recursive calibration**.
"""
fvtk.rm(ren, response_actor)
"""
Now, that we have the response function, we are ready to start the deconvolution
process. Let's import the CSD model and fit the datasets.
"""
from dipy.reconst.csdeconv import ConstrainedSphericalDeconvModel
csd_model = ConstrainedSphericalDeconvModel(gtab, response)
"""
For illustration purposes we will fit only a small portion of the data.
"""
data_small = data[20:50, 55:85, 38:39]
csd_fit = csd_model.fit(data_small)
"""
Show the CSD-based ODFs also known as FODFs (fiber ODFs).
"""
csd_odf = csd_fit.odf(sphere)
"""
示例12: test_csdeconv
def test_csdeconv():
SNR = 100
S0 = 1
_, fbvals, fbvecs = get_data('small_64D')
bvals = np.load(fbvals)
bvecs = np.load(fbvecs)
gtab = gradient_table(bvals, bvecs)
mevals = np.array(([0.0015, 0.0003, 0.0003],
[0.0015, 0.0003, 0.0003]))
angles = [(0, 0), (60, 0)]
S, sticks = multi_tensor(gtab, mevals, S0, angles=angles,
fractions=[50, 50], snr=SNR)
sphere = get_sphere('symmetric362')
odf_gt = multi_tensor_odf(sphere.vertices, mevals, angles, [50, 50])
response = (np.array([0.0015, 0.0003, 0.0003]), S0)
csd = ConstrainedSphericalDeconvModel(gtab, response)
csd_fit = csd.fit(S)
assert_equal(csd_fit.shm_coeff[0] > 0, True)
fodf = csd_fit.odf(sphere)
directions, _, _ = peak_directions(odf_gt, sphere)
directions2, _, _ = peak_directions(fodf, sphere)
ang_sim = angular_similarity(directions, directions2)
assert_equal(ang_sim > 1.9, True)
assert_equal(directions.shape[0], 2)
assert_equal(directions2.shape[0], 2)
with warnings.catch_warnings(record=True) as w:
ConstrainedSphericalDeconvModel(gtab, response, sh_order=10)
assert_equal(len(w) > 0, True)
with warnings.catch_warnings(record=True) as w:
ConstrainedSphericalDeconvModel(gtab, response, sh_order=8)
assert_equal(len(w) > 0, False)
mevecs = []
for s in sticks:
mevecs += [all_tensor_evecs(s).T]
S2 = single_tensor(gtab, 100, mevals[0], mevecs[0], snr=None)
big_S = np.zeros((10, 10, 10, len(S2)))
big_S[:] = S2
aresponse, aratio = auto_response(gtab, big_S, roi_center=(5, 5, 4), roi_radius=3, fa_thr=0.5)
assert_array_almost_equal(aresponse[0], response[0])
assert_almost_equal(aresponse[1], 100)
assert_almost_equal(aratio, response[0][1]/response[0][0])
aresponse2, aratio2 = auto_response(gtab, big_S, roi_radius=3, fa_thr=0.5)
assert_array_almost_equal(aresponse[0], response[0])
示例13: _run_interface
def _run_interface(self, runtime):
import numpy as np
import nibabel as nib
from dipy.io import read_bvals_bvecs
from dipy.core.gradients import gradient_table
from nipype.utils.filemanip import split_filename
# Loading the data
fname = self.inputs.in_file
img = nib.load(fname)
data = img.get_data()
affine = img.get_affine()
FA_fname = self.inputs.FA_file
FA_img = nib.load(FA_fname)
fa = FA_img.get_data()
affine = FA_img.get_affine()
affine = np.matrix.round(affine)
mask_fname = self.inputs.brain_mask
mask_img = nib.load(mask_fname)
mask = mask_img.get_data()
bval_fname = self.inputs.bval
bvals = np.loadtxt(bval_fname)
bvec_fname = self.inputs.bvec
bvecs = np.loadtxt(bvec_fname)
bvecs = np.vstack([bvecs[0,:],bvecs[1,:],bvecs[2,:]]).T
gtab = gradient_table(bvals, bvecs)
# Creating a white matter mask
fa = fa*mask
white_matter = fa >= 0.2
# Creating a seed mask
from dipy.tracking import utils
seeds = utils.seeds_from_mask(white_matter, density=[2, 2, 2], affine=affine)
# Fitting the CSA model
from dipy.reconst.shm import CsaOdfModel
from dipy.data import default_sphere
from dipy.direction import peaks_from_model
csa_model = CsaOdfModel(gtab, sh_order=8)
csa_peaks = peaks_from_model(csa_model, data, default_sphere,
relative_peak_threshold=.8,
min_separation_angle=45,
mask=white_matter)
from dipy.tracking.local import ThresholdTissueClassifier
classifier = ThresholdTissueClassifier(csa_peaks.gfa, .25)
# CSD model
from dipy.reconst.csdeconv import (ConstrainedSphericalDeconvModel, auto_response)
response, ratio = auto_response(gtab, data, roi_radius=10, fa_thr=0.7)
csd_model = ConstrainedSphericalDeconvModel(gtab, response, sh_order=8)
csd_fit = csd_model.fit(data, mask=white_matter)
from dipy.direction import ProbabilisticDirectionGetter
prob_dg = ProbabilisticDirectionGetter.from_shcoeff(csd_fit.shm_coeff,
max_angle=45.,
sphere=default_sphere)
# Tracking
from dipy.tracking.local import LocalTracking
streamlines = LocalTracking(prob_dg, classifier, seeds, affine,
step_size=.5, maxlen=200, max_cross=1)
# Compute streamlines and store as a list.
streamlines = list(streamlines)
# Saving the trackfile
from dipy.io.trackvis import save_trk
_, base, _ = split_filename(fname)
save_trk(base + '_CSDprob.trk', streamlines, affine, fa.shape)
return runtime
示例14: add_noise
data_noisy = add_noise(data, 1, np.mean(data[mask]), noise_type='rician')
# Select a small part of it
data_small = data[25:40, 65:80, 35:42]
data_noisy_small = data_noisy[25:40, 65:80, 35:42]
"""
Fit an initial model to the data, in this case Constrained Spherical
Deconvolution is used.
"""
# Perform CSD on the original data
from dipy.reconst.csdeconv import auto_response
from dipy.reconst.csdeconv import ConstrainedSphericalDeconvModel
response, ratio = auto_response(gtab, data, roi_radius=10, fa_thr=0.7)
csd_model_orig = ConstrainedSphericalDeconvModel(gtab, response)
csd_fit_orig = csd_model_orig.fit(data_small)
csd_shm_orig = csd_fit_orig.shm_coeff
# Perform CSD on the original data + noise
response, ratio = auto_response(gtab, data_noisy, roi_radius=10, fa_thr=0.7)
csd_model_noisy = ConstrainedSphericalDeconvModel(gtab, response)
csd_fit_noisy = csd_model_noisy.fit(data_noisy_small)
csd_shm_noisy = csd_fit_noisy.shm_coeff
"""
Inspired by [RodriguesEurographics_], a lookup-table is created, containing
rotated versions of the kernel :math:`P_t` sampled over a discrete set of
orientations. In order to ensure rotationally invariant processing, the discrete
orientations are required to be equally distributed over a sphere. Per default,
a sphere with 100 directions is used.
示例15: test_recursive_response_calibration
def test_recursive_response_calibration():
"""
Test the recursive response calibration method.
"""
SNR = 100
S0 = 1
sh_order = 8
_, fbvals, fbvecs = get_data('small_64D')
bvals = np.load(fbvals)
bvecs = np.load(fbvecs)
sphere = get_sphere('symmetric724')
gtab = gradient_table(bvals, bvecs)
evals = np.array([0.0015, 0.0003, 0.0003])
evecs = np.array([[0, 1, 0], [0, 0, 1], [1, 0, 0]]).T
mevals = np.array(([0.0015, 0.0003, 0.0003],
[0.0015, 0.0003, 0.0003]))
angles = [(0, 0), (90, 0)]
where_dwi = lazy_index(~gtab.b0s_mask)
S_cross, sticks_cross = multi_tensor(gtab, mevals, S0, angles=angles,
fractions=[50, 50], snr=SNR)
S_single = single_tensor(gtab, S0, evals, evecs, snr=SNR)
data = np.concatenate((np.tile(S_cross, (8, 1)),
np.tile(S_single, (2, 1))),
axis=0)
odf_gt_cross = multi_tensor_odf(sphere.vertices, mevals, angles, [50, 50])
odf_gt_single = single_tensor_odf(sphere.vertices, evals, evecs)
response = recursive_response(gtab, data, mask=None, sh_order=8,
peak_thr=0.01, init_fa=0.05,
init_trace=0.0021, iter=8, convergence=0.001,
parallel=False)
csd = ConstrainedSphericalDeconvModel(gtab, response)
csd_fit = csd.fit(data)
assert_equal(np.all(csd_fit.shm_coeff[:, 0] >= 0), True)
fodf = csd_fit.odf(sphere)
directions_gt_single, _, _ = peak_directions(odf_gt_single, sphere)
directions_gt_cross, _, _ = peak_directions(odf_gt_cross, sphere)
directions_single, _, _ = peak_directions(fodf[8, :], sphere)
directions_cross, _, _ = peak_directions(fodf[0, :], sphere)
ang_sim = angular_similarity(directions_cross, directions_gt_cross)
assert_equal(ang_sim > 1.9, True)
assert_equal(directions_cross.shape[0], 2)
assert_equal(directions_gt_cross.shape[0], 2)
ang_sim = angular_similarity(directions_single, directions_gt_single)
assert_equal(ang_sim > 0.9, True)
assert_equal(directions_single.shape[0], 1)
assert_equal(directions_gt_single.shape[0], 1)
sphere = Sphere(xyz=gtab.gradients[where_dwi])
sf = response.on_sphere(sphere)
S = np.concatenate(([response.S0], sf))
tenmodel = dti.TensorModel(gtab, min_signal=0.001)
tenfit = tenmodel.fit(S)
FA = fractional_anisotropy(tenfit.evals)
FA_gt = fractional_anisotropy(evals)
assert_almost_equal(FA, FA_gt, 1)