Example #1
0
def view_thresholdedT(design, contrast, threshold, inequality=np.greater):
    """
    A mayavi isosurface view of thresholded t-statistics

    Parameters
    ----------

    design: one of ['block', 'event']

    contrast: str
    
    threshold: float

    inequality: one of [np.greater, np.less]

    """

    maska = np.asarray(MASK)
    tmap = np.array(load_image_fiac('group', design, contrast, 't.nii'))
    test = inequality(tmap, threshold)
    tval = np.zeros(tmap.shape)
    tval[test] = tmap[test]

    # XXX make the array axes agree with mayavi2
    avganata = np.array(AVGANAT)
    avganat_iso = mlab.contour3d(avganata * maska, opacity=0.3, contours=[3600],
                               color=(0.8,0.8,0.8))

    avganat_iso.actor.property.backface_culling = True
    avganat_iso.actor.property.ambient = 0.3

    tval_iso = mlab.contour3d(tval * MASK, color=(0.8,0.3,0.3),
                            contours=[threshold])
    return avganat_iso, tval_iso
Example #2
0
    def isosurface(self):
        from enthought.mayavi import mlab

        npoints,ndim = self.points.shape
        dimensions = array([20,20,20])

        x = zeros(dimensions)
        y = zeros(dimensions)
        z = zeros(dimensions)
        s = zeros(dimensions)

        ipoint = 0
        for i in range(dimensions[0]):
            for j in range(dimensions[1]):
                for k in range(dimensions[2]):
                    r = self.points[ipoint,:]
                    u = dot(self.axinv,r)
                    #u=r
                    x[i,j,k] = u[0]
                    y[i,j,k] = u[1]
                    z[i,j,k] = u[2]
                    s[i,j,k] = self.E[ipoint]
                    ipoint+=1
                #end for
            #end for
        #end for

        mlab.contour3d(x,y,z,s)
        mlab.show()

        return
Example #3
0
def feature_plot(unit,size,delta_xyz):
    '''
    A three dimensional plot the the voxilized feature. Does what spy_on but
    does a three dimensional plot rather then z slices.

    feature (type: Lego_Model): contains all of the information required to
    calculate the scattering off the feature
    '''
    from enthought.mayavi import mlab

    dumbie_unit = roll(unit,1,axis = 0)
    dumbie_unit = roll(dumbie_unit,1,axis = 1)
    dumbie_unit[:,0,:] = 0.0
    dumbie_unit[:,-1,:] = 0.0
    dumbie_unit[0,:,:] = 0.0
    dumbie_unit[-1,:,:] = 0.0

    xyz = indices((unit.shape), 'd')


    xyz[0] *= delta_xyz[0]
    xyz[1] *= delta_xyz[1]
    xyz[2] *= delta_xyz[2]


    feature_size = shape(unit)
    mlab.figure(0)
    s = mlab.contour3d(xyz[0],xyz[1],xyz[2],dumbie_unit,opacity=.07,contours = 20)
    mlab.figure(1)
    t = mlab.contour3d(xyz[0],xyz[1],xyz[2]*10,dumbie_unit,opacity=.07,contours = 20)
    mlab.figure(2)
    u = mlab.contour3d(dumbie_unit,opacity=.05,contours = 20)
    mlab.show()
    return
Example #4
0
def displayBlobsFromContourCenters(gui, contourList):
    """Deprecated. Nolonger using this GUI functionality"""

    from enthought.mayavi import mlab as enthought_mlab

    count = 0
    for contour in contourList:
        blobVolume = contour.features['fastMarchFromEllipseCenter']
        enthought_mlab.contour3d(blobVolume, contours=3)
        gui.addVolumeAndRefreshDataTree(blobVolume, 'BlobFromContour%d' % count)
        count += 1    
Example #5
0
def evolve_visual3d(msnake, levelset=None, num_iters=20):
    """
    Visual evolution of a three-dimensional morphological snake.
    
    Parameters
    ----------
    msnake : MorphGAC or MorphACWE instance
        The morphological snake solver.
    levelset : array-like, optional
        If given, the levelset of the solver is initialized to this. If not
        given, the evolution will use the levelset already set in msnake.
    num_iters : int, optional
        The number of iterations.
    """
    from enthought.mayavi import mlab
    
    if levelset is not None:
        msnake.levelset = levelset
    
    fig = mlab.gcf()
    mlab.clf()
    src = mlab.pipeline.scalar_field(msnake.data)
    mlab.pipeline.image_plane_widget(src, plane_orientation='x_axes', colormap='gray')
    cnt = mlab.contour3d(msnake.levelset, contours=[0.5])
    
    for i in xrange(num_iters):
        msnake.step()
        cnt.mlab_source.scalars = msnake.levelset
    
    # Return the last levelset.
    return msnake.levelset
Example #6
0
    def __init__(self,channels, thresholds, pixelsize = (1., 1., 1.)):
        self.f = mlab.figure()

        self.isos = []
        self.projs = []

        for im, th, i in zip(channels, thresholds, range(len(channels))):
            c = mlab.contour3d(im, contours=[th], color = pylab.cm.gist_rainbow(float(i)/len(channels))[:3])
            c.mlab_source.dataset.spacing = pixelsize
            self.isos.append(c)

            ps = []
            thf = th*1.5

            pr = im.mean(2)
            #f = im.max()/pr.max()
            #pr *= im.max()/pr.max()
            ps.append(self.drawProjection((255*pylab.minimum(pr/(1.*thf), 1)).astype('uint8'), 'z', c))
            pr = im.mean(0)
            #pr *= im.max()/pr.max()
            ps.append(self.drawProjection((255*pylab.minimum(pr/(.6*thf), 1)).astype('uint8'), 'x', c))
            pr = im.mean(1)
            #pr *= im.max()/pr.max()
            ps.append(self.drawProjection((255*pylab.minimum(pr/(.8*thf), 1)).astype('uint8'), 'y', c))

            self.projs.append(ps)
    def plot(self):
        "绘制场景"
        # 产生三维网格
        x, y, z = np.mgrid[self.x0:self.x1:1j * self.points,
                           self.y0:self.y1:1j * self.points,
                           self.z0:self.z1:1j * self.points]

        # 根据函数计算标量场的值
        scalars = eval(self.function)
        mlab.clf()  # 清空当前场景

        # 绘制等值平面
        g = mlab.contour3d(x, y, z, scalars, contours=8, transparent=True)
        g.contour.auto_contours = self.autocontour
        mlab.axes()  # 添加坐标轴

        # 添加一个X-Y的切面
        s = mlab.pipeline.scalar_cut_plane(g)
        cutpoint = (self.x0 + self.x1) / 2, (self.y0 + self.y1) / 2, (
            self.z0 + self.z1) / 2
        s.implicit_plane.normal = (0, 0, 1)  # x cut
        s.implicit_plane.origin = cutpoint

        self.g = g
        self.scalars = scalars
        # 计算标量场的值的范围
        self.v0 = np.min(scalars)
        self.v1 = np.max(scalars)
    def plot(self):
        "绘制场景"
        # 产生三维网格
        x, y, z = np.mgrid[
            self.x0 : self.x1 : 1j * self.points,
            self.y0 : self.y1 : 1j * self.points,
            self.z0 : self.z1 : 1j * self.points,
        ]

        # 根据函数计算标量场的值
        scalars = eval(self.function)
        mlab.clf()  # 清空当前场景

        # 绘制等值平面
        g = mlab.contour3d(x, y, z, scalars, contours=8, transparent=True)
        g.contour.auto_contours = self.autocontour
        mlab.axes()  # 添加坐标轴

        # 添加一个X-Y的切面
        s = mlab.pipeline.scalar_cut_plane(g)
        cutpoint = (self.x0 + self.x1) / 2, (self.y0 + self.y1) / 2, (self.z0 + self.z1) / 2
        s.implicit_plane.normal = (0, 0, 1)  # x cut
        s.implicit_plane.origin = cutpoint

        self.g = g
        self.scalars = scalars
        # 计算标量场的值的范围
        self.v0 = np.min(scalars)
        self.v1 = np.max(scalars)
Example #9
0
def evolve_visual3d(msnake, levelset=None, num_iters=20):
    """
    Visual evolution of a three-dimensional morphological snake.
    
    Parameters
    ----------
    msnake : MorphGAC or MorphACWE instance
        The morphological snake solver.
    levelset : array-like, optional
        If given, the levelset of the solver is initialized to this. If not
        given, the evolution will use the levelset already set in msnake.
    num_iters : int, optional
        The number of iterations.
    """
    from enthought.mayavi import mlab

    if levelset is not None:
        msnake.levelset = levelset

    fig = mlab.gcf()
    mlab.clf()
    src = mlab.pipeline.scalar_field(msnake.data)
    mlab.pipeline.image_plane_widget(src,
                                     plane_orientation='x_axes',
                                     colormap='gray')
    cnt = mlab.contour3d(msnake.levelset, contours=[0.5])

    for i in xrange(num_iters):
        msnake.step()
        cnt.mlab_source.scalars = msnake.levelset

    # Return the last levelset.
    return msnake.levelset
