How to use the pyxtal.crystal.random_crystal function in pyxtal

To help you get started, we’ve selected a few pyxtal examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github qzhu2017 / PyXtal / pyxtal / test_cases / test_all.py View on Github external
print("pyxtal.crystal")
    reset()
    try:
        import pyxtal.crystal
    except Exception as e:
        fail(e)

    print("  random_crystal")
    try:
        from pyxtal.crystal import random_crystal
    except Exception as e:
        fail(e)

    if passed():
        try:
            c = random_crystal(1, ["H"], [1], 10.0)
            if c.valid is True:
                pass
            else:
                fail()
        except Exception as e:
            fail(e)

    check()

    print("  random_crystal_2D")
    try:
        from pyxtal.crystal import random_crystal_2D
    except Exception as e:
        fail(e)

    if passed():
github qzhu2017 / PyXtal / pyxtal / test_cases / test_all.py View on Github external
def check_struct_group(crystal, group, dim=3, tol=1e-2):
    # Supress pymatgen/numpy complex casting warnings
    from pyxtal.crystal import random_crystal
    from pyxtal.molecular_crystal import molecular_crystal
    from copy import deepcopy
    import warnings

    with warnings.catch_warnings():
        warnings.simplefilter("ignore")

        """Given a pymatgen structure, group number, and dimension, return
        whether or not the structure matches the group number."""
        if isinstance(crystal, (random_crystal, molecular_crystal)):
            lattice = crystal.struct.lattice.matrix
            if dim != 0:
                old_coords = deepcopy(crystal.struct.frac_coords)
                old_species = deepcopy(crystal.struct.atomic_numbers)
            elif dim == 0:
                old_coords = deepcopy(crystal.cart_coords)
                old_species = deepcopy(crystal.species)
        else:
            lattice = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
            old_coords = np.array(crystal)
            old_species = ["C"] * len(old_coords)

        from pyxtal.symmetry import distance
        from pyxtal.symmetry import filtered_coords
        from copy import deepcopy
github qzhu2017 / PyXtal / scripts / pyxtal_atom.py View on Github external
raise ValueError("Volume factor {:.2f} must be greater than 0.".format(factor))

    verbosity = options.verbosity
    attempts = options.attempts
    outdir = options.outdir
    dimension = options.dimension
    thickness = options.thickness

    if not os.path.exists(outdir):
        os.mkdir(outdir)

    for i in range(attempts):
        numIons0 = np.array(numIons)
        start = time()
        if dimension == 3:
            rand_crystal = random_crystal(sg, system, numIons0, factor)
        elif dimension == 2:
            rand_crystal = random_crystal_2D(sg, system, numIons0, thickness, factor)
        elif dimension == 1:
            rand_crystal = random_crystal_1D(sg, system, numIons0, thickness, factor)
        if dimension == 0:
            rand_crystal = random_cluster(sg, system, numIons0, factor)
        end = time()
        timespent = np.around((end - start), decimals=2)

        if rand_crystal.valid:
            # Output a cif or xyz file
            comp = str(rand_crystal.struct.composition)
            comp = comp.replace(" ", "")
            if dimension > 0:
                outpath = outdir + "/" + comp + ".cif"
                CifWriter(rand_crystal.struct, symprec=0.1).write_file(filename=outpath)
github qzhu2017 / PyXtal / C.py View on Github external
from pyxtal.interface.gulp import GULP
from pyxtal.crystal import random_crystal
from ase import Atoms
import os
from spglib import get_symmetry_dataset

file = "C-POSCARs"
if os.path.exists(file):
    os.remove(file)
for i in range(100):
    struc = random_crystal(19, ["C"], [16], 1.0)
    if struc.valid:
        calc = GULP(struc, ff="tersoff.lib")
        calc.run()
        s = Atoms(struc.sites, scaled_positions=calc.positions, cell=calc.cell)
        info = get_symmetry_dataset(s, symprec=1e-1)
        s.write("1.vasp", format='vasp', vasp5=True, direct=True)
        os.system("cat 1.vasp >> " + file)
        print("{:4d} {:8.3f} {:s}".format(i, calc.energy, info['international']))
        #print(calc.stress)
github qzhu2017 / PyXtal / examples / example_01_3D_VASP.py View on Github external
t0 = time()

for i in range(N):
    run = True
    while run:
        sg = randint(2, 230)
        species = []
        numIons = []
        for ele in elements.keys():
            species.append(ele)
            if len(elements[ele]) == 2:
                numIons.append(randint(elements[ele][0], elements[ele][1]))
            else:
                numIons.append(elements[ele])

        crystal = random_crystal(sg, species, numIons, factor)

        if crystal.valid:
            struc = crystal.struct
            run = False

    print(
        "SG requested: {0:3d} Vol: {1:6.2f} Time: {2:6.1f} mins".format(
            sg, struc.volume, (time() - t0) / 60.0
        )
    )
    dir1 = str(i) + "-" + str(struc.formula).replace(" ", "")
    [strucs, energies, times] = optimize(struc, dir1, modes=modes)

    os.chdir(dir0)
    if len(strucs) == len(modes):
        dump_json(strucs, energies, times, json1, json2)
