Example #1
0
def draw_struct():
    fig = mlab.figure()
    r = gen_fe()
    s = gen_spins()
    #view along z-axis
    x = r[:, 0]
    y = r[:, 1]
    z = r[:, 2]
    u = s[:, 0]
    v = s[:, 1]
    w = s[:, 2]

    #print x.shape
    #print y.shape
    #print z.shape
    pts_as = mlab.points3d(x,
                           y,
                           z,
                           color=(0, 0, 1),
                           colormap='gist_rainbow',
                           figure=fig,
                           scale_factor=.1)
    mlab.quiver3d(x, y, z, u, v, w, line_width=3, scale_factor=.3, figure=fig)
    outline = mlab.outline(figure=fig, extent=[0, 1, 0, 1, 0, 1])
    mlab.orientation_axes(figure=fig, xlabel='a', ylabel='b', zlabel='c')
    print 'done'
Example #2
0
def plot_normals(pts, normals, curvature=None):

    x = pts[0, :].A1
    y = pts[1, :].A1
    z = pts[2, :].A1

    u = normals[0, :].A1
    v = normals[1, :].A1
    w = normals[2, :].A1

    if curvature != None:
        #mlab.points3d(x,y,z,curvature,mode='point',scale_factor=1.0)
        mlab.points3d(x,
                      y,
                      z,
                      curvature,
                      mode='sphere',
                      scale_factor=0.1,
                      mask_points=1)
        mlab.colorbar()
    else:
        mlab.points3d(x, y, z, mode='point')
    mlab.quiver3d(x, y, z, u, v, w, mask_points=16, scale_factor=0.1)
    #    mlab.axes()
    mlab.show()
Example #3
0
def show_convection1(new_fig=True):
    x, y, z = np.mgrid[0:1:20j, 0:1:20j, 0:1:20j]
    u, v, w = convection_cell(x, y, z)
    if new_fig:
        mlab.figure(size=(600,600))

    mlab.quiver3d(u, v, w)
    mlab.outline()
Example #4
0
def show_convection1(new_fig=True):
    x, y, z = np.mgrid[0:1:20j, 0:1:20j, 0:1:20j]
    u, v, w = convection_cell(x, y, z)
    if new_fig:
        mlab.figure(size=(600, 600))

    mlab.quiver3d(u, v, w)
    mlab.outline()
def PlotResultsVectorField(results, onSurf=False):
    x, y = np.mgrid[0:512,0:512]
    w = np.zeros((512, 512))
    if onSurf:
        mlab.quiver3d(x, y, results['combineMap'],
                  results['sU'], results['sV'], w)
    else:
        mlab.quiver3d(results['sU'], results['sV'], w)
Example #6
0
def plot_quiver(pts, vecs, color=(0.,1.,0.), arrow_scale = 0.05,
                point_mode='sphere', point_scale=0.002):
    x = pts[0,:].A1
    y = pts[1,:].A1
    z = pts[2,:].A1

    u = vecs[0,:].A1
    v = vecs[1,:].A1
    w = vecs[2,:].A1

    plot_points(pts, mode=point_mode, scale_factor=point_scale)
    mlab.quiver3d(x, y, z, u, v, w, scale_factor=arrow_scale,
                  color=color, scale_mode='vector')
Example #7
0
def graph_plot(x, y, z, start_idx, end_idx, edge_scalars=None, **kwargs):
    """ Show the graph edges using Mayavi

        Parameters
        -----------
        x: ndarray
            x coordinates of the points
        y: ndarray
            y coordinates of the points
        z: ndarray
            z coordinates of the points
        edge_scalars: ndarray, optional
            optional data to give the color of the edges.
        kwargs:
            extra keyword arguments are passed to quiver3d.
    """
    vec = mlab.quiver3d(x[start_idx],
                        y[start_idx],
                        z[start_idx],
                        x[end_idx] - x[start_idx],
                        y[end_idx] - y[start_idx],
                        z[end_idx] - z[start_idx],
                        scalars=edge_scalars,
                        mode='2ddash',
                        scale_factor=1,
                        **kwargs)
    if edge_scalars is not None:
        vec.glyph.color_mode = 'color_by_scalar'
    return vec
Example #8
0
 def plot_orbits3d(self,xaxis='x',yaxis='y',clf=True,**kwargs):
     """
     Plots a 3D plot of the particles and their orbits with mayavi.
     
     :param bool clf: If True, clear figure before plotting.
     
     kwargs are passed into :func:`enthough.mayavi.mlab.plot3d`.
     
     :returns: 
         the result of :func:`enthough.mayavi.mlab.plot3d` and the result of
         :func:`enthough.mayavi.mlab.quiver3d`
     """
     from enthought.mayavi import mlab as M
     
     if clf:
         M.clf()
         
     orbarr = self.getOrbits()[1].transpose((1,2,0))
     t = self._orbt
     
     pntress = []
     for o in orbarr:
         pntress.append(M.plot3d(o[0],o[1],o[2],t,**kwargs))
     
     xp,yp,zp = self.particles.position.T
     vx,vy,vz = self.particles.velocity.T
     quiverres = M.quiver3d(xp,yp,zp,vx,vy,vz)
     
     return pntress,quiverres
Example #9
0
 def __init__(self, objects, t, zscale=1.0, **kwargs):
     """Invokes mlab.quiver3d. Mayavi 2 by Enthought has to be installed
     objects: Either a cmf.node_list or a sequence of cells
     t      : A cmf.Time or a datetime.datetime object
     keywords are passed to mlab.quiver3d
     """
     try:
         from enthought.mayavi import mlab
         from numpy import asarray, meshgrid
     except ImportError:
         raise NotImplementedError(
             "Raster.draw3d needs an installation of mayavi to work")
     if isinstance(objects, cmf.node_list):
         p = objects.get_positions()
         f = objects.get_fluxes3d(t)
     elif isinstance(objects, cmf.project):
         p = cmf.cell_positions(objects.cells)
         f = cmf.cell_fluxes(objects.cells, t)
     elif isinstance(objects[0], cmf.Cell):
         p = cmf.cell_positions(objects)
         f = cmf.cell_fluxes(objects, t)
     else:
         raise ValueError(
             "Given objects are not a nodelist or a sequence of cells")
     self.objects = objects
     self.zscale = zscale
     self.quiver = mlab.quiver3d(p.X, p.Y, p.Z, f.X, f.Y, f.Z * zscale,
                                 **kwargs)
Example #10
0
def graph_plot(x, y, z, start_idx, end_idx, edge_scalars=None, **kwargs):
    """ Show the graph edges using Mayavi

        Parameters
        -----------
        x: ndarray
            x coordinates of the points
        y: ndarray
            y coordinates of the points
        z: ndarray
            z coordinates of the points
        edge_scalars: ndarray, optional
            optional data to give the color of the edges.
        kwargs:
            extra keyword arguments are passed to quiver3d.
    """
    vec = mlab.quiver3d(x[start_idx], 
                        y[start_idx],
                        z[start_idx],
                        x[end_idx] - x[start_idx],
                        y[end_idx] - y[start_idx],
                        z[end_idx] - z[start_idx],
                        scalars=edge_scalars,
                        mode='2ddash', 
                        scale_factor=1,
                        **kwargs)
    if edge_scalars is not None:
        vec.glyph.color_mode = 'color_by_scalar'
    return vec
Example #11
0
def test_quiver3d():
    fig=mlab.figure(fgcolor=(0, 0, 0), bgcolor=(1, 1, 1))
    x, y, z = numpy.mgrid[-2:3, -2:3, -2:3]
    print 'almost'
    #mlab.quiver3d(x, y, z,f, line_width=3, scale_factor=1,figure=fig)

    d=0.2
    x=d*numpy.arange(0,25)
    y=-d*numpy.arange(0,25)
    z=numpy.zeros(len(x))
    if 0:
        func=spiral
    if 1:
        func=amplitude
    mlab.quiver3d(x, y, z,func, line_width=3, scale_factor=1,figure=fig)
    outline=mlab.outline(figure=fig,extent=[-1,1,-1,1,-1,1])
    mlab.orientation_axes(figure=fig,xlabel='a',ylabel='b',zlabel='c')
    print 'done'
