Exemplo n.º 1
0
    def show_uvw(self):
        uvw = self.uvw
        ez =  np.cross(uvw[0],uvw[-1])

        plts = [[[0,u[0]],[0,u[1]],[0,u[2]],'b'] for u in uvw ]
        plts +=[[ [0,ez[0]],[0,ez[1]],[0,ez[2]] , 'r' ]]
        dsp.stddisp(plots=plts,labs=['x','y','z'],rc='3d',lw=4)
Exemplo n.º 2
0
def show_trihedron(ax,
                   uvw=None,
                   x0=[0, 0, 0],
                   cs=None,
                   clabs=None,
                   lw=2,
                   rc=0.1,
                   h=0.2,
                   **kwargs):
    '''
    x0 : position of trihedron
    uvw : Nx3 ndarray
    ll,rc,h : length,radius and height af arrow/cones
    cs,labs : colors and labels of cones (default black and None)
    '''
    if not isinstance(uvw, np.ndarray): uvw = np.identity(3)
    txts, x0 = [], np.array(x0)
    if not cs: cs = ['k'] * uvw.shape[0]
    if clabs:
        xtxt = x0 + 1.1 * uvw
        for i in range(len(clabs)):
            xt0, yt0, zt0 = xtxt[i, :]
            txts += [[xt0, yt0, zt0, clabs[i], cs[i][0]]]
    plots, surfs = [], []
    for u, cu in zip(uvw, cs):
        (x, y, z), (xl, yl, zl) = get_arrow_3d(u, x0, rc=0.1, h=0.2)
        plots += [[xl, yl, zl, cu]]
        surfs += [[x, y, z, cu[0], None, lw, cu[0]]]
    dsp.stddisp(ax=ax, texts=txts, plots=plots, surfs=surfs, lw=lw, **kwargs)
Exemplo n.º 3
0
def plot2Dcutplane(Shkl, n='100', title='auto', **kwargs):
    '''Not working for arbitrary cut yet '''
    N = Shkl.shape[0]
    if title == 'auto': title = 'Silicon([%s]) $S_{hk}$' % n
    if n == '100': Scut = Shkl[0, :, :]
    elif n == '110': Scut = Shkl[np.identity(N, dtype=bool), :]
    dsp.stddisp(im=Scut, imOpt='c', legOpt=0, title=title, **kwargs)
def _test_elect_atomic(name='', fmt='svg', **kwargs):
    elts = ['H', 'C', 'N', 'O', 'S', 'P']  #+ ['Si','Cu','Au','U']
    qe, fq_e = get_elec_atomic_factors(elts, qmax=3, npts=100)
    qx, fq_x = get_xray_atomic_factors(elts, qmax=6, npts=100)
    Z = get_elt(elts)  #pd.read_pickle(dat_path+'atoms.pkl')['Z'][elts].values
    cs = [
        dsp.unicolor(0.85),
        dsp.unicolor(0.4), (0, 0, 1), (1, 0, 0), (0, 1, 1), (1, 0, 1)
    ]  #+ ['k']*4
    df = pd.DataFrame(np.array([Z, cs, fq_e, fq_x]).T,
                      columns=['Z', 'color', 'fq_e', 'fq_x'],
                      index=elts)

    plts = [[qe, elt.fq_e, elt.color,
             '$%s$' % elt.name] for index, elt in df.iterrows()]
    dsp.stddisp(plts,
                labs=['$q(A^{-1})$', '$f^e(A)$'],
                lw=2,
                name=name + 'ED_scattering_factors.%s' % fmt,
                **kwargs)
    plts = [[qx, elt.fq_x, elt.color,
             '$%s$' % elt.name] for index, elt in df.iterrows()]
    dsp.stddisp(plts,
                labs=['$q(A^{-1})$', '$f^x(e)$'],
                lw=2,
                name=name + 'MX_scattering_factors.%s' % fmt,
                **kwargs)
    return df