def display_points(val=0.3):
    scalars = shelf["scalars"]
    scalars = generate_points()
    shelf["scalars"] = scalars
    min = scalars.min()
    max = scalars.max()

    from enthought.mayavi import mlab
    x, y, z = make_grid(np.mgrid)
    contours = list(np.arange(-val, val, 0.02))
    obj = mlab.contour3d(x,
                         y,
                         z,
                         scalars,
                         contours=contours,
                         opacity=0.3,
                         colormap="PRGn",
                         transparent=True)

    display_atoms()
    #    source = mlab.pipeline.scalar_field(x,y,z,scalars)
    #    vol = mlab.pipeline.volume(source, vmin=min+0.65*(max-min),
    #                               vmax=min+0.9*(max-min))
    #    mlab.view(132, 54, 45, [21, 20, 21.5])
    mlab.show()
def display_points_func():
    from enthought.mayavi import mlab
    scf = shelf["scf"]
    mo = MolecularOrbital(scf, 0)
    x, y, z = make_grid(np.mgrid)
    obj = mlab.contour3d(x, y, z, mo(x, y, z))
    mlab.show()
def display_points_func():
    from enthought.mayavi import mlab 
    scf = shelf["scf"]
    mo  = MolecularOrbital(scf,0)
    x,y,z = make_grid(np.mgrid)
    obj = mlab.contour3d(x,y,z,mo(x,y,z) )
    mlab.show()
Example #13
0
def make_3d_graph(scalarfield, filename):
    mlab.figure(bgcolor=(1,1,1),fgcolor=(0,0,0))
    #mlab.options.offscreen = True
    #win = e.new_scene()
    #src = mlab.pipeline.scalar_scatter(Phi_graph)
    #e.add_source(src)
    #e.add_module(IsoSurface())
    #e.add_module(
    #win.scene.isometric_view()
    #win.scene.save(filename,size=(800,600))
    mlab.clf()
    mlab.contour3d(scalarfield,opacity=.5,transparent=True)#,contours=[1.0])
#    mlab.outline()
    mlab.zlabel('Z')
    mlab.xlabel('X')
    mlab.ylabel('Y')
    print 'saving %s' % filename
    mlab.savefig(filename)
Example #14
0
def make_multiple_3d_graphs(data, filename):
    '''data is a list of 3d scalar fields. filename is a string, probably ending in .png'''
    mlab.figure(bgcolor=(1,1,1),fgcolor=(0,0,0),size=(1000,600))

#    f = mlab.gcf()
#    camera = f.scene.camera
#    cam.parallel_scale = 9

#    view = mlab.view()
#    roll = mlab.roll()
#    print 'camera view is:',view
#    print 'camera roll is:',roll

    #mlab.options.offscreen = True
    #win = e.new_scene()
    #src = mlab.pipeline.scalar_scatter(Phi_graph)
    #e.add_source(src)
    #e.add_module(IsoSurface())
    #e.add_module(
    #win.scene.isometric_view()
    #win.scene.save(filename,size=(800,600))
    i=0
#    print 'mean is: ',data[i].mean()
#    print 'min is: ',data[i].min()
    for contourpercent in [.232,]:  # [.16, .20,.22,.232,.25,.28,.32,.36,.40,.44,.48,.52,.56,.60,.64,.68,.72]:
        mlab.clf()
#        contourpercent = .232 # .28, .24 is good
        value = (data[i].max()-data[i].min())*contourpercent+data[i].min()
        print 'graphing contours at',contourpercent,'of min-max distance, where value is ',value,'(versus a max of',data[i].max(),'and a min of',data[i].min(),', and a range of ',data[i].max()-data[i].min(),').'
    #    print 'graphing data[%i].shape='%i,data[i].shape
        mlab.contour3d(data[i],contours=[value],opacity=.36,transparent=True,colormap='bone')
        for i in range(1,len(data)):
    #        print data[i]
    #        print 'graphing data[%i].shape='%i,data[i].shape
            mlab.contour3d(data[i],contours=[(data[i].max()-data[i].min())*contourpercent+data[i].min()],opacity=.56,transparent=True)
    #    mlab.view(distance=36.0)
    #    mlab.outline()
    #    mlab.zlabel('Z')
    #    mlab.xlabel('X')
    #    mlab.ylabel('Y')
        tosave = filename + '%.03f'%contourpercent + '.png'
        print 'saving %s' % tosave
        mlab.savefig(tosave)
Example #15
0
def plotfield(ufunc):
    d = ufunc(x, y, z, t)
    print "field: min, max, mean, std = %g, %g, %g, %g" % (
            d.min(), d.max(), d.mean(), d.std() )
    print "lwall: min, max, mean, std = %g, %g, %g, %g" % (
            d[:,0,:].min(), d[:,0,:].max(), d[:,0,:].mean(), d[:,0,:].std() )
    print "uwall: min, max, mean, std = %g, %g, %g, %g" % (
            d[:,-1,:].min(), d[:,-1,:].max(), d[:,-1,:].mean(), d[:,-1,:].std() )
    mlab.clf()
    f = mlab.contour3d(x, y, z, d, transparent = True)
    return (d, f)
Example #16
0
def plotfield(ufunc):
    d = ufunc(x, y, z, t)
    print "field: min, max, mean, std = %g, %g, %g, %g" % (d.min(), d.max(),
                                                           d.mean(), d.std())
    print "lwall: min, max, mean, std = %g, %g, %g, %g" % (
        d[:, 0, :].min(), d[:, 0, :].max(), d[:, 0, :].mean(), d[:,
                                                                 0, :].std())
    print "uwall: min, max, mean, std = %g, %g, %g, %g" % (d[:, -1, :].min(
    ), d[:, -1, :].max(), d[:, -1, :].mean(), d[:, -1, :].std())
    mlab.clf()
    f = mlab.contour3d(x, y, z, d, transparent=True)
    return (d, f)
Example #17
0
    def On3DIsosurf(self, event):
        try:
            from enthought.mayavi import mlab
        except ImportError:
            from mayavi import mlab

        self.dsviewer.f3d = mlab.figure()
        self.dsviewer.f3d.scene.stereo = True

        for i in range(self.image.data.shape[3]):
            c = mlab.contour3d(self.image.data[:,:,:,i].astype('f'), contours=[self.do.Offs[i] + .5/self.do.Gains[i]], color = pylab.cm.gist_rainbow(float(i)/self.image.data.shape[3])[:3])
            self.lastSurf = c
            c.mlab_source.dataset.spacing = (self.image.mdh.getEntry('voxelsize.x') ,self.image.mdh.getEntry('voxelsize.y'), self.image.mdh.getEntry('voxelsize.z'))
Example #18
0
    def On3DIsosurf(self, event):
        try:
            from enthought.mayavi import mlab
        except ImportError:
            from mayavi import mlab

        self.dsviewer.f3d = mlab.figure()
        self.dsviewer.f3d.scene.stereo = True

        for i in range(self.image.data.shape[3]):
            c = mlab.contour3d(self.image.data[:,:,:,i].squeeze().astype('f'), contours=[self.do.Offs[i] + .5/self.do.Gains[i]], color = matplotlib.cm.gist_rainbow(float(i)/self.image.data.shape[3])[:3])
            self.lastSurf = c
            c.mlab_source.dataset.spacing = self.image.voxelsize
Example #19
0
    def plot3d (self, typs=['MC','MN'], clr='red', np=40):

        # radius
        r = 1.*phi_calc_M(self.phi,'oct') if self.r==None else self.r

        # contour
        F = []
        for typ in typs: F.append (zeros((np,np,np)))
        sa    = zeros ((np,np,np))
        sb    = zeros ((np,np,np))
        sc    = zeros ((np,np,np))
        samin = -1.1*r       if self.samin==None else self.samin
        samax =  1.1*r       if self.samax==None else self.samax
        sbmin = -1.1*r       if self.sbmin==None else self.sbmin
        sbmax =  1.1*r       if self.sbmax==None else self.sbmax
        scmin =  0.0         if self.scmin==None else self.scmin
        scmax =  1.1*self.sc if self.scmax==None else self.scmax
        dsa   = (samax-samin)/np
        dsb   = (sbmax-sbmin)/np
        dsc   = (scmax-scmin)/np
        for i in range(np):
            for j in range(np):
                for k in range(np):
                    sa[i,j,k] = samin + i*dsa
                    sb[i,j,k] = sbmin + j*dsb
                    sc[i,j,k] = scmin + k*dsc
                    if self.sxyz: s = oct_calc_sxyz (sa[i,j,k], sb[i,j,k], sc[i,j,k])
                    else:         s = oct_calc_s123 (sa[i,j,k], sb[i,j,k], sc[i,j,k])
                    sig      = matrix([[s[0]],[s[1]],[s[2]],[0.0]])
                    for m, typ in enumerate(typs): F[m][i,j,k] = self.func (sig, typ)

        from enthought.mayavi.mlab import contour3d
        from enthought.mayavi.mlab import show as mlab_show

        for m, typ in enumerate(typs): contour3d (sa, sb, sc, F[m], contours=[0.0])
        mlab_show ()
	def _plotbutton2_fired(self):
		mlab.clf()
		self.loaddata()
		field=mlab.contour3d(self.sregion,colormap='gist_ncar')     # Generate a scalar field
		field.contour.maximum_contour = self.datamax
		field.contour.minimum_contour = self.datamin
		field.actor.property.opacity = self.opacity

		mlab.outline()
		mlab.xlabel('RA(J2000)')
		mlab.ylabel('DEC(J2000)')
		mlab.zlabel('Velocity')
		mlab.view(azimuth=0, elevation=0)
		mlab.show()

		self.field   = field
