Esempio n. 1
0
def show_signals(data,bvals,gradients,sticks=None):
    
    s=data[1:]
    s0=data[0]    
    ls=np.log(s)-np.log(s0)
    ind=np.arange(1,data.shape[-1])
    ob=-1/bvals[1:]
    #lg=np.log(s[1:])-np.log(s0)
    d=ob*(np.log(s)-np.log(s0))    
    r=fvtk.ren()
    all=fvtk.crossing(s,ind,gradients,scale=1)
    #fvtk.add(r,fvtk.line(all,fvtk.coral))    
    #d=d-d.min()        
    #all3=fvtk.crossing(d,ind,gradients,scale=10**4)
    #fvtk.add(r,fvtk.line(all3,fvtk.red))    
    #d=d-d.min()        
    all2=fvtk.crossing(d,ind,gradients,scale=10**4)
    fvtk.add(r,fvtk.line(all2,fvtk.green))    
    #"""
    #d2=d*10**4
    #print d2.min(),d2.mean(),d2.max(),d2.std()    
    for a in all2:    
        fvtk.label(r,str(np.round(np.linalg.norm(a[0]),2)),pos=a[0],scale=(.2,.2,.2),color=(1,0,0))        
    if sticks!=None:
        for s in sticks:
            ln=np.zeros((2,3))
            ln[1]=s
            fvtk.add(r,fvtk.line(d.max()*10**4*ln,fvtk.blue)) 
    #data2=data.reshape(1,len(data))
    #pdi=ProjectiveDiffusivity(data2,bvals,gradients,dotpow=6,width=6,sincpow=2)
    #pd=pdi.spherical_diffusivity(data)
    #print pd
    #"""    
    fvtk.show(r)
def showsls(sls, values, outpath, show=False):
    from dipy.viz import window, actor, fvtk
    from dipy.data import fetch_bundles_2_subjects, read_bundles_2_subjects
    from dipy.tracking.streamline import transform_streamlines
    #renderer.clear()

    from dipy.tracking.streamline import length

    renderer = window.Renderer()

    hue = [0.5, 1]  # white to purple to red
    saturation = [0.0, 1.0]  # black to white

    lut_cmap = actor.colormap_lookup_table(
        scale_range=(values.min(), np.percentile(values, 50)),
        hue_range=hue,
        saturation_range=saturation)

    stream_actor5 = actor.line(sls,
                               values,
                               linewidth=0.1,
                               lookup_colormap=lut_cmap)

    renderer.add(stream_actor5)
    bar3 = actor.scalar_bar(lut_cmap)

    renderer.add(bar3)

    # window.show(renderer, size=(600, 600), reset_camera=False)
    if outpath:
        window.record(renderer, out_path=outpath, size=(600, 600))
    if show:
        fvtk.show(renderer)
Esempio n. 3
0
def draw_ellipsoid(data, gtab, outliers, data_without_noise):

    bvecs = gtab.bvecs
    raw_data = bvecs * np.array([data, data, data]).T

    ren = fvtk.ren()

    # Draw Sphere of predicted data
    new_sphere = sphere.Sphere(xyz=bvecs[~gtab.b0s_mask, :])
    sf1 = fvtk.sphere_funcs(data_without_noise[~gtab.b0s_mask],
                            new_sphere,
                            colormap=None,
                            norm=False,
                            scale=1)
    sf1.GetProperty().SetOpacity(0.35)
    fvtk.add(ren, sf1)

    # Draw Raw Data as points, Red means outliers
    good_values = [index for index, voxel in enumerate(outliers) if voxel == 0]
    bad_values = [index for index, voxel in enumerate(outliers) if voxel == 1]
    point_actor_good = fvtk.point(raw_data[good_values, :],
                                  fvtk.colors.yellow,
                                  point_radius=.05)
    point_actor_bad = fvtk.point(raw_data[bad_values, :],
                                 fvtk.colors.red,
                                 point_radius=0.05)
    fvtk.add(ren, point_actor_good)
    fvtk.add(ren, point_actor_bad)

    fvtk.show(ren)
Esempio n. 4
0
def show_many_fractions(name):

    data,bvals,bvecs=get_data(name)
    
    S0s=[];S1s=[];S2s=[];
    X0s=[];X1s=[];X2s=[];
    U0s=[];U1s=[];U2s=[];
    
    Fractions=[0,10,20,30,40,50,60,70,80,90,100]
    #Fractions=[90,100]
    for f in Fractions:
        S0,sticks=simulations_dipy(bvals,bvecs,d=0.0015,S0=200,angles=[(0,0)],fractions=[f],snr=None)
        X0=diffusivitize(S0,bvals,bvecs);S0s.append(S0);X0s.append(X0)
        
        S1,sticks=simulations_dipy(bvals,bvecs,d=0.0015,S0=200,angles=[(0,0),(90,0)],fractions=[f/2.,f/2.],snr=None)
        X1=diffusivitize(S1,bvals,bvecs);S1s.append(S1);X1s.append(X1)
        
        S2,sticks=simulations_dipy(bvals,bvecs,d=0.0015,S0=200,angles=[(0,0),(90,0),(90,90)],fractions=[f/3.,f/3.,f/3.],snr=None)
        X2=diffusivitize(S2,bvals,bvecs);S2s.append(S2);X2s.append(X2)
        U,s,V=np.linalg.svd(np.dot(X2.T,X2),full_matrices=True)
        U2s.append(U)
        
    r=fvtk.ren()
    for i in range(len(Fractions)):
        fvtk.add(r,fvtk.point(X0s[i]+np.array([30*i,0,0]),fvtk.red,1,.5,8,8))
        fvtk.add(r,fvtk.point(X1s[i]+np.array([30*i,30,0]),fvtk.green,1,.5,8,8))
        fvtk.add(r,fvtk.point(X2s[i]+np.array([30*i,60,0]),fvtk.yellow,1,.5,8,8))
        
    fvtk.show(r)
Esempio n. 5
0
def plot_proj_shell(ms,
                    use_sym=True,
                    use_sphere=True,
                    same_color=False,
                    rad=0.025):

    ren = fvtk.ren()
    ren.SetBackground(1, 1, 1)
    if use_sphere:
        sphere = get_sphere('symmetric724')
        sphere_actor = fvtk.sphere_funcs(np.ones(sphere.vertices.shape[0]),
                                         sphere,
                                         colormap='winter',
                                         scale=0)
        fvtk.add(ren, sphere_actor)

    for i, shell in enumerate(ms):
        if same_color:
            i = 0
        pts_actor = fvtk.point(shell, vtkcolors[i], point_radius=rad)
        fvtk.add(ren, pts_actor)
        if use_sym:
            pts_actor = fvtk.point(-shell, vtkcolors[i], point_radius=rad)
            fvtk.add(ren, pts_actor)
    fvtk.show(ren)
def show_all_bundles(start, end):

    ren = fvtk.ren()
    ren.SetBackground(1, 1, 1.)
    from dipy.viz.fvtk import colors as c

    colors = [c.alice_blue, c.maroon, c.alizarin_crimson, c.mars_orange, c.antique_white,
             c.mars_yellow, c.aquamarine, c.melon, c.aquamarine_medium, c.midnight_blue,
             c.aureoline_yellow, c.mint, c.azure, c.mint_cream, c.banana, c.misty_rose,
             c.beige]

    print(len(colors))

    for (i, bundle) in enumerate(bundle_names[start:end]):

        bun = load_bundle(bundle)

        bun_actor = vtk_a.streamtube(bun, colors[i], linewidth=0.5, tube_sides=9)
        fvtk.add(ren, bun_actor)

    fvtk.show(ren, size=(1800, 1000))
    #fvtk.record(ren, n_frames=100, out_path='test.png', 
    #            magnification=1)
    fvtk.record(ren, size=(1800, 1000), n_frames=100, out_path='test.png', 
                path_numbering=True, magnification=1)