Exemplo n.º 5
0
 def plot_unit_cells(self,opts='AV',nh=3,nk=4,lvls=10,alpha=0.5,fg='12',**kwargs) :
     '''Display the wallpaper
     pOpt :  A(Atom), V(potential), u(unit_cell), a(asym_unit)
     '''
     fig,ax = dsp.create_fig(figsize=fg,pad=[2.,5]['t' in opts])
     colls,scat,im,cs,lOpt=[],None,None,None,''
     if self.lat_type=='hex' : lOpt += 'hq'
     if 'u' in opts : lattice.plot_lattice(self.lattice_vec,max(nh,3),max(nk,3),pOpt=lOpt,ax=ax)
     if 'a' in opts : colls=[coll.PatchCollection([self.asym_cell],alpha=0.3,linewidth=1.5,edgecolor='b')]
     #plot potential
     if 'V' in opts :
         # na = int(self.Xcell.shape[0]/self.X0.shape[0])
         N = int(np.sqrt(self.Xp.shape[0]))
         (x,y),f = self.Xp.T, self.fp
         # triang = mtri.Triangulation(x, y, Delaunay(self.Xc).vertices)
         # cs=ax.tricontourf(triang,self.fc,levels=lvls)
         # cont = ax.contourf(x.reshape((N,N)),y.reshape((N,N)),f.reshape((N,N)),levels=lvls)
         im = [x.reshape((N,N)),y.reshape((N,N)),f.reshape((N,N))]#,snap=True)
         # cs = ax.pcolormesh(x.reshape((N,N)),y.reshape((N,N)),f.reshape((N,N)))#,snap=True)
     #plot atoms
     if 'A' in opts :
         x,y = self.Xa.T
         s,c = atoms.iloc[self.fa][['size','color']].values.T
         scat=[x.flatten(),y.flatten(),np.int_(50*np.array(s)),c]
     dsp.stddisp(fig=fig,ax=ax,labs=[r'$x(\AA)$',r'$y(\AA)$'],
         scat=scat,colls=colls,im=im+[alpha],contour=im+[lvls],
         title=self.name,name=self.path+self.name,
         **kwargs)
Exemplo n.º 6
0
    def show_frame(self,frame=0,opts='Pqr',
        thick=1000,Nmax=5,Smax=0.02,e0=[1,0,0],rot=0,Imag=10,Itol=20,
        show_hkl=True,qopt=True,rings=True,
        **kwargs):
        ''' Show a frame with information specified by opts
        - opts : E(exp), P(proc), S(sim), K(kin), h(hkl),q(rec A),r(rings), k(hkl_k)
        '''
        if isinstance(opts,str):exp,proc,sim,kin,show_hkl,qopt,rings,show_hkl_kin = [c in opts for c in 'EPSKhqrk']
        if kin:qopt=1

        plts,scat,txts,labs,qmax,wm = [[0,0,'b+']],(),[],['px','py'],0,5
        # plts=[]
        if qopt :
            wm*=self.aper
            labs = ['$q_x$','$q_y$']
        if proc:
            rpl0  = self.rpl.loc[self.rpl.F==frame]
            cx,cy = self.cen.iloc[frame-1][['px','py']].values.T
            px,py,I,Im = rpl0[['px','py','I','Im']].values.T

            if qopt :
                px,py = ((np.vstack([px,-py]).T-[cx,-cy])*self.aper).T
            else:
                plts = [[cx,cy,'b+']]
            scat += ([px,py,I,'w','o'],)
            qmax = np.ceil(max(py.max(),px.max()))

            if show_hkl:
                hkl1  = rpl0[['h','k','l']]
                h,k,l = hkl1.values.T
                hx,kx,lx = rpl0[['hx','kx','lx']].values.T
                sx = lambda x:['%d' %round(x),'%.1f' %x][abs(x-round(x))>0.06]
                txts += [[x+0*wm,y+wm,'(%s,%s,%s)' %(sx(h0),sx(k0),sx(l0)),(0.5,)*3] for x,y,h0,k0,l0 in zip(px,py,hx,kx,lx)]
                print(h,k,l)

        if kin:
            px_k,py_k,I_k,hkl_k = self.get_kin(frame,thick,Nmax,Smax,e0,rot,Imag)
            scat += ([px_k,py_k,I_k,'g','o'],)
            if show_hkl_kin:
                h,k,l = hkl_k
                Itol = I_k.max()/Itol
                txts += [[x,y+wm,'(%s,%s,%s)' %(h0,k0,l0),'g'] for x,y,h0,k0,l0,I in zip(px_k,py_k,h,k,l,I_k) if I>Itol]
                print(h,k,l)
            qmax = np.ceil(max(qmax,px_k.max(),py_k.max()))

        if rings and qopt:
            t = np.linspace(0,np.pi*2,100)
            ct,st = np.cos(t),np.sin(t)
            plts+=[[i*ct,i*st,'m','',0.5] for i in np.arange(0.25,qmax,0.25)]
            plts+=[[i*ct,i*st,'m','',2] for i in np.arange(1,qmax)]
        # if rot:
        #     ct,st = np.cos(np.deg2rad(rot)),np.sin(np.deg2rad(rot))
        #     px,py = ct*px-st*py,st*px+ct*py


        if not 'fonts' in kwargs.keys():kwargs['fonts']={'text':15}
        if not 'xylims' in kwargs.keys():kwargs['xylims']=[-px.max(),px.max(),-py.max(),py.max()]
        dsp.stddisp(plts,ms=20,scat=scat,texts=txts,bgcol='k',gridOn=0,
            labs=labs,**kwargs)
