Esempio n. 1
0
    def generate_defects(self,
                         enforce_c_size=10.0,
                         on_conventional_cell=False,
                         extend=1):
        """Provide function to generate defects."""
        atoms = self._atoms
        if on_conventional_cell:
            atoms = Spacegroup3D(atoms).conventional_standard_structure
        a = atoms.lattice.lat_lengths()[0]
        b = atoms.lattice.lat_lengths()[1]
        c = atoms.lattice.lat_lengths()[2]
        if enforce_c_size is not None:
            dim1 = int(float(enforce_c_size) / float(a)) + extend
            dim2 = int(float(enforce_c_size) / float(b)) + extend
            dim3 = int(float(enforce_c_size) / float(c)) + extend
            # atoms = atoms.make_supercell([dim1, dim2, dim3])
            supercell_size = [dim1, dim2, dim3]

        spg = Spacegroup3D(atoms)
        wyckoffs = spg._dataset["wyckoffs"]
        atoms.props = wyckoffs
        supercell = atoms.make_supercell(supercell_size)
        props = rand_select(supercell.props)
        vacs = []
        for i, j in props.items():
            defect_strt = supercell.remove_site_by_index(j)
            vac = Vacancy(
                atoms=supercell,
                defect_structure=defect_strt,
                defect_index=j,
                wyckoff_multiplicity=i,
                symbol=supercell.elements[j],
            )
            vacs.append(vac)
        return vacs
Esempio n. 2
0
def test_spg():
    box = [[2.715, 2.715, 0], [0, 2.715, 2.715], [2.715, 0, 2.715]]
    coords = [[0, 0, 0], [0.25, 0.25, 0.25]]
    elements = ["Si", "Si"]
    Si = Atoms(lattice_mat=box, coords=coords, elements=elements)
    spg = Spacegroup3D(atoms=Si)  # .spacegroup_data()
    cvn = spg.conventional_standard_structure
    ml = symmetrically_distinct_miller_indices(max_index=3, cvn_atoms=cvn)
    # print ('ml',ml)
    x = get_wyckoff_position_operators(488)
    # print  (x['wyckoff'][0]['letter'])
    assert (
        spg.space_group_number,
        spg.space_group_symbol,
        cvn.num_atoms,
        ml[0][0],
        x["wyckoff"][0]["letter"],
    ) == (227, "Fd-3m", 8, 1, "l")
    spg = Spacegroup3D(atoms=s1)
    assert spg.space_group_number == 191
    print(spg.space_group_number)
    cvn = spg.conventional_standard_structure
    spg = Spacegroup3D(atoms=s2)
    assert spg.space_group_number == 166
    print(spg.space_group_number)
    cvn = spg.conventional_standard_structure
    spg = Spacegroup3D(atoms=s3)
    print(spg.space_group_number)
    cvn = spg.conventional_standard_structure
    assert spg.space_group_number == 139
    spg = Spacegroup3D(atoms=s4)
    print(spg.space_group_number)
    cvn = spg.conventional_standard_structure
    assert spg.space_group_number == 63

    spg = Spacegroup3D(atoms=s5)
    print(spg.space_group_number)
    cvn = spg.conventional_standard_structure
    assert spg.space_group_number == 39

    spg = Spacegroup3D(atoms=s6)
    print(spg.space_group_number)
    cvn = spg.conventional_standard_structure
    assert spg.space_group_number == 12

    spg = Spacegroup3D(atoms=s7)
    print(spg.space_group_number)
    cvn = spg.conventional_standard_structure
    assert spg.space_group_number == 7

    spg = Spacegroup3D(atoms=s8)
    print(spg.space_group_number)
    cvn = spg.conventional_standard_structure
    assert spg.space_group_number == 2

    spg = Spacegroup3D(atoms=s9)
    print(spg.space_group_number)
    cvn = spg.conventional_standard_structure
    assert spg.space_group_number == 11
Esempio n. 3
0
def test_inputs():
    box = [[2.715, 2.715, 0], [0, 2.715, 2.715], [2.715, 0, 2.715]]
    coords = [[0, 0, 0], [0.25, 0.25, 0.25]]
    elements = ["Al", "Al"]
    Al = Atoms(lattice_mat=box, coords=coords, elements=elements)
    spg = Spacegroup3D(atoms=Al)
    Al = spg.conventional_standard_structure
    box = LammpsData().atoms_to_lammps(atoms=Al)
    td = box.to_dict()
    fd = LammpsData.from_dict(td)
    box.write_file(filename=data)
    d = box.to_dict()
    # print ('d=',d)
    reload_d = LammpsData.from_dict(d)
    # print ('d=',reload_d)
    atoms = box.lammps_to_atoms()
    lmp = LammpsData().read_data(filename=data, potential_file=pot)
    lmp = LammpsData().atoms_to_lammps(atoms=atoms)
    pair_coeff = "abc"
    inp = LammpsInput(LammpsDataObj=lmp).write_lammps_in(
        lammps_in=init,
        lammps_in1=pot,
        lammps_in2=inm,
        parameters={
            "pair_style": "eam/alloy",
            "pair_coeff": pair_coeff,
            "atom_style": "charge",
            "control_file": "/users/knc6/inelast.mod",
        },
    )
    d = LammpsInput(LammpsDataObj=lmp).to_dict()
    d = LammpsInput.from_dict(d)
    assert (lmp._lammps_box[1], atoms.num_atoms) == (5.43, 8)
Esempio n. 4
0
    def __init__(
        self,
        atoms=None,
        indices=[0, 0, 1],
        layers=3,
        vacuum=18.0,
        tol=1e-10,
        from_conventional_structure=True,
    ):
        """Initialize the class.

        Args:
             atoms: jarvis.core.Atoms object

             indices: Miller indices

             layers: Number of surface layers

             vacuum: vacuum padding

             tol: tolerance during dot product

             from_conventional_structure: whether to use the conv. atoms
        """
        self.indices = np.array(indices)
        self.from_conventional_structure = from_conventional_structure
        if self.from_conventional_structure:
            self.atoms = Spacegroup3D(atoms).conventional_standard_structure
        else:
            self.atoms = atoms
        self.tol = tol
        self.vacuum = vacuum
        self.layers = layers
