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_make_spin_charges(simple_cubic): structure = Structure.from_dict(simple_cubic.as_dict()) chgcar = Chgcar(structure, data={"total": np.array([[[2.0]]])}) actual = make_spin_charges(chgcar) assert_almost_equal(actual[0].data["total"], np.array([[[1.0]]])) chgcar = Chgcar(structure, data={ "total": np.array([[[2.0]]]), "diff": np.array([[2.0]]) }) actual = make_spin_charges(chgcar) assert_almost_equal(actual[1].data["total"], np.array([[[0.0]]]))
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 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 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 chgcar(): struc = Structure(lattice=Lattice.cubic(10), species=["H"], coords=[[0] * 3]) data = { "total": np.array([[[0.0, 2.0, 4.0, 6.0, 8.0]]]), "diff": np.array([[[0.0, 1.0, 2.0, 3.0, 4.0]]]) } return Chgcar(struc, data=data)
def get_chgcar(self, task_id): """ Read the CHGCAR data into a PMG Chgcar object Args: task_id(int or str): the task_id containing the data Returns: chgcar: Chgcar object """ obj_dict = self.get_data_from_maggma_or_gridfs(task_id, key="chgcar") return Chgcar.from_dict(obj_dict)
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 get_aeccar(self, task_id, check_valid=True): """ Read the AECCAR0 + AECCAR2 grid_fs data into a Chgcar object Args: task_id(int or str): the task_id containing the gridfs metadata check_valid (bool): make sure that the aeccar is positive definite Returns: {"aeccar0" : Chgcar, "aeccar2" : Chgcar}: dict of Chgcar objects """ obj_dict = self.get_data_from_maggma_or_gridfs(task_id, key="aeccar0") aeccar0 = Chgcar.from_dict(obj_dict) obj_dict = self.get_data_from_maggma_or_gridfs(task_id, key="aeccar2") aeccar2 = Chgcar.from_dict(obj_dict) if check_valid and (aeccar0.data["total"] + aeccar2.data["total"]).min() < 0: ValueError( f"The AECCAR seems to be corrupted for task_id = {task_id}") return {"aeccar0": aeccar0, "aeccar2": aeccar2}
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 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 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(): structure = Structure(Lattice.cubic(3), ["H"], [[0, 0, 0]]) data = { "total": np.array([[[3] * 3] * 3] * 3), "diff": np.array([[[-1] * 3] * 3] * 3) } chgcar = Chgcar(structure, data) rad = RadialDist(chgcar, [0, 0, 0]) assert len(rad.distances_data) == 1 + 6 + 12 np.testing.assert_almost_equal(rad.distances_data[0][0], np.array([-1 / 3, -1. / 3, 0.0])) assert rad.distances_data[0][1] == np.sqrt(2) assert rad.distances_data[0][2] == 24 np.testing.assert_almost_equal(rad.distances_data[0][3], np.array([-1, -1, 0.0])) hist_data, half_point, summed = rad.histogram(Spin.up) np.testing.assert_almost_equal(hist_data[0], [5.00000000e-02, 1.16355283e-03])
def test_light_weight_vol_text(tmpdir): print(tmpdir) tmpdir.chdir() structure = Structure(Lattice.cubic(1), species=["O"], coords=[[0] * 3]) chgcar = Chgcar(structure, data={"total": np.array([[[0.0, 0.1, 0.2, -1e-5]]])}) actual = light_weight_vol_text(volumetric_data=chgcar, border_fractions=[0.45, 0.55]) expected = """O1 1.0 1.000000 0.000000 0.000000 0.000000 1.000000 0.000000 0.000000 0.000000 1.000000 O 1 direct 0.000000 0.000000 0.000000 O 1 1 4 0 1 2 0""" assert actual == expected
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
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 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)
def check(self): aeccar0 = Chgcar.from_file("AECCAR0") aeccar2 = Chgcar.from_file("AECCAR2") aeccar = aeccar0 + aeccar2 return check_broken_chgcar(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
# 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,
#%% 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 parchg(): struc = Structure(lattice=Lattice.cubic(10), species=["H"], coords=[[0]*3]) data = {"total": np.array([[[0, 0], [0, 2000.0]], [[0, 0], [0, 0]]]), "diff": np.array([[[0, 0], [0, 1000.0]], [[0, 0], [0, 0]]])} # spin-up: 1.5, spin-down: 0.5 return Chgcar(struc, data=data)
#%% 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 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 to_Chgcar(self) -> Chgcar: struct = self.chargeden_dict[self._tmp_key].structure data_ = {k: v.renormalized_data for k, v in self.chargeden_dict.items()} return Chgcar(Poscar(struct), data_, data_aug=self.aug_charge)
def interstitials_from_charge_density(aeccar0, aeccar2, **kwargs): aeccar = Chgcar.from_file(aeccar0) + Chgcar.from_file(aeccar2) interstitials_from_volumetric_data(aeccar, **kwargs)