Beispiel #1
0
def generate_rdf(r_min, r_max, step, folder, both_atoms=False):
    from pymatgen.io.vasp import Xdatcar
    from vasppy.rdf import RadialDistributionFunction
    bins = int((r_max - r_min) / step)
    xd = Xdatcar(folder + os.sep + 'POSCAR')

    rdf_C_Pd = RadialDistributionFunction.from_species_strings(
        structures=xd.structures,
        species_i='C',
        species_j='Pd',
        nbins=bins,
        r_min=r_min,
        r_max=r_max)
    f = open(folder + os.sep + 'RDF_C', 'w')
    for i in range(len(rdf_C_Pd.r)):
        f.write(str(rdf_C_Pd.r[i]) + ' ')
        f.write(str(rdf_C_Pd.smeared_rdf()[i]) + '\n')
    f.close()

    if both_atoms:
        rdf_O_Pd = RadialDistributionFunction.from_species_strings(
            structures=xd.structures,
            species_i='O',
            species_j='Pd',
            nbins=bins,
            r_min=r_min,
            r_max=r_max)
        f = open(folder + os.sep + 'RDF_O', 'w')
        for i in range(len(rdf_O_Pd.r)):
            f.write(str(rdf_O_Pd.r[i]) + ' ')
            f.write(str(rdf_O_Pd.smeared_rdf()[i]) + '\n')
        f.close()
Beispiel #2
0
 def from_run_paths(cls, p, T, el, corr_t, block_l, t_step=2.0, l_lim=50, skip_first=0):
     D_t = []
     for t in range(len(p)):
         xdatcar = Xdatcar(p[t])
         d = Diffusion(xdatcar.structures, corr_t=corr_t, block_l=block_l,
                       t_step=t_step, l_lim=l_lim, skip_first=skip_first)
         D_t.append([T[t], d.getD(el)])
     return cls(D_t)
Beispiel #3
0
def prep_ml_formation_energy(fileroot="."):
    """
    writes .poscar and .energy files with index information for use in model training

    Parameters
    ----------
    """
    n = 100  # number of steps to sample
    i = 0
    for a in os.walk("."):
        directory = a[0]
        s_extension = "poscar"
        e_extension = "energy"
        prefix = ""  # prefix for files, e.g. name of structure
        # e.g. "[root]/[prefix][i].[poscar]" where i=1,2,...,n
        try:
            s_list = Xdatcar(directory + "/XDATCAR").structures
            e_list = [
                step["E0"]
                for step in Oszicar(directory + "/OSZICAR").ionic_steps
            ]
            if n < len(s_list) - 1:
                # the idea here is to obtain a subset of n energies
                # such that the energies are as evenly-spaced as possible
                # we do this in energy-space not in relaxation-space
                # because energies drop fast and then level off
                idx_to_keep = []
                fitting_data = np.array(
                    e_list)[:, np.newaxis]  # kmeans expects 2D
                kmeans_model = KMeans(n_clusters=n)
                kmeans_model.fit(fitting_data)
                cluster_centers = sorted(
                    kmeans_model.cluster_centers_.flatten())
                for centroid in cluster_centers:
                    closest_idx = np.argmin(np.subtract(e_list, centroid)**2)
                    idx_to_keep.append(closest_idx)
                idx_to_keep[-1] = len(e_list) - 1  # replace the last
                idx_list = np.arange(len(s_list))
                idx_batched = np.array_split(idx_list[:-1], n)
                idx_kept = [batch[0] for batch in idx_batched]
                idx_kept.append(idx_list[-1])
            else:
                idx_kept = np.arange(len(e_list))

            for j, idx in enumerate(idx_kept):
                filestem = str(j)
                i2 = str(i)
                s_filename = "{}/{}{}_{}.{}".format(fileroot, prefix, i2,
                                                    filestem, s_extension)
                e_filename = "{}/{}{}_{}.{}".format(fileroot, prefix, i2,
                                                    filestem, e_extension)
                s_list[idx].to(fmt="poscar", filename=s_filename)
                with open(e_filename, "w") as f:
                    f.write(str(e_list[idx]))
            i = i + 1
        except:
            print("noFile")