Esempio n. 5
0
 def interpolated_points(self,
                         atoms,
                         line_density=20,
                         coords_are_cartesian=False):
     """Provide bandstructure k-points, controlled by the line_density."""
     list_k_points = []
     sym_point_labels = []
     spg = Spacegroup3D(atoms=atoms)
     prim = spg.primitive_atoms
     self.kpath = self.high_kpath(atoms)
     self._prim_rec = prim.lattice.reciprocal_lattice()
     # print ('self._prim_rec',self._prim_rec)
     for b in self.kpath["path"]:
         for i in range(1, len(b)):
             start = np.array(self.kpath["kpoints"][b[i - 1]])
             end = np.array(self.kpath["kpoints"][b[i]])
             distance = np.linalg.norm(
                 self._prim_rec.cart_coords(start) -
                 self._prim_rec.cart_coords(end))
             nb = int(ceil(distance * line_density))
             print("nb", nb, distance, line_density)
             sym_point_labels.extend([b[i - 1]] + [""] * (nb - 1) + [b[i]])
             list_k_points.extend([
                 self._prim_rec.cart_coords(start) + float(i) / float(nb) *
                 (self._prim_rec.cart_coords(end) -
                  self._prim_rec.cart_coords(start))
                 for i in range(0, nb + 1)
             ])
     if coords_are_cartesian:
         return list_k_points, sym_point_labels
     else:
         frac_k_points = [
             self._prim_rec.frac_coords(k) for k in list_k_points
         ]
         return frac_k_points, sym_point_labels
Esempio n. 6
0
    def elastic(
        self,
        mat=None,
        encut=None,
        nbands=None,
        potim=0.015,
        npar=None,
        length=20,
    ):
        """
        Use for elastic property calculations using IBRION = 6.

        Enforces conventional standard structure.

        Args:
            mat :  Poscar object

            encut :  Plane-wave cut-off, 1.3 times will be used

            nbands : number of bands, generally high-value recommended

            npar : NPAR tag, see VASP manual, set it as number of cores

            length :  K-points in length unit
        """
        incar = self.use_incar_dict
        cvn = Spacegroup3D(mat.atoms).conventional_standard_structure
        comment = mat.comment
        p = Poscar(cvn, comment=comment)

        if npar is not None:
            incar.update({"NPAR": npar})

        if nbands is not None:
            nbands = int(nbands * 3)
            incar.update({"NBANDS": nbands})
        data = {
            "ENCUT": 1.3 * float(encut),
            "NEDOS": 5000,
            "ISIF": 3,
            "POTIM": potim,
            "ISPIN": 2,
            "IBRION": 6,
            "LCHARG": ".FALSE.",
        }
        incar.update(data)
        kpoints = Kpoints().automatic_length_mesh(
            lattice_mat=p.atoms.lattice_mat,
            length=length)  # Auto_Kpoints(mat=mat, length=length)

        en, contcar = VaspJob(
            poscar=p,
            incar=incar,
            pot_type=self.pot_type,
            kpoints=kpoints,
            jobname=str("MAIN-ELASTIC-") + str(p.comment.split()[0]),
        ).runjob()

        return en, contcar
Esempio n. 7
0
def test_input():
    box = [[2.715, 2.715, 0], [0, 2.715, 2.715], [2.715, 0, 2.715]]
    coords = [[0, 0, 0], [0.25, 0.25, 0.25]]
    elements = ["Si", "Si"]
    Si = Atoms(lattice_mat=box, coords=coords, elements=elements)
    spg = Spacegroup3D(Si)
    Si_cvn = spg.conventional_standard_structure
    p = PhonopyInputs(atoms=Si_cvn).generate_all_files()
Esempio n. 8
0
def get_selective_dyn_decorated_atoms(atoms):
    """Freeze coordinates based on symmetry."""
    spg = Spacegroup3D(atoms=atoms)  # .spacegroup_data()
    frac_coords = atoms.frac_coords
    hall_number = spg._dataset["hall_number"]
    wdata = get_wyckoff_position_operators(hall_number)["wyckoff"]
    wsymbols = spg._dataset["wyckoffs"]
    info = defaultdict()
    for i in wdata:
        info[i["letter"]] = i["positions"]

    props = []
    for i, j in zip(wsymbols, frac_coords):
        ops = info[i]
        # print ('ops,j',ops, j)

        arr = ops
        new_arr = []
        for ii in arr:
            a = ii.split(",")
            b = []
            for jj in a:
                ind = jj
                if "(" in jj:
                    ind = jj.split("(")[1]  # .split(')')[0]
                if ")" in jj:
                    ind = jj.split(")")[0]  # .split(')')[0]
                # print (a,ind,j)
                if "/" in ind:
                    try:
                        tmp = ind.split("/")
                        ind = float(tmp[0]) / float(tmp[1])
                    except Exception:
                        pass
                try:
                    ind = float(ind)
                except Exception:
                    pass
                b.append(ind)

            new_arr.append(b)
        # print ('arr',arr)
        # print ('coord',j)
        # print ()
        arr_T_F = decorate_T_F(options=new_arr, coord=j)
        props.append(arr_T_F)
        # print ('new_arr',new_arr,j, arr_T_F)
        # print ()
        # print ()
        # print ()
    decorated_atoms = Atoms(
        lattice_mat=atoms.lattice_mat,
        elements=atoms.elements,
        coords=frac_coords,
        cartesian=False,
        props=props,
    )
    return decorated_atoms, hall_number, wsymbols
Esempio n. 9
0
def test_wann():
    a = Atoms.from_poscar(pos)
    fc = read_fc(fc_file)
    get_phonon_tb(fc=fc, atoms=a, out_file=wtb)
    cvn = Spacegroup3D(a).conventional_standard_structure
    w = WannierHam(wtb)
    w.get_bandstructure_plot(atoms=cvn, yrange=[0, 550])
    cmd = "rm phonopyTB_hr.dat bs.png"
    os.system(cmd)
