Esempio n. 1
0
def gen_xyz(file, n=[0, 0, 1], rep=[1, 1, 1], pad=0, xyz='', **kwargs):
    ''' convert cif file into autoslic .xyz input file
    - file : cif_file
    - rep : super cell repeat
    - n : reorient of the z axis into n
    - pad : amount of padding on each side (in unit of super cell size)
    '''
    if isinstance(file, str):
        tail = ''.join(np.array(n, dtype=str)) + '.xyz'
        if file.split('.')[-1] == 'cif':
            crys = Crystal.from_cif(file)
            if not xyz: xyz = file.replace('.cif', tail)
        elif sum(np.array(list(Crystal.builtins)) == file):
            crys = Crystal.from_database(file)
            if not xyz: xyz = file + tail
        lat_vec = np.array(crys.lattice_vectors)
        lat_params = crys.lattice_parameters[:3]
        pattern = np.array([[a.atomic_number] + list(a.coords_cartesian) +
                            [a.occupancy, 1.0] for a in crys.atoms])
    else:
        if not xyz: raise Exception('xyz filename required')
        pattern = file
    pattern, lat = make_xyz(xyz,
                            pattern,
                            lat_vec,
                            lat_params,
                            n=n,
                            pad=pad,
                            rep=rep,
                            **kwargs)
    npy_file = xyz.replace('.xyz', '.npy')
    np.save(npy_file, [lat, pattern])
    print(colors.green + 'binary coords file saved :' + colors.yellow +
          npy_file + colors.black)
Esempio n. 2
0
def import_cif(file,
               xyz='',
               n=[0, 0, 1],
               rep=[1, 1, 1],
               pad=0,
               dopt='s',
               lfact=1.0,
               tail=''):
    ''' convert cif file into autoslic .xyz input file
    - file : cif_file
    - rep : super cell repeat
    - n : reorient of the z axis into n
    - pad : amount of padding on each side (in unit of super cell size)
    '''
    crys = Crystal.from_cif(file)
    lat_vec = np.array(crys.lattice_vectors)
    lat_params = crys.lattice_parameters[:3]
    pattern = np.array([[a.atomic_number] + list(lfact * a.coords_cartesian) +
                        [a.occupancy, 1.0] for a in crys.atoms])

    if xyz:
        make_xyz(xyz,
                 pattern,
                 lat_vec,
                 lat_params,
                 n=n,
                 pad=pad,
                 rep=rep,
                 fmt='%.4f',
                 dopt=dopt)
    pattern[:,
            1:4] = rcc.orient_crystal(pattern[:, 1:4],
                                      n_u=n)  #,lat_params #pattern,crys # file
    return pattern
Esempio n. 3
0
def import_crys(file):
    if file.split('.')[-1] == 'cif':
        crys = Crystal.from_cif(file)
    elif sum(np.array(list(Crystal.builtins)) == file):
        crys = Crystal.from_database(file)
    else:
        raise Exception('cannot import %s' % file)
    return crys
Esempio n. 4
0
def test_cif_vo2():
    """Test CIFParser on vo2.cif (monoclinic M1)"""
    VO2_path = Path(__file__).parent.parent / "cifs" / "vo2-m1.cif"
    vo2 = Crystal.from_cif(VO2_path)

    assert len(vo2) == 12
    assert np.allclose(vo2.lattice_parameters,
                       (5.743, 4.517, 5.375, 90.0, 122.6, 90.0))
    assert round(abs(vo2.volume - 117.466_153_0), 7) == 0  # from cif2cell
Esempio n. 5
0
    def load_cif(self):
        path, *_ = QtWidgets.QFileDialog.getOpenFileName(
            parent=self, caption="Load structure from CIF", filter="*.cif"
        )
        if not path:
            return

        self.crystal = Crystal.from_cif(path)
        self.new_crystal.emit(self.crystal)