Esempio n. 7
0
def plot_tract(bundle, affine, num_class=1, pred=[], ignore=[]):
    # Visualize the results
    from dipy.viz import fvtk, actor
    from dipy.tracking.streamline import transform_streamlines

    # Create renderer
    r = fvtk.ren()

    if len(pred) > 0:
        colors = get_spaced_colors(num_class)
        for i in range(num_class):
            if i in ignore:
                continue
            idx = np.argwhere(pred == i).squeeze()
            bundle_native = transform_streamlines(
                bundle[idx], np.linalg.inv(affine))
            if len(bundle_native) == 0:
                continue
            lineactor = actor.line(
                bundle_native, colors[i], linewidth=0.2)
            fvtk.add(r, lineactor)
    elif num_class == 1:
        bundle_native = transform_streamlines(bundle, np.linalg.inv(affine))
        lineactor = actor.line(bundle_native, linewidth=0.2)
        fvtk.add(r, lineactor)

    # Show original fibers
    fvtk.camera(r, pos=(-264, 285, 155), focal=(0, -14, 9),
        viewup=(0, 0, 1), verbose=False)

    fvtk.show(r)
Esempio n. 8
0
def visualize(streamlines_A, streamlines_B, mappingAB, line='line', shift=np.array([0.0, 0.0, 200.0]), color_A=fvtk.colors.white, color_B=fvtk.colors.green, color_line=fvtk.colors.yellow):
    assert(len(mappingAB) == len(streamlines_A))
    assert(mappingAB.max() <= len(streamlines_B))
    if line == 'line':
        line = fvtk.line
        linewidth = 2.0
        linekwargs = {'linewidth':linewidth}
    elif line == 'tube':
        line = fvtk.streamtube
        linewidth = 1.0
        linekwargs = {'linewidth':linewidth, 'lod':False}
    else:
        raise Exception

    if color_A == 'auto':
        color_A = line_colors(streamlines_A)

    if color_B == 'auto':
        color_B = line_colors(streamlines_B)
            
    streamlines_B_shifted = np.array([s + shift for s in streamlines_B])
    midpointA = [s[int(s.shape[0] / 2)] for s in streamlines_A]
    midpointB = [s[int(s.shape[0] / 2)] for s in streamlines_B_shifted]

    ren = fvtk.ren()
    fvtk.add(ren, line(streamlines_A.tolist(), colors=color_A, **linekwargs))
    fvtk.add(ren, line(streamlines_B_shifted.tolist(), colors=color_B, **linekwargs))
    fvtk.add(ren, fvtk.line(zip(midpointA, midpointB), colors=color_line, opacity=0.5, linewidth=0.5))
    fvtk.show(ren)
Esempio n. 9
0
def visualize_bundles(trk, ren=None, inline=True, interact=False):
    """
    Visualize bundles in 3D using fvtk


    """
    if isinstance(trk, str):
        trk = nib.streamlines.load(trk)

    if ren is None:
        ren = fvtk.ren()

    for b in np.unique(trk.tractogram.data_per_streamline['bundle']):
        idx = np.where(trk.tractogram.data_per_streamline['bundle'] == b)[0]
        this_sl = list(trk.streamlines[idx])
        sl_actor = fvtk.line(this_sl, Tableau_20.colors[int(b)])
        fvtk.add(ren, sl_actor)

    if inline:
        tdir = tempfile.gettempdir()
        fname = op.join(tdir, "fig.png")
        fvtk.record(ren, out_path=fname)
        display.display_png(display.Image(fname))

    if interact:
        fvtk.show(ren)

    return ren
Esempio n. 10
0
def viz_vol(vol):
   
    
    ren = fvtk.ren()
    vl = 100*vol
    v = fvtk.volume(vl)
    fvtk.add(ren, v)    
    fvtk.show(ren)
Esempio n. 11
0
def show_sim_odfs(peaks, sphere, title):
    ren = fvtk.ren()
    odf = np.dot(peaks.shm_coeff, peaks.invB)
    odf2 = peaks.odf
    print(np.sum( np.abs(odf - odf2)))
    sfu = fvtk.sphere_funcs(odf, sphere, norm=True)
    fvtk.add(ren, sfu)
    fvtk.show(ren, title=title)
Esempio n. 12
0
def draw_p(p, x, new_sphere):
    ren = fvtk.ren()
    raw_data = x * np.array([p, p, p])

    sf1 = fvtk.sphere_funcs(raw_data, new_sphere, colormap=None, norm=False, scale=0)
    sf1.GetProperty().SetOpacity(0.35)
    fvtk.add(ren, sf1)
    
    fvtk.show(ren)
def show(fname):

    streams, hdr = tv.read(fname)
    streamlines = [s[0] for s in streams]

    renderer = fvtk.ren() 
    fvtk_tubes = vtk_a.line(streamlines, opacity=0.2, linewidth=5)
    fvtk.add(renderer, fvtk_tubes)
    fvtk.show(renderer)
Esempio n. 14
0
def show_Pi_mapping(streamlines_A, streamlines_B, Pi_ids_A, mapping_Pi):
        r = fvtk.ren()
        Pi_viz_A = fvtk.streamtube(streamlines_A[Pi_ids_A], fvtk.colors.red)
        fvtk.add(r, Pi_viz_A)
        # Pi_viz_B = fvtk.streamtube(streamlines_B[Pi_ids_B], fvtk.colors.blue)
        # fvtk.add(r, Pi_viz_B)
        Pi_viz_A_1nn_B = fvtk.streamtube(streamlines_B[mapping_Pi], fvtk.colors.white)
        fvtk.add(r, Pi_viz_A_1nn_B)
        fvtk.show(r)
Esempio n. 15
0
def plotODF(ODF, sphere):
    r = fvtk.ren()
    sfu = fvtk.sphere_funcs(ODF, sphere, scale=2.2, norm=True)
    sfu.RotateY(90)
    # sfu.RotateY(180)
    fvtk.add(r, sfu)
    # outname = 'screenshot_signal_r.png'
    # fvtk.record(r, n_frames=1, out_path = outname, size=(3000, 1500), magnification = 2)
    fvtk.show(r)
Esempio n. 16
0
def show_odfs(peaks, sphere):
    ren = fvtk.ren()
    odf = np.dot(peaks.shm_coeff, peaks.invB)
    #odf = odf[14:24, 22, 23:33]
    #odf = odf[:, 22, :]
    odf = odf[:, 0, :]
    sfu = fvtk.sphere_funcs(odf[:, None, :], sphere, norm=True)
    sfu.RotateX(-90)
    fvtk.add(ren, sfu)
    fvtk.show(ren)
Esempio n. 17
0
def show_tract(segmented_tract, color):
    ren = fvtk.ren()
    fvtk.add(
        ren,
        fvtk.line(segmented_tract.tolist(),
                  colors=color,
                  linewidth=2,
                  opacity=0.3))
    fvtk.show(ren)
    fvtk.clear(ren)
Esempio n. 18
0
def show_odf_sample(filename):

    odf = nib.load(filename).get_data()

    sphere = get_sphere('symmetric724')
    from dipy.viz import fvtk
    r = fvtk.ren()
    # fvtk.add(r, fvtk.sphere_funcs(odf[:, :, 25], sphere))
    fvtk.add(r, fvtk.sphere_funcs(odf[25 - 10:25 + 10, 25 - 10:25 + 10, 25], sphere))
    fvtk.show(r)
