Пример #1
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)
def show_gradients(gtab):
    
    renderer = window.Renderer()
    renderer.add(fvtk.point(gtab.gradients, (1,0,0), point_radius=100))
    renderer.add(fvtk.point(-gtab.gradients, (1,0,0), point_radius=100))
    
    window.show(renderer)
Пример #3
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)
Пример #4
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_gradients(gtab):

    renderer = window.Renderer()
    renderer.add(fvtk.point(gtab.gradients, (1, 0, 0), point_radius=100))
    renderer.add(fvtk.point(-gtab.gradients, (1, 0, 0), point_radius=100))

    window.show(renderer)
Пример #6
0
def show_signal(r,S,gradients,offset=np.zeros(3)):
    PS = np.dot(np.diag(S),gradients)
#for (i,s) in enumerate(S):
    fvtk.add(r,fvtk.point(offset+PS/np.max(PS),fvtk.cyan,point_radius=0.05,theta=8,phi=8))
    fvtk.add(r,fvtk.point([offset],fvtk.green,point_radius=0.1,theta=8,phi=8))    
    fvtk.add(r,fvtk.axes((1,1,1)))
    lines = fvtk.line([1.5*np.row_stack((needles3d[0],-needles3d[0])), \
                   1.5*np.row_stack((needles3d[1],-needles3d[1]))], \
                   colors=np.row_stack((fvtk.golden,fvtk.aquamarine)),linewidth=10)
    fvtk.add(r,lines)
Пример #7
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)
Пример #8
0
def show_signals(r,Signals,bvecs,offset=0):
    #r=fvtk.ren()
    global CNT
    Bvecs=np.concatenate([bvecs[1:],-bvecs[1:]])
    for (i,S) in enumerate(Signals):
        X=np.dot(np.diag(np.concatenate([50*S,50*S])),Bvecs)
        mX=np.mean(np.sqrt(X[:,0]**2+X[:,1]**2+X[:,2]**2))
        print CNT,mX,np.var(S)
        CNT=CNT+1
        fvtk.add(r,fvtk.point(X+np.array([(i+1)*200,offset,0]),fvtk.green,1,2,6,6))
Пример #9
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)
Пример #10
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)
Пример #11
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)
Пример #12
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)
Пример #13
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)  
Пример #14
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)
Пример #15
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)
Пример #16
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)
Пример #17
0
def simulations_marta(): 

    #gq_tn_calc_save()
    #a_few_phantoms()
    
    #sd=['fibres_2_SNR_100_angle_60_l1_1.4_l2_0.35_l3_0.35_iso_0_diso_00']
    #sd=['fibres_2_SNR_60_angle_60_l1_1.4_l2_0.35_l3_0.35_iso_0_diso_00']
    #sd=['fibres_2_SNR_100_angle_60_l1_1.4_l2_0.35_l3_0.35_iso_1_diso_0.7']
    sd=['fibres_2_SNR_100_angle_90_l1_1.4_l2_0.35_l3_0.35_iso_0_diso_00']
    #sd=['fibres_1_SNR_100_angle_00_l1_1.4_l2_0.35_l3_0.35_iso_0_diso_00']
    #sd=['fibres_2_SNR_20_angle_90_l1_1.4_l2_0.35_l3_0.35_iso_0_diso_00']
    #for simfile in simdata:
    
    np.set_printoptions(2)
    
    dotpow=6
    width=6
    sincpow=2
    sampling_length=1.2
    
    print dotpow,width,sincpow
    print sampling_length
    
    verts,faces=get_sphere('symmetric362')
    
    for simfile in sd:
        
        data=np.loadtxt(simdir+simfile)
        sf=simfile.split('_')        
        b_vals_dirs=np.loadtxt(simdir+'Dir_and_bvals_DSI_marta.txt')
        bvals=b_vals_dirs[:,0]*1000
        gradients=b_vals_dirs[:,1:]
            
        data2=data[::1000,:]   
        
        table={'fibres':sf[1],'snr':sf[3],'angle':sf[5],'l1':sf[7],'l2':sf[9],\
               'l3':sf[11],'iso':sf[13],'diso':sf[15],\
               'data':data2,'bvals':bvals,'gradients':gradients}
        
        print table['data'].shape
        pdi=ProjectiveDiffusivity(table['data'],table['bvals'],table['gradients'],dotpow,width,sincpow)
        gqs=GeneralizedQSampling(table['data'],table['bvals'],table['gradients'],sampling_length)
        ten=Tensor(table['data'],table['bvals'],table['gradients'])
        r=fvtk.ren()
        
        for i in range(10):#range(len(sdi.xa())):
            
            print 'No:',i
            print 'simulation fibres ',table['fibres'], ' snr ',table['snr'],' angle ', table['angle']
            pdiind=pdi.ind()[i]
            gqsind=gqs.ind()[i]
            
            print 'indices',pdiind,gqsind,\
                np.rad2deg(np.arccos(np.dot(verts[pdiind[0]],verts[pdiind[1]]))),\
                np.rad2deg(np.arccos(np.dot(verts[gqsind[0]],verts[gqsind[1]])))
                
            #ten.ind()[i],
            print 'peaks', pdi.xa()[i]*10**3,gqs.qa()[i]
            
            pd=pdi.spherical_diffusivity(table['data'][i])#*10**3
            #print 'pd stat',pd.min(),pd.max(),pd.mean(),pd.std()
            
            #colors=fvtk.colors(sdf,'jet')
            sdfcol=np.interp(pd,[pd.mean()-4*pd.std(),pd.mean()+4*pd.std()],[0,1])
            colors=fvtk.colors(sdfcol,'jet',False)        
            fvtk.add(r,fvtk.point(5*pdi.odf_vertices+np.array([12*i,0,0]),colors,point_radius=.6,theta=10,phi=10))
            
            odf=gqs.odf(table['data'][i])
            colors=fvtk.colors(odf,'jet')
            fvtk.add(r,fvtk.point(5*gqs.odf_vertices+np.array([12*i,-12,0]),colors,point_radius=.6,theta=10,phi=10))
             
        fvtk.show(r)