Example #21
0
 def test_probe_data(self):
     """ Test probe_data
     """
     x, y, z = np.mgrid[0:1:10j, 0:1:10j, 0:1:10j]
     r = np.sqrt(x**2 + y**2 + z**2)
     iso = mlab.contour3d(x, y, z, r)
     x_, y_, z_ = np.random.random((3, 10, 4, 2))
     r_ = mlab.pipeline.probe_data(iso, x_, y_, z_)
     np.testing.assert_array_almost_equal(r_,
                                          np.sqrt(x_**2 + y_**2 + z_**2),
                                          decimal=2)
     flow = mlab.flow(x, y, z, x, y, z)
     u_, v_, w_ = mlab.pipeline.probe_data(flow, x_, y_, z_, type='vectors')
     np.testing.assert_array_almost_equal(u_, x_, decimal=2)
     np.testing.assert_array_almost_equal(v_, y_, decimal=2)
     np.testing.assert_array_almost_equal(w_, z_, decimal=3)
Example #22
0
def marsyasplay(sfname):
  mng = marsyas.MarSystemManager()

  net = mng.create("Series","series")
  net.addMarSystem(mng.create("SoundFileSource", "src"))
  net.addMarSystem(mng.create("BinauralCARFAC", "carfac"))
  net.updControl("SoundFileSource/src/mrs_string/filename", marsyas.MarControlPtr.from_string(sfname))

  outData  = net.getControl("mrs_realvec/processedData")

  data = np.zeros((96,200,1))
  while net.getControl("SoundFileSource/src/mrs_bool/hasData").to_bool():
    net.tick()
    a = np.array(outData.to_realvec()).reshape((96,200,1))
    data = np.append(data,a,axis=2)

  obj = mlab.contour3d(data, contours=4, transparent=True)
  mlab.show()
def display_points(val=0.3):
    scalars = shelf["scalars"]
    scalars =  generate_points()
    shelf["scalars"] = scalars
    min = scalars.min()
    max = scalars.max()
    
    from enthought.mayavi import mlab
    x,y,z = make_grid(np.mgrid)
    contours = list(np.arange(-val,val,0.02))
    obj = mlab.contour3d(x,y,z,scalars,contours=contours,opacity=0.3,colormap="PRGn",transparent=True)

    display_atoms()
#    source = mlab.pipeline.scalar_field(x,y,z,scalars)
#    vol = mlab.pipeline.volume(source, vmin=min+0.65*(max-min), 
#                               vmax=min+0.9*(max-min))
#    mlab.view(132, 54, 45, [21, 20, 21.5])
    mlab.show()
def marsyasplay(sfname):
    mng = marsyas.MarSystemManager()

    net = mng.create("Series", "series")
    net.addMarSystem(mng.create("SoundFileSource", "src"))
    net.addMarSystem(mng.create("BinauralCARFAC", "carfac"))
    net.updControl("SoundFileSource/src/mrs_string/filename",
                   marsyas.MarControlPtr.from_string(sfname))

    outData = net.getControl("mrs_realvec/processedData")

    data = np.zeros((96, 200, 1))
    while net.getControl("SoundFileSource/src/mrs_bool/hasData").to_bool():
        net.tick()
        a = np.array(outData.to_realvec()).reshape((96, 200, 1))
        data = np.append(data, a, axis=2)

    obj = mlab.contour3d(data, contours=4, transparent=True)
    mlab.show()
Example #25
0
 def test_probe_data(self):
     """ Test probe_data
     """
     x, y, z = np.mgrid[0:1:10j, 0:1:10j, 0:1:10j]
     r = np.sqrt(x**2 + y**2 + z**2)
     iso = mlab.contour3d(x, y, z, r)
     x_, y_, z_ = np.random.random((3, 10, 4, 2))
     r_ = mlab.pipeline.probe_data(iso, x_, y_, z_)
     np.testing.assert_array_almost_equal(r_, 
                                          np.sqrt(x_**2 + y_**2 + z_**2),
                                          decimal=2)
     flow = mlab.flow(x, y, z, x, y, z)
     u_, v_, w_ = mlab.pipeline.probe_data(flow, x_, y_, z_,
                                           type='vectors')
     np.testing.assert_array_almost_equal(u_, x_,
                                          decimal=2)
     np.testing.assert_array_almost_equal(v_, y_,
                                          decimal=2)
     np.testing.assert_array_almost_equal(w_, z_,
                                          decimal=3)
Example #26
0
    def __init__(self, channels, thresholds, pixelsize=(1., 1., 1.)):
        self.f = mlab.figure()

        self.isos = []
        self.projs = []

        for im, th, i in zip(channels, thresholds, range(len(channels))):
            c = mlab.contour3d(im,
                               contours=[th],
                               color=matplotlib.cm.gist_rainbow(
                                   float(i) / len(channels))[:3])
            c.mlab_source.dataset.spacing = pixelsize
            self.isos.append(c)

            ps = []
            thf = th * 1.5

            pr = im.mean(2)
            #f = im.max()/pr.max()
            #pr *= im.max()/pr.max()
            ps.append(
                self.drawProjection(
                    (255 * np.minimum(pr / (1. * thf), 1)).astype('uint8'),
                    'z', c))
            pr = im.mean(0)
            #pr *= im.max()/pr.max()
            ps.append(
                self.drawProjection(
                    (255 * np.minimum(pr / (.6 * thf), 1)).astype('uint8'),
                    'x', c))
            pr = im.mean(1)
            #pr *= im.max()/pr.max()
            ps.append(
                self.drawProjection(
                    (255 * np.minimum(pr / (.8 * thf), 1)).astype('uint8'),
                    'y', c))

            self.projs.append(ps)
Example #27
0
def main():

    fc_int_file = open("snapshots/find_color_intention_field.txt", 'r')
    fc_int_field = numpy.fromfile(fc_int_file, sep=', ')
    fc_cos_file = open("snapshots/find_color_cos_field.txt", 'r')
    fc_cos_field = numpy.fromfile(fc_cos_file, sep=', ')

    mee_int_file = open("snapshots/move_ee_intention_field.txt", 'r')
    mee_int_field = numpy.fromfile(mee_int_file, sep=', ')
    mee_int_field = mee_int_field.reshape(50,50)
    mee_cos_file = open("snapshots/move_ee_cos_field.txt", 'r')
    mee_cos_field = numpy.fromfile(mee_cos_file, sep=', ')
    mee_cos_field = mee_cos_field.reshape(50,50)

    gr_int_file = open("snapshots/gripper_intention_field.txt", 'r')
    gr_int_field = numpy.fromfile(gr_int_file, sep=', ')
    gr_cos_file = open("snapshots/gripper_cos_field.txt", 'r')
    gr_cos_field = numpy.fromfile(gr_cos_file, sep=', ')

    st_file = open("snapshots/spatial_target_field.txt", 'r')
    st_field = numpy.fromfile(st_file, sep=', ')
    st_field = st_field.reshape(50,50)

    pe_file = open("snapshots/perception_ee_field.txt", 'r')
    pe_field = numpy.fromfile(pe_file, sep=', ')
    pe_field = pe_field.reshape(50,50)

    color_space_file = open("snapshots/color_space_field.txt", 'r')
    color_space_field = numpy.fromfile(color_space_file, sep=', ')
    color_space_field = color_space_field.reshape(50,50,50)


    plot_settings.set_mode("mini")

    ##########################################################################
    # create a figure for the find color int plot
    fig = plt.figure(1)