def show_tract(segmented_tract, color):
    """Visualization of the segmented tract.
    """
    ren = fvtk.ren()
    fvtk.add(ren, fvtk.line(segmented_tract.tolist(),
                            colors=color,
                            linewidth=2,
                            opacity=0.3))
    fvtk.show(ren)
    fvtk.clear(ren)
Esempio n. 20
0
def see_skeletons(fskel):
    
    C=load_pickle(fskel)
    tracks=[C[c]['most'] for c in C if C[c]['N'] > 10 ]
    
    r=fvtk.ren()    
    colors=np.array([t[0]-t[-1] for t in tracks])
    colors=colormap.orient2rgb(colors)
    fvtk.add(r,fvtk.line(tracks,colors))
    
    fvtk.show(r)
def show(imgtck, clusters, out_path):
    colormap = fvtk.create_colormap(np.ravel(clusters.centroids), name='jet')
    colormap_full = np.ones((len(imgtck.streamlines), 3))
    for cluster, color in zip(clusters, colormap):
        colormap_full[cluster.indices] = color

    ren = fvtk.ren()
    ren.SetBackground(1, 1, 1)
    fvtk.add(ren, fvtk.streamtube(imgtck.streamlines, colormap_full))
    fvtk.record(ren, n_frames=1, out_path=out_path, size=(600, 600))
    fvtk.show(ren)
def show_all_bundles_fnames(fnames, colors=None):

    ren = fvtk.ren()
    for (i, fname) in enumerate(fnames):
        streamlines = read_bundles(fname)
        if colors is None:
            color = np.random.rand(3)
        else:
            color = colors[i]
        fvtk.add(ren, fvtk.line(streamlines, color))
    fvtk.show(ren)
Esempio n. 23
0
def show_odfs_with_map(odf, sphere, map):
    ren = fvtk.ren()
    sfu = fvtk.sphere_funcs(odf[:, None, :], sphere, norm=True)
    sfu.RotateX(-90)
    sfu.SetPosition(5, 5, 1)
    sfu.SetScale(0.435)

    slice = fvtk.slicer(map, plane_i=None, plane_j=[0])
    slice.RotateX(-90)
    fvtk.add(ren, slice)
    fvtk.add(ren, sfu)
    fvtk.show(ren)
Esempio n. 24
0
def displaySphericalHist(odf, pts, minmax=False):
    # assumes pts and odf are hemisphere
    fullsphere = HemiSphere(xyz=pts).mirror()
    fullodf = np.concatenate((odf, odf), axis=0)

    r = fvtk.ren()
    if minmax:
        a = fvtk.sphere_funcs(fullodf - fullodf.min(), fullsphere)
    else:
        a = fvtk.sphere_funcs(fullodf, fullsphere)
    fvtk.add(r, a)
    fvtk.show(r)
def show_odfs(peaks, sphere, fname):
    ren = fvtk.ren()
    ren.SetBackground(1, 1, 1.)
    odf = np.dot(peaks.shm_coeff, peaks.invB)
    #odf = odf[14:24, 22, 23:33]
    #odf = odf[:, 22, :]
    odf = odf[:, 0, :]
    sfu = fvtk.sphere_funcs(odf[:, None, :], sphere, norm=True)
    sfu.RotateX(-90)
    fvtk.add(ren, sfu)
    fvtk.show(ren)
    fvtk.record(ren, n_frames=1, out_path=fname, size=(600, 600))
Esempio n. 26
0
def show_sph_grid():
    r=fvtk.ren()
    print verts.shape, faces.shape
    sph=np.abs(np.dot(gradients[1],verts.T)**2)
    print sph.shape
    cols=fvtk.colors(sph,'jet')
    #fvtk.add(r,fvtk.point(verts,cols,point_radius=.1,theta=10,phi=10))
    
    for (i,v) in enumerate(gradients):    
        fvtk.label(r,str(i),pos=v,scale=(.02,.02,.02))
        if i in [62,76,58]:
            fvtk.label(r,str(i),pos=v,scale=(.05,.05,.05),color=(1,0,0))
    fvtk.show(r)
Esempio n. 27
0
def draw_p(p, x, new_sphere):
    ren = fvtk.ren()
    raw_data = x * np.array([p, p, p])

    sf1 = fvtk.sphere_funcs(raw_data,
                            new_sphere,
                            colormap=None,
                            norm=False,
                            scale=0)
    sf1.GetProperty().SetOpacity(0.35)
    fvtk.add(ren, sf1)

    fvtk.show(ren)
Esempio n. 28
0
def show_odfs(fpng, odf_sh, invB, sphere):
    ren = fvtk.ren()
    ren.SetBackground(1, 1, 1.0)
    odf = np.dot(odf_sh, invB)
    print(odf.shape)
    odf = odf[14:24, 22, 23:33]
    # odf = odf[:, 22, :]
    # odf = odf[:, 0, :]
    sfu = fvtk.sphere_funcs(odf[:, None, :], sphere, norm=True)
    sfu.RotateX(-90)
    fvtk.add(ren, sfu)
    fvtk.show(ren)
    fvtk.record(ren, n_frames=1, out_path=fpng, size=(900, 900))
    fvtk.clear(ren)
Esempio n. 29
0
def test(x,y,z):
    
    fimg,fbvals,fbvecs=get_dataX('small_101D')
    img=nib.load(fimg)
    data=img.get_data()
    print('data.shape (%d,%d,%d,%d)' % data.shape)
    bvals=np.loadtxt(fbvals)
    bvecs=np.loadtxt(fbvecs).T
    S=data[x,y,z,:]
    print('S.shape (%d)' % S.shape)
    X=diffusivitize(S,bvals,bvecs,scale=10**4)
    r=fvtk.ren()
    fvtk.add(r,fvtk.point(X,fvtk.green,1,.5,16,16))
    fvtk.show(r)
Esempio n. 30
0
def show_odfs_from_nii(fshm_coeff, finvB, sphere=None):

    odf_sh = nib.load(fshm_coeff).get_data()
    invB = np.loadtxt(finvB)
    odf = np.dot(odf_sh, invB.T)
    # odf = odf[14:24, 22, 23:33]
    odf = odf[:, 22, :]

    if sphere is None:
        sphere = get_sphere('symmetric724')
    ren = fvtk.ren()
    sfu = fvtk.sphere_funcs(odf[:, None, :], sphere, norm=True)
    fvtk.add(ren, sfu)
    fvtk.show(ren)
def show_tracts(estimated_target_tract, target_tract):
    """Visualization of the tracts.
	"""
    ren = fvtk.ren()
    fvtk.add(
        ren,
        fvtk.line(estimated_target_tract,
                  fvtk.colors.green,
                  linewidth=1,
                  opacity=0.3))
    fvtk.add(
        ren,
        fvtk.line(target_tract, fvtk.colors.white, linewidth=2, opacity=0.3))
    fvtk.show(ren)
    fvtk.clear(ren)
Esempio n. 32
0
def loadPeaksFromMrtrix():

    filename='CSD8.nii.gz'
    mask='mask.nii.gz'
    pkdir,pkval,pkind = getPeaksFromMrtrix(filename, mask)
    fodf_peaks = fvtk.peaks(pkdir, pkval, scale=1)
    #fodf_spheres = fvtk.sphere_funcs(data_small, sphere, scale=0.6, norm=False)

    ren = fvtk.ren()
    #fodf_spheres.GetProperty().SetOpacity(0.4)
    fvtk.add(ren, fodf_peaks)
    #fvtk.add(ren, fodf_peaks)
    fvtk.show(ren)

    return fodf_peaks