Esempio n. 6
0
def test_cif_international_number(file):
    """Test that the international space group number  found by
    CIFParser is the same as spglib's"""
    with CIFParser(file) as p:
        from_parser = Hall2Number[p.hall_symbol()]

        crystal = Crystal.from_cif(file)
        from_spglib = crystal.international_number
        assert from_parser == from_spglib
Esempio n. 7
0
def test_cif_writer_idempotence(name):
    """ Test that conversion to CIF of a structure loaded from CIF is idempotent. """
    # Testing on all built-in structure assures us that corner cases
    # are taken care of.
    cryst = Crystal.from_database(name)
    with tempfile.TemporaryDirectory() as temp_dir:
        f = Path(temp_dir) / "temp.cif"
        cryst.to_cif(f)
        cryst2 = Crystal.from_cif(f)
        assert cryst == cryst2
Esempio n. 8
0
    def test_vo2(self):
        """ Test CIFParser on vo2.cif (monoclinic M1) """
        VO2_path = os.path.join("crystals", "cifs", "vo2-m1.cif")
        vo2 = Crystal.from_cif(VO2_path)

        self.assertEqual(len(vo2), 12)
        self.assertTrue(
            np.allclose(vo2.lattice_parameters,
                        (5.743, 4.517, 5.375, 90.0, 122.6, 90.0)))
        self.assertAlmostEqual(vo2.volume, 117.466_153_0)  # from cif2cell
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)
Esempio n. 10
0
    def test_international_number(self):
        """ Test that the international space group number  found by 
        CIFParser is the same as spglib's """
        for name in self._cif_files():
            with self.subTest(name.split("\\")[-1]):
                with CIFParser(name) as p:
                    from_parser = Hall2Number[p.hall_symbol()]

                    crystal = Crystal.from_cif(name)
                    from_spglib = crystal.international_number
                    self.assertEqual(from_parser, from_spglib)
Esempio n. 11
0
    def test_idempotence(self):
        """ Test that conversion to CIF of a structure loaded from CIF is idempotent. """
        # Testing on all built-in structure assures us that corner cases
        # are taken care of.
        for name in Crystal.builtins:
            with self.subTest(f"CIF idempotence {name}"):

                cryst = Crystal.from_database(name)
                with tempfile.TemporaryDirectory() as temp_dir:
                    f = Path(temp_dir) / "temp.cif"
                    cryst.to_cif(f)
                    cryst2 = Crystal.from_cif(f)
                    self.assertEqual(cryst, cryst2)
Esempio n. 12
0
def import_cif(cif_file, xyz_file=None, rep=[1, 1, 1], bfacts=None, pad=0):
    ''' convert cif file into autoslic .xyz input file
    - cif_file : file to import
    - rep : super cell repeat
    - pad : amount of padding on each side (in unit of super cell size)
    returns :
    - saves cif_file.xyz
    '''
    if not bfacts: bfacts = {1: 0.01, 6: 0.06, 7: 0.07, 8: 0.08}

    crys = Crystal.from_cif(cif_file)
    lat_params = np.array(crys.lattice_parameters[:3])
    Za = np.array([a.atomic_number for a in crys.atoms])
    occ = np.array([a.occupancy for a in crys.atoms])
    bfact = np.array([bfacts[Z] for Z in Za])  #np.ones(Za.shape)
    coords = np.array([a.coords_cartesian for a in crys.atoms])

    if isinstance(rep, int): rep = [rep] * 3  #;print(rep)
    Nx, Ny, Nz = rep
    ax, by, cz = lat_params

    #replicate
    if Nx + Ny + Nz > 3:
        ni, nj, nk = np.meshgrid(range(Nx), range(Ny), range(Nz))
        ni, nj, nk = ni.flatten(), nj.flatten(), nk.flatten()
        a1, a2, a3 = np.array(crys.lattice_vectors)
        coords = np.vstack(
            [coords + i * a1 + j * a2 + k * a3 for i, j, k in zip(ni, nj, nk)])
        Za = np.tile(Za, [ni.size])
        occ = np.tile(occ, [ni.size])
        bfact = np.tile(bfact, [ni.size])
        lat_params[0] = Nx * ax
        lat_params[1] = Ny * by
        lat_params[2] = Nz * cz

    #apply padding
    if pad:
        coords[:, 0] += Nx * ax * pad
        coords[:, 1] += Ny * by * pad
        coords[:, 2] += Nz * cz * pad
        lat_params[0] *= 1 + 2 * pad
        lat_params[1] *= 1 + 2 * pad
        lat_params[2] *= 1 + 2 * pad

    #save
    # print(Za.shape,coords.shape)
    pattern = np.hstack([Za[:, None], coords, occ[:, None], bfact[:, None]])
    if not xyz_file: xyz_file = cif_file.replace('.cif', '.xyz')
    make_xyz(xyz_file, pattern, lat_params, fmt='%.4f')