Example #12
0
def test_quiver3d():
    fig = mlab.figure(fgcolor=(0, 0, 0), bgcolor=(1, 1, 1))
    x, y, z = numpy.mgrid[-2:3, -2:3, -2:3]
    print 'almost'
    #mlab.quiver3d(x, y, z,f, line_width=3, scale_factor=1,figure=fig)

    d = 0.2
    x = d * numpy.arange(0, 25)
    y = -d * numpy.arange(0, 25)
    z = numpy.zeros(len(x))
    if 0:
        func = spiral
    if 1:
        func = amplitude
    mlab.quiver3d(x, y, z, func, line_width=3, scale_factor=1, figure=fig)
    outline = mlab.outline(figure=fig, extent=[-1, 1, -1, 1, -1, 1])
    mlab.orientation_axes(figure=fig, xlabel='a', ylabel='b', zlabel='c')
    print 'done'
Example #13
0
    def plot3d(self,ix=0,iy=1,iz=2,clf=True):
        """
        Generates a 3-dimensional plot of the data set and principle components
        using mayavi.

        ix, iy, and iz specify which of the input p-dimensions to place on each of
        the x,y,z axes, respectively (0-indexed).
        """
        import enthought.mayavi.mlab as M
        if clf:
            M.clf()
        z3=np.zeros(3)
        v=(self.getEigenvectors()*self.getEigenvalues())
        M.quiver3d(z3,z3,z3,v[ix],v[iy],v[iz],scale_factor=5)
        M.points3d(self.N[:,ix],self.N[:,iy],self.N[:,iz],scale_factor=0.3)
        if self.names:
            M.axes(xlabel=self.names[ix]+'/sigma',ylabel=self.names[iy]+'/sigma',zlabel=self.names[iz]+'/sigma')
        else:
            M.axes()
Example #14
0
    def plot3d(self,ix=0,iy=1,iz=2,clf=True):
        """
        Generates a 3-dimensional plot of the data set and principle components
        using mayavi.

        ix, iy, and iz specify which of the input p-dimensions to place on each of
        the x,y,z axes, respectively (0-indexed).
        """
        import enthought.mayavi.mlab as M
        if clf:
            M.clf()
        z3=np.zeros(3)
        v=(self.getEigenvectors()*self.getEigenvalues())
        M.quiver3d(z3,z3,z3,v[ix],v[iy],v[iz],scale_factor=5)
        M.points3d(self.N[:,ix],self.N[:,iy],self.N[:,iz],scale_factor=0.3)
        if self.names:
            M.axes(xlabel=self.names[ix]+'/sigma',ylabel=self.names[iy]+'/sigma',zlabel=self.names[iz]+'/sigma')
        else:
            M.axes()
Example #15
0
def plot_normals(pts, normals, curvature=None):

    x = pts[0, :].A1
    y = pts[1, :].A1
    z = pts[2, :].A1

    u = normals[0, :].A1
    v = normals[1, :].A1
    w = normals[2, :].A1

    if curvature != None:
        # mlab.points3d(x,y,z,curvature,mode='point',scale_factor=1.0)
        mlab.points3d(x, y, z, curvature, mode="sphere", scale_factor=0.1, mask_points=1)
        mlab.colorbar()
    else:
        mlab.points3d(x, y, z, mode="point")
    mlab.quiver3d(x, y, z, u, v, w, mask_points=16, scale_factor=0.1)
    #    mlab.axes()
    mlab.show()
Example #16
0
    def do(self):
        ############################################################
        # Imports.
        from enthought.mayavi import mlab
              
        ############################################################
        # Create a new scene and set up the visualization.
        s = self.new_scene()

        ############################################################
        # run all the "test_foobar" functions in the mlab module.
        for name, func in getmembers(mlab):
            if not callable(func) or not name[:4] in ('test', 'Test'):
                continue
            mlab.clf()
            func()
            # Mayavi has become too fast: the operator cannot see if the
            # Test function was succesful.
            sleep(0.1)
     
        ############################################################
        # Test some specific corner-cases
        import numpy
        x, y, z = numpy.mgrid[1:10, 1:10, 1:10]
        u, v, w = numpy.mgrid[1:10, 1:10, 1:10]
        s = numpy.sqrt(u**2 + v**2)
        
        mlab.clf()
        # Test the extra argument "scalars"
        mlab.quiver3d(x, y, z, u, v, w, scalars=s)

        # Test surf with strange-shaped inputs
        X, Y = numpy.ogrid[-10:10, -10:10]
        Z = X**2 + Y**2
        mlab.surf(X, Y, Z)
        mlab.surf(X.ravel(), Y.ravel(), Z)

        x, y, z = numpy.mgrid[-10:10, -10:10, -3:2]
        mlab.flow(x, y, z)

        # Test glyphs with number-only coordinnates
        mlab.points3d(0, 0, 0, resolution=50)
Example #17
0
def draw_struct():
    fig=mlab.figure()
    r=gen_fe()
    s=gen_spins()
    #view along z-axis
    x=r[:,0]
    y=r[:,1]
    z=r[:,2]
    u=s[:,0]
    v=s[:,1]
    w=s[:,2]

    #print x.shape
    #print y.shape
    #print z.shape
    pts_as=mlab.points3d(x,y,z,color=(0,0,1),colormap='gist_rainbow',figure=fig,scale_factor=.1)
    mlab.quiver3d(x, y, z,u,v,w, line_width=3, scale_factor=.3,figure=fig)
    outline=mlab.outline(figure=fig,extent=[0,1,0,1,0,1])
    mlab.orientation_axes(figure=fig,xlabel='a',ylabel='b',zlabel='c')
    print 'done'
def plot_normals(pts, normals, curvature=None, mask_points=1,
                 color=(0.,1.,0.), scale_factor = 0.1):
    x = pts[0,:].A1
    y = pts[1,:].A1
    z = pts[2,:].A1

    u = normals[0,:].A1
    v = normals[1,:].A1
    w = normals[2,:].A1

    if curvature != None:
        curvature = np.array(curvature)
        #idxs = np.where(curvature>0.03)
        #mlab.points3d(x[idxs],y[idxs],z[idxs],curvature[idxs],mode='sphere',scale_factor=0.1,mask_points=1)
        mlab.points3d(x,y,z,curvature,mode='sphere',scale_factor=0.1,mask_points=1, color=color)
#        mlab.points3d(x,y,z,mode='point')
        mlab.colorbar()
    else:
        mlab.points3d(x,y,z,mode='point')
    mlab.quiver3d(x, y, z, u, v, w, mask_points=mask_points,
                  scale_factor=scale_factor, color=color)
Example #19
0
def efield(name, sources, grid):
    X, Y, Z = grid
    Ex, Ey, Ez = (zeros_like(X), zeros_like(Y), zeros_like(Z))
    for source in sources:
        (Xp, Yp, Zp), q = source
        if q < 0e0:
            color = (0,0,1)
        else:
            color = (1,0,0)
        mlab.points3d(Xp, Yp, Zp, color=color, scale_factor=q)
        Xs, Ys, Zs = (X - Xp, Y - Yp, Z - Zp)
        rminus3half = (Xs*Xs + Ys*Ys + Zs*Zs)**(-1.5e0)
        #~ rminus3half[isnan(rminus3half)] = 0
        Ex += q * rminus3half * Xs
        Ey += q * rminus3half * Ys
        Ez += q * rminus3half * Zs
    #  Run isnan on the data after adding all of the field contributions
    Xs[isnan(Xs)] = 0
    Ys[isnan(Ys)] = 0
    Zs[isnan(Zs)] = 0
    mlab.quiver3d(X, Y, Z, Ex, Ey, Ez, line_width=2, scale_factor=1)
    mlab.show()
def plot_normals(pts,
                 normals,
                 curvature=None,
                 mask_points=1,
                 color=(0., 1., 0.),
                 scale_factor=0.1):
    x = pts[0, :].A1
    y = pts[1, :].A1
    z = pts[2, :].A1

    u = normals[0, :].A1
    v = normals[1, :].A1
    w = normals[2, :].A1

    if curvature != None:
        curvature = np.array(curvature)
        #idxs = np.where(curvature>0.03)
        #mlab.points3d(x[idxs],y[idxs],z[idxs],curvature[idxs],mode='sphere',scale_factor=0.1,mask_points=1)
        mlab.points3d(x,
                      y,
                      z,
                      curvature,
                      mode='sphere',
                      scale_factor=0.1,
                      mask_points=1,
                      color=color)
        #        mlab.points3d(x,y,z,mode='point')
        mlab.colorbar()
    else:
        mlab.points3d(x, y, z, mode='point')
    mlab.quiver3d(x,
                  y,
                  z,
                  u,
                  v,
                  w,
                  mask_points=mask_points,
                  scale_factor=scale_factor,
                  color=color)
