Exemple #1
0
def plot_sln_mayavi(x, y, mesh, sln_values, colorbar=False):
    """
    Plot a solution using mayavi.

    Example:

    >>> from numpy import array
    >>> from femhub.plot import plot_sln_mayavi
    >>> f = plot_sln_mayavi([0, 1, 1], [0, 0, 1], [1, 2, 3])
    >>> f.savefig("a.png")

    """
    from enthought.mayavi import mlab
    #mlab.options.offscreen = True
    mlab.clf()
    #mlab.options.show_scalar_bar = False
    z = [0] * len(x)
    mlab.triangular_mesh(x, y, z, mesh, scalars=sln_values)
    engine = mlab.get_engine()
    image = engine.current_scene
    image.scene.background = (1.0, 1.0, 1.0)
    image.scene.foreground = (0.0, 0.0, 0.0)
    if colorbar:
        mlab.colorbar(orientation="vertical")
    mlab.view(0, 0)
    return mlab
Exemple #2
0
def plotsln(mesh, z=None, sln=None, colorbar=False, view=(0,0),
        filename="a.png"):
    """
    Plot a solution for the mesh editor in the online lab.
    """
    x = [n[0] for n in mesh.nodes]
    y = [n[1] for n in mesh.nodes]
    if z == None:
        try:
            z = [n[2] for n in mesh.nodes]
        except IndexError:
            z = [0]*len(y)
    from enthought.mayavi import mlab
    mlab.options.offscreen = True
    mlab.clf()
    #mlab.options.show_scalar_bar = False
    mlab.triangular_mesh(x, y, z, mesh.elems, scalars=sln)
    engine = mlab.get_engine()
    image = engine.current_scene
    image.scene.background = (1.0, 1.0, 1.0)
    image.scene.foreground = (0.0, 0.0, 0.0)
    if colorbar:
        mlab.colorbar(orientation="vertical")
    if view:
        mlab.view(view[0], view[1])
    mlab.savefig(filename)
Exemple #3
0
def plot_surface(s):
    x, y, z, t = gts.get_coords_and_face_indices(s, True)
    mlab.triangular_mesh(x, y, z, t, color=(0.8, 0.8, 0.8))
    mlab.triangular_mesh(x,
                         y,
                         z,
                         t,
                         color=(0, 0, 1),
                         representation='fancymesh',
                         tube_radius=.001,
                         scale_factor=0.001)
Exemple #4
0
 def plotbdy(self, fig, id, opac = 0.9):
     idset = set(map(tuple, self.boundaries[id]))
     bdyts = []
     for t in self.triangles:
         if idset.issuperset(set(t)): bdyts.append(t)
     for q in self.quads:
         if idset.issuperset(set(q)): 
             bdyts.append(q[[0,1,3]])
             bdyts.append(q[[2,1,3]])
         
     x,y,z = zip(*self.getPoints(np.array(bdyts).flatten()))
     emm.triangular_mesh(x,y,z, np.arange(len(bdyts)*3).reshape(-1,3), representation = 'surface', figure = fig, color=(0.5,0.2,0.5), opacity = opac, line_width=0.5)
Exemple #5
0
def plot_retino_image(mesh_path, name, tf=None, tex=None, curv=None, mask=None,
                     vmin=0, vmax=0):
    """Custom function to plot mesh in the case of retinotopic mapping  

    Parameters
    ----------
    mesh_path: string, path of the mesh to plot
    name: string, object identifier
    tf: (4, 4)  array
        affine transformation that has to be applied to the mesh
    tex: array of shape (mes.n_vertices),
         texture to plot on the surface
    curv: array of shape (mes.n_vertices),
          curvature texture to plot on the surface
    mask: array of shape (mes.n_vertices),
          A mask for functional regions of interest
    vmin, vmax: bounds for color clipping
    """
    vertices, triangles =  mesh_arrays(mesh_path)
    af_coord = np.hstack((vertices, np.ones((vertices.shape[0], 1))))
    if tf is not None:
        af_coord = np.dot(af_coord, tf.T)
    
    vertices = af_coord[:, :3]
    x, y, z = vertices.T

    # it is expected that the curvature takes values between 0 and 1
    if curv is not None:
        cmin = 2 * curv.min() - curv.max()
        cmax = 2 * curv.max() - curv.min()
        mlab.triangular_mesh(x, y, z, triangles, transparent=False, opacity=1.,
                             name=name, scalars=curv, colormap="bone",
                             vmin=cmin, vmax=cmax)
    else:
        mlab.triangular_mesh(x, y, z, triangles, transparent=False, opacity=1.,
                             name=name)
    if tex is not None:
        if mask is not None:
            tex[mask == 0] = vmin - 1

        func_mesh = mlab.pipeline.triangular_mesh_source(x, y, z,
                                                  triangles,
                                                  scalars=tex)
        thresh = mlab.pipeline.threshold(func_mesh, low=vmin)
        mlab.pipeline.surface(thresh, colormap="jet", vmin=vmin,
                              vmax=vmax, transparent=True,
                              opacity=.8)
        mlab.scalarbar(thresh)
 def CreateReducedModel(self,bandwidth=0.04,bandthresh=0.01,neighthresh=0.01,showdata=False,savefile=None):
     self.measurements,indices = self.Prune(self.rawmeasurements,100,neighthresh**2,1)
     uniformpoints,dists,pointscale = self.UniformlySampleSpace(bandwidth,bandthresh)
     if showdata:
         from enthought.mayavi import mlab
         mlab.figure(1,fgcolor=(0,0,0), bgcolor=(1,1,1))
         src = mlab.pipeline.scalar_field(dists)
         mlab.pipeline.iso_surface(src,contours=[0.01],opacity=0.1)
         mlab.pipeline.volume(mlab.pipeline.scalar_field(dists*500))
         v = pointscale[0]*self.trimesh.vertices+pointscale[1]
         mlab.triangular_mesh(v[:,0],v[:,1],v[:,2],self.trimesh.indices,color=(0,0,0.5))
     if savefile is None:
         savefile = self.getfilename()
     print 'saving measurements to %s'%savefile
     mkdir_recursive(os.path.split(savefile)[0])
     savetxt(savefile,uniformpoints,'%f')
Exemple #7
0
def plot_sln_mayavi(sln, notebook=False):
    """
    Plots the Solution() instance sln using Linearizer() and matplotlib.

    Currently only a very simple version is implemented, that takes the
    vertices from linearizer and interpolates them. More sophisticated version
    should take the triangles.
    """
    lin = Linearizer()
    lin.process_solution(sln)
    vert = lin.get_vertices()
    triangles = lin.get_triangles()
    from numpy import zeros
    from enthought.mayavi import mlab
    x = vert[:, 0]
    y = vert[:, 1]
    z = zeros(len(y))
    t = vert[:, 2]
    if notebook:
        # the off screen rendering properly works only with VTK-5.2 or above:
        mlab.options.offscreen = True
    s = mlab.triangular_mesh(x, y, z, triangles, scalars=t)
    mlab.view(0, 0)

    # Below is a code that does exactly what the "View along the +Z axis"
    # button does:
    #scene = mlab.get_engine().current_scene.scene
    #scene.camera.focal_point = [0, 0, 0]
    #scene.camera.position = [0, 0, 1]
    #scene.camera.view_up = [0, 1, 0]
    #scene.renderer.reset_camera()
    #scene.render()
    # the above looks ok, but there is still quite a large margin, so we prefer
    # to just call .view(0, 0), which seems to be working fine.
    return s
Exemple #8
0
    def plot(self, **kwarg):
        """Plot mesh with Mayavi
        """
        from enthought.mayavi import mlab

        f = mlab.triangular_mesh(self.points[:, 0], self.points[:, 1], self.points[:, 2], self.faces, **kwarg)
        return f
Exemple #9
0
def show_blobs(blobs, v, faces,fa_slice=None,colormap='jet'):
    """Mayavi gets really slow when triangular_mesh is called too many times
    so this function stacks blobs and calls triangular_mesh once
    """
 
    print blobs.shape
    xcen = blobs.shape[0]/2.
    ycen = blobs.shape[1]/2.
    zcen = blobs.shape[2]/2.
    faces = np.asarray(faces, 'int')
    xx = []
    yy = []
    zz = []
    count = 0
    ff = []
    mm = []
    for ii in xrange(blobs.shape[0]):
        for jj in xrange(blobs.shape[1]):
            for kk in xrange(blobs.shape[2]):
                m = blobs[ii,jj,kk]
                #m /= (2.2*m.max())
                #m /= (2.2*abs(m).max())
                #m /= (2.2*1.)
                #m[m<.4*abs(m).max()]=0
                
                x, y, z = v.T*m/2.2
                x += ii - xcen
                y += jj - ycen
                z += kk - zcen
                ff.append(count+faces)
                count += len(x)
                xx.append(x)
                yy.append(y)
                zz.append(z)
                mm.append(m)
    ff = np.concatenate(ff)
    xx = np.concatenate(xx)
    yy = np.concatenate(yy)
    zz = np.concatenate(zz)
    mm = np.concatenate(mm)
    mlab.triangular_mesh(xx, yy, zz, ff, scalars=mm, colormap=colormap)
    if fa_slice!=None:        
        mlab.imshow(fa_slice, colormap='gray', interpolate=False)
    mlab.colorbar()
    mlab.show()