Exemplo n.º 7
0
def _test_trihedron():
    fig,ax = dsp.stddisp(rc='3d',std=0)
    show_trihedron(ax,x0=[0,0,0],cs=None,labs=None,
        lw=1,rc=0.1,h=0.2)
    uvw = np.array([[1,0,0],[0,2,2],[1,1,1]])
    show_trihedron(ax,uvw,x0=[-2,-2,-2],cs=['r','g','b'],labs=['$x$','$y$','$z$'],
        lw=2,rc=0.1,h=0.2)
    dsp.stddisp(ax=ax,pOpt='e',opt='p')
Exemplo n.º 8
0
 def Pattern_show(self,**kwargs):
     '''Show diffraction pattern'''
     C = [Cs[Z] for Z in self.Za]
     Nx0,Nx1 = int(self.Nx/2),int(np.ceil(self.Nx/2))
     dsp.stddisp(scat=[self.z,self.x,C],
         ms=20,labs=[r'$z(\AA)$',r'$x(\AA)$'],
         xyTicks=[self.bz,self.ax],xylims=[0,self.Nz*self.bz,-Nx0*self.ax,Nx1*self.ax],
         **kwargs)
Exemplo n.º 9
0
def plot_structure3D(hkl, Fhkl, log=0, **kwargs):
    '''scatter plot of the intensity'''
    hx, ky, lz = hkl
    hx, ky, lz = hx.flatten(), ky.flatten(), lz.flatten()
    S = np.abs(Fhkl.flatten())**2
    if log: S = np.log10(S + 1)
    N = hx.max()
    lims = [0, N, 0, N, 0, N]
    dsp.stddisp(scat=[hx, ky, lz, S], rc='3d', xylims=lims, **kwargs)
Exemplo n.º 10
0
 def get_im(self, **kwargs):
     fig = self.figs[self.i]
     figname = os.path.basename(fig)
     print(colors.yellow + fig + colors.black)
     im = self.load(fig)
     dsp.stddisp(im=[im],
                 cmap='gray',
                 caxis=[0, self.cutoff],
                 pOpt='t',
                 **kwargs)
Exemplo n.º 11
0
def show_cell(file,
              n=[0, 0, 1],
              bopt=1,
              x0=[0, 0, 0],
              rep=[1, 1, 1],
              **kwargs):
    crys = Crystal.from_cif(file)
    tail = ''.join(np.array(n, dtype=str))
    n = get_vec(n, crys, bopt)

    #unit cells,lattice vectors,atom coordinates
    cell_mesh = crys.mesh(range(rep[0] + 1), range(rep[1] + 1),
                          range(rep[2] + 1))
    surfs = get_unit_cell(cell_mesh, n)
    uvw = rcc.orient_crystal(np.array(crys.lattice_vectors), n_u=n, T=True)
    pattern, lat_params = APAP_xyz(name, n, rep, dopt='s', tail=tail)
    E, X, Y, Z = pattern[:, :4].T
    scat = [X, Y, Z, [cs[int(e)] for e in E]]

    scat2 = []
    # pattern2,lat_params = APAP_xyz(name,n,rep,dopt='')
    # E2,X2,Y2,Z2 = pattern2[:,:4].T
    # scat2       = [X2,Y2,Z2, [cs[int(e)] for e in E2]];#print(E2)

    #display options
    c1, c2, c3 = (X.min() + X.max()) / 2, (Y.min() + Y.max()) / 2, (
        Z.min() + Z.max()) / 2
    w = 0.75 * max(X.max() - X.min(), Y.max() - Y.min(), Z.max() - Z.min())
    xylims = [
        c1 - w / 2, c1 + w / 2, c2 - w / 2, c2 + w / 2, c3 - w / 2, c3 + w / 2
    ]
    fig, ax = dsp.stddisp(scat=scat, ms=100, surfs=surfs, rc='3d', std=0)
    rcc.show_trihedron(ax,
                       uvw=uvw,
                       x0=[0, 0, 0],
                       cs=['r', 'g', 'b'],
                       labs=['$a$', '$b$', '$c$'],
                       lw=2,
                       rc=0.1,
                       h=0.2)
    rcc.show_trihedron(ax,
                       x0=x0,
                       labs=['$x$', '$y$', '$z$'],
                       lw=2,
                       rc=0.1,
                       h=0.2)
    dsp.stddisp(ax=ax,
                ms=50,
                scat=scat2,
                xylims=xylims,
                axPos=[0, 0, 1, 1],
                pOpt='eXp',
                **kwargs)

    hdl = handler_3d(fig, persp=False)