#    fig.subplots_adjust(bottom=0.07, left=0.07, right=0.97, top=0.93)

    plt.axes([0.125,0.2,0.95-0.125,0.95-0.2])
    plt.axis([0,50,-6.5,5])
    plt.grid(color='grey', linestyle='dotted')

    plt.plot(fc_int_field, 'r-', label=r'fc int', antialiased=True)
    plt.xlabel(r'hue')
    plt.ylabel(r'act')

    plt.savefig("fig/find_color_int_field.pdf", format="pdf")

    ##########################################################################
    # create a figure for the find color cos plot
    fig = plt.figure(2)
#    fig.subplots_adjust(bottom=0.07, left=0.07, right=0.97, top=0.93)

    plt.axes([0.125,0.2,0.95-0.125,0.95-0.2])
    plt.axis([0,50,-6.5,5])
    plt.grid(color='grey', linestyle='dotted')

    plt.plot(fc_cos_field, 'r-', label=r'fc cos', antialiased=True)
    plt.xlabel(r'hue')
    plt.ylabel(r'act')

    plt.savefig("fig/find_color_cos_field.pdf", format="pdf")

    ##########################################################################
    # create a figure for the gripper int plot
    fig = plt.figure(3)
#    fig.subplots_adjust(bottom=0.07, left=0.07, right=0.97, top=0.93)

    plt.axes([0.125,0.2,0.95-0.125,0.95-0.2])
    plt.axis([0,50,-6.5,5])
    plt.grid(color='grey', linestyle='dotted')

    plt.plot(gr_int_field, 'r-', label=r'gr int', antialiased=True)
    plt.xlabel(r'$\Delta g$')
    plt.ylabel(r'act')

    plt.savefig("fig/gripper_int_field.pdf", format="pdf")

    ##########################################################################
    # create a figure for the gripper cos plot
    fig = plt.figure(4)
#    fig.subplots_adjust(bottom=0.07, left=0.07, right=0.97, top=0.93)

    plt.axes([0.125,0.2,0.95-0.125,0.95-0.2])
    plt.axis([0,50,-6.5,5])
    plt.grid(color='grey', linestyle='dotted')

    plt.plot(gr_cos_field, 'r-', label=r'gr cos', antialiased=True)
    plt.xlabel(r'$\Delta g$')
    plt.ylabel(r'act')

    plt.savefig("fig/gripper_cos_field.pdf", format="pdf")

    ##########################################################################
    # create a figure for the move ee int plot
    x,y = numpy.mgrid[0:mee_int_field.shape[0]:1, 0:mee_int_field.shape[1]:1]

    fig = plt.figure(5)
#    fig.subplots_adjust(bottom=0.07, left=0.07, right=0.97, top=0.93)

    ax = fig.gca(projection='3d')
    surf = ax.plot_surface(x, y, mee_int_field, rstride=1, cstride=1, vmin=-5, vmax=5, cmap=cm.jet, linewidth=0, antialiased=True)
    ax.set_zlim3d(-5.01, 5.01)

#    ax.set_xticks([0,20,40])
#    ax.set_yticks([0,20,40])
#    ax.w_zaxis.set_ticks([-4,0,4])

#    ax.set_xlabel(r'x')
#    ax.set_ylabel(r'y')
#    ax.set_zlabel(r'act')

    plt.savefig("fig/move_ee_int_field.pdf", format="pdf")

    ##########################################################################
    # create a figure for the move ee cos plot
    x,y = numpy.mgrid[0:mee_cos_field.shape[0]:1, 0:mee_cos_field.shape[1]:1]

    fig = plt.figure(6)
#    fig.subplots_adjust(bottom=0.07, left=0.07, right=0.97, top=0.93)

    ax = fig.gca(projection='3d')
    surf = ax.plot_surface(x, y, mee_cos_field, rstride=1, cstride=1, vmin=-5, vmax=5, cmap=cm.jet, linewidth=0, antialiased=True)
    ax.set_zlim3d(-5.01, 5.01)

#    ax.set_xticks([0,20,40])
#    ax.set_yticks([0,20,40])
#    ax.w_zaxis.set_ticks([-4,0,4])

#    ax.set_xlabel(r'x')
#    ax.set_ylabel(r'y')
#    ax.set_zlabel(r'act')

    plt.savefig("fig/move_ee_cos_field.pdf", format="pdf")

    ##########################################################################
    # create a figure for the spatial target plot
    x,y = numpy.mgrid[0:st_field.shape[0]:1, 0:st_field.shape[1]:1]

    fig = plt.figure(7)
#    fig.subplots_adjust(bottom=0.07, left=0.07, right=0.97, top=0.93)

    ax = fig.gca(projection='3d')
    surf = ax.plot_surface(x, y, st_field, rstride=1, cstride=1, vmin=-5, vmax=5, cmap=cm.jet, linewidth=0, antialiased=True)
    ax.set_zlim3d(-5.01, 5.01)

#    ax.set_xticks([0,20,40])
#    ax.set_yticks([0,20,40])
#    ax.w_zaxis.set_ticks([-4,0,4])

#    ax.set_xlabel(r'x')
#    ax.set_ylabel(r'y')
#    ax.set_zlabel(r'act')

    plt.savefig("fig/spatial_target_field.pdf", format="pdf")

    ##########################################################################
    # create a figure for the perception ee plot
    x,y = numpy.mgrid[0:pe_field.shape[0]:1, 0:pe_field.shape[1]:1]

    fig = plt.figure(8)
#    fig.subplots_adjust(bottom=0.07, left=0.07, right=0.97, top=0.93)

    ax = fig.gca(projection='3d')
    surf = ax.plot_surface(x, y, pe_field, rstride=1, cstride=1, vmin=-5, vmax=5, cmap=cm.jet, linewidth=0, antialiased=True)
    ax.set_zlim3d(-5.01, 5.01)

#    ax.set_xticks([0,20,40])
#    ax.set_yticks([0,20,40])
#    ax.w_zaxis.set_ticks([-4,0,4])

#    ax.set_xlabel(r'x')
#    ax.set_ylabel(r'y')
#    ax.set_zlabel(r'act')

    plt.savefig("fig/perception_ee_field.pdf", format="pdf")

    ##########################################################################
    # create a figure for the color-space plot
    x,y,z = numpy.mgrid[0:color_space_field.shape[0]:1, 0:color_space_field.shape[1]:1, 0:color_space_field.shape[2]:1]

    fig = plt.figure(9)

#    ax = fig.gca(projection='3d')
    surf = mlab.contour3d(x, y, z, color_space_field, vmin=-5, vmax=5, colormap='jet')
#    ax.set_zlim3d(-5.01, 5.01)

#    plt.savefig("fig/color_space_field.pdf", format="pdf")




    plt.show()


    fc_int_file.close()
    fc_cos_file.close()
    mee_int_file.close()
    mee_cos_file.close()
    gr_int_file.close()
    gr_cos_file.close()
    st_file.close()
    pe_file.close()
    color_space_file.close()
Example #28
0
fn = './data.pkl'
file = open(fn, 'r')
print 'De-pickling data ...'
[
    x, y, z, x_b, y_b, z_b, scidata_cleana, scidata_cleana_noplane,
    scidata_cleanb
] = pickle.load(file)
file.close()

print 'Plotting it ...'
# Start plotting ... make it an interactive 3D map !
fig1 = mlab.figure(bgcolor=(1.0, 1.0, 1.0),
                   fgcolor=(0.0, 0.0, 0.0),
                   size=(1200, 900))

surf2 = mlab.contour3d(x,y,z,scidata_cleana,contours=[10],\
                opacity=0.5, colormap='RdYlBu', name='[O III]-1')
mlab.outline()
surf3 = mlab.contour3d(x,y,z,scidata_cleana,contours=[40],\
                opacity=1, colormap='Blues', name='[O III]-2')

surf5 = mlab.contour3d(x_b,y_b,z_b,scidata_cleanb,contours=[10],\
                           opacity=0.1,colormap='autumn', name='Hbeta')

surf6 = mlab.points3d((stars[:, 0] - size_x / 2) * 0.5 * astopc,
                      (stars[:, 1] - size_y / 2.) * 0.5 * astopc,
                      stars[:, 0] * 0.0,
                      stars[:, 2] * 0.5 * astopc * 2,
                      color=(0, 0, 0),
                      scale_factor=1,
                      name='Stars')
Example #29
0
# make a white figure
mlab.figure(1, bgcolor=(1, 1, 1))
# plot the atoms as spheres
for atom in atoms:
    mlab.points3d(
        atom.x,
        atom.y,
        atom.z,
        #this determines the size of the atom
        scale_factor=vdw_radii[atom.number] / 5.,
        resolution=20,
        # a tuple is required for the color
        color=tuple(cpk_colors[atom.number]),
        scale_mode='none')