Exemple #10
0
def add_xy_plane():
    z = [0, 0, 0, 0]
    x = [-1, -1, 1, 1]
    y = [-1, 1, 1, -1]
    tris = [(0, 3, 2), (2, 1, 0)]
    mesh = mlab.triangular_mesh(x, y, z,
            tris,
            color=(0, 0, 1),
            opacity=g_plane_opacity)
Exemple #11
0
def plot_mesh(mesh, name, tf=None, tex=None):
    """ old version -- probably deprecated
    """
    vertices, triangles =  mesh_arrays(mesh)
    af_coord = np.hstack((vertices, np.ones((vertices.shape[0], 1))))
    if tf is not None:
        af_coord = np.dot(af_coord, tf.T)
    
    vertices = af_coord[:, :3]
    x, y, z = vertices.T
    # show with mayavi

    if tex is None:
        mlab.triangular_mesh(x, y, z, triangles, transparent=False, opacity=1.,
                             name=name, color=(0.5, 0.5, 0.))
    else:
        mlab.triangular_mesh(x, y, z, triangles, transparent=False, opacity=1.,
                             name=name, scalars=tex)
Exemple #12
0
def color_patches(vertices, faces, heights, colors):
    """Mayavi gets really slow when triangular_mesh is called too many times
    so this function stacks blobs and calls triangular_mesh once
    """

    print colors.shape
    xcen = colors.shape[0] / 2.0
    ycen = colors.shape[1] / 2.0
    zcen = colors.shape[2] / 2.0
    faces = np.asarray(faces, "int")
    xx = []
    yy = []
    zz = []
    count = 0
    ff = []
    cc = []
    for ii in xrange(colors.shape[0]):
        for jj in xrange(colors.shape[1]):
            for kk in xrange(colors.shape[2]):
                c = colors[ii, jj, kk]
                # m[m<.4*abs(m).max()]=0
                m = heights[ii, jj, kk]

                print "vertices", vertices.shape
                print "m", m.shape

                x, y, z = vertices.T * m
                x += ii - xcen
                y += jj - ycen
                z += kk - zcen
                ff.append(count + faces)
                count += len(x)
                xx.append(x)
                yy.append(y)
                zz.append(z)
                cc.append(c)
    ff = np.concatenate(ff)
    xx = np.concatenate(xx)
    yy = np.concatenate(yy)
    zz = np.concatenate(zz)
    cc = np.concatenate(cc)
    mlab.triangular_mesh(xx, yy, zz, ff, scalars=cc)
    mlab.show()
Exemple #13
0
def add_xy_plane():
    z = [0, 0, 0, 0]
    x = [-1, -1, 1, 1]
    y = [-1, 1, 1, -1]
    tris = [(0, 3, 2), (2, 1, 0)]
    mesh = mlab.triangular_mesh(x,
                                y,
                                z,
                                tris,
                                color=(0, 0, 1),
                                opacity=g_plane_opacity)
def show_blobs(blobs, v, faces):
    """Mayavi gets really slow when triangular_mesh is called too many times
    sot this function stacks blobs and calls triangular_mesh once
    """

    blobs
    xcen = blobs.shape[0] / 2
    ycen = blobs.shape[1] / 2
    zcen = blobs.shape[2] / 2
    faces = asarray(faces, 'int')
    xx = []
    yy = []
    zz = []
    count = 0
    ff = []
    mm = []
    for ii in xrange(blobs.shape[0]):
        for jj in xrange(blobs.shape[1]):
            for kk in xrange(blobs.shape[2]):
                m = blobs[ii, jj, kk]
                m /= (2.2 * abs(m).max())
                x, y, z = v.T * m
                x += ii - xcen
                y += jj - ycen
                z += kk - zcen
                ff.append(count + faces)
                count += len(x)
                xx.append(x)
                yy.append(y)
                zz.append(z)
                mm.append(m)
    ff = concatenate(ff)
    xx = concatenate(xx)
    yy = concatenate(yy)
    zz = concatenate(zz)
    mm = concatenate(mm)

    mlab.triangular_mesh(xx, yy, zz, ff, scalars=mm)
Exemple #15
0
 def doit():
     global s
     global iter
     if iter == 0:
         print "plotting the triangular mesh..."
         s = mlab.triangular_mesh(x, y, z, triangles, scalars=t)
         print "  done."
         print "adjusting view..."
         mlab.view(0, 0)
         print "  done."
     else:
         print "changing the source..."
         # This doesn't work due to a bug in mayavi/VTK:
         # http://github.com/certik/mhd-hermes/issues#issue/1
         #s.mlab_source.reset(x=x, y=y, z=z, triangles=triangles, scalars=t)
         # so until this is fixed, let's call triangular_mesh and delete the
         # old mesh (this is slow but works):
         scene = mlab.gcf().scene
         scene.disable_render = True
         s = mlab.triangular_mesh(x, y, z, triangles, scalars=t)
         mlab.get_engine().scenes[0].children[:1] = []
         scene.disable_render = False
         print "  done."
     iter += 1
Exemple #16
0
 def doit():
     global s
     global iter
     if iter == 0:
         print "plotting the triangular mesh..."
         s = mlab.triangular_mesh(x, y, z, triangles, scalars=t)
         print "  done."
         print "adjusting view..."
         mlab.view(0, 0)
         print "  done."
     else:
         print "changing the source..."
         # This doesn't work due to a bug in mayavi/VTK:
         # http://github.com/certik/mhd-hermes/issues#issue/1
         #s.mlab_source.reset(x=x, y=y, z=z, triangles=triangles, scalars=t)
         # so until this is fixed, let's call triangular_mesh and delete the
         # old mesh (this is slow but works):
         scene = mlab.gcf().scene
         scene.disable_render = True
         s = mlab.triangular_mesh(x, y, z, triangles, scalars=t)
         mlab.get_engine().scenes[0].children[:1] = []
         scene.disable_render = False
         print "  done."
     iter += 1
Exemple #17
0
    def display(self):
        """ Display Nucleus in Mayavi """
        # Create and display a triangular mesh
        from enthought.mayavi.mlab import triangular_mesh
        f = mlab.figure(figure=mlab.gcf(),
                        bgcolor=(0,0,0),
                        size=(800,600))
        self.mlab_mesh = triangular_mesh(self.pts[:, 0],
                                         self.pts[:, 1],
                                         self.pts[:, 2],
                                         self.tris,
                                         color=self.color,
                                         name=self.name)

        # Visual Tweaks
        #self.mlab_mesh.actor.property.backface_culling = True
        self.mlab_mesh.parent.parent.filter.splitting = False
Exemple #18
0
    def test_triangular_mesh_reset(self):
        """ When reseting the triangular mesh (ie polydata), if we are
            not careful, we can create a segfault by passing triangules 
            between points that do not exist.
        """
        # We need to run this as a full test of mlab, rather than only a
        # test of the source, as to get a segfault, we need a module
        # opened on the source.
        n = 100
        triangles = np.c_[np.arange(n - 3),
                          np.arange(n - 3) + 1, n - 1 - np.arange(n - 3)]
        x, y, z = np.random.random((3, n))
        src = mlab.triangular_mesh(x, y, z, triangles)

        # Now grow the mesh
        n = 1000
        triangles = np.c_[np.arange(n - 3),
                          np.arange(n - 3) + 1, n - 1 - np.arange(n - 3)]
        x, y, z = np.random.random((3, n))
        src.mlab_source.reset(x=x, y=y, z=z, triangles=triangles)
