def __init__(self,parchg_file): """ Reads in the data from the provided PARCHG file and store as class attributes Parameters ---------- parchg_file: (str) full path to PARCHG file """ self.path, self.filename = os.path.split(parchg_file) if self.filename.endswith('.hdf5'): parchg = VolumetricData.from_hdf5(parchg_file) else: parchg = Chgcar.from_file(parchg_file) ## convert to hdf5 for much quicker reading in the future... Chgcar.from_file(parchg_file).to_hdf5(os.path.join(self.path,'%s.hdf5'%self.filename)) ## structure associated w/ volumetric data self.structure = parchg.structure ## charge data from PARCHG/CHGCAR self.chgdata = parchg.data['total'] ## grid size (NGXF, NGYF, NGZF) (self.ngrid_a, self.ngrid_b, self.ngrid_c) = np.shape(self.chgdata) ## grid vectors self.gridvec_a = self.structure.lattice.matrix[0]/self.ngrid_a self.gridvec_b = self.structure.lattice.matrix[1]/self.ngrid_b
def check(self): """ Check for error. """ aeccar0 = Chgcar.from_file("AECCAR0") aeccar2 = Chgcar.from_file("AECCAR2") aeccar = aeccar0 + aeccar2 return check_broken_chgcar(aeccar)
def test_image_num(self): module_dir = os.path.dirname(os.path.abspath(__file__)) test_file_dir = os.path.join(module_dir, "..", "..", "..", "test_files", "path_finder") start_s = Poscar.from_file(os.path.join(test_file_dir, 'LFP_POSCAR_s')).structure end_s = Poscar.from_file(os.path.join(test_file_dir, 'LFP_POSCAR_e')).structure mid_s = start_s.interpolate(end_s, nimages=2, interpolate_lattices=False)[1] chg = Chgcar.from_file(os.path.join(test_file_dir, 'LFP_CHGCAR.gz')) moving_cation_specie = Element('Li') relax_sites = [] for site_i, site in enumerate(start_s.sites): if site.specie == moving_cation_specie: relax_sites.append(site_i) pf = NEBPathfinder(start_s, end_s, relax_sites=relax_sites, v=ChgcarPotential(chg).get_v(), n_images=(8 * 3)) images = [] for i, image in enumerate(pf.images): if i % 3 == 0: images.append(image) self.assertEqual(len(images), 9) pf_mid = NEBPathfinder(start_s, end_s, relax_sites=relax_sites, v=ChgcarPotential(chg).get_v(), n_images=10, mid_struct=mid_s) moving_site = relax_sites[0] dists = [s1.sites[moving_site].distance(s2.sites[moving_site]) for s1, s2 in zip(pf.images[:-1], pf.images[1:])] # check that all the small distances are about equal self.assertTrue(abs(min(dists)-max(dists))/mean(dists) < 0.02)
def test_image_num(self): os.path.dirname(os.path.abspath(__file__)) test_file_dir = os.path.join(PymatgenTest.TEST_FILES_DIR, "path_finder") start_s = Poscar.from_file(os.path.join(test_file_dir, "LFP_POSCAR_s")).structure end_s = Poscar.from_file(os.path.join(test_file_dir, "LFP_POSCAR_e")).structure chg = Chgcar.from_file(os.path.join(test_file_dir, "LFP_CHGCAR.gz")) moving_cation_specie = Element("Li") relax_sites = [] for site_i, site in enumerate(start_s.sites): if site.specie == moving_cation_specie: relax_sites.append(site_i) pf = NEBPathfinder( start_s, end_s, relax_sites=relax_sites, v=ChgcarPotential(chg).get_v(), n_images=(8 * 3), ) images = [] for i, image in enumerate(pf.images): if i % 3 == 0: images.append(image) self.assertEqual(len(images), 9) moving_site = relax_sites[0] dists = [ s1.sites[moving_site].distance(s2.sites[moving_site]) for s1, s2 in zip(pf.images[:-1], pf.images[1:]) ] # check that all the small distances are about equal self.assertTrue(abs(min(dists) - max(dists)) / mean(dists) < 0.02)
def get_chgint_plot(args): chgcar = Chgcar.from_file(args.chgcar_file) s = chgcar.structure if args.inds: atom_ind = [int(i) for i in args.inds[0].split(",")] else: finder = SpacegroupAnalyzer(s, symprec=0.1) sites = [ sites[0] for sites in finder.get_symmetrized_structure().equivalent_sites ] atom_ind = [s.sites.index(site) for site in sites] from pymatgen.util.plotting import pretty_plot plt = pretty_plot(12, 8) for i in atom_ind: d = chgcar.get_integrated_diff(i, args.radius, 30) plt.plot(d[:, 0], d[:, 1], label="Atom {} - {}".format(i, s[i].species_string)) plt.legend(loc="upper left") plt.xlabel("Radius (A)") plt.ylabel("Integrated charge (e)") plt.tight_layout() return plt
def make_defect_charge_info_main(args): band_idxs = [int(parchg.split(".")[-2]) - 1 for parchg in args.parchgs] parchgs = [Chgcar.from_file(parchg) for parchg in args.parchgs] defect_charge_info = make_defect_charge_info(parchgs, band_idxs, args.bin_interval, args.grids) defect_charge_info.to_json_file() plt = defect_charge_info.show_dist() plt.savefig("dist.pdf")
def setUp(self): self.test_ents_MOF = loadfn(f"{dir_path}/full_path_files/Mn6O5F7_cat_migration.json") self.aeccar_MOF = Chgcar.from_file(f"{dir_path}/full_path_files/AECCAR_Mn6O5F7.vasp") self.li_ent = loadfn(f"{dir_path}/full_path_files/li_ent.json")["li_ent"] self.full_struct = MigrationGraph.get_structure_from_entries( base_entries=[self.test_ents_MOF["ent_base"]], inserted_entries=self.test_ents_MOF["one_cation"], migrating_ion_entry=self.li_ent, )[0]
def setUp(self): self.full_sites_MOF = loadfn(f"{dir_path}/full_path_files/LixMn6O5F7_full_sites.json") self.aeccar_MOF = Chgcar.from_file(f"{dir_path}/full_path_files/AECCAR_Mn6O5F7.vasp") self.cbg = ChargeBarrierGraph.with_distance( structure=self.full_sites_MOF, migrating_specie="Li", max_distance=4, potential_field=self.aeccar_MOF, potential_data_key="total", ) self.cbg._tube_radius = 10000
def make_scene_dicts(parchg_list, defect_pos, level=None): band_indices = [c.split(".")[-2] for c in parchg_list] # parchgs = [Chgcar.from_file(c) for c in parchg_list] parchgs = [] for c in parchg_list: try: parchgs.append(Chgcar.from_file(c)) except ValueError: continue if len(parchgs) == 0: return None structure: Structure = parchgs[0].structure if len(parchg_list) > 1: for parchg in parchgs[1:]: assert structure == parchg.structure lattice_matrix = parchgs[0].structure.lattice.matrix # centering to [0.5, 0.5, 0.5] shift_vector = np.array([0.5 - pos for pos in defect_pos]) shape = parchgs[0].data["total"].shape shift_numbers = np.array(np.rint(shape * shift_vector), dtype=np.int) actual_shift_vector = shift_numbers / shape step_size = int(min(parchgs[0].dim) / 30) results = {} for name, parchg in zip(band_indices, parchgs): for spin in [Spin.up, Spin.down]: spin_str = "up" if spin is Spin.up else "down" key = name + "_" + spin_str data = parchg.spin_data[spin] x_shifted = np.roll(data, shift_numbers[0], axis=0) xy_shifted = np.roll(x_shifted, shift_numbers[1], axis=1) xyz_shifted = np.roll(xy_shifted, shift_numbers[2], axis=2) try: vertices, faces = get_vertices_and_faces(xyz_shifted, lattice_matrix, step_size=step_size, level=level) results[key] = {"vertices": vertices, "faces": faces} except RuntimeError: continue structure.translate_sites(indices=list(range(len(structure))), vector=actual_shift_vector) graph = StructureGraph.with_empty_graph(structure=structure) return SceneDicts(results, structure_graph=graph)
def setUp(self): self.test_ents_MOF = loadfn( f'{dir_path}/full_path_files/Mn6O5F7_cat_migration.json') self.aeccar_MOF = Chgcar.from_file( f'{dir_path}/full_path_files/AECCAR_Mn6O5F7.vasp') self.cep = ComputedEntryPath( base_struct_entry=self.test_ents_MOF['ent_base'], migrating_specie='Li', single_cat_entries=self.test_ents_MOF['one_cation'], base_aeccar=self.aeccar_MOF) # structure matcher used for validation self.rough_sm = StructureMatcher(comparator=ElementComparator(), primitive_cell=False, ltol=0.5, stol=0.5, angle_tol=7)
def make_light_weight_vol_data(args): chgcar = Chgcar.from_file(args.volumetric_file) output_vol_filename = (args.output_lw_volumetric_filename or Path(f"{args.volumetric_file}_lw")) lw_vol_text = light_weight_vol_text(chgcar, args.border_fractions) Path(output_vol_filename).write_text(lw_vol_text) if args.output_vesta_filename: is_chg = "CHG" in args.volumetric_file volume = chgcar.structure.volume isurfs = calc_isurfs(args.border_fractions, is_chg, volume) if args.original_vesta_file: vesta_text = args.original_vesta_file.read_text() else: vesta_text = VestaFile(chgcar.structure).__repr__() to_vesta_text = add_density(vesta_text, isurfs, str(output_vol_filename)) Path(args.output_vesta_filename).write_text(to_vesta_text)
def test_image_num(self): module_dir = os.path.dirname(os.path.abspath(__file__)) test_file_dir = os.path.join(module_dir, "..", "..", "..", "test_files", "path_finder") start_s = Poscar.from_file(os.path.join(test_file_dir, 'LFP_POSCAR_s')).structure end_s = Poscar.from_file(os.path.join(test_file_dir, 'LFP_POSCAR_e')).structure chg = Chgcar.from_file(os.path.join(test_file_dir, 'LFP_CHGCAR.gz')) moving_cation_specie = Element('Li') relax_sites = [] for site_i, site in enumerate(start_s.sites): if site.specie == moving_cation_specie: relax_sites.append(site_i) pf = NEBPathfinder(start_s, end_s, relax_sites=relax_sites, v=ChgcarPotential(chg).get_v(), n_images=(8 * 3)) images = [] for i, image in enumerate(pf.images): if i % 3 == 0: images.append(image) self.assertEqual(len(images), 9)
def read_structure(filename, primitive=True, sort=False): """ Reads a structure based on file extension. For example, anything ending in a "cif" is assumed to be a Crystallographic Information Format file. Supported formats include CIF, POSCAR/CONTCAR, CHGCAR, LOCPOT, vasprun.xml, CSSR and pymatgen's JSON serialized structures. Args: filename (str): A filename to read from. primitive (bool): Whether to convert to a primitive cell for cifs. Defaults to True. sort (bool): Whether to sort sites. Default to False. Returns: A Structure object. """ fname = os.path.basename(filename) if fnmatch(fname.lower(), "*.cif*"): parser = CifParser(filename) s = parser.get_structures(primitive=primitive)[0] elif fnmatch(fname, "POSCAR*") or fnmatch(fname, "CONTCAR*"): s = Poscar.from_file(filename, False).structure elif fnmatch(fname, "CHGCAR*") or fnmatch(fname, "LOCPOT*"): s = Chgcar.from_file(filename).structure elif fnmatch(fname, "vasprun*.xml*"): s = Vasprun(filename).final_structure elif fnmatch(fname.lower(), "*.cssr*"): cssr = Cssr.from_file(filename) s = cssr.structure elif fnmatch(fname, "*.json*") or fnmatch(fname, "*.mson*"): with zopen(filename) as f: s = json.load(f, cls=MontyDecoder) if type(s) != Structure: raise IOError("File does not contain a valid serialized " "structure") else: raise ValueError("Unrecognized file extension!") if sort: s = s.get_sorted_structure() return s
def get_chgint_plot(args): chgcar = Chgcar.from_file(args.chgcar_file) s = chgcar.structure if args.inds: atom_ind = [int(i) for i in args.inds[0].split(",")] else: finder = SpacegroupAnalyzer(s, symprec=0.1) sites = [sites[0] for sites in finder.get_symmetrized_structure().equivalent_sites] atom_ind = [s.sites.index(site) for site in sites] from pymatgen.util.plotting import pretty_plot plt = pretty_plot(12, 8) for i in atom_ind: d = chgcar.get_integrated_diff(i, args.radius, 30) plt.plot(d[:, 0], d[:, 1], label="Atom {} - {}".format(i, s[i].species_string)) plt.legend(loc="upper left") plt.xlabel("Radius (A)") plt.ylabel("Integrated charge (e)") plt.tight_layout() return plt
# ctc.register_app(app) # StructureMoleculeComponent def get_mesh(chgcar, data_tag="total", isolvl=2.0, step_size=3): vertices, faces, normals, values = measure.marching_cubes_lewiner( chgcar.data[data_tag], level=isolvl, step_size=step_size) vertices = (vertices / chgcar.data[data_tag].shape ) # transform to fractional coordinates vertices = np.dot(vertices - 0.5, cc.structure.lattice.matrix) # transform to cartesian return vertices, faces cc = Chgcar.from_file("./test_files/chgcar.vasp") vertices, faces = get_mesh(cc) vertices = vertices pos = [vert for triangle in vertices[faces].tolist() for vert in triangle] add_comp = [ ctc.Scene( "test", contents=[ ctc.Surface(positions=pos), ctc.Arrows(positionPairs=[[[0, 0, 0], [1, 1, 1]]]), ], ) ] struct_component = ctc.StructureMoleculeComponent(cc.structure,
def make_spin_decomposed_volumetric_files(args): chgcar = Chgcar.from_file(args.chgcar) for c, spin in zip(make_spin_charges(chgcar), ["up", "down"]): c.write_file(f"{args.chgcar}_{spin}")
def chgcar_test(): from pymatgen.io.vasp import Chgcar c = Chgcar.from_file("../test_files/CHGCAR.noncubic") print c.get_integrated_diff(1, 2.5, 3)
def interstitials_from_charge_density(aeccar0, aeccar2, **kwargs): aeccar = Chgcar.from_file(aeccar0) + Chgcar.from_file(aeccar2) interstitials_from_volumetric_data(aeccar, **kwargs)
#%% from pymatgen.io.vasp import Chgcar import os import matplotlib.pyplot as plt from joblib import Parallel, delayed os.chdir( '/home/jinho93/new/oxides/perobskite/lanthanum-aluminate/slab/3uc/efield/2/delta' ) chg = Chgcar.from_file('CHGCAR') #%% def distance(p1, p2): return math.sqrt(((p1[0] - p2[0])**2) + ((p1[1] - p2[1])**2) + ((p1[2] - p2[2])**2)) def potential(z): pot = 0 for i, a in enumerate(chg.data['total']): for j, b in enumerate(a): for k, c in enumerate(b): d = distance([chg.dim[0] // 2, 0, z], [i, j, k]) if d > 0: pot += c / d return pot
def from_file(cls, filename, primitive=False, sort=False, merge_tol=0.0): """ Reads a structure from a file. For example, anything ending in a "cif" is assumed to be a Crystallographic Information Format file. Supported formats include CIF, POSCAR/CONTCAR, CHGCAR, LOCPOT, vasprun.xml, CSSR, Netcdf and pymatgen's JSON serialized structures. Args: filename (str): The filename to read from. primitive (bool): Whether to convert to a primitive cell Only available for cifs. Defaults to False. sort (bool): Whether to sort sites. Default to False. merge_tol (float): If this is some positive number, sites that are within merge_tol from each other will be merged. Usually 0.01 should be enough to deal with common numerical issues. Returns: Structure. """ filename = str(filename) if filename.endswith(".nc"): # Read Structure from a netcdf file. from pymatgen.io.abinit.netcdf import structure_from_ncdata s = structure_from_ncdata(filename, cls=cls) if sort: s = s.get_sorted_structure() return s from pymatgen.io.lmto import LMTOCtrl from pymatgen.io.vasp import Vasprun, Chgcar from pymatgen.io.exciting import ExcitingInput from monty.io import zopen fname = os.path.basename(filename) with zopen(filename, "rt") as f: contents = f.read() if fnmatch(fname.lower(), "*.cif*") or fnmatch(fname.lower(), "*.mcif*"): return cls.from_str(contents, fmt="cif", primitive=primitive, sort=sort, merge_tol=merge_tol) elif fnmatch(fname, "*POSCAR*") or fnmatch(fname, "*CONTCAR*") or fnmatch(fname, "*.vasp"): s = cls.from_str(contents, fmt="poscar", primitive=primitive, sort=sort, merge_tol=merge_tol) elif fnmatch(fname, "CHGCAR*") or fnmatch(fname, "LOCPOT*"): s = Chgcar.from_file(filename).structure elif fnmatch(fname, "vasprun*.xml*"): s = Vasprun(filename).final_structure elif fnmatch(fname.lower(), "*.cssr*"): return cls.from_str(contents, fmt="cssr", primitive=primitive, sort=sort, merge_tol=merge_tol) elif fnmatch(fname, "*.json*") or fnmatch(fname, "*.mson*"): return cls.from_str(contents, fmt="json", primitive=primitive, sort=sort, merge_tol=merge_tol) elif fnmatch(fname, "*.yaml*"): return cls.from_str(contents, fmt="yaml", primitive=primitive, sort=sort, merge_tol=merge_tol) elif fnmatch(fname, "*.xsf"): return cls.from_str(contents, fmt="xsf", primitive=primitive, sort=sort, merge_tol=merge_tol) elif fnmatch(fname, "input*.xml"): return ExcitingInput.from_file(fname).structure elif fnmatch(fname, "*rndstr.in*") \ or fnmatch(fname, "*lat.in*") \ or fnmatch(fname, "*bestsqs*"): return cls.from_str(contents, fmt="mcsqs", primitive=primitive, sort=sort, merge_tol=merge_tol) elif fnmatch(fname, "CTRL*"): return LMTOCtrl.from_file(filename=filename).structure else: raise ValueError("Unrecognized file extension!") if sort: s = s.get_sorted_structure() if merge_tol: s.merge_sites(merge_tol) s.__class__ = cls return s
def check(self): aeccar0 = Chgcar.from_file("AECCAR0") aeccar2 = Chgcar.from_file("AECCAR2") aeccar = aeccar0 + aeccar2 return check_broken_chgcar(aeccar)
# so that Crystal Toolkit can create callbacks # ctc.register_app(app) # StructureMoleculeComponent def get_mesh(chgcar, data_tag='total', isolvl=2.0, step_size = 3): vertices, faces, normals, values = measure.marching_cubes_lewiner(chgcar.data[data_tag], level=isolvl, step_size=step_size) vertices = vertices/chgcar.data[data_tag].shape # transform to fractional coordinates vertices = np.dot(vertices-0.5, cc.structure.lattice.matrix) # transform to cartesian return vertices, faces cc = Chgcar.from_file('./test_files/chgcar.vasp') vertices,faces = get_mesh(cc) vertices = vertices pos = [vert for triangle in vertices[faces].tolist() for vert in triangle] add_comp = [ctc.Scene("test", contents=[ ctc.Surface(positions=pos), ctc.Arrows(positionPairs=[[[0,0,0], [1,1,1]]]), ])] struct_component = ctc.StructureMoleculeComponent( cc.structure, scene_additions=add_comp, hide_incomplete_bonds=True # get the data points to plot ) # for a custom-sized component, use `struct_component.struct_layout` and put
def test_make_local_extrema_from_volumetric_data(vasp_files, vol_params): aeccar0 = Chgcar.from_file(str(vasp_files / "NaMgF3_AECCAR0")) aeccar2 = Chgcar.from_file(str(vasp_files / "NaMgF3_AECCAR2")) aeccar = aeccar0 + aeccar2 aeccar.write_file("CHGCAR") make_local_extrema_from_volumetric_data(aeccar, vol_params)
#%% from pymatgen.io.vasp import Chgcar import numpy as np import os os.chdir('/home/share') chg = Chgcar.from_file('PARCHG') print(np.sum(chg.data['total']) / chg.ngridpts) #%% import matplotlib.pyplot as plt plt.plot(chg.get_average_along_axis(2)) # plt.imshow(np.sum(chg.data['total'], axis=0)) #%% n = chg.ngridpts k = 0 while n > 96: n -= 96 k += 1 #%% chg.structure.to('POSCAR', 'POSCAR')
def test_interstitials_from_charge_density(vasp_files): aeccar0 = Chgcar.from_file(str(vasp_files / "NaMgF3_AECCAR0")) aeccar2 = Chgcar.from_file(str(vasp_files / "NaMgF3_AECCAR2")) aeccar = aeccar0 + aeccar2 aeccar.write_file("CHGCAR") interstitials_from_volumetric_data(aeccar)
def process_chgcar(cls, chg_file): try: chgcar = Chgcar.from_file(chg_file) except IOError: raise ValueError("Unable to open CHGCAR/AECCAR file" ) return chgcar