# draw the unit cell - there are 8 corners, and 12 connections
a1, a2, a3 = atoms.get_cell()
origin = [0, 0, 0]
cell_matrix = [[origin, a1], [origin, a2], [origin, a3], [a1, a1 + a2],
               [a1, a1 + a3], [a2, a2 + a1], [a2, a2 + a3], [a3, a1 + a3],
               [a3, a2 + a3], [a1 + a2, a1 + a2 + a3], [a2 + a3, a1 + a2 + a3],
               [a1 + a3, a1 + a3 + a2]]
for p1, p2 in cell_matrix:
    mlab.plot3d(
        [p1[0], p2[0]],  # x-positions
        [p1[1], p2[1]],  # y-positions
        [p1[2], p2[2]],  # z-positions
        tube_radius=0.02)
# Now plot the charge density
mlab.contour3d(x, y, z, cd)
mlab.view(azimuth=-90, elevation=90, distance='auto')
mlab.savefig('images/co-cd.png')
Example #30
0
#!/usr/bin/python

#import numpy
#from mayavi.mlab import *

import numpy as np
from enthought.mayavi import mlab

# x, y, z = np.ogrid[-10:10:20j, -10:10:20j, -10:10:20j]
# s = np.sin(x*y*z)/(x*y*z)

# src = mlab.pipeline.scalar_field(s)
# mlab.pipeline.iso_surface(src, contours=[s.min()+0.1*s.ptp(), ], opacity=0.3)
# mlab.pipeline.iso_surface(src, contours=[s.max()-0.1*s.ptp(), ],)

# mlab.show()

# def test_contour3d():

# x, y, z = np.ogrid[-5:5:64j, -5:5:64j, -5:5:64j]
# scalars = x*x*0.5 + y*y + z*z*2.0
# print scalars
scalars = [[[0, 0, 0], [1, 0, 1], [2, 0, 2]]]
obj = mlab.contour3d(scalars, contours=4, transparent=True)
mlab.show()

#   return obj

# test_contour3d()
Example #31
0
mlab.figure(bgcolor=(1, 1, 1))
# plot the atoms as spheres
for atom in atoms:
    mlab.points3d(
        atom.x,
        atom.y,
        atom.z,
        scale_factor=vdw_radii[atom.number] / 5.,
        resolution=20,
        # a tuple is required for the color
        color=tuple(cpk_colors[atom.number]),
        scale_mode='none')
# draw the unit cell - there are 8 corners, and 12 connections
a1, a2, a3 = atoms.get_cell()
origin = [0, 0, 0]
cell_matrix = [[origin, a1], [origin, a2], [origin, a3], [a1, a1 + a2],
               [a1, a1 + a3], [a2, a2 + a1], [a2, a2 + a3], [a3, a1 + a3],
               [a3, a2 + a3], [a1 + a2, a1 + a2 + a3], [a2 + a3, a1 + a2 + a3],
               [a1 + a3, a1 + a3 + a2]]
for p1, p2 in cell_matrix:
    mlab.plot3d(
        [p1[0], p2[0]],  # x-positions
        [p1[1], p2[1]],  # y-positions
        [p1[2], p2[2]],  # z-positions
        tube_radius=0.02)
# Now plot the charge density
mlab.contour3d(x, y, z, cd, transparent=True)
# this view was empirically found by iteration
mlab.view(azimuth=-90, elevation=90, distance='auto')
mlab.savefig('images/co-centered-cd.png')
mlab.show()
Example #32
0
  for i in range(len(f[0,:,0,0])):
    for j in range(len(f[0,0,:,0])):
      for k in range(len(f[0,0,0,:])):
        # Calculate kinetic energy and norm per particle
        temperature[i,j,k] = (f[:,i,j,k]* v[2:-2]**2).sum() / f.sum(axis=0)[i,j,k]


  return temperature


for frame in range(len(fileh.root.Time[:])):
  # 3D Movie
  frame = 4*frame
  mlab.clf(figure=fig3d)
  scene = mlab.contour3d(Temperature(fileh.root.Phasespace[:,:,:,:,frame], fileh.root.Phasespace.attrs.v), contours=50)
  # Density profile
  #scene = mlab.contour3d(fileh.root.Phasespace[:,:,:,:,frame].sum(axis=0), contours=50)
  #source = mlab.pipeline.scalar_field(Temperature(fileh.root.Phasespace[:,:,:,:,frame], fileh.root.Phasespace.attrs.v))
  #vol = mlab.pipeline.volume(source)
  angle = 50.
  mlab.view(azimuth=angle%360, distance=72.0)
  #mlab.axes(color=(0.0,0.0,0.),extent=ext,xlabel='X',ylabel='Y',zlabel='Z')
  #a = array(gradient(fileh.root.Phi[:,:,:,frame]))**2
  #mlab.quiver3d(a[0],a[1],a[2])
  mlab.colorbar(orientation='vertical')#, label_fmt="%.2f", nb_labels=3)
  mlab.outline()
  mlab.savefig("Rho_" + string.zfill(frame, 4) + ".jpg")#, size=(600,600))
  print "[", string.zfill(frame, 4),"/", len(fileh.root.Time[:]), "]"

#!/usr/bin/env python
from numpy import *
from enthought.mayavi import mlab
K1=-1.35
K2=-.4
dphi, dtheta = pi/250.0, pi/250.0
[phi,theta] = mgrid[0:2*pi+dphi*1.5:dphi,0:pi+dtheta*1.5:dtheta]
E= K1*((cos(phi)*sin(theta))**2*(sin(phi)*sin(theta))**2+(sin(phi)*sin(theta))**2*(cos(theta))**2+(cos(theta))**2*(cos(phi)*sin(theta))**2) + K2*(cos(phi)*sin(theta))**2*(sin(phi)*sin(theta))**2*cos(theta)**2
#x=E*cos(phi)*sin(theta)
#y=E*sin(phi)*sin(theta)
#z=E*cos(theta)
s=mlab.contour3d(E,contours=4)
mlab.show()
  file = h5py.File( filename, "r" )
except IOError as e:
  print "Error: no se puede abrir el fichero ---> {0}\n".format(filename)
  sys.exit()


# Get temperature data
temperature = file["temperature"]

m=0

if(dims==0): #3D

  while( updatefig3() ):
    if( m % 10 == 0 ):
      fig = mlab.contour3d( ui, colormap='hot', opacity=0.3 )
  
  fig = mlab.contour3d( ui, colormap='hot', opacity=0.3 )
  mlab.show()

else: #2D

  # First frame configuration
  fig = plt.figure(1)
  img = subplot(111)
  if ((dim == 'Z') or (dim == 'z')): 
    im  = img.imshow( temperature[0,:,:,val], cmap=cm.hot, interpolation="nearest", origin="lower", vmax=1.01)
  elif ((dim == 'Y') or (dim == 'y')): 
    im  = img.imshow( temperature[0,:,val,:], cmap=cm.hot, interpolation="nearest", origin="lower", vmax=1.01)
  elif ((dim == 'X') or (dim == 'x')): 
    im  = img.imshow( temperature[0,val,:,:], cmap=cm.hot, interpolation="nearest", origin="lower", vmax=1.01)
Example #35
0
                  atom.z,
                  scale_factor=vdw_radii[atom.number]/5., #this determines the size of the atom
                  resolution=20,
                  # a tuple is required for the color
                  color=tuple(cpk_colors[atom.number]),
                  scale_mode='none')
# draw the unit cell - there are 8 corners, and 12 connections
a1, a2, a3 = atoms.get_cell()
origin = [0, 0, 0]
cell_matrix = [[origin,  a1],
               [origin,  a2],
               [origin,  a3],
               [a1,      a1 + a2],
               [a1,      a1 + a3],
               [a2,      a2 + a1],
               [a2,      a2 + a3],
               [a3,      a1 + a3],
               [a3,      a2 + a3],
               [a1 + a2, a1 + a2 + a3],
               [a2 + a3, a1 + a2 + a3],
               [a1 + a3, a1 + a3 + a2]]
for p1, p2 in cell_matrix:
    mlab.plot3d([p1[0], p2[0]], # x-positions
                [p1[1], p2[1]], # y-positions
                [p1[2], p2[2]], # z-positions
                tube_radius=0.02)
# Now plot the charge density
mlab.contour3d(x, y, z, cd)
mlab.view(azimuth=-90, elevation=90, distance='auto')
mlab.savefig('images/co-cd.png')
mlab.show()
# -*- coding: utf-8 -*-
# -*- coding: utf-8 -*-
import numpy as np
from enthought.mayavi import mlab
from enthought.mayavi.modules.scalar_cut_plane import ScalarCutPlane

def sphere(x, y, z):
    return x**2+y**2+z**2

x, y, z = np.mgrid[-1:1:20j, -1:1:20j, 0:1:10j]
surface = mlab.contour3d(sphere(x,y,z), transparent=True)
surface.contour.auto_contours = False
surface.contour.contours = [1.0]
surface.actor.property.opacity = 0.3