def viz_BARY(data, j_data, file_name=None, labels=None, size=(600, 600)):
    u"""Visualizes the barycenters of the electron density difference (for visualizing dipole moments).

	** Parameters **
	  data : tuple(numpy.ndarray((3,N)), numpy.ndarray((3,N)))
	Pair of column-major matrices containing the coordinates of the positive and negative barycenters, in that order.
	  j_data : dict
	Data on the molecule, as deserialized from the scanlog format.
	  file_name : str, optional
	Base name of the files in which to save the images.
	  labels : list(str), optional
	Labels to append to `file_name` for each datum in `data`. If None, the position of the datum is appended.
	  size : tuple(int, int), optional
	The size of the image to save.

	** Returns **
	  figure : mayavi.core.scene.Scene
	The MayaVi scene containing the visualization.
	"""

    figure = _init_scene(j_data)[0]

    for i, D in enumerate(data):
        #Pp = mlab.points3d(D[0][0], D[0][1], D[0][2], figure=figure, mode='axes', scale_factor=0.3, color=(0.0, 0.5, 0.5))
        #Pm = mlab.points3d(D[1][0], D[1][1], D[1][2], figure=figure, mode='axes', scale_factor=0.3, color=(0.95, 0.95, 0.95))

        ## Chemistry convention (from negative to positive)
        Mu = mlab.quiver3d(D[1][0],
                           D[1][1],
                           D[1][2],
                           D[0][0] - D[1][0],
                           D[0][1] - D[1][1],
                           D[0][2] - D[1][2],
                           figure=figure,
                           mode='arrow',
                           scale_factor=1.0,
                           color=(0.0, 0.5, 0.5))

        if file_name is not None:
            mlab.savefig("{}-BARY-{}.png".format(
                file_name, labels[i] if labels is not None else i),
                         figure=figure,
                         size=size)

        #Pp.remove()
        #Pm.remove()

        Mu.remove()

    return figure
Example #22
0
def plot_quiver(pts,
                vecs,
                color=(0., 1., 0.),
                arrow_scale=0.05,
                point_mode='sphere',
                point_scale=0.002):
    x = pts[0, :].A1
    y = pts[1, :].A1
    z = pts[2, :].A1

    u = vecs[0, :].A1
    v = vecs[1, :].A1
    w = vecs[2, :].A1

    plot_points(pts, mode=point_mode, scale_factor=point_scale)
    mlab.quiver3d(x,
                  y,
                  z,
                  u,
                  v,
                  w,
                  scale_factor=arrow_scale,
                  color=color,
                  scale_mode='vector')
def bfield():
    x = linspace(0, 2*np.pi, 15)
    rho = linspace(1, 2.5, 3)
    rhogrid, phigrid = meshgrid(rho, phi)
    x = rhogrid * np.cos(phigrid)
    y = rhogrid * np.sin(phigrid)
    z = np.zeros_like(x)
    #  phihat = -sin(phi)*xhat + cos(phi)*yhat = -y/rho*xhat + x/rho*yhat
    #  Be careful when you divide by zero as the eps graphic will be corrupted
    u = -y / rhogrid; u[np.isnan(u)] = 0
    v =  x / rhogrid; v[np.isnan(v)] = 0
    w = np.zeros_like(z)
    obj = quiver3d(x, y, z, u, v, w, line_width=3, scale_factor=0.3)
#    outline()
    return obj
Example #24
0
def plotThisThing(state, proc):
    react = sData.getInitReactant(state)
    prod = sData.getInitReactant(proc)
    #react, prod = sData.getReacProd(state,proc)
    cn = ChangingNeighbors(react, prod, cutoffs)


    ln = cn.nrValues(cn.lostNeighbors)
    indxs = np.where(ln > 0)
    ln = ln[indxs]
    pos = react.get_positions()[indxs]
    t = react.get_atomic_numbers()[indxs]
    pts = mlab.quiver3d(pos[:,0], pos[:,1], pos[:,2],t,t,t,scalars=ln, mode='sphere')

    pts.glyph.color_mode = 'color_by_scalar'
    pts.glyph.glyph_source.glyph_source.center = [0,0,0]

    indx2 = np.setdiff1d(np.array(range(prod.get_number_of_atoms())),indxs[0])
    p = react.get_positions()[indx2]
    t2 = react.get_atomic_numbers()[indx2]
    pt = mlab.quiver3d(p[:,0],p[:,1],p[:,2],t2,t2,t2, opacity=.06, mode='sphere')
    
    mlab.figure()
    
    ln = cn.nrValues(cn.newNeighbors)
    indxs = np.where(ln > 0)
    ln = ln[indxs]
    pos = react.get_positions()[indxs]
    t = react.get_atomic_numbers()[indxs]
    pts = mlab.quiver3d(pos[:,0], pos[:,1], pos[:,2],t,t,t,scalars=ln, mode='sphere')

    pts.glyph.color_mode = 'color_by_scalar'
    pts.glyph.glyph_source.glyph_source.center = [0,0,0]

    indx2 = np.setdiff1d(np.array(range(prod.get_number_of_atoms())),indxs[0])
    p = react.get_positions()[indx2]
    t2 = react.get_atomic_numbers()[indx2]
    pt = mlab.quiver3d(p[:,0],p[:,1],p[:,2],t2,t2,t2, opacity=.06, mode='sphere')
    
    mlab.figure()
    
    ln = cn.nrValues(cn.lostNeighbors) + cn.nrValues(cn.newNeighbors)
    indxs = np.where(ln > 0)
    ln = ln[indxs]
    pos = react.get_positions()[indxs]
    t = react.get_atomic_numbers()[indxs]
    pts = mlab.quiver3d(pos[:,0], pos[:,1], pos[:,2],t,t,t,scalars=ln, mode='sphere')

    pts.glyph.color_mode = 'color_by_scalar'
    pts.glyph.glyph_source.glyph_source.center = [0,0,0]

    indx2 = np.setdiff1d(np.array(range(prod.get_number_of_atoms())),indxs[0])
    p = react.get_positions()[indx2]
    t2 = react.get_atomic_numbers()[indx2]
    pt = mlab.quiver3d(p[:,0],p[:,1],p[:,2],t2,t2,t2, opacity=.06, mode='sphere')
Example #25
0
def add_arrows(at,
               arrows,
               arrow_colour=(0, 0, 0),
               arrow_scale_factor=1.0,
               clf=True):
    pos = np.array(at.pos)
    arrows = np.array(arrows)
    return mlab.quiver3d(pos[0, :],
                         pos[1, :],
                         pos[2, :],
                         arrows[0, :],
                         arrows[1, :],
                         arrows[2, :],
                         scale_factor=arrow_scale_factor,
                         color=arrow_colour,
                         name='arrows')
Example #26
0
 def plot_velocities3d(self,clf=True,**kwargs):
     """
     Plots the particle velocities in a 3d projection with mayavi.
     
     :param bool clf: If True, clear figure before plotting.
         
     kwargs are passed into :func:`enthought.mayavi.mlab.quiver3d`.
     
     :returns: The result of the plotting command
     """
     from enthought.mayavi import mlab as M
     
     if clf:
         M.clf()
         
     args = list(self._pos.T)
     args.extend(list(self._vel.T))
     
     return M.quiver3d(*args,**kwargs)
Example #27
0
def add_balls(at,
              colours=None,
              colorbar=False,
              atom_scale_factor=1.0,
              vmin=None,
              vmax=None):

    r = np.array([quippy.ElementCovRad[z] for z in at.z])

    if colours is None:
        scalars = at.z
        vmin = 0
        vmax = 110
    else:
        scalars = colours

    pts = mlab.quiver3d(at.pos[1, :],
                        at.pos[2, :],
                        at.pos[3, :],
                        r, [0] * len(r), [0] * len(r),
                        scale_factor=atom_scale_factor,
                        scale_mode='vector',
                        scalars=scalars,
                        mode='sphere',
                        name='balls',
                        vmin=vmin,
                        vmax=vmax)

    pts.glyph.color_mode = 'color_by_scalar'
    #pts.glyph.glyph.scale_mode = 'scale_by_vector'
    pts.glyph.glyph_source.glyph_source.center = [0, 0, 0]

    if colours is None:
        pts.module_manager.scalar_lut_manager.lut.table = atom_colours_lut

    if colorbar: mlab.colorbar()

    return pts