Esempio n. 10
0
 def write_struct(self, filename="boltztrap.struct"):
     """Write BoltzTrap based struct file."""
     atoms = self.vrun.all_structures[-1]
     spg = Spacegroup3D(atoms)
     spg_symb = spg.space_group_symbol
     formula = atoms.composition.formula
     operations = spg._dataset["rotations"]
     lattice_mat = np.array(atoms.lattice_mat) * Angs_to_Bohr
     f = open(filename, "w")
     f.write("%s %s\n" % (formula, spg_symb))
     f.write("%12.8f %12.8f %12.8f\n" %
             (lattice_mat[0][0], lattice_mat[0][1], lattice_mat[0][2]))
     f.write("%12.8f %12.8f %12.8f\n" %
             (lattice_mat[1][0], lattice_mat[1][1], lattice_mat[1][2]))
     f.write("%12.8f %12.8f %12.8f\n" %
             (lattice_mat[2][0], lattice_mat[2][1], lattice_mat[2][2]))
     f.write("%d\n" % (len(operations)))
     for c in operations:
         for row in c:
             f.write("{}\n".format(" ".join(str(i) for i in row)))
     f.close()
Esempio n. 11
0
    def prim_axis(self):
        """
        Use when taking conventional cell.

        Such as elastic constant calculations.
        """
        prim = self.atoms.get_primitive_atoms
        if prim.num_atoms < self.atoms.num_atoms:
            spaceg = Spacegroup3D(self.atoms)
            latt = spaceg.lattice_system
            sgp = spaceg.space_group_symbol
            if latt == "rhombohedral":
                transf = (np.array([[2, -1, -1], [1, 1, -2], [1, 1, 1]],
                                   dtype=np.float) / 3)
            elif "I" in sgp:
                transf = (np.array([[-1, 1, 1], [1, -1, 1], [1, 1, -1]],
                                   dtype=np.float) / 2)

            elif "F" in sgp:
                transf = (np.array([[0, 1, 1], [1, 0, 1], [1, 1, 0]],
                                   dtype=np.float) / 2)
            elif "A" in sgp:
                transf = (np.array([[2, 0, 0], [0, 1, -1], [0, 1, 1]],
                                   dtype=np.float) / 2)
            elif "C" in sgp:
                if latt == "monoclinic":
                    transf = (np.array([[1, 1, 0], [-1, 1, 0], [0, 0, 2]],
                                       dtype=np.float) / 2)
                else:
                    transf = (np.array([[1, -1, 0], [1, 1, 0], [0, 0, 2]],
                                       dtype=np.float) / 2)
        else:
            transf = np.eye(3)
        ax = ""
        for el in transf:
            ax = (str(ax) + str(" ") + str(el[0]) + str(" ") + str(el[1]) +
                  str(" ") + str(el[2]))
        ax_line = str("PRIMITIVE_AXIS = ") + str(ax) + "\n"
        return ax_line
Esempio n. 12
0
def test_download(jid="JVASP-1002"):
    for i in fls["FD-ELAST"]:
        if isinstance(i, dict):
            if i["name"].split(".zip")[0] == jid:
                print(i)

                r = requests.get(i["download_url"])
                z = zipfile.ZipFile(io.BytesIO(r.content))
                vrun_path = z.read("vasprun.xml").decode("utf-8")
                fd, path = tempfile.mkstemp()
                with os.fdopen(fd, "w") as tmp:
                    tmp.write(vrun_path)
                vrun = Vasprun(path)
                fc = vrun.phonon_data()["force_constants"]
                atoms = vrun.all_structures[0]
                print(atoms)
                # atoms = Atoms.from_poscar(pos)
                print(atoms)
                fd, path = tempfile.mkstemp()
                get_phonon_tb(fc=fc, atoms=atoms, out_file=path)
                cvn = Spacegroup3D(atoms).conventional_standard_structure
                w = WannierHam(path)
                # print ('atoms',atoms)
                w.get_bandstructure_plot(atoms=atoms, yrange=[0, 550])
Esempio n. 13
0
    def get_unique_magnetic_structures(
        self,
        atoms,
        supercell_dim=[1, 1, 1],
        magnetic_ions=None,
        noferri=True,
        magmom=3.0,
    ):
        """
        Generate supercells with unique magnetic orderings.

        noferri=False to get ferrimagnetic configurations.
        """
        if magnetic_ions is None:
            magnetic_ions = set(atoms.elements)

        ss = atoms.make_supercell(dim=supercell_dim)
        # spg = Spacegroup3D(atoms)
        spg = Spacegroup3D(atoms)  # kfg

        # Apply symmetry with various tolerances until we find one that works
        worked = False
        for tol in [1e-7, 1e-6, 1e-5, 1e-4, 1e-3, 1e-2, 1e-1]:
            permutations, worked = self.apply_symmetry_operations(ss,
                                                                  spg,
                                                                  tol=tol)
            if worked:
                print("applied sym ", tol)
                break
        if not worked:
            print("error in apply_symmetry_operations")

        print("number of sym permutations:", len(permutations))
        nat = ss.num_atoms

        magnetic_list = []
        magnetic_count = 0
        mag_dict = {}
        for i, el in enumerate(ss.elements):
            if el in magnetic_ions:
                magnetic_list.append(True)
                mag_dict[magnetic_count] = i
                magnetic_count += 1

            else:
                magnetic_list.append(False)

        print("magnetic count: ", magnetic_count)
        if magnetic_count == 0:
            print("no magnetic ions, what are you doing????")
            return

        # generate all magnetic configurations
        magnetic_list = []
        for i in range(2**(magnetic_count)):
            magnetic_list.append(np.zeros(magnetic_count))
            # magnetic_list[-1][0] = 5.0

        tmp = "00000000000000000000000000000000000000000000000000000000000000"
        if magnetic_count > 0:
            for i in range(2**(magnetic_count)):
                binary_int = bin(i).replace("0b", "")  # convert to binary
                total_int = tmp + binary_int

                for ii, d in enumerate(total_int[-magnetic_count:]):
                    if d == "0":
                        # print(i, ii, d)
                        magnetic_list[i][ii] = magmom
                    else:
                        # print(i, ii, d)
                        magnetic_list[i][ii] = -1 * magmom

        if (
                noferri
        ):  # get rid if ferrimagnetic configurations, only exact AFM and FM
            newlist = []
            for i in range(2**(magnetic_count)):
                if (np.abs(
                        np.abs(np.sum(magnetic_list[i])) / abs(magmom) -
                        magnetic_count) < 1e-5
                        or np.abs(np.sum(magnetic_list[i])) < 1e-5):
                    newlist.append(magnetic_list[i])
            magnetic_list = newlist

        # convert to all atoms in cell
        mag_all = []
        for mag in magnetic_list:
            z = np.zeros(nat)
            for i, m in enumerate(mag):
                z[mag_dict[i]] = m
            mag_all.append(z)

        print("generated, now apply sym opps to find unique")
        # apply symmetry ops
        symm_list = []
        for mag in mag_all:
            already_in_list = False
            for p in permutations:
                mag_new = mag[p]
                for s in symm_list:
                    if (
                            np.sum(np.abs(s - mag_new)) < 1e-5
                            or np.sum(np.abs(s + mag_new)) < 1e-5
                    ):  # either we found the same config, or same config * -1
                        already_in_list = True
                        break
            if not already_in_list:  # then we need it
                symm_list.append(mag)

        print("number of unique configs: ", len(symm_list))
        return symm_list, ss