Exemplo n.º 12
0
    def V_show(self, **kwargs):
        x0, z0, fv = self.pattern
        x, z = np.meshgrid(x0, z0)

        args = {
            'imOpt': 'cv',
            'axPos': 'V',
            'xylims': [z0.min(), z0.max(),
                       x0.min(), x0.max()]
        }
        args.update(kwargs)
        dsp.stddisp(im=[z, x, fv], labs=['$z$', '$x$'], **args)
Exemplo n.º 13
0
def _test_get_arrow():
    #N = 1
    U = np.array([[0,1,1],[1,1,1],[1,0,1]])
    x0 = [0,0,1]
    cs,lw = dsp.getCs('viridis',U.shape[0]),2
    plots,surfs = [],[]
    for u,cu in zip(U,cs) :
        (x,y,z),(xl,yl,zl) = get_arrow_3d(u,x0,rc=0.1,h=0.2)
        plots += [[xl,yl,zl,cu]]
        surfs += [[x,y,z,cu,None,lw,cu]]

    dsp.stddisp(rc='3d',plots=plots,surfs=surfs,lw=lw,pOpt='e')#,texts=txts)
Exemplo n.º 14
0
def plot_v(x, z, fv, ax, bz, xa, za):
    print('..plotting fv...')
    dr = bz / 2
    idx = np.abs(x[0] - ax / 2) < dr
    xylims = np.hstack(
        [za + dr * np.array([-1, 1]), xa + dr * np.array([-1, 1])])
    dsp.stddisp(im=[z[:, idx], x[:, idx], fv[:, idx]],
                labs=['$z$', '$x$'],
                imOpt='c',
                axPos='V',
                xylims=xylims,
                opt='p')
Exemplo n.º 15
0
    def F_show(self,qopt=0,**kwargs):
        '''Show atomic form factors'''
        Za = np.unique(self.Za)
        t = self.getAngle()*np.pi/180
        if qopt:
            labx,x = r'$q(\AA^{-1})$',self.getQ()
        else:
            labx,x = r'$\theta (deg)$', self.getAngle()

        plts = [[x,self.fj(t,Z)**2,'b','$Z_a=%d$' %Z] for Z in Za]
        plts += [[x,self.fj(t,Z),'g--','$Z_a=%d$' %Z] for Z in Za]
        dsp.stddisp(plts,labs=[labx,r'$f_j^2(\AA)$'],**kwargs)
