def dipy_gt(): print("Loading slice...") sample_slice, qvecs, gtab = load_slice('./test_data/david_data', '3112_BL_data_subject_space.nii.gz', gtab=True) mapmodel = GeneralizedQSamplingModel(gtab) mapfit = mapmodel.fit(sample_slice) sphere = get_sphere('repulsion724') odfs = mapfit.odf(sphere) vis_2d_field(odfs, sphere)
def test_mvoxel_gqi(): data, gtab = dsi_voxels() gq = GeneralizedQSamplingModel(gtab, 'standard') sphere = get_sphere('symmetric724') gq.direction_finder.config(sphere=sphere, min_separation_angle=25, relative_peak_threshold=.35) gqfit = gq.fit(data) directions = gqfit.directions assert_equal(directions[0, 0, 0].shape[0], 2) assert_equal(directions[-1, -1, -1].shape[0], 2)
def gqi(training, category, snr, denoised, odeconv, tv, method, weight=0.1, sl=3.): data, affine, gtab, mask, evals, S0, prefix = prepare(training, category, snr, denoised, odeconv, tv, method) model = GeneralizedQSamplingModel(gtab, method='gqi2', sampling_length=sl, normalize_peaks=False) fit = model.fit(data, mask) sphere = get_sphere('symmetric724') odf = fit.odf(sphere) if odeconv == True: odf_sh = sf_to_sh(odf, sphere, sh_order=8, basis_type='mrtrix') # # nib.save(nib.Nifti1Image(odf_sh, affine), model_tag + 'odf_sh.nii.gz') reg_sphere = get_sphere('symmetric724') fodf_sh = odf_sh_to_sharp(odf_sh, reg_sphere, basis='mrtrix', ratio=3.8 / 16.6, sh_order=8, Lambda=1., tau=1.) # # nib.save(nib.Nifti1Image(odf_sh, affine), model_tag + 'fodf_sh.nii.gz') fodf_sh[np.isnan(fodf_sh)]=0 r, theta, phi = cart2sphere(sphere.x, sphere.y, sphere.z) B_regul, m, n = real_sph_harm_mrtrix(8, theta[:, None], phi[:, None]) fodf = np.dot(fodf_sh, B_regul.T) odf = fodf if tv == True: odf = tv_denoise_4d(odf, weight=weight) save_odfs_peaks(training, odf, affine, sphere, dres, prefix)
def test_mvoxel_gqi(): data, gtab = dsi_voxels() sphere = get_sphere('symmetric724') gq = GeneralizedQSamplingModel(gtab, 'standard') gqfit = gq.fit(data) all_odfs = gqfit.odf(sphere) # Check that the first and last voxels each have 2 peaks odf = all_odfs[0, 0, 0] directions, values, indices = peak_directions(odf, sphere, .35, 25) assert_equal(directions.shape[0], 2) odf = all_odfs[-1, -1, -1] directions, values, indices = peak_directions(odf, sphere, .35, 25) assert_equal(directions.shape[0], 2)
def test_mvoxel_gqi(): data, gtab = dsi_voxels() sphere = get_sphere('symmetric724') gq = GeneralizedQSamplingModel(gtab, 'standard') gqfit = gq.fit(data) all_odfs = gqfit.odf(sphere) # Check that the first and last voxels each have 2 peaks odf = all_odfs[0, 0, 0] directions, values, indices = peak_directions(odf, sphere, .35, 25) assert_equal(directions.shape[0], 2) odf = all_odfs[-1, -1, -1] directions, values, indices = peak_directions(odf, sphere, .35, 25) assert_equal(directions.shape[0], 2)
def reconst_gqi_fodf_return_sh_coeffs(bval_path,bvec_path,data_path,data_var): bval_path = os.path.normpath(bval_path) bvec_path = os.path.normpath(bvec_path) data_path = os.path.normpath(data_path) bvals, bvecs = read_bvals_bvecs(bval_path, bvec_path) gtab = gradient_table(bvals, bvecs) data = loadmat(data_path) data = data[data_var] gqmodel = GeneralizedQSamplingModel(gtab, sampling_length=1.2) #gqfit = gqmodel.fit(dataslice, mask=mask) sphere = get_sphere('symmetric724') #ODF = gqfit.odf(sphere) #odf = gqmodel.fit(data).odf(sphere) gqpeaks = peaks_from_model(model=gqmodel, data=data, sphere=sphere, relative_peak_threshold=.5, min_separation_angle=25, return_odf=True, normalize_peaks=True) print('Debug here') fodfs_shm = gqpeaks.shm_coeff return fodfs_shm
def test_gqi(): #load symmetric 724 sphere sphere = get_sphere('symmetric724') #load icosahedron sphere sphere2 = create_unit_sphere(5) btable = np.loadtxt(get_data('dsi515btable')) bvals = btable[:, 0] bvecs = btable[:, 1:] gtab = gradient_table(bvals, bvecs) data, golden_directions = SticksAndBall(gtab, d=0.0015, S0=100, angles=[(0, 0), (90, 0)], fractions=[50, 50], snr=None) gq = GeneralizedQSamplingModel(gtab, method='gqi2', sampling_length=1.4) #symmetric724 gqfit = gq.fit(data) odf = gqfit.odf(sphere) directions, values, indices = peak_directions(odf, sphere, .35, 25) assert_equal(len(directions), 2) assert_almost_equal(angular_similarity(directions, golden_directions), 2, 1) #5 subdivisions gqfit = gq.fit(data) odf2 = gqfit.odf(sphere2) directions, values, indices = peak_directions(odf2, sphere2, .35, 25) assert_equal(len(directions), 2) assert_almost_equal(angular_similarity(directions, golden_directions), 2, 1) sb_dummies = sticks_and_ball_dummies(gtab) for sbd in sb_dummies: data, golden_directions = sb_dummies[sbd] odf = gq.fit(data).odf(sphere2) directions, values, indices = peak_directions(odf, sphere2, .35, 25) if len(directions) <= 3: assert_equal(len(directions), len(golden_directions)) if len(directions) > 3: assert_equal(gfa(odf) < 0.1, True)
def test_gqi(): # load symmetric 724 sphere sphere = get_sphere('symmetric724') # load icosahedron sphere sphere2 = create_unit_sphere(5) btable = np.loadtxt(get_fnames('dsi515btable')) bvals = btable[:, 0] bvecs = btable[:, 1:] gtab = gradient_table(bvals, bvecs) data, golden_directions = SticksAndBall(gtab, d=0.0015, S0=100, angles=[(0, 0), (90, 0)], fractions=[50, 50], snr=None) gq = GeneralizedQSamplingModel(gtab, method='gqi2', sampling_length=1.4) # symmetric724 gqfit = gq.fit(data) odf = gqfit.odf(sphere) directions, values, indices = peak_directions(odf, sphere, .35, 25) assert_equal(len(directions), 2) assert_almost_equal(angular_similarity(directions, golden_directions), 2, 1) # 5 subdivisions gqfit = gq.fit(data) odf2 = gqfit.odf(sphere2) directions, values, indices = peak_directions(odf2, sphere2, .35, 25) assert_equal(len(directions), 2) assert_almost_equal(angular_similarity(directions, golden_directions), 2, 1) sb_dummies = sticks_and_ball_dummies(gtab) for sbd in sb_dummies: data, golden_directions = sb_dummies[sbd] odf = gq.fit(data).odf(sphere2) directions, values, indices = peak_directions(odf, sphere2, .35, 25) if len(directions) <= 3: assert_equal(len(directions), len(golden_directions)) if len(directions) > 3: assert_equal(gfa(odf) < 0.1, True)
def test_gqi(): #load symmetric 724 sphere sphere = get_sphere('symmetric724') #load icosahedron sphere sphere2 = create_unit_sphere(5) btable = np.loadtxt(get_data('dsi515btable')) bvals = btable[:,0] bvecs = btable[:,1:] data, golden_directions = SticksAndBall(bvals, bvecs, d=0.0015, S0=100, angles=[(0, 0), (90, 0)], fractions=[50, 50], snr=None) gtab = gradient_table(bvals, bvecs) gq = GeneralizedQSamplingModel(gtab, method='gqi2', sampling_length=1.4) #symmetric724 gq.direction_finder.config(sphere=sphere, min_separation_angle=25, relative_peak_threshold=.35) gqfit = gq.fit(data) odf = gqfit.odf(sphere) #from dipy.viz._show_odfs import show_odfs #show_odfs(odf[None,None,None,:], (sphere.vertices, sphere.faces)) directions = gqfit.directions assert_equal(len(directions), 2) assert_almost_equal(angular_similarity(directions, golden_directions), 2, 1) #5 subdivisions gq.direction_finder.config(sphere=sphere2, min_separation_angle=25, relative_peak_threshold=.35) gqfit = gq.fit(data) odf2 = gqfit.odf(sphere2) directions = gqfit.directions assert_equal(len(directions), 2) assert_almost_equal(angular_similarity(directions, golden_directions), 2, 1) #show_odfs(odf[None,None,None,:], (sphere.vertices, sphere.faces)) sb_dummies=sticks_and_ball_dummies(gtab) for sbd in sb_dummies: data, golden_directions = sb_dummies[sbd] odf = gq.fit(data).odf(sphere2) directions = gq.fit(data).directions #show_odfs(odf[None, None, None, :], (sphere2.vertices, sphere2.faces)) if len(directions) <= 3: assert_equal(len(gq.fit(data).directions), len(golden_directions)) if len(directions) > 3: assert_equal(gfa(gq.fit(data).odf(sphere2)) < 0.1, True)
def dmri_recon(sid, data_dir, out_dir, resolution, recon='csd', dirs='', num_threads=2): import tempfile #tempfile.tempdir = '/om/scratch/Fri/ksitek/' import os oldval = None if 'MKL_NUM_THREADS' in os.environ: oldval = os.environ['MKL_NUM_THREADS'] os.environ['MKL_NUM_THREADS'] = '%d' % num_threads ompoldval = None if 'OMP_NUM_THREADS' in os.environ: ompoldval = os.environ['OMP_NUM_THREADS'] os.environ['OMP_NUM_THREADS'] = '%d' % num_threads import nibabel as nib import numpy as np from glob import glob if resolution == '0.2mm': filename = 'Reg_S64550_nii4d.nii' #filename = 'angular_resample/dwi_%s.nii.gz'%dirs fimg = os.path.abspath(glob(os.path.join(data_dir, filename))[0]) else: filename = 'Reg_S64550_nii4d_resamp-%s.nii.gz' % (resolution) fimg = os.path.abspath( glob(os.path.join(data_dir, 'resample', filename))[0]) print("dwi file = %s" % fimg) fbval = os.path.abspath( glob(os.path.join(data_dir, 'bvecs', 'camino_120_RAS.bvals'))[0]) print("bval file = %s" % fbval) fbvec = os.path.abspath( glob(os.path.join(data_dir, 'bvecs', 'camino_120_RAS_flipped-xy.bvecs'))[0]) # 'angular_resample', # 'dwi_%s.bvecs'%dirs))[0]) print("bvec file = %s" % fbvec) img = nib.load(fimg) data = img.get_fdata() affine = img.get_affine() prefix = sid from dipy.io import read_bvals_bvecs bvals, bvecs = read_bvals_bvecs(fbval, fbvec) ''' from dipy.core.gradients import vector_norm b0idx = [] for idx, val in enumerate(bvals): if val < 1: pass #bvecs[idx] = [1, 0, 0] else: b0idx.append(idx) #print "b0idx=%d"%idx #print "input bvecs:" #print bvecs bvecs[b0idx, :] = bvecs[b0idx, :]/vector_norm(bvecs[b0idx])[:, None] #print "bvecs after normalization:" #print bvecs ''' from dipy.core.gradients import gradient_table gtab = gradient_table(bvals, bvecs) gtab.bvecs.shape == bvecs.shape gtab.bvecs gtab.bvals.shape == bvals.shape gtab.bvals #from dipy.segment.mask import median_otsu #b0_mask, mask = median_otsu(data[:, :, :, b0idx].mean(axis=3).squeeze(), 4, 4) if resolution == '0.2mm': mask_name = 'Reg_S64550_nii_b0-slice_mask.nii.gz' fmask1 = os.path.join(data_dir, mask_name) else: mask_name = 'Reg_S64550_nii_b0-slice_mask_resamp-%s.nii.gz' % ( resolution) fmask1 = os.path.join(data_dir, 'resample', mask_name) print("fmask file = %s" % fmask1) mask = nib.load(fmask1).get_fdata() ''' DTI model & save metrics ''' from dipy.reconst.dti import TensorModel print("running tensor model") tenmodel = TensorModel(gtab) tenfit = tenmodel.fit(data, mask) from dipy.reconst.dti import fractional_anisotropy print("running FA") FA = fractional_anisotropy(tenfit.evals) FA[np.isnan(FA)] = 0 fa_img = nib.Nifti1Image(FA, img.get_affine()) tensor_fa_file = os.path.abspath('%s_tensor_fa.nii.gz' % (prefix)) nib.save(fa_img, tensor_fa_file) from dipy.reconst.dti import axial_diffusivity print("running AD") AD = axial_diffusivity(tenfit.evals) AD[np.isnan(AD)] = 0 ad_img = nib.Nifti1Image(AD, img.get_affine()) tensor_ad_file = os.path.abspath('%s_tensor_ad.nii.gz' % (prefix)) nib.save(ad_img, tensor_ad_file) from dipy.reconst.dti import radial_diffusivity print("running RD") RD = radial_diffusivity(tenfit.evals) RD[np.isnan(RD)] = 0 rd_img = nib.Nifti1Image(RD, img.get_affine()) tensor_rd_file = os.path.abspath('%s_tensor_rd.nii.gz' % (prefix)) nib.save(rd_img, tensor_rd_file) from dipy.reconst.dti import mean_diffusivity print("running MD") MD = mean_diffusivity(tenfit.evals) MD[np.isnan(MD)] = 0 md_img = nib.Nifti1Image(MD, img.get_affine()) tensor_md_file = os.path.abspath('%s_tensor_md.nii.gz' % (prefix)) nib.save(md_img, tensor_md_file) evecs = tenfit.evecs evec_img = nib.Nifti1Image(evecs, img.get_affine()) tensor_evec_file = os.path.abspath('%s_tensor_evec.nii.gz' % (prefix)) nib.save(evec_img, tensor_evec_file) ''' ODF model ''' useFA = True print("creating %s model" % recon) if recon == 'csd': from dipy.reconst.csdeconv import ConstrainedSphericalDeconvModel from dipy.reconst.csdeconv import auto_response response, ratio = auto_response(gtab, data, roi_radius=10, fa_thr=0.5) # 0.7 model = ConstrainedSphericalDeconvModel(gtab, response) useFA = True return_sh = True elif recon == 'csa': from dipy.reconst.shm import CsaOdfModel, normalize_data model = CsaOdfModel(gtab, sh_order=8) useFA = True return_sh = True elif recon == 'gqi': from dipy.reconst.gqi import GeneralizedQSamplingModel model = GeneralizedQSamplingModel(gtab) return_sh = False else: raise ValueError('only csd, csa supported currently') from dipy.reconst.dsi import (DiffusionSpectrumDeconvModel, DiffusionSpectrumModel) model = DiffusionSpectrumDeconvModel(gtab) '''reconstruct ODFs''' from dipy.data import get_sphere sphere = get_sphere('symmetric724') #odfs = fit.odf(sphere) # with CSD/GQI, uses > 50GB per core; don't get greedy with cores! from dipy.reconst.peaks import peaks_from_model print("running peaks_from_model") peaks = peaks_from_model( model=model, data=data, sphere=sphere, mask=mask, return_sh=return_sh, return_odf=False, normalize_peaks=True, npeaks=5, relative_peak_threshold=.5, min_separation_angle=10, #25, parallel=num_threads > 1, nbr_processes=num_threads) # save the peaks from dipy.io.peaks import save_peaks peaks_file = os.path.abspath('%s_peaks.pam5' % (prefix)) save_peaks(peaks_file, peaks) # save the spherical harmonics shm_coeff_file = os.path.abspath('%s_shm_coeff.nii.gz' % (prefix)) if return_sh: shm_coeff = peaks.shm_coeff nib.save(nib.Nifti1Image(shm_coeff, img.get_affine()), shm_coeff_file) else: # if it's not a spherical model, output it as an essentially null file np.savetxt(shm_coeff_file, [0]) # save the generalized fractional anisotropy image gfa_img = nib.Nifti1Image(peaks.gfa, img.get_affine()) model_gfa_file = os.path.abspath('%s_%s_gfa.nii.gz' % (prefix, recon)) nib.save(gfa_img, model_gfa_file) #from dipy.reconst.dti import quantize_evecs #peak_indices = quantize_evecs(tenfit.evecs, sphere.vertices) #eu = EuDX(FA, peak_indices, odf_vertices = sphere.vertices, #a_low=0.2, seeds=10**6, ang_thr=35) ''' probabilistic tracking ''' ''' from dipy.direction import ProbabilisticDirectionGetter from dipy.tracking.local import LocalTracking from dipy.tracking.streamline import Streamlines from dipy.io.streamline import save_trk prob_dg = ProbabilisticDirectionGetter.from_shcoeff(shm_coeff, max_angle=45., sphere=sphere) streamlines_generator = LocalTracking(prob_dg, affine, step_size=.5, max_cross=1) # Generate streamlines object streamlines = Streamlines(streamlines_generator) affine = img.get_affine() vox_size=fa_img.get_header().get_zooms()[:3] fname = os.path.abspath('%s_%s_prob_streamline.trk' % (prefix, recon)) save_trk(fname, streamlines, affine, vox_size=vox_size) ''' ''' deterministic tracking with EuDX method''' from dipy.tracking.eudx import EuDX print("reconstructing with EuDX") if useFA: eu = EuDX( FA, peaks.peak_indices[..., 0], odf_vertices=sphere.vertices, a_low=0.001, # default is 0.0239 seeds=10**6, ang_thr=75) else: eu = EuDX( peaks.gfa, peaks.peak_indices[..., 0], odf_vertices=sphere.vertices, #a_low=0.1, seeds=10**6, ang_thr=45) sl_fname = os.path.abspath('%s_%s_det_streamline.trk' % (prefix, recon)) # trying new dipy.io.streamline module, per email to neuroimaging list # 2018.04.05 from nibabel.streamlines import Field from nibabel.orientations import aff2axcodes affine = img.get_affine() vox_size = fa_img.get_header().get_zooms()[:3] fov_shape = FA.shape[:3] if vox_size is not None and fov_shape is not None: hdr = {} hdr[Field.VOXEL_TO_RASMM] = affine.copy() hdr[Field.VOXEL_SIZES] = vox_size hdr[Field.DIMENSIONS] = fov_shape hdr[Field.VOXEL_ORDER] = "".join(aff2axcodes(affine)) tractogram = nib.streamlines.Tractogram(eu) tractogram.affine_to_rasmm = affine trk_file = nib.streamlines.TrkFile(tractogram, header=hdr) nib.streamlines.save(trk_file, sl_fname) if oldval: os.environ['MKL_NUM_THREADS'] = oldval else: del os.environ['MKL_NUM_THREADS'] if ompoldval: os.environ['OMP_NUM_THREADS'] = ompoldval else: del os.environ['OMP_NUM_THREADS'] print('all output files created') return (tensor_fa_file, tensor_evec_file, model_gfa_file, sl_fname, affine, tensor_ad_file, tensor_rd_file, tensor_md_file, shm_coeff_file, peaks_file)
gtab = gradient_table(bvals, bvecs) sphere = get_sphere('symmetric724') """ w=10 data_roi = data[:, :, 32] #data_roi = data[48-w:48+w, 48-w:48+w, 32] #27-w:27+w,:] data_roi = data_roi[:,:,None,:] data = data_roi.astype('f8') """ S0 = data[..., 0] mask = S0 > 50 gq = GeneralizedQSamplingModel(gtab) gq.direction_finder.config(sphere=sphere, min_separation_angle=25, relative_peak_threshold=.35) gqfit = gq.fit(data, mask) gfa = gqfit.gfa peak_values = gqfit.peak_values peak_indices = gqfit.peak_indices qa = gqfit.qa #ODF = gqfit.odf(sphere) """ data, gtab = half_to_full_qspace(data, gtab) ds = DiffusionSpectrumModel(gtab) ds.direction_finder.config(sphere=sphere,
def test_gqi(): #load odf sphere vertices, faces = sphere_vf_from('symmetric724') edges = unique_edges(faces) half_vertices, half_edges, half_faces = reduce_antipodal(vertices, faces) #load bvals and gradients btable = np.loadtxt(get_data('dsi515btable')) bvals = btable[:, 0] bvecs = btable[:, 1:] S, stics = SticksAndBall(bvals, bvecs, d=0.0015, S0=100, angles=[(0, 0), (90, 0), (90, 90)], fractions=[50, 50, 0], snr=None) #pdf0,odf0,peaks0=standard_dsi_algorithm(S,bvals,bvecs) S2 = S.copy() S2 = S2.reshape(1, len(S)) odf_sphere = (vertices, faces) ds = GeneralizedQSamplingModel(bvals, bvecs, odf_sphere) dsfit = ds.fit(S) assert_equal((dsfit.peak_values > 0).sum(), 3) #change thresholds ds.relative_peak_threshold = 0.5 ds.angular_distance_threshold = 30 dsfit = ds.fit(S) assert_equal((dsfit.peak_values > 0).sum(), 2) #1 fiber S, stics = SticksAndBall(bvals, bvecs, d=0.0015, S0=100, angles=[(0, 0), (90, 0), (90, 90)], fractions=[100, 0, 0], snr=None) ds = GeneralizedQSamplingModel(bvals, bvecs, odf_sphere) ds.relative_peak_threshold = 0.5 ds.angular_distance_threshold = 20 dsfit = ds.fit(S) QA = dsfit.qa #1/0 assert_equal(np.sum(QA > 0), 1) #2 fibers S, stics = SticksAndBall(bvals, bvecs, d=0.0015, S0=100, angles=[(0, 0), (90, 0), (90, 90)], fractions=[50, 50, 0], snr=None) ds = GeneralizedQSamplingModel(bvals, bvecs, odf_sphere) ds.relative_peak_threshold = 0.5 ds.angular_distance_threshold = 20 dsfit = ds.fit(S) QA = dsfit.qa assert_equal(np.sum(QA > 0), 2) #3 fibers S, stics = SticksAndBall(bvals, bvecs, d=0.0015, S0=100, angles=[(0, 0), (90, 0), (90, 90)], fractions=[33, 33, 33], snr=None) ds = GeneralizedQSamplingModel(bvals, bvecs, odf_sphere) ds.relative_peak_threshold = 0.5 dsfit = ds.fit(S) QA = dsfit.qa assert_equal(np.sum(QA > 0), 3) #isotropic S, stics = SticksAndBall(bvals, bvecs, d=0.0015, S0=100, angles=[(0, 0), (90, 0), (90, 90)], fractions=[0, 0, 0], snr=None) ds = GeneralizedQSamplingModel(bvals, bvecs, odf_sphere) dsfit = ds.fit(S) QA = dsfit.qa assert_equal(np.sum(QA > 0), 0) #3 fibers DSI2 S, stics = SticksAndBall(bvals, bvecs, d=0.0015, S0=100, angles=[(0, 0), (90, 0), (90, 90)], fractions=[33, 33, 33], snr=None) ds = GeneralizedQSamplingModel(bvals, bvecs, odf_sphere, squared=True) ds.relative_peak_threshold = 0.5 dsfit = ds.fit(S, gfa_thr=0.05) QA = dsfit.qa #3 fibers DSI2 with a 3D volume data = np.zeros((3, 3, 3, len(S))) data[..., :] = S.copy() dsfit = ds.fit(data, gfa_thr=0.05) #1/0 assert_array_almost_equal(np.sum(dsfit.peak_values > 0, axis=-1), 3 * np.ones((3, 3, 3)))
def test_gqi(): # load odf sphere vertices, faces = sphere_vf_from("symmetric724") edges = unique_edges(faces) half_vertices, half_edges, half_faces = reduce_antipodal(vertices, faces) # load bvals and gradients btable = np.loadtxt(get_data("dsi515btable")) bvals = btable[:, 0] bvecs = btable[:, 1:] S, stics = SticksAndBall( bvals, bvecs, d=0.0015, S0=100, angles=[(0, 0), (90, 0), (90, 90)], fractions=[50, 50, 0], snr=None ) # pdf0,odf0,peaks0=standard_dsi_algorithm(S,bvals,bvecs) S2 = S.copy() S2 = S2.reshape(1, len(S)) odf_sphere = (vertices, faces) ds = GeneralizedQSamplingModel(bvals, bvecs, odf_sphere) dsfit = ds.fit(S) assert_equal((dsfit.peak_values > 0).sum(), 3) # change thresholds ds.relative_peak_threshold = 0.5 ds.angular_distance_threshold = 30 dsfit = ds.fit(S) assert_equal((dsfit.peak_values > 0).sum(), 2) # 1 fiber S, stics = SticksAndBall( bvals, bvecs, d=0.0015, S0=100, angles=[(0, 0), (90, 0), (90, 90)], fractions=[100, 0, 0], snr=None ) ds = GeneralizedQSamplingModel(bvals, bvecs, odf_sphere) ds.relative_peak_threshold = 0.5 ds.angular_distance_threshold = 20 dsfit = ds.fit(S) QA = dsfit.qa # 1/0 assert_equal(np.sum(QA > 0), 1) # 2 fibers S, stics = SticksAndBall( bvals, bvecs, d=0.0015, S0=100, angles=[(0, 0), (90, 0), (90, 90)], fractions=[50, 50, 0], snr=None ) ds = GeneralizedQSamplingModel(bvals, bvecs, odf_sphere) ds.relative_peak_threshold = 0.5 ds.angular_distance_threshold = 20 dsfit = ds.fit(S) QA = dsfit.qa assert_equal(np.sum(QA > 0), 2) # 3 fibers S, stics = SticksAndBall( bvals, bvecs, d=0.0015, S0=100, angles=[(0, 0), (90, 0), (90, 90)], fractions=[33, 33, 33], snr=None ) ds = GeneralizedQSamplingModel(bvals, bvecs, odf_sphere) ds.relative_peak_threshold = 0.5 dsfit = ds.fit(S) QA = dsfit.qa assert_equal(np.sum(QA > 0), 3) # isotropic S, stics = SticksAndBall( bvals, bvecs, d=0.0015, S0=100, angles=[(0, 0), (90, 0), (90, 90)], fractions=[0, 0, 0], snr=None ) ds = GeneralizedQSamplingModel(bvals, bvecs, odf_sphere) dsfit = ds.fit(S) QA = dsfit.qa assert_equal(np.sum(QA > 0), 0) # 3 fibers DSI2 S, stics = SticksAndBall( bvals, bvecs, d=0.0015, S0=100, angles=[(0, 0), (90, 0), (90, 90)], fractions=[33, 33, 33], snr=None ) ds = GeneralizedQSamplingModel(bvals, bvecs, odf_sphere, squared=True) ds.relative_peak_threshold = 0.5 dsfit = ds.fit(S, gfa_thr=0.05) QA = dsfit.qa # 3 fibers DSI2 with a 3D volume data = np.zeros((3, 3, 3, len(S))) data[..., :] = S.copy() dsfit = ds.fit(data, gfa_thr=0.05) # 1/0 assert_array_almost_equal(np.sum(dsfit.peak_values > 0, axis=-1), 3 * np.ones((3, 3, 3)))
data.shape ``(96, 96, 60, 203)`` This dataset has anisotropic voxel sizes, therefore reslicing is necessary. """ affine = img.affine """ Read the voxel size from the image header. """ voxel_size = img.header.get_zooms()[:3] """ Instantiate the model and apply it to the data. """ gqmodel = GeneralizedQSamplingModel(gtab, sampling_length=3) """ The parameter ``sampling_length`` is used here to Lets just use one slice only from the data. """ dataslice = data[:, :, data.shape[2] // 2] mask = dataslice[..., 0] > 50 gqfit = gqmodel.fit(dataslice, mask=mask) """ Load an ODF reconstruction sphere """
# data = data[:, :, 25] mevals = np.array([[0.0017, 0.0003, 0.0003], [0.0017, 0.0003, 0.0003], [0.0017, 0.0003, 0.0003]]) # ang = [(20, 10), (70, 20), (45, 60)] ang = [(0, 0), (45, 45), (90, 90)] data, sticks = MultiTensor(gtab, mevals, S0=100, angles=ang, fractions=[33.3, 33.3, 33.4], snr=100) gqi_model = GeneralizedQSamplingModel(gtab, method='gqi2', sampling_length=4., normalize_peaks=False) gqi_fit = gqi_model.fit(data) sphere = get_sphere('symmetric724') gqi_odf = gqi_fit.odf(sphere) def optimal_transform(model, data, sphere): from dipy.reconst.gqi import squared_radial_component H = squared_radial_component b_vector = model.b_vector bnorm = np.sqrt(np.sum(b_vector ** 2, axis=1))
import nibabel as nib from dipy.reconst.gqi import GeneralizedQSamplingModel from dipy.reconst.odf import gfa from dipy.reconst.dsi import DiffusionSpectrumDeconvModel from dipy.data import get_sphere from dipy.viz.mayavi.spheres import show_odfs from load_data import get_train_dsi data, affine, gtab = get_train_dsi(30) gqi_model = GeneralizedQSamplingModel(gtab, method='gqi2', sampling_length=3, normalize_peaks=True) crop = 20 gqi_fit = gqi_model.fit(data[crop:29,crop:29,crop:29]) sphere = get_sphere('symmetric724') gqi_odf = gqi_fit.odf(sphere) gqi_gfa = gfa(gqi_odf) import nibabel as nib affine[:3,3] += crop print affine nib.save(nib.Nifti1Image(gqi_odf, affine), 'gqi_odf_norm.nii.gz') nib.save(nib.Nifti1Image(gqi_gfa, affine), 'gfa_norm.nii.gz') import numpy as np
S0 = np.mean(S0s) l01 = np.mean(lambdas, axis = 0) evals = np.array([l01[0], l01[1], l01[1]]) #1/0 data = data[25 - 10:25 + 10, 25 - 10:25 + 10, 25] mask = mask[25 - 10:25 + 10, 25 - 10:25 + 10, 25] # data = data[:, :, 25] model_tag = 'dsdeconv_' model = GeneralizedQSamplingModel(gtab, method='gqi2', sampling_length=3., normalize_peaks=False) #model = DiffusionSpectrumDeconvModel(gtab) fit = model.fit(data, mask) sphere = get_sphere('symmetric724') odf = fit.odf(sphere) #nib.save(nib.Nifti1Image(odf, affine), model_tag + 'odf.nii.gz')
# # fvtk.add(r, fvtk.line(np.array([[0, 0, 0], sticks2H[1]]), fvtk.green)) # # fvtk.add(r, fvtk.line(np.array([[0, 0, 0], sticks2H[2]]), fvtk.green)) fvtk.show(r) # from pylab import plot, show # plot(S, 'b') # plot(S2, 'r') # show() # # plot(np.abs(S - S2)) # plot((S - S2)) # show() gq = GeneralizedQSamplingModel(gtab_full, sampling_length=3.5) gqfit = gq.fit(SS) gqodf = gqfit.odf(sphere) gqdir, _, _ = peak_directions(gqodf, sphere, .35, 15) print angular_similarity(sticks, gqdir) grid_size = 35 dds = DiffusionSpectrumDeconvModel(gtab_full, qgrid_size=grid_size, r_start=0.2 * (grid_size // 2), r_end=0.7 * (grid_size // 2), r_step=0.02 * (grid_size // 2), filter_width=np.inf,
rec_model = 'GQI2' sphere = get_sphere('repulsion724') bvals, bvecs = read_bvals_bvecs(fbvals, fbvecs) gtab = gradient_table(bvals, bvecs) data, affine, vox_size = load_nifti(fdwi, return_voxsize=True) mask, _ = load_nifti(fbmask) pve, _, img, vox_size = load_nifti(fpve, return_img=True, return_voxsize=True) shape = data.shape[:3] if rec_model == 'GQI2': # Try with SFM, SHore, MAPL, MSMTCSD model = GeneralizedQSamplingModel(gtab, sampling_length=1.2) if rec_model == 'SFM': # Ariel please add here your best SFM calls and parameters pass if rec_model == 'MAPL': # Brent look at Aman's PR and call here pass if rec_model == 'CSD': # Elef add CSD version and add MTMSCSD when is ready. pass pam = peaks_from_model(model, data, sphere,
This dataset has anisotropic voxel sizes, therefore reslicing is necessary. """ affine = img.affine """ Read the voxel size from the image header. """ voxel_size = img.header.get_zooms()[:3] """ Instantiate the Model and apply it to the data. """ gqmodel = GeneralizedQSamplingModel(gtab, sampling_length=3) """ The parameter `sampling_length` is used here to Lets just use one slice only from the data. """ dataslice = data[:, :, data.shape[2] / 2] mask = dataslice[..., 0] > 50 gqfit = gqmodel.fit(dataslice, mask=mask) """ Load an odf reconstruction sphere
bvals, bvecs = read_bvals_bvecs(fdsi_bvals, fdsi_bvecs) gtab = gradient_table(bvals, bvecs) #sb = sticks_and_ball_dummies(gtab) S, sticks = SticksAndBall(gtab, d=0.0015, S0=100, angles=[(0, 0), (30, 0)], fractions=[50, 50], snr=30.0) sphere = get_sphere('symmetric724') sphere = sphere.subdivide(n=1) r=np.zeros(sphere.vertices.shape[0]) sampling_lengths=[1.25,1.5,2.,2.5,3.,3.5,4.] for ss in sampling_lengths: gqi_model = GeneralizedQSamplingModel(gtab, method='gqi2', sampling_length=ss, normalize_peaks=False) gqi_fit = gqi_model.fit(S) gqi_odf = gqi_fit.odf(sphere) r=np.vstack((r,gqi_odf)) show_odfs(r[:,None,None], sphere)