Esempio n. 14
0
def basic_data(data={}, source="JARVIS-FF-LAMMPS"):
    """Get basic data for table."""
    info = {}
    info["id"] = data["jid"]
    info["source_folder"] = data["source_folder"]
    info["tmp_source_folder"] = "'" + data["source_folder"] + "'"
    info["tmp_id"] = "'" + data["jid"] + "'"
    ref = data["source_folder"].split("/")[-1].split("@")[1].split("_")[0]
    info["ref"] = "'" + ref + "'"
    info["jvid"] = get_jvid(ref)
    final_atoms = data["bulk_data"]["final_str"]
    initial_atoms = data["bulk_data"]["initial_str"]
    info["formula"] = final_atoms.composition.reduced_formula
    info["tmp_formula"] = "'" + final_atoms.composition.reduced_formula + "'"
    info["elements"] = ",".join(final_atoms.uniq_species)
    info["tmp_elements"] = "'" + ",".join(final_atoms.uniq_species) + "'"
    info["number_uniq_species"] = len(final_atoms.uniq_species)
    info["data_source"] = source
    info["tmp_data_source"] = "'" + source + "'"
    info["pair_style"] = data["bulk_data"]["pair_style"]
    info["pair_coeff"] = data["bulk_data"]["pair_coeff"]
    # info["pair_coeff"] = (
    #    '<a href="http://www.ctcms.nist.gov/~knc6/DOWNLOADS/'
    #    + data["bulk_data"]["pair_coeff"]
    #    + '.zip">'
    #    + data["bulk_data"]["pair_coeff"]
    #    + "</a>"
    # )
    info["energy_per_atom"] = round(
        float(data["bulk_data"]["energy_per_atom"]), 3)
    info["pressure"] = round(float(data["bulk_data"]["system_pressure"]), 3)

    initial_spg = Spacegroup3D(initial_atoms)
    final_spg = Spacegroup3D(final_atoms)
    info["initial_spacegroup_number"] = initial_spg.space_group_number
    info["initial_spacegroup_symbol"] = initial_spg.space_group_symbol
    info["initial_pointgroup_symbol"] = initial_spg.point_group_symbol
    info["initial_crystal_system"] = initial_spg.crystal_system
    initial_lat_params = initial_atoms.lattice.parameters
    info["initial_a"] = round(initial_lat_params[0], 2)
    info["initial_b"] = round(initial_lat_params[1], 2)
    info["initial_c"] = round(initial_lat_params[2], 2)
    info["initial_alpha"] = round(initial_lat_params[3], 2)
    info["initial_beta"] = round(initial_lat_params[4], 2)
    info["initial_gamma"] = round(initial_lat_params[5], 2)
    info["initial_density"] = round(initial_atoms.density, 3)
    dim = get_supercell_dims(final_atoms)
    info["xyz"] = (
        '"' +
        str(final_atoms.make_supercell_matrix(dim).get_xyz_string).replace(
            "\n", "\\n") + '"')
    info["final_str"] = ('"' +
                         str(final_atoms.get_string()).replace("\n", "\\n") +
                         '"')
    info["initial_str"] = (
        '"' + str(initial_atoms.get_string()).replace("\n", "\\n") + '"')
    final_lat_params = final_atoms.lattice.parameters
    info["final_a"] = round(final_lat_params[0], 2)
    info["final_b"] = round(final_lat_params[1], 2)
    info["final_c"] = round(final_lat_params[2], 2)
    info["final_alpha"] = round(final_lat_params[3], 2)
    info["final_beta"] = round(final_lat_params[4], 2)
    info["final_gamma"] = round(final_lat_params[5], 2)
    info["final_density"] = round(final_atoms.density, 3)

    info["final_spacegroup_number"] = final_spg.space_group_number
    info["final_spacegroup_symbol"] = final_spg.space_group_symbol
    info["final_pointgroup_symbol"] = final_spg.point_group_symbol
    info["final_crystal_system"] = final_spg.crystal_system

    et = ""
    # print(data["bulk_data"]["elastic_tensor"]["raw_et_tensor"])
    try:
        if data["bulk_data"]["elastic_tensor"] != "":
            cij = np.round(
                (data["bulk_data"]["elastic_tensor"]["raw_et_tensor"]), 2)
            et = (
                '<cij>"' +
                ";".join([",".join(map(str, cij[:, i]))
                          for i in range(0, 6)]) + '"</cij>')

    except Exception as exp:
        print("Cannot obtain elastic tensor data.", info["source_folder"], exp)
        pass

    info["elastic_tensor"] = et
    vacancy_line = ""
    if len(data["vacancy_info"]) != 0:
        for i in data["vacancy_info"]:
            vacancy_line += i[0] + "," + i[1] + "," + str(round(i[2], 3)) + ";"
    info["vacancy_info"] = '"' + vacancy_line + '"'

    surf_line = ""
    if len(data["surface_info"]) != 0:
        for i in data["surface_info"]:
            surf_line += i[0] + "," + str(round(i[1], 3)) + ";"
    info["surface_info"] = '"' + surf_line + '"'

    phonon_band_line = ""
    try:
        # Band
        frequencies = data["band_frequencies"]
        distances = data["band_distances"]
        labels = data["band_labels"]
        label_points = data["band_label_points"]

        tmp = ""
        for i in range(np.array(frequencies).shape[1]):
            tmp += ",".join(map(str, np.array(frequencies)[:, i])) + ";"

        phonon_band_line += ("<phonon_bandstructure_distances>'" +
                             ",".join(map(str, distances)) +
                             "'</phonon_bandstructure_distances>")

        phonon_band_line += ("<phonon_bandstructure_frequencies>'" + tmp +
                             "'</phonon_bandstructure_frequencies>")
        phonon_band_line += ("<phonon_bandstructure_labels>'" +
                             ",".join(map(str, labels)) +
                             "'</phonon_bandstructure_labels>")
        phonon_band_line += ("<phonon_bandstructure_label_points>'" +
                             ",".join(map(str, label_points)) +
                             "'</phonon_bandstructure_label_points>")
    except Exception as exp:
        print("Cannot obtain phonon band data.", exp)

    # Comment until 4 MB text size error
    info["phonon_band_line"] = phonon_band_line
    phonon_dos_line = ""
    try:
        freq = data["dos_freq"]
        pdos = data["dos_intensity"]
        phonon_dos_line += ("<phonon_dos_frequencies>'" +
                            ",".join(map(str, freq)) +
                            "'</phonon_dos_frequencies>")

        phonon_dos_line += ("<phonon_dos_intensity>'" +
                            ",".join(map(str, pdos)) +
                            "'</phonon_dos_intensity>")

    except Exception:
        print("Cannot obtain phonon dod data.")
        pass
    info["phonon_dos_line"] = phonon_dos_line

    return info