Exemplo n.º 16
0
def show_grid(xyz_file, opts='', ms=1, **kwargs):
    '''display an .xyz file content in a 2D plane
    xyz_file : .xyz file
    opt : str format for 2 plane 'x1x2' - 'xy','xz','yz','zx',...
    '''
    pattern, lat_params = import_xyz(xyz_file)
    cs = {
        1: tuple([0.75] * 3),
        6: tuple([0.25] * 3),
        7: (0, 0, 1),
        8: (1, 0, 0),
        16: (1, 1, 0),
        17: (0, 1, 1)
    }
    Z = np.array(pattern[:, 0], dtype=int)
    C = [cs[E] for E in Z]

    if opts == '3d':
        fig = plt.figure()
        ax = plt.subplot(111, projection='3d')
        ax.scatter3D(pattern[:, 1], pattern[:, 2], pattern[:, 3], s=5, c=C)
        set_axes_equal(ax)
        ax.set_xlabel("x")
        ax.set_ylabel("y")
        ax.set_zlabel("z")
        fig.show()

    elif 'x' in opts or 'y' in opts or 'z' in opts:
        xij = {'x': 1, 'y': 2, 'z': 3}
        x1, x2 = opts
        i, j = xij[x1], xij[x2]

        # fig,ax = plt.subplots()
        # plt.scatter(pattern[:,i],pattern[:,j],ms,C)
        # ax.add_patch(Rectangle((0,0),lat_params[i-1],lat_params[j-1],linewidth=2,edgecolor='b',alpha=0.1))
        # ax.set_xlabel('$%s$'%x1,fontsize=20)
        # ax.set_ylabel('$%s$'%x2,fontsize=20)
        # fig.show()
        scat = [pattern[:, i], pattern[:, j], ms, C]
        patches = [
            Rectangle((0, 0),
                      lat_params[i - 1],
                      lat_params[j - 1],
                      linewidth=2,
                      edgecolor='b',
                      alpha=0.1)
        ]
        dsp.stddisp(scat=scat,
                    patches=patches,
                    labs=['$%s$' % x1, '$%s$' % x2],
                    **kwargs)
    else:
        print('opts should be xy, xz, yz, or 3d')
Exemplo n.º 17
0
def plot_fe(qmax=1, Nx=20, Vcell=1, **kwargs):
    q0, fq_e = scat.get_elec_atomic_factors(['Si'],
                                            q=np.linspace(0, qmax, 1000))
    vg = fq_e[0] / Vcell
    vgmax = vg.max()
    Xq = np.arange(Nx)[:, None].dot(np.array([1, 1])[None, :]).T / ax
    Yq = np.tile([0, vgmax], [Nx, 1]).T
    plts = [[Xq, Yq, [(0.7, 1.0, 0.7), '--'], ''],
            [q0, vg, 'g--', '$v_g(Si)$']]
    dsp.stddisp(plts,
                labs=['$q(A^{-1})$', '$v_g(q)(A^{-2})$'],
                xylims=[0, qmax, 0, vgmax],
                legLoc='upper right',
                **kwargs)
Exemplo n.º 18
0
    def Vz_show(self,iz,**kwargs):
        print(colors.blue+'...Integrating projected potential...'+colors.black)
        Vz = self._projected_potential(iz)
        nx,ny = np.array(self.nxy/self.Nxy,dtype=int)
        x,y   = np.meshgrid(np.arange(nx)*self.dx, np.arange(ny)*self.dy)  #;print(x.shape,y.shape,Vz.shape)
        im    = [x,y,Vz.T]
        Za,xa,ya  = self.pattern[self.Zas[iz]:self.Zas[iz+1],:3].T
        Zatom   = atoms.loc[Za]
        scat    = [xa,ya,Zatom.s,Zatom.c]

        tle = '$V_z$ for slice z=%.2fA, iz=%d' %(self._get_z(iz),iz)
        dsp.stddisp(im=im,scat=scat,labs=['$x$','$y$'],title=tle,
            caxis=[0,Vz.max()],imOpt='c',cs='I',axPos='V',pOpt='pt',#gridOn=False,
            **kwargs)
Exemplo n.º 19
0
def plot_npy(npy_file, title=None, log=False, **kwargs):
    from utils import displayStandards as dsp  #;imp.reload(dsp)
    qx, qy, I = np.load(npy_file)
    # print('npy : Imax=%d, Imean=%d' %(I.max(),I.mean()))
    I /= I.max()
    if log:
        I[I < 1e-10] = 1e-10
        I = np.log10(I)
    if not title: title = '%s' % os.path.basename(npy_file).replace('_', ' '),
    dsp.stddisp(im=[qx, -qy, I],
                title=title,
                imOpt='cv',
                axPos='V',
                cmap='binary',
                **kwargs)