Пример #18
0
        R2=(np.trace(np.dot(X0,XM.T))**2)/(np.trace(np.dot(X0,X0.T))*np.trace(np.dot(XM,XM.T)))
        print R2   
    fvtk.show(r)
    """
    
if __name__=='__main__':
    
    data,bvals,bvecs=get_data('515_32')
    
    D=[0,-1,1,-2,2,-3,3,-4,4,-5,5,-6,6]
    
    cnt=0
    for a in D:
        for b in D:
            for c in D:
                if a**2+b**2+c**2<=36:
                    cnt+=1
                    
    print cnt

    for (i,g) in enumerate(bvecs[2:]):
        if np.sum((bvecs[1]+g)**2)<0.0001:
            print 2+i,g

    bvecs[0]=np.array([0,0,0])
    qtable=np.vstack((bvals,bvals,bvals)).T * bvecs
    
    r=fvtk.ren()
    fvtk.add(r,fvtk.point(qtable/qtable.max(),fvtk.red,1,0.01,6,6))
    fvtk.show(r)
Пример #19
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)

Пример #20
0
# Extract feature of every streamline.
centers = np.asarray(map(feature.extract, streamlines))

# Color each center of mass according to the cluster they belong to.
rng = np.random.RandomState(42)
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

# Visualization
ren = fvtk.ren()
fvtk.clear(ren)
ren.SetBackground(0, 0, 0)
fvtk.add(ren, fvtk.streamtube(streamlines, fvtk.colors.white, opacity=0.05))
fvtk.add(ren, fvtk.point(centers[:, 0, :], colormap_full, point_radius=0.2))
fvtk.record(ren,
            n_frames=1,
            out_path='center_of_mass_feature.png',
            size=(600, 600))
"""
.. figure:: center_of_mass_feature.png
   :align: center

   **Showing the center of mass of each streamline and colored according to
   the QuickBundles results**.

.. _clustering-examples-MidpointFeature:

Midpoint Feature
================
# Extract feature of every streamline.
centers = np.asarray(map(feature.extract, streamlines))

# Color each center of mass according to the cluster they belong to.
rng = np.random.RandomState(42)
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

# Visualization
ren = fvtk.ren()
fvtk.clear(ren)
ren.SetBackground(0, 0, 0)
fvtk.add(ren, fvtk.streamtube(streamlines, fvtk.colors.white, opacity=0.05))
fvtk.add(ren, fvtk.point(centers[:, 0, :], colormap_full, point_radius=0.2))
fvtk.record(ren, n_frames=1, out_path='center_of_mass_feature.png', size=(600, 600))