Esempio n. 15
0
    def all_props_eam_alloy(
        self,
        atoms=None,
        ff_path="",
        lammps_cmd="",
        enforce_conventional_structure=True,
        enforce_c_size=0,
        extend=1,
    ):
        """
        Provide generic function for LAMMPS calculations using eam/alloy.

        Must provide Atoms class and path to force-field.
        Args:
            atoms :  Atoms object

            ff_path :  inter-atomic potential path

            lammps_cmd : LAMMPS executable path

            enforce_conventional_structure :
            whether to enforce conventional cell

            enforce_c_size : minimum cell-sizes

            extend : used for round-off during making supercells
        """
        if enforce_conventional_structure:
            atoms = Spacegroup3D(atoms).conventional_standard_structure

        if enforce_c_size is not None:
            dim = get_supercell_dims(atoms, enforce_c_size=enforce_c_size)
            atoms = atoms.make_supercell([dim[0], dim[1], dim[2]])

        self.pair_style = "eam/alloy"
        self.pair_coeff = ff_path
        parameters = {
            "pair_style": self.pair_style,
            "atom_style": "charge",
            "pair_coeff": self.pair_coeff,
        }
        parameters["control_file"] = "inelast.mod"
        en, final_str, forces = LammpsJob(
            atoms=atoms,
            jobname="ELASTIC",
            parameters=parameters,
            lammps_cmd=lammps_cmd,
        ).runjob()
        print("en, final_str, forces", en, final_str, forces)

        indices = symmetrically_distinct_miller_indices(max_index=1,
                                                        cvn_atoms=atoms)
        for i in indices:
            surf = Surface(atoms=final_str, indices=i).make_surface()
            jobname = str("Surf-") + str("_".join(map(str, i)))
            en2, final_str2, forces2 = LammpsJob(
                atoms=surf,
                jobname=jobname,
                parameters=parameters,
                lammps_cmd=lammps_cmd,
            ).runjob()

        # sys.exit()

        v = Vacancy(atoms=final_str).generate_defects(enforce_c_size=5)
        print("vacs=", v)
        for i, ii in enumerate(v):
            jobname = (str("symbol-") + str(ii._symbol) + str("-") +
                       str("Wycoff-") + str(ii._wyckoff_multiplicity))
            print("ii._defect_structure", ii._atoms)
            en2, final_str2, forces2 = LammpsJob(
                atoms=ii._defect_structure,
                jobname=jobname,
                parameters=parameters,
                lammps_cmd=lammps_cmd,
            ).runjob()

        self.phonons(atoms=atoms, lammps_cmd=lammps_cmd, parameters=parameters)
Esempio n. 16
0
def test_spg229():
    d = loadjson(os.path.join(os.path.dirname(__file__), "spg229.json"))
    for i in d:
        atoms = Atoms.from_dict(i["atoms"])
        spg = Spacegroup3D(atoms).space_group_number
        assert spg == i["spg_number"]
Esempio n. 17
0
from jarvis.tasks.lammps.lammps import LammpsJob, JobFactory
from jarvis.core.atoms import Atoms
from jarvis.db.figshare import get_jid_data
from jarvis.analysis.structure.spacegroup import Spacegroup3D

# atoms = Atoms.from_poscar('POSCAR')
# Get Aluminum FCC
tmp_dict = get_jid_data(jid="JVASP-816", dataset="dft_3d")["atoms"]
atoms = Atoms.from_dict(tmp_dict)
# Get conventional cell
spg = Spacegroup3D(atoms)
cvn_atoms = spg.conventional_standard_structure
ff = "/users/knc6/Software/LAMMPS/lammps-master/potentials/Al_zhou.eam.alloy"
mod = "/users/knc6/Software/Devs/jarvis/jarvis/tasks/lammps/templates/inelast.mod"
cmd = "/users/knc6/Software/LAMMPS/lammps-master/src/lmp_serial<in.main>out"
parameters = {
    "pair_style": "eam/alloy",
    "pair_coeff": ff,
    "atom_style": "charge",
    "control_file": mod,
}
# Test LammpsJob
lmp = LammpsJob(atoms=cvn_atoms,
                parameters=parameters,
                lammps_cmd=cmd,
                jobname="Test").runjob()