def prep_ml_formation_energy(calculation, fileroot='.'):
    os.mkdir('formation_energy')
    os.chdir('formation_energy')
    urlo = ('http://2d' + calculation['path'][9:21] + '.org/' +
            calculation['path'][22:] + '/OSZICAR')
    fileo = urllib.request.urlopen(urlo)
    urlx = ('http://2d' + calculation['path'][9:21] + '.org/' +
            calculation['path'][22:] + '/XDATCAR')
    filex = urllib.request.urlopen(urlx)
    with open('OsZICAR', 'a') as oszicar:
        for line in fileo:
            decoded_line = line.decode("utf-8")
            oszicar.write(decoded_line)

    with open('XdATCAR', 'a') as xdatcar:
        for line in filex:
            decoded_line = line.decode("utf-8")
            xdatcar.write(decoded_line)

    n = 100  # number of steps to sample
    s_extension = 'poscar'
    e_extension = 'energy'
    prefix = ''  # prefix for files, e.g. name of structure
    # e.g. "[root]/[prefix][i].[poscar]" where i=1,2,...,n
    s_list = Xdatcar('XdATCAR').structures
    e_list = [step['E0'] for step in Oszicar('OsZICAR').ionic_steps]
    if n < len(s_list) - 1:
        # the idea here is to obtain a subset of n energies
        # such that the energies are as evenly-spaced as possible
        # we do this in energy-space not in relaxation-space
        # because energies drop fast and then level off
        idx_to_keep = []
        fitting_data = np.array(e_list)[:, np.newaxis]  # kmeans expects 2D
        kmeans_model = KMeans(n_clusters=n)
        kmeans_model.fit(fitting_data)
        cluster_centers = sorted(kmeans_model.cluster_centers_.flatten())
        for centroid in cluster_centers:
            closest_idx = np.argmin(np.subtract(e_list, centroid)**2)
            idx_to_keep.append(closest_idx)
        idx_to_keep[-1] = len(e_list) - 1  # replace the last
        idx_list = np.arange(len(s_list))
        idx_batched = np.array_split(idx_list[:-1], n)
        idx_kept = [batch[0] for batch in idx_batched]
        idx_kept.append(idx_list[-1])
    else:
        idx_kept = np.arange(len(e_list))

    for j, idx in enumerate(idx_kept):
        filestem = str(j)
        s_filename = '{}/{}{}.{}'.format(fileroot, prefix, filestem,
                                         s_extension)
        e_filename = '{}/{}{}.{}'.format(fileroot, prefix, filestem,
                                         e_extension)
        s_list[idx].to(fmt='poscar', filename=s_filename)
        with open(e_filename, 'w') as f:
            f.write(str(e_list[idx]))
Beispiel #5
0
 def test_pymatgen_big_timestep(self):
     xd = Xdatcar(os.path.join(os.path.dirname(kinisi.__file__), 'tests/inputs/example_XDATCAR.gz'))
     da_params = { 'specie': 'Li',
                   'time_step': 20.0,
                   'step_skip': 100,
                   'min_obs': 50}
     data = parser.PymatgenParser(xd.structures, **da_params)
     assert_almost_equal(data.time_step, 20.0)
     assert_almost_equal(data.step_skip, 100)
     assert_equal(data.indices, list(range(xd.natoms[0])))