Exemplo n.º 20
0
def show_cell(file,
              n=[0, 0, 1],
              bopt=1,
              x0=None,
              rep=[1, 1, 1],
              h3D=1,
              xylims=None,
              axPos=[],
              **kwargs):
    '''Show unit cell and coords from cif file '''
    crys = Crystal.from_cif(file)
    n = get_vec(n, crys, bopt)

    #unit cells,lattice vectors,atom coordinates
    cell_mesh = crys.mesh(range(rep[0] + 1), range(rep[1] + 1),
                          range(rep[2] + 1))
    surfs = get_unit_cell(cell_mesh, n)
    uvw = rcc.orient_crystal(np.array(crys.lattice_vectors), n_u=n, T=True)
    pattern = import_cif(file, n=n, rep=rep)
    E, X, Y, Z = pattern[:, :4].T
    scat = [X, Y, Z, [cs[int(e)] for e in E]]

    #display options
    if x0 == None: x0 = -1
    if isinstance(x0, float) or isinstance(x0, int): x0 = np.array([x0] * 3)
    if not xylims:
        c1, c2, c3 = (X.min() + X.max()) / 2, (Y.min() + Y.max()) / 2, (
            Z.min() + Z.max()) / 2
        w = 0.75 * max(X.max() - X.min(), Y.max() - Y.min(), Z.max() - Z.min())
        xylims = [
            c1 - w / 2, c1 + w / 2, c2 - w / 2, c2 + w / 2, c3 - w / 2,
            c3 + w / 2
        ]
        # print(xylims)
    if not axPos: axPos = [0, 0, 1, 0.95]
    fig, ax = dsp.stddisp(scat=scat, ms=100, surfs=surfs, rc='3d', std=0)
    show_trihedron(ax,
                   uvw=uvw,
                   x0=[0, 0, 0],
                   cs=['r', 'g', 'b'],
                   labs=['$a$', '$b$', '$c$'],
                   lw=2,
                   rc=0.1,
                   h=0.2)
    show_trihedron(ax, x0=x0, labs=['$x$', '$y$', '$z$'], lw=2, rc=0.1, h=0.2)
    dsp.stddisp(ax=ax, xylims=xylims, axPos=axPos, pOpt='Xpt', **kwargs)

    if h3D: hdl = h3d.handler_3d(fig, persp=False)
Exemplo n.º 21
0
def plot_lattice(lattice_vec, nh=3, nk=3, hOpt=True, **kwargs):
    '''Plot lattice grid :
    - nh,nk : number of cells along each direction
    - hOpt : additional lines for hexagonal
    '''
    gridcolor = (0.75, 0.75, 0.75)
    a, b = lattice_vec
    n_h, n_k = np.arange(nh + 1), np.arange(nk + 1)
    line_h = [h * a + np.array([[0, 0], nk * b]) for h in range(nh + 1)]
    line_k = [k * b + np.array([[0, 0], nh * a]) for k in range(nk + 1)]
    plts = [[xy[:, 0], xy[:, 1], gridcolor, ''] for xy in line_h + line_k]
    if hOpt:
        P = (a + b)
        n, m, nn, nm = a, b, nh, nk
        if nk > nh: n, m, nn, nm = b, a, nk, nh
        line_hex = [
            h * n + np.array([[0, 0], (nn - h) * P]) for h in range(nm, nn)
        ]
        line_hex += [
            k * m + np.array([[0, 0], (nm - k) * P]) for k in range(nm)
        ]
        if not nk == nh:
            line_hex += [
                h * n + np.array([[0, 0], nm * P]) for h in range(nn - nm)
            ]
        plts += [[xy[:, 0], xy[:, 1], [gridcolor, '--'], '']
                 for xy in line_hex]
    fig, ax = dsp.stddisp(plts, **kwargs)
    # xylims=xylims,mg=0,changeXYlims='x' in pOpt,
    # gridOn='g' in pOpt,ticksOn='t' in pOpt,equal='e' in pOpt,
    # setPos='s' in pOpt,)
    return fig, ax
Exemplo n.º 22
0
    def __init__(self,bloch,u_params=[0,0,5,5],u=None,Smax=0.01,Nmax=3,thick=100,
            F='L',xylims=None,**kwargs):
        '''Dynamic beam viewer :
        - u_params : [theta,phi,dtheta,dphi] in degrees
        '''
        self.bloch = bloch
        self.theta,self.phi,self.dtheta,self.dphi = u_params
        self.dtheta_dphi = [self.dtheta,self.dphi]
        self.dthick = 5
        self.beams_args = kwargs
        self.Smax  = Smax
        self.Nmax  = Nmax
        self.thick = thick
        self.xylims = xylims
        self.Fs = {'L':'L','G':'Sw','V':'Vg','S':'S','I':'I'}
        self.F  = F
        self.show_hkl = 0
        self.show_i   = 0
        self.show_u   = 0

        self.fig,self.ax = dsp.stddisp()
        cid = self.fig.canvas.mpl_connect('key_press_event', self)

        self.set_theta_phi_from_u(u)
        self.solved=0
        self.update()
        self.show()