# Test high-throughput
job_fact = JobFactory(pair_style="eam/alloy", name="my_first_lammps_run")
job_fact.all_props_eam_alloy(atoms=cvn_atoms, ff_path=ff, lammps_cmd=cmd)
Esempio n. 18
0
    def high_symm_path(self, atoms):
        """Get high symmetry k-points for given Atoms."""
        spg = Spacegroup3D(atoms=atoms)
        lat_sys = spg.lattice_system
        spg_symb = spg.space_group_symbol
        kp = None
        if lat_sys == "cubic":
            if "P" in spg_symb:
                kp = HighSymmetryKpoint3DFactory().cubic()
            elif "F" in spg_symb:
                kp = HighSymmetryKpoint3DFactory().fcc()
            elif "I" in spg_symb:
                kp = HighSymmetryKpoint3DFactory().bcc()
            else:
                print("kpath space group  is not implemeted ", spg_symb)

        elif lat_sys == "tetragonal":
            if "P" in spg_symb:
                kp = HighSymmetryKpoint3DFactory().tet()
            elif "I" in spg_symb:
                cvn = spg.conventional_standard_structure
                a = cvn.lattice.a
                c = cvn.lattice.c
                if c < a:
                    kp = HighSymmetryKpoint3DFactory().bctet1(c, a)
                else:
                    kp = HighSymmetryKpoint3DFactory().bctet2(c, a)
            else:
                print("kpath space group is not implemeted ", spg_symb)

        elif lat_sys == "orthorhombic":
            cvn = spg.conventional_standard_structure
            a = cvn.lattice.a
            c = cvn.lattice.c
            b = cvn.lattice.b

            if "P" in spg_symb:
                kp = HighSymmetryKpoint3DFactory().orc()

            elif "F" in spg_symb:
                if 1 / a**2 > 1 / b**2 + 1 / c**2:
                    kp = HighSymmetryKpoint3DFactory().orcf1(a, b, c)
                elif 1 / a**2 < 1 / b**2 + 1 / c**2:
                    kp = HighSymmetryKpoint3DFactory().orcf2(a, b, c)
                else:
                    kp = HighSymmetryKpoint3DFactory().orcf3(a, b, c)

            elif "I" in spg_symb:
                kp = HighSymmetryKpoint3DFactory().orci(a, b, c)

            elif "C" in spg_symb or "A" in spg_symb:
                kp = HighSymmetryKpoint3DFactory().orcc(a, b, c)
            else:
                print("kpath space group is not implemeted ", spg_symb)

        elif lat_sys == "hexagonal":
            kp = HighSymmetryKpoint3DFactory().hex()

        elif lat_sys == "rhombohedral":
            prim = spg.primitive_atoms
            alpha = prim.lattice.angles[0]
            if alpha < 90:
                kp = HighSymmetryKpoint3DFactory().rhl1(alpha * pi / 180)
            else:
                kp = HighSymmetryKpoint3DFactory().rhl2(alpha * pi / 180)

        elif lat_sys == "monoclinic":
            cvn = spg.conventional_standard_structure
            a, b, c = cvn.lattice.abc
            alpha = cvn.lattice.angles[0]

            if "P" in spg_symb:
                kp = HighSymmetryKpoint3DFactory().mcl(b, c, alpha * pi / 180)

            elif "C" in spg_symb:
                prim = spg.primitive_atoms.lattice.reciprocal_lattice()

                kgamma = prim.angles[2]
                if kgamma > 90:
                    kp = HighSymmetryKpoint3DFactory().mclc1(
                        a, b, c, alpha * pi / 180)
                if kgamma == 90:
                    kp = HighSymmetryKpoint3DFactory().mclc2(
                        a, b, c, alpha * pi / 180)
                if kgamma < 90:
                    if (b * cos(alpha * pi / 180) / c +
                            b**2 * sin(alpha * pi / 180)**2 / a**2 < 1):
                        kp = HighSymmetryKpoint3DFactory().mclc3(
                            a, b, c, alpha * pi / 180)
                    if (b * cos(alpha * pi / 180) / c +
                            b**2 * sin(alpha * pi / 180)**2 / a**2 == 1):
                        kp = HighSymmetryKpoint3DFactory().mclc4(
                            a, b, c, alpha * pi / 180)
                    if (b * cos(alpha * pi / 180) / c +
                            b**2 * sin(alpha * pi / 180)**2 / a**2 > 1):
                        kp = HighSymmetryKpoint3DFactory().mclc5(
                            a, b, c, alpha * pi / 180)
            else:
                print("kpath space group is not implemeted ", spg_symb)

        elif lat_sys == "triclinic":
            prim = spg.primitive_atoms.lattice.reciprocal_lattice()
            kalpha = prim.angles[0]
            kbeta = prim.angles[1]
            kgamma = prim.angles[2]
            if kalpha > 90 and kbeta > 90 and kgamma > 90:
                kp = HighSymmetryKpoint3DFactory().tria()
            elif kalpha < 90 and kbeta < 90 and kgamma < 90:
                kp = HighSymmetryKpoint3DFactory().trib()
            elif kalpha > 90 and kbeta > 90 and kgamma == 90:
                kp = HighSymmetryKpoint3DFactory().tria()
            elif kalpha < 90 and kbeta < 90 and kgamma == 90:
                kp = HighSymmetryKpoint3DFactory().trib()
            else:
                # Need to check
                kp = HighSymmetryKpoint3DFactory().tria()
        else:
            print("kpath space group is not implemeted ", spg_symb)
        # print("kp",spg_symb)
        return kp
Esempio n. 19
0
    def get_primitive_atoms(self):
        """Get primitive Atoms using spacegroup information."""
        from jarvis.analysis.structure.spacegroup import Spacegroup3D

        return Spacegroup3D(self).primitive_atoms