Esempio n. 33
0
def show_both_bundles(bundles, colors=None, show=False, fname=None):

    ren = fvtk.ren()
    ren.SetBackground(1.0, 1, 1)
    for (i, bundle) in enumerate(bundles):
        color = colors[i]
        lines = fvtk.streamtube(bundle, color, linewidth=0.3)
        lines.RotateX(-90)
        lines.RotateZ(90)
        fvtk.add(ren, lines)
    if show:
        fvtk.show(ren)
    if fname is not None:
        sleep(1)
        fvtk.record(ren, n_frames=1, out_path=fname, size=(900, 900))
Esempio n. 34
0
def show_both_bundles(bundles, colors=None, show=False, fname=None):

    ren = fvtk.ren()
    ren.SetBackground(1., 1, 1)
    for (i, bundle) in enumerate(bundles):
        color = colors[i]
        lines = fvtk.streamtube(bundle, color, linewidth=0.3)
        lines.RotateX(-90)
        lines.RotateZ(90)
        fvtk.add(ren, lines)
    if show:
        fvtk.show(ren)
    if fname is not None:
        sleep(1)
        fvtk.record(ren, n_frames=1, out_path=fname, size=(900, 900))
Esempio n. 35
0
def draw_odf(data, gtab, odf, sphere_odf):

    ren = fvtk.ren()
    bvecs = gtab.bvecs
    raw_data = bvecs * np.array([data, data, data]).T

    # Draw Raw Data as points, Red means outliers    
    point = fvtk.point(raw_data[~gtab.b0s_mask, :], fvtk.colors.red, point_radius=0.05)
    fvtk.add(ren, point)

    sf1 = fvtk.sphere_funcs(odf, sphere_odf, colormap=None, norm=False, scale=0)
    sf1.GetProperty().SetOpacity(0.35)
    fvtk.add(ren, sf1)
    
    fvtk.show(ren)
Esempio n. 36
0
def viz_vol1(vol,color):
       
    ren = fvtk.ren()
    ren.SetBackground(255,255,255)
    d1, d2, d3 = vol.shape
    
    point = []
    for i in np.arange(d1):
        for j in np.arange(d2):
            for k in np.arange(d3):    
                if (vol[i, j, k] == 1):
                    point.append([i,j,k])
    pts = fvtk.point(point,color, point_radius=0.85)#0.85)    
    fvtk.add(ren, pts)
    fvtk.show(ren)  
Esempio n. 37
0
def draw_points(data, gtab, predicted_data):
    ren = fvtk.ren()
    bvecs = gtab.bvecs
    raw_points = bvecs * np.array([data, data, data]).T
    predicted_points = bvecs * np.array([predicted_data, predicted_data, predicted_data]).T

    # Draw Raw Data as points, Red means outliers    
    point = fvtk.point(raw_points[~gtab.b0s_mask, :], fvtk.colors.red, point_radius=0.02)
    fvtk.add(ren, point)

    new_sphere = sphere.Sphere(xyz=bvecs[~gtab.b0s_mask, :])
    sf1 = fvtk.sphere_funcs(predicted_data[~gtab.b0s_mask], new_sphere, colormap=None, norm=False, scale=0)
    sf1.GetProperty().SetOpacity(0.35)
    fvtk.add(ren, sf1)
    
    fvtk.show(ren)
Esempio n. 38
0
def renderBundles(clusters):
    from dipy.viz import fvtk
    import numpy as np

    ren = fvtk.ren()
    ren.SetBackground(0, 0, 0)

    colormap = fvtk.create_colormap(np.arange(len(clusters)))

    colormap_full = np.ones((len(streamlines), 3))
    for cluster in clusters:
        colormap_full[cluster.indices] = np.random.rand(3)

    fvtk.add(ren, fvtk.line(streamlines, colormap_full))
    #fvtk.record(ren, n_frames=1, out_path='fornix_clusters.png', size=(600, 600))
    fvtk.show(ren)
    fvtk.clear(ren)
Esempio n. 39
0
def renderCentroids(clusters):
    from dipy.viz import fvtk
    import numpy as np

    ren = fvtk.ren()
    ren.SetBackground(0, 0, 0)
    colormap = fvtk.create_colormap(np.arange(len(clusters)))

    colormap_full = np.ones((len(streamlines), 3))
    for cluster in clusters:
        colormap_full[cluster.indices] = np.random.rand(3)

    #fvtk.add(ren, fvtk.streamtube(streamlines, fvtk.colors.white, opacity=0.05))
    fvtk.add(ren, fvtk.line(clusters.centroids, linewidth=0.4, opacity=1))
    #fvtk.record(ren, n_frames=1, out_path='fornix_centroids.png', size=(600, 600))
    fvtk.show(ren)
    fvtk.clear(ren)
Esempio n. 40
0
def renderBundles(streamlines, clusters):
    from dipy.viz import fvtk
    import numpy as np
    
    ren = fvtk.ren()
    ren.SetBackground(0, 0, 0)

    colormap = fvtk.create_colormap(np.arange(len(clusters)))

    colormap_full = np.ones((len(streamlines), 3))
    for cluster in clusters:
        colormap_full[cluster.indices] = np.random.rand(3)

    fvtk.add(ren, fvtk.line(streamlines, colormap_full))
    #fvtk.record(ren, n_frames=1, out_path='fornix_clusters.png', size=(600, 600))
    fvtk.show(ren)
    fvtk.clear(ren)
Esempio n. 41
0
def renderCentroids(streamlines, clusters):
    from dipy.viz import fvtk
    import numpy as np
    
    ren = fvtk.ren()
    ren.SetBackground(0, 0, 0)
    colormap = fvtk.create_colormap(np.arange(len(clusters)))

    colormap_full = np.ones((len(streamlines), 3))
    for cluster in clusters:
        colormap_full[cluster.indices] = np.random.rand(3)

    #fvtk.add(ren, fvtk.streamtube(streamlines, fvtk.colors.white, opacity=0.05))
    fvtk.add(ren, fvtk.line(clusters.centroids, linewidth=0.4, opacity=1))
    #fvtk.record(ren, n_frames=1, out_path='fornix_centroids.png', size=(600, 600))
    fvtk.show(ren)
    fvtk.clear(ren)
Esempio n. 42
0
def show_different_ds(bvals,bvecs):
    global CNT
    r=fvtk.ren()
    r.SetBackground(1.,1.,1.)
    Signals=[]
    for d in [0.0005,0.0010,0.0015,0.0020,0.0025,0.0030,0.0035,0.0040]:
        S1,sticks1=simulations_dipy(bvals,bvecs,d=d,S0=100,angles=[(0,0),(45,0),(90,90)],fractions=[100,0,0],snr=None)
        Signals.append(S1[1:]/S1[0])
    show_signals(r,Signals,bvecs)
    CNT=0
    draw_needles(r,sticks1,100,2,off=np.array([0,0,0]))

    Signals=[]
    for d in [0.0005,0.0010,0.0015,0.0020,0.0025,0.0030,0.0035,0.0040]:
        S1,sticks1=simulations_dipy(bvals,bvecs,d=d,S0=100,angles=[(0,0),(45,0),(90,90)],fractions=[50,50,0],snr=None)
        Signals.append(S1[1:]/S1[0])
    show_signals(r,Signals,bvecs,-200)
    CNT=0
    
    Signals=[]
    for d in [0.0005,0.0010,0.0015,0.0020,0.0025,0.0030,0.0035,0.0040]:
        S1,sticks1=simulations_dipy(bvals,bvecs,d=d,S0=100,angles=[(0,0),(45,0),(90,90)],fractions=[33,33,33],snr=None)
        Signals.append(S1[1:]/S1[0])
    show_signals(r,Signals,bvecs,-400)
    """
    Signals=[]
    for d in [0.0005,0.0010,0.0015,0.0025,0.0030,0.0035,0.0040]:
        S1,sticks1=simulations_dipy(bvals,bvecs,d=d,S0=100,angles=[(0,0),(90,0),(90,90)],fractions=[20,50,0],snr=None)
        Signals.append(S1[1:]/S1[0])
    show_signals(r,Signals,bvecs,-600)
    
    Signals=[]
    for d in [0.0005,0.0010,0.0015,0.0025,0.0030,0.0035,0.0040]:
        S1,sticks1=simulations_dipy(bvals,bvecs,d=d,S0=100,angles=[(0,0),(90,0),(90,90)],fractions=[10,50,0],snr=None)
        Signals.append(S1[1:]/S1[0])
    show_signals(r,Signals,bvecs,-800)
        
    Signals=[]
    for d in [0.0005,0.0010,0.0015,0.0025,0.0030,0.0035,0.0040]:
        S1,sticks1=simulations_dipy(bvals,bvecs,d=d,S0=100,angles=[(0,0),(90,0),(90,90)],fractions=[0,50,0],snr=None)
        Signals.append(S1[1:]/S1[0])
    show_signals(r,Signals,bvecs,-1000)
    
    """
            
    fvtk.show(r)