Exemplo n.º 23
0
 def Xxz_show(self, iZs=1, iXs=1, **kwargs):
     '''Show 2D wave propagation solution'''
     if isinstance(iZs, int): iZs = slice(0, -1, iZs)
     if isinstance(iXs, int): iZs = slice(0, -1, iXs)
     x, z = np.meshgrid(self.x, self.z)
     im = [x[iZs, :], z[iZs, :], self.psi_xz[iZs, :]]
     return dsp.stddisp(im=im, labs=[r'$x(\AA)$', r'$z(\AA)$'], **kwargs)
Exemplo n.º 24
0
 def __init__(self,
              figpath='',
              frame=None,
              thick=5,
              cutoff=50,
              i=0,
              v=1,
              pargs={}):  #,fig=None,ax=None,):
     self.fig, self.ax = dsp.stddisp()
     cid = self.fig.canvas.mpl_connect('key_press_event', self)
     self.figpath = figpath
     self.nfigs = self._get_nfigs()
     if frame:
         i = min(max(frame, 0), self.nfigs) - 1
     else:
         frame = i + 1
     self.frame = frame  #starting image
     self.i = frame  #starting image
     self.inc = 1  #increment(use 'p' or 'm' to change)
     self.cutoff = cutoff
     self.thick = thick
     self.fieldNames = ['thick', 'frame', 'cutoff', 'inc']
     self.mode = 1
     self.pargs = pargs
     rc('text', usetex=False)
     self.show()
     if v: self.show_help()
Exemplo n.º 25
0
 def show_image(self, im=None, lab='q', stack=1, **kwargs):
     rc('text', usetex=False)
     if not im: im = self.im
     file = "%s_%s.cbf" % (self.basename, str(im).zfill(self.pad)
                           )  #;print(filename)
     # with open(file,'wb') as f:print(file)
     content = cbf.read(file)
     image = content.data
     if stack > 1:
         for i in range(1, stack):
             filename = "%s_%s.cbf" % (self.basename, str(im + i).zfill(
                 self.pad))  #;print(filename)
             image += cbf.read(filename).data
         if 'caxis' in list(kwargs.keys()):
             kwargs['caxis'] = list(np.array(kwargs['caxis']) *
                                    stack)  #; print(kwargs['caxis'])
     if 'q' in lab:
         labs = ['$q_x(A^{-1})$', '$q_y(A^{-1})$']
         X, Y = self.qx, -self.qy
     elif 'p' in lab:
         labs = ['', '']  #['$p_x$','$p_y$']
         X, Y = self.pX, self.pY
     elif 'x' in lab:
         labs = ['$x(mm)$', '$y(mm)$']
         px, py = self.pxy
         X, Y = self.pX * px * 1e3, self.pY * py * 1e3
     return dsp.stddisp(im=[X, Y, image],
                        labs=labs,
                        pOpt='ptX',
                        title="%s" % os.path.basename(file),
                        **kwargs)
Exemplo n.º 26
0
def show_ewald_sphere(lat_params,
                      lam=0.025,
                      tmax=7,
                      T=0.2,
                      nx=20,
                      ny=10,
                      **kwargs):
    '''lam(wavelength Angstrum), tmax(angle degrees), T(Thickness mum)'''
    a1, a2, a3 = lat_params
    b1, b2, b3 = 1 / a1, 1 / a2, 1 / a3
    tmax, K = np.deg2rad(tmax), 1 / lam
    dqT = 10 / (T * 1e4) * np.array([-1, 1])
    #reciprocal lattice
    h, k = np.meshgrid(b1 * np.arange(-nx, nx + 1), b2 * np.arange(-1, ny))
    #sphere
    t = 3 * np.pi / 2 + np.linspace(-tmax, tmax, 100)
    plts = [[
        K * np.cos(t), K * np.sin(t) + K, 'r',
        r'$\lambda=%.2f\AA$' % lam
    ]]
    #rel rods
    plts += [[[h, h], k + dqT, 'b-', '']
             for h, k in zip(h.flatten(), k.flatten())]

    #display
    scat = [h, k, 15, 'b']
    fig, ax = dsp.stddisp(
        plts,
        scat=scat,
        labs=['$q_x$', '$q_y$'],
        lw=3,  #,xylims=[-nx*b1,nx*b1,-b2,ny*b2],xyTickLabs=[[],[]],
        **kwargs)