Example #28
0
def plot_axis(x, y, z, directions):
    from enthought.mayavi import mlab
    mlab.quiver3d(x,
                  y,
                  z, [directions[0, 0]], [directions[1, 0]],
                  [directions[2, 0]],
                  scale_factor=1,
                  color=(1, 0, 0))
    if directions.shape[1] > 1:
        mlab.quiver3d(x,
                      y,
                      z, [directions[0, 1]], [directions[1, 1]],
                      [directions[2, 1]],
                      scale_factor=1,
                      color=(0, 1, 0))
        mlab.quiver3d(x,
                      y,
                      z, [directions[0, 2]], [directions[1, 2]],
                      [directions[2, 2]],
                      scale_factor=1,
                      color=(0, 0, 1))
b /= norm

mlab.figure(1, bgcolor=(1, 1, 1), fgcolor=(0, 0, 0))
mlab.clf()
pts = mlab.points3d(a, b, c, density, colormap='jet', mode='2dvertex')
mlab.outline(extent=[-3*a.std(), 3*a.std(), -3*b.std(), 3*b.std(),
                     -3*c.std(), 3*c.std()], line_width=2)

Y = np.c_[a, b, c]
U, pca_score, V = np.linalg.svd(Y, full_matrices=False)
x_pca_axis, y_pca_axis, z_pca_axis = V.T*pca_score/pca_score.min()

mlab.view(-20.8, 83, 9, [0.18, 0.2, -0.24])
#mlab.savefig('pca_3d.jpg')
mlab.quiver3d(0.1*x_pca_axis, 0.1*y_pca_axis, 0.1*z_pca_axis,
                2*x_pca_axis, 2*y_pca_axis, 2*z_pca_axis,
                color=(0.6, 0, 0), line_width=2)

x_pca_axis, y_pca_axis, z_pca_axis = 3*V.T
x_pca_plane = np.r_[x_pca_axis[:2], - x_pca_axis[1::-1]]
y_pca_plane = np.r_[y_pca_axis[:2], - y_pca_axis[1::-1]]
z_pca_plane = np.r_[z_pca_axis[:2], - z_pca_axis[1::-1]]

x_pca_plane.shape = (2, 2)
y_pca_plane.shape = (2, 2)
z_pca_plane.shape = (2, 2)

mlab.mesh(x_pca_plane, y_pca_plane, z_pca_plane, color=(0.6, 0, 0),
            opacity=0.1)
mlab.mesh(x_pca_plane, y_pca_plane, z_pca_plane, color=(0.6, 0, 0),
            representation='wireframe', line_width=3, opacity=0.3)
Example #30
0
display.display(grid.get_grid())

# Choose the molecular orbitals to be calculated
selected_MO = ['1.1_a', '1.5_a']
qc.mo_spec = read.mo_select(qc.mo_spec, selected_MO, strict=True)['mo_spec']

# Calculate molecular orbitals
mo_list = core.rho_compute(qc,
                           calc_mo=True,
                           slice_length=slice_length,
                           drv=None,
                           numproc=numproc)

# Calculate analytic derivatives of molecular orbitals
mo_list_drv = core.rho_compute(qc,
                               calc_mo=True,
                               slice_length=slice_length,
                               drv='xyz',
                               numproc=numproc)

# Calculate Transition Electronic Flux Densities (time independent)

# Calculate the STEFD [in units of (i E_h/(hbar a_0^2))]
j_stefd = -0.5 * (mo_list[numpy.newaxis, 0] * mo_list_drv[:, 1] -
                  mo_list[numpy.newaxis, 1] * mo_list_drv[:, 0])

Z, Y, X = output.meshgrid2(*grid.tolist()[::-1])

mlab.quiver3d(X, Y, Z, *j_stefd)
mlab.show()
Example #31
0
def animate(coords, mass, dipole, temp, F, cycles, w0=None, max_tstep=100000, no_anim=True):
    """
    UNITS:
    coords    angstrom
    mass      amu
    t         ps
    dipole    e * angstrom
    temp      kelvin 
    F         amu * angstrom / ps**2.0 / e
    """

    cm_coords = coords - tile(center_of_mass(coords, mass), (coords.shape[0], 1))

    mol_I, mol_Ix = eig(inertia_tensor(cm_coords, mass))
    mol_I.sort()

    print "principal moments of inertia"
    print mol_I

    q0, w0 = initial_cond(coords, mass, dipole, temp, F)

    print "initial conditions"
    print " q0 = ", q0, " norm(q0) = ", norm(q0)
    print " w0 = ", w0, " norm(w0) = ", norm(w0)

    # q0 = array([0., 0., 1., 0.])
    # w0 = array([0.,1.,0.], dtype=float)

    print "time in picoseconds"

    # t0 = 2.0 * pi / norm(w0) * cycles[0]
    # t1 = t0 + 2.0 * pi / norm(w0) * cycles[1]
    # t2 = t1 + 2.0 * pi / norm(w0) * cycles[2]

    t0 = cycles[0]
    t1 = t0 + cycles[1]
    t2 = t1 + cycles[2]

    print "t0 = ", t0
    print "t1 = ", t1
    print "t2 = ", t2
    print "total time = ", t0 + t1 + t2

    print "integrating motion of rotor"

    qt = ar.asym_rotor(t0, t1, t2, max_tstep, r_[q0, w0], F, dipole, mol_I)

    print "qt.shape = ", qt.shape

    # now extract the orientation quaternions
    tsr = qt[:, 0]
    qtr = qt[:, 1:5]
    wtr = qt[:, 5:8]

    # diagnostic plots

    # field in rk time steps
    ft = zeros(len(tsr))
    ft[tsr < t0] = 0.0
    ft[(tsr > t0) * (tsr < t1)] = F * tsr / (t1 - t0)
    ft[tsr > t1] = F

    fp = pylab.figure(figsize=(3, 4))

    # total energy
    pylab.subplot(4, 1, 1)
    pylab.plot(tsr, array([total_energy(qt[i, :], ft[i], dipole, mol_I) for i in xrange(len(tsr))]))
    pylab.title("Total Energy")

    # angular momentum
    pylab.subplot(4, 1, 2)
    L = r_[[angular_momentum(qt[i, :], ft[i], dipole, mol_I) for i in xrange(len(tsr))]]

    print "L.shape = ", L.shape
    # pylab.plot(tsr, array([norm(L[i,:]) for i in xrange(len(tsr))]), 'r-')
    pylab.plot(tsr, array([L[i, 0] for i in xrange(len(tsr))]), "b-")
    pylab.plot(tsr, array([L[i, 1] for i in xrange(len(tsr))]), "g-")
    pylab.plot(tsr, array([L[i, 2] for i in xrange(len(tsr))]), "r-")
    pylab.title("Angular Momentum")

    # dipole projection
    pylab.subplot(4, 1, 3)
    dp = array([dipole_projection(qt[i, :], ft[i], dipole, mol_I) for i in xrange(len(tsr))])
    dpavg = cumsum(dp) / (arange(len(dp)) + 1.0)
    pylab.plot(tsr, dpavg)

    pylab.title("Projected Dipole (polarization)")

    # field strength
    pylab.subplot(4, 1, 4)
    pylab.plot(tsr, ft)
    pylab.title("Field Strength")

    pylab.subplots_adjust(hspace=0.95)

    pylab.show()

    if no_anim:
        return

        # frame rate is 10 ps to 1 s
    frames = floor(t2 / 10 * 30)
    print "total time is ", t2, " rendering ", frames, " frames"
    ts, qt = interpolate_quat(tsr, qtr, frames)

    # field
    ft = zeros(len(ts))
    ft[ts < t0] = 0.0
    ft[(ts > t0) * (ts < t1)] = F * ts / (t1 - t0)
    ft[ts > t1] = F

    # render the molecule
    f = mlab.figure(size=(500, 500), bgcolor=(1, 1, 1), fgcolor=(0, 0, 0))
    # # draw the molecule
    molecule = mlab.points3d(
        cm_coords[:, 0], cm_coords[:, 1], cm_coords[:, 2], scale_factor=2, color=(1, 1, 0), resolution=20
    )
    # and the dipole moment
    dip = mlab.quiver3d(
        [0], [0], [0], [dipole[0]], [dipole[1]], [dipole[2]], scale_factor=1, line_width=2.0, color=(0, 1, 0)
    )

    mlab.view(distance=45.0)

    # timelab = mlab.text(0.1, 0.9, 'Time: 0 ps', width=0.4)
    # fieldlab = mlab.text(0.5, 0.9, 'Field: 0 kV/cm', width=0.4)

    ms = molecule.mlab_source
    dms = dip.mlab_source
    for t, fi, q in zip(ts, ft, qt):
        # timelab.text = "Time: %d ps" % t
        # fieldlab.text = "Field: %f" % fi
        M = q_to_rotmatrix(q)
        cp = dot(cm_coords, M)
        dp = dot(dipole, M) * 12.0
        ms.set(x=cp[:, 0], y=cp[:, 1], z=cp[:, 2])
        dms.set(u=[dp[0]], v=[dp[1]], w=[dp[2]])