Exemple #19
0
def plot_sln_mayavi(sln, offscreen=False, show_scale=True):
    """
    Plots the Solution() instance sln using Linearizer() and matplotlib.

    It takes the vertices from linearizer and interpolates them.
    """
    lin = Linearizer()
    lin.process_solution(sln)
    vert = lin.get_vertices()
    triangles = lin.get_triangles()
    from numpy import zeros
    from enthought.mayavi import mlab
    x = vert[:, 0]
    y = vert[:, 1]
    z = zeros(len(y))
    t = vert[:, 2]
    if offscreen:
        # the off screen rendering properly works only with VTK-5.2 or above:
        mlab.options.offscreen = True
    mlab.clf()
    mlab.figure(bgcolor=(1, 1, 1), fgcolor=(0, 0, 0))
    s = mlab.triangular_mesh(x, y, z, triangles, scalars=t)
    mlab.view(0, 0)
    mlab.view(distance=4)
    mlab.view(focalpoint=(.35, 0, 0))
    mlab.colorbar(title="Solution", orientation="vertical")

    #mlab.move(right=-1.0, up=-10.0)
    # Below is a code that does exactly what the "View along the +Z axis"
    # button does:
    #scene = mlab.get_engine().current_scene.scene
    #scene.camera.focal_point = [0, 0, 0]
    #scene.camera.position = [0, 0, 1]
    #scene.camera.view_up = [0, 1, 0]
    #scene.renderer.reset_camera()
    #scene.render()
    # the above looks ok, but there is still quite a large margin, so we prefer
    # to just call .view(0, 0), which seems to be working fine.
    return mlab
Exemple #20
0
def plot_sln_mayavi(sln, offscreen=False, show_scale=True):
    """
    Plots the Solution() instance sln using Linearizer() and matplotlib.

    It takes the vertices from linearizer and interpolates them.
    """
    lin = Linearizer()
    lin.process_solution(sln)
    vert = lin.get_vertices()
    triangles = lin.get_triangles()
    from numpy import zeros
    from enthought.mayavi import mlab
    x = vert[:, 0]
    y = vert[:, 1]
    z = zeros(len(y))
    t = vert[:, 2]
    if offscreen:
        # the off screen rendering properly works only with VTK-5.2 or above:
        mlab.options.offscreen = True
    mlab.clf()
    mlab.figure(bgcolor=(1, 1, 1), fgcolor=(0, 0, 0))
    s = mlab.triangular_mesh(x, y, z, triangles, scalars=t)
    mlab.view(0, 0)
    mlab.view(distance=4)
    mlab.view(focalpoint=(.35,0,0))
    mlab.colorbar(title="Solution", orientation="vertical")

    #mlab.move(right=-1.0, up=-10.0)
    # Below is a code that does exactly what the "View along the +Z axis"
    # button does:
    #scene = mlab.get_engine().current_scene.scene
    #scene.camera.focal_point = [0, 0, 0]
    #scene.camera.position = [0, 0, 1]
    #scene.camera.view_up = [0, 1, 0]
    #scene.renderer.reset_camera()
    #scene.render()
    # the above looks ok, but there is still quite a large margin, so we prefer
    # to just call .view(0, 0), which seems to be working fine.
    return mlab
Exemple #21
0
    def test_triangular_mesh_reset(self):
        """ When reseting the triangular mesh (ie polydata), if we are
            not careful, we can create a segfault by passing triangules 
            between points that do not exist.
        """
        # We need to run this as a full test of mlab, rather than only a  
        # test of the source, as to get a segfault, we need a module
        # opened on the source.
        n = 100
        triangles = np.c_[np.arange(n-3),
                            np.arange(n-3)+1,
                            n-1-np.arange(n-3)]
        x, y, z = np.random.random((3, n))
        src = mlab.triangular_mesh(x, y, z, triangles)

        # Now grow the mesh
        n = 1000
        triangles = np.c_[np.arange(n-3),
                            np.arange(n-3)+1,
                            n-1-np.arange(n-3)]
        x, y, z = np.random.random((3, n))
        src.mlab_source.reset(x=x, y=y, z=z, triangles=triangles)
Exemple #22
0
def plot_sln_mayavi(sln, notebook=False):
    """
    Plots the Solution() instance sln using Linearizer() and matplotlib.

    Currently only a very simple version is implemented, that takes the
    vertices from linearizer and interpolates them. More sophisticated version
    should take the triangles.
    """
    lin = Linearizer()
    lin.process_solution(sln)
    vert = lin.get_vertices()
    triangles = lin.get_triangles()
    from numpy import zeros
    from enthought.mayavi import mlab
    x = vert[:, 0]
    y = vert[:, 1]
    z = zeros(len(y))
    t = vert[:, 2]
    if notebook:
        # the off screen rendering properly works only with VTK-5.2 or above:
        mlab.options.offscreen = True
    mlab.clf()
    s = mlab.triangular_mesh(x, y, z, triangles, scalars=t)
    mlab.view(0, 0)

    # Below is a code that does exactly what the "View along the +Z axis"
    # button does:
    #scene = mlab.get_engine().current_scene.scene
    #scene.camera.focal_point = [0, 0, 0]
    #scene.camera.position = [0, 0, 1]
    #scene.camera.view_up = [0, 1, 0]
    #scene.renderer.reset_camera()
    #scene.render()
    # the above looks ok, but there is still quite a large margin, so we prefer
    # to just call .view(0, 0), which seems to be working fine.
    return s
Exemple #23
0
from pylab import *
import sys,triangleio

try:
    name = sys.argv[1]
except:
    raise Exception('Must enter filename to read')

nv,vertices,nf,facets = triangleio.read(name,faces=True)