Esempio n. 13
0
def APAP_xyz(name, n=[0, 0, 1], rep=[1, 1, 1], dopt='scp', lfact=1.0, tail=''):
    path = os.path.dirname(name) + '/'
    crys = Crystal.from_cif(path + 'paracetamol.cif')
    lat_vec = np.array(crys.lattice_vectors)
    if sum(rep) > 3: crys = crys.supercell(rep[0], rep[1], rep[2])
    pattern = np.array([[a.atomic_number] + list(lfact * a.coords_cartesian) +
                        [a.occupancy, 1.0] for a in crys.atoms])
    file = path + 'APAP%s.xyz' % tail
    pattern, lat_params = mupy.make_xyz(file,
                                        pattern,
                                        lat_vec,
                                        n,
                                        fmt='%.4f',
                                        dopt=dopt)
    return pattern, lat_params  #pattern,crys # file
Esempio n. 14
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)
Esempio n. 15
0
def make_mulslice_datfile(dat_file, cif_file):
    ''' create a data file used by atompot(mulslice) from a cif file
    - dat_file : name of file to save
    - cif_file : the file to import
    '''
    crys = Crystal.from_cif(cif_file)
    pattern = np.array(
        [np.hstack([a.coords_cartesian, a.atomic_number]) for a in crys.atoms])
    deck = ' '.join(np.array(crys.lattice_parameters[:3], dtype=str)) + '\n'
    deck += '0\n'
    Za = np.array(np.unique(pattern[:, -1]), dtype=int)
    for Z in Za:
        deck += str(Z) + '\n'  #; print()
        xyz = np.array(pattern[pattern[:, -1] == 1][:, :3], dtype=str)
        xyz = '\n'.join([' '.join(l) for l in xyz])  #; print(xyz)
        deck += xyz + '\n'
    deck += '\n\nComment here'
    with open(dat_file, 'w') as f:
        f.write(deck)
Esempio n. 16
0
    def __init__(self,pts_file,cif_file=None,gen=False):
        '''
        - pts_file : str - full path to .pts file
        - cif_file : str - full path to .cif file (automatically found if None)
        - gen      : bool - regenerate if True
        '''
        self.name  = os.path.basename(pts_file).split('.pts')[0] #;print(self.name)
        self.path  = os.path.dirname(pts_file)
        self.out   = self.path+'/dat/'

        self.cif_file   = self._get_cif_file(cif_file)
        self.crys       = Crystal.from_cif(self.cif_file)
        self.lat_vec    = np.array(self.crys.lattice_vectors)
        self.lat_vec1   = np.array(self.crys.reciprocal_vectors)/(2*np.pi)
        self.lat_params = self.crys.lattice_parameters

        gen |= not os.path.exists(self.out)
        # if os.path.exists(self.out):gen |= not os.path.exists(self.out+'rpl.txt')
        if gen:self.convert_pets()
        self.load_all()
        self.nFrames = self.uvw.shape[0]