def assess_XDATCAR(directory):
    """
  reports how many ionic steps a calculation has run for by reading the XDATCAR (cannot always rely on vasprun, as it is unreadable if the caluclation is unfinished)
  args:
      - directory (str): directory to check for XDATCAR
  returns:
      - xdatcar (int): the number of steps saved to the XDATCAR
  """
    if os.path.exists(f'{directory}/XDATCAR'):
        try:
            xdatcar = len(Xdatcar(f'{directory}/XDATCAR').structures)
        except:
            xdatcar = None
    else:
        xdatcar = None
    return xdatcar
    def from_xdatcar(cls,
                     filename,
                     recipes,
                     read_config_numbers=True,
                     config_numbers=None,
                     verbose=False,
                     progress=None,
                     ncores=None):
        """
        Args:
            filename (str): Filename for a VASP XDATCAR file.
            recipes (list(:obj:`PolyhedraRecipe`): List of `PolyhedraRecipe` recipes, 
                where each recipe defines how to construct a set of `CoordinationPolyhedra` 
                for each configuration.
            read_config_numbers (:obj:`bool`, optional): Read configuration frame numbers from the XDATCAR.
            config_numbers (:obj:`list`, optional): Optional list of integers to use as frame numbers for
                each configuration in the XDATCAR input. If this argument is set, it will override
                the `read_config_numbers` argument.

                      config_numbers=None, verbose=False ):

        Returns:
            (:obj:`Trajectory`): a :obj:`Trajectory` object.

        Notes:
            If `read_config_numbers` is set to False, and `config_numbers` is not set,
            the XDATCAR configurations will be numbered 1, 2, 3, 4, ….
        """
        xdatcar = Xdatcar(filename)
        structures = xdatcar.structures
        if read_config_numbers and not config_numbers:
            config_numbers = read_config_numbers_from_xdatcar(filename)
        elif config_numbers:
            config_numbers = config_numbers
        else:
            config_numbers = list(range(1, len(structures) + 1))
        if len(config_numbers) != len(structures):
            raise ValueError(
                'number of configuration numbers != number of structures: {}, {}'
                .format(config_numbers, len(structures)))
        return cls.from_structures(structures,
                                   recipes,
                                   config_numbers,
                                   verbose=verbose,
                                   progress=progress,
                                   ncores=ncores)
Beispiel #8
0
def main():
    args = parse_command_line_arguments()
    max_r = args.max_r
    number_of_bins = args.n_bins
    species_1 = args.label[ 0 ]
    species_2 = args.label[ 1 ]
    xdatcar = Xdatcar( args.xdatcar )
    indices_i = [ i for i, s in enumerate(xdatcar.structures[0]) 
                  if s.species_string == species_1 ]
    if not indices_i:
        raise ValueError( f'No species {species_1} found' )
    indices_j = [ i for i, s in enumerate(xdatcar.structures[0]) 
                  if s.species_string == species_2 ]
    if not indices_j:
        raise ValueError( f'No species {species_2} found' )
    rdf = RadialDistributionFunction( xdatcar.structures, indices_i, indices_j, 
                                      number_of_bins, 0.0, max_r )
    for x, y in zip( rdf.r, rdf.rdf ):
        print(x, y)
 def from_xdatcars(cls,
                   filenames: List[str],
                   recipes: List[PolyhedraRecipe],
                   verbose: bool = False,
                   ncores: Optional[int] = None,
                   progress: Union[bool, str] = False) -> Trajectory:
     """
     TODO
     """
     if ncores and len(filenames) > 1:
         with multiprocessing.Pool(ncores) as p:
             xdatcars = p.map(_get_xdatcar, filenames)
     else:
         xdatcars = [Xdatcar(f) for f in filenames]
     structures = flatten([x.structures for x in xdatcars])
     return cls.from_structures(structures,
                                recipes,
                                verbose,
                                ncores=ncores,
                                progress=progress)
 def from_xdatcars(cls,
                   filenames,
                   recipes,
                   verbose=False,
                   ncores=None,
                   progress=None):
     """
     TODO
     """
     if ncores and len(filenames) > 1:
         with multiprocessing.Pool(ncores) as p:
             xdatcars = p.map(_get_xdatcar, filenames)
     else:
         xdatcars = [Xdatcar(f) for f in filenames]
     structures = flatten([x.structures for x in xdatcars])
     config_numbers = list(range(1, len(structures) + 1))
     return cls.from_structures(structures,
                                recipes,
                                config_numbers,
                                verbose,
                                ncores=ncores,
                                progress=progress)
    def from_xdatcar(cls,
                     filename: str,
                     recipes: List[PolyhedraRecipe],
                     verbose: bool = False,
                     progress: Union[str, bool] = False,
                     ncores: Optional[int] = None) -> Trajectory:
        """
        Args:
            filename (str): Filename for a VASP XDATCAR file.
            recipes (list(:obj:`PolyhedraRecipe`): List of `PolyhedraRecipe` recipes, 
                where each recipe defines how to construct a set of `CoordinationPolyhedra` 
                for each configuration.

        Returns:
            (:obj:`Trajectory`): a :obj:`Trajectory` object.

        """
        xdatcar = Xdatcar(filename)
        structures = xdatcar.structures
        return cls.from_structures(structures,
                                   recipes,
                                   verbose=verbose,
                                   progress=progress,
                                   ncores=ncores)