from enthought.mayavi import mlab
mlab.triangular_mesh(vertices[:,0],vertices[:,1],vertices[:,2],facets)
mlab.show()
"""
print(__doc__)

# Authors: Denis Engemann <*****@*****.**>
#          Alexandre Gramfort <*****@*****.**>
#
# License: BSD (3-clause)

import mne
from mne.surface import decimate_surface

path = mne.datasets.sample.data_path()
surf = mne.read_bem_surfaces(path + '/subjects/sample/bem/sample-head.fif')[0]

points, triangles = surf['rr'], surf['tris']

# reduce to 30000 meshes equaling ${SUBJECT}-head-medium.fif output from
# mne_make_scalp_surfaces.py and mne_make_scalp_surfaces
points_dec, triangles_dec = decimate_surface(points, triangles,
                                             n_triangles=30000)

try:
    from enthought.mayavi import mlab
except:
    from mayavi import mlab

head_col = (0.95, 0.83, 0.83)  # light pink

p, t = points_dec, triangles_dec
mlab.triangular_mesh(p[:, 0], p[:, 1], p[:, 2], t, color=head_col)
Exemple #25
0
def draw_camera (R, t, scale = 0.1, opt = 'fancy', figure = None):
    """ Draw a camera in world coords according to its pose 
    If R = id and t = [0 0 0]' show a camera in the world 
    center pointing towards the +Z axis.

    Usage: draw_camera (R, t, scale, opt);

    Input:
    R - 3x3 Rotation matrix or 3x1 Rodrigues rotation vector (camera to
       world rotation)
    t - 3x1 Translation vector (camera to world translation)
    scale - (optional) scaling parameter, in meters. Default: 0.1.
    opt - Visualization option: (default: 'pyr') 
         'pyr' shows an inverted pyramid in the camera direction
         'axis' shows the 3 axis (red for X, green for Y, blue for Z)
    """

    # Generate figure if none given
    if figure == None:
        figure = mlab.figure()

    # Enforce 2d column vector of translation
    t = np.atleast_2d(t.ravel()).T

    # Five points that define the pyramid
    # Careful, because np.c_ somehow transposes this matrix, this is 3x6.
    pyr_points = scale * np.c_[[   0,    0, 0], \
                               [-0.4, -0.4, 1], \
                               [ 0.4, -0.4, 1], \
                               [ 0.4,  0.4, 1], \
                               [-0.4,  0.4, 1], \
                               [np.nan, np.nan, np.nan]]

    pyr_tri_side = np.c_[[0, 1, 2], \
                         [0, 2, 3], \
                         [0, 3, 4], \
                         [0, 1, 4]].T

    pyr_tri_front = np.c_[[1, 2, 3], \
                          [1, 3, 4]].T

    # Four points that define the axis in 3-space
    axis_points = scale * np.c_[[0, 0, 0], \
                                [1, 0, 0], \
                                [0, 1, 0], \
                                [0, 0, 1]]

    # Order in which to draw the points, so that it looks like 3 axis
    axis_idx_x = np.r_[1, 2] - 1
    axis_idx_y = np.r_[1, 3] - 1
    axis_idx_z = np.r_[1, 4] - 1

    # Some color constants
    RED   = (1,0,0)
    GREEN = (0,1,0)
    BLUE  = (0,0,1)
    
    if opt == 'pyr':  
        # Rotate pyramid and plot it
        tx_pyr = np.dot(R, pyr_points) + \
                 np.tile( t, (1, pyr_points.shape[1]) )

        mlab.triangular_mesh(tx_pyr[0, :],  \
                             tx_pyr[1, :],  \
                             tx_pyr[2, :],  \
                             pyr_tri_side,        \
                             color = BLUE,        \
                             figure = figure)
        mlab.draw() 
        mlab.triangular_mesh(tx_pyr[0, :],  \
                             tx_pyr[1, :],  \
                             tx_pyr[2, :],  \
                             pyr_tri_front,       \
                             color = GREEN,       \
                             figure = figure)       


    elif opt == 'axis':
        # Rotate the 3 axis and plot them
        tx_axis = np.dot(R, axis_points) + \
                  np.tile( t, (1, axis_points.shape[1]) )

        mlab.plot3d(tx_axis[0, axis_idx_x], \
                    tx_axis[1, axis_idx_x], \
                    tx_axis[2, axis_idx_x], \
                    color = RED, \
                    tube_radius = .003, \
                    figure = figure)
        
        mlab.plot3d(tx_axis[0, axis_idx_y], \
                    tx_axis[1, axis_idx_y], \
                    tx_axis[2, axis_idx_y], \
                    color = GREEN, \
                    tube_radius = .003, \
                    figure = figure)

        mlab.plot3d(tx_axis[0, axis_idx_z], \
                    tx_axis[1, axis_idx_z], \
                    tx_axis[2, axis_idx_z], \
                    color = BLUE, \
                    tube_radius = .003, \
                    figure = figure)

    elif opt == 'fancy':
        # Rotate pyramid and plot it
        tx_pyr = np.dot(R, pyr_points) + \
                 np.tile( t, (1, pyr_points.shape[1]) )

        mlab.triangular_mesh(tx_pyr[0, :],  \
                             tx_pyr[1, :],  \
                             tx_pyr[2, :],  \
                             pyr_tri_side,        \
                             color = BLUE,        \
                             figure = figure)

        mlab.triangular_mesh(tx_pyr[0, :],  \
                             tx_pyr[1, :],  \
                             tx_pyr[2, :],  \
                             pyr_tri_front,       \
                             color = GREEN,       \
                             figure = figure)     
        
        # Rotate the 3 axis and plot them
        tx_axis = np.dot(R, axis_points) + \
                  np.tile( t, (1, axis_points.shape[1]) )

        mlab.plot3d(tx_axis[0, axis_idx_x], \
                    tx_axis[1, axis_idx_x], \
                    tx_axis[2, axis_idx_x], \
                    color = RED, \
                    tube_radius = .003, \
                    figure = figure)
        
        mlab.plot3d(tx_axis[0, axis_idx_y], \
                    tx_axis[1, axis_idx_y], \
                    tx_axis[2, axis_idx_y], \
                    color = GREEN, \
                    tube_radius = .003, \
                    figure = figure)


    else: 
        print('Unrecognized option');
print(__doc__)

# Authors: Denis Engemann <*****@*****.**>
#          Alexandre Gramfort <*****@*****.**>
#
# License: BSD (3-clause)

import mne
from mne.surface import decimate_surface

path = mne.datasets.sample.data_path()
surf = mne.read_bem_surfaces(path + '/subjects/sample/bem/sample-head.fif')[0]

points, triangles = surf['rr'], surf['tris']

# reduce to 30000 meshes equaling ${SUBJECT}-head-medium.fif output from
# mne_make_scalp_surfaces.py and mne_make_scalp_surfaces
points_dec, triangles_dec = decimate_surface(points,
                                             triangles,
                                             n_triangles=30000)

try:
    from enthought.mayavi import mlab
except:
    from mayavi import mlab

head_col = (0.95, 0.83, 0.83)  # light pink

p, t = points_dec, triangles_dec
mlab.triangular_mesh(p[:, 0], p[:, 1], p[:, 2], t, color=head_col)
import mne
from mne.datasets import sample

data_path = sample.data_path()
fname = data_path + '/subjects/sample/bem/sample-5120-5120-5120-bem-sol.fif'

surfaces = mne.read_bem_surfaces(fname, add_geom=True)

print("Number of surfaces : %d" % len(surfaces))

###############################################################################
# Show result
head_col = (0.95, 0.83, 0.83)  # light pink
skull_col = (0.91, 0.89, 0.67)
brain_col = (0.67, 0.89, 0.91)  # light blue
colors = [head_col, skull_col, brain_col]

# 3D source space
try:
    from enthought.mayavi import mlab
except:
    from mayavi import mlab

mlab.figure(size=(600, 600), bgcolor=(0, 0, 0))
for c, surf in zip(colors, surfaces):
    points = surf['rr']
    faces = surf['tris']
    mlab.triangular_mesh(points[:, 0], points[:, 1], points[:, 2], faces,
                         color=c, opacity=0.3)
Exemple #28
0
    x = sin(phi)
    y = cos(phi)

    
    #normals = -vstack([n * x + b * y for n, b in zip(N, B)])
    points = vstack([p + thickness * (n * x + b * y) for p, n, b in zip(path, N, B)])
    
    return make_tube(points, sides)
    

if __name__ == '__main__':
    import sys
    
    m = Mesh(sys.argv[1])
    x, y, z = m.points.T
    
    
    
    print 'Points: %d' % len(m.points)
    print 'Triangles: %d' % len(m.triangles)

    #m.triangles[0] = m.triangles[0, ::-1] #Flip a triangle to test the closed shape detection
    print 'Volume: %f (%s)' % (m.volume(), 'mesh appears closed and properly oriented' if m.is_closed(tol=1E-12) else 'MESH DOES NOT APPEAR CLOSED AND ORIENTED PROPERLY)\n   (A translated copy had a different calculated volume at 1 part in 10^12;\n    this could be a rounding error.')
    print 'Print price: $%.2f (assuming units=mm and $0.30/cc)' % (m.volume() / 1000. * 0.30)
    print 'X extents: (%f, %f)' % (min(x), max(x))
    print 'Y extents: (%f, %f)' % (min(y), max(y))
    print 'Z extents: (%f, %f)' % (min(z), max(z))
    
    from enthought.mayavi import mlab
    mlab.triangular_mesh(x, y, z, m.triangles)
    mlab.show()   
Exemple #29
0
def dense_reconstruction(S, P1, P2, H1, H2, region=None, step=1, imbw1=None):
    """
    Build and show a dense reconstruction.
    
    Parameters
    ----------
    S : ndarray
        Matrix of disparities.
    P1, P2 : ndarray
        Projection matrices of the stereo pair.
    H1, H2 : ndarray
        Homographies which rectify the images of the stereo
        pair. See projmat2rectify.
    region : array-like, optional
        Region of the matrix of disparities that will be used for
        the dense reconstruction. It must be expressed
        as [x_min, x_max, y_min, y_max].
        
        If not given, the full matrix of disparities is considered.
    step : integer, optional
        Quality of the reconstruction. Only one of every 'step' pixels
        inside the region of interest is taken for the reconstruction.
        
        If not given, all pixels are used.
    imbw1 : ndarray, optional
        The image before rectification. This is used to assign a color
        to the 3D vertices of the reconstruction. If not given, an arbitrary
        color is assigned to vertices.
        
        imbw1 should be a gray scale image.
    """
    if region is None:
        region = [0, S.shape[1], 0, S.shape[0]]

    # The matrix of disparities is smoothed.
    H = np.ones((3, 3)) / 9.0
    S = ndimage.convolve(np.double(S), H, mode='constant')

    # Point correspondences.
    X, Y = np.mgrid[region[0]:region[1] + 1:step, region[2]:region[3] + 1:step]
    num_points = np.prod(X.shape)
    points1 = np.ones((3, num_points))
    points1[0, :] = X.ravel()
    points1[1, :] = Y.ravel()
    X2 = X.ravel() + S[np.int32(points1[1, :]), np.int32(points1[0, :])]
    points2 = np.copy(points1)
    points2[0, :] = X2

    # Colors
    if imbw1 is not None:
        points1back = hom2cart(np.dot(la.inv(H1), points1))
        colors = ndimage.map_coordinates(imbw1,
                                         [points1back[1], points1back[0]],
                                         order=1)
    else:
        colors = None

    # Polygons.
    vlist = np.arange(0, num_points)
    vlist = vlist.reshape(X.shape)
    vlist1 = vlist[:-1, :-1]
    vlist2 = vlist[:-1, 1:]
    vlist3 = vlist[1:, 1:]
    vlist4 = vlist[1:, :-1]
    faces1 = np.array([vlist1.ravel(), vlist2.ravel(), vlist3.ravel()])
    faces2 = np.array([vlist1.ravel(), vlist3.ravel(), vlist4.ravel()])
    faces = matarray(faces1, faces2).T

    # Reconstruction.
    from stereo import reconstruct
    M = reconstruct(points1, points2, np.dot(H1, P1), np.dot(H2, P2))

    # Show the result.
    try:
        from enthought.mayavi import mlab
    except ImportError:
        from mayavi import mlab
    mlab.clf()
    mlab.triangular_mesh(M[0],
                         M[1],
                         M[2],
                         faces,
                         scalars=colors,
                         colormap='gray')

    return M, faces, colors
Exemple #30
0
vis, illum, outs = taco.calc_earth_vis(-p_earth_body,
                                       att,
                                       ngrid=30,
                                       to_earth=True,
                                       max_reflect=0)

mask_points = (len(outs) // 300) or None
rx = [out[0][0] for out in outs]
ry = [out[0][1] for out in outs]
rz = [out[0][2] for out in outs]
ru = [out[1][0] * (2 if out[3] else 1) for out in outs]
rv = [out[1][1] * (2 if out[3] else 1) for out in outs]
rw = [out[1][2] * (2 if out[3] else 1) for out in outs]

mlab.clf()
mlab.triangular_mesh(xs, ys, zs, triangles, color=(1, 1, 0), opacity=0.9)
mlab.triangular_mesh(xs,
                     ys,
                     zs,
                     triangles,
                     color=(1, .8, 0),
                     representation='wireframe',
                     line_width=4)
mlab.quiver3d(rx,
              ry,
              rz,
              ru,
              rv,
              rw,
              scale_factor=1.0,
              mask_points=mask_points,
    from enthought.mayavi import mlab
except:
    from mayavi import mlab

lh_points = src[0]['rr']
lh_faces = src[0]['use_tris']
mlab.figure(size=(600, 600), bgcolor=(1, 1, 1), fgcolor=(0, 0, 0))

# show brain surface after proper coordinate system transformation
points = brain_surface['rr']
faces = brain_surface['tris']
coord_trans = fwd['mri_head_t']['trans']
points = np.dot(coord_trans[:3, :3], points.T).T + coord_trans[:3, -1]
mlab.triangular_mesh(points[:, 0],
                     points[:, 1],
                     points[:, 2],
                     faces,
                     color=(1, 1, 0),
                     opacity=0.3)

# show one cortical surface
mlab.triangular_mesh(lh_points[:, 0],
                     lh_points[:, 1],
                     lh_points[:, 2],
                     lh_faces,
                     color=(0.7, ) * 3)

# show dipole as small cones
dipoles = mlab.quiver3d(pos[:, 0],
                        pos[:, 1],
                        pos[:, 2],
                        ori[:, 0],
Exemple #32
0
    #    v1 = np.array([0,0,0])
    #    v2 = np.array([100,0,0])
    #    mlab.triangular_mesh([[v1[0]-1,v1[0]+1,v2[0]-1,v2[0]+1]], [[v1[1]-1,v1[1]+1,v2[1]-1,v2[1]+1]], [[v1[2]-1,v1[2]+1,v2[2]-1,v2[2]+1]], [(0,1,2),(1,2,3)])
    #    v1 = np.array([0,0,0])
    #    v2 = np.array([0,100,0])
    #    mlab.triangular_mesh([[v1[0]-1,v1[0]+1,v2[0]-1,v2[0]+1]], [[v1[1]-1,v1[1]+1,v2[1]-1,v2[1]+1]], [[v1[2]-1,v1[2]+1,v2[2]-1,v2[2]+1]], [(0,1,2),(1,2,3)])
    #    v1 = np.array([0,0,0])
    #    v2 = np.array([0,0,100])
    #    mlab.triangular_mesh([[v1[0]-1,v1[0]+1,v2[0]-1,v2[0]+1]], [[v1[1]-1,v1[1]+1,v2[1]-1,v2[1]+1]], [[v1[2]-1,v1[2]+1,v2[2]-1,v2[2]+1]], [(0,1,2),(1,2,3)])

    v1 = np.array([0, 0, 0])
    v2 = np.array([80, 0, 0])
    v2 = np.dot(R[:, 0:3], v2)
    mlab.triangular_mesh([[v1[0] - 1, v1[0] + 1, v2[0] - 1, v2[0] + 1]],
                         [[v1[1] - 1, v1[1] + 1, v2[1] - 1, v2[1] + 1]],
                         [[v1[2] - 1, v1[2] + 1, v2[2] - 1, v2[2] + 1]],
                         [(0, 1, 2), (1, 2, 3)],
                         color=(1, 1, 1))

    v1 = np.array([0, 0, 0])
    v2 = np.array([0, 80, 0])
    v2 = np.dot(R[:, 0:3], v2)
    mlab.triangular_mesh([[v1[0] - 1, v1[0] + 1, v2[0] - 1, v2[0] + 1]],
                         [[v1[1] - 1, v1[1] + 1, v2[1] - 1, v2[1] + 1]],
                         [[v1[2] - 1, v1[2] + 1, v2[2] - 1, v2[2] + 1]],
                         [(0, 1, 2), (1, 2, 3)],
                         color=(1, 1, 1))

    v1 = np.array([0, 0, 0])
    v2 = np.array([0, 0, 80])
    v2 = np.dot(R[:, 0:3], v2)
Exemple #33
0
def show_odfs(odfs, vertices_faces, image=None, colormap='jet',
              scale=2.2, norm=True, radial_scale=True):
    """
    Display a grid of ODFs.

    Parameters
    ----------
    odfs : (X, Y, Z, M) ndarray
        A 3-D arrangement of orientation distribution functions (ODFs).  At
        each ``(x, y, z)`` position, it contains the the values of the
        corresponding ODF evaluated on the M vertices.
    vertices_faces : str or tuple of (vertices, faces)
        A named sphere from `dipy.data.get_sphere`, or a combination of
        `(vertices, faces)`.
    image : (X, Y) ndarray
        Background image (e.g., fractional anisotropy) do display behind the
        ODFs.
    colormap : str
        Color mapping.
    scale : float
        Increasing the scale spaces ODFs further apart.
    norm : bool
        Whether or not to normalize each individual ODF (divide by its maximum
        absolute value).
    radial_scale : bool
        Whether or not to change the radial shape of the ODF according to its
        scalar value.  If set to False, the ODF is displayed as a sphere.

    Notes
    -----
    Mayavi gets really slow when `triangular_mesh` is called too many times,
    so this function stacks ODF data and calls `triangular_mesh` once.

    Examples
    --------
    >>> from dipy.data import get_sphere
    >>> verts, faces = get_sphere('symmetric724')

    >>> angle = np.linspace(0, 2*np.pi, len(verts))
    >>> odf1 = np.sin(angle)
    >>> odf2 = np.cos(angle)
    >>> odf3 = odf1**2 * odf2
    >>> odf4 = odf1 + odf2**2

    >>> odfs = [[[odf1, odf2],
    ...          [odf3, odf4]]]

    >>> show_odfs(odfs, (verts, faces), scale=5)

    """
    vertices, faces = sphere_vf_from(vertices_faces)

    odfs = np.asarray(odfs)
    if odfs.ndim != 4:
        raise ValueError("ODFs must by an (X,Y,Z,M) array. " +
                         "Has shape " + str(odfs.shape))

    grid_shape = np.array(odfs.shape[:3])
    faces = np.asarray(faces, dtype=int)

    xx, yy, zz, ff, mm = [], [], [], [], []
    count = 0

    for ijk in np.ndindex(*grid_shape):
        m = odfs[ijk]

        if norm:
            m /= abs(m).max()

        if radial_scale:
            xyz = vertices.T * m
        else:
            xyz = vertices.T.copy()

        xyz += scale * (ijk - grid_shape / 2.)[:, None]

        x, y, z = xyz
        ff.append(count + faces)
        xx.append(x)
        yy.append(y)
        zz.append(z)
        mm.append(m)

        count += len(x)

    ff, xx, yy, zz, mm = (np.concatenate(arrs) for arrs in (ff, xx, yy, zz, mm))
    mlab.triangular_mesh(xx, yy, zz, ff, scalars=mm, colormap=colormap)

    if image is not None:
        mlab.imshow(image, colormap='gray', interpolate=False)

    mlab.colorbar()
    mlab.show()
data_path = sample.data_path()
fname = data_path + '/subjects/sample/bem/sample-5120-5120-5120-bem-sol.fif'

surfaces = mne.read_bem_surfaces(fname, add_geom=True)

print "Number of surfaces : %d" % len(surfaces)

###############################################################################
# Show result
head_col = (0.95, 0.83, 0.83)  # light pink
skull_col = (0.91, 0.89, 0.67)
brain_col = (0.67, 0.89, 0.91)  # light blue
colors = [head_col, skull_col, brain_col]

# 3D source space
try:
    from enthought.mayavi import mlab
except:
    from mayavi import mlab

mlab.figure(size=(600, 600), bgcolor=(0, 0, 0))
for c, surf in zip(colors, surfaces):
    points = surf['rr']
    faces = surf['tris']
    mlab.triangular_mesh(points[:, 0],
                         points[:, 1],
                         points[:, 2],
                         faces,
                         color=c,
                         opacity=0.3)
Exemple #35
0
def main():
    from optparse import OptionParser
    parser = OptionParser(usage="Usage: %prog [options] <mesh.neu>")
    parser.add_option("--cl", action="store_true", help="use OpenCL")
    parser.add_option("-v", "--vis-every", type="int", metavar="S",
            help="visualize on-line every S steps")
    parser.add_option("--update-colors", action="store_true", 
            help="update colors in visualization (expensive)")
    parser.add_option("--profile", type="int", 
            help="set the profiling level (CL only)")
    parser.add_option("-i", "--ic", metavar="NAME",
            help="use initial condition NAME (try 'help')",
            default="gaussian")
    parser.add_option("-t", "--final-time", metavar="T",
            help="set final time", type="float",
            default=5)
    parser.add_option("-n", metavar="N", type="int", default=4,
            help="use polynomial degree N")

    options, args = parser.parse_args()
    if not args:
        parser.print_help()
        return

    ldis = LocalDiscretization2D(N=options.n)
    print "loading mesh"
    mesh = pydgeon.read_2d_gambit_mesh(args[0])

    print "building discretization"
    if options.cl:
        from pydgeon.opencl import CLDiscretization2D
        d = CLDiscretization2D(ldis, *mesh, **{"profile": options.profile})
    else:
        d = pydgeon.Discretization2D(ldis, *mesh)

    print "%d elements" % d.K

    # set initial conditions
    if options.ic == "sine":
        mmode = 3; nmode = 2
        Hx = np.zeros((d.K, d.ldis.Np))
        Hy = np.zeros((d.K, d.ldis.Np))
        Ez = np.sin(mmode*np.pi*d.x)*np.sin(nmode*np.pi*d.y)
    elif options.ic == "gaussian":
        Hx = np.zeros((d.K, d.ldis.Np))
        Hy = np.zeros((d.K, d.ldis.Np))

        min_x = np.min(d.x)
        max_x = np.max(d.x)
        min_y = np.min(d.y)
        max_y = np.max(d.y)

        x0 = min_x + 0.85*(max_x-min_x)
        y0 = min_y + 0.85*(max_y-min_y)

        x = d.x-x0
        y = d.y-y0
        r = (max_x-min_x)*0.005
        Ez = np.exp(-(x**2+y**2)/r**2)
    else:
        print "available ICs: sine, gaussian"
        return

    state = make_obj_array([Hx, Hy, Ez])
    if options.cl:
        state = make_obj_array([d.to_dev(x) for x in state])

    # compute time step size
    rLGL = JacobiGQ(0,0, d.ldis.N)[0]
    rmin = abs(rLGL[0]-rLGL[1])
    dt_scale = d.dt_scale()
    dt = dt_scale.min()*rmin*2/3

    # setup
    if options.vis_every:
        try:
            import enthought.mayavi.mlab as mayavi
        except ImportError:
            options.vis_every = 0

    if options.vis_every:
        vis_mesh = mayavi.triangular_mesh(
                d.x.ravel(), d.y.ravel(), Ez.ravel(),
                d.gen_vis_triangles())

    def vis_hook(step, t, state):
        if options.vis_every and step % options.vis_every == 0:
            if options.cl:
                Hx, Hy, Ez = [d.from_dev(x) for x in state]
            else:
                Hx, Hy, Ez = state

            vis_mesh.mlab_source.z = Ez.ravel()
            # update colors, too (expensive)
            if options.update_colors:
                vis_mesh.mlab_source.scalars = Ez.ravel()

        from time import time as wall_time
        progress_every = 20
        start_timing_at_step = progress_every
        if step % 20 == 0:
            if options.cl:
                d.queue.finish()
            if step == start_timing_at_step:
                start_time[0] = wall_time()
            elif step > start_timing_at_step:
                elapsed = wall_time()-start_time[0]
                timed_steps = step - start_timing_at_step
                time_per_step = elapsed/timed_steps

                line = ("step=%d, sim_time=%f, elapsed wall time=%.2f s,"
                        "time per step=%f s" % (
                        step, t, elapsed, time_per_step))

                if options.cl:
                    flops = 5 * (inner_rhs.flops + 4*d.K*d.ldis.Np)
                    line += " %f gflops/s" % (flops/time_per_step/1e9)

                print line


    if options.cl:
        from pydgeon.maxwell import CLMaxwellsRhs2D
        inner_rhs = CLMaxwellsRhs2D(d)

        def rhs(t, state):
            return make_obj_array(inner_rhs(*state))
    else:
        from pydgeon.maxwell import MaxwellRHS2D

        def rhs(t, state):
            return make_obj_array(MaxwellRHS2D(d, *state))

    # time loop
    print "entering time loop"
    start_time = [0]
    time, final_state = integrate_in_time(state, rhs, dt, 
            final_time=options.final_time, vis_hook=vis_hook)
Exemple #36
0
def show_odfs(odfs,
              vertices_faces,
              image=None,
              colormap='jet',
              scale=2.2,
              norm=True,
              radial_scale=True):
    """
    Display a grid of ODFs.

    Parameters
    ----------
    odfs : (X, Y, Z, M) ndarray
        A 3-D arrangement of orientation distribution functions (ODFs).  At
        each ``(x, y, z)`` position, it contains the the values of the
        corresponding ODF evaluated on the M vertices.
    vertices_faces : str or tuple of (vertices, faces)
        A named sphere from `dipy.data.get_sphere`, or a combination of
        `(vertices, faces)`.
    image : (X, Y) ndarray
        Background image (e.g., fractional anisotropy) do display behind the
        ODFs.
    colormap : str
        Color mapping.
    scale : float
        Increasing the scale spaces ODFs further apart.
    norm : bool
        Whether or not to normalize each individual ODF (divide by its maximum
        absolute value).
    radial_scale : bool
        Whether or not to change the radial shape of the ODF according to its
        scalar value.  If set to False, the ODF is displayed as a sphere.

    Notes
    -----
    Mayavi gets really slow when `triangular_mesh` is called too many times,
    so this function stacks ODF data and calls `triangular_mesh` once.

    Examples
    --------
    >>> from dipy.data import get_sphere
    >>> verts, faces = get_sphere('symmetric724')

    >>> angle = np.linspace(0, 2*np.pi, len(verts))
    >>> odf1 = np.sin(angle)
    >>> odf2 = np.cos(angle)
    >>> odf3 = odf1**2 * odf2
    >>> odf4 = odf1 + odf2**2

    >>> odfs = [[[odf1, odf2],
    ...          [odf3, odf4]]]

    >>> show_odfs(odfs, (verts, faces), scale=5)

    """
    vertices, faces = sphere_vf_from(vertices_faces)

    odfs = np.asarray(odfs)
    if odfs.ndim != 4:
        raise ValueError("ODFs must by an (X,Y,Z,M) array. " + "Has shape " +
                         str(odfs.shape))

    grid_shape = np.array(odfs.shape[:3])
    faces = np.asarray(faces, dtype=int)

    xx, yy, zz, ff, mm = [], [], [], [], []
    count = 0

    for ijk in np.ndindex(*grid_shape):
        m = odfs[ijk]

        if norm:
            m /= abs(m).max()

        if radial_scale:
            xyz = vertices.T * m
        else:
            xyz = vertices.T.copy()

        xyz += scale * (ijk - grid_shape / 2.)[:, None]

        x, y, z = xyz
        ff.append(count + faces)
        xx.append(x)
        yy.append(y)
        zz.append(z)
        mm.append(m)

        count += len(x)

    ff, xx, yy, zz, mm = (np.concatenate(arrs)
                          for arrs in (ff, xx, yy, zz, mm))
    mlab.triangular_mesh(xx, yy, zz, ff, scalars=mm, colormap=colormap)

    if image is not None:
        mlab.imshow(image, colormap='gray', interpolate=False)

    mlab.colorbar()
    mlab.show()
# Show result on 3D source space
try:
    from enthought.mayavi import mlab
except:
    from mayavi import mlab

lh_points = src[0]['rr']
lh_faces = src[0]['use_tris']
mlab.figure(size=(600, 600), bgcolor=(1, 1, 1), fgcolor=(0, 0, 0))

# show brain surface after proper coordinate system transformation
points = brain_surface['rr']
faces = brain_surface['tris']
coord_trans = fwd['mri_head_t']['trans']
points = np.dot(coord_trans[:3,:3], points.T).T + coord_trans[:3,-1]
mlab.triangular_mesh(points[:, 0], points[:, 1], points[:, 2],
                     faces, color=(1, 1, 0), opacity=0.3)

# show one cortical surface
mlab.triangular_mesh(lh_points[:, 0], lh_points[:, 1], lh_points[:, 2],
                     lh_faces, color=(0.7, ) * 3)

# show dipole as small cones
dipoles = mlab.quiver3d(pos[:,0], pos[:,1], pos[:,2],
                        ori[:,0], ori[:,1], ori[:,2],
                        opacity=1., scale_factor=4e-4, scalars=time,
                        mode='cone')
mlab.colorbar(dipoles, title='Dipole fit time (ms)')

# proper 3D orientation
mlab.get_engine().scenes[0].scene.x_plus_view()
Exemple #38
0
 def plot(self, fig):
     x,y,z = zip(*self.getPoints(np.array(self.triangles).flatten()))
     emm.triangular_mesh(x,y,z, np.arange(len(self.triangles)*3).reshape(-1,3), representation = 'wireframe', figure = fig, color=(0.4,0.4,0.4), opacity = 0.4, line_width=0.5)
Exemple #39
0
def make_flash_bem(subject, subjects_dir, flash05, flash30, show=False):
    """Create 3-Layers BEM model from Flash MRI images

    Parameters
    ----------
    subject : string
        Subject name
    subjects_dir : string
        Directory containing subjects data (Freesurfer SUBJECTS_DIR)
    flash05 : string
        Full path of the NIFTI file for the
        FLASH sequence with a spin angle of 5 degrees
    flash30 : string
        Full path of the NIFTI file for the
        FLASH sequence with a spin angle of 30 degrees
    show : bool
        Show surfaces in 3D to visually inspect all three BEM
        surfaces (recommended)

    Notes
    -----
    This program assumes that both Freesurfer/FSL, and MNE,
    including MNE's Matlab Toolbox, are installed properly.
    For reference please read the MNE manual and wiki, and Freesurfer's wiki:
    http://www.nmr.mgh.harvard.edu/meg/manuals/
    http://www.nmr.mgh.harvard.edu/martinos/userInfo/data/sofMNE.php
    http://www.nmr.mgh.harvard.edu/martinos/userInfo/data/MNE_register/index.php
    http://surfer.nmr.mgh.harvard.edu/
    http://surfer.nmr.mgh.harvard.edu/fswiki

    References:
    B. Fischl, D. H. Salat, A. J. van der Kouwe, N. Makris, F. Segonne,
    B. T. Quinn, and A. M. Dale, "Sequence-independent segmentation of magnetic
    resonance images," Neuroimage, vol. 23 Suppl 1, pp. S69-84, 2004.
    J. Jovicich, S. Czanner, D. Greve, E. Haley, A. van der Kouwe, R. Gollub,
    D. Kennedy, F. Schmitt, G. Brown, J. Macfall, B. Fischl, and A. Dale,
    "Reliability in multi-site structural MRI studies: effects of gradient
    non-linearity correction on phantom and human data," Neuroimage,
    vol. 30, Epp. 436-43, 2006.
    """
    os.environ['SUBJECT'] = subject
    os.chdir(os.path.join(subjects_dir, subject, "mri"))
    if not os.path.exists('flash'):
        os.mkdir("flash")
    os.chdir("flash")
    # flash_dir = os.getcwd()
    if not os.path.exists('parameter_maps'):
        os.mkdir("parameter_maps")
    print("--- Converting Flash 5")
    os.system('mri_convert -flip_angle %s -tr 25 %s mef05.mgz' %
                                            (5 * math.pi / 180, flash05))
    print("--- Converting Flash 30")
    os.system('mri_convert -flip_angle %s -tr 25 %s mef30.mgz' %
                                            (30 * math.pi / 180, flash30))
    print("--- Running mne_flash_bem")
    os.system('mne_flash_bem --noconvert')
    os.chdir(os.path.join(subjects_dir, subject, 'bem'))
    if not os.path.exists('flash'):
        os.mkdir("flash")
    os.chdir("flash")
    print("[done]")

    if show:
        fnames = ['outer_skin.surf', 'outer_skull.surf', 'inner_skull.surf']
        head_col = (0.95, 0.83, 0.83)  # light pink
        skull_col = (0.91, 0.89, 0.67)
        brain_col = (0.67, 0.89, 0.91)  # light blue
        colors = [head_col, skull_col, brain_col]
        from enthought.mayavi import mlab
        mlab.clf()
        for fname, c in zip(fnames, colors):
            points, faces = mne.read_surface(fname)
            mlab.triangular_mesh(points[:, 0], points[:, 1], points[:, 2], faces,
                                 color=c, opacity=0.3)
        mlab.show()
print(__doc__)

import os.path as op

import mne
from mne.datasets import sample

data_path = sample.data_path()
fname = op.join(data_path, 'subjects', 'sample', 'bem', 'sample-oct-6-src.fif')

add_geom = True  # include high resolution source space
src = mne.read_source_spaces(fname, add_geom=add_geom)

# 3D source space (high sampling)
lh_points = src[0]['rr']
lh_faces = src[0]['tris']
rh_points = src[1]['rr']
rh_faces = src[1]['tris']
try:
    from enthought.mayavi import mlab
except:
    from mayavi import mlab
mlab.figure(size=(600, 600), bgcolor=(0, 0, 0),)
mesh = mlab.triangular_mesh(lh_points[:, 0], lh_points[:, 1], lh_points[:, 2],
                            lh_faces, colormap='RdBu')
mesh.module_manager.scalar_lut_manager.reverse_lut = True

mesh = mlab.triangular_mesh(rh_points[:, 0], rh_points[:, 1], rh_points[:, 2],
                            rh_faces, colormap='RdBu')
mesh.module_manager.scalar_lut_manager.reverse_lut = True
Exemple #41
0
#    v1 = np.array([0,0,0])
#    v2 = np.array([100,0,0])
#    mlab.triangular_mesh([[v1[0]-1,v1[0]+1,v2[0]-1,v2[0]+1]], [[v1[1]-1,v1[1]+1,v2[1]-1,v2[1]+1]], [[v1[2]-1,v1[2]+1,v2[2]-1,v2[2]+1]], [(0,1,2),(1,2,3)])
#    v1 = np.array([0,0,0])
#    v2 = np.array([0,100,0])
#    mlab.triangular_mesh([[v1[0]-1,v1[0]+1,v2[0]-1,v2[0]+1]], [[v1[1]-1,v1[1]+1,v2[1]-1,v2[1]+1]], [[v1[2]-1,v1[2]+1,v2[2]-1,v2[2]+1]], [(0,1,2),(1,2,3)])
#    v1 = np.array([0,0,0])
#    v2 = np.array([0,0,100])
#    mlab.triangular_mesh([[v1[0]-1,v1[0]+1,v2[0]-1,v2[0]+1]], [[v1[1]-1,v1[1]+1,v2[1]-1,v2[1]+1]], [[v1[2]-1,v1[2]+1,v2[2]-1,v2[2]+1]], [(0,1,2),(1,2,3)])



    v1 = np.array([0,0,0])
    v2 = np.array([80,0,0])
    v2 = np.dot(R[:,0:3],v2)
    mlab.triangular_mesh([[v1[0]-1,v1[0]+1,v2[0]-1,v2[0]+1]], [[v1[1]-1,v1[1]+1,v2[1]-1,v2[1]+1]], [[v1[2]-1,v1[2]+1,v2[2]-1,v2[2]+1]], [(0,1,2),(1,2,3)],color=(1,1,1))

    v1 = np.array([0,0,0])
    v2 = np.array([0,80,0])
    v2 = np.dot(R[:,0:3],v2)
    mlab.triangular_mesh([[v1[0]-1,v1[0]+1,v2[0]-1,v2[0]+1]], [[v1[1]-1,v1[1]+1,v2[1]-1,v2[1]+1]], [[v1[2]-1,v1[2]+1,v2[2]-1,v2[2]+1]], [(0,1,2),(1,2,3)],color=(1,1,1))

    v1 = np.array([0,0,0])
    v2 = np.array([0,0,80])
    v2 = np.dot(R[:,0:3],v2)
    mlab.triangular_mesh([[v1[0]-1,v1[0]+1,v2[0]-1,v2[0]+1]], [[v1[1]-1,v1[1]+1,v2[1]-1,v2[1]+1]], [[v1[2]-1,v1[2]+1,v2[2]-1,v2[2]+1]], [(0,1,2),(1,2,3)],color=(1,1,1))


    print 
    #axis
    mlab.triangular_mesh([[0,0,100]], [[-0.3,0.3,0]], [[0,0,0]], [(0,1,2)])
Exemple #42
0
def plot3d(cf, vp1, vp2, precision, m1,m2,centerline,showbases,seq,mult,ghost): #DRAWS THE MOLECULE(S)
    print "Loading mlab....."
    from anim import stiffness, ACP
    from draw import data3d
    from enthought.mayavi import mlab
    r, q, d, g, h, sequence = cf
    nbbases = q.shape[0]
    #mlab.options.backend = 'envisage' #to use the full Mayavi interface
    fig = mlab.figure(1, bgcolor=(0, 0, 0), size=(1024,768)) #creates a new window
    mlab.clf() #clears the window
    
    if centerline >0 :
        #DRAWS CENTRAL AXIS
        #axis_nodes = mlab.points3d(q[:,0],q[:,1],q[:,2],scale_factor=0.4,color=(1,0,1))
        ghost_axis = mlab.plot3d(q[:,0],q[:,1],q[:,2],tube_radius=0.05, color=(1,1,1)) #will never move
        axis = mlab.plot3d(q[:,0],q[:,1],q[:,2],tube_radius=0.05, color=(1,0,1))
    
    #DRAWS LAB FRAME e
    ee = mlab.quiver3d([0,0,0],[0,0,0],[0,0,0],[1,0,0],[0,1,0],[0,0,1], \
                  mode='arrow',scale_factor=2, color=(1,1,1))

    if showbases >0 :
        #DRAWS BASES AND BASE FRAMES
        points, triangles, centres, frames, i,j, repere, s = data3d(r,d,sequence) #see draw.py
        if ghost >0 :
            ghost = mlab.triangular_mesh(points[:,0],points[:,1],points[:,2],triangles,color=(1,1,1),opacity=0.4)
        k = array(repere)[nbbases,0] #index i : points
        l = array(repere)[nbbases,1] #index j : triangles
        main_strand = mlab.triangular_mesh(points[:k,0],points[:k,1],points[:k,2],triangles[:l],\
                      scalars=s[:k], colormap="autumn") #main strand
        comp_strand = mlab.triangular_mesh(points[k:i,0],points[k:i,1],points[k:i,2],triangles[l:j]-triangles[l,0],\
                      scalars=s[k:i], colormap="autumn") #complementary
        baseframes  = mlab.quiver3d(centres[:,0],centres[:,1],centres[:,2],frames[:,0],frames[:,1],frames[:,2], \
                      mode='arrow',scale_factor=2, colormap="Oranges")

    #ANIMATION
    if vp1 >0 :
        if centerline >0 :
            #axis_nodes_src = axis_nodes.mlab_source
            axis_src = axis.mlab_source
        if showbases >0 :
            main_strand_src = main_strand.mlab_source
            comp_strand_src = comp_strand.mlab_source
            baseframes_src  = baseframes.mlab_source
        vecp = stiffness(m1,1,vp1-1) #chosen eigenvector 1
        #mult = 2.0 #multiple of the added eigenvector
        fig.scene.anti_aliasing_frames = 0 #antialiasing, default=8, off=0
        for p in range(precision):
            wmod = ACP(readParameters(),vecp,mult*(p+1)/precision) #modified configuration
            cfmod = calculPoints(wmod) #modified coordinates
            r_p, q_p, d_p, g_p, h_p, sequence = cfmod
            fig.scene.disable_render = True #accelerates rendering
            if showbases >0 : 
                points_p, triangles_p, centres_p, frames_p, i,j, repere, s = data3d(r_p,d_p,sequence) #modified graphics
                main_strand_src.set(x=points_p[:k,0],y=points_p[:k,1],z=points_p[:k,2])
                comp_strand_src.set(x=points_p[k:i,0],y=points_p[k:i,1],z=points_p[k:i,2])
                baseframes_src.reset(x=centres_p[:,0],y=centres_p[:,1],z=centres_p[:,2],\
                                   u=frames_p[:,0],v=frames_p[:,1],w=frames_p[:,2])
            if centerline >0 :
                #axis_nodes_src.set(x=q_p[:,0],y=q_p[:,1],z=q_p[:,2],scale_factor=0.7,color=(1,0,1))
                axis_src.set(x=q_p[:,0],y=q_p[:,1],z=q_p[:,2],tube_radius=0.05, color=(1,0,1))
            fig.scene.disable_render = False
    if vp2 > 0:
        if showbases >0 :
            #new instance of the entire molecule
            new_main_strand = mlab.triangular_mesh(points[:k,0],points[:k,1],points[:k,2],triangles[:l],\
                      scalars=s[:k], colormap="winter") #main strand
            new_comp_strand = mlab.triangular_mesh(points[k:i,0],points[k:i,1],points[k:i,2],triangles[l:j]-triangles[l,0],\
                      scalars=s[k:i], colormap="winter") #complementary
            new_baseframes  = mlab.quiver3d(centres[:,0],centres[:,1],centres[:,2],frames[:,0],frames[:,1],frames[:,2], \
                      mode='arrow',scale_factor=2, colormap="Blues")
            new_main_strand_src = new_main_strand.mlab_source
            new_comp_strand_src = new_comp_strand.mlab_source
            new_baseframes_src  = new_baseframes.mlab_source
        if centerline >0 :
            new_axis = mlab.plot3d(q[:,0],q[:,1],q[:,2],tube_radius=0.05, color=(1,0,1))
            new_axis_src        = new_axis.mlab_source
        vecp = stiffness(m2,1,vp2-1) #chosen eigenvector 2
        #mult = 2.0 #multiple of the added eigenvector
        
        for p in range(precision):
            wmod = ACP(readParameters(),vecp,mult*(p+1)/precision) #modified configuration
            cfmod = calculPoints(wmod) #modified coordinates
            r_p, q_p, d_p, g_p, h_p, sequence = cfmod
            if showbases >0 :
                points_p, triangles_p, centres_p, frames_p, i,j, repere, s = data3d(r_p,d_p,sequence) #modified graphics
                fig.scene.disable_render = True #accelerates rendering
                new_main_strand_src.set(x=points_p[:k,0],y=points_p[:k,1],z=points_p[:k,2])
                new_comp_strand_src.set(x=points_p[k:i,0],y=points_p[k:i,1],z=points_p[k:i,2])
                new_baseframes_src.reset(x=centres_p[:,0],y=centres_p[:,1],z=centres_p[:,2],\
                                   u=frames_p[:,0],v=frames_p[:,1],w=frames_p[:,2])
            if centerline >0 :
                #new_axis_nodes_src.set(x=q_p[:,0],y=q_p[:,1],z=q_p[:,2],scale_factor=0.7,color=(1,0,1))
                new_axis_src.set(x=q_p[:,0],y=q_p[:,1],z=q_p[:,2],tube_radius=0.05, color=(1,0,1))
            fig.scene.disable_render = False
    mlab.orientation_axes()
    mlab.show()
Exemple #43
0
#
# License: BSD (3-clause)

print(__doc__)

import os.path as op

import mne
from mne.datasets import sample

data_path = sample.data_path()
fname = op.join(data_path, 'MEG', 'sample', 'sample_audvis-eeg-oct-6p-fwd.fif')

add_geom = True  # include high resolution source space
src = mne.read_source_spaces(fname, add_geom=add_geom)

# 3D source space (high sampling)
lh_points = src[0]['rr']
lh_faces = src[0]['tris']
rh_points = src[1]['rr']
rh_faces = src[1]['tris']
try:
    from enthought.mayavi import mlab
except:
    from mayavi import mlab
mlab.figure(size=(600, 600), bgcolor=(0, 0, 0))
mlab.triangular_mesh(lh_points[:, 0], lh_points[:, 1], lh_points[:, 2],
                     lh_faces)
mlab.triangular_mesh(rh_points[:, 0], rh_points[:, 1], rh_points[:, 2],
                     rh_faces)
Exemple #44
0
xs = []
ys = []
zs = []
triangles = []
for i, plane in enumerate(planes):
    xs.extend([plane.p0[0], plane.p1[0], plane.p2[0]])
    ys.extend([plane.p0[1], plane.p1[1], plane.p2[1]])
    zs.extend([plane.p0[2], plane.p1[2], plane.p2[2]])
    triangles.append((3*i, 3*i+1, 3*i+2))


p_earth_body = numpy.array([-20000e3,   0,   30000e3])
p_earth_body = numpy.array([-11913349.37481491,   1600513.79810546,   6787847.04879577])
att = [0, 0, 0]

vis, illum, outs = taco.calc_earth_vis(-p_earth_body, att, ngrid=30, to_earth=True, max_reflect=0)

mask_points = (len(outs) // 300) or None
rx = [out[0][0] for out in outs]
ry = [out[0][1] for out in outs]
rz = [out[0][2] for out in outs]
ru = [out[1][0] * (2 if out[3] else 1) for out in outs]
rv = [out[1][1] * (2 if out[3] else 1) for out in outs]
rw = [out[1][2] * (2 if out[3] else 1) for out in outs]

mlab.clf()
mlab.triangular_mesh(xs, ys, zs, triangles, color=(1, 1, 0), opacity=0.9)
mlab.triangular_mesh(xs, ys, zs, triangles, color=(1, .8, 0), representation='wireframe', line_width=4)
mlab.quiver3d(rx, ry, rz, ru, rv, rw, scale_factor=1.0, mask_points=mask_points, vmin=1, vmax=2)
mlab.show()