def show_tract(segmented_tract_positive, color_positive, color_negative,
               segmented_tract_negative):
    """Visualization of the segmented tract.
   """
    ren = fvtk.ren()
    fvtk.add(
        ren,
        fvtk.line(segmented_tract_positive.tolist(),
                  colors=color_positive,
                  linewidth=2,
                  opacity=0.3))
    #   fvtk.add(ren, fvtk.line(segmented_tract_negative.tolist(),
    #                           colors=color_negative,
    #                           linewidth=2,
    #                           opacity=0.3))
    fvtk.show(ren)
    fvtk.clear(ren)
Esempio n. 44
0
def investigate_pca():
        
    data,bvals,bvecs=get_data(name='118_32')
    
    deg_angles=rotate_needles(needles=[(0,0),(90,0),(90,90)],angles=(0,0,0))
    S0,sticks0=simulations_dipy(bvals,bvecs,d=0.0015,S0=100,angles=deg_angles,fractions=[100,0,0],snr=None)
    X0=diffusivitize(S0,bvals,bvecs,invert=False)
    D0=np.sqrt(np.sum(X0**2,axis=1))
    print 'D0 shape',D0.shape
    
    
    deg_angles=rotate_needles(needles=[(0,0),(90,0),(90,90)],angles=(0,0,0))
    S1,sticks0=simulations_dipy(bvals,bvecs,d=0.0015,S0=100,angles=deg_angles,fractions=[0,100,0],snr=None)
    X1=diffusivitize(S1,bvals,bvecs,invert=False)
    D1=np.sqrt(np.sum(X1**2,axis=1))
    
    deg_angles=rotate_needles(needles=[(0,0),(90,0),(90,90)],angles=(0,0,0))
    S2,sticks0=simulations_dipy(bvals,bvecs,d=0.0015,S0=100,angles=deg_angles,fractions=[0,0,100],snr=None)
    X2=diffusivitize(S2,bvals,bvecs,invert=False)
    D2=np.sqrt(np.sum(X2**2,axis=1))
    
    
    
    deg_angles=rotate_needles(needles=[(0,0),(90,0),(90,90)],angles=(0,0,0))
    SM,sticks0=simulations_dipy(bvals,bvecs,d=0.0015,S0=100,angles=deg_angles,fractions=[33,33,33],snr=None)
    XM=diffusivitize(SM,bvals,bvecs,invert=False)
    DM=np.sqrt(np.sum(XM**2,axis=1))
    
    deg_angles=rotate_needles(needles=[(0,0),(90,0),(90,90)],angles=(0,0,0))
    SM2,sticks0=simulations_dipy(bvals,bvecs,d=0.0015,S0=100,angles=deg_angles,fractions=[50,50,0],snr=None)
    XM2=diffusivitize(SM2,bvals,bvecs,invert=False)
    DM2=np.sqrt(np.sum(XM2**2,axis=1))
    
    X012=(X0+X1+X2)/3.
    S012=(S0+S1+S2)/3.
    D012=(D0+D1+D2)/3.
    X01=(X0+X1)/2.
    
    print 'D', np.corrcoef(DM,D012)
    
    print 'X', np.corrcoef(np.sqrt(np.sum(XM**2,axis=1)), np.sqrt(np.sum(X012**2,axis=1)))
    
    r=fvtk.ren()
    fvtk.add(r,fvtk.point(X01,fvtk.yellow,1,.2,16,16))
    fvtk.add(r,fvtk.point(XM2,fvtk.red,1,.2,16,16))
    fvtk.show(r)
Esempio n. 45
0
def show_bundles(streamlines, clusters, show_b=True):
    # Color each streamline according to the cluster they belong to.
    colormap = fvtk.create_colormap(np.arange(len(clusters)))
    colormap_full = np.ones((len(streamlines), 3))
    for cluster, color in zip(clusters, colormap):
        colormap_full[cluster.indices] = color

    ren = fvtk.ren()
    ren.SetBackground(1, 1, 1)
    fvtk.add(ren, fvtk.streamtube(streamlines, colormap_full))
    fvtk.record(ren,
                n_frames=1,
                out_path='fornix_clusters_cosine.png',
                size=(600, 600))

    if show_b:
        fvtk.show(ren)
Esempio n. 46
0
def show_streamlines(streamlines, cmap='orient', opacity=1., r=None):

    if r is None:
        ren = fvtk.ren()
    else:
        ren = r
    
    if cmap == 'orient':
        colors = line_colors(streamlines)

    line_actor = fvtk.line(streamlines, colors,
                           opacity=opacity)
    fvtk.add(ren, line_actor)
        
    if r is None:
        fvtk.show(ren)
    else:
        return ren
Esempio n. 47
0
def visualize(streamlines_A,
              streamlines_B,
              mappingAB,
              line='line',
              shift=np.array([0.0, 0.0, 200.0]),
              color_A=fvtk.colors.white,
              color_B=fvtk.colors.green,
              color_line=fvtk.colors.yellow):
    assert (len(mappingAB) == len(streamlines_A))
    assert (mappingAB.max() <= len(streamlines_B))
    if line == 'line':
        line = fvtk.line
        linewidth = 2.0
        linekwargs = {'linewidth': linewidth}
    elif line == 'tube':
        line = fvtk.streamtube
        linewidth = 1.0
        linekwargs = {'linewidth': linewidth, 'lod': False}
    else:
        raise Exception

    if color_A == 'auto':
        color_A = line_colors(streamlines_A)

    if color_B == 'auto':
        color_B = line_colors(streamlines_B)

    streamlines_B_shifted = np.array([s + shift for s in streamlines_B])
    midpointA = [s[int(s.shape[0] / 2)] for s in streamlines_A]
    midpointB = [s[int(s.shape[0] / 2)] for s in streamlines_B_shifted]

    ren = fvtk.ren()
    fvtk.add(ren, line(streamlines_A.tolist(), colors=color_A, **linekwargs))
    fvtk.add(
        ren, line(streamlines_B_shifted.tolist(), colors=color_B,
                  **linekwargs))
    fvtk.add(
        ren,
        fvtk.line(zip(midpointA, midpointB),
                  colors=color_line,
                  opacity=0.5,
                  linewidth=0.5))
    fvtk.show(ren)