Example #32
0
    my_x = coords_plot[0][0]
    my_y = coords_plot[0][1]
    my_z = vel_n
    lw = 5

    # Plot the black crosses first ...
    mlab.points3d([my_x], [my_y], [my_z], [1.0],
                  color=(0, 0, 0),
                  mode='axes',
                  scale_factor=sphere_size)

    # ... and a sphere at the same location.
    mlab.quiver3d([my_x], [my_y - sphere_size / 4.], [my_z], [0], [1], [0],
                  scalars=[1],
                  scale_factor=sphere_size / 2.,
                  scale_mode='scalar',
                  mode='sphere',
                  line_width=lw * 0.75,
                  name=gal,
                  color=gals[gal]['col'])

    # Finally, add the galaxy name as 3D text.
    #mlab.text3d(my_x,my_y,my_z,'HCG91'+gal[-1],scale=20,color = (0,0,0))
    mlab.text(my_x,
              my_y,
              'HCG91' + gal[-1],
              color=(0, 0, 0),
              z=my_z,
              width=0.1)

# Next, add peculiar HII regions of interest inside HCG 91c
# (See Vogt+, MNRAS (2015) for details)
                     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',
                        colormap='RdBu')
# revert colormap
dipoles.module_manager.scalar_lut_manager.reverse_lut = True
mlab.colorbar(dipoles, title='Dipole fit time (ms)')

# proper 3D orientation
mlab.get_engine().scenes[0].scene.x_plus_view()
Example #34
0
J_x_temp = J_temp[:, 0]
J_y_temp = J_temp[:, 1]
J_z_temp = J_temp[:, 2]

J_x = reshape(J_x_temp, u2.shape)
J_y = reshape(J_y_temp, u2.shape)
J_z = reshape(J_z_temp, u2.shape)

#==============================================================================
# Plotting current vectors
#==============================================================================

#mlab.options.backend = 'envisage'         # one way to save visualization
#f = mlab.figure()
c1 = mlab.points3d(0, 0, 0)
mlab.quiver3d(x, y, z2, J_x, J_y, J_z, colormap="jet", scale_factor=1)

#==============================================================================
# Plotting actual ***boids
#==============================================================================

if (eps1 == 1):

    s2 = mlab.mesh(x, y, z2, colormap="gray", transparent=True)
#    mlab.quiver3d(x, y, z2, u2, v2, w2, scale_factor=1)
else:

    #    sr = mlab.mesh(x_r, y_r, z_r, colormap="gray", transparent=True)

    s2 = mlab.mesh(x, y, z2, colormap="gray", transparent=True)
#    mlab.quiver3d(x, y, z2, u2, v2, w2,colormap="gray",transparent=True, scale_factor=1)
Example #35
0
def genvec(vec,fig,color=None):
    vmag=np.sqrt(vec[0]**2+vec[1]**2+vec[2]**2); vec=vec/vmag
    u=[vec[0]];v=[vec[1]];w=[vec[2]]
    mlab.quiver3d([0],[0],[0],u,v,w,line_width=3, scale_factor=1,figure=fig,color=color)
Example #36
0
                       0,
                       0,
                       scale_mode='none',
                       scale_factor=2,
                       color=tango.aluminum3,
                       resolution=50,
                       opacity=0.7,
                       name='Poincare')
sphere.actor.property.specular = 0.45
sphere.actor.property.specular_power = 5
sphere.actor.property.backface_culling = True

# Display Cartesian axes
mlab.points3d((0, 0), (0, 0), (0, 0), mode='axes', scale_factor=1.2)  # axes
mlab.quiver3d(*itertools.chain(rotations([1.2, 0, 0]), rotations([1, 0, 0])),
              color=tango.black,
              mode='arrow',
              scale_factor=0.1)  # axes arrows

# Display great circles
t = N.linspace(0, 2 * N.pi, 100, endpoint=True)
for coords in rotations([N.cos(t), N.sin(t), N.zeros_like(t)]):
    mlab.plot3d(*coords, tube_radius=None)