github qzhu2017 / PyXtal / pyxtal / crystal.py View on Github external
thickness=None,
        lattice=None,
        sites = None,
        tm=Tol_matrix(prototype="atomic"),
    ):
        self.dim = 2
        self.PBC = [1, 1, 0]

        if type(group) != Group:
            group = Group(group, self.dim)
        number = group.number  # The layer group number of the crystal
        self.thickness = thickness  # in Angstroms, in the 3rd dimenion of unit cell
        self.init_common(species, numIons, factor, number, lattice, sites, tm)


class random_crystal_1D(random_crystal):
    """
    A 1d counterpart to random_crystal. Generates a random atomic crystal based
    on a 1d Rod group instead of a 3d spacegroup. The generated pymatgen
    structure can be accessed via self.struct

    Args:
        group: the Rod group number between 1 and 75. NOT equal to the
            international space group number, which is between 1 and 230
            OR, a pyxtal.symmetry.Group object
        species: a list of atomic symbols for each ion type
        numIons: a list of the number of each type of atom within the
            primitive cell (NOT the conventional cell)
        area: the effective cross-sectional area, in Angstroms squared, of the
            unit cell
        factor: a volume factor used to generate a larger or smaller
            unit cell. Increasing this gives extra space between atoms
github qzhu2017 / PyXtal / pyxtal / crystal.py View on Github external
)
                        species_tmp.extend([specie] * len(coords_toadd))
                        wyckoff_sites_tmp.append(current_site)
                        numIon_added += len(coords_toadd)

                        # Check if enough atoms have been added
                        if numIon_added == numIon:
                            return coordinates_tmp, species_tmp, wyckoff_sites_tmp

            cycle3 += 1
            self.numattempts += 1

        return None


class random_crystal_2D(random_crystal):
    """
    A 2d counterpart to random_crystal. Generates a random atomic crystal based
    on a 2d layer group instead of a 3d spacegroup. Note that each layer group
    is equal to a corresponding 3d spacegroup, but without periodicity in one
    direction. The generated pymatgen structure can be accessed via self.struct

    Args:
        group: the layer group number between 1 and 80. NOT equal to the
            international space group number, which is between 1 and 230
            OR, a pyxtal.symmetry.Group object
        species: a list of atomic symbols for each ion type
        numIons: a list of the number of each type of atom within the
            primitive cell (NOT the conventional cell)
        thickness: the thickness, in Angstroms, of the unit cell in the 3rd
            dimension (the direction which is not repeated periodically)
        factor: a volume factor used to generate a larger or smaller
github Tomoki-YAMASHITA / CrySPY / CrySPY / gen_struc / random / gen_pyxtal.py View on Github external
else:
            raise ValueError('init_pos_path is wrong.'
                             ' init_pos_path = {}'.format(init_pos_path))
        # ---------- initialize
        self.init_struc_data = {}
        # ---------- loop for structure generattion
        while len(self.init_struc_data) < nstruc:
            # ------ spgnum --> spg
            if self.spgnum == 'all':
                spg = random.randint(1, 230)
            else:
                spg = random.choice(self.spgnum)
            if spg in self.spg_error:
                continue
            # ------ generate structure
            tmp_crystal = random_crystal(spg, self.atype,
                                         self.nat, self.vol_factor)
            if tmp_crystal.valid:
                tmp_struc = tmp_crystal.struct    # pymatgen Structure format
                # -- check nat
                if not self._check_nat(tmp_struc):
                    # pyxtal returns conventional cell, that is, too many atoms
                    tmp_struc = tmp_struc.get_primitive_structure()
                    # recheck nat
                    if not self._check_nat(tmp_struc):    # failure
                        continue
                # -- sort, just in case
                tmp_struc = sort_by_atype(tmp_struc, self.atype)
                # -- check actual space group
                try:
                    spg_sym, spg_num = tmp_struc.get_space_group_info(
                        symprec=self.symprec)
github qzhu2017 / PyXtal / pyxtal / interface / LJ.py View on Github external
for index in inices:
                m2[index] = value
        elif len(indices) == 3:
            total = 0
            for index in indices:
                total += stress[index]        
            value = np.cbrt(total)
            for index in inices:
                m2[index] = value
        return m2

from pyxtal.crystal import random_crystal
from spglib import get_symmetry_dataset

for i in range(10):
    crystal = random_crystal(11, ['C'], [4], 1.0)
    if crystal.valid:
        crystal1 = deepcopy(crystal)
        test = LJ(epsilon=0.01, sigma=3.40, rcut=8.0)
        struc = (crystal1.lattice_matrix, crystal1.frac_coords, [6]*4)
        eng, enth, force, stress = test.calc(crystal1)
        sg =  get_symmetry_dataset(struc)['number']
        print('\nBefore relaxation Space group:            {:4d}   Energy: {:12.4}  Enthalpy: {:12.4}'.format(sg, eng, enth))
    
        dyn1 = FIRE(crystal1, test, f_tol=1e-5, dt=0.2, maxmove=0.2) #, symmetrize=True)
        dyn1.run(500)
        eng, enth, force, stress = test.calc(crystal1)
        struc = (dyn1.struc.lattice_matrix, dyn1.struc.frac_coords, [6]*4)
        sg =  get_symmetry_dataset(struc, symprec=0.1)['number']
        print('After relaxation without symm Space group: {:4d}  Energy: {:12.4}  Enthalpy: {:12.4}'.format(sg, eng, enth))

        dyn1 = FIRE(crystal, test, f_tol=1e-5, dt=0.2, maxmove=0.2, symmetrize=True)