Exemplo n.º 27
0
def _test_orient(n=[1,1,1],**kwargs):
    coords = bcc_coords()
    coords = orient_crystal(coords,n)
    scat    = coords.T.tolist()
    fig,ax  = dsp.stddisp(scat=scat,ms=100,rc='3d',opt='',legOpt=0)
    show_unit_cell(ax,n,a=0.1,c='b',lw=2)
    W = np.sqrt(3);xylims = [-W/2,W/2,-W/2,W/2,0,W]
    dsp.standardDisplay(ax,xylims=xylims,gridOn=0,ticksOn=0,legOpt=0,**kwargs)
Exemplo n.º 28
0
 def Pq_show(self, **kwargs):
     '''Show Propagator function in q space '''
     q = fft.fftshift(self.q)
     Pq = fft.fftshift(self.Pq)
     plts = [[q, Pq.real, 'b', '$re$'], [q, Pq.imag, 'r', '$im$']]
     return dsp.stddisp(plts,
                        labs=[r'$q(\AA^{-1})$', '$P_q$'],
                        title='Propagator',
                        **kwargs)
Exemplo n.º 29
0
def find_xyz(lat_vec, lat_params, n_u, theta, plot=0, v=0):
    ax, by, cz = lat_params
    rot_vec = rcc.orient_crystal(lat_vec, n_u=n_u, T=True, theta=theta)
    # ra1,ra2,ra3 = rot_vec
    #### brute force unit cells generation
    N = np.ceil(1.5 * max(lat_params) / min(np.linalg.norm(lat_vec, axis=0)))
    u1 = np.arange(-N, N + 1)
    l, m, n = np.meshgrid(u1, u1, u1)
    #### l*a1+m*a2+n*a3
    lmn = np.vstack([l.flatten(), m.flatten(), n.flatten()]).T
    if v: print('...\torienting full mesh N=%d...' % N)
    xyz = lmn.dot(rot_vec)
    x, y, z = xyz.T
    if v: print('...\tkeeping valid unit cells...')
    idx = (x > 0) & (y > 0) & (z > 0) & (x < ax) & (y < by) & (z < cz)
    lmn = lmn[idx]

    if plot:
        print('N', N)
        print('rot_vec', rot_vec)
        l, m, n = lmn.T
        x, y, z = xyz[idx].T
        print('lminmax', l.min(), l.max(), m.min(), m.max(), n.min(), n.max())

        #### generate super cell corners
        l0, m0, n0 = np.meshgrid([0, 1], [0, 1], [0, 1])
        ax, by, cz = np.diag(lat_params)
        sc = np.vstack([
            ax * i + by * j + cz * k
            for i, j, k in zip(l0.flatten(), m0.flatten(), n0.flatten())
        ])
        x0, y0, z0 = sc.T
        #### get actual corners
        lat_p2 = np.linalg.norm(rot_vec, axis=0)**2
        nlm1 = np.array([np.round(rot_vec.dot(v) / lat_p2) for v in sc])
        print('corners', nlm1)
        x1, y1, z1 = nlm1.dot(rot_vec).T

        scat = ()
        scat += ([x0, y0, z0, 50, 'b', 'o'], )
        scat += ([x0, y0, z0, 50, 'g', 'd'], )
        scat += ([x, y, z, 20, 'r', 's'], )
        dsp.stddisp(rc='3d', scat=scat)
    return lmn.T
Exemplo n.º 30
0
 def Qxz_show(self, iZs=1, **kwargs):
     '''Show 2D wave propagation solution'''
     iZs = slice(0, -1, iZs)
     q, z = np.meshgrid(self.q, self.z[iZs])
     Pqs = self.psi_qz[iZs, :].copy()
     Pqs[:, 0] = 0
     im = [q, z, Pqs]
     return dsp.stddisp(im=im,
                        labs=[r'$q(\AA^{-1})$', r'$z(\AA)$'],
                        **kwargs)