Esempio n. 17
0
def show_setup(name, gopts=['xy', 'yz', 'xz'], **kwargs):
    xyz_name = dsp.basename(name)
    for opts in gopts:
        figname = figpath + xyz_name.replace('.xyz', '') + opts + '.png'
        mut.show_grid(name, opts, name=figname, **kwargs)

    # dials.frame_orientations integrated.expt

    # n= np.array([-1249.0467359091645, 494.06323332809154, 1151.1835101484317])/200
    # n = 10*np.array([-1.51089556, -0.51374498, 0.65074564])
    # array([-0.08540403, -0.02904403,  0.0367669 ])
    angles = np.deg2rad([134.61, 106.78, 49.40])
    crys = Crystal.from_cif(cif_file)
    lat_vec = np.array(crys.lattice_vectors)
    lat_params = np.array(crys.lattice_parameters[:3])

    n = np.array([-0.08540851, -0.02904118, 0.03678561]) * lat_params
    ## original structure
    # name = path+'ireloh111.xyz'
    # rcc.import_cif(cif_file,xyz=name)
    #
    # fig,ax = mut.show_grid3(name,opt='',ms=50)
    # rcc.show_unit_cell(ax,a=0.2,c='b',lw=2,lat_params=crys.lattice_parameters[:3])
    # rcc.show_trihedron(ax,uvw=np.array([n]) ,x0=[0,0,0],cs=['k--'],clabs=['beam'],lw=3,rc=0.1,h=0.2,opt='')
    # rcc.show_trihedron(ax,uvw=lat_vec,x0=[0,0,0],cs=['r--','g--','b--'],clabs=['$a$','$b$','$c$'],lw=3,rc=0.1,h=0.2,
    #     labs=['$x$','$y$','$z$'],xylims=[-10,15,-10,15,-5,20],view=[10,-20],name=figpath+'1_484_xyz.png',opt='p')
    #
    # ## rotated structure
    ez = [0, 0, -1]

    uvw = rcc.orient_crystal(lat_vec, n_u=n / np.linalg.norm(n), ez=ez)
    n_rot = rcc.orient_crystal(n, n_u=n / np.linalg.norm(n), ez=ez)

    np.rad2deg(np.arccos(uvw.dot([0, 0, -1]) / lat_params))

    a = 0
    # a = np.deg2rad(225)

    uvw = np.array([rotz(a).dot(u) for u in uvw])
    # n_rot = rotz(a).dot(n_rot)

    mut.import_cif(cif_file, xyz=name, n=n)
    #
    # fig,ax = mut.show_grid3(name,opt='',ms=50)
    # rcc.show_unit_cell(ax,n=n,a=0.2,c='b',lw=2,lat_params=crys.lattice_parameters[:3])
    # rcc.show_trihedron(ax,uvw=np.array([n_rot]) ,x0=[0,0,0],cs=['k'],clabs=['beam'],lw=3,rc=0.1,h=0.2,opt='')
    # rcc.show_trihedron(ax,uvw=uvw    ,x0=[0,0,0],cs=['r','g','b'],clabs=['$a$','$b$','$c$'],lw=3,rc=0.1,h=0.2,
    #     labs=['$x$','$y$','$z$'],xylims=[-10,20,-10,20,-10,20],view=[20,-100],name=figpath+'1_484_rot.png',opt='p')

    # fig,ax = mut.show_grid3(name,opt='',ms=50)
    # name = path+'ireloh111_rotated484.xyz'
    # rcc.show_unit_cell(ax,n=n,a=0.2,c='b',lw=2,lat_params=crys.lattice_parameters[:3])
    # rcc.show_trihedron(ax,uvw=np.array([n_rot]) ,x0=[0,0,0],cs=['k'],clabs=['beam'],lw=3,rc=0.1,h=0.2,opt='')
    # rcc.show_trihedron(ax,uvw=uvw    ,x0=[0,0,0],cs=['r','g','b'],clabs=['$a$','$b$','$c$'],lw=3,rc=0.1,h=0.2,
    #     labs=['$x$','$y$','$z$'],xylims=[-10,20,-10,20,-10,20],view=[20,10],name=figpath+'1_484_dav.png',opt='p')

    rsa = np.array([
        [5.75197579, 1.08642157, 5.77468802],
        [-1.09493538, -9.45325930, 2.86911892],
        [12.49046736, -4.94063233, -11.5118351],
    ])
    rsa_ = mut.get_reciprocal(rsa)

    # name = path+'ireloh111_SRFU.xyz'
    a, b, c = crys.lattice_parameters[:3]
    fig, ax = dsp.stddisp(rc='3d')
    # fig,ax = mut.show_grid3(name,opt='',ms=50)
    # rcc.show_unit_cell(ax,n=n,ez=ez,a=0.2,c='b',lw=2,lat_params=[a,b,c])
    # rcc.show_unit_cell(ax,a=0.05,c='b',lw=2,lat_params=[a,b,c],ls='--')
    rcc.show_trihedron(ax,
                       uvw=np.array([10 * n, 10 * n_rot, [10, 0, 0]]),
                       x0=[0, 0, 0],
                       cs=['k-.', 'k--', 'k-'],
                       clabs=['beam', '$b_z$', 'phi'],
                       lw=3,
                       rc=0.1,
                       h=0.2)
    # rcc.show_trihedron(ax,uvw=np.array() ,x0=[0,0,0],cs=['k'],clabs=['beam'],lw=3,rc=0.1,h=0.2,opt='')
    # rcc.show_trihedron(ax,uvw=rsa    ,x0=[0,0,0],cs=['r-','g-','b-']   ,clabs=['$a$','$b$','$c$'],lw=3,rc=0.1,h=0.2)
    rcc.show_trihedron(ax,
                       uvw=rsa_,
                       x0=[0, 0, 0],
                       cs=['r--', 'g--', 'b--'],
                       clabs=['$a^{*}$', '$b^{*}$', '$c^{*}$'],
                       lw=3,
                       rc=0.1,
                       h=0.2)
    # rcc.show_trihedron(ax,uvw=uvw1   ,x0=[0,0,0],cs=['r','g','b'],clabs=['$a1$','$b1$','$c1$'],lw=3,rc=0.1,h=0.2)
    # rcc.show_trihedron(ax,uvw=uvw    ,x0=[0,0,0],cs=['r','g','b'],clabs=['$a$','$b$','$c$'],lw=3,rc=0.1,h=0.2,

    dsp.stddisp(ax=ax,
                fig=fig,
                labs=['$x$', '$y$', '$z$'],
                xylims=np.array([-10, 20, -10, 20, -10, 20]),
                view=[20, 10],
                name=figpath + '1_484_dav.png',
                opt='p')