Beispiel #12
0
    def __init__(self,
                 trajectory,
                 parser_params,
                 bootstrap_params=None,
                 dtype='Xdatcar'):  # pragma: no cover
        if bootstrap_params is None:
            bootstrap_params = {}
        if dtype is 'Xdatcar':
            try:
                from pymatgen.io.vasp import Xdatcar
            except ModuleNotFoundError:
                raise ModuleNotFoundError(
                    "To use the Xdatcar file parsing, pymatgen must be installed."
                )
            if isinstance(trajectory, list):
                trajectory_list = (Xdatcar(f) for f in trajectory)
                structures = _flatten_list(
                    [x.structures for x in trajectory_list])
            else:
                xd = Xdatcar(trajectory)
                structures = xd.structures
            u = PymatgenParser(structures, **parser_params)
            self.first_structure = structures[0]
            dt = u.delta_t
            disp_3d = u.disp_3d
        elif dtype is 'IdenticalXdatcar':
            try:
                from pymatgen.io.vasp import Xdatcar
            except ModuleNotFoundError:
                raise ModuleNotFoundError(
                    "To use the Xdatcar file parsing, pymatgen must be installed."
                )
            u = [
                PymatgenParser(Xdatcar(f).structures, **parser_params)
                for f in trajectory
            ]
            joint_disp_3d = []
            for i in range(len(u[0].disp_3d)):
                disp = np.zeros(
                    (u[0].disp_3d[i].shape[0] * len(u),
                     u[0].disp_3d[i].shape[1], u[0].disp_3d[i].shape[2]))
                disp[:u[0].disp_3d[i].shape[0]] = u[0].disp_3d[i]
                for j in range(1, len(u)):
                    disp[u[0].disp_3d[i].shape[0] *
                         j:u[0].disp_3d[i].shape[0] *
                         (j + 1)] = u[j].disp_3d[i]
                joint_disp_3d.append(disp)
            dt = u[0].delta_t
            disp_3d = joint_disp_3d
        elif dtype is 'structures':
            u = PymatgenParser(trajectory, **parser_params)
            self.first_structure = trajectory[0]
            dt = u.delta_t
            disp_3d = u.disp_3d
        elif dtype == 'universe':
            u = MDAnalysisParser(trajectory, **parser_params)
            dt = u.delta_t
            disp_3d = u.disp_3d
        else:
            try:
                import MDAnalysis as mda
            except ModuleNotFoundError:
                raise ModuleNotFoundError(
                    "To use the MDAnalysis from file parsing, MDAnalysis must be installed."
                )
            universe = mda.Universe(*trajectory, format=dtype)
            u = MDAnalysisParser(universe, **parser_params)
            dt = u.delta_t
            disp_3d = u.disp_3d

        self._diff = diffusion.MSDBootstrap(dt, disp_3d, **bootstrap_params)

        self.dt = self._diff.dt
        self.msd_observed = self._diff.msd_observed
        self.distributions = self._diff.distributions