axes =mlab.axes(xlabel='x', ylabel='y', zlabel='z')
axes.axes.use_ranges = True
axes.axes.ranges = np.array([-1., -1.,  0.,  1.,  1.,  1.])

engine = mlab.get_engine()
module_manager = engine.scenes[0].children[0].children[0]

cut_plane = ScalarCutPlane()
engine.add_filter(cut_plane, module_manager)

cut_plane.warp_scalar.filter.normal = np.array([ 1.,  0.,  0.])
cut_plane.enable_contours = True
cut_plane.contour.auto_contours = True
cut_plane.contour.maximum_contour = 1.0
cut_plane.contour.number_of_contours = 3
cut_plane.contour.filled_contours = True
cut_plane.implicit_plane.widget.origin = np.array([ 15,10,5])
Example #38
0
ext = [ min(X), max(X), min(Y), max(Y), min(Z), max(Z) ]



fig3d = mlab.figure(bgcolor=(1.0, 1.0, 1.0), fgcolor=(0.0, 0.0, 0.0), size=(1280, 1280))

angle = 1.0*25


for frame in range(len(fileh.root.Time[1:])):
  frame=frame_skip*frame
  # 3D Movie
  
  mlab.clf(figure=fig3d)
  #Simple contour
  scene = mlab.contour3d((fileh.root.Phi[2:-2,2:-2,2:-2,frame]**2), contours=50, extent=ext, vmax=fmax, vmin=fmin)#, colormap='ylgn')

  # Cutplane
  #E  = gradient(fileh.root.Phi[:,:,:,frame])
  #mlab.quiver3d(E[0], E[1], E[2])
  #src = mlab.pipeline.vector_field(E[2], E[1], E[0])
  #mlab.pipeline.vectors(src, mask_points=20, scale_factor=3.)
  #mlab.pipeline.vector_cut_plane(src, mask_points=1, scale_factor=5)
  #src = mlab.pipeline.vector_field(E[0], E[1], E[2])
  #magnitude = mlab.pipeline.extract_vector_norm(src)
  #flow = mlab.pipeline.streamline(magnitude, seedtype='plane', seed_visible=False, seed_scale=1.0, seed_resolution=100, linetype='line',integration_direction='both')
  #$mlab.axes(color=(0.0,0.0,0.),extent=ext,xlabel='X',ylabel='Y',zlabel='Z')
  #source = mlab.pipeline.scalar_field(fileh.root.Phi[:,:,:,frame]**2)
  #vol = mlab.pipeline.volume(source)
  #a = array(gradient(fileh.root.Phi[:,:,:,frame]))**2
  #mlab.quiver3d(a[0],a[1],a[2])
Example #39
0
    def display(self,show_illum=True,dvol=50,cladding=None,scattering=True,spreading=True,bounds = None):
        """ Display optrode in mayavi
        """
        if not bounds:
            if hasattr(self,"bounds"):
                bounds = self.bounds
            else:
                bounds = [[-500,500],[-500,500],[-500,500]]
        self.bounds = bounds
        if cladding==None:
            if hasattr(self,'mlab_cladding'):
                cladding = True
            else:
                cladding = False
        if hasattr(self,'mlab_tube'):
            self.mlab_tube.parent.parent.remove()
        if hasattr(self,'mlab_illum'):
            self.mlab_illum.parent.parent.remove()
        if hasattr(self,'mlab_cladding'):
            self.mlab_cladding.parent.parent.remove()
        try:
            from enthought.mayavi import mlab
        except:
            from mayavi import mlab
        cyl = mlab.plot3d(self.x,
                          self.y,
                          self.z,
                          name='optrode',
                          color=(.9,.9,.9))
        self.mlab_tube = cyl.parent.parent
        self.mlab_tube.filter.capping = True
        self.mlab_tube.filter.number_of_sides = 20
        self.mlab_tube.filter.radius = self.radius
        if cladding:
            from numpy import array
            clad= mlab.plot3d(self.x,
                              self.y,
                              self.z-array([0.1,0.1]),
                              name='cladding',
                              color=(0.5,0.5,0.5),
                              opacity = 0.5)
            self.mlab_cladding = clad.parent.parent
            self.mlab_cladding.filter.capping = True
            self.mlab_cladding.filter.number_of_sides = 20
            self.mlab_cladding.filter.radius = self.radius*2
            self.mlab_cladding.children[0].children[0].actor.property.backface_culling = True
        if show_illum:
            from numpy import diff, mgrid,array,matrix,c_,cos,sin,arctan,ones
            from numpy.linalg import norm
            x = self.xyz[1,0]
            y = self.xyz[1,1]
            z = self.xyz[1,2]
            X,Y,Z = mgrid[x+bounds[0][0]:x+bounds[0][1]:dvol*1j,
                          y+bounds[1][0]:y+bounds[1][1]:dvol*1j,
                          z+bounds[2][0]:z+bounds[2][1]:dvol*1j]

            Tx = self.find_illumination(X,Y,Z,spreading,scattering)
            self.mlab_illum = mlab.contour3d(X,Y,Z,Tx,
                                             #opacity=0.8,
                                             transparent=True,
                                             vmin=0.001,
                                             vmax=0.1,
                                             contours=[t for t in [0.1,0.01,0.001]])
            self.mlab_illum.parent.scalar_lut_manager.use_default_range = False
            self.mlab_illum.parent.scalar_lut_manager.data_range = array([ 0.001,  0.1   ])
            self.mlab_illum.parent.scalar_lut_manager.lut.scale='log10'
            #self.mlab_illum.actor.property.backface_culling = True
            self.mlab_illum.actor.property.frontface_culling = True
Example #40
0
    def test(self):
        from enthought.mayavi import mlab
        from numpy import array,dot,arange,sin,ogrid,mgrid,zeros

        n=10
        n2=2*n
        s = '-'+str(n)+':'+str(n)+':'+str(n2)+'j'
        exec 'x, y, z = ogrid['+s+','+s+','+s+']'
        del s

        #x, y, z = ogrid[-10:10:20j, -10:10:20j, -10:10:20j]
        #x, y, z = mgrid[-10:11:1, -10:11:1, -10:11:1]

        s = sin(x*y*z)/(x*y*z)


        #xl = [-5.0,-4.2,-3.5,-2.1,-1.7,-0.4,0.7,1.8,2.6,3.7,4.3,5.0]
        #yl = [-5.0,-4.3,-3.6,-2.2,-1.8,-0.3,0.8,1.7,2.7,3.6,4.4,5.0]
        #zl = [-5.0,-4.4,-3.7,-2.3,-1.9,-0.4,0.9,1.6,2.8,3.5,4.5,5.0]
        dx = 2.0*n/(2.0*n-1.0)
        xl = arange(-n,n+dx,dx)
        yl = xl
        zl = xl

        x,y,z = ndgrid(xl,yl,zl)

        s2 = sin(x*y*z)/(x*y*z)

        #shear the grid
        nx,ny,nz = x.shape
        A = array([[1,1,-1],[1,-1,1],[-1,1,1]])
        #A = array([[3,2,1],[0,2,1],[0,0,1]])
        #A = array([[4,7,2],[8,4,3],[2,5,3]])
        #A = 1.0*array([[1,2,3],[4,5,6],[7,8,9]]).transpose()
        r = zeros((3,))
        np=0
        for i in range(nx):
            for j in range(ny):
                for k in range(nz):
                    r[0] = x[i,j,k]
                    r[1] = y[i,j,k]
                    r[2] = z[i,j,k]
                    
                    #print np,r[0],r[1],r[2]
                    np+=1

                    r = dot(A,r)
                    x[i,j,k] = r[0]  
                    y[i,j,k] = r[1]  
                    z[i,j,k] = r[2]  
                #end for
            #end for
        #end for
        s2 = sin(x*y*z)/(x*y*z)

        mlab.contour3d(x,y,z,s2)
        mlab.show()

        out = QAobject()
        out.x=x
        out.y=y
        out.z=z
        out.s=s2
        out.A=A

        return out
Example #41
0
            atoms=atoms)
calc.set_nbands(f=2)
calc.stop_if(calc.potential_energy is None)
x, y, z, lp = calc.get_local_potential()
x, y, z, cd = calc.get_charge_density()
mlab.figure(1, bgcolor=(1, 1, 1))  # make a white figure
# plot the atoms as spheres
for atom in atoms:
    mlab.points3d(
        atom.x,
        atom.y,
        atom.z,
        scale_factor=vdw_radii[atom.number] / 5.,
        resolution=20,
        # a tuple is required for the color
        color=tuple(cpk_colors[atom.number]),
        scale_mode='none')