Esempio n. 18
0
def test_cif_uncertainties_issue7():
    """Test that the CIF parser handles atomic positions with uncertainties (issue #7)."""
    path = Path(__file__).parent / "data" / "issue7.cif"
    Crystal.from_cif(path)
Esempio n. 19
0
import importlib as imp
import pickle
from scattering.structure_factor import structure_factor3D
import multislice.multislice as mupy; imp.reload(mupy)
import multislice.postprocess as pp ; imp.reload(pp)
import multislice.mupy_utils as mut ; imp.reload(mut)
from crystals import Crystal
from utils import*
plt.close('all')
path = '../dat/biotin/'
figpath = '../docs_fig/'
file = path+'biotin.cif'
opts = 'T '  #E(Ewald) T(tilts) B(Beams)F(structFact)


crys = Crystal.from_cif(file)
lat_params = crys.lattice_parameters[:3]
a1,a2,a3 = lat_params
b12 = np.sqrt(1/a1**2+1/a2**2)

fs = {'leg':30,'lab':40,'tick':25}
if 'E' in opts:
    #Ewald configuration [010]
    mut.ewald_sphere(lat_params,lam=cst.eV2mum(12000)*1e4,tmax=60,T=20.,nx=5 ,ny=20,opt='p',name=figpath+'E_MX.png',xylims=[-1,1.01,-0.1,2.01],xyTicks=1,legLoc='upper right',fonts=fs)
    mut.ewald_sphere(lat_params,lam=cst.keV2lam(200)     ,tmax=7 ,T=0.2,nx=20,ny=10,opt='p',name=figpath+'E_ED.png',xylims=[-3,3.01,-0.1,1.01],xyTicks=1,legLoc='upper right',fonts=fs)