Esempio n. 20
0
    def write_cif(
        self, filename="atoms.cif", comment=None, with_spg_info=True
    ):
        """
        Write CIF format file from Atoms object.

        Caution: can't handle fractional occupancies right now
        """
        if comment is None:
            comment = "CIF file written using JARVIS-Tools package."
        comment = comment + "\n"
        f = open(filename, "w")
        f.write(comment)
        composition = self.composition
        line = "data_" + str(composition.reduced_formula) + "\n"
        f.write(line)
        from jarvis.analysis.structure.spacegroup import Spacegroup3D

        if with_spg_info:
            spg = Spacegroup3D(self)
            line = (
                "_symmetry_space_group_name_H-M  "
                + str("'")
                + str(spg.space_group_symbol)
                + str("'")
                + "\n"
            )
        else:
            line = "_symmetry_space_group_name_H-M  " + str("'P 1'") + "\n"

        f.write(line)
        a, b, c, alpha, beta, gamma = self.lattice.parameters
        f.write("_cell_length_a       %g\n" % a)
        f.write("_cell_length_b       %g\n" % b)
        f.write("_cell_length_c       %g\n" % c)
        f.write("_cell_angle_alpha    %g\n" % alpha)
        f.write("_cell_angle_beta     %g\n" % beta)
        f.write("_cell_angle_gamma    %g\n" % gamma)
        f.write("\n")
        if with_spg_info:
            line = (
                "_symmetry_Int_Tables_number  "
                + str(spg.space_group_number)
                + "\n"
            )
        else:
            line = "_symmetry_Int_Tables_number  " + str(1) + "\n"
        f.write(line)

        line = (
            "_chemical_formula_structural  "
            + str(composition.reduced_formula)
            + "\n"
        )
        f.write(line)
        line = "_chemical_formula_sum  " + str(composition.formula) + "\n"
        f.write(line)
        line = "_cell_volume  " + str(self.volume) + "\n"
        f.write(line)
        reduced, repeat = composition.reduce()
        line = "_cell_formula_units_Z  " + str(repeat) + "\n"
        f.write(line)
        f.write("loop_\n")
        f.write("  _symmetry_equiv_pos_site_id\n")
        f.write(" _symmetry_equiv_pos_as_xyz\n")
        f.write(" 1  'x, y, z'\n")
        f.write("loop_\n")
        f.write(" _atom_site_type_symbol\n")
        f.write(" _atom_site_label\n")
        f.write(" _atom_site_symmetry_multiplicity\n")
        f.write(" _atom_site_fract_x\n")
        f.write(" _atom_site_fract_y\n")
        f.write(" _atom_site_fract_z\n")
        f.write(" _atom_site_fract_occupancy\n")
        order = np.argsort(self.elements)
        coords_ordered = np.array(self.frac_coords)[order]
        elements_ordered = np.array(self.elements)[order]
        occ = 1
        extra = 1
        element_types = []
        # count = 0
        for ii, i in enumerate(elements_ordered):
            if i not in element_types:
                element_types.append(i)
                count = 0
            symbol = i
            count = count + 1
            label = str(i) + str(count)
            element_types.append(i)
            coords = coords_ordered[ii]
            f.write(
                " %s  %s  %s  %7.5f  %7.5f  %7.5f  %s\n"
                % (symbol, label, occ, coords[0], coords[1], coords[2], extra)
            )
        f.close()
Esempio n. 21
0
def upload_sample_data(curate_xml=False):
    """
    Generate and upload XML files.

    Set curate_xml==True to upload all the XML documents.
    """
    d = data("dft_2d")

    count = 0
    for i in d[0:1]:
        filname = str(i["jid"]) + str(".xml")
        if not os.path.exists(filname):
            count = count + 1
            energy = (str(i["optb88vdw_total_energy"]) + str(",") +
                      str(i["formation_energy_peratom"]))
            atoms = Atoms.from_dict(i["atoms"])
            formula = str(atoms.composition.reduced_formula)
            sgp = str(Spacegroup3D(atoms).space_group_symbol)
            name = str(i["jid"])
            print(name)
            # ref = str("")
            func = str("OptB88vdW")
            elem = ""
            species = atoms.elements
            for j in species:
                elem = str(elem) + str(j) + str("-")
            encut = str(i["encut"])
            kpoints = (str(i["kpoints_array"][0]) + str("x") +
                       str(i["kpoints_array"][1]) + str("x") +
                       str(i["kpoints_array"][2]))
            el_tens = "na"
            try:
                el_tens = str(",".join(
                    map(str,
                        np.array(i["elastic_tensor"]).flatten())))
            except Exception:
                pass
            KV = str(i["bulk_modulus_kv"])
            GV = str(i["shear_modulus_gv"])
            op_eg = str(i["optb88vdw_bandgap"])
            mbj_eg = str(i["mbj_bandgap"])
            realx_arr = str(i["epsx"])
            mrealx_arr = str(i["mepsx"])
            realy_arr = str(i["epsy"])
            mrealy_arr = str(i["mepsy"])
            realz_arr = str(i["epsz"])
            mrealz_arr = str(i["mepsz"])
            typ = str("2D")  # 3D
            other = str(
                "Citation: 1) DOI:10.1038/s41598-017-05402-0" +
                ",2) DOI: 10.1038/sdata.2018.82, 3) arXiv:1804.01033v2 ")
            struct = atoms.get_string()
            data_json(
                other=other,
                energy=energy,
                typ=typ,
                formula=formula,
                sgp=sgp,
                name=name,
                func=func,
                elem=elem,
                encut=encut,
                kpoints=kpoints,
                el_tens=el_tens,
                KV=KV,
                GV=GV,
                op_eg=op_eg,
                mbj_eg=mbj_eg,
                realx_arr=realx_arr,
                mrealx_arr=mrealx_arr,
                realy_arr=realy_arr,
                mrealy_arr=mrealy_arr,
                realz_arr=realz_arr,
                mrealz_arr=mrealz_arr,
                struct=struct,
                curate_xml=curate_xml,
            )