# plot the bonds. We want a line from C-Br, C-F, etc...
# We create a bond matrix showing which atoms are connected.
bond_matrix = [[0, 1], [0, 2], [0, 3], [0, 4]]
for a1, a2 in bond_matrix:
    mlab.plot3d(
        atoms.positions[[a1, a2], 0],  # x-positions
        atoms.positions[[a1, a2], 1],  # y-positions
        atoms.positions[[a1, a2], 2],  # z-positions
        [2, 2],
        tube_radius=0.02,
        colormap='Reds')
mlab.contour3d(x, y, z, lp)
mlab.savefig('images/halogen-ep.png')
mlab.show()
Example #42
0
import numpy
from enthought.mayavi import mlab


def Ea(x, y, z):
    K1 = -1.35e4
    K2 = -.4e4
    R = numpy.sqrt(x**2 + y**2 + z**2)
    a, b, c = x / R, y / R, z / R
    return K1 * (a**2 * b**2 + b**2 * c**2 +
                 c**2 * a**2) + K2 * a**2 * b**2 * c**2


X, Y, Z = numpy.mgrid[-1:1:100j, -1:1:100j, -1:1:100j]
energy = Ea(X, Y, Z)
mlab.contour3d(energy, contours=4)
mlab.show()
Example #43
0
stars = np.array([[30,30,5],[50,43,5],[40,52,5],[119,43,5],[67,120,4],
                  [122,42,5],[67,142,5],[110,80,7],[138,98,5],[136,67,6],[97,90,5]])

# Load the data ... a tad big, but it's a real IFU observation after all ...
fn = './data.pkl'
file = open(fn,'r')
print 'De-pickling data ...'
[x,y,z,x_b,y_b,z_b,
 scidata_cleana,scidata_cleana_noplane,scidata_cleanb] = pickle.load(file)
file.close()

print 'Plotting it ...'
# Start plotting ... make it an interactive 3D map !
fig1 = mlab.figure(bgcolor=(1.0,1.0,1.0),fgcolor=(0.0,0.0,0.0), size=(1200,900))

surf2 = mlab.contour3d(x,y,z,scidata_cleana,contours=[10],\
                opacity=0.5, colormap='RdYlBu', name='[O III]-1')
mlab.outline()
surf3 = mlab.contour3d(x,y,z,scidata_cleana,contours=[40],\
                opacity=1, colormap='Blues', name='[O III]-2')

surf5 = mlab.contour3d(x_b,y_b,z_b,scidata_cleanb,contours=[10],\
                           opacity=0.1,colormap='autumn', name='Hbeta')

surf6 =  mlab.points3d((stars[:,0]-size_x/2)*0.5*astopc,(stars[:,1]-size_y/2.)*0.5*astopc,stars[:,0]*0.0,stars[:,2]*0.5*astopc*2,color=(0,0,0), scale_factor=1, name = 'Stars')