if 'B' in opts:
    df = pd.read_pickle(path+'df0.pkl')
    p1 = pp.load_multi_obj(path+'biotin_m0_autoslic.pkl')
    p1.datpath = p1.datpath.replace('ronan','tarik')
    p1.get_beams(bOpt='na')
Esempio n. 20
0
def test_cif_compatibility(file):
    """Test the CIFParser on all CIF files stored herein to check build errors"""
    Crystal.from_cif(file)
Esempio n. 21
0
 def test_issue_5(self):
     """ Test that the parsing of MgSiO3 is working. See Issue 5 for details on why this was a problem. """
     c = Crystal.from_cif(
         Path(__file__).parent / "data" / "issue5_MgSiO3.cif")
     self.assertEqual(len(c), 20)
Esempio n. 22
0
imp.reload(ms)
import multislice.multi_3D as MS3D
imp.reload(MS3D)
import multislice.mupy_utils as mut
imp.reload(mut)
from crystals import Crystal
plt.close('all')
path = '../../multislice/docs_fig/multi3D/'
new = 1
name = 'dat/test.pkl'

#cif file for alpha-glycine from :
#https://pubs.acs.org/doi/suppl/10.1021/cg101059c/suppl_file/cg101059c_si_002.pdf
cif_file = 'dat/alpha_glycine.cif'
# xyz_file = cif_file.replace('.cif','.xyz')
crys = Crystal.from_cif(cif_file)
lat_vec = np.array(crys.lattice_vectors)
pattern = mut.import_cif(cif_file)  #,xyz=xyz_file)#

pattern[:, 3] -= pattern[:, 3].min()

lat_params = lat_vec.max(axis=0) - lat_vec.min(axis=0)
# mut.plot_grid(pattern,lat_params,'xy',equal=True,ms=20)
# mut.plot_grid(pattern,lat_params,'xz',equal=True,ms=20)
# mut.plot_grid(pattern,lat_params,'yz',equal=True,ms=20)