Esempio n. 48
0
def draw_odf(data, gtab, odf, sphere_odf):

    ren = fvtk.ren()
    bvecs = gtab.bvecs
    raw_data = bvecs * np.array([data, data, data]).T

    # Draw Raw Data as points, Red means outliers
    point = fvtk.point(raw_data[~gtab.b0s_mask, :],
                       fvtk.colors.red,
                       point_radius=0.05)
    fvtk.add(ren, point)

    sf1 = fvtk.sphere_funcs(odf,
                            sphere_odf,
                            colormap=None,
                            norm=False,
                            scale=0)
    sf1.GetProperty().SetOpacity(0.35)
    fvtk.add(ren, sf1)

    fvtk.show(ren)
Esempio n. 49
0
def show_both_bundles(bundles, colors=None, show_b=False, fname=None):
    """
    Show both bundles
    bundles: return of --pyfat/algorithm/fiber_math/bundle_registration
    example:
    show_both_bundles([cb_subj1, cb_subj2_aligned],
                     colors=[fvtk.colors.orange, fvtk.colors.red],
                     fname='after_registration.png')
    """
    ren = fvtk.ren()
    ren.SetBackground(1., 1, 1)
    for (i, bundle) in enumerate(bundles):
        color = colors[i]
        lines = fvtk.streamtube(bundle, color, linewidth=0.3)
        lines.RotateX(-90)
        lines.RotateZ(90)
        fvtk.add(ren, lines)
    if show_b:
        fvtk.show(ren)
    if fname is not None:
        sleep(1)
        fvtk.record(ren, n_frames=1, out_path=fname, size=(900, 900))
Esempio n. 50
0
    def plot(self):
        if self.pargs.plot == "no":
            return

        p = self.params['plot']

        from qball.tools.plot import plot_as_odf, prepare_odfplot
        if self.pargs.plot == "show":
            logging.info("Plotting results...")
            data = [self.data.odf_ground_truth, self.data.odf, self.upd]
            r = prepare_odfplot(data, p, self.data.dipy_sph)
            fvtk.show(r, size=(1024, 768))

        logging.info("Recording plot...")
        p['records'] = [p['slice']] if len(p['records']) == 0 else p['records']
        imgdata = [(self.upd, "upd"), (self.data.odf, "fin"),
                   (self.data.odf_ground_truth, "fin_orig")]
        plot_as_odf(imgdata, p, self.data.dipy_sph, self.output_dir)

        if hasattr(self.data, "phantom"):
            phantom_plot_file = os.path.join(self.output_dir,
                                             "plot-phantom.pdf")
            self.data.phantom.plot_phantom(output_file=phantom_plot_file)
Esempio n. 51
0
def draw_points(data, gtab, predicted_data):
    ren = fvtk.ren()
    bvecs = gtab.bvecs
    raw_points = bvecs * np.array([data, data, data]).T
    predicted_points = bvecs * np.array(
        [predicted_data, predicted_data, predicted_data]).T

    # Draw Raw Data as points, Red means outliers
    point = fvtk.point(raw_points[~gtab.b0s_mask, :],
                       fvtk.colors.red,
                       point_radius=0.02)
    fvtk.add(ren, point)

    new_sphere = sphere.Sphere(xyz=bvecs[~gtab.b0s_mask, :])
    sf1 = fvtk.sphere_funcs(predicted_data[~gtab.b0s_mask],
                            new_sphere,
                            colormap=None,
                            norm=False,
                            scale=0)
    sf1.GetProperty().SetOpacity(0.35)
    fvtk.add(ren, sf1)

    fvtk.show(ren)
Esempio n. 52
0
def main():
    parser = buildArgsParser()
    args = parser.parse_args()

    bvals, bvecs = read_bvals_bvecs(args.bvals, args.bvecs)

    ren = fvtk.ren()

    if args.points:

        points = fvtk.point(bvecs * bvals[..., None] * 0.01,
                            fvtk.colors.red,
                            point_radius=.5)
        fvtk.add(ren, points)

        if args.antipod:
            points = fvtk.point(-bvecs * bvals[..., None] * 0.01,
                                fvtk.colors.green,
                                point_radius=.5)
            fvtk.add(ren, points)
    else:
        for i in range(bvecs.shape[0]):
            label = fvtk.label(ren,
                               text=str(i),
                               pos=bvecs[i] * bvals[i] * 0.01,
                               color=fvtk.colors.red,
                               scale=(0.5, 0.5, 0.5))
            fvtk.add(ren, label)
            if args.antipod:
                label = fvtk.label(ren,
                                   text=str(i),
                                   pos=-bvecs[i] * bvals[i] * 0.01,
                                   color=fvtk.colors.green,
                                   scale=(0.5, 0.5, 0.5))
                fvtk.add(ren, label)

    fvtk.show(ren)
def main():
    parser = _build_arg_parser()
    args = parser.parse_args()
    logging.basicConfig(level=logging.INFO)

    assert_inputs_exist(parser, [args.bvecs_in, args.eddyparams])
    assert_outputs_exists(parser, args,
                          [args.bvecs_out, args.trans, args.angles])

    _, bvecs = read_bvals_bvecs(None, args.bvecs_in)

    eddy = np.loadtxt(args.eddyparams)
    eddy_a = np.array(eddy)
    bvecs_rotated = np.zeros(bvecs.shape)
    norm_diff = np.zeros(bvecs.shape[0])
    angle = np.zeros(bvecs.shape[0])

    # Documentation here: http://fsl.fmrib.ox.ac.uk/fsl/fslwiki/eddy/Faq
    # Will eddy rotate my bvecs for me?
    # No, it will not. There is nothing to prevent you from doing that
    # yourself though. eddy produces two output files, one with the corrected
    # images and another a text file with one row of parameters for each volume
    # in the --imain file. Columns 4-6 of these rows pertain to rotation
    # (in radians) around around the x-, y- and z-axes respectively.
    # eddy uses "pre-multiplication".
    # IMPORTANT: from various emails with FSL's people, we couldn't directly
    #            get the information about the handedness of the system.
    #            From the FAQ linked earlier, we deduced that the system
    #            is considered left-handed, and therefore the following
    #            matrices are correct.
    for i in range(len(bvecs)):
        theta_x = eddy_a[i, 3]
        theta_y = eddy_a[i, 4]
        theta_z = eddy_a[i, 5]
        Rx = np.array([[1, 0, 0], [0, np.cos(theta_x),
                                   np.sin(theta_x)],
                       [0, -np.sin(theta_x),
                        np.cos(theta_x)]])
        Ry = np.array([[np.cos(theta_y), 0, -np.sin(theta_y)], [0, 1, 0],
                       [np.sin(theta_y), 0,
                        np.cos(theta_y)]])
        Rz = np.array([[np.cos(theta_z), np.sin(theta_z), 0],
                       [-np.sin(theta_z), np.cos(theta_z), 0], [0, 0, 1]])
        v = bvecs[i, :]
        rotation_matrix = np.linalg.inv(np.dot(np.dot(Rx, Ry), Rz))
        v_rotated = np.dot(rotation_matrix, v)
        bvecs_rotated[i, :] = v_rotated
        norm_diff[i] = np.linalg.norm(v - v_rotated)
        if np.linalg.norm(v):
            angle[i] = np.arctan2(np.linalg.norm(np.cross(v, v_rotated)),
                                  np.dot(v, v_rotated))

    logging.info('%s mm is the maximum translation error', np.max(norm_diff))
    logging.info('%s degrees is the maximum rotation error',
                 np.max(angle) * 180 / np.pi)

    if args.vis:
        print('Red points are the original & Green points are the motion '
              'corrected ones')
        ren = fvtk.ren()
        sphere_actor = fvtk.point(bvecs,
                                  colors=fvtk.colors.red,
                                  opacity=1,
                                  point_radius=0.01,
                                  theta=10,
                                  phi=20)
        fvtk.add(ren, sphere_actor)
        sphere_actor_rot = fvtk.point(bvecs_rotated,
                                      colors=fvtk.colors.green,
                                      opacity=1,
                                      point_radius=0.01,
                                      theta=10,
                                      phi=20)
        fvtk.add(ren, sphere_actor_rot)
        fvtk.show(ren)

        fvtk.record(ren,
                    n_frames=1,
                    out_path=args.bvecs_out + '.png',
                    size=(600, 600))

    np.savetxt(args.bvecs_out, bvecs_rotated.T)

    if args.trans:
        np.savetxt(args.trans, norm_diff)

    if args.angles:
        np.savetxt(args.angles, angle * 180 / np.pi)