# Now to make it look decent ...
ax = mlab.axes(extent=[-10,10,-12,12,-7,7],nb_labels=5)
ax.axes.fly_mode = 'outer_edges'
ax.title_text_property.font_size = 10
ax.title_text_property.font_family = 'courier'
ax.label_text_property.font_family = 'courier'
Example #44
0
		.5*numpy.pi*numpy.sign(y),
		numpy.arctan(y/x)+numpy.pi*numpy.sign(y)]
)
"""
a0 = 1.
R = lambda r, n, l: (2 * r / n / a0
                     )**l * numpy.exp(-r / n / a0) * scipy.special.genlaguerre(
                         n - l - 1, 2 * l + 1)(2 * r / n / a0)
WF = lambda r, theta, phi, n, l, m: R(r, n, l) * scipy.special.sph_harm(
    m, l, phi, theta)
absWF = lambda r, theta, phi, n, l, m: abs(WF(r, theta, phi, n, l, m))**2

x, y, z = numpy.ogrid[-24:24:55j, -24:24:55j, -24:24:55j]

mlab.figure()

#mask = numpy.select([theta(x,y,z)>numpy.pi/3.],[numpy.select([abs(phi(x,y,z))<numpy.pi/3.],[numpy.nan],default=1)],default=1)
mask = 1

level = int(input("How many levels: "))

for n in range(1, level + 1):
    for l in range(1, n):
        for m in range(-l, l + 1, 1):
            w = absWF(r(x, y, z), theta(x, y, z), phi(x, y, z), n, l, m)
            mlab.contour3d(w * mask, contours=6, transparent=True)

mlab.colorbar()
mlab.outline()
mlab.show()
Example #45
0
# Plot the different iso-contours of the HI emission
# Draw them one-at-a-time to a) control their transparency individually and b)
# export them as individual structures (useful for the interactive html model).
for (j, level) in enumerate(isolevels):
    if j == len(isolevels) - 1:
        op = 1
    else:
        op = 0.2

    # Plot the said contour - and flip the colorscheme for aesthetic purposes.
    cm_tweak = -1.0
    mlab.contour3d(ras,
                   decs,
                   vs,
                   HI_cube * cm_tweak,
                   contours=[level * cm_tweak],
                   opacity=op,
                   vmin=color_scale[1] * cm_tweak,
                   vmax=color_scale[0] * cm_tweak,
                   name='I: ' + np.str(level),
                   colormap='Set1')

# Draw a box around the cube to aid in the visualization
mlab.outline(extent=[
    np.min(ras),
    np.max(ras),
    np.min(decs),
    np.max(decs), c_v[slice_min, 1], c_v[slice_max, 1]
],
             color=(0, 0, 0),
             line_width=2.0)  # Draw a box around it
Example #46
0
# compute ELF for CF4
from jasp import *
from ase.structure import molecule
from enthought.mayavi import mlab
atoms = molecule('CF4')
atoms.center(vacuum=5)
with jasp('molecules/cf4-elf',
          encut=350,
          prec='high',
          ismear=0,
          sigma=0.01,
          xc='PBE',
          lelf=True,
          atoms=atoms) as calc:
    calc.calculate()
    x, y, z, elf = calc.get_elf()
    mlab.contour3d(x, y, z, elf,contours=[0.3])
    mlab.savefig('../../images/cf4-elf-3.png')
    mlab.figure()
    mlab.contour3d(x, y, z, elf,contours=[0.75])
    mlab.savefig('../../images/cf4-elf-75.png')
# -*- coding: utf-8 -*-
import numpy as np
from enthought.mayavi import mlab

x, y, z = np.ogrid[-2:2:40j, -2:2:40j, -2:0:40j]
s = 2/np.sqrt((x-1)**2 + y**2 + z**2) + 1/np.sqrt((x+1)**2 + y**2 + z**2)
surface = mlab.contour3d(s)
surface.contour.maximum_contour = 15
surface.contour.number_of_contours = 10
surface.actor.property.opacity = 0.4
mlab.figure()

mlab.pipeline.volume(mlab.pipeline.scalar_field(s))
mlab.figure()

field = mlab.pipeline.scalar_field(s)
mlab.pipeline.volume(field, vmin=1.5, vmax=10)
cut = mlab.pipeline.scalar_cut_plane(field.children[0], plane_orientation="y_axes")
cut.enable_contours = True
cut.contour.number_of_contours = 40
mlab.gcf().scene.background = (0.8, 0.8, 0.8)
mlab.show()
Example #48
0
# -*- coding: utf-8 -*-
import numpy as np
from enthought.mayavi import mlab

const = 2.19967e34
x, y = np.ogrid[0:7000000:200j, 500:1500:100j]
s = const * np.exp(-x / y) * np.sqrt(x) / (y**1.5)
surface = mlab.contour3d(s)
surface.contour.maximum_contour = 15
surface.contour.number_of_contours = 10
surface.actor.property.opacity = 0.4
mlab.figure()

mlab.pipeline.volume(mlab.pipeline.scalar_field(s))
mlab.figure()

field = mlab.pipeline.scalar_field(s)
mlab.pipeline.volume(field, vmin=1.5, vmax=80)
cut = mlab.pipeline.scalar_cut_plane(field.children[0],
                                     plane_orientation="y_axes")
cut.enable_contours = True
cut.contour.number_of_contours = 40
mlab.gcf().scene.background = (0.8, 0.8, 0.8)
mlab.show()
Example #49
0
from vasp import Vasp
### Setup calculators
benzene = molecule('C6H6')
benzene.set_cell([10, 10, 10])
benzene.center()
calc1 = Vasp('molecules/benzene',
             xc='PBE',
             nbands=18,
             encut=350,
             atoms=benzene)
calc1.set(lcharg=True)
chlorobenzene = molecule('C6H6')
chlorobenzene.set_cell([10, 10, 10])
chlorobenzene.center()
chlorobenzene[11].symbol = 'Cl'
calc2 = Vasp('molecules/chlorobenzene',
             xc='PBE',
             nbands=22,
             encut=350,
             atoms=chlorobenzene)
calc2.set(lcharg=True)
calc2.stop_if(None in (calc1.potential_energy, calc2.potential_energy))
x1, y1, z1, cd1 = calc1.get_charge_density()
x2, y2, z2, cd2 = calc2.get_charge_density()
cdiff = cd2 - cd1
print(cdiff.min(), cdiff.max())
##########################################
##### set up visualization of charge difference
from enthought.mayavi import mlab
mlab.contour3d(x1, y1, z1, cdiff, contours=[-0.02, 0.02])
mlab.savefig('images/cdiff.png')
## [RA, DEC, VEL, POL?]
#radec = corr.wcs_pix2sky([10,10,55,0], 1)
#wx, wy = corr.wcs_pix2sky([px,py], 0)
#wy = corr.wcs_pix2world(10, 0)
#wy = corr.wcs_pix2world([0,py], 0)
#print radec


from enthought.mayavi import mlab

## For volume rendering (problems in saving as a obj file)
#field=mlab.pipeline.scalar_field(sregion)     # Generate a scalar field
#mlab.pipeline.volume(field,vmin=2000,vmax=10000) # Render the field with dots

## For surface rendering
field=mlab.contour3d(sregion,colormap='gist_ncar')     # Generate a scalar field
#field.contour.maximum_contour = 13000
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)
Example #51
0
                  scale_factor=vdw_radii[atom.number]/5.,
                  resolution=20,
                  # a tuple is required for the color
                  color=tuple(cpk_colors[atom.number]),
                  scale_mode='none')
# draw the unit cell - there are 8 corners, and 12 connections
a1, a2, a3 = atoms.get_cell()
origin = [0, 0, 0]
cell_matrix = [[origin,  a1],
               [origin,  a2],
               [origin,  a3],
               [a1,      a1 + a2],
               [a1,      a1 + a3],
               [a2,      a2 + a1],
               [a2,      a2 + a3],
               [a3,      a1 + a3],
               [a3,      a2 + a3],
               [a1 + a2, a1 + a2 + a3],
               [a2 + a3, a1 + a2 + a3],
               [a1 + a3, a1 + a3 + a2]]
for p1, p2 in cell_matrix:
    mlab.plot3d([p1[0], p2[0]], # x-positions
                [p1[1], p2[1]], # y-positions
                [p1[2], p2[2]], # z-positions
                tube_radius=0.02)
# Now plot the charge density
mlab.contour3d(x, y, z, cd, transparent=True)
# this view was empirically found by iteration
mlab.view(azimuth=-90, elevation=90, distance='auto')
mlab.savefig('images/co-centered-cd.png')
mlab.show()
    mito_prob50 = prob_file50['/volume/prediction'][0,0,:,:,label_index]
    prob_file50.close()
    blur_img50 = scipy.ndimage.gaussian_filter(mito_prob50, 13)
    mito_pred250 = blur_img50<.85
    mito_pred250 = mahotas.erode(mito_pred250, disc)
    
    # Make a 3D rendering of the mitochondria - outputed replaced with Vaa3d's
    
    mlab.clf()
    values = mito_pred2+mito_pred22+mito_pred23+mito_pred24+mito_pred25+mito_pred26+mito_pred27+mito_pred28+mito+pred29+
    mito_pred210+mito_pred211+mito_pred212+mito_pred213+mito_pred214+mito_pred215+mito_pred216+mito_pred217+mito_pred218
    + mito_pred219+mito_pred220+mito_pred221+mito_pred222+mito_pred223+mito_pred224+mito_pred225+mito_pred226+mito_pred227+
    mito_pred228+mito_pred229+mito_pred230+mito_pred231+mito_pred232+mito_pred233+mito_pred234+mito_pred235+mito_pred236+
    mito_pred237+mito_pred238+mito_pred239+mito_pred240+mito_pred241+mito_pred242+mito_pred243+mito_pred244+mito_pred245+
    mito_pred246+mito_pred247+mito_pred248+mito_pred249+mito_pred250
    mlab.contour3d(values)
    mlab.show()
    
  
    # We can also feed these probabilities into the Vaa3D application to generate 3D renderings
    

    
    #
    #
    #
    #
    #
    #
    
    
#!/usr/bin/env python
from numpy import *
from enthought.mayavi import mlab
K1 = -1.35
K2 = -.4
dphi, dtheta = pi / 250.0, pi / 250.0
[phi, theta] = mgrid[0:2 * pi + dphi * 1.5:dphi, 0:pi + dtheta * 1.5:dtheta]
E = K1 * ((cos(phi) * sin(theta))**2 * (sin(phi) * sin(theta))**2 +
          (sin(phi) * sin(theta))**2 * (cos(theta))**2 + (cos(theta))**2 *
          (cos(phi) * sin(theta))**2) + K2 * (cos(phi) * sin(theta))**2 * (
              sin(phi) * sin(theta))**2 * cos(theta)**2
#x=E*cos(phi)*sin(theta)
#y=E*sin(phi)*sin(theta)
#z=E*cos(theta)
s = mlab.contour3d(E, contours=4)
mlab.show()
Example #54
0
### Setup calculators
benzene = molecule('C6H6')
benzene.set_cell([10, 10, 10])
benzene.center()
with jasp('molecules/benzene',
          xc='PBE',
          nbands=18,
          encut=350,
          atoms=benzene) as calc:
    print(benzene.get_potential_energy())
    x1, y1, z1, cd1 = calc.get_charge_density()
chlorobenzene =  molecule('C6H6')
chlorobenzene.set_cell([10, 10, 10])
chlorobenzene.center()
chlorobenzene[11].symbol ='Cl'
with jasp('molecules/chlorobenzene',
          xc='PBE',
          nbands=18,
          encut=350,
          atoms=chlorobenzene) as calc:
    chlorobenzene.get_potential_energy()
    x2, y2, z2, cd2 = calc.get_charge_density()
cdiff = cd2 - cd1
print(cdiff.min(), cdiff.max())
##########################################
##### set up visualization of charge difference
from enthought.mayavi import mlab
mlab.contour3d(x1, y1, z1, cdiff,
               contours=[-0.02, 0.02])
mlab.savefig('images/cdiff.png')
mlab.show()
Example #55
0
fig3d = mlab.figure(bgcolor=(1.0, 1.0, 1.0),
                    fgcolor=(0.0, 0.0, 0.0),
                    size=(1280, 1280))

angle = 1.0 * 25

for frame in range(len(fileh.root.Time[1:])):
    frame = frame_skip * frame
    # 3D Movie

    mlab.clf(figure=fig3d)
    #Simple contour
    scene = mlab.contour3d((fileh.root.Phi[2:-2, 2:-2, 2:-2, frame]**2),
                           contours=50,
                           extent=ext,
                           vmax=fmax,
                           vmin=fmin)  #, colormap='ylgn')

    # Cutplane
    #E  = gradient(fileh.root.Phi[:,:,:,frame])
    #mlab.quiver3d(E[0], E[1], E[2])
    #src = mlab.pipeline.vector_field(E[2], E[1], E[0])
    #mlab.pipeline.vectors(src, mask_points=20, scale_factor=3.)
    #mlab.pipeline.vector_cut_plane(src, mask_points=1, scale_factor=5)
    #src = mlab.pipeline.vector_field(E[0], E[1], E[2])
    #magnitude = mlab.pipeline.extract_vector_norm(src)
    #flow = mlab.pipeline.streamline(magnitude, seedtype='plane', seed_visible=False, seed_scale=1.0, seed_resolution=100, linetype='line',integration_direction='both')
    #$mlab.axes(color=(0.0,0.0,0.),extent=ext,xlabel='X',ylabel='Y',zlabel='Z')
    #source = mlab.pipeline.scalar_field(fileh.root.Phi[:,:,:,frame]**2)
    #vol = mlab.pipeline.volume(source)
Example #56
0
# -*- coding: utf-8 -*-
import numpy as np
from enthought.mayavi import mlab
from enthought.mayavi.modules.scalar_cut_plane import ScalarCutPlane


def sphere(x, y, z):
    return x**2 + y**2 + z**2


x, y, z = np.mgrid[-1:1:20j, -1:1:20j, 0:1:10j]
surface = mlab.contour3d(sphere(x, y, z), transparent=True)
surface.contour.auto_contours = False
surface.contour.contours = [1.0]
surface.actor.property.opacity = 0.3

axes = mlab.axes(xlabel='x', ylabel='y', zlabel='z')
axes.axes.use_ranges = True
axes.axes.ranges = np.array([-1., -1., 0., 1., 1., 1.])

engine = mlab.get_engine()
module_manager = engine.scenes[0].children[0].children[0]

cut_plane = ScalarCutPlane()
engine.add_filter(cut_plane, module_manager)

cut_plane.warp_scalar.filter.normal = np.array([1., 0., 0.])
cut_plane.enable_contours = True
cut_plane.contour.auto_contours = True
cut_plane.contour.maximum_contour = 1.0
cut_plane.contour.number_of_contours = 3