"""
.. figure:: center_of_mass_feature.png
   :align: center

   **Showing the center of mass of each streamline and colored according to
   the QuickBundles results**.

.. _clustering-examples-MidpointFeature:

Midpoint Feature
================
**What:** Instances of `MidpointFeature` extract the middle point of a
streamline. If there is an even number of points, the feature will then
Пример #22
0
def codebook_invest():
        
    data,bvals,bvecs=get_data(name='118_32',par=0)
    CBK,STK,FRA,REG=codebook(bvals,bvecs,fractions=True)
    Bvecs=np.concatenate([bvecs[1:],-bvecs[1:]])
    S0,sticks0=simulations_dipy(bvals,bvecs,d=0.0015,S0=100,angles=[(0,0),(90,0),(90,90)],fractions=[0,100,0],snr=None)
    #S0=S0*bvals/1000
    #S0=S0[0]-S0
    #S0=100*S0/S0[0]
    
    SIN=CBK[:33]
    SIN_STK=STK[:33]
    #SIN=S0-SIN
    
    ASIN=np.sum(SIN,axis=1)
    
    print '#####################'
    print ASIN.min(), ASIN.argmin(), SIN_STK[ASIN.argmin()]
    print ASIN.max(), ASIN.argmax(), SIN_STK[ASIN.argmax()]
    print '#####################'
    
    #S0=np.abs(S0-SIN[ASIN.argmax()])
    
    X0=np.dot(np.diag(np.concatenate([S0[1:],S0[1:]])),Bvecs)
    
    #P0=np.fft.ifftn(X0)
    #P0=P0/np.sqrt(np.sum(P0[:,0]**2+P0[:,1]**2+P0[:,2]**2,axis=1))
    
    #S0=CBK[2000]
    #S0=S0[0]-S0
    #X0=np.dot(np.diag(np.concatenate([S0[1:],S0[1:]])),Bvecs)
    S0MF0=match_codebook(S0,CBK,REG,type=0)
    S0MF1=match_codebook(S0,CBK,REG,type=1)
    S0MF2=match_codebook(S0,CBK,REG,type=2)
    S0MF3=match_codebook(S0,CBK,REG,type=3)
    
    #S0M=S0M[0]-S0M
    
    
    X0M=np.dot(np.diag(np.concatenate([S0MF0[1:],S0MF0[1:]])),Bvecs)
    r=fvtk.ren()
    fvtk.add(r,fvtk.point(X0,fvtk.yellow,1,2,16,16))
    draw_needles(r,sticks0,100,2)
    
    
    
    l=[]
    for i in range(len(SIN)):
        S=S0-SIN[i]
        print '>>>>'
        print SIN_STK[i]
        print i, np.sum(S[1:]),np.mean(S[1:]),np.var(S[1:])
        l.append(np.var(S[1:]))
        
        """
        X=np.dot(np.diag(np.concatenate([S[1:],S[1:]])),Bvecs)
        fvtk.add(r,fvtk.point(X+(i+1-14)*np.array([200,0,0]),fvtk.green,1,2,8,8))
        XSIN=np.dot(np.diag(np.concatenate([SIN[i][1:],SIN[i][1:]])),Bvecs)
        fvtk.add(r,fvtk.point(XSIN+np.array([(i+1-14)*200,-200,0]),fvtk.yellow,1,2,8,8))
        
        draw_needles(r,sticks0,100,2,off=(i+1-14)*np.array([200,0,0]))
        """
    
    print np.array(l).argmin()
    print '#=<>'
    print np.argsort(l)
    
    #fvtk.add(r,fvtk.point(0.01*P0,fvtk.green,1,2,16,16))
    #fvtk.add(r,fvtk.point(100*P0,fvtk.green,1,2,16,16))
    #fvtk.add(r,fvtk.point(X0M,fvtk.cyan,1,2,16,16))
    fvtk.show(r)
    
    """
Пример #23
0
from dipy.viz import fvtk
from prepare_phantoms import get_data,codebook,simulations_dipy
    
    
data,bvals,bvecs=get_data(name='118_32',par=0)
CBK,STK,FRA,REG=codebook(bvals,bvecs,fractions=True)
Bvecs=np.concatenate([bvecs[1:],-bvecs[1:]])
#S0,sticks0=simulations_dipy(bvals,bvecs,d=0.0015,S0=100,angles=[(0,0),(45,0),(90,90)],fractions=[100,0,0],snr=None)

SIN=CBK[:33]

ST0=SIN[0]
ST1=SIN[2]
ST2=SIN[4]

XST0=np.dot(np.diag(np.concatenate([ST0[1:],ST0[1:]])),Bvecs)
XST1=np.dot(np.diag(np.concatenate([ST1[1:],ST1[1:]])),Bvecs)
XST2=np.dot(np.diag(np.concatenate([ST2[1:],ST2[1:]])),Bvecs)

r=fvtk.ren()
#fvtk.add(r,fvtk.point(.5*XST0-1.*XST1,fvtk.green,1,2,8,8))
the_vals = XST0*0.5+XST1*0.5
fvtk.add(r,fvtk.point(XST0,fvtk.green,1,2,8,8))
fvtk.add(r,fvtk.point(XST1,fvtk.red,1,2,8,8))
fvtk.add(r,fvtk.point(the_vals,fvtk.yellow,1,2,8,8))
fvtk.add(r,fvtk.point(XST0-XST1,fvtk.cyan,1,2,8,8))
#fvtk.add(r,fvtk.point(-XST0,fvtk.green,1,2,8,8))

fvtk.show(r)

pointA = [0.48412286, 0.97713726, 0.74590314]
pointB = [0.07821987, 0.13495185, 0.7239567]
pointC = [0.79723847, 0.06467979, 0.45524464]
pointD = [0.25058964, 0.83944661, 0.16528851]
pointE = [0.61336066, 0.28185135, 0.94522671]


example_xyz = np.array([pointA, 
                        pointB,
                        pointC,
                        pointD,
                        pointE])


ren = fvtk.ren()
point_actor = fvtk.point(example_xyz, fvtk.colors.blue_light)
fvtk.add(ren, point_actor)

lineAB = np.array([pointA, pointB])
lineBC = np.array([pointB, pointC])
lineCD = np.array([pointC, pointD])
lineCE = np.array([pointC, pointE])

line_color = [0.9, 0.97, 1.0]
line_actor_AB = fvtk.line(lineAB, line_color)
line_actor_BC = fvtk.line(lineBC, line_color)
line_actor_CD = fvtk.line(lineCD, line_color)
line_actor_CE = fvtk.line(lineCE, line_color)


fvtk.add(ren, line_actor_AB)
Пример #25
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)
Пример #26
0
label_coords = np.loadtxt('labels_coords_86.txt')
labelsConnectivity = np.loadtxt('allconnectivityMatrix.txt')