Esempio n. 54
0
def draw_adc(D_noisy, D, threeD=False):

    # 3D Plot
    if threeD == True:

        amound = 50
        alpha = np.linspace(0, 2 * np.pi, amound)
        theta = np.linspace(0, 2 * np.pi, amound)
        vector = np.empty((amound**2, 3))
        vector[:, 0] = (np.outer(np.sin(theta), np.cos(alpha))).reshape(
            (-1, 1))[:, 0]
        vector[:, 1] = (np.outer(np.sin(theta), np.sin(alpha))).reshape(
            (-1, 1))[:, 0]
        vector[:, 2] = (np.outer(np.cos(theta), np.ones(amound))).reshape(
            (-1, 1))[:, 0]

        adc_noisy = np.empty((vector.shape[0], 3))
        shape_noisy = np.empty((vector.shape[0], 1))
        shape = np.empty((vector.shape[0], 1))

        for i in range(vector.shape[0]):
            adc_noisy[i] = np.dot(
                vector[i], np.dot(vector[i], np.dot(D_noisy, vector[i].T)))
            shape_noisy[i] = np.dot(vector[i], np.dot(D_noisy, vector[i].T))
            shape[i] = np.dot(vector[i], np.dot(D, vector[i].T))

        ren = fvtk.ren()

        # noisy sphere
        new_sphere = sphere.Sphere(xyz=vector)
        sf1 = fvtk.sphere_funcs(shape_noisy[:, 0],
                                new_sphere,
                                colormap=None,
                                norm=False,
                                scale=0.0001)
        sf1.GetProperty().SetOpacity(0.35)
        sf1.GetProperty().SetColor((1, 0, 0))
        fvtk.add(ren, sf1)

        # ideal sphere
        sf2 = fvtk.sphere_funcs(shape[:, 0],
                                new_sphere,
                                colormap=None,
                                norm=False,
                                scale=0.0001)
        sf2.GetProperty().SetOpacity(0.35)
        fvtk.add(ren, sf2)
        #point_actor_bad = fvtk.point(adc_noisy, fvtk.colors.red, point_radius=0.00003)
        #fvtk.add(ren, point_actor_bad)

        fvtk.show(ren)

    # 2D Plot in XY-Plane
    alpha = np.linspace(0, 2 * np.pi, 100)
    vector = np.empty((100, 3))
    vector[:, 0] = np.cos(alpha)
    vector[:, 1] = np.sin(alpha)
    vector[:, 2] = 0.0
    adc_noisy_2d = np.empty((vector.shape[0], 3))
    adc_2d = np.empty((vector.shape[0], 3))
    for i in range(vector.shape[0]):
        adc_noisy_2d[i] = np.dot(
            vector[i], np.dot(vector[i], np.dot(D_noisy, vector[i].T)))
        adc_2d[i] = np.dot(vector[i], np.dot(vector[i], np.dot(D,
                                                               vector[i].T)))

    # Change Axis so that there is 20% room on each side of the plot
    x = np.concatenate((adc_noisy_2d, adc_2d), axis=0)
    minimum = np.min(x, axis=0)
    maximum = np.max(x, axis=0)
    plt.plot(adc_noisy_2d[:, 0], adc_noisy_2d[:, 1], 'r')
    plt.plot(adc_2d[:, 0], adc_2d[:, 1], 'b')
    plt.axis([
        minimum[0] * 1.2, maximum[0] * 1.2, minimum[1] * 1.2, maximum[1] * 1.2
    ])
    plt.xlabel('ADC (mm2*s-1)')
    plt.ylabel('ADC (mm2*s-1)')
    red_patch = mpatches.Patch(color='red', label='Noisy ADC')
    blue_patch = mpatches.Patch(color='blue', label='Ideal ADC')
    plt.legend(handles=[red_patch, blue_patch])
    plt.show()
Esempio n. 55
0
qball_sphere = dipy.core.sphere.Sphere(xyz=b_sph.v.T, faces=b_sph.faces.T)

maskdata, mask = median_otsu(S_data,
                             3,
                             1,
                             True,
                             vol_idx=range(10, 50),
                             dilate=2)
S_data = maskdata[20:30, 61, 28]

#u = solve_shm({ 'S': S_data, 'gtab': gtab, 'sph': qball_sphere })
u = solve_cvx({'S': S_data, 'gtab': gtab, 'sph': b_sph})

plotdata = u.copy()
if len(plotdata.shape) < 3:
    plotdata = plotdata[:, :, np.newaxis, np.newaxis].transpose(0, 2, 3, 1)
else:
    plotdata = plotdata[:, :, :, np.newaxis].transpose(0, 1, 3, 2)
plot_scale = 2.4
plot_norm = True

r = fvtk.ren()
fvtk.add(
    r,
    fvtk.sphere_funcs(plotdata,
                      qball_sphere,
                      colormap='jet',
                      norm=plot_norm,
                      scale=plot_scale))