# Plotting parameters
plots = zip(
    ['D', 'A', 'R', 'L'],  # polarization
    [(0, 1, 0), (0, -1, 0), (0, 0, 1), (0, 0, -1)],  # incident stokes vector
    ['butter3', 'chameleon3', 'skyblue3', 'scarletred3'],  # colors
    [1, 1, 1, 1],  # E_TM
    [1, 1, 1, 1],  # E_TE
    [0, N.pi, N.pi / 2, -N.pi / 2],  # psi
Example #37
0
    lw = 5
    
    # Plot the black crosses first ...
    mlab.points3d([my_x],[my_y],
                [my_z],[1.0],
                color=(0,0,0),
                mode = 'axes',
                scale_factor= sphere_size)

    # ... and a sphere at the same location.                    
    mlab.quiver3d([my_x],
                  [my_y - sphere_size/4.],
                  [my_z],
                  [0],[1],[0],
                  scalars = [1],
                  scale_factor = sphere_size/2.,
                  scale_mode = 'scalar',
                  mode = 'sphere',
                  line_width = lw*0.75,
                  name = gal,
                  color=gals[gal]['col'])
                  
    # Finally, add the galaxy name as 3D text.             
    #mlab.text3d(my_x,my_y,my_z,'HCG91'+gal[-1],scale=20,color = (0,0,0))        
    mlab.text(my_x,my_y,'HCG91'+gal[-1],color=(0,0,0),z=my_z,width=0.1) 
                 
# Next, add peculiar HII regions of interest inside HCG 91c
# (See Vogt+, MNRAS (2015) for details)

# First, compute their coordinates                
coords_91c = [[ratodeg(gals['hcg91c']['ra']), 
Example #38
0
mos = orbkit.run_orbkit()

# Write a npz file with all the ouput
orbkit.output.main_output(mos, outputname='h2o_MO', otype='npz')

# plot derivative
x = orbkit.grid.x
y = orbkit.grid.y
z = orbkit.grid.z

# test if mayavi exists and possibly plot
maya = False
try:
    from enthought.mayavi import mlab
    maya = True
except ImportError:
    pass
try:
    from mayavi import mlab
    maya = True
except Exception:
    pass

if maya == False:
    print('mayavi module could not be loaded and vector field cannot be shown')
else:
    mo_num = 3
    mlab.quiver3d(x,y,z,mos[1,mo_num,:],mos[2,mo_num,:],\
                    mos[3,mo_num,:],line_width=1.5,scale_factor=0.1)
    mlab.show()
Example #39
0
                                       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()
# 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.0,
    scale_factor=4e-4,
    scalars=time,
    mode="cone",
    colormap="RdBu",
)
# revert colormap
dipoles.module_manager.scalar_lut_manager.reverse_lut = True
mlab.colorbar(dipoles, title="Dipole fit time (ms)")

# proper 3D orientation
mlab.get_engine().scenes[0].scene.x_plus_view()
Example #41
0
 def renderSnapshot(self, t):
     px,py,pz,vx,vy,vz = self._generateDataVector(t)
     return mlab.quiver3d(px,py,pz,vx,vy,vz, scale_factor=1,
             *self._mlab_args, **self._mlab_kwargs).mlab_source
Example #42
0
    mlab.clf()
    points = mlab.points3d(xyz[:, 0],
                           xyz[:, 1],
                           xyz[:, 2], [v for v in g],
                           scale_factor=0.1,
                           scale_mode='none',
                           colormap='summer',
                           resolution=20)
    print points
    edge_start = []
    edge_end = []
    for edge in g.edges():
        edge_start.append(pos[edge[0]])
        edge_end.append(pos[edge[1]])

    edge_start = np.array(edge_start)
    edge_end = np.array(edge_end)
    components = edge_end - edge_start
    mlab.quiver3d(edge_start[:, 0],
                  edge_start[:, 1],
                  edge_start[:, 2],
                  components[:, 0],
                  components[:, 1],
                  components[:, 2],
                  scale_factor=0.1)
    mlab.show()
    print xyz

#
# test_mayavi.py ends here
Example #43
0
    append='/',  # where to append in file
    data_only=True,  # do not include grid, structure, and MO data
    is_mo_output=False,
    mo_spec=mo['mo_spec'])

# plot derivative
x = ok.grid.x
y = ok.grid.y
z = ok.grid.z

# test if mayavi exists and possibly plot
maya = False
try:
    from enthought.mayavi import mlab
    maya = True
except ImportError:
    pass
try:
    from mayavi import mlab
    maya = True
except Exception:
    pass

if maya == False:
    print('mayavi module could not be loaded and vector field cannot be shown')
else:
    mo_num = 3
    mlab.quiver3d(x,y,z,delta_mo_list[0,mo_num,:],delta_mo_list[1,mo_num,:],\
                    delta_mo_list[2,mo_num,:],line_width=1.5,scale_factor=0.1)
    mlab.show()
Example #44
0
def ip_format(
    a,
    b,
    A,
    gamma=np.pi / 2,
    plot=False,
    color="b",
    linewidth=1,
    linestyle="-",
    alpha=1,
    show=True,
    stem=False,
    stemline="g--",
    stemmarker="ro",
    mayavi_app=False,
):
    r"""
    Function to generate the 'Arraytool' input format.

    :param a:          separation between elements along the x-axis in wavelengths
    :param b:          separation between elements along the y-axis in wavelengths
    :param A:          visual excitation matrix
    :param gamma:      lattice angle in radians
    :param plot:       if True, produces a 2D/3D plot of the array excitation
    :param stem:       if True, the array excitation is plotted as 'stem plot'
    :param mayavi_app: if True, the 3D plot will be opened in the MayaVi application
    
    All other parameters are nothing but the 'Matplotlib' parameters. These
    should be familiar to 'Matlab' or 'Matplotlib' users.
    
    :rtype:            array_ip, a Numpy array of size (Number_elements(A)*4)
    """
    M = float(A.shape[1])  # no. of elements along the x-axis
    N = float(A.shape[0])  # no. of elements along the y-axis
    if M == 1:  # i.e, linear array is along the y-direction
        a = 0
        gamma = np.pi / 2
    if N == 1:  # i.e, linear array is along the x-direction
        b = 0
        gamma = np.pi / 2
    xlim = (M * a) / 2  # array is with in the x-limits [-xlim, +xlim]

    # Grid generation
    [x, y] = np.mgrid[0:M, 0:N]
    x = (x - (M - 1) / 2).T
    y = np.flipud((y - (N - 1) / 2).T)
    x = x * a
    y = y * b  # rectangular grid is generated

    # modifying the rect-grid according to the given lattice angle 'gamma'
    if gamma != np.pi / 2:
        x = x + (y / np.tan(gamma)) % a

    # Adjusting the rows so that the array lies within [-xlim, +xlim]
    for i1 in range(int(N)):
        if x[i1, 0] < -xlim:
            x[i1, :] = x[i1, :] + a  # RIGHT shifting the row by 'a'
        if x[i1, -1] > xlim:
            x[i1, :] = x[i1, :] - a  # LEFT shifting the row by 'a'

    # Finally, arranging all the data into 'Arraytool' input format
    x = np.reshape(x, (M * N, -1))
    y = np.reshape(y, (M * N, -1))
    z = np.zeros_like(x)  # because only planar arrays are permitted here
    A = np.reshape(A, (M * N, -1))
    array_ip = np.hstack((x, y, z, A))  # finally, 'Arraytool' input format

    # plotting the 'absolute' value of the array excitation (2D/3D)
    if plot:
        # checking whether 'A' has any imaginary values
        if (A.imag > 1e-10).sum():
            A_plt = abs(A)  # if A.imag are significant, then '|A|' will be plotted
        else:
            A_plt = A.real  # if A.imag are negligible, then 'A'  will be plotted
        if M == 1:  # i.e, linear array is along the y-direction
            plt.plot(y, A_plt, color=color, linewidth=linewidth, linestyle=linestyle, alpha=alpha)
            if stem:
                plt.stem(y, A_plt, linefmt=stemline, markerfmt=stemmarker)
            plt.axis("tight")
            plt.grid(True)
            plt.xlabel(r"$y$", fontsize=16)
            plt.ylabel(r"$\left|A_{n}\right|$", fontsize=16)
            if show:
                plt.title(r"$\mathrm{Array}\ \mathrm{Excitation}$", fontsize=18)
                plt.show()
        elif N == 1:  # i.e, linear array is along the x-direction
            plt.plot(x, A_plt, color=color, linewidth=linewidth, linestyle=linestyle, alpha=alpha)
            if stem:
                plt.stem(x, A_plt, linefmt=stemline, markerfmt=stemmarker)
            plt.axis("tight")
            plt.grid(True)
            plt.xlabel(r"$x$", fontsize=16)
            plt.ylabel(r"$\left|A_{m}\right|$", fontsize=16)
            if show:
                plt.title(r"$\mathrm{Array}\ \mathrm{Excitation}$", fontsize=18)
                plt.show()
        else:
            if mayavi_app:  # this option opens the 3D plot in MayaVi Application
                mlab.options.backend = "envisage"
            s1 = mlab.quiver3d(x, y, z, z, z, A_plt)  # stem3D representation
            ranges1 = [x.min(), x.max(), y.min(), y.max(), A_plt.min(), A_plt.max()]
            mlab.axes(xlabel="x", ylabel="y", zlabel="Amn", ranges=ranges1, nb_labels=3)
            mlab.colorbar(orientation="vertical", nb_labels=5)
            s1.scene.isometric_view()
            if show:
                mlab.show()
    return array_ip
Example #45
0
right_ys = []

for line in data:
    cm = line.split()
    top_xs.append(float(cm[0]))
    left_zs.append(float(cm[2]))
    right_ys.append(float(cm[1]))

    dms.append(float(cm[9]))

# diameters
mlab.options.offscreen = True

mlab.figure(1, bgcolor=(1, 1, 1), size=(1280, 720))
dms = [x / 2.0 for x in dms]
q = mlab.quiver3d(top_xs, right_ys, left_zs, dms, dms, dms, mode='sphere', scale_factor=1)
mlab.orientation_axes()
mlab.outline(color=(0,0,0), line_width=1.0)
a = mlab.axes(color=(0.1,0.1,0.1), nb_labels=3, line_width=1.0)
a.axes.axis_label_text_property.color = (0,0,0)

q.scene.isometric_view()

count = 1
while count < 360:
    q.scene.camera.azimuth(1)
    mlab.draw()
    mlab.savefig('animate/' + stage + '-dms-animated-' + str(count).zfill(3) + '.png')
    count += 1
    print(count)
Example #46
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()
Example #47
0
mlab.points3d(ecog_electrodes[[ecog_chan_idx],0],
              ecog_electrodes[[ecog_chan_idx],1],
              ecog_electrodes[[ecog_chan_idx],2],
              opacity=0.5, scale_factor=8, color=(1,0,0))

###############################################################################
# MEG leadfield
mlab.figure(3)
mlab.clf()

meg_chan_idx = 30
cortex.plot(opacity=1, scalars=G_meg[meg_chan_idx,:])

# view MEG squids
mlab.quiver3d(squids[[meg_chan_idx], 0], squids[[meg_chan_idx], 1],
              squids[[meg_chan_idx], 2], -squids[[meg_chan_idx], 3],
              -squids[[meg_chan_idx], 4], -squids[[meg_chan_idx], 5],
              opacity=0.5, scale_factor=10, mode='cone')

###############################################################################
# EIT leadfield
mlab.figure(4)
mlab.clf()

# Generate sample current injection set up
n_electrodes = eeg_electrodes.shape[0]
j_eit = np.zeros(n_electrodes)
idx_in = 10
idx_out = 13
j_eit[idx_in] = 1 # +1 current enters in idx_in electrode
j_eit[idx_out] = -1 # -1 current leaves in idx_out electrode
mlab.outline(extent=[
    -3 * a.std(), 3 * a.std(), -3 * b.std(), 3 * b.std(), -3 * c.std(),
    3 * c.std()
],
             line_width=2)

Y = np.c_[a, b, c]
U, pca_score, V = np.linalg.svd(Y, full_matrices=False)
x_pca_axis, y_pca_axis, z_pca_axis = V.T * pca_score / pca_score.min()

mlab.view(-20.8, 83, 9, [0.18, 0.2, -0.24])
#mlab.savefig('pca_3d.jpg')
mlab.quiver3d(0.1 * x_pca_axis,
              0.1 * y_pca_axis,
              0.1 * z_pca_axis,
              2 * x_pca_axis,
              2 * y_pca_axis,
              2 * z_pca_axis,
              color=(0.6, 0, 0),
              line_width=2)

x_pca_axis, y_pca_axis, z_pca_axis = 3 * V.T
x_pca_plane = np.r_[x_pca_axis[:2], -x_pca_axis[1::-1]]
y_pca_plane = np.r_[y_pca_axis[:2], -y_pca_axis[1::-1]]
z_pca_plane = np.r_[z_pca_axis[:2], -z_pca_axis[1::-1]]

x_pca_plane.shape = (2, 2)
y_pca_plane.shape = (2, 2)
z_pca_plane.shape = (2, 2)

mlab.mesh(x_pca_plane,
          y_pca_plane,
Example #49
0
                    mlab.clf()
                    mlab.points3d(center.T[0],
                                  center.T[1],
                                  center.T[2],
                                  colors_,
                                  scale_factor=0.05,
                                  scale_mode='none',
                                  colormap='RdBu',
                                  vmin=colors_.min(),
                                  vmax=colors_.max())
                    #mlab.quiver3d(center.T[0],center.T[1],center.T[2],normal.T[0],normal.T[1],normal.T[2],colormap='spectral',scale_mode='none')
                    mlab.colorbar()

                    if i >= 1:
                        vx,vy,vz = center.T[0]-old_center.T[0],\
                                   center.T[1]-old_center.T[1],\
                                   center.T[2]-old_center.T[2]
                        v = np.sqrt(vx**2 + vy**2 + vz**2)
                        mlab.quiver3d(center.T[0],center.T[1],center.T[2],\
                                      vx,vy,vz,scalars=v,colormap='spectral',scale_mode='scalar')
                        #mlab.show()
                    old_center = center.copy()
                    mlab.view(distance=5, azimuth=-90, elevation=90)
                    mlab.savefig('pulsation_lm%d%d_k%03d_%03d.png' %
                                 (l, m, k, i))
                mlab.close()
                multimedia.make_movie(
                    'pulsation_lm%d%d_k%03d_*.png' % (l, m, k),
                    output='pulsation_lm%d%d_k%03d.avi' % (l, m, k))
Example #50
0
                     faces,
                     color=(1, 1, 0),
                     opacity=0.1)

# show one cortical surface
mlab.triangular_mesh(rh_points[:, 0],
                     rh_points[:, 1],
                     rh_points[:, 2],
                     rh_faces,
                     color=(0.7, ) * 3,
                     opacity=0.3)

# show dipole as small cones
dipoles = mlab.quiver3d(dip.pos[:, 0],
                        dip.pos[:, 1],
                        dip.pos[:, 2],
                        dip.ori[:, 0],
                        dip.ori[:, 1],
                        dip.ori[:, 2],
                        opacity=0.8,
                        scale_factor=4e-3,
                        scalars=dip.times,
                        mode='cone',
                        colormap='RdBu')
# revert colormap
dipoles.module_manager.scalar_lut_manager.reverse_lut = True
mlab.colorbar(dipoles, title='Dipole fit time (ms)')

# proper 3D orientation
mlab.get_engine().scenes[0].scene.x_plus_view()
Example #51
0
     print "PE=%g" % (PE)
 print "=" * 50
 print ""
 if not (disabled):
     mlab.clf()
     if md == True:
         mlab.points3d(ax,
                       ay,
                       az,
                       types,
                       colormap="gist_heat",
                       scale_factor=0.7)
         mlab.quiver3d(ax,
                       ay,
                       az,
                       afx,
                       afy,
                       afz,
                       line_width=3,
                       scale_factor=1)
     else:
         datoms, dtypes = duplicate26(zip(ax, ay, az), types,
                                      zip(v1, v2, v3))
         axd, ayd, azd = zip(*datoms)
         mlab.points3d(axd,
                       ayd,
                       azd,
                       dtypes,
                       colormap="gist_heat",
                       scale_factor=0.7)
         mlab.plot3d([0, v1[0]], [0, v1[1]], [0, v1[2]],
                     color=(0, 1, 0))
Example #52
0
         break
 print "="*50
 print count
 print "Stress (in kB) XX YY ZZ XY YZ XZ:"
 print stresskb
 if md==True:
     print "T=%g,   PE=%g,   TE=%g" % (T,PE,KE)
 else:
     print "PE=%g" % (PE)
 print "="*50
 print ""
 if not(disabled):
     mlab.clf()
     if md==True:
         mlab.points3d(ax,ay,az,types,colormap="gist_heat",scale_factor=0.7)
         mlab.quiver3d(ax,ay,az,afx,afy,afz,line_width=3,scale_factor=1)
     else:
         datoms,dtypes=duplicate26(zip(ax,ay,az),types,zip(v1,v2,v3))
         axd,ayd,azd=zip(*datoms)
         mlab.points3d(axd,ayd,azd,dtypes,colormap="gist_heat",scale_factor=0.7)
         mlab.plot3d([0,v1[0]],[0,v1[1]],[0,v1[2]],color=(0,1,0))
         mlab.plot3d([v1[0],v1[0]+v2[0]],[v1[1],v1[1]+v2[1]],[v1[2],v1[2]+v2[2]],color=(0,1,0))
         mlab.plot3d([v1[0],v1[0]+v3[0]],[v1[1],v1[1]+v3[1]],[v1[2],v1[2]+v3[2]],color=(0,1,0))
         mlab.plot3d([v1[0]+v2[0],v1[0]+v2[0]+v3[0]],[v1[1]+v2[1],v1[1]+v2[1]+v3[1]],[v1[2]+v2[2],v1[2]+v2[2]+v3[2]],color=(0,1,0))
     
         mlab.plot3d([0,v2[0]],[0,v2[1]],[0,v2[2]],color=(0,1,0))
         mlab.plot3d([v2[0],v2[0]+v1[0]],[v2[1],v2[1]+v1[1]],[v2[2],v2[2]+v1[2]],color=(0,1,0))
         mlab.plot3d([v2[0],v2[0]+v3[0]],[v2[1],v2[1]+v3[1]],[v2[2],v2[2]+v3[2]],color=(0,1,0))
         mlab.plot3d([v2[0]+v3[0],v1[0]+v2[0]+v3[0]],[v2[1]+v3[1],v1[1]+v2[1]+v3[1]],[v2[2]+v3[2],v1[2]+v2[2]+v3[2]],color=(0,1,0))
         
         mlab.plot3d([0,v3[0]],[0,v3[1]],[0,v3[2]],color=(0,1,0))
field.contour.minimum_contour = 2000
field.actor.property.opacity = 0.3

mlab.outline()
mlab.xlabel('RA(J2000)')
mlab.ylabel('DEC(J2000)')
mlab.zlabel('Velocity')
#mlab.axes()
#mlab.colorbar()

## Add 3-d text in the cube
mlab.text3d(30,80,23,'Outflows in L1551 IRS5',scale=2.)
#mlab.text(45,45,"outflows!",width=0.2,z=20)

## Draw arrows to show outflows etc.
vector1=mlab.quiver3d(55,55,30,1,1,0.2,mode='arrow',scale_factor=10.0,color=(0.0,0.0,1.0))
vector2=mlab.quiver3d(55,40,30,1,-1.2,0.2,mode='arrow',scale_factor=10.0,color=(0.0,0.0,1.0))
vector3=mlab.quiver3d(45,50,30,-0.8,1,0.2,mode='2dthick_arrow',scale_factor=10.0,color=(0.0,0.0,1.0))
vector4=mlab.quiver3d(49,48,30,0.2,0,1,mode='2darrow',scale_factor=8.0,color=(0.0,0.0,1.0))

vector5=mlab.quiver3d(47,58,20,-1,1.8,-0.2,mode='arrow',scale_factor=10.0,color=(1.0,0.0,0.0))
vector6=mlab.quiver3d(45,45,20,-1.2,-1,-0.2,mode='arrow',scale_factor=10.0,color=(1.0,0.0,0.0))
vector7=mlab.quiver3d(55,45,20,1,-1.4,-0.2,mode='2dthick_arrow',scale_factor=10.0,color=(1.0,0.0,0.0))
vector8=mlab.quiver3d(48,48,20,-0.2,0,-1,mode='2darrow',scale_factor=8.0,color=(1.0,0.0,0.0))

# Insert the continuum image as a background
img=pyfits.open('L1551.cont.fits')     # Read the fits data
dat=img[0].data
dat0=dat[0]
channel=dat0[0]
region=channel[0:95,0:95]*1000   # Select a region. Use mJy unit
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()
Example #55
0
# Display a semi-transparent sphere
sphere = mlab.points3d(0, 0, 0,
    scale_mode='none',
    scale_factor=2,
    color=tango.aluminum3,
    resolution=50,
    opacity=0.7,
    name='Poincare')
sphere.actor.property.specular = 0.45
sphere.actor.property.specular_power = 5
sphere.actor.property.backface_culling = True

# Display Cartesian axes
mlab.points3d((0, 0), (0, 0), (0, 0), mode='axes', scale_factor=1.2)  # axes
mlab.quiver3d(*itertools.chain(rotations([1.2, 0, 0]), rotations([1, 0, 0])),
    color=tango.black,
    mode='arrow',
    scale_factor=0.1)  # axes arrows

# Display great circles
t = N.linspace(0, 2 * N.pi, 100, endpoint=True)
for coords in rotations([N.cos(t), N.sin(t), N.zeros_like(t)]):
    mlab.plot3d(*coords, tube_radius=None)

# Plotting parameters
plots = zip(
    ['D', 'A', 'R', 'L'],  # polarization
    [(0, 1, 0), (0, -1, 0), (0, 0, 1), (0, 0, -1)],  # incident stokes vector
    ['butter3', 'chameleon3', 'skyblue3', 'scarletred3'],  # colors
    [1, 1, 1, 1],  # E_TM
    [1, 1, 1, 1],  # E_TE
    [0, N.pi, N.pi / 2, -N.pi / 2],  # psi
Example #56
0
def ip_format(a, b, A, gamma=np.pi / 2, plot=False, color='b', linewidth=1,
              linestyle='-', alpha=1, show=True, stem=False, stemline='g--',
              stemmarker='ro', mayavi_app=False):
    r"""
    Function to generate the 'Arraytool' input format.

    :param a:          separation between elements along the x-axis in wavelengths
    :param b:          separation between elements along the y-axis in wavelengths
    :param A:          visual excitation matrix
    :param gamma:      lattice angle in radians
    :param plot:       if True, produces a 2D/3D plot of the array excitation
    :param stem:       if True, the array excitation is plotted as 'stem plot'
    :param mayavi_app: if True, the 3D plot will be opened in the MayaVi application
    
    All other parameters are nothing but the 'Matplotlib' parameters. These
    should be familiar to 'Matlab' or 'Matplotlib' users.
    
    :rtype:            array_ip, a Numpy array of size (Number_elements(A)*4)
    """
    M = float(A.shape[1]) # no. of elements along the x-axis
    N = float(A.shape[0]) # no. of elements along the y-axis
    if (M == 1):  # i.e, linear array is along the y-direction
        a = 0
        gamma = np.pi / 2
    if (N == 1):  # i.e, linear array is along the x-direction
        b = 0
        gamma = np.pi / 2
    xlim = (M * a) / 2 # array is with in the x-limits [-xlim, +xlim]

    # Grid generation
    [x, y] = np.mgrid[0:M, 0:N]
    x = (x - (M - 1) / 2).T
    y = np.flipud((y - (N - 1) / 2).T)
    x = x * a
    y = y * b # rectangular grid is generated

    # modifying the rect-grid according to the given lattice angle 'gamma'
    if (gamma != np.pi / 2):
        x = x + (y / np.tan(gamma)) % a

    # Adjusting the rows so that the array lies within [-xlim, +xlim]
    for i1 in range(int(N)):
        if (x[i1, 0] < -xlim):
            x[i1, :] = x[i1, :] + a # RIGHT shifting the row by 'a'
        if (x[i1, -1] > xlim):
            x[i1, :] = x[i1, :] - a # LEFT shifting the row by 'a'

    # Finally, arranging all the data into 'Arraytool' input format
    x = np.reshape(x, (M * N, -1))
    y = np.reshape(y, (M * N, -1))
    z = np.zeros_like(x) # because only planar arrays are permitted here
    A = np.reshape(A, (M * N, -1))
    array_ip = np.hstack((x, y, z, A))  # finally, 'Arraytool' input format

    # plotting the 'absolute' value of the array excitation (2D/3D)
    if (plot):
        # checking whether 'A' has any imaginary values
        if((A.imag > 1e-10).sum()):
            A_plt = abs(A) # if A.imag are significant, then '|A|' will be plotted
        else:
            A_plt = A.real # if A.imag are negligible, then 'A'  will be plotted
        if (M == 1):  # i.e, linear array is along the y-direction
            plt.plot(y, A_plt, color=color, linewidth=linewidth,
                         linestyle=linestyle, alpha=alpha)
            if(stem): plt.stem(y, A_plt, linefmt=stemline, markerfmt=stemmarker)
            plt.axis('tight'); plt.grid(True)
            plt.xlabel(r'$y$', fontsize=16); plt.ylabel(r'$\left|A_{n}\right|$', fontsize=16)
            if(show): plt.title(r'$\mathrm{Array}\ \mathrm{Excitation}$', fontsize=18); plt.show()
        elif (N == 1):  # i.e, linear array is along the x-direction
            plt.plot(x, A_plt, color=color, linewidth=linewidth,
                         linestyle=linestyle, alpha=alpha)
            if(stem): plt.stem(x, A_plt, linefmt=stemline, markerfmt=stemmarker)
            plt.axis('tight'); plt.grid(True)
            plt.xlabel(r'$x$', fontsize=16); plt.ylabel(r'$\left|A_{m}\right|$', fontsize=16)
            if(show): plt.title(r'$\mathrm{Array}\ \mathrm{Excitation}$', fontsize=18); plt.show()
        else:
            if (mayavi_app): # this option opens the 3D plot in MayaVi Application
                mlab.options.backend = 'envisage'
            s1 = mlab.quiver3d(x, y, z, z, z, A_plt) # stem3D representation
            ranges1 = [x.min(), x.max(), y.min(), y.max(), A_plt.min(), A_plt.max()]
            mlab.axes(xlabel="x", ylabel="y", zlabel="Amn", ranges=ranges1, nb_labels=3)
            mlab.colorbar(orientation="vertical", nb_labels=5)
            s1.scene.isometric_view()
            if(show): mlab.show()
    return array_ip
Example #57
0
def plot_axis(x,y, z, directions):
    from enthought.mayavi import mlab
    mlab.quiver3d(x, y, z, [directions[0,0]], [directions[1,0]], [directions[2,0]], scale_factor=1, color=(1,0,0))
    if directions.shape[1] > 1:
        mlab.quiver3d(x, y, z, [directions[0,1]], [directions[1,1]], [directions[2,1]], scale_factor=1, color=(0,1,0))
        mlab.quiver3d(x, y, z, [directions[0,2]], [directions[1,2]], [directions[2,2]], scale_factor=1, color=(0,0,1))