lines_color = [205 / 255.0, 247 / 255.0, 255 / 255.0]
points_color = [2 / 255.0, 128 / 255.0, 232 / 255.0]

lines = []
for columnNumber in range(86):
    for rowNumber in range(86):
        if labelsConnectivity[columnNumber][rowNumber] > 20:
            lines.append([label_coords[columnNumber], label_coords[rowNumber]])

ren = fvtk.ren()
pointActors = fvtk.point(label_coords,
                         points_color,
                         opacity=0.8,
                         point_radius=3)
lineActors = fvtk.line(lines, lines_color, opacity=0.2, linewidth=2)

fvtk.add(ren, pointActors)
fvtk.add(ren, lineActors)

# to explore the data in 3D interactive way
# fvtk.show(ren)

# save figure

fvtk.camera(ren, [-1, -1, 0], [0, 0, 0], viewup=[0, 0, 1])
fvtk.record(ren,
            n_frames=1,
            out_path='brain_network_example.png',
Пример #27
0
def playing_with_diffusivities_and_simulations():

    data,bvals,bvecs=get_data(name='101_32')
    #S=data[:,:,42]
    #drange=np.linspace(0,40,5)
    
    S1,sticks1=simulations_dipy(bvals,bvecs,d=0.0015,S0=200,angles=[(0,0),(90,0)],fractions=[50,50],snr=None)
    S2,sticks2=simulations_dipy(bvals,bvecs,d=0.0015,S0=200,angles=[(0,0),(90,0),(90,90)],fractions=[33,33,33],snr=None)
    
    scale=10**4
    
    ob=-1/bvals[1:]       
    D1=ob*(np.log(S1[1:])-np.log(S1[0]))*scale
    D2=ob*(np.log(S2[1:])-np.log(S2[0]))*scale
    
    Bvecs=np.concatenate([bvecs[1:],-bvecs[1:]])
    SS1=np.concatenate([S1[1:],S1[1:]])
    SS2=np.concatenate([S2[1:],S2[1:]])
    
    DD1=np.concatenate([D1,D1])
    DD2=np.concatenate([D2,D2])
    
    X1=np.dot(np.diag(DD1),Bvecs)
    X2=np.dot(np.diag(DD2),Bvecs)
    
    U,s,V=np.linalg.svd(np.dot(X1.T,X2),full_matrices=True)
    R=np.dot(U,V.T)
    
    print np.round(R,2)
    print np.sum(np.dot(X1,R)-X2,axis=0)
    
    r=fvtk.ren()
    fvtk.add(r,fvtk.point(X1,fvtk.red,1,.5,16,16))
    fvtk.add(r,fvtk.point(X2,fvtk.green,1,.5,16,16))
    fvtk.add(r,fvtk.axes((10,10,10)))
    fvtk.show(r)
    
    U1,s1,V1=np.linalg.svd(np.dot(X1.T,X1),full_matrices=True)
    U2,s2,V2=np.linalg.svd(np.dot(X2.T,X2),full_matrices=True)
    
    u1=U1[:,2]
    u2=U2[:,2]
    
    R2=vec2vecrotmat(u1,u2)
    
    print np.round(R2,2)
    print np.rad2deg(np.arccos(np.dot(u1,u2)))
    
    uu1=np.zeros((2,3))
    uu1[1]=u1
    uu2=np.zeros((2,3))
    uu2[1]=u2
    
    kX1=online_kurtosis(X1)
    kX2=online_kurtosis(X2)
    
    print 's1',s1
    print 's2',s2
    print 'kX1',kX1
    print 'kX2',kX2
    print 'average diffusivity 1',np.mean(np.linalg.norm(X1))
    print 'average diffusivity 2',np.mean(np.linalg.norm(X2))
Пример #28
0
Next, we call `disperse_charges` which will iteratively move the points so that
the electrostatic potential energy is minimized.
"""

hsph_updated, potential = disperse_charges(hsph_initial, 5000)
"""
In ``hsph_updated` we have the updated HemiSphere with the points nicely 
distributed on the hemisphere. Let's visualize them.
"""

from dipy.viz import fvtk

ren = fvtk.ren()
ren.SetBackground(1, 1, 1)
fvtk.add(ren,
         fvtk.point(hsph_initial.vertices, fvtk.colors.red, point_radius=0.05))
fvtk.add(
    ren, fvtk.point(hsph_updated.vertices,
                    fvtk.colors.green,
                    point_radius=0.05))

print('Saving illustration as initial_vs_updated.png')
fvtk.record(ren, out_path='initial_vs_updated.png', size=(300, 300))
"""
.. figure:: initial_vs_updated.png
   :align: center

   **Example of electrostatic repulsion of red points which become green points**.

We can also create a sphere from the hemisphere and show it in the following way.
"""
Пример #29
0
import numpy as np
from dipy.viz import fvtk
from prepare_phantoms import get_data,codebook,simulations_dipy,draw_needles

data,bvals,bvecs=get_data(name='118_32',par=0)
CBK,STK,FRA,REG=codebook(bvals,bvecs,fractions=True)
Bvecs=np.concatenate([bvecs[1:],-bvecs[1:]])

S0,sticks0=simulations_dipy(bvals,bvecs,d=0.0015,S0=100,angles=[(0,0),(90,0),(90,90)],fractions=[100,0,0],snr=None)
S1,sticks1=simulations_dipy(bvals,bvecs,d=0.0015,S0=100,angles=[(0,0),(90,0),(90,90)],fractions=[50,50,0],snr=None)
S2,sticks2=simulations_dipy(bvals,bvecs,d=0.0015,S0=100,angles=[(0,0),(45,0),(90,90)],fractions=[50,50,0],snr=None)

SIN=CBK[:33]

r=fvtk.ren()

X0=np.dot(np.diag(np.concatenate([S0[1:],S0[1:]])),Bvecs)
fvtk.add(r,fvtk.point(X0,fvtk.red,1,2,8,8))
X1=np.dot(np.diag(np.concatenate([S1[1:],S1[1:]])),Bvecs)
fvtk.add(r,fvtk.point(X1+np.array([200,0,0]),fvtk.green,1,2,8,8))
X2=np.dot(np.diag(np.concatenate([S2[1:],S2[1:]])),Bvecs)
fvtk.add(r,fvtk.point(X2+np.array([400,0,0]),fvtk.blue,1,2,8,8))


for i in range(0,10):#len(SIN)):
        S=SIN[i]        
        X=np.dot(np.diag(np.concatenate([S[1:],S[1:]])),Bvecs)
        fvtk.add(r,fvtk.point(X+np.array([i*200,-200,0]),fvtk.green,1,2,8,8))
        #draw_needles(r,sticks0,100,2,off=(i+1)*np.array([200,0,0]))
fvtk.show(r)
Пример #30
0
def show_graph_values(rt, bundle, show_final=True):

    #r.add(streamlines_actor)
    #actor_slicer = actor.slicer(FA, interpolation='nearest')
    #r.add(actor_slicer)
    if not show_final:
        window.show(r)

    colors2 = np.array((0, 1, 1))
    color3 = np.array((1, 1, 1))
    colors = np.array((1, 0, 0))
    colors1 = np.array((0, 1, 0))
    goal_point = np.array([35, 67, 41])
    #goal_point = np.array([37,53,59])
    starting_point = np.array([53, 65, 40])
    #starting_point = np.array([42,55,20])
    goal_point = goal_point[None, :]
    #r.add(point_actor1)
    #r.AddActor(point_actor1)
    #r.add(point_actor2)
    #r.AddActor(point_actor2)
    r = window.Renderer()
    r.add(actor.line(bundle))

    #def time_event(obj, ev):
    #time.sleep(20)
    for i in range(len(rt.seeds_nodes_graph)):
        #print(i)
        #r.clear()
        #node_actor = actor.streamtube([nodes[100]])
        if len(rt.seeds_nodes_graph[i].graph.shape) == 1:
            #colors = np.random.rand(1,3)
            colors = np.array((1, 1, 1))
            if np.array(rt.seeds_nodes_graph[i].value) > 0:
                colors = np.array(
                    (1, 1 - rt.seeds_nodes_graph[i].value[0] / 100,
                     1 - rt.seeds_nodes_graph[i].value[0] / 100))

        else:
            max_value = np.abs(rt.seeds_nodes_graph[i].value.max())
            ss = np.where(rt.seeds_nodes_graph[i].value < 0)[0]
            colors = np.ones((rt.seeds_nodes_graph[i].graph.shape[0], 3))
            #colors[:,2] = 1 - seeds_nodes_graph[i].value/max_value
            #colors[:,1] = 1 - seeds_nodes_graph[i].value/max_value
            colors[ss, 2] = 1
            colors[ss, 1] = 1

            sss = np.where(rt.seeds_nodes_graph[i].value > 0)[0]
            colors[sss, 1] = 0
            colors[sss, 2] = 0

            #if rt.seeds_nodes_graph[i].value.max()>0:
            #colors = np.zeros((seeds_nodes_graph[i].graph.shape[0],3))
            #colors[:,0] = 1
            #streamlines_sub.append(rt.seeds_nodes_graph[i].graph)

        if len(rt.seeds_nodes_graph[i].graph.shape) == 1:
            point_actor = fvtk.point(rt.seeds_nodes_graph[i].graph[None, :],
                                     colors,
                                     point_radius=0.3)
        else:
            point_actor = fvtk.point(rt.seeds_nodes_graph[i].graph,
                                     colors,
                                     point_radius=0.3)
        r.add(point_actor)
        #r.AddActor(point_actor)
        #iren = obj
        #iren.GetRenderWindow().Render()
    if not show_final:
        window.show(r)
    #peak_slicer = actor.line(streamlines_sub)
    #r.add(peak_slicer)
    if show_final:
        window.show(r)
label_coords = np.loadtxt('labels_coords_86.txt')
labelsConnectivity = np.loadtxt('allconnectivityMatrix.txt')

lines_color = [205/255.0,247/255.0,255/255.0]
points_color = [2/255.0, 128/255.0, 232/255.0]

lines = []
for columnNumber in range(86):
    for rowNumber in range(86):
        if labelsConnectivity[columnNumber][rowNumber] > 20 :
            lines.append([label_coords[columnNumber],label_coords[rowNumber]])


ren = fvtk.ren()
pointActors = fvtk.point(label_coords, points_color, opacity=0.8, point_radius=3)
lineActors = fvtk.line(lines, lines_color, opacity=0.2, linewidth=2)


fvtk.add(ren, pointActors)
fvtk.add(ren, lineActors)


# to explore the data in 3D interactive way
# fvtk.show(ren)

# save figure

fvtk.camera(ren, [-1, -1, 0], [0, 0, 0], viewup=[0, 0, 1])
fvtk.record(ren, n_frames=1, 
            out_path='brain_network_example.png',
Пример #32
0
Next, we call `disperse_charges` which will iteratively move the points so that
the electrostatic potential energy is minimized.
"""

hsph_updated, potential = disperse_charges(hsph_initial, 5000)

"""
In ``hsph_updated` we have the updated HemiSphere with the points nicely 
distributed on the hemisphere. Let's visualize them.
"""

from dipy.viz import fvtk

ren = fvtk.ren()
ren.SetBackground(1, 1, 1)
fvtk.add(ren, fvtk.point(hsph_initial.vertices, fvtk.colors.red, point_radius=0.05))
fvtk.add(ren, fvtk.point(hsph_updated.vertices, fvtk.colors.green, point_radius=0.05))

print("Saving illustration as initial_vs_updated.png")
fvtk.record(ren, out_path="initial_vs_updated.png", size=(300, 300))

"""
.. figure:: initial_vs_updated.png
   :align: center

   **Example of electrostatic repulsion of red points which become green points**.

We can also create a sphere from the hemisphere and show it in the following way.
"""

sph = Sphere(xyz=np.vstack((hsph_updated.vertices, -hsph_updated.vertices)))
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)
Пример #34
0
def test():

    # img=nib.load('/home/eg309/Data/project01_dsi/connectome_0001/tp1/RAWDATA/OUT/mr000001.nii.gz')
    btable = np.loadtxt(get_data("dsi515btable"))
    # volume size
    sz = 16
    # shifting
    origin = 8
    # hanning width
    filter_width = 32.0
    # number of signal sampling points
    n = 515
    # odf radius
    radius = np.arange(2.1, 6, 0.2)
    # create q-table
    bv = btable[:, 0]
    bmin = np.sort(bv)[1]
    bv = np.sqrt(bv / bmin)
    qtable = np.vstack((bv, bv, bv)).T * btable[:, 1:]
    qtable = np.floor(qtable + 0.5)
    # copy bvals and bvecs
    bvals = btable[:, 0]
    bvecs = btable[:, 1:]
    # S=img.get_data()[38,50,20]#[96/2,96/2,20]
    S, stics = SticksAndBall(
        bvals, bvecs, d=0.0015, S0=100, angles=[(0, 0), (60, 0), (90, 90)], fractions=[0, 0, 0], snr=None
    )

    S2 = S.copy()
    S2 = S2.reshape(1, len(S))
    dn = DiffusionNabla(S2, bvals, bvecs, auto=False)
    pR = dn.equators
    odf = dn.odf(S)
    # Xs=dn.precompute_interp_coords()
    peaks, inds = peak_finding(odf.astype("f8"), dn.odf_faces.astype("uint16"))
    print peaks
    print peaks / peaks.min()
    # print dn.PK
    dn.fit()
    print dn.PK

    # """
    ren = fvtk.ren()
    colors = fvtk.colors(odf, "jet")
    fvtk.add(ren, fvtk.point(dn.odf_vertices, colors, point_radius=0.05, theta=8, phi=8))
    fvtk.show(ren)
    # """

    stop

    # ds=DiffusionSpectrum(S2,bvals,bvecs)
    # tpr=ds.pdf(S)
    # todf=ds.odf(tpr)

    """
    #show projected signal
    Bvecs=np.concatenate([bvecs[1:],-bvecs[1:]])
    X0=np.dot(np.diag(np.concatenate([S[1:],S[1:]])),Bvecs)    
    ren=fvtk.ren()
    fvtk.add(ren,fvtk.point(X0,fvtk.yellow,1,2,16,16))    
    fvtk.show(ren)
    """
    # qtable=5*matrix[:,1:]

    # calculate radius for the hanning filter
    r = np.sqrt(qtable[:, 0] ** 2 + qtable[:, 1] ** 2 + qtable[:, 2] ** 2)

    # setting hanning filter width and hanning
    hanning = 0.5 * np.cos(2 * np.pi * r / filter_width)

    # center and index in q space volume
    q = qtable + origin
    q = q.astype("i8")

    # apply the hanning filter
    values = S * hanning

    """
    #plot q-table
    ren=fvtk.ren()
    colors=fvtk.colors(values,'jet')
    fvtk.add(ren,fvtk.point(q,colors,1,0.1,6,6))
    fvtk.show(ren)
    """

    # create the signal volume
    Sq = np.zeros((sz, sz, sz))
    for i in range(n):
        Sq[q[i][0], q[i][1], q[i][2]] += values[i]

    # apply fourier transform
    Pr = fftshift(np.abs(np.real(fftn(fftshift(Sq), (sz, sz, sz)))))

    # """
    ren = fvtk.ren()
    vol = fvtk.volume(Pr)
    fvtk.add(ren, vol)
    fvtk.show(ren)
    # """

    """
    from enthought.mayavi import mlab
    mlab.pipeline.volume(mlab.pipeline.scalar_field(Sq))
    mlab.show()
    """

    # vertices, edges, faces  = create_unit_sphere(5)
    vertices, faces = sphere_vf_from("symmetric362")
    odf = np.zeros(len(vertices))

    for m in range(len(vertices)):

        xi = origin + radius * vertices[m, 0]
        yi = origin + radius * vertices[m, 1]
        zi = origin + radius * vertices[m, 2]
        PrI = map_coordinates(Pr, np.vstack((xi, yi, zi)), order=1)
        for i in range(len(radius)):
            odf[m] = odf[m] + PrI[i] * radius[i] ** 2

    """
    ren=fvtk.ren()
    colors=fvtk.colors(odf,'jet')
    fvtk.add(ren,fvtk.point(vertices,colors,point_radius=.05,theta=8,phi=8))
    fvtk.show(ren)
    """

    """
    #Pr[Pr<500]=0    
    ren=fvtk.ren()
    #ren.SetBackground(1,1,1)
    fvtk.add(ren,fvtk.volume(Pr))
    fvtk.show(ren)
    """

    peaks, inds = peak_finding(odf.astype("f8"), faces.astype("uint16"))

    Eq = np.zeros((sz, sz, sz))
    for i in range(n):
        Eq[q[i][0], q[i][1], q[i][2]] += S[i] / S[0]

    LEq = laplace(Eq)

    # Pr[Pr<500]=0
    ren = fvtk.ren()
    # ren.SetBackground(1,1,1)
    fvtk.add(ren, fvtk.volume(Eq))
    fvtk.show(ren)

    phis = np.linspace(0, 2 * np.pi, 100)

    planars = []
    for phi in phis:
        planars.append(sphere2cart(1, np.pi / 2, phi))
    planars = np.array(planars)

    planarsR = []
    for v in vertices:
        R = vec2vec_rotmat(np.array([0, 0, 1]), v)
        planarsR.append(np.dot(R, planars.T).T)

    """
    ren=fvtk.ren()
    fvtk.add(ren,fvtk.point(planarsR[0],fvtk.green,1,0.1,8,8))
    fvtk.add(ren,fvtk.point(2*planarsR[1],fvtk.red,1,0.1,8,8))
    fvtk.show(ren)
    """

    azimsums = []
    for disk in planarsR:
        diskshift = 4 * disk + origin
        # Sq0=map_coordinates(Sq,diskshift.T,order=1)
        # azimsums.append(np.sum(Sq0))
        # Eq0=map_coordinates(Eq,diskshift.T,order=1)
        # azimsums.append(np.sum(Eq0))
        LEq0 = map_coordinates(LEq, diskshift.T, order=1)
        azimsums.append(np.sum(LEq0))

    azimsums = np.array(azimsums)

    # """
    ren = fvtk.ren()
    colors = fvtk.colors(azimsums, "jet")
    fvtk.add(ren, fvtk.point(vertices, colors, point_radius=0.05, theta=8, phi=8))
    fvtk.show(ren)
    # """

    # for p in planarsR[0]:
    """
Пример #35
0
    def show_graph_values(self,
                          show_final=True,
                          show_node=True,
                          show_start=True,
                          show_node_general=True):

        #streamlines_actor = actor.line(streamlines)
        time_count = 0
        renderwindow = vtk.vtkRenderWindow()
        renderwindow.SetSize(1000, 1000)
        r = window.Renderer()
        #r = vtk.vtkRenderer()
        #r.clear()
        r.background((1, 1, 1))
        #r.SetBackground(1,1,1)
        renderwindow.AddRenderer(r)
        renderwindowInteractor = vtkRenderWindowInteractor()
        #r = vtk.vtkRenderWindowInteractor()
        renderwindowInteractor.SetRenderWindow(renderwindow)
        camera = vtkCamera()
        camera.SetPosition(-50, -50, -50)
        camera.SetFocalPoint(0, 0, 0)
        #r.SetActiveCamera(camera)
        streamlines_sub = []
        #r.add(streamlines_actor)
        #actor_slicer = actor.slicer(FA, interpolation='nearest')
        #r.add(actor_slicer)
        if not show_final:
            window.show(r)

        colors2 = np.array((0, 1, 1))
        color3 = np.array((1, 1, 1))
        colors = np.array((1, 0, 0))
        colors1 = np.array((0, 1, 0))
        #goal_point = np.array([35,67,41])
        #goal_point = np.array([37,53,59])
        #starting_point = np.array([53,65,40])
        #starting_point = np.array([42,55,20])
        #goal_point = goal_point[None,:]
        #point_actor2 = fvtk.point(self.seed[None,:],colors2, point_radius=0.5)#point_radius=self.start_radius)
        point_actor2 = fvtk.point(self.start_points, colors2, point_radius=0.5)
        #point_actor1 = fvtk.point(self.goal_points[None,:],colors1, point_radius=self.goal_radius)
        point_actor1 = fvtk.point(self.goal_points, colors1, point_radius=0.5)
        if show_start:
            r.add(point_actor1)
            #r.AddActor(point_actor1)
            r.add(point_actor2)
        #r.AddActor(point_actor2)

        #def time_event(obj, ev):
        #time.sleep(20)
        """Alter
        """
        if len(self.exp_graph_general.shape) == 1:
            #colors = np.random.rand(1,3)
            colors = np.array((1, 1, 1))
            if np.array(self.exp_value_general) > 0:
                colors = np.array((1, 1 - self.exp_value_general[0] / 100,
                                   1 - self.exp_value_general[0] / 100))

        else:
            max_value = np.abs(self.exp_value_general.max())
            ss = np.where(self.exp_value_general < 0)[0]
            colors = np.ones((self.exp_graph_general.shape[0], 3))
            #colors[:,2] = 1 - seeds_nodes_graph[i].value/max_value
            #colors[:,1] = 1 - seeds_nodes_graph[i].value/max_value
            colors[ss, 2] = 1
            colors[ss, 1] = 1

            sss = np.where(self.exp_value_general > 0)[0]
            colors[sss, 1] = 0
            colors[sss, 2] = 0

        if len(self.exp_graph_general.shape) == 1:
            point_actor = fvtk.point(self.exp_graph_general[None, :],
                                     colors,
                                     point_radius=0.3)
        else:
            point_actor = fvtk.point(self.exp_graph_general,
                                     colors,
                                     point_radius=0.3)
        if show_node_general:
            r.add(point_actor)

        for i in range(len(self.seeds_nodes_graph)):
            #print(i)
            #r.clear()
            #node_actor = actor.streamtube([nodes[100]])
            if len(self.seeds_nodes_graph[i].graph.shape) == 1:
                #colors = np.random.rand(1,3)
                colors = np.array((1, 1, 1))
                if np.array(self.seeds_nodes_graph[i].value) > 0:
                    colors = np.array(
                        (1, 1 - self.seeds_nodes_graph[i].value[0] / 100,
                         1 - self.seeds_nodes_graph[i].value[0] / 100))

            else:
                max_value = np.abs(self.seeds_nodes_graph[i].value.max())
                ss = np.where(self.seeds_nodes_graph[i].value < 0)[0]
                colors = np.ones((self.seeds_nodes_graph[i].graph.shape[0], 3))
                #colors[:,2] = 1 - seeds_nodes_graph[i].value/max_value
                #colors[:,1] = 1 - seeds_nodes_graph[i].value/max_value
                colors[ss, 2] = 1
                colors[ss, 1] = 1

                sss = np.where(self.seeds_nodes_graph[i].value > 0)[0]
                colors[sss, 1] = 0
                colors[sss, 2] = 0

                if self.seeds_nodes_graph[i].value.max() > 0:
                    #colors = np.zeros((seeds_nodes_graph[i].graph.shape[0],3))
                    #colors[:,0] = 1
                    streamlines_sub.append(self.seeds_nodes_graph[i].graph)

            if len(self.seeds_nodes_graph[i].graph.shape) == 1:
                point_actor = fvtk.point(
                    self.seeds_nodes_graph[i].graph[None, :],
                    colors,
                    point_radius=0.3)
            else:
                point_actor = fvtk.point(self.seeds_nodes_graph[i].graph,
                                         colors,
                                         point_radius=0.3)
            if show_node:
                r.add(point_actor)
            #r.AddActor(point_actor)
            #iren = obj
            #iren.GetRenderWindow().Render()
        if not show_final:
            window.show(r)
        if not len(self.streamlines) == 0:
            peak_slicer = actor.line(self.streamlines)
            r.add(peak_slicer)
        if show_final:
            window.show(r)
Пример #36
0
import dipy.viz.fvtk as fvtk
import numpy as np

pointA = [0.48412286, 0.97713726, 0.74590314]
pointB = [0.07821987, 0.13495185, 0.7239567]
pointC = [0.79723847, 0.06467979, 0.45524464]
pointD = [0.25058964, 0.83944661, 0.16528851]
pointE = [0.61336066, 0.28185135, 0.94522671]

example_xyz = np.array([pointA, pointB, pointC, pointD, pointE])

ren = fvtk.ren()
point_actor = fvtk.point(example_xyz, fvtk.colors.blue_light)
fvtk.add(ren, point_actor)

lineAB = np.array([pointA, pointB])
lineBC = np.array([pointB, pointC])
lineCD = np.array([pointC, pointD])
lineCE = np.array([pointC, pointE])

line_color = [0.9, 0.97, 1.0]
line_actor_AB = fvtk.line(lineAB, line_color)
line_actor_BC = fvtk.line(lineBC, line_color)
line_actor_CD = fvtk.line(lineCD, line_color)
line_actor_CE = fvtk.line(lineCE, line_color)

fvtk.add(ren, line_actor_AB)
fvtk.add(ren, line_actor_BC)
fvtk.add(ren, line_actor_CD)
fvtk.add(ren, line_actor_CE)