fvtk.show(r, size=(1024, 768))
Esempio n. 56
0
def life(dwifile, bvecsfile, bvalsfile, tractogramfile, outdir,
         display_tracks=False, verbose=0):
    """ Linear fascicle evaluation (LiFE)
    Evaluating the results of tractography algorithms is one of the biggest
    challenges for diffusion MRI. One proposal for evaluation of tractography
    results is to use a forward model that predicts the signal from each of a
    set of streamlines, and then fit a linear model to these simultaneous
    prediction.

    Parameters
    ----------
    dwifile: str
        the path to the diffusion dataset.
    bvecsfile: str
        the path to the diffusion b-vectors.
    bvalsfile: str
        the path to the diffusion b-values.
    tractogramfile: str
        the path to the tractogram.
    outdir: str
        the destination folder.
    display_tracks: bool, default False
        if True render the tracks.
    verbose: int, default 0
        the verbosity level.

    Returns
    -------
    life_weights_file: str
        a file containing the fiber track weights.
    life_weights_snap: str
        a snap with the distrubution of weights.
    spatial_error_file: str
        the model root mean square error.
    tracks_snap: str
        a snap with the tracks.
    """
    # Load diffusion data and tractogram
    bvecs = numpy.loadtxt(bvecsfile)
    bvals = numpy.loadtxt(bvalsfile)
    gtab = gradient_table(bvals, bvecs)
    im = nibabel.load(dwifile)
    data = im.get_data()
    trk = nibabel.streamlines.load(tractogramfile)
    if verbose > 0:
        print("[info] Diffusion shape: {0}".format(data.shape))
        print("[info] Number of tracks: {0}".format(len(trk.streamlines)))

    # Express the tractogram in voxel coordiantes
    inv_affine = numpy.linalg.inv(trk.affine)
    trk = [
        numpy.dot(
            numpy.concatenate(
                (
                    streamline,
                    numpy.ones(
                        (len(streamline), 1)
                    )
                ), axis=1
            ),
            inv_affine) for streamline in trk.streamlines]
    trk = [track[..., :3] for track in trk]

    # Create a viewer
    tracks_snap = None
    if display_tracks:
        nb_tracks = len(trk)
        if nb_tracks < 5000:
            downsampling = 1
        else:
            downsampling = nb_tracks // 5000
        tracks_snap = os.path.join(outdir, "tracks.png")
        streamlines_actor = fvtk.line(trk[::downsampling],
                                      line_colors(trk[::downsampling]))
        vol_actor = fvtk.slicer(data[..., 0])

        vol_actor.display(data.shape[0] // 2, None, None)
        ren = fvtk.ren()
        fvtk.add(ren, streamlines_actor)
        fvtk.add(ren, vol_actor)
        fvtk.record(ren, n_frames=1, out_path=tracks_snap, size=(800, 800))
        if verbose > 1:
            fvtk.show(ren)

    # Fit the Life model and save the associated weights
    fiber_model = dpilife.FiberModel(gtab)
    fiber_fit = fiber_model.fit(data, trk, affine=numpy.eye(4))
    life_weights = fiber_fit.beta
    life_weights_file = os.path.join(outdir, "life_weights.txt")
    numpy.savetxt(life_weights_file, life_weights)
    life_weights_snap = os.path.join(outdir, "life_weights.png")
    fig, ax = plt.subplots(1)
    ax.hist(life_weights, bins=100, histtype="step")
    ax.set_xlabel("Fiber weights")
    ax.set_ylabel("# Fibers")
    fig.savefig(life_weights_snap)

    # Invert the model and predict back either the data that was used to fit
    # the model: compute the prediction error of the diffusion-weighted data
    # and calculate the root of the mean squared error.
    model_predict = fiber_fit.predict()
    model_error = model_predict - fiber_fit.data
    model_rmse = numpy.sqrt(numpy.mean(model_error[:, 10:] ** 2, -1))
    data_rmse = numpy.ones(data.shape[:3]) * numpy.nan
    data_rmse[fiber_fit.vox_coords[:, 0],
              fiber_fit.vox_coords[:, 1],
              fiber_fit.vox_coords[:, 2]] = model_rmse
    model_error_file = os.path.join(outdir, "model_rmse.nii.gz")
    error_im = nibabel.Nifti1Image(data_rmse, im.affine)
    nibabel.save(error_im, model_error_file)

    # As a baseline against which we can compare, we assume that the weight
    # for each streamline is equal to zero. This produces the naive prediction
    # of the mean of the signal in each voxel.
    life_weights_baseline = numpy.zeros(life_weights.shape[0])
    pred_weighted = numpy.reshape(
        opt.spdot(fiber_fit.life_matrix, life_weights_baseline),
        (fiber_fit.vox_coords.shape[0], numpy.sum(~gtab.b0s_mask)))
    mean_pred = numpy.empty(
        (fiber_fit.vox_coords.shape[0], gtab.bvals.shape[0]))
    S0 = fiber_fit.b0_signal

    # Since the fitting is done in the demeaned S/S0 domain, we need to add
    # back the mean and then multiply by S0 in every voxels.
    mean_pred[..., gtab.b0s_mask] = S0[:, None]
    mean_pred[..., ~gtab.b0s_mask] = (
            (pred_weighted + fiber_fit.mean_signal[:, None]) * S0[:, None])
    mean_error = mean_pred - fiber_fit.data
    mean_rmse = numpy.sqrt(numpy.mean(mean_error ** 2, -1))
    data_rmse = numpy.ones(data.shape[:3]) * numpy.nan
    data_rmse[fiber_fit.vox_coords[:, 0],
              fiber_fit.vox_coords[:, 1],
              fiber_fit.vox_coords[:, 2]] = mean_rmse
    mean_error_file = os.path.join(outdir, "mean_rmse.nii.gz")
    error_im = nibabel.Nifti1Image(data_rmse, im.affine)
    nibabel.save(error_im, mean_error_file)

    # Compute the improvment array
    data_rmse = numpy.ones(data.shape[:3]) * numpy.nan
    data_rmse[fiber_fit.vox_coords[:, 0],
              fiber_fit.vox_coords[:, 1],
              fiber_fit.vox_coords[:, 2]] = mean_rmse - model_rmse
    improvment_error_file = os.path.join(outdir, "improvment_rmse.nii.gz")
    error_im = nibabel.Nifti1Image(data_rmse, im.affine)
    nibabel.save(error_im, improvment_error_file)

    return (life_weights_file, life_weights_snap, model_error_file,
            mean_error_file, improvment_error_file, tracks_snap)
qb = QuickBundles(streamlines, dist_thr=10., pts=18)

"""
qb has attributes like `centroids` (cluster representatives), `total_clusters`
(total number of clusters) and methods like `partitions` (complete description
of all clusters) and `label2tracksids` (provides the indices of the streamlines
which belong in a specific cluster).

Lets first show the initial dataset.
"""

r = fvtk.ren()
fvtk.add(r, fvtk.line(streamlines, fvtk.colors.white, opacity=1, linewidth=3))
r0=r
fvtk.show(r0)
fvtk.record(r, n_frames=1, out_path='fornix_initial.png', size=(600, 600))

"""
.. figure:: fornix_initial.png
   :align: center

   **Initial Fornix dataset**.

Show the centroids of the fornix after clustering (with random colors):
"""

centroids = qb.centroids
colormap = np.random.rand(len(centroids), 3)

fvtk.clear(r)
Esempio n. 58
0
            #print grad3.shape
            #vertices = grad3*gradients
            vertices = gradients
        if omit > 0:
            vertices = vertices[omit:, :]
        if entry['hemi']:
            vertices = np.vstack([vertices, -vertices])

        return vertices[omit:, :]


print sphere_dic.keys()

#vertices = get_vertex_set('create5')
#vertices = get_vertex_set('siem64')
#vertices = get_vertex_set('dsi102')

vertices = get_vertex_set('fy362')
gradients = get_vertex_set('siem64')
gradients = gradients[:gradients.shape[0] / 2]
print gradients.shape

from dipy.viz import fvtk
sph = -np.sinc(np.dot(gradients[1], vertices.T))
r = fvtk.ren()
#sph = np.arange(vertices.shape[0])
print sph.shape
cols = fvtk.colors(sph, 'jet')
fvtk.add(r, fvtk.point(vertices, cols, point_radius=.1, theta=10, phi=10))
fvtk.show(r)
Esempio n. 59
0
axial_middle = data.shape[2] / 2
plt.figure('Showing the datasets')
plt.subplot(1, 2, 1).set_axis_off()
plt.imshow(data[:, :, axial_middle, 0].T, cmap='gray', origin='lower')
plt.subplot(1, 2, 2).set_axis_off()
plt.imshow(data[:, :, axial_middle, 10].T, cmap='gray', origin='lower')
plt.show()
plt.savefig('data.png', bbox_inches='tight')

from dipy.data import get_sphere
sphere = get_sphere('symmetric642')

from dipy.viz import fvtk
ren = fvtk.ren()

evals = tenfit.evals[55:85, 80:90, 40:45]
evecs = tenfit.evecs[55:85, 80:90, 40:45]

cfa = Rgbv[55:80, 80:90, 40:45]

#print cfa[1,1,1]
cfa /= cfa.max()

fvtk.add(ren, fvtk.tensor(evals, evecs, cfa))

fvtk.show(ren)
print('Saving illustration as fa.png')
fvtk.record(ren, n_frames=1, out_path='fa.png', size=(600, 600))
print "Hello World!"