Esempio n. 22
0
def test_extra_spgs():
    from jarvis.db.figshare import data

    d = data("dft_3d")
    few_spgs = {
        "JVASP-4663": 119,
        "JVASP-4666": 194,
        "JVASP-588": 160,
        "JVASP-4669": 191,
        "JVASP-4672": 141,
        "JVASP-581": 164,
        "JVASP-4687": 139,
        "JVASP-4693": 62,
        "JVASP-4696": 187,
        "JVASP-4711": 225,
        "JVASP-4714": 2,
        "JVASP-4723": 60,
        "JVASP-32": 167,
        "JVASP-107": 186,
        "JVASP-4756": 63,
        "JVASP-96": 216,
        "JVASP-4334": 123,
        "JVASP-4222": 11,
        "JVASP-4804": 156,
        "JVASP-329": 129,
        "JVASP-4852": 163,
        "JVASP-155": 61,
        "JVASP-4340": 51,
        "JVASP-4343": 15,
        "JVASP-4361": 14,
        "JVASP-137": 72,
        "JVASP-4879": 166,
        "JVASP-4885": 19,
        "JVASP-4894": 31,
        "JVASP-4216": 12,
        "JVASP-4918": 121,
        "JVASP-4948": 25,
        "JVASP-4957": 221,
        "JVASP-4960": 65,
        "JVASP-5059": 189,
        "JVASP-5071": 66,
        "JVASP-5074": 150,
        "JVASP-5086": 74,
        "JVASP-4388": 64,
        "JVASP-4391": 136,
        "JVASP-5155": 127,
        "JVASP-5185": 43,
        "JVASP-5197": 59,
        "JVASP-5212": 29,
        "JVASP-164": 176,
        "JVASP-5224": 137,
        "JVASP-5227": 148,
        "JVASP-4234": 193,
        "JVASP-5257": 7,
        "JVASP-5266": 140,
        "JVASP-4397": 33,
        "JVASP-5317": 8,
        "JVASP-5332": 13,
        "JVASP-5353": 16,
        "JVASP-5371": 4,
        "JVASP-5407": 229,
        "JVASP-5416": 147,
        "JVASP-5509": 52,
        "JVASP-5536": 70,
        "JVASP-5560": 71,
        "JVASP-5680": 28,
        "JVASP-5740": 6,
        "JVASP-5839": 162,
        "JVASP-5863": 79,
        "JVASP-110": 99,
        "JVASP-579": 38,
        "JVASP-4501": 5,
        "JVASP-91": 227,
        "JVASP-41": 154,
        "JVASP-4516": 96,
        "JVASP-4564": 82,
        "JVASP-4645": 130,
        "JVASP-152": 55,
        "JVASP-4792": 88,
        "JVASP-5041": 107,
        "JVASP-5425": 87,
        "JVASP-5464": 115,
        "JVASP-5650": 157,
        "JVASP-4450": 36,
        "JVASP-22520": 152,
        "JVASP-22523": 205,
        "JVASP-11998": 53,
        "JVASP-22528": 58,
        "JVASP-22533": 41,
        "JVASP-12091": 32,
        "JVASP-22541": 215,
        "JVASP-22543": 97,
        "JVASP-22549": 9,
        "JVASP-12103": 138,
        "JVASP-22575": 40,
        "JVASP-22602": 180,
        "JVASP-22611": 182,
        "JVASP-12022": 85,
        "JVASP-22637": 111,
        "JVASP-12139": 10,
        "JVASP-22709": 92,
        "JVASP-12060": 20,
        "JVASP-12064": 1,
        "JVASP-12194": 185,
        "JVASP-13885": 128,
        "JVASP-14096": 56,
        "JVASP-14020": 122,
        "JVASP-13904": 54,
        "JVASP-13783": 135,
        "JVASP-14213": 26,
        "JVASP-14034": 23,
        "JVASP-14158": 113,
        "JVASP-14256": 21,
        "JVASP-32150": 217,
        "JVASP-28392": 224,
        "JVASP-32180": 146,
        "JVASP-32197": 57,
        "JVASP-31813": 67,
        "JVASP-31819": 219,
        "JVASP-29262": 39,
        "JVASP-29281": 102,
        "JVASP-31825": 226,
        "JVASP-29425": 143,
        "JVASP-29441": 42,
        "JVASP-29520": 73,
        "JVASP-29526": 18,
        "JVASP-29555": 149,
        "JVASP-29597": 151,
        "JVASP-29705": 174,
        "JVASP-31921": 199,
        "JVASP-33147": 161,
        "JVASP-33220": 46,
        "JVASP-33344": 114,
        "JVASP-30263": 44,
        "JVASP-33832": 155,
        "JVASP-30458": 69,
        "JVASP-30461": 144,
        "JVASP-30518": 132,
        "JVASP-36540": 198,
        "JVASP-36548": 220,
        "JVASP-36568": 3,
        "JVASP-36573": 145,
        "JVASP-35061": 131,
        "JVASP-35137": 125,
        "JVASP-35222": 204,
        "JVASP-35344": 109,
        "JVASP-42053": 173,
        "JVASP-40216": 91,
        "JVASP-38594": 165,
        "JVASP-37330": 86,
        "JVASP-37573": 84,
        "JVASP-36714": 47,
        "JVASP-36754": 98,
        "JVASP-59313": 230,
        "JVASP-46893": 95,
        "JVASP-46896": 76,
        "JVASP-45779": 30,
        "JVASP-45831": 158,
        "JVASP-46446": 35,
        "JVASP-44393": 159,
        "JVASP-44773": 22,
        "JVASP-47741": 78,
        "JVASP-47811": 181,
        "JVASP-48055": 94,
        "JVASP-48916": 34,
        "JVASP-49907": 190,
        "JVASP-50342": 223,
        "JVASP-50360": 68,
        "JVASP-50431": 37,
        "JVASP-52902": 142,
        "JVASP-52377": 24,
        "JVASP-50791": 214,
        "JVASP-54512": 108,
        "JVASP-56567": 213,
        "JVASP-54867": 126,
        "JVASP-55180": 81,
        "JVASP-57780": 212,
        "JVASP-57807": 118,
        "JVASP-57816": 50,
        "JVASP-57100": 197,
        "JVASP-57138": 116,
        "JVASP-58233": 124,
        "JVASP-59682": 200,
        "JVASP-20180": 206,
        "JVASP-21448": 203,
        "JVASP-40468": 90,
        "JVASP-42914": 17,
        "JVASP-21594": 100,
        "JVASP-21706": 188,
        "JVASP-22783": 218,
        "JVASP-24006": 202,
        "JVASP-30879": 83,
        "JVASP-31186": 49,
        "JVASP-21031": 110,
        "JVASP-21116": 192,
        "JVASP-25245": 134,
        "JVASP-7066": 169,
        "JVASP-13017": 112,
        "JVASP-58953": 105,
        "JVASP-8682": 183,
        "JVASP-9902": 80,
        "JVASP-34882": 208,
        "JVASP-34330": 179,
        "JVASP-34502": 48,
        "JVASP-62982": 178,
    }
    """
 mem=[]
 spgs=[]
 pos=[]
 info=defaultdict()
 for i in d:
     a=Atoms.from_dict(i['atoms'])
     spg=Spacegroup3D(a).space_group_number
     if spg not in spgs:
        spgs.append(spg)
        pos.append(i['jid'])
        info[i['jid']]=spg
        print (info)
        if len(spgs)==230:
            break
 """
    for i, j in few_spgs.items():
        for ii in d:
            if ii["jid"] == i:

                a = Atoms.from_dict(ii["atoms"])
                spg = Spacegroup3D(a).space_group_number
                assert j == spg

                lattice_mat = a.lattice_mat
                kp = Kpoints3D().automatic_length_mesh(lattice_mat=lattice_mat,
                                                       length=40)
                sym = kp.high_symm_path(a)._path
                # print (ii['jid'],a)
                # TODO: following line failing for JVASP-4222
                # x, y = kp.interpolated_points(a)
                break