def test_ordering_enumeration(self): # simple afm structure = Structure.from_file(os.path.join(ref_dir, "ordering/LaMnO3.json")) wf = MagneticOrderingsWF(structure) self.assertEqual(wf.input_origin, "afm") # ferrimagnetic (Cr produces net spin) structure = Structure.from_file(os.path.join(ref_dir, "ordering/Cr2NiO4.json")) wf = MagneticOrderingsWF(structure) self.assertEqual(wf.input_origin, "ferri_by_Cr") # antiferromagnetic on single magnetic site structure = Structure.from_file(os.path.join(ref_dir, "ordering/Cr2WO6.json")) wf = MagneticOrderingsWF(structure) self.assertEqual(wf.input_origin, "afm_by_Cr") # afm requiring large cell size # (enable for further development of workflow, too slow for CI) # structure = Structure.from_file(os.path.join(ref_dir, "CuO.json")) # wf = MagneticOrderingsWF(structure, default_magmoms={'Cu': 1.73}, # transformation_kwargs={'max_cell_size': 4}) # self.assertEqual(wf.input_origin, "afm") # antiferromagnetic by structural motif structure = Structure.from_file(os.path.join(ref_dir, "ordering/Ca3Co2O6.json")) wf = MagneticOrderingsWF( structure, strategies=("antiferromagnetic_by_motif",), # this example just misses default cut-off, so do not truncate truncate_by_symmetry=False, transformation_kwargs={"max_cell_size": 2}, ) self.assertEqual(wf.input_origin, "afm_by_motif_2a")
def run(self): if os.path.exists("CONTCAR"): structure = Structure.from_file("CONTCAR") elif (not self.contcar_only) and os.path.exists("POSCAR"): structure = Structure.from_file("POSCAR") else: raise RuntimeError("No CONTCAR/POSCAR detected to generate input!") modname, classname = self.input_set.rsplit(".", 1) mod = __import__(modname, globals(), locals(), [classname], 0) vis = getattr(mod, classname)(structure, **self.kwargs) vis.write_input(".")
def test_supercell_fit(self): sm = StructureMatcher(attempt_supercell=False) s1 = Structure.from_file(os.path.join(test_dir, "Al3F9.json")) s2 = Structure.from_file(os.path.join(test_dir, "Al3F9_distorted.json")) self.assertFalse(sm.fit(s1, s2)) sm = StructureMatcher(attempt_supercell=True) self.assertTrue(sm.fit(s1, s2)) self.assertTrue(sm.fit(s2, s1))
def setUp(self): with open(os.path.join(test_dir, "TiO2_entries.json"), 'r') as fp: entries = json.load(fp, cls=MontyDecoder) self.struct_list = [e.structure for e in entries] self.oxi_structs = [self.get_structure("Li2O"), Structure.from_file(os.path.join( test_dir, "POSCAR.Li2O"))]
def run_task(self, fw_spec): prev_dir = fw_spec.get('PREV_DIR', None) self.custom_params = self.get('custom_params', None) if isinstance(self["structure"], Structure): s = self["structure"] elif isinstance(self["structure"], dict): s = Structure.from_dict(self["structure"]) else: s = Structure.from_file(os.path.join(prev_dir, self["structure"])) vis = load_class("pymatgen.io.vasp.sets", self["vasp_input_set"])( **self.get("input_set_params", {})) vis.write_input(s, ".") # Write Custom KPOINTS settings if necessary ksettings = self.custom_params.get('user_kpts_settings', None) if isinstance( self.custom_params, dict) else None if ksettings: style = ksettings.get('kpts_style', 'Gamma') kpoints = ksettings.get('kpts', [16,16,16]) shift = ksettings.get('kpts_shift', [0,0,0]) k = Kpoints(kpts=[kpoints], kpts_shift=shift) k.style = style k.write_file("KPOINTS")
def generate_diffraction_plot(args): s = Structure.from_file(args.filenames[0]) c = XRDCalculator() if args.outfile: c.get_xrd_plot(s).savefig(args.outfile[0]) else: c.show_xrd_plot(s)
def test_partial_disorder(self): s = Structure.from_file(filename=os.path.join(test_dir, "garnet.cif")) a = SpacegroupAnalyzer(s, 0.1) prim = a.find_primitive() s = prim.copy() s["Al3+"] = {"Al3+": 0.5, "Ga3+": 0.5} adaptor = EnumlibAdaptor(s, 1, 1, enum_precision_parameter=0.01) adaptor.run() structures = adaptor.structures self.assertEqual(len(structures), 7) for s in structures: self.assertEqual(s.formula, 'Ca12 Al4 Ga4 Si12 O48') s = prim.copy() s["Ca2+"] = {"Ca2+": 1/3, "Mg2+": 2/3} adaptor = EnumlibAdaptor(s, 1, 1, enum_precision_parameter=0.01) adaptor.run() structures = adaptor.structures self.assertEqual(len(structures), 20) for s in structures: self.assertEqual(s.formula, 'Ca4 Mg8 Al8 Si12 O48') s = prim.copy() s["Si4+"] = {"Si4+": 1/3, "Ge4+": 2/3} adaptor = EnumlibAdaptor(s, 1, 1, enum_precision_parameter=0.01) adaptor.run() structures = adaptor.structures self.assertEqual(len(structures), 18) for s in structures: self.assertEqual(s.formula, 'Ca12 Al8 Si4 Ge8 O48')
def test_timeout(self): s = Structure.from_file(filename=os.path.join(test_dir, "garnet.cif")) a = SpacegroupAnalyzer(s, 0.1) s["Al3+"] = {"Al3+": 0.5, "Ga3+": 0.5} adaptor = EnumlibAdaptor(s, 1, 1, enum_precision_parameter=0.01, timeout=0.0000000000001) self.assertRaises(TimeoutError, adaptor._run_multienum)
def test_get_interstitial_sites_with_octahedra(self): os.chdir(ROOT) structure = Structure.from_file("POSCAR_Cu") test_ints = get_interstitial_sites(structure, octahedra=True) self.assertTrue(len(test_ints["tetrahedral"]) != 0) self.assertTrue(len(test_ints["hexahedral"]) != 0) self.assertTrue(len(test_ints["octahedral"]) != 0)
def parse_view(args): from pymatgen.vis.structure_vtk import StructureVis excluded_bonding_elements = args.exclude_bonding[0].split(",") \ if args.exclude_bonding else [] s = Structure.from_file(args.filename[0]) vis = StructureVis(excluded_bonding_elements=excluded_bonding_elements) vis.set_structure(s) vis.show()
def test_align_c_axis_for_non_aligned_structure(self): os.chdir(ROOT) structure = Structure.from_file('POSCAR_SF6') structure = align_axis(structure, 'c', (0, 0, 1)) control_axis = [9.04099732e-13, -2.42627092e-13, 8.3829076073038635] for i in range(3): self.assertAlmostEqual(structure.lattice.matrix[2][i], control_axis[i])
def test_large_systems(self): struct = Structure.from_file(os.path.join(test_dir, "La4Fe4O12.cif")) user_tag_settings = {"RECIPROCAL": "", "KMESH": "1000"} elnes = MPELNESSet("Fe", struct, user_tag_settings=user_tag_settings) self.assertNotIn("RECIPROCAL", elnes.tags) self.assertNotIn("KMESH", elnes.tags) self.assertNotIn("CIF", elnes.tags) self.assertNotIn("TARGET", elnes.tags)
def test_postfeffset(self): self.mp_xanes.write_input(os.path.join('.', 'xanes_3')) feff_dict_input = FEFFDictSet.from_directory(os.path.join('.', 'xanes_3')) self.assertTrue(feff_dict_input.tags == Tags.from_file(os.path.join('.', 'xanes_3/feff.inp'))) self.assertTrue(str(feff_dict_input.header()) == str(Header.from_file(os.path.join('.', 'xanes_3/HEADER')))) feff_dict_input.write_input('xanes_3_regen') origin_tags = Tags.from_file(os.path.join('.', 'xanes_3/PARAMETERS')) output_tags = Tags.from_file(os.path.join('.', 'xanes_3_regen/PARAMETERS')) origin_mole = Atoms.cluster_from_file(os.path.join('.', 'xanes_3/feff.inp')) output_mole = Atoms.cluster_from_file(os.path.join('.', 'xanes_3_regen/feff.inp')) original_mole_dist = np.array(origin_mole.distance_matrix[0, :]).astype(np.float64) output_mole_dist = np.array(output_mole.distance_matrix[0, :]).astype(np.float64) original_mole_shell = [x.species_string for x in origin_mole] output_mole_shell = [x.species_string for x in output_mole] self.assertTrue(np.allclose(original_mole_dist, output_mole_dist)) self.assertTrue(origin_tags == output_tags) self.assertTrue(original_mole_shell == output_mole_shell) shutil.rmtree(os.path.join('.', 'xanes_3')) shutil.rmtree(os.path.join('.', 'xanes_3_regen')) reci_mp_xanes = MPXANESSet(self.absorbing_atom, self.structure, user_tag_settings={"RECIPROCAL": ""}) reci_mp_xanes.write_input('xanes_reci') feff_reci_input = FEFFDictSet.from_directory(os.path.join('.', 'xanes_reci')) self.assertTrue("RECIPROCAL" in feff_reci_input.tags) feff_reci_input.write_input('Dup_reci') self.assertTrue(os.path.exists(os.path.join('.', 'Dup_reci', 'HEADER'))) self.assertTrue(os.path.exists(os.path.join('.', 'Dup_reci', 'feff.inp'))) self.assertTrue(os.path.exists(os.path.join('.', 'Dup_reci', 'PARAMETERS'))) self.assertFalse(os.path.exists(os.path.join('.', 'Dup_reci', 'ATOMS'))) self.assertFalse(os.path.exists(os.path.join('.', 'Dup_reci', 'POTENTIALS'))) tags_original = Tags.from_file(os.path.join('.', 'xanes_reci/feff.inp')) tags_output = Tags.from_file(os.path.join('.', 'Dup_reci/feff.inp')) self.assertTrue(tags_original == tags_output) stru_orig = Structure.from_file(os.path.join('.', 'xanes_reci/Co2O2.cif')) stru_reci = Structure.from_file(os.path.join('.', 'Dup_reci/Co2O2.cif')) self.assertTrue(stru_orig.__eq__(stru_reci)) shutil.rmtree(os.path.join('.', 'Dup_reci')) shutil.rmtree(os.path.join('.', 'xanes_reci'))
def test_align_c_axis_for_already_aligned_structure(self): os.chdir(ROOT) control_axis = [0, 0, 23.4186286267] structure = Structure.from_file('BiTeCl/POSCAR') structure = align_axis(structure, 'c', (0, 0, 1)) for i in range(3): self.assertTrue(abs( structure.lattice.matrix[2][i] - control_axis[i] ) < 0.0001)
def setUp(self): super(TestEXAFSPaths, self).setUp() self.struct = Structure.from_file(os.path.join(module_dir, "..", "..", "test_files", "feo_781777.json")) wflow = get_wf_exafs_paths(0, self.struct, [[249, 0], [85, 0]], feff_cmd="feff", db_file=None) self.wf_dict = wflow.as_dict() self.fw1_dict = self.wf_dict["fws"][0] self.fw2_dict = self.wf_dict["fws"][1] if self.wf_dict["fws"][0]['name'] not in ['FeO-EXAFS-K-0']: self.fw1_dict, self.fw2_dict = self.fw2_dict, self.fw1_dict
def test_electronegativity(self): sm = StructureMatcher(ltol=0.2, stol=0.3, angle_tol=5) s1 = Structure.from_file(os.path.join(test_dir, "Na2Fe2PAsO4S4.json")) s2 = Structure.from_file(os.path.join(test_dir, "Na2Fe2PNO4Se4.json")) self.assertEqual(sm.get_best_electronegativity_anonymous_mapping(s1, s2), {Element('S'): Element('Se'), Element('As'): Element('N'), Element('Fe'): Element('Fe'), Element('Na'): Element('Na'), Element('P'): Element('P'), Element('O'): Element('O'),}) self.assertEqual(len(sm.get_all_anonymous_mappings(s1, s2)), 2) # test include_dist dists = {Element('N'): 0, Element('P'): 0.0010725064} for mapping, d in sm.get_all_anonymous_mappings(s1, s2, include_dist=True): self.assertAlmostEqual(dists[mapping[Element('As')]], d)
def test_ignore_species(self): s1 = Structure.from_file(os.path.join(test_dir, "LiFePO4.cif")) s2 = Structure.from_file(os.path.join(test_dir, "POSCAR")) m = StructureMatcher(ignored_species=["Li"], primitive_cell=False, attempt_supercell=True) self.assertTrue(m.fit(s1, s2)) self.assertTrue(m.fit_anonymous(s1, s2)) groups = m.group_structures([s1, s2]) self.assertEqual(len(groups), 1) s2.make_supercell((2, 1, 1)) ss1 = m.get_s2_like_s1(s2, s1, include_ignored_species=True) self.assertAlmostEqual(ss1.lattice.a, 20.820740000000001) self.assertEqual(ss1.composition.reduced_formula, "LiFePO4") self.assertEqual({ k.symbol: v.symbol for k, v in m.get_best_electronegativity_anonymous_mapping(s1, s2).items()}, {"Fe": "Fe", "P": "P", "O": "O"})
def analyze_symmetry(args): tolerance = args.symmetry t = [] for filename in args.filenames: s = Structure.from_file(filename, primitive=False) finder = SpacegroupAnalyzer(s, tolerance) dataset = finder.get_symmetry_dataset() t.append([filename, dataset["international"], dataset["number"], dataset["hall"]]) print(tabulate(t, headers=["Filename", "Int Symbol", "Int number", "Hall"]))
def setUpClass(cls): cls.Cu_conv = Structure.from_file(os.path.join(test_dir, "Cu_mp-30_conventional_standard.cif")) GB_Cu_conv = GBGenerator(cls.Cu_conv) cls.Cu_GB1 = GB_Cu_conv.gb_from_parameters([1, 2, 3], 123.74898859588858, expand_times=4, vacuum_thickness=1.5, ab_shift=[0.0, 0.0], plane=[1, 3, 1]) cls.Cu_GB2 = GB_Cu_conv.gb_from_parameters([1, 2, 3], 123.74898859588858, expand_times=4, vacuum_thickness=1.5, ab_shift=[0.2, 0.2])
def test_rounding_errors(self): # It used to be that a rounding issue would result in this structure # showing that Cu3Te2 satisfies an ordering of this structure. # This has been fixed by multiplying the base by 100. struct = Structure.from_file(os.path.join(test_dir, "Cu7Te5.cif")) adaptor = EnumlibAdaptor(struct, 1, 2) self.assertRaises(EnumError, adaptor.run) adaptor = EnumlibAdaptor(struct, 1, 5) adaptor.run() self.assertEqual(len(adaptor.structures), 197)
def setUp(self): """Set up Structure from Cif file and path to jsons folder in Chemenv module in Pymatgen""" self.structure = Structure.from_file('LiCoO2.cif', True, False) self.structure.make_supercell([3, 3, 3]) for isite, site in enumerate(self.structure._sites): if site.species_string == 'Li': self.first_site = site self.ifirst_site = isite break self.path_to_jsons = os.path.dirname(cg_files.__file__)
def convert_fmt(args): iformat = args.input_format[0] oformat = args.output_format[0] filename = args.input_filename[0] out_filename = args.output_filename[0] try: if iformat == "smart": structure = Structure.from_file(filename) if iformat == "POSCAR": p = Poscar.from_file(filename) structure = p.structure elif iformat == "CIF": r = CifParser(filename) structure = r.get_structures()[0] elif iformat == "CONVENTIONAL_CIF": r = CifParser(filename) structure = r.get_structures(primitive=False)[0] elif iformat == "CSSR": structure = Cssr.from_file(filename).structure if oformat == "smart": structure.to(filename=out_filename) elif oformat == "POSCAR": p = Poscar(structure) p.write_file(out_filename) elif oformat == "CIF": w = CifWriter(structure) w.write_file(out_filename) elif oformat == "CSSR": c = Cssr(structure) c.write_file(out_filename) elif oformat == "VASP": input_set = MPVaspInputSet() ts = TransformedStructure( structure, [], history=[{"source": "file", "datetime": str(datetime.datetime.now()), "original_file": open(filename).read()}]) ts.write_vasp_input(input_set, output_dir=out_filename) elif oformat == "MITVASP": input_set = MITVaspInputSet() ts = TransformedStructure( structure, [], history=[{"source": "file", "datetime": str(datetime.datetime.now()), "original_file": open(filename).read()}]) ts.write_vasp_input(input_set, output_dir=out_filename) except Exception as ex: print("Error converting file. Are they in the right format?") print(str(ex))
def test_init(self): test_dir = os.path.join(os.path.dirname(__file__), "..", "..", "..", "test_files") struct = self.get_structure("LiFePO4") subtrans = SubstitutionTransformation({"Li": {"Li": 0.5}}) adaptor = EnumlibAdaptor(subtrans.apply_transformation(struct), 1, 2) adaptor.run() structures = adaptor.structures self.assertEqual(len(structures), 86) for s in structures: self.assertAlmostEqual(s.composition.get_atomic_fraction(Element("Li")), 0.5 / 6.5) adaptor = EnumlibAdaptor(subtrans.apply_transformation(struct), 1, 2, refine_structure=True) adaptor.run() structures = adaptor.structures self.assertEqual(len(structures), 52) subtrans = SubstitutionTransformation({"Li": {"Li": 0.25}}) adaptor = EnumlibAdaptor(subtrans.apply_transformation(struct), 1, 1, refine_structure=True) adaptor.run() structures = adaptor.structures self.assertEqual(len(structures), 1) for s in structures: self.assertAlmostEqual(s.composition.get_atomic_fraction(Element("Li")), 0.25 / 6.25) # Make sure it works for completely disordered structures. struct = Structure([[10, 0, 0], [0, 10, 0], [0, 0, 10]], [{"Fe": 0.5}], [[0, 0, 0]]) adaptor = EnumlibAdaptor(struct, 1, 2) adaptor.run() self.assertEqual(len(adaptor.structures), 3) # Make sure it works properly when symmetry is broken by ordered sites. struct = self.get_structure("LiFePO4") subtrans = SubstitutionTransformation({"Li": {"Li": 0.25}}) s = subtrans.apply_transformation(struct) # REmove some ordered sites to break symmetry. removetrans = RemoveSitesTransformation([4, 7]) s = removetrans.apply_transformation(s) adaptor = EnumlibAdaptor(s, 1, 1, enum_precision_parameter=0.01) adaptor.run() structures = adaptor.structures self.assertEqual(len(structures), 4) struct = Structure([[3, 0, 0], [0, 3, 0], [0, 0, 3]], [{"Si": 0.5}] * 2, [[0, 0, 0], [0.5, 0.5, 0.5]]) adaptor = EnumlibAdaptor(struct, 1, 3, enum_precision_parameter=0.01) adaptor.run() structures = adaptor.structures self.assertEqual(len(structures), 10) struct = Structure.from_file(os.path.join(test_dir, "EnumerateTest.json")) adaptor = EnumlibAdaptor(struct, 1, 1) adaptor.run() structures = adaptor.structures self.assertEqual(len(structures), 2)
def setUp(self): # trivial example, simple square lattice for testing structure = Structure(Lattice.tetragonal(5.0, 50.0), ['H'], [[0, 0, 0]]) self.square_sg = StructureGraph.with_empty_graph(structure, edge_weight_name="", edge_weight_units="") self.square_sg.add_edge(0, 0, from_jimage=(0, 0, 0), to_jimage=(1, 0, 0)) self.square_sg.add_edge(0, 0, from_jimage=(0, 0, 0), to_jimage=(-1, 0, 0)) self.square_sg.add_edge(0, 0, from_jimage=(0, 0, 0), to_jimage=(0, 1, 0)) self.square_sg.add_edge(0, 0, from_jimage=(0, 0, 0), to_jimage=(0, -1, 0)) # body-centered square lattice for testing structure = Structure(Lattice.tetragonal(5.0, 50.0), ['H', 'He'], [[0, 0, 0], [0.5, 0.5, 0.5]]) self.bc_square_sg = StructureGraph.with_empty_graph(structure, edge_weight_name="", edge_weight_units="") self.bc_square_sg.add_edge(0, 0, from_jimage=(0, 0, 0), to_jimage=(1, 0, 0)) self.bc_square_sg.add_edge(0, 0, from_jimage=(0, 0, 0), to_jimage=(-1, 0, 0)) self.bc_square_sg.add_edge(0, 0, from_jimage=(0, 0, 0), to_jimage=(0, 1, 0)) self.bc_square_sg.add_edge(0, 0, from_jimage=(0, 0, 0), to_jimage=(0, -1, 0)) self.bc_square_sg.add_edge(0, 1, from_jimage=(0, 0, 0), to_jimage=(0, 0, 0)) self.bc_square_sg.add_edge(0, 1, from_jimage=(0, 0, 0), to_jimage=(-1, 0, 0)) self.bc_square_sg.add_edge(0, 1, from_jimage=(0, 0, 0), to_jimage=(-1, -1, 0)) self.bc_square_sg.add_edge(0, 1, from_jimage=(0, 0, 0), to_jimage=(0, -1, 0)) # body-centered square lattice for testing # directions reversed, should be equivalent to as bc_square structure = Structure(Lattice.tetragonal(5.0, 50.0), ['H', 'He'], [[0, 0, 0], [0.5, 0.5, 0.5]]) self.bc_square_sg_r = StructureGraph.with_empty_graph(structure, edge_weight_name="", edge_weight_units="") self.bc_square_sg_r.add_edge(0, 0, from_jimage=(0, 0, 0), to_jimage=(1, 0, 0)) self.bc_square_sg_r.add_edge(0, 0, from_jimage=(0, 0, 0), to_jimage=(-1, 0, 0)) self.bc_square_sg_r.add_edge(0, 0, from_jimage=(0, 0, 0), to_jimage=(0, 1, 0)) self.bc_square_sg_r.add_edge(0, 0, from_jimage=(0, 0, 0), to_jimage=(0, -1, 0)) self.bc_square_sg_r.add_edge(0, 1, from_jimage=(0, 0, 0), to_jimage=(0, 0, 0)) self.bc_square_sg_r.add_edge(1, 0, from_jimage=(-1, 0, 0), to_jimage=(0, 0, 0)) self.bc_square_sg_r.add_edge(1, 0, from_jimage=(-1, -1, 0), to_jimage=(0, 0, 0)) self.bc_square_sg_r.add_edge(1, 0, from_jimage=(0, -1, 0), to_jimage=(0, 0, 0)) # MoS2 example, structure graph obtained from critic2 # (not ground state, from mp-1023924, single layer) stdout_file = os.path.join(os.path.dirname(__file__), "..", "..", "..", 'test_files/critic2/MoS2_critic2_stdout.txt') with open(stdout_file, 'r') as f: reference_stdout = f.read() self.structure = Structure.from_file(os.path.join(os.path.dirname(__file__), "..", "..", "..", 'test_files/critic2/MoS2.cif')) c2o = Critic2Output(self.structure, reference_stdout) self.mos2_sg = c2o.structure_graph(edge_weight="bond_length", edge_weight_units="Å") latt = Lattice.cubic(4.17) species = ["Ni", "O"] coords = [[0, 0, 0], [0.5, 0.5, 0.5]] self.NiO = Structure.from_spacegroup(225, latt, species, coords).get_primitive_structure()
def setUpClass(cls): cls.structure = Structure.from_file(os.path.join(module_dir, "reference_files", "Co2O2.cif")) cls.user_tag_settings = {"RPATH": -1, "SCF": "7 0 30 0.2 3", "FMS": "9 0", "LDOS": "-30.0 30.0 0.1", "RECIPROCAL":"", "EDGE": "L1", "COREHOLE": "RPA"} # 3rd site cls.absorbing_atom = 2 cls.edge = "L1" cls.nkpts = 1000 cls.scratch_dir = os.path.join(module_dir, "scratch")
def test_mix(self): structures = [self.get_structure("Li2O"), self.get_structure("Li2O2"), self.get_structure("LiFePO4")] for fname in ["POSCAR.Li2O", "POSCAR.LiFePO4"]: structures.append(Structure.from_file(os.path.join(test_dir, fname))) sm = StructureMatcher(comparator=ElementComparator()) groups = sm.group_structures(structures) for g in groups: formula = g[0].composition.reduced_formula if formula in ["Li2O", "LiFePO4"]: self.assertEqual(len(g), 2) else: self.assertEqual(len(g), 1)
def parse_symmetry(args): tolerance = float(args.tolerance[0]) for filename in args.filenames: s = Structure.from_file(filename) if args.spacegroup: finder = SpacegroupAnalyzer(s, tolerance) dataset = finder.get_symmetry_dataset() print(filename) print("Spacegroup : {}".format(dataset["international"])) print("Int number : {}".format(dataset["number"])) print("Hall symbol : {}".format(dataset["hall"])) print()
def setUpClass(cls): # CoO cls.structure = Structure.from_file(os.path.join(module_dir, "reference_files", "Co2O2.cif")) #PymatgenTest.get_mp_structure("mp-715460") cls.user_tag_settings = {"RPATH": -1, "SCF": "7 0 30 0.2 3", "FMS": "9 0", "LDOS": "-30.0 30.0 0.1", "RECIPROCAL": "", "EDGE": "K"} # 3rd site cls.absorbing_atom = 2 cls.edge = "K" cls.nkpts = 1000 cls.scratch_dir = os.path.join(module_dir, "scratch")
def setUp(self): super(TestEELSWorkflow, self).setUp() self.structure = Structure.from_file(os.path.join(module_dir, "..", "..", "test_files", "Co2O2.cif")) self.user_tag_settings = {"RPATH": -1, "SCF": "7 0 30 0.2 3", "FMS": "9 0", "LDOS": "-30.0 30.0 0.1", "RECIPROCAL":"", "EDGE": "L1", "COREHOLE": "RPA"} # 3rd site self.absorbing_atom = 2 self.edge = "L1" self.nkpts = 1000
def test_probability(self): traj_file = os.path.join(tests_dir, "cNa3PS4_trajectories.npy") struc_file = os.path.join(tests_dir, "cNa3PS4.cif") trajectories = np.load(traj_file) structure = Structure.from_file(struc_file, False) #ProbabilityDensityAnalysis object pda = ProbabilityDensityAnalysis(structure, trajectories, interval=0.5) dV = pda.structure.lattice.volume / pda.lens[0] / pda.lens[1] / pda.lens[2] Pr_tot = np.sum(pda.Pr) * dV self.assertAlmostEqual(pda.Pr.max(), 0.030735573102, 12) self.assertAlmostEqual(pda.Pr.min(), 0.0, 12) self.assertAlmostEqual(Pr_tot, 1.0, 12)
def get_convergence_data(jfile, params=('ENCUT', 'KPOINTS')): """ returns data dict in the following format {'Al': {'ENCUT': [ [500,1.232], [600,0.8798] ], 'KPOINTS':[ [], [] ] }, 'W': ... } Note: processes only INCAR parmaters and KPOINTS """ cutoff_jobs = jobs_from_file(jfile) data = {} for j in cutoff_jobs: jdir = os.path.join(j.parent_job_dir, j.job_dir) poscar_file = os.path.join(jdir, 'POSCAR') struct_m = Structure.from_file(poscar_file) species = ''.join([tos.symbol for tos in struct_m.types_of_specie]) if data.get(species): for p in params: if j.vis.incar.get(p): data[species][p].append( [j.vis.incar[p], j.final_energy / len(struct_m)]) elif p == 'KPOINTS': data[species]['KPOINTS'].append( [j.vis.kpoints.kpts, j.final_energy / len(struct_m)]) else: logger.warn( 'dont know how to parse the parameter {}'.format(p)) else: data[species] = {} for p in params: data[species][p] = [] data[species][p] = [] return data
def test_from_seed(self): from pymatgen import Lattice, Structure coords = [[0, 0, 0], [0.75, 0.5, 0.75]] lattice = Lattice.from_parameters(a=3.84, b=3.84, c=3.84, alpha=120, beta=90, gamma=60) struct = Structure(lattice, ["Si", "C"], coords) s1 = pyxtal() s1.from_seed(struct) s2 = s1.subgroup_once(eps=0) pmg_s1 = s1.to_pymatgen() pmg_s2 = s2.to_pymatgen() self.assertTrue(sm.StructureMatcher().fit(pmg_s1, pmg_s2)) pmg_s1 = Structure.from_file(cif_path + "B28.vasp") struc = pyxtal() struc.from_seed(seed=cif_path + "B28.vasp") pmg_s2 = struc.to_pymatgen() self.assertTrue(sm.StructureMatcher().fit(pmg_s1, pmg_s2)) permutation = {"B": "C"} struc.subgroup_once(0.01, None, permutation, max_cell=2)
def make_super_cell_poscar(jdata): out_dir = jdata['out_dir'] super_cell = jdata['super_cell'] path_sc = os.path.join(out_dir, global_dirname_02) create_path(path_sc) from_poscar_path = jdata['from_poscar_path'] assert (os.path.isfile(from_poscar_path) ), "file %s should exists" % from_poscar_path from_file = os.path.join(path_sc, 'POSCAR.copied') shutil.copy2(from_poscar_path, from_file) to_path = path_sc to_file = os.path.join(to_path, 'POSCAR') #minor bug for element symbol behind the coordinates from_struct = Structure.from_file(from_file) from_struct.make_supercell(super_cell) from_struct.to('poscar', to_file) # make system dir (copy) lines = open(to_file, 'r').read().split('\n') natoms_str = lines[6] natoms_list = [int(ii) for ii in natoms_str.split()] dlog.info(natoms_list) comb_name = "sys-" for idx, ii in enumerate(natoms_list): comb_name += "%04d" % ii if idx != len(natoms_list) - 1: comb_name += "-" path_work = os.path.join(path_sc, comb_name) create_path(path_work) cwd = os.getcwd() to_file = os.path.abspath(to_file) os.chdir(path_work) os.symlink(os.path.relpath(to_file), 'POSCAR') os.chdir(cwd)
def graph_from_file(filename, rcut, elements): """ Takes a pymatgen compatible file, an converts it to a graph object Args: - filename (str): name of file to set up graph from - rcut (float): cut-off radius node-node connections in forming clusters - elements ([str,str,.....]): list of elements to include in setting up graph Returns: - graph (Graph): graph object for structure """ clusters = clusters_from_file(filename=filename, rcut=rcut, elements=elements) structure = Structure.from_file(filename) all_elements = set([species for species in structure.symbol_set]) remove_elements = [x for x in all_elements if x not in elements] structure.remove_species(remove_elements) graph = Graph(clusters=clusters, structure=structure) return graph
def setUpClass(cls): cls.Cu_prim = Structure.from_file( os.path.join(test_dir, "Cu_mp-30_primitive.cif")) cls.GB_Cu_prim = GBGenerator(cls.Cu_prim) cls.Cu_conv = Structure.from_file( os.path.join(test_dir, "Cu_mp-30_conventional_standard.cif")) cls.GB_Cu_conv = GBGenerator(cls.Cu_conv) cls.Be = Structure.from_file( os.path.join(test_dir, "Be_mp-87_conventional_standard.cif")) cls.GB_Be = GBGenerator(cls.Be) cls.Pa = Structure.from_file( os.path.join(test_dir, "Pa_mp-62_conventional_standard.cif")) cls.GB_Pa = GBGenerator(cls.Pa) cls.Br = Structure.from_file( os.path.join(test_dir, "Br_mp-23154_conventional_standard.cif")) cls.GB_Br = GBGenerator(cls.Br) cls.Bi = Structure.from_file( os.path.join(test_dir, "Bi_mp-23152_primitive.cif")) cls.GB_Bi = GBGenerator(cls.Bi)
def test_postfeffset(self): self.mp_xanes.write_input(os.path.join(".", "xanes_3")) feff_dict_input = FEFFDictSet.from_directory( os.path.join(".", "xanes_3")) self.assertTrue(feff_dict_input.tags == Tags.from_file( os.path.join(".", "xanes_3/feff.inp"))) self.assertTrue( str(feff_dict_input.header()) == str( Header.from_file(os.path.join(".", "xanes_3/HEADER")))) feff_dict_input.write_input("xanes_3_regen") origin_tags = Tags.from_file(os.path.join(".", "xanes_3/PARAMETERS")) output_tags = Tags.from_file( os.path.join(".", "xanes_3_regen/PARAMETERS")) origin_mole = Atoms.cluster_from_file( os.path.join(".", "xanes_3/feff.inp")) output_mole = Atoms.cluster_from_file( os.path.join(".", "xanes_3_regen/feff.inp")) original_mole_dist = np.array( origin_mole.distance_matrix[0, :]).astype(np.float64) output_mole_dist = np.array(output_mole.distance_matrix[0, :]).astype( np.float64) original_mole_shell = [x.species_string for x in origin_mole] output_mole_shell = [x.species_string for x in output_mole] self.assertTrue(np.allclose(original_mole_dist, output_mole_dist)) self.assertTrue(origin_tags == output_tags) self.assertTrue(original_mole_shell == output_mole_shell) shutil.rmtree(os.path.join(".", "xanes_3")) shutil.rmtree(os.path.join(".", "xanes_3_regen")) reci_mp_xanes = MPXANESSet(self.absorbing_atom, self.structure, user_tag_settings={"RECIPROCAL": ""}) reci_mp_xanes.write_input("xanes_reci") feff_reci_input = FEFFDictSet.from_directory( os.path.join(".", "xanes_reci")) self.assertTrue("RECIPROCAL" in feff_reci_input.tags) feff_reci_input.write_input("Dup_reci") self.assertTrue(os.path.exists(os.path.join(".", "Dup_reci", "HEADER"))) self.assertTrue( os.path.exists(os.path.join(".", "Dup_reci", "feff.inp"))) self.assertTrue( os.path.exists(os.path.join(".", "Dup_reci", "PARAMETERS"))) self.assertFalse(os.path.exists(os.path.join(".", "Dup_reci", "ATOMS"))) self.assertFalse( os.path.exists(os.path.join(".", "Dup_reci", "POTENTIALS"))) tags_original = Tags.from_file(os.path.join(".", "xanes_reci/feff.inp")) tags_output = Tags.from_file(os.path.join(".", "Dup_reci/feff.inp")) self.assertTrue(tags_original == tags_output) stru_orig = Structure.from_file( os.path.join(".", "xanes_reci/Co2O2.cif")) stru_reci = Structure.from_file(os.path.join(".", "Dup_reci/Co2O2.cif")) self.assertTrue(stru_orig.__eq__(stru_reci)) shutil.rmtree(os.path.join(".", "Dup_reci")) shutil.rmtree(os.path.join(".", "xanes_reci"))
import numpy as np from pymatgen import Structure from fireworks import LaunchPad, Workflow from atomate.vasp.powerups import add_modify_incar, add_tags from atomate.vasp.workflows.base.ferroelectric import get_wf_ferroelectric comp = 'LaSnO2N' np_struct = Structure.from_file(comp + '_hex_30.vasp') p_struct = Structure.from_file(comp + '_dist.vasp') wf = get_wf_ferroelectric(p_struct, np_struct, vasp_cmd='ibrun tacc_affinity vasp_std', add_analysis_task=True, tags=[comp], db_file='/scratch/04391/tg836903/ilmenites/db.json') wf = add_modify_incar(wf, modify_incar_params={ 'incar_update': { 'Algo': 'Normal', 'EDIFF': 0.00001, 'NEDOS': 3000 } }) lpad = LaunchPad.auto_load() # loads this based on the FireWorks configuration lpad.add_wf(wf)
def test_symmetrized(self): filepath = self.TEST_FILES_DIR / 'POSCAR' poscar = Poscar.from_file(filepath, check_for_POTCAR=False) writer = CifWriter(poscar.structure, symprec=0.1) ans = """# generated using pymatgen data_FePO4 _symmetry_space_group_name_H-M Pnma _cell_length_a 10.41176687 _cell_length_b 6.06717188 _cell_length_c 4.75948954 _cell_angle_alpha 90.00000000 _cell_angle_beta 90.00000000 _cell_angle_gamma 90.00000000 _symmetry_Int_Tables_number 62 _chemical_formula_structural FePO4 _chemical_formula_sum 'Fe4 P4 O16' _cell_volume 300.65685512 _cell_formula_units_Z 4 loop_ _symmetry_equiv_pos_site_id _symmetry_equiv_pos_as_xyz 1 'x, y, z' 2 '-x, -y, -z' 3 '-x+1/2, -y, z+1/2' 4 'x+1/2, y, -z+1/2' 5 'x+1/2, -y+1/2, -z+1/2' 6 '-x+1/2, y+1/2, z+1/2' 7 '-x, y+1/2, -z' 8 'x, -y+1/2, z' loop_ _atom_site_type_symbol _atom_site_label _atom_site_symmetry_multiplicity _atom_site_fract_x _atom_site_fract_y _atom_site_fract_z _atom_site_occupancy Fe Fe1 4 0.218728 0.250000 0.525133 1 P P2 4 0.094613 0.750000 0.581757 1 O O3 8 0.165710 0.546072 0.714616 1 O O4 4 0.043372 0.250000 0.292862 1 O O5 4 0.096642 0.750000 0.258680 1""" cif = CifParser.from_string(str(writer)) m = StructureMatcher() self.assertTrue(m.fit(cif.get_structures()[0], poscar.structure)) # for l1, l2 in zip(str(writer).split("\n"), ans.split("\n")): # self.assertEqual(l1.strip(), l2.strip()) ans = """# generated using pymatgen data_LiFePO4 _symmetry_space_group_name_H-M Pnma _cell_length_a 10.41037000 _cell_length_b 6.06577000 _cell_length_c 4.74480000 _cell_angle_alpha 90.00000000 _cell_angle_beta 90.00000000 _cell_angle_gamma 90.00000000 _symmetry_Int_Tables_number 62 _chemical_formula_structural LiFePO4 _chemical_formula_sum 'Li4 Fe4 P4 O16' _cell_volume 299.619458734 _cell_formula_units_Z 4 loop_ _symmetry_equiv_pos_site_id _symmetry_equiv_pos_as_xyz 1 'x, y, z' 2 '-x, -y, -z' 3 '-x+1/2, -y, z+1/2' 4 'x+1/2, y, -z+1/2' 5 'x+1/2, -y+1/2, -z+1/2' 6 '-x+1/2, y+1/2, z+1/2' 7 '-x, y+1/2, -z' 8 'x, -y+1/2, z' loop_ _atom_site_type_symbol _atom_site_label _atom_site_symmetry_multiplicity _atom_site_fract_x _atom_site_fract_y _atom_site_fract_z _atom_site_occupancy Li Li1 4 0.000000 0.000000 0.000000 1.0 Fe Fe2 4 0.218845 0.750000 0.474910 1.0 P P3 4 0.094445 0.250000 0.417920 1.0 O O4 8 0.165815 0.044060 0.286540 1.0 O O5 4 0.043155 0.750000 0.708460 1.0 O O6 4 0.096215 0.250000 0.741480 1.0 """ s = Structure.from_file(self.TEST_FILES_DIR / 'LiFePO4.cif') writer = CifWriter(s, symprec=0.1) s2 = CifParser.from_string(str(writer)).get_structures()[0] self.assertTrue(m.fit(s, s2)) s = self.get_structure("Li2O") writer = CifWriter(s, symprec=0.1) s2 = CifParser.from_string(str(writer)).get_structures()[0] self.assertTrue(m.fit(s, s2)) # test angle tolerance. s = Structure.from_file(self.TEST_FILES_DIR / 'LiFePO4.cif') writer = CifWriter(s, symprec=0.1, angle_tolerance=0) d = list(writer.ciffile.data.values())[0] self.assertEqual(d["_symmetry_Int_Tables_number"], 14) s = Structure.from_file(self.TEST_FILES_DIR / 'LiFePO4.cif') writer = CifWriter(s, symprec=0.1, angle_tolerance=2) d = list(writer.ciffile.data.values())[0] self.assertEqual(d["_symmetry_Int_Tables_number"], 62)
d[lable.name] = str.composition.get(lable) temp = json.dumps(d) result["unitcellformula"] = json.JSONDecoder().decode(temp) return result # Supercell, Substitution, Extract, Download condition = str(sys.argv[1]) # POSCAR file path file_path = str(sys.argv[2]) #poscar = Poscar.from_file(file_path) #structure = poscar.structure structure = Structure.from_file(file_path) # POSCAR Output path poscarOutputPath = sys.argv[3] # Number of parameters (Whether it is Substitution or Remove) num_parameter = len(sys.argv) # devsky adds time to file name now = datetime.datetime.now() nowDatetime = now.strftime('%Y%m%d%H%M%S%f') # jaesung adds error handling code flag = True if condition == "supercell":
def test_left_handed_lattice(self): """Ensure Left handed lattices are accepted""" sm = StructureMatcher() s = Structure.from_file(os.path.join(test_dir, "Li3GaPCO7.json")) self.assertTrue(sm.fit(s, s))
# -*- coding: utf-8 -*- """ Created on Mon Jun 15 11:20:45 2020 @author: Tao.Fan """ import numpy as np from pymatgen import Structure from pymatgen.symmetry.analyzer import SpacegroupAnalyzer from aicon.myworkflow import wf_phonon_conductivity from fireworks import LaunchPad from aicon.tools import Generate_kpoints if __name__ == '__main__': struct = Structure.from_file("POSCAR") finder = SpacegroupAnalyzer(struct) struct=finder.get_conventional_standard_structure() custom_settings_relax = {"SYSTEM": "Si", "ENCUT": 600, "ISTART": 0, "ICHARG": 2, "ISMEAR": -5, "SIGMA": 0.02, "NSW": 60, "IBRION": 2, "ISIF": 3, "POTIM": 0.05, "EDIFF": 1E-7, "EDIFFG": -1E-3, "PREC": "Accurate", "NPAR": 2}
def setUp(self): struct = Structure.from_file( f"{dir_path}/full_path_files/MnO2_full_Li.vasp") self.fpm = FullPathMapper(structure=struct, migrating_specie='Li', max_path_length=4)
def get_xrd_plot(args): s = Structure.from_file(args.xrd_structure_file) c = XRDCalculator() return c.get_plot(s)
def get_cif(filename, tolerance=0.1): struc = Structure.from_file(filename) cif = CifWriter(struc, symprec=tolerance) cif.write_file(filename + '.cif')
def test_not_matching_first(self): structure = Structure.from_file( f"{dir_path}/pathfinder_files/Li6MnO4.json") fpm_lmo = FullPathMapper(structure, "Li", max_path_length=4) for u, v, d in fpm_lmo.s_graph.graph.edges(data=True): self.assertIn(d["hop"].eindex, {0, 1})
continue tmp = float(l[30:45]) + 19.433700000000 newline = l[:30] + f'{tmp}' + l[45:] if n % 202 == 91 or n % 202 == 168: new.write(l.replace('O', 'F')) new.write(newline.replace('O', 'F')) elif n % 202 == 46 or n % 202 == 47: new.write(l.replace('La', 'Fe')) new.write(newline.replace('La', 'Fe')) else: new.write(l) new.write(newline) # tmp = float(l[30:45]) + 15 # newline = l[:30] + f'{tmp}' + l[45:] # %% tmp = float(l[30:45]) + 19.433700000000 newline = l[:30] + f'{tmp}' + l[45:] # %% from pymatgen import Structure from phonopy import Phonopy p = Phonopy() p.generate_displacements(distance=) s = Structure.from_file() s.tra
def vasp_set(args): if args.print_json: vis = ViseInputSet.load_json(args.print_json) print(vis) return flags = [str(s) for s in list(Element)] ldauu = list2dict(args.ldauu, flags) ldaul = list2dict(args.ldaul, flags) potcar_set = potcar_str2dict(args.potcar_set) task = Task.from_string(args.task) xc = Xc.from_string(args.xc) base_kwargs = {"kpt_density": args.kpt_density, "standardize_structure": args.standardize, "ldauu": ldauu, "ldaul": ldaul} flags = list(ViseInputSet.ALL_OPTIONS.keys()) base_kwargs.update(list2dict(args.vise_opts, flags)) flags = list(chain.from_iterable(incar_flags.values())) base_user_incar_settings = list2dict(args.user_incar_setting, flags) original_dir = os.getcwd() dirs = args.dirs or ["."] for d in dirs: os.chdir(os.path.join(original_dir, d)) logger.info(f"Constructing vasp set in {d}") user_incar_settings = deepcopy(base_user_incar_settings) kwargs = deepcopy(base_kwargs) if args.prior_info: if os.path.exists("prior_info.json"): prior_info = PriorInfo.load_json("prior_info.json") kwargs["band_gap"] = prior_info["band_gap"] kwargs["is_magnetization"] = \ abs(prior_info["total_magnetization"]) > 0.1 if args.prev_dir: files = {"CHGCAR": "C", "WAVECAR": "M", "WAVEDER": "M"} input_set = ViseInputSet.from_prev_calc(args.prev_dir, task=task, xc=xc, charge=args.charge, files_to_transfer=files, **kwargs) else: s = Structure.from_file(args.poscar) input_set = \ ViseInputSet.make_input(structure=s, task=task, xc=xc, charge=args.charge, user_incar_settings=user_incar_settings, override_potcar_set=potcar_set, **kwargs) input_set.write_input(".") os.chdir(original_dir)
from pymatgen import Structure from pymatgen.io.vasp.sets import MPRelaxSet s = Structure.from_file("ICSD_182730_Si.cif", primitive=True) custom_settings = {"NELMIN": 5} # user custom incar settings relax = MPRelaxSet(s, user_incar_settings=custom_settings) relax.write_input("Si-relax")
def test_init(self): with warnings.catch_warnings(): warnings.simplefilter("ignore") struct = self.get_structure("LiFePO4") subtrans = SubstitutionTransformation({'Li': {'Li': 0.5}}) adaptor = EnumlibAdaptor(subtrans.apply_transformation(struct), 1, 2) adaptor.run() structures = adaptor.structures self.assertEqual(len(structures), 86) for s in structures: self.assertAlmostEqual( s.composition.get_atomic_fraction(Element("Li")), 0.5 / 6.5) adaptor = EnumlibAdaptor(subtrans.apply_transformation(struct), 1, 2, refine_structure=True) adaptor.run() structures = adaptor.structures self.assertEqual(len(structures), 52) subtrans = SubstitutionTransformation({'Li': {'Li': 0.25}}) adaptor = EnumlibAdaptor(subtrans.apply_transformation(struct), 1, 1, refine_structure=True) adaptor.run() structures = adaptor.structures self.assertEqual(len(structures), 1) for s in structures: self.assertAlmostEqual( s.composition.get_atomic_fraction(Element("Li")), 0.25 / 6.25) # Make sure it works for completely disordered structures. struct = Structure([[10, 0, 0], [0, 10, 0], [0, 0, 10]], [{ 'Fe': 0.5 }], [[0, 0, 0]]) adaptor = EnumlibAdaptor(struct, 1, 2) adaptor.run() self.assertEqual(len(adaptor.structures), 3) # Make sure it works properly when symmetry is broken by ordered sites. struct = self.get_structure("LiFePO4") subtrans = SubstitutionTransformation({'Li': {'Li': 0.25}}) s = subtrans.apply_transformation(struct) # REmove some ordered sites to break symmetry. removetrans = RemoveSitesTransformation([4, 7]) s = removetrans.apply_transformation(s) adaptor = EnumlibAdaptor(s, 1, 1, enum_precision_parameter=0.01) adaptor.run() structures = adaptor.structures self.assertEqual(len(structures), 4) struct = Structure([[3, 0, 0], [0, 3, 0], [0, 0, 3]], [{ "Si": 0.5 }] * 2, [[0, 0, 0], [0.5, 0.5, 0.5]]) adaptor = EnumlibAdaptor(struct, 1, 3, enum_precision_parameter=0.01) adaptor.run() structures = adaptor.structures self.assertEqual(len(structures), 10) struct = Structure.from_file( os.path.join(test_dir, "EnumerateTest.json")) adaptor = EnumlibAdaptor(struct, 1, 1) adaptor.run() structures = adaptor.structures self.assertEqual(len(structures), 2)
def test_symmetrized(self): filepath = os.path.join(test_dir, 'POSCAR') poscar = Poscar.from_file(filepath, check_for_POTCAR=False) writer = CifWriter(poscar.structure, symprec=0.1) ans = """# generated using pymatgen data_FePO4 _symmetry_space_group_name_H-M Pnma _cell_length_a 10.41176687 _cell_length_b 6.06717188 _cell_length_c 4.75948954 _cell_angle_alpha 90.00000000 _cell_angle_beta 90.00000000 _cell_angle_gamma 90.00000000 _symmetry_Int_Tables_number 62 _chemical_formula_structural FePO4 _chemical_formula_sum 'Fe4 P4 O16' _cell_volume 300.65685512 _cell_formula_units_Z 4 loop_ _symmetry_equiv_pos_site_id _symmetry_equiv_pos_as_xyz 1 'x, y, z' 2 '-x, -y, -z' 3 '-x+1/2, -y, z+1/2' 4 'x+1/2, y, -z+1/2' 5 'x+1/2, -y+1/2, -z+1/2' 6 '-x+1/2, y+1/2, z+1/2' 7 '-x, y+1/2, -z' 8 'x, -y+1/2, z' loop_ _atom_site_type_symbol _atom_site_label _atom_site_symmetry_multiplicity _atom_site_fract_x _atom_site_fract_y _atom_site_fract_z _atom_site_occupancy Fe Fe1 4 0.218728 0.250000 0.525133 1 P P2 4 0.094613 0.750000 0.581757 1 O O3 8 0.165710 0.546072 0.714616 1 O O4 4 0.043372 0.250000 0.292862 1 O O5 4 0.096642 0.750000 0.258680 1""" for l1, l2 in zip(str(writer).split("\n"), ans.split("\n")): self.assertEqual(l1.strip(), l2.strip()) ans = """# generated using pymatgen data_LiFePO4 _symmetry_space_group_name_H-M Pnma _cell_length_a 10.41037000 _cell_length_b 6.06577000 _cell_length_c 4.74480000 _cell_angle_alpha 90.00000000 _cell_angle_beta 90.00000000 _cell_angle_gamma 90.00000000 _symmetry_Int_Tables_number 62 _chemical_formula_structural LiFePO4 _chemical_formula_sum 'Li4 Fe4 P4 O16' _cell_volume 299.619458734 _cell_formula_units_Z 4 loop_ _symmetry_equiv_pos_site_id _symmetry_equiv_pos_as_xyz 1 'x, y, z' 2 '-x, -y, -z' 3 '-x+1/2, -y, z+1/2' 4 'x+1/2, y, -z+1/2' 5 'x+1/2, -y+1/2, -z+1/2' 6 '-x+1/2, y+1/2, z+1/2' 7 '-x, y+1/2, -z' 8 'x, -y+1/2, z' loop_ _atom_site_type_symbol _atom_site_label _atom_site_symmetry_multiplicity _atom_site_fract_x _atom_site_fract_y _atom_site_fract_z _atom_site_occupancy Li Li1 4 0.000000 0.000000 0.000000 1.0 Fe Fe2 4 0.218845 0.750000 0.474910 1.0 P P3 4 0.094445 0.250000 0.417920 1.0 O O4 8 0.165815 0.044060 0.286540 1.0 O O5 4 0.043155 0.750000 0.708460 1.0 O O6 4 0.096215 0.250000 0.741480 1.0 """ s = Structure.from_file(os.path.join(test_dir, 'LiFePO4.cif')) writer = CifWriter(s, symprec=0.1) s2 = CifParser.from_string(str(writer)).get_structures()[0] m = StructureMatcher() self.assertTrue(m.fit(s, s2)) s = self.get_structure("Li2O") writer = CifWriter(s, symprec=0.1) ans = """# generated using pymatgen data_Li2O _symmetry_space_group_name_H-M Fm-3m _cell_length_a 4.65884171 _cell_length_b 4.65884171 _cell_length_c 4.65884171 _cell_angle_alpha 90.00000000 _cell_angle_beta 90.00000000 _cell_angle_gamma 90.00000000 _symmetry_Int_Tables_number 225 _chemical_formula_structural Li2O _chemical_formula_sum 'Li8 O4' _cell_volume 101.11925577 _cell_formula_units_Z 4 loop_ _symmetry_equiv_pos_site_id _symmetry_equiv_pos_as_xyz 1 'x, y, z' 2 '-x, -y, -z' 3 'z, y, -x' 4 '-z, -y, x' 5 '-x, y, -z' 6 'x, -y, z' 7 '-z, y, x' 8 'z, -y, -x' 9 'x, -y, -z' 10 '-x, y, z' 11 'z, -y, x' 12 '-z, y, -x' 13 '-x, -y, z' 14 'x, y, -z' 15 '-z, -y, -x' 16 'z, y, x' 17 'y, -z, -x' 18 '-y, z, x' 19 'y, x, -z' 20 '-y, -x, z' 21 'y, z, x' 22 '-y, -z, -x' 23 'y, -x, z' 24 '-y, x, -z' 25 '-y, z, -x' 26 'y, -z, x' 27 '-y, -x, -z' 28 'y, x, z' 29 '-y, -z, x' 30 'y, z, -x' 31 '-y, x, z' 32 'y, -x, -z' 33 '-z, x, -y' 34 'z, -x, y' 35 'x, z, -y' 36 '-x, -z, y' 37 'z, -x, -y' 38 '-z, x, y' 39 '-x, -z, -y' 40 'x, z, y' 41 'z, x, y' 42 '-z, -x, -y' 43 '-x, z, y' 44 'x, -z, -y' 45 '-z, -x, y' 46 'z, x, -y' 47 'x, -z, y' 48 '-x, z, -y' 49 'x+1/2, y+1/2, z' 50 '-x+1/2, -y+1/2, -z' 51 'z+1/2, y+1/2, -x' 52 '-z+1/2, -y+1/2, x' 53 '-x+1/2, y+1/2, -z' 54 'x+1/2, -y+1/2, z' 55 '-z+1/2, y+1/2, x' 56 'z+1/2, -y+1/2, -x' 57 'x+1/2, -y+1/2, -z' 58 '-x+1/2, y+1/2, z' 59 'z+1/2, -y+1/2, x' 60 '-z+1/2, y+1/2, -x' 61 '-x+1/2, -y+1/2, z' 62 'x+1/2, y+1/2, -z' 63 '-z+1/2, -y+1/2, -x' 64 'z+1/2, y+1/2, x' 65 'y+1/2, -z+1/2, -x' 66 '-y+1/2, z+1/2, x' 67 'y+1/2, x+1/2, -z' 68 '-y+1/2, -x+1/2, z' 69 'y+1/2, z+1/2, x' 70 '-y+1/2, -z+1/2, -x' 71 'y+1/2, -x+1/2, z' 72 '-y+1/2, x+1/2, -z' 73 '-y+1/2, z+1/2, -x' 74 'y+1/2, -z+1/2, x' 75 '-y+1/2, -x+1/2, -z' 76 'y+1/2, x+1/2, z' 77 '-y+1/2, -z+1/2, x' 78 'y+1/2, z+1/2, -x' 79 '-y+1/2, x+1/2, z' 80 'y+1/2, -x+1/2, -z' 81 '-z+1/2, x+1/2, -y' 82 'z+1/2, -x+1/2, y' 83 'x+1/2, z+1/2, -y' 84 '-x+1/2, -z+1/2, y' 85 'z+1/2, -x+1/2, -y' 86 '-z+1/2, x+1/2, y' 87 '-x+1/2, -z+1/2, -y' 88 'x+1/2, z+1/2, y' 89 'z+1/2, x+1/2, y' 90 '-z+1/2, -x+1/2, -y' 91 '-x+1/2, z+1/2, y' 92 'x+1/2, -z+1/2, -y' 93 '-z+1/2, -x+1/2, y' 94 'z+1/2, x+1/2, -y' 95 'x+1/2, -z+1/2, y' 96 '-x+1/2, z+1/2, -y' 97 'x+1/2, y, z+1/2' 98 '-x+1/2, -y, -z+1/2' 99 'z+1/2, y, -x+1/2' 100 '-z+1/2, -y, x+1/2' 101 '-x+1/2, y, -z+1/2' 102 'x+1/2, -y, z+1/2' 103 '-z+1/2, y, x+1/2' 104 'z+1/2, -y, -x+1/2' 105 'x+1/2, -y, -z+1/2' 106 '-x+1/2, y, z+1/2' 107 'z+1/2, -y, x+1/2' 108 '-z+1/2, y, -x+1/2' 109 '-x+1/2, -y, z+1/2' 110 'x+1/2, y, -z+1/2' 111 '-z+1/2, -y, -x+1/2' 112 'z+1/2, y, x+1/2' 113 'y+1/2, -z, -x+1/2' 114 '-y+1/2, z, x+1/2' 115 'y+1/2, x, -z+1/2' 116 '-y+1/2, -x, z+1/2' 117 'y+1/2, z, x+1/2' 118 '-y+1/2, -z, -x+1/2' 119 'y+1/2, -x, z+1/2' 120 '-y+1/2, x, -z+1/2' 121 '-y+1/2, z, -x+1/2' 122 'y+1/2, -z, x+1/2' 123 '-y+1/2, -x, -z+1/2' 124 'y+1/2, x, z+1/2' 125 '-y+1/2, -z, x+1/2' 126 'y+1/2, z, -x+1/2' 127 '-y+1/2, x, z+1/2' 128 'y+1/2, -x, -z+1/2' 129 '-z+1/2, x, -y+1/2' 130 'z+1/2, -x, y+1/2' 131 'x+1/2, z, -y+1/2' 132 '-x+1/2, -z, y+1/2' 133 'z+1/2, -x, -y+1/2' 134 '-z+1/2, x, y+1/2' 135 '-x+1/2, -z, -y+1/2' 136 'x+1/2, z, y+1/2' 137 'z+1/2, x, y+1/2' 138 '-z+1/2, -x, -y+1/2' 139 '-x+1/2, z, y+1/2' 140 'x+1/2, -z, -y+1/2' 141 '-z+1/2, -x, y+1/2' 142 'z+1/2, x, -y+1/2' 143 'x+1/2, -z, y+1/2' 144 '-x+1/2, z, -y+1/2' 145 'x, y+1/2, z+1/2' 146 '-x, -y+1/2, -z+1/2' 147 'z, y+1/2, -x+1/2' 148 '-z, -y+1/2, x+1/2' 149 '-x, y+1/2, -z+1/2' 150 'x, -y+1/2, z+1/2' 151 '-z, y+1/2, x+1/2' 152 'z, -y+1/2, -x+1/2' 153 'x, -y+1/2, -z+1/2' 154 '-x, y+1/2, z+1/2' 155 'z, -y+1/2, x+1/2' 156 '-z, y+1/2, -x+1/2' 157 '-x, -y+1/2, z+1/2' 158 'x, y+1/2, -z+1/2' 159 '-z, -y+1/2, -x+1/2' 160 'z, y+1/2, x+1/2' 161 'y, -z+1/2, -x+1/2' 162 '-y, z+1/2, x+1/2' 163 'y, x+1/2, -z+1/2' 164 '-y, -x+1/2, z+1/2' 165 'y, z+1/2, x+1/2' 166 '-y, -z+1/2, -x+1/2' 167 'y, -x+1/2, z+1/2' 168 '-y, x+1/2, -z+1/2' 169 '-y, z+1/2, -x+1/2' 170 'y, -z+1/2, x+1/2' 171 '-y, -x+1/2, -z+1/2' 172 'y, x+1/2, z+1/2' 173 '-y, -z+1/2, x+1/2' 174 'y, z+1/2, -x+1/2' 175 '-y, x+1/2, z+1/2' 176 'y, -x+1/2, -z+1/2' 177 '-z, x+1/2, -y+1/2' 178 'z, -x+1/2, y+1/2' 179 'x, z+1/2, -y+1/2' 180 '-x, -z+1/2, y+1/2' 181 'z, -x+1/2, -y+1/2' 182 '-z, x+1/2, y+1/2' 183 '-x, -z+1/2, -y+1/2' 184 'x, z+1/2, y+1/2' 185 'z, x+1/2, y+1/2' 186 '-z, -x+1/2, -y+1/2' 187 '-x, z+1/2, y+1/2' 188 'x, -z+1/2, -y+1/2' 189 '-z, -x+1/2, y+1/2' 190 'z, x+1/2, -y+1/2' 191 'x, -z+1/2, y+1/2' 192 '-x, z+1/2, -y+1/2' loop_ _atom_type_symbol _atom_type_oxidation_number Li+ 1.0 O2- -2.0 loop_ _atom_site_type_symbol _atom_site_label _atom_site_symmetry_multiplicity _atom_site_fract_x _atom_site_fract_y _atom_site_fract_z _atom_site_occupancy Li+ Li1 8 0.250000 0.250000 0.250000 1 O2- O2 4 0.000000 0.000000 0.000000 1""" for l1, l2 in zip(str(writer).split("\n"), ans.split("\n")): self.assertEqual(l1.strip(), l2.strip())
def convert_fmt(args): if len(args.filenames) != 2: print("File format conversion takes in only two filenames.") s = Structure.from_file(args.filenames[0], primitive="prim" in args.filenames[1].lower()) s.to(filename=args.filenames[1])
def setUp(self): self.in_str = "2 5.5" st = Structure.from_file("POSCAR") self.system_1 = parse_sphere(self.in_str, st) self.system_2 = [1, 2, 4, 5]
import numpy as np sites_Na = [[55, 59, 64, 68], [51, 54, 60, 63], [56, 58, 65, 67], [52, 53, 62, 64], [57, 57, 67, 67]] directories = ["c5", "c4", "c3", "c2", "c1", "relax", "t1", "t2", "t3", "t4", "t5"] o_fig = o_file = 'NaObonds' all_dist_NaO = []# (strain,layers,atom,bond) for element in directories: """ This populates the distances array with all the Na-O bonds detected by the CrystalNN routine. The innermost index varies in size as each atom in sites_Na can have more or less neigbours. The second innermost index size is always 4 due to array symmetry reasons. It registers the number of Na atoms at a layer The third innermost index is 5. It is the number of layers in the slab. The first index registers the strain steps taken. """ input_struct = Structure.from_file( element+"/CONTCAR" ) ox_struct = BVAnalyzer().get_oxi_state_decorated_structure( input_struct ) dist_NaO = [] for layer, atom_list in enumerate( sites_Na ): layer_atoms = [] for atom in atom_list: atom_neigbors = CrystalNN( cation_anion=True ).get_nn( ox_struct, atom-1 ) distances = [] for neighbor in range( len( atom_neigbors ) ): distances.append( atom_neigbors[neighbor].distance( input_struct[atom-1] ) ) layer_atoms.append( distances ) dist_NaO.append( layer_atoms ) all_dist_NaO.append( dist_NaO ) avrg_bond = np.zeros( [len(all_dist_NaO), len(all_dist_NaO[0]), len(all_dist_NaO[0][0])] ) avrg_layer = np.zeros( [len(all_dist_NaO), len(all_dist_NaO[0])] )
def setUp(self): self.in_str = "0 0.5 |0.2 0.3| " st = Structure.from_file("POSCAR") self.system_1 = parse_range(self.in_str, st) self.system_2 = [4]
def test_defect_matching(self): # SETUP DEFECTS FOR TESTING # symmorphic defect test set s_struc = Structure.from_file(os.path.join( test_dir, "CsSnI3.cif")) # tetragonal CsSnI3 identical_Cs_vacs = [ Vacancy(s_struc, s_struc[0]), Vacancy(s_struc, s_struc[1]) ] identical_I_vacs_sublattice1 = [ Vacancy(s_struc, s_struc[4]), Vacancy(s_struc, s_struc[5]), Vacancy(s_struc, s_struc[8]), Vacancy(s_struc, s_struc[9]) ] # in plane halides identical_I_vacs_sublattice2 = [ Vacancy(s_struc, s_struc[6]), Vacancy(s_struc, s_struc[7]) ] # out of plane halides pdc = PointDefectComparator() # NOW TEST DEFECTS # test vacancy matching self.assertTrue( pdc.are_equal(identical_Cs_vacs[0], identical_Cs_vacs[0])) # trivial vacancy test self.assertTrue( pdc.are_equal( identical_Cs_vacs[0], identical_Cs_vacs[1])) # vacancies on same sublattice for i, j in itertools.combinations(range(4), 2): self.assertTrue( pdc.are_equal(identical_I_vacs_sublattice1[i], identical_I_vacs_sublattice1[j])) self.assertTrue( pdc.are_equal(identical_I_vacs_sublattice2[0], identical_I_vacs_sublattice2[1])) self.assertFalse( pdc.are_equal( identical_Cs_vacs[ 0], # both vacancies, but different specie types identical_I_vacs_sublattice1[0])) self.assertFalse( pdc.are_equal( identical_I_vacs_sublattice1[ 0], # same specie type, different sublattice identical_I_vacs_sublattice2[0])) # test substitutional matching sub_Cs_on_I_sublattice1_set1 = PeriodicSite( 'Cs', identical_I_vacs_sublattice1[0].site.frac_coords, s_struc.lattice) sub_Cs_on_I_sublattice1_set2 = PeriodicSite( 'Cs', identical_I_vacs_sublattice1[1].site.frac_coords, s_struc.lattice) sub_Cs_on_I_sublattice2 = PeriodicSite( 'Cs', identical_I_vacs_sublattice2[0].site.frac_coords, s_struc.lattice) sub_Rb_on_I_sublattice2 = PeriodicSite( 'Rb', identical_I_vacs_sublattice2[0].site.frac_coords, s_struc.lattice) self.assertTrue( pdc.are_equal( # trivial substitution test Substitution(s_struc, sub_Cs_on_I_sublattice1_set1), Substitution(s_struc, sub_Cs_on_I_sublattice1_set1))) self.assertTrue( pdc.are_equal( # same sublattice, different coords Substitution(s_struc, sub_Cs_on_I_sublattice1_set1), Substitution(s_struc, sub_Cs_on_I_sublattice1_set2))) self.assertFalse( pdc.are_equal( # different subs (wrong specie) Substitution(s_struc, sub_Cs_on_I_sublattice2), Substitution(s_struc, sub_Rb_on_I_sublattice2))) self.assertFalse( pdc.are_equal( # different subs (wrong sublattice) Substitution(s_struc, sub_Cs_on_I_sublattice1_set1), Substitution(s_struc, sub_Cs_on_I_sublattice2))) # test symmorphic interstitial matching # (using set generated from Voronoi generator, with same sublattice given by saturatated_interstitial_structure function) inter_H_sublattice1_set1 = PeriodicSite('H', [0., 0.75, 0.25], s_struc.lattice) inter_H_sublattice1_set2 = PeriodicSite('H', [0., 0.75, 0.75], s_struc.lattice) inter_H_sublattice2 = PeriodicSite( 'H', [0.57796112, 0.06923687, 0.56923687], s_struc.lattice) inter_H_sublattice3 = PeriodicSite('H', [0.25, 0.25, 0.54018268], s_struc.lattice) inter_He_sublattice3 = PeriodicSite('He', [0.25, 0.25, 0.54018268], s_struc.lattice) self.assertTrue( pdc.are_equal( # trivial interstitial test Interstitial(s_struc, inter_H_sublattice1_set1), Interstitial(s_struc, inter_H_sublattice1_set1))) self.assertTrue( pdc.are_equal( # same sublattice, different coords Interstitial(s_struc, inter_H_sublattice1_set1), Interstitial(s_struc, inter_H_sublattice1_set2))) self.assertFalse( pdc.are_equal( # different interstitials (wrong sublattice) Interstitial(s_struc, inter_H_sublattice1_set1), Interstitial(s_struc, inter_H_sublattice2))) self.assertFalse( pdc.are_equal( # different interstitials (wrong sublattice) Interstitial(s_struc, inter_H_sublattice1_set1), Interstitial(s_struc, inter_H_sublattice3))) self.assertFalse( pdc.are_equal( # different interstitials (wrong specie) Interstitial(s_struc, inter_H_sublattice3), Interstitial(s_struc, inter_He_sublattice3))) # test non-symmorphic interstitial matching # (using set generated from Voronoi generator, with same sublattice given by saturatated_interstitial_structure function) ns_struc = Structure.from_file(os.path.join(test_dir, "CuCl.cif")) ns_inter_H_sublattice1_set1 = PeriodicSite( 'H', [0.06924513, 0.06308959, 0.86766528], ns_struc.lattice) ns_inter_H_sublattice1_set2 = PeriodicSite( 'H', [0.43691041, 0.36766528, 0.06924513], ns_struc.lattice) ns_inter_H_sublattice2 = PeriodicSite( 'H', [0.06022109, 0.60196031, 0.1621814], ns_struc.lattice) ns_inter_He_sublattice2 = PeriodicSite( 'He', [0.06022109, 0.60196031, 0.1621814], ns_struc.lattice) self.assertTrue( pdc.are_equal( # trivial interstitial test Interstitial(ns_struc, ns_inter_H_sublattice1_set1), Interstitial(ns_struc, ns_inter_H_sublattice1_set1))) self.assertTrue( pdc.are_equal( # same sublattice, different coords Interstitial(ns_struc, ns_inter_H_sublattice1_set1), Interstitial(ns_struc, ns_inter_H_sublattice1_set2))) self.assertFalse( pdc.are_equal( Interstitial(ns_struc, ns_inter_H_sublattice1_set1 ), # different interstitials (wrong sublattice) Interstitial(ns_struc, ns_inter_H_sublattice2))) self.assertFalse( pdc.are_equal( # different interstitials (wrong specie) Interstitial(ns_struc, ns_inter_H_sublattice2), Interstitial(ns_struc, ns_inter_He_sublattice2))) # test influence of charge on defect matching (default is to be charge agnostic) vac_diff_chg = identical_Cs_vacs[0].copy() vac_diff_chg.set_charge(3.) self.assertTrue(pdc.are_equal(identical_Cs_vacs[0], vac_diff_chg)) chargecheck_pdc = PointDefectComparator( check_charge=True) # switch to PDC which cares about charge state self.assertFalse( chargecheck_pdc.are_equal(identical_Cs_vacs[0], vac_diff_chg)) # test different supercell size # (comparing same defect but different supercells - default is to not check for this) sc_agnostic_pdc = PointDefectComparator(check_primitive_cell=True) sc_scaled_s_struc = s_struc.copy() sc_scaled_s_struc.make_supercell([2, 2, 3]) sc_scaled_I_vac_sublatt1_ps1 = PeriodicSite( 'I', identical_I_vacs_sublattice1[0].site.coords, sc_scaled_s_struc.lattice, coords_are_cartesian=True) sc_scaled_I_vac_sublatt1_ps2 = PeriodicSite( 'I', identical_I_vacs_sublattice1[1].site.coords, sc_scaled_s_struc.lattice, coords_are_cartesian=True) sc_scaled_I_vac_sublatt2_ps = PeriodicSite( 'I', identical_I_vacs_sublattice2[1].site.coords, sc_scaled_s_struc.lattice, coords_are_cartesian=True) sc_scaled_I_vac_sublatt1_defect1 = Vacancy( sc_scaled_s_struc, sc_scaled_I_vac_sublatt1_ps1) sc_scaled_I_vac_sublatt1_defect2 = Vacancy( sc_scaled_s_struc, sc_scaled_I_vac_sublatt1_ps2) sc_scaled_I_vac_sublatt2_defect = Vacancy(sc_scaled_s_struc, sc_scaled_I_vac_sublatt2_ps) self.assertFalse( pdc.are_equal( identical_I_vacs_sublattice1[ 0], # trivially same defect site but between different supercells sc_scaled_I_vac_sublatt1_defect1)) self.assertTrue( sc_agnostic_pdc.are_equal(identical_I_vacs_sublattice1[0], sc_scaled_I_vac_sublatt1_defect1)) self.assertFalse( pdc.are_equal( identical_I_vacs_sublattice1[ 1], # same coords, different lattice structure sc_scaled_I_vac_sublatt1_defect1)) self.assertTrue( sc_agnostic_pdc.are_equal(identical_I_vacs_sublattice1[1], sc_scaled_I_vac_sublatt1_defect1)) self.assertFalse( pdc.are_equal( identical_I_vacs_sublattice1[ 0], # same sublattice, different coords sc_scaled_I_vac_sublatt1_defect2)) self.assertTrue( sc_agnostic_pdc.are_equal(identical_I_vacs_sublattice1[0], sc_scaled_I_vac_sublatt1_defect2)) self.assertFalse( sc_agnostic_pdc.are_equal( identical_I_vacs_sublattice1[ 0], # different defects (wrong sublattice) sc_scaled_I_vac_sublatt2_defect)) # test same structure size, but scaled lattice volume # (default is to not allow these to be equal, but check_lattice_scale=True allows for this) vol_agnostic_pdc = PointDefectComparator(check_lattice_scale=True) vol_scaled_s_struc = s_struc.copy() vol_scaled_s_struc.scale_lattice(s_struc.volume * 0.95) vol_scaled_I_vac_sublatt1_defect1 = Vacancy(vol_scaled_s_struc, vol_scaled_s_struc[4]) vol_scaled_I_vac_sublatt1_defect2 = Vacancy(vol_scaled_s_struc, vol_scaled_s_struc[5]) vol_scaled_I_vac_sublatt2_defect = Vacancy(vol_scaled_s_struc, vol_scaled_s_struc[6]) self.assertFalse( pdc.are_equal( identical_I_vacs_sublattice1[ 0], # trivially same defect (but vol change) vol_scaled_I_vac_sublatt1_defect1)) self.assertTrue( vol_agnostic_pdc.are_equal(identical_I_vacs_sublattice1[0], vol_scaled_I_vac_sublatt1_defect1)) self.assertFalse( pdc.are_equal( identical_I_vacs_sublattice1[ 0], # same defect, different sublattice point (and vol change) vol_scaled_I_vac_sublatt1_defect2)) self.assertTrue( vol_agnostic_pdc.are_equal(identical_I_vacs_sublattice1[0], vol_scaled_I_vac_sublatt1_defect2)) self.assertFalse( vol_agnostic_pdc.are_equal( identical_I_vacs_sublattice1[ 0], # different defect (wrong sublattice) vol_scaled_I_vac_sublatt2_defect)) # test identical defect which has had entire lattice shifted shift_s_struc = s_struc.copy() shift_s_struc.translate_sites(range(len(s_struc)), [0.2, 0.3, 0.4], frac_coords=True, to_unit_cell=True) shifted_identical_Cs_vacs = [ Vacancy(shift_s_struc, shift_s_struc[0]), Vacancy(shift_s_struc, shift_s_struc[1]) ] self.assertTrue( pdc.are_equal( identical_Cs_vacs[0], # trivially same defect (but shifted) shifted_identical_Cs_vacs[0])) self.assertTrue( pdc.are_equal( identical_Cs_vacs[ 0], # same defect on different sublattice point (and shifted) shifted_identical_Cs_vacs[1])) # test uniform lattice shift within non-symmorphic structure shift_ns_struc = ns_struc.copy() shift_ns_struc.translate_sites(range(len(ns_struc)), [0., 0.6, 0.3], frac_coords=True, to_unit_cell=True) shift_ns_inter_H_sublattice1_set1 = PeriodicSite( 'H', ns_inter_H_sublattice1_set1.frac_coords + [0., 0.6, 0.3], shift_ns_struc.lattice) shift_ns_inter_H_sublattice1_set2 = PeriodicSite( 'H', ns_inter_H_sublattice1_set2.frac_coords + [0., 0.6, 0.3], shift_ns_struc.lattice) self.assertTrue( pdc.are_equal( Interstitial(ns_struc, ns_inter_H_sublattice1_set1 ), # trivially same defect (but shifted) Interstitial(shift_ns_struc, shift_ns_inter_H_sublattice1_set1))) self.assertTrue( pdc.are_equal( Interstitial(ns_struc, ns_inter_H_sublattice1_set1), # same defect on different sublattice point (and shifted) Interstitial(shift_ns_struc, shift_ns_inter_H_sublattice1_set2))) # test a rotational + supercell type structure transformation (requires check_primitive_cell=True) rotated_s_struc = s_struc.copy() rotated_s_struc.make_supercell([[2, 1, 0], [-1, 3, 0], [0, 0, 2]]) rotated_identical_Cs_vacs = [ Vacancy(rotated_s_struc, rotated_s_struc[0]), Vacancy(rotated_s_struc, rotated_s_struc[1]) ] self.assertFalse( pdc.are_equal( identical_Cs_vacs[0], # trivially same defect (but rotated) rotated_identical_Cs_vacs[0])) self.assertTrue( sc_agnostic_pdc.are_equal(identical_Cs_vacs[0], rotated_identical_Cs_vacs[0])) self.assertFalse( pdc.are_equal( identical_Cs_vacs[ 0], # same defect on different sublattice (and rotated) rotated_identical_Cs_vacs[1])) self.assertTrue( sc_agnostic_pdc.are_equal( identical_Cs_vacs[ 0], # same defect on different sublattice point (and rotated) rotated_identical_Cs_vacs[1])) # test a rotational + supercell + shift type structure transformation for non-symmorphic structure rotANDshift_ns_struc = ns_struc.copy() rotANDshift_ns_struc.translate_sites(range(len(ns_struc)), [0., 0.6, 0.3], frac_coords=True, to_unit_cell=True) rotANDshift_ns_struc.make_supercell([[2, 1, 0], [-1, 3, 0], [0, 0, 2]]) ns_vac_Cs_set1 = Vacancy(ns_struc, ns_struc[0]) rotANDshift_ns_vac_Cs_set1 = Vacancy(rotANDshift_ns_struc, rotANDshift_ns_struc[0]) rotANDshift_ns_vac_Cs_set2 = Vacancy(rotANDshift_ns_struc, rotANDshift_ns_struc[1]) self.assertTrue( sc_agnostic_pdc.are_equal( ns_vac_Cs_set1, # trivially same defect (but rotated and sublattice shifted) rotANDshift_ns_vac_Cs_set1)) self.assertTrue( sc_agnostic_pdc.are_equal( ns_vac_Cs_set1, # same defect on different sublattice point (shifted and rotated) rotANDshift_ns_vac_Cs_set2))
def setUp(self): self.in_str = "Mn" st = Structure.from_file("POSCAR") self.system_1 = parse_label(self.in_str, st) self.system_2 = [3, 4, 5]
import os, re from mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import from pymatgen import Structure import matplotlib.pyplot as plt import numpy as np os.chdir('/home/jinho93/metal/3.Fe16N2/phonon/2.Al/disp/007') s1 = Structure.from_file('POSCAR') s2 = Structure.from_file('../SPOSCAR') pos = s1.cart_coords pos2 = pos - s2.cart_coords
def test_featurize(): """Test the featurization wrapper function.""" structure = Structure.from_file( os.path.join(THIS_DIR, "..", "..", "examples", "structures", "BaO2_mp-1105_computed.cif")) x, indices, names = featurize(structure) # pylint: disable=invalid-name assert len(x) == len(indices) == len(names) == 2 assert indices[0] == 0 assert indices[1] == 1 structure = Structure.from_file( os.path.join(THIS_DIR, "..", "..", "examples", "structures", "Mg_MOF_74.cif")) x, indices, names = featurize(structure) # pylint: disable=invalid-name assert len(x) == len(indices) == len(names) == 6 assert indices[0] == 0 assert indices[1] == 1 structure = Structure.from_file( os.path.join(THIS_DIR, "..", "structure_data_files", "RSM0027.cif")) x, indices, names = featurize(structure) # pylint: disable=invalid-name assert len(x) == len(indices) == len(names) == 2 spga = SpacegroupAnalyzer(structure) spga = SpacegroupAnalyzer(structure) x, indices, names = featurize( # pylint: disable=invalid-name spga.get_primitive_standard_structure()) assert len(x) == len(indices) == len(names) == 2 x, indices, names = featurize( # pylint: disable=invalid-name spga.get_conventional_standard_structure()) assert len(x) == len(indices) == len(names) == 4 structure = Structure.from_file( os.path.join(THIS_DIR, "..", "structure_data_files", "RSM0099.cif")) x, indices, names = featurize(structure) # pylint: disable=invalid-name assert len(x) == len(indices) == len(names) == 3 spga = SpacegroupAnalyzer(structure) x, indices, names = featurize( # pylint: disable=invalid-name spga.get_primitive_standard_structure()) # pylint: disable=invalid-name assert len(x) == len(indices) == len(names) == 3 x, indices, names = featurize( # pylint: disable=invalid-name spga.get_conventional_standard_structure()) assert len(x) == len(indices) == len(names) == 9 # Test Daniele's xyz file m = Molecule.from_file( # pylint: disable=invalid-name os.path.join(THIS_DIR, "..", "structure_data_files", "TSS03_structuredata.xyz")) lattice = np.array([ [6.4214088758454, 0.0, -2.0278718029537], [-1.7281031033172, 9.4571070308166, -5.4721686991526], [0.0, 0.0, 11.18087355], ]) s = Structure(lattice, [s.specie for s in m], m.cart_coords) # pylint: disable=invalid-name x, indices, names = featurize(s) # pylint: disable=invalid-name assert len(x) == len(indices) == len(names) == 2 assert indices[0] == 0 assert indices[1] == 1
+ " know what you're doing...") sys.stdout.flush() if worldrank >= nreplicas: # belong to comm that does nothing comm = commworld.Split(color=1, key=worldrank) comm.Free() sys.exit() # Wait for MPI_finalize else: comm = commworld.Split(color=0, key=worldrank) else: comm = commworld # prepare config cellsize = [1, 1, 3] base_structure = Structure.from_file( os.path.join(os.path.dirname(__file__), "POSCAR")) # .get_primitive_structure(tolerance=0.001) config = HAp_config(base_structure=base_structure, cellsize=cellsize) # prepare lattice-gas type representation reps = make_latgas_reps(spec_id=[0, 1, 2], nspec=[1, 4, 1], spec_orient=[1, 2, 1]) energy_reps = np.zeros(len(reps)) # prepare vasp model path_to_vasp = "/home/i0009/i000900/src/vasp.5.3/vasp.spawnready.gamma" solver = VASPSolver(path_to_vasp) vasprun = runner( Solver=solver, nprocs=nprocs_per_vasp,
def Write_Vasp_INCAR(cal_loc, structure_filename, workflow): """ Write or modify INCAR in folder cal_loc as follows: step I: If no INCAR in cal_loc, write INCAR using pymatgen.io.vasp.sets.MPRelaxSet step II: Modify INCAR according to new_incar_tags and remove_incar_tags. Input arguments: cal_loc (str): the absolute path structure_filename (str): the file from which the structure is read using pymatgen.Structure.from_file workflow """ firework = get_current_firework_from_cal_loc(cal_loc, workflow) firework_name = os.path.split(cal_loc)[-1] log_txt = os.path.join(cal_loc, "log.txt") write_INCAR = False if not os.path.isfile(os.path.join(cal_loc, "INCAR")): structure = Structure.from_file( os.path.join(cal_loc, structure_filename)) vis = MPRelaxSet(structure=structure) vis.incar.write_file(filename=os.path.join(cal_loc, "INCAR")) write_INCAR = True with open(log_txt, "a") as f: f.write("{} INFO: no INCAR in {}\n".format(get_time_str(), firework_name)) f.write( "\t\t\tuse pymatgen.io.vasp.sets.MPRelaxSet to write INCAR\n") new_incar_tags = dict([ (incar_tag, incar_value) for incar_tag, incar_value in firework["new_incar_tags"].items() ]) remove_incar_tags = firework["remove_incar_tags"] #Tags related to partial charge calculations. if firework["partial_charge_cal"]: new_incar_tags.update( get_partial_charge_tags(cal_loc=cal_loc, firework=firework, workflow=workflow)) if firework["ldau_cal"]: new_incar_tags.update( generate_Hubbard_U_J_INCAR_tags( cal_loc=cal_loc, U_J_table_filename=firework["ldau_u_j_table"])) if new_incar_tags or remove_incar_tags: if write_INCAR: modify_vasp_incar(cal_loc=cal_loc, new_tags=new_incar_tags, rename_old_incar="INCAR.pymatgen", remove_tags=remove_incar_tags) else: modify_vasp_incar(cal_loc=cal_loc, new_tags=new_incar_tags, remove_tags=remove_incar_tags) with open(log_txt, "a") as f: f.write("{} INFO: modify INCAR in {}\n".format( get_time_str(), firework_name)) if new_incar_tags: f.write("\t\tnew incar tags:\n") [ f.write("\t\t\t{}={}\n".format(key_, value_)) for key_, value_ in new_incar_tags.items() ] if remove_incar_tags: f.write("\t\tremove incar tags: ") [f.write("{}\t".format(tag_)) for tag_ in remove_incar_tags] f.write("\n") if write_INCAR: f.write("\t\told INCAR --> INCAR.pymatgen\n") if firework["bader_charge"]: if firework["step_no"] == 1: with open(log_txt, "a") as f: f.write("{} INFO: in {}\n".format(get_time_str(), firework_name)) f.write("\t\t\t'bader_charge' is on\n") f.write( "\t\t\tBut this is the first step. Cannot find NGXF, NGYF, NGZF\n" ) f.write( "\t\t\tLet's make a calculation without this INCAR tags first to get the default NGXF, NGYF and NGZF\n" ) else: prev_cal = os.path.join( os.path.split(cal_loc)[0], workflow[firework["copy_which_step"] - 1]["firework_folder_name"]) new_incar_tags = get_bader_charge_tags(cal_loc=prev_cal) modify_vasp_incar(cal_loc=cal_loc, new_tags=new_incar_tags, rename_old_incar="INCAR.no_bader_charge") with open(log_txt, "a") as f: f.write("{} INFO: in {}\n".format(get_time_str(), firework_name)) f.write("\t\t\t'bader_charge' is on\n") f.write( "\t\t\tretrieve NGXF, NGYF, NGZF from {} and double them\n" .format(os.path.split(prev_cal)[1])) f.write("\t\tnew incar tags:\n") [ f.write("\t\t\t{}={}\n".format(key_, value_)) for key_, value_ in new_incar_tags.items() ]