if new:
    ax, by, cz = lat_params
    mp = MS3D.Multi3D(pattern,
                      ax,
                      by,
Esempio n. 23
0
def test_pwscf_lattice_vectors_alat(poscar):
    """Test POSCAR parser against CIF parser"""
    c0 = Crystal.from_cif(Path(__file__).parent / "data" / "issue5_MgSiO3.cif")
    c1 = Crystal.from_poscar(Path(__file__).parent / "data" / poscar)
    assert c0 == c1
Esempio n. 24
0
print ('* BiCRYSTAL--', now,'\n\n')
print ('**************************************************************************\n \n')

# reading csv with elements from workspace
# i.e. directory where you installed bicrystal
with open('workspace') as f:
    line = f.readline()
program_directory = str(line).rstrip("\n")
dir1 = os.path.join("" +program_directory+"", 'periodic_table.csv')
colnames = ['number', 'symbol']
periodic_table = pandas.read_csv(dir1, usecols=colnames)
number = periodic_table.number.tolist()
symbol = periodic_table.symbol.tolist()

# Input crystal
my_crystal = Crystal.from_cif(input('***Input cif file*** \n'))
#print (my_crystal)

# Input super cell parameters and rotation angle
print ('\n***Rotation parameters*** ')
m = int(input('Enter m '))
n = int(input('Enter n '))
#rotation_angle = float(input('Enter rotation angle '))

# lattice parameters
a, b, c, alpha, beta, gamma = my_crystal.lattice_parameters

# specify vacuum size in bohr
#print('\n***Specify z-coordinate in cell parameter***')
#print ('(Default = ', c*1.8897259886,' Bohr)')
#vacuum = float(input('Enter z value [Bohr] '))
Esempio n. 25
0
 def test_compatibility(self):
     """ Test the CIFParser on all CIF files stored herein to check build errors"""
     for name in self._cif_files():
         with self.subTest(name.split("\\")[-1]):
             Crystal.from_cif(name)
Esempio n. 26
0
def plot_diff_pattern(intensity_dict):
    max_intensity = max(intensity_dict[key][3] * intensity_dict[key][1]
                        for key in intensity_dict)
    for d_key in intensity_dict:
        two_theta = intensity_dict[d_key][0]
        multiplicity = intensity_dict[d_key][3]
        rel_intensity = multiplicity * intensity_dict[d_key][1] / max_intensity
        hkl = intensity_dict[d_key][2]
        plt.axvline(two_theta, 0, rel_intensity, label=hkl)
    plt.xlabel("Angle (2$\Theta$)")
    plt.ylabel("Relative Intensity (counts)")
    #plt.xlim(15, 80)
    mplcursors.cursor(hover=True)
    plt.show()


# Cu = Crystal.from_mp(api_key="0qweAvX1EkrqqHzp", query = "mp-30")
Cu = Crystal.from_cif("D:/Clement Research/xrd/cif/Cu.cif")
Si = Crystal.from_database('Si')
Diamond = Crystal.from_cif("D:/Clement Research/xrd/cif/diamond.cif")
NaMnFe = Crystal.from_cif("D:/Clement Research/xrd/cif/Na2Mn2Fe(VO4)3.cif")
print(list(Cu.unitcell))
# print(Cu)
#sf = calculate_structure_factor(Cu.unitcell, 1, 1, 1)
peaks = calculate_peaks(Cu, 1.54059)
#print(peaks)
plot_diff_pattern(peaks)
#print(peaks)
#sf = structure_factor()
Esempio n. 27
0
    def test_silicon(self):
        """ Test CIFParser on Si.cif (diamond structure) """
        Si_path = os.path.join("crystals", "cifs", "Si.cif")
        si = Crystal.from_cif(Si_path)

        self.assertEqual(len(si), 8)
Esempio n. 28
0
def test_cif_silicon():
    """Test CIFParser on Si.cif (diamond structure)"""
    Si_path = Path(__file__).parent.parent / "cifs" / "Si.cif"
    si = Crystal.from_cif(Si_path)

    assert len(si) == 8
Esempio n. 29
0
from crystals import Crystal,Atom,symmetry_expansion,write_xyz
# import rotating_crystal as rcc; imp.reload(rcc)

cif='225.cif'  #201(SC), 212,225,229

lattice_vectors = np.diag([2,2,2])
cCIF = Crystal.from_cif('../dat/Carbone_SC/'+cif)
# cCIF = Crystal.from_database('Fe')
syms = cCIF.symmetry_operations()
atoms = [Atom(z, c) for z,c in zip(['C','C','C'], [[0.5,0.5,0],[0,0.5,0.5],[0.5,0.,0.5]]) ]
# atoms = [Atom('C', [0.5,0.5,1])]
# atoms = [Atom('C', [1.,1.,1.])]
syms4 = [ np.hstack([np.vstack([s[0],[0,0,0]]), np.vstack([s[1][:,None],1]) ]) for s in syms]
unitcell = symmetry_expansion(atoms,syms4)
C = Crystal(unitcell, lattice_vectors)
print('international_number:', cCIF.symmetry()['international_number'])
print('international_number:', C.symmetry()['international_number'])
print(C)
# write_xyz(C,'test.xyz')
def rotate_xyz(file,nx,nz,Nx=40,Nz=5,name='',opt='',**kwargs):
    '''Generates .xyz files corresponding to individual rotation
    - file : path to cif file (.xyz files will be put in the same folder )
    - Nrot : number of rotation to perform within 0,pi/2
    '''
    crys = file
    if isinstance(file,str):
        crys = Crystal.from_cif(file)
        if not name : name = file.replace('.cif','')

    a1,a2,a3    = np.array(crys.lattice_vectors)
    ax1,by2,cz3 = np.array(crys.lattice_parameters[:3])
    nxz   = int(cz3/ax1)
    #int(nx.max()+nxz*nz.max()), int(nx.max()/nxz+nz.max())
    xy0   = (0,(Nz-nz.max())*cz3)
    print('super cell calculation ...')
    crys0   = crys.supercell(Nx,1,Nz)
    pattern = np.array([
        [a.atomic_number]+list(a.coords_cartesian)+[a.occupancy,wobbles[a.atomic_number]] for a in crys0.atoms])
    coords0 = np.array([a.coords_cartesian for a in crys0.atoms])

    files = []
    Cs = [cs[E] for E in pattern[:,0]]
    for i1,i2 in zip(nx,nz):
        # i1,i2 = i,Nrot-i; n0 = gcd(i1,i2)
        # i1,i2 = i1/n0,i2/n0;#print(i1,i2)
        cz = i1*a1+i2*a3; #print(cz)
        ax = np.array([cz[1],-cz[0]]); #print(cz)
        c,angle = np.linalg.norm(cz),np.arctan(cz[0]/cz[2])
        if not i1%i2*nxz:
            n0 = i1/gcd(i1,i2*nxz)
            if not n0%2 : n0/=2
            a = np.linalg.norm([i2*nxz/i1,1])*cz3*n0
        else:
            a = np.linalg.norm([i2*nxz,i1])*cz3
        # a = np.linalg.norm([i2*nxz,i1])*cz3

        print(green+'i1=%d,i2=%d,angle=%.2f' %(i1,i2,angle*180/np.pi)+black)
        rect=Rectangle(xy0,1.0*a,1.0*c,angle=-angle*180/np.pi,edgecolor='k',linewidth=2,alpha=0.1)
        print('finding points ...')
        idc = rect.contains_points(coords0[:,[0,2]],radius=0.001)
        print('done')
        n   = (i1,0,i2)
        xyz = name+'%d%d%d.xyz' %n
        if opt:
            path = dsp.dirname(name)

            x,z = coords0[:,[0,2]].T;
            x0,z0 = (coords0[idc,:])[:,[0,2]].T
            X,Z = np.hstack([x,x0]),np.hstack([z,z0])
            S = np.array([10]*x.size+[30]*x0.size)
            C = Cs+list(np.array(Cs)[idc,:])
            dsp.stddisp(scat=[X,Z,S,C],patches=[rect],equal=1,figsize='12',
                xyTicks=[ax1,cz3],pOpt='tGeX',xylims=[0,40*ax1,-10*cz3,10*cz3],
                opt=opt,name=path+'figures/'+dsp.basename(xyz).replace('xyz','png'))
            plt.show()

        lat_vec = [a,a2[1],c]#np.array([Nrot*(a3+a1),a2,Nrot*(a3-a1)])#
        cc = coords0[idc,:]
        cc[:,2]-=xy0[1]
        coords  = Rot(-angle).dot(cc.T).T
        pattern[idc,1:4] = coords
        # make_xyz(xyz,pattern[idc,:],np.diag(lat_vec),n,fmt='%.4f',dopt='s')
        files+=[xyz] #dsp.basename(xyz)]
    return files