Beispiel #13
0
 def setUp(self):
     self.traj = Xdatcar('test_rdf_XDATCAR.txt').structures
     self.ref_data = np.loadtxt('test_rdf_ref.txt')
     self.threshold = 0.07
rdf_clcl = RadialDistributionFunction.from_species_strings(structures=[structure],
                                                           species_i='Cl')
rdf_nacl = RadialDistributionFunction.from_species_strings(structures=[structure],
                                                           species_i='Na',
                                                           species_j='Cl')
plt.plot(rdf_nana.r, rdf_nana.smeared_rdf(), 'k', label='Na-Na')
plt.plot(rdf_clcl.r, rdf_clcl.smeared_rdf(sigma=0.07), 'b:', label='Cl-Cl')
plt.plot(rdf_nacl.r, rdf_nacl.smeared_rdf(sigma=0.07), 'g--', label='Na-Cl')
plt.legend(loc='best', fontsize=20)
plt.xticks(fontsize=20)
plt.yticks(fontsize=20)
plt.show()

from pymatgen.io.vasp import Xdatcar

xd = Xdatcar('NaCl_800K_MD_XDATCAR')

rdf_nana_800K = RadialDistributionFunction.from_species_strings(
    structures=xd.structures,
    species_i='Na',
    r_max=20
)
rdf_clcl_800K = RadialDistributionFunction.from_species_strings(
    structures=xd.structures,
    species_i='Cl',
    r_max=20
)
rdf_nacl_800K = RadialDistributionFunction.from_species_strings(
    structures=xd.structures,
    species_i='Na',
    species_j='Cl',
Beispiel #15
0
import os

from pymatgen.io.vasp import Xdatcar
from pymatgen_diffusion.aimd.van_hove import EvolutionAnalyzer

os.chdir('/home/jinho93/oxides/cluster/zno/vasp/1.aimd/2.10A/2.02/3fs')
structures = Xdatcar('XDATCAR').structures
e = EvolutionAnalyzer(structures)
for s in structures:
    s.substitute()
e.plot_rdf_evolution(('O', 'O'))
def _get_xdatcar(filename):
    """
    Internal method to support multiprocessing.
    """
    return Xdatcar(filename)
Beispiel #17
0
#%%
from pymatgen.core.structure import Structure
from pymatgen.io.vasp import Xdatcar
import numpy as np
import os

os.chdir('/home/jinho93/tmdc/WTe2/noelect/novdw/from_paper/MD')
xdat = Xdatcar.from_file('XDATCAR')

coords = [s.frac_coords for s in xdat.structures]

coords = np.array(coords)
coords = np.sum(coords, axis=0) / 100
print(coords.shape)

si: Structure = xdat.structures[0]
s = Structure(si.lattice, si.species, coords)

s.to('POSCAR', 'new-POSCAR')
Beispiel #18
0
#!/usr/bin/env python
# coding: utf-8

from pymatgen.io.vasp import Poscar, Xdatcar
from pymatgen.symmetry.groups import SpaceGroup
from pymatgen import Structure, Lattice
import numpy as np
import operator
from site_analysis import Atom, Analysis, ShortestDistanceSite, get_vertex_indices, AtomsTrajectory, SitesTrajectory
from collections import Counter
import tqdm

x1 = Xdatcar('1/XDATCAR')
x2 = Xdatcar('2/XDATCAR')
x3 = Xdatcar('3/XDATCAR')
x4 = Xdatcar('4/XDATCAR')
x5 = Xdatcar('5/XDATCAR')
structures = x1.structures + x2.structures + x3.structures + x4.structures + x5.structures


all_na_structure = Poscar.from_file('na_sn_all_na_ext.POSCAR.vasp').structure
vertex_species = 'Se'
centre_species = 'Na'

sg = SpaceGroup('I41/acd:2')
from pymatgen import Structure, Lattice
lattice = all_na_structure.lattice
na1 = Structure.from_spacegroup(sg='I41/acd:2', lattice=lattice, species=['Na'], coords=[[0.25, 0.0, 0.125]])
na2 = Structure.from_spacegroup(sg='I41/acd:2', lattice=lattice, species=['Na'], coords=[[0.00, 0.0, 0.125]])
na3 = Structure.from_spacegroup(sg='I41/acd:2', lattice=lattice, species=['Na'], coords=[[0.0, 0.25, 0.0]])
na4 = Structure.from_spacegroup(sg='I41/acd:2', lattice=lattice, species=['Na'], coords=[[0.0, 0.0, 0.0]])
Beispiel #19
0
import math

from pymatgen import Structure, Element
from pymatgen.io.vasp import Oszicar, Xdatcar, Vasprun
import os
import numpy as np
os.chdir('/home/jinho93/interface/lsmo-bto-pt/2.vaccum/baobao/up/again')
dat = Xdatcar('XDATCAR')
zicar = Oszicar('OSZICAR')
vrun = Vasprun('vasprun.xml')
energies = zicar.ionic_steps
selective = [
    r.properties['selective_dynamics'][2] for r in vrun.final_structure.sites
]
output = []
ionic = vrun.ionic_steps
for s, e, ion in zip(dat.structures, energies, ionic):
    sr = []
    ti = []
    z = []
    for i in s.sites:
        if i.specie == Element.O:
            z.append(i.z)
        elif i.specie == Element.Ti or i.specie == Element.Ti:
            ti.append(i.z)
        elif i.specie is Element.Ba or i.specie == Element.Ba:
            sr.append(i.z)

    arr_Sr = [x - y for x, y in zip(sorted(sr[1:]), sorted(z)[2::3])]
    arr_Ti = [x - y for x, y in zip(sorted(ti), sorted(z)[1::3])]
    if max(np.array(ion['forces'])[:, 2][selective]) < .2:
#!/usr/bin/env python
# coding: utf-8

import matplotlib.pyplot as plt
from pymatgen import Structure
from pymatgen.io.vasp import Poscar, Xdatcar
from pymatgen.analysis.diffusion_analyzer import DiffusionAnalyzer, get_arrhenius_plot, get_extrapolated_conductivity

temperatures = [500, 600, 700, 800, 900, 1000]
tetrels = ["Ge", "Sn"]

for i in temperatures:
    for j in tetrels:
        x1 = Xdatcar(f'{i}K/{j}/1/XDATCAR')
        x2 = Xdatcar(f'{i}K/{j}/2/XDATCAR')
        x3 = Xdatcar(f'{i}K/{j}/3/XDATCAR')
        x4 = Xdatcar(f'{i}K/{j}/4/XDATCAR')
        x5 = Xdatcar(f'{i}K/{j}/5/XDATCAR')
        structures = x1.structures + x2.structures + x3.structures + x4.structures + x5.structures

s500K = [
    "500/Sn/1/vasprun.xml", "500/Sn/2/vasprun.xml", "500/Sn/3/vasprun.xml"
]
d500K = DiffusionAnalyzer.from_files(s500K, specie="Na", smoothed=max)
s600K = [
    "600/Sn/1/vasprun.xml", "600/Sn/2/vasprun.xml", "600/Sn/3/vasprun.xml"
]
d600K = DiffusionAnalyzer.from_files(s600K, specie="Na", smoothed=max)
s700K = [
    "700/Sn/1/vasprun.xml", "700/Sn/2/vasprun.xml", "700/Sn/3/vasprun.xml"
]