예제 #1
0
    def test_make_confs_0(self):
        if not os.path.exists(os.path.join(self.equi_path, 'CONTCAR')):
            with self.assertRaises(RuntimeError):
                self.surface.make_confs(self.target_path, self.equi_path)
        shutil.copy(os.path.join(self.source_path, 'mp-141.vasp'),
                    os.path.join(self.equi_path, 'CONTCAR'))
        task_list = self.surface.make_confs(self.target_path, self.equi_path)
        self.assertEqual(len(task_list), 7)
        dfm_dirs = glob.glob(os.path.join(self.target_path, 'task.*'))

        incar0 = Incar.from_file(os.path.join('vasp_input', 'INCAR.rlx'))
        incar0['ISIF'] = 4

        self.assertEqual(
            os.path.realpath(os.path.join(self.equi_path, 'CONTCAR')),
            os.path.realpath(os.path.join(self.target_path, 'POSCAR')))
        ref_st = Structure.from_file(os.path.join(self.target_path, 'POSCAR'))
        dfm_dirs.sort()
        for ii in dfm_dirs:
            st_file = os.path.join(ii, 'POSCAR')
            self.assertTrue(os.path.isfile(st_file))
            st0 = Structure.from_file(st_file)
            st1_file = os.path.join(ii, 'POSCAR.tmp')
            self.assertTrue(os.path.isfile(st1_file))
            st1 = Structure.from_file(st1_file)
            miller_json_file = os.path.join(ii, 'miller.json')
            self.assertTrue(os.path.isfile(miller_json_file))
            miller_json = loadfn(miller_json_file)
            sl = SlabGenerator(ref_st, miller_json,
                               self.prop_param[0]["min_slab_size"],
                               self.prop_param[0]["min_vacuum_size"])
            slb = sl.get_slab()
            st2 = Structure(slb.lattice, slb.species, slb.frac_coords)
            self.assertEqual(len(st1), len(st2))
예제 #2
0
def test_make_poscars_from_query(tmpdir):
    mg_structure = Structure(Lattice.cubic(1), species=["Mg", "Mg"],
                             coords=[[0, 0, 0], [0.5, 0.5, 0.5]])

    query = [{"full_formula": "Mg2", "task_id": "mp-1",
              "total_magnetization": 0.1,
              "band_gap": 0.0,
              "structure": mg_structure},
             {"full_formula": "O16"}]
    make_poscars_from_query(query, path=Path(tmpdir))
    tmpdir.chdir()
    s_mg = Structure.from_file(Path("Mg_mp-1") / "POSCAR")
    assert s_mg == mg_structure

    actual = loadfn(Path("Mg_mp-1") / "prior_info.yaml")
    expected = {'band_gap': 0.0, 'data_source': 'mp-1', 'total_magnetization': 0.1}
    assert actual == expected

    actual = Structure.from_file(Path("mol_O2") / "POSCAR")
    expected = Structure.from_str("""Default POSCAR of O2 molecule
   1.00000000000000     
    10.0000000000000000    0.0000000000000000    0.0000000000000000
     0.0000000000000000   10.0000000000000000    0.0000000000000000
     0.0000000000000000    0.0000000000000000   10.0000000000000000
   O 
     2
Direct
  0.0145089778962415  0.0000000000000000  0.0000000000000000
  0.1354910221037571  0.0000000000000000  0.0000000000000000""", fmt="POSCAR")
    assert actual == expected
예제 #3
0
def rmsd_pbc(file_path_1, file_path_2, original_def=True):
    """
    Calculate absolute root-mean-square diffence between two structures.
    No rotation nor recentering will be considered. Periodic boundary condition
    will be considered.
    """
    try:
        a = Structure.from_file(filename=file_path_1)
        b = Structure.from_file(filename=file_path_2)
    except Exception:
        sys.exit("File import failed.")

    # check if two structures are valid for compare
    natoms = check_validity(a, b)

    # get fractional coords of each structure
    # a_frac = [a[i].frac_coords for i in range(natoms)]
    # b_frac = [b[i].frac_coords for i in range(natoms)]
    a_frac = a.frac_coords
    b_frac = b.frac_coords

    # get frac_diff considering pbc (abs(diff) <= 0.5)
    frac_diff = pbc_diff(a_frac, b_frac)

    # convert to cartesian coords difference
    cart_diff = a.lattice.get_cartesian_coords(frac_diff)

    if original_def:
        # original definition of RMSD
        return np.sqrt(np.sum(cart_diff**2))
    else:
        # revised definition. The top 5 deviation is considered
        # aiming to better compare the difference of two similar structures
        return np.sum(np.sort(np.abs(cart_diff))[:5]) / 5
예제 #4
0
    def test_get_endpoint_dist(self):
        ep0 = Structure.from_file(get_path("POSCAR_ep0", dirname="io_files"))
        ep1 = Structure.from_file(get_path("POSCAR_ep1", dirname="io_files"))
        distances = get_endpoint_dist(ep0, ep1)

        self.assertAlmostEqual(max(distances), 6.3461081051543893, 7)
        self.assertEqual(min(distances), 0.0)
예제 #5
0
    def test_make_confs_0(self):
        if not os.path.exists(os.path.join(self.equi_path, 'CONTCAR')):
            with self.assertRaises(RuntimeError):
                self.vacancy.make_confs(self.target_path, self.equi_path)
        shutil.copy(os.path.join(self.source_path, 'CONTCAR'),
                    os.path.join(self.equi_path, 'CONTCAR'))
        task_list = self.vacancy.make_confs(self.target_path, self.equi_path)
        dfm_dirs = glob.glob(os.path.join(self.target_path, 'task.*'))
        self.assertEqual(len(dfm_dirs), 5)

        incar0 = Incar.from_file(os.path.join('vasp_input', 'INCAR.rlx'))
        incar0['ISIF'] = 4

        self.assertEqual(
            os.path.realpath(os.path.join(self.equi_path, 'CONTCAR')),
            os.path.realpath(os.path.join(self.target_path, 'POSCAR')))
        ref_st = Structure.from_file(os.path.join(self.target_path, 'POSCAR'))
        sga = SpacegroupAnalyzer(ref_st)
        sym_st = sga.get_symmetrized_structure()
        equiv_site_seq = list(sym_st.equivalent_sites)
        dfm_dirs.sort()
        for ii in dfm_dirs:
            st_file = os.path.join(ii, 'POSCAR')
            self.assertTrue(os.path.isfile(st_file))
            st0 = Structure.from_file(st_file)
            vac_site = equiv_site_seq.pop(0)
            vac = pmg_Vacancy(ref_st, vac_site[0], charge=0.0)
            st1 = vac.generate_defect_structure(
                self.prop_param[0]['supercell'])
            self.assertEqual(st0, st1)
    def setUp(self):
        struct = Structure.from_file(f"{dir_path}/full_path_files/MnO2_full_Li.vasp")
        self.fpm_li = MigrationGraph.with_distance(structure=struct, migrating_specie="Li", max_distance=4)

        # Particularity difficult pathfinding since both the starting and ending positions are outside the unit cell
        struct = Structure.from_file(f"{dir_path}/full_path_files/Mg_2atom.vasp")
        self.fpm_mg = MigrationGraph.with_distance(structure=struct, migrating_specie="Mg", max_distance=2)
예제 #7
0
    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"
            })
예제 #8
0
    def test_get_endpoints_from_index(self):
        endpoints = get_endpoints_from_index(structure=self.structure, site_indices=[0, 1])
        ep_0 = endpoints[0].as_dict()
        ep_1 = endpoints[1].as_dict()
        ep_0_expect = Structure.from_file(get_path("POSCAR_ep0", dirname="io_files")).as_dict()
        ep_1_expect = Structure.from_file(get_path("POSCAR_ep1", dirname="io_files")).as_dict()

        self.assertEqual(ep_0, ep_0_expect)
        self.assertEqual(ep_1, ep_1_expect)
예제 #9
0
 def setUpClass(cls):
     cls.structures = [
         Structure.from_file(
             os.path.join(module_dir, "cifs",
                          "LiFePO4_mp-19017_computed.cif")),
         Structure.from_file(
             os.path.join(module_dir, "cifs",
                          "BaTiO3_mp-2998_computed.cif"))
     ]
예제 #10
0
 def setUp(self):
     self.gnd_real = Structure.from_file(TEST_FILES / 'POSCAR.C0.gz')
     self.exd_real = Structure.from_file(TEST_FILES / 'POSCAR.C-.gz')
     self.gnd_test = Structure(Lattice.cubic(1.), ['H'], [[0., 0., 0.]])
     self.exd_test = Structure(Lattice.cubic(1.), ['H'], [[0.5, 0.5, 0.5]])
     self.sct_test = Structure(Lattice.cubic(1.), ['H'],
                               [[0.25, 0.25, 0.25]])
     self.vrs = [TEST_FILES / 'vasprun.xml.0.gz'] + \
         glob.glob(str(TEST_FILES / 'lower' / '*' / 'vasprun.xml.gz'))
예제 #11
0
    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))
예제 #12
0
    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))
예제 #13
0
    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)
예제 #14
0
    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)
예제 #15
0
    def test_predict(self):
        s = PymatgenTest.get_structure("CsCl")
        nacl = PymatgenTest.get_structure("CsCl")
        nacl.replace_species({"Cs": "Na"})
        nacl.scale_lattice(184.384551033)
        p = RLSVolumePredictor(radii_type="ionic")
        self.assertAlmostEqual(p.predict(s, nacl), 342.84905395082535)
        p = RLSVolumePredictor(radii_type="atomic")
        self.assertAlmostEqual(p.predict(s, nacl), 391.884366481)
        lif = PymatgenTest.get_structure("CsCl")
        lif.replace_species({"Cs": "Li", "Cl": "F"})
        p = RLSVolumePredictor(radii_type="ionic")
        self.assertAlmostEqual(p.predict(lif, nacl), 74.268402413690467)
        p = RLSVolumePredictor(radii_type="atomic")
        self.assertAlmostEqual(p.predict(lif, nacl), 62.2808125839)

        lfpo = PymatgenTest.get_structure("LiFePO4")
        lmpo = PymatgenTest.get_structure("LiFePO4")
        lmpo.replace_species({"Fe": "Mn"})
        p = RLSVolumePredictor(radii_type="ionic")
        self.assertAlmostEqual(p.predict(lmpo, lfpo), 310.08253254420134)
        p = RLSVolumePredictor(radii_type="atomic")
        self.assertAlmostEqual(p.predict(lmpo, lfpo), 299.607967711)

        sto = PymatgenTest.get_structure("SrTiO3")
        scoo = PymatgenTest.get_structure("SrTiO3")
        scoo.replace_species({"Ti4+": "Co4+"})
        p = RLSVolumePredictor(radii_type="ionic")
        self.assertAlmostEqual(p.predict(scoo, sto), 56.162534974936463)
        p = RLSVolumePredictor(radii_type="atomic")
        self.assertAlmostEqual(p.predict(scoo, sto), 57.4777835108)

        # Use Ag7P3S11 as a test case:

        # (i) no oxidation states are assigned and CVP-atomic scheme is selected.
        aps = Structure.from_file(os.path.join(dir_path,
                                               "Ag7P3S11_mp-683910_primitive.cif"))
        apo = Structure.from_file(os.path.join(dir_path,
                                               "Ag7P3S11_mp-683910_primitive.cif"))
        apo.replace_species({"S": "O"})
        p = RLSVolumePredictor(radii_type="atomic", check_isostructural=False)
        self.assertAlmostEqual(p.predict(apo, aps), 1196.31384276)

        # (ii) Oxidation states are assigned.
        apo.add_oxidation_state_by_element({"Ag": 1, "P": 5, "O": -2})
        aps.add_oxidation_state_by_element({"Ag": 1, "P": 5, "S": -2})
        p = RLSVolumePredictor(radii_type="ionic")
        self.assertAlmostEqual(p.predict(apo, aps), 1165.23259079)
        p = RLSVolumePredictor(radii_type="atomic")
        self.assertAlmostEqual(p.predict(apo, aps), 1196.31384276)
예제 #16
0
    def test_predict(self):
        s = PymatgenTest.get_structure("CsCl")
        nacl = PymatgenTest.get_structure("CsCl")
        nacl.replace_species({"Cs": "Na"})
        nacl.scale_lattice(184.384551033)
        p = RLSVolumePredictor(radii_type="ionic")
        self.assertAlmostEqual(p.predict(s, nacl), 342.84905395082535)
        p = RLSVolumePredictor(radii_type="atomic")
        self.assertAlmostEqual(p.predict(s, nacl), 391.884366481)
        lif = PymatgenTest.get_structure("CsCl")
        lif.replace_species({"Cs": "Li", "Cl": "F"})
        p = RLSVolumePredictor(radii_type="ionic")
        self.assertAlmostEqual(p.predict(lif, nacl), 74.268402413690467)
        p = RLSVolumePredictor(radii_type="atomic")
        self.assertAlmostEqual(p.predict(lif, nacl), 62.2808125839)

        lfpo = PymatgenTest.get_structure("LiFePO4")
        lmpo = PymatgenTest.get_structure("LiFePO4")
        lmpo.replace_species({"Fe": "Mn"})
        p = RLSVolumePredictor(radii_type="ionic")
        self.assertAlmostEqual(p.predict(lmpo, lfpo), 310.08253254420134)
        p = RLSVolumePredictor(radii_type="atomic")
        self.assertAlmostEqual(p.predict(lmpo, lfpo), 299.607967711)

        sto = PymatgenTest.get_structure("SrTiO3")
        scoo = PymatgenTest.get_structure("SrTiO3")
        scoo.replace_species({"Ti4+": "Co4+"})
        p = RLSVolumePredictor(radii_type="ionic")
        self.assertAlmostEqual(p.predict(scoo, sto), 56.162534974936463)
        p = RLSVolumePredictor(radii_type="atomic")
        self.assertAlmostEqual(p.predict(scoo, sto), 57.4777835108)

        # Use Ag7P3S11 as a test case:

        # (i) no oxidation states are assigned and CVP-atomic scheme is selected.
        aps = Structure.from_file(os.path.join(dir_path,
                                               "Ag7P3S11_mp-683910_primitive.cif"))
        apo = Structure.from_file(os.path.join(dir_path,
                                               "Ag7P3S11_mp-683910_primitive.cif"))
        apo.replace_species({"S": "O"})
        p = RLSVolumePredictor(radii_type="atomic", check_isostructural=False)
        self.assertAlmostEqual(p.predict(apo, aps), 1196.31384276)

        # (ii) Oxidation states are assigned.
        apo.add_oxidation_state_by_element({"Ag": 1, "P": 5, "O": -2})
        aps.add_oxidation_state_by_element({"Ag": 1, "P": 5, "S": -2})
        p = RLSVolumePredictor(radii_type="ionic")
        self.assertAlmostEqual(p.predict(apo, aps), 1165.23259079)
        p = RLSVolumePredictor(radii_type="atomic")
        self.assertAlmostEqual(p.predict(apo, aps), 1196.31384276)
예제 #17
0
def test_undercoordinated_n_past_issue():
    mofchecker = MOFChecker(
        Structure.from_file(os.path.join(THIS_DIR, "test_files",
                                         "axipee.cif")))
    assert mofchecker.has_undercoordinated_n == False

    mofchecker = MOFChecker(
        Structure.from_file(
            os.path.join(THIS_DIR, "test_files", "ABOVOF_FSR.cif")))
    assert mofchecker.has_undercoordinated_n == False

    mofchecker = MOFChecker(
        Structure.from_file(os.path.join(THIS_DIR, "test_files",
                                         "abiqae.cif")))
    assert mofchecker.has_undercoordinated_n == False
 def test_max_path_length(self):
     s = Structure.from_file(
         get_path("LYPS.cif", dirname="pathfinder_files"))
     dp1 = DistinctPathFinder(s, "Li", perc_mode="1d")
     self.assertAlmostEqual(dp1.max_path_length, 4.11375354207, 7)
     dp2 = DistinctPathFinder(s, "Li", 5, perc_mode="1d")
     self.assertAlmostEqual(dp2.max_path_length, 5.0, 7)
예제 #19
0
파일: phonopy.py 프로젝트: jmmshn/pymatgen
def get_gruneisenparameter(gruneisen_path, structure=None, structure_path=None) -> GruneisenParameter:
    """
    Get Gruneisen object from gruneisen.yaml file, as obtained from phonopy (Frequencies in THz!).
    The order is structure > structure path > structure from gruneisen dict.
    Newer versions of phonopy include the structure in the yaml file,
    the structure/structure_path is kept for compatibility.

    Args:
        gruneisen_path: Path to gruneisen.yaml file (frequencies have to be in THz!)
        structure: pymatgen Structure object
        structure_path: path to structure in a file (e.g., POSCAR)

    Returns: GruneisenParameter object

    """

    gruneisen_dict = loadfn(gruneisen_path)

    if structure_path and structure is None:
        structure = Structure.from_file(structure_path)
    else:
        try:
            structure = get_structure_from_dict(gruneisen_dict)
        except ValueError:
            raise ValueError("\nPlease provide a structure.\n")

    qpts, multiplicities, frequencies, gruneisen = ([] for _ in range(4))
    phonopy_labels_dict = {}

    for p in gruneisen_dict["phonon"]:
        q = p["q-position"]
        qpts.append(q)
        if "multiplicity" in p:
            m = p["multiplicity"]
        else:
            m = 1
        multiplicities.append(m)
        bands, gruneisenband = ([] for _ in range(2))
        for b in p["band"]:
            bands.append(b["frequency"])
            if "gruneisen" in b:
                gruneisenband.append(b["gruneisen"])
        frequencies.append(bands)
        gruneisen.append(gruneisenband)
        if "label" in p:
            phonopy_labels_dict[p["label"]] = p["q-position"]

    qpts_np = np.array(qpts)
    multiplicities_np = np.array(multiplicities)
    # transpose to match the convention in PhononBandStructure
    frequencies_np = np.transpose(frequencies)
    gruneisen_np = np.transpose(gruneisen)

    return GruneisenParameter(
        gruneisen=gruneisen_np,
        qpoints=qpts_np,
        multiplicities=multiplicities_np,
        frequencies=frequencies_np,
        structure=structure,
    )
예제 #20
0
def data():
    # prepare path
    pwd = Path(__file__).parent
    cif1 = pmg_S.from_file(str(pwd / '1.cif'))
    cif2 = pmg_S.from_file(str(pwd / '2.cif'))

    # ignore numpy warning
    import warnings
    print('ignore NumPy RuntimeWarning\n')
    warnings.filterwarnings("ignore", message="numpy.dtype size changed")
    warnings.filterwarnings("ignore", message="numpy.ndarray size changed")

    cifs = pd.Series([cif1, cif2], name='structure')
    yield cifs

    print('test over')
예제 #21
0
    def test_writebandstr(self):
        filepath = os.path.join(test_dir, 'CsI3Pb.cif')
        structure = Structure.from_file(filepath)
        excin = ExcitingInput(structure)
        string = excin.write_string('primitive', bandstr=True)
        bandstr = string.split('<properties>')[1].split('</properties>')[0]

        coord = []
        label = []
        coord_ref = [[0.0, 0.0, 0.0], [0.5, 0.0, 0.0], [0.5, 0.5, 0.0],
                     [0.0, 0.5, 0.0],
                     [0.0, 0.0, 0.0], [0.0, 0.0, 0.5], [0.5, 0.0, 0.5],
                     [0.5, 0.5, 0.5],
                     [0.0, 0.5, 0.5], [0.0, 0.0, 0.5], [0.0, 0.5, 0.0],
                     [0.0, 0.5, 0.5],
                     [0.5, 0.0, 0.5], [0.5, 0.0, 0.0], [0.5, 0.5, 0.0],
                     [0.5, 0.5, 0.5]]
        label_ref = ['GAMMA', 'X', 'S', 'Y', 'GAMMA', 'Z', 'U', 'R', 'T', 'Z',
                     'Y', 'T',
                     'U', 'X', 'S', 'R']
        root = ET.fromstring(bandstr)
        for plot1d in root.iter('plot1d'):
            for point in plot1d.iter('point'):
                coord.append([float(i) for i in point.get('coord').split()])
                label.append(point.get('label'))
        self.assertEqual(label, label_ref)
        self.assertEqual(coord, coord_ref)
예제 #22
0
    def test_substitute(self):
        structure = Structure.from_file(os.path.join(PymatgenTest.TEST_FILES_DIR, "Li2O.cif"))
        molecule = FunctionalGroups["methyl"]

        structure_copy = copy.deepcopy(structure)
        structure_copy_graph = copy.deepcopy(structure)

        sg = StructureGraph.with_local_env_strategy(structure, MinimumDistanceNN())
        sg_copy = copy.deepcopy(sg)

        # Ensure that strings and molecules lead to equivalent substitutions
        sg.substitute_group(1, molecule, MinimumDistanceNN)
        sg_copy.substitute_group(1, "methyl", MinimumDistanceNN)
        self.assertEqual(sg, sg_copy)

        # Ensure that the underlying structure has been modified as expected
        structure_copy.substitute(1, "methyl")
        self.assertEqual(structure_copy, sg.structure)

        # Test inclusion of graph dictionary
        graph_dict = {
            (0, 1): {"weight": 0.5},
            (0, 2): {"weight": 0.5},
            (0, 3): {"weight": 0.5},
        }

        sg_with_graph = StructureGraph.with_local_env_strategy(structure_copy_graph, MinimumDistanceNN())
        sg_with_graph.substitute_group(1, "methyl", MinimumDistanceNN, graph_dict=graph_dict)
        edge = sg_with_graph.graph.get_edge_data(11, 13)[0]
        self.assertEqual(edge["weight"], 0.5)
예제 #23
0
    def test_predict(self):
        p = DLSVolumePredictor()
        p_fast = DLSVolumePredictor(cutoff=0.0)  # for speed on compressed cells
        p_nolimit = DLSVolumePredictor(min_scaling=None, max_scaling=None)  # no limits on scaling

        fen = Structure.from_file(os.path.join(dir_path, "FeN_mp-6988.cif"))

        self.assertAlmostEqual(p.predict(fen), 18.2252568873)
        fen.scale_lattice(fen.volume * 3.0)
        self.assertAlmostEqual(p_nolimit.predict(fen), 18.2252568873)
        self.assertAlmostEqual(p.predict(fen), fen.volume * 0.5)
        fen.scale_lattice(fen.volume * 0.1)
        self.assertAlmostEqual(p_nolimit.predict(fen), 18.2252568873)
        self.assertAlmostEqual(p.predict(fen), fen.volume * 1.5)
        self.assertAlmostEqual(p_fast.predict(fen), fen.volume * 1.5)

        lfpo = PymatgenTest.get_structure("LiFePO4")

        lfpo.scale_lattice(lfpo.volume * 3.0)
        self.assertAlmostEqual(p_nolimit.predict(lfpo), 291.62094410192924)
        self.assertAlmostEqual(p.predict(lfpo), lfpo.volume * 0.5)
        lfpo.scale_lattice(lfpo.volume * 0.1)
        self.assertAlmostEqual(p_nolimit.predict(lfpo), 291.62094410192924)
        self.assertAlmostEqual(p.predict(lfpo), lfpo.volume * 1.5)
        self.assertAlmostEqual(p_fast.predict(lfpo), lfpo.volume * 1.5)

        lmpo = PymatgenTest.get_structure("LiFePO4")
        lmpo.replace_species({"Fe": "Mn"})
        self.assertAlmostEqual(p.predict(lmpo), 290.795329052)
예제 #24
0
 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"))]
예제 #25
0
class UtilityTest(unittest.TestCase):
    """
    Unit test for outside methods in io.py
    """
    structure = Structure.from_file(get_path("POSCAR", dirname="io_files"))

    def test_get_endpoints_from_index(self):
        endpoints = get_endpoints_from_index(structure=self.structure,
                                             site_indices=[0, 1])
        ep_0 = endpoints[0].as_dict()
        ep_1 = endpoints[1].as_dict()
        ep_0_expect = Structure.from_file(get_path("POSCAR_ep0",
                                                   dirname="io_files")).as_dict()
        ep_1_expect = Structure.from_file(get_path("POSCAR_ep1",
                                                   dirname="io_files")).as_dict()

        self.assertEqual(ep_0, ep_0_expect)
        self.assertEqual(ep_1, ep_1_expect)

    def test_get_endpoint_dist(self):
        ep0 = Structure.from_file(get_path("POSCAR_ep0", dirname="io_files"))
        ep1 = Structure.from_file(get_path("POSCAR_ep1", dirname="io_files"))
        distances = get_endpoint_dist(ep0, ep1)

        self.assertAlmostEqual(max(distances), 6.3461081051543893, 7)
        self.assertEqual(min(distances), 0.0)
예제 #26
0
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
예제 #27
0
def predict(args):
    """
    Handle view commands.

    :param args: Args from command.
    """
    headers = ["Filename"]
    output = []
    models = []
    prefix = ""
    for i, mn in enumerate(args.models):
        model = MEGNetModel.from_file(mn)
        models.append(model)
        if i == 0:
            prefix = mn
        else:
            sm = SequenceMatcher(None, prefix, mn)
            match = sm.find_longest_match(0, len(prefix), 0, len(mn))
            prefix = prefix[0:match.size]
        headers.append(
            f"{mn} ({model.metadata.get('unit', '').strip('log10')}")
    headers = [h.lstrip(prefix) for h in headers]

    for fn in args.structures:
        structure = Structure.from_file(fn)
        row = [fn]
        for model in models:
            val = model.predict_structure(structure).ravel()
            if "log10" in str(model.metadata.get("unit", "")):
                val = 10**val
            row.append(val)
        output.append(row)
    print(tabulate(output, headers=headers))
예제 #28
0
    def run_task(self, fw_spec):
        unitcell = Structure.from_file("POSCAR")
        supercell = self.get("supercell", None)
        if supercell is not None:
            os.system('cp POSCAR POSCAR-unitcell')
            unitcell.make_supercell(supercell)

        lepsilon = self.get("lepsilon", False)
        standardize = self.get("standardize", False)
        other_params = self.get("other_params", {})
        user_incar_settings = self.get("user_incar_settings", {})
        finder = SpacegroupAnalyzer(unitcell)
        prims = finder.get_primitive_standard_structure()
        # for lepsilon runs, the kpoints should be denser
        if lepsilon:
            kpoint_set = Generate_kpoints(prims, 0.02)
            struct = prims
        elif standardize:
            kpoint_set = Generate_kpoints(prims, 0.03)
            struct = prims
        else:
            kpoint_set = Generate_kpoints(unitcell, 0.03)
            struct = unitcell

        vis = MPStaticSet(struct,
                          user_incar_settings=user_incar_settings,
                          user_kpoints_settings=kpoint_set,
                          sym_prec=self.get("sym_prec", 0.1),
                          lepsilon=lepsilon,
                          **other_params)
        vis.write_input(".")
예제 #29
0
class MVLCINEBEndPointSetTest(unittest.TestCase):

    endpoint = Structure.from_file(get_path("POSCAR0", dirname="io_files"))

    def test_incar(self):
        m = MVLCINEBEndPointSet(self.endpoint)
        incar_string = m.incar.get_string(sort_keys=True, pretty=True)
        incar_expect = """ALGO    =  Fast
EDIFF   =  5e-05
EDIFFG  =  -0.02
ENCUT   =  520
IBRION  =  2
ICHARG  =  1
ISIF    =  2
ISMEAR  =  0
ISPIN   =  2
ISYM    =  0
LCHARG  =  False
LORBIT  =  11
LREAL   =  Auto
LWAVE   =  False
MAGMOM  =  35*0.6
NELM    =  200
NELMIN  =  4
NSW     =  99
PREC    =  Accurate
SIGMA   =  0.05"""
        self.assertEqual(incar_string, incar_expect)

    def test_incar_user_setting(self):
        user_incar_settings = {"ALGO": "Normal",
                               "EDIFFG": -0.05,
                               "NELECT": 576,
                               "NPAR": 4,
                               "NSW": 100,}
        m = MVLCINEBEndPointSet(self.endpoint, user_incar_settings=user_incar_settings)
        incar_string = m.incar.get_string(sort_keys=True)
        incar_expect = """ALGO = Normal
EDIFF = 5e-05
EDIFFG = -0.05
ENCUT = 520
IBRION = 2
ICHARG = 1
ISIF = 2
ISMEAR = 0
ISPIN = 2
ISYM = 0
LCHARG = False
LORBIT = 11
LREAL = Auto
LWAVE = False
MAGMOM = 35*0.6
NELECT = 576
NELM = 200
NELMIN = 4
NPAR = 4
NSW = 100
PREC = Accurate
SIGMA = 0.05"""
        self.assertEqual(incar_string.strip(), incar_expect.strip())
예제 #30
0
    def test_make_confs(self):

        shutil.copy(os.path.join(self.source_path, 'Al-fcc.json'),
                    os.path.join(self.equi_path, 'result.json'))
        if not os.path.exists(os.path.join(self.equi_path, 'CONTCAR')):
            with self.assertRaises(RuntimeError):
                self.elastic.make_confs(self.target_path, self.equi_path)
        shutil.copy(os.path.join(self.source_path, 'CONTCAR_Al_fcc'),
                    os.path.join(self.equi_path, 'CONTCAR'))
        task_list = self.elastic.make_confs(self.target_path, self.equi_path)
        dfm_dirs = glob.glob(os.path.join(self.target_path, 'task.*'))

        incar0 = Incar.from_file(os.path.join('vasp_input', 'INCAR.rlx'))
        incar0['ISIF'] = 4

        self.assertEqual(
            os.path.realpath(os.path.join(self.equi_path, 'CONTCAR')),
            os.path.realpath(os.path.join(self.target_path, 'POSCAR')))
        ref_st = Structure.from_file(os.path.join(self.target_path, 'POSCAR'))
        dfm_dirs.sort()
        for ii in dfm_dirs:
            st_file = os.path.join(ii, 'POSCAR')
            self.assertTrue(os.path.isfile(st_file))
            strain_json_file = os.path.join(ii, 'strain.json')
            self.assertTrue(os.path.isfile(strain_json_file))
예제 #31
0
    def test_writebandstr(self):
        filepath = os.path.join(test_dir, 'CsI3Pb.cif')
        structure = Structure.from_file(filepath)
        excin = ExcitingInput(structure)
        string = excin.write_string('primitive', bandstr=True)
        bandstr = string.split('<properties>')[1].split('</properties>')[0]

        coord = []
        label = []
        coord_ref = [[0.0, 0.0, 0.0], [0.5, 0.0, 0.0], [0.5, 0.5, 0.0],
                     [0.0, 0.5, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.5],
                     [0.5, 0.0, 0.5], [0.5, 0.5, 0.5], [0.0, 0.5, 0.5],
                     [0.0, 0.0, 0.5], [0.0, 0.5, 0.0], [0.0, 0.5, 0.5],
                     [0.5, 0.0, 0.5], [0.5, 0.0, 0.0], [0.5, 0.5, 0.0],
                     [0.5, 0.5, 0.5]]
        label_ref = [
            'GAMMA', 'X', 'S', 'Y', 'GAMMA', 'Z', 'U', 'R', 'T', 'Z', 'Y', 'T',
            'U', 'X', 'S', 'R'
        ]
        root = ET.fromstring(bandstr)
        for plot1d in root.iter('plot1d'):
            for point in plot1d.iter('point'):
                coord.append([float(i) for i in point.get('coord').split()])
                label.append(point.get('label'))
        self.assertEqual(label, label_ref)
        self.assertEqual(coord, coord_ref)
예제 #32
0
def slab_from_file(structure, hkl):
    """
    Reads in structure from the file and returns slab object.

    Args:
         structure (str): Structure file in any format supported by pymatgen.
            Will accept a pymatgen.Structure object directly.
         hkl (tuple): Miller index of the slab in the input file.

    Returns:
         Slab object
    """
    if type(structure) == str:
        slab_input = Structure.from_file(structure)
    else:
        slab_input = structure
    return Slab(
        slab_input.lattice,
        slab_input.species_and_occu,
        slab_input.frac_coords,
        hkl,
        Structure.from_sites(slab_input, to_unit_cell=True),
        # this OUC is not correct, need to get it from slabgenerator
        shift=0,
        scale_factor=np.eye(3, dtype=np.int),
        site_properties=slab_input.site_properties)
def test_make_defect_entries(tmpdir, supercell_info):
    tmpdir.chdir()
    supercell_info.to_json_file()
    defect_set = DefectSet({SimpleDefect(None, "He1", [-1, 0])})
    defect_set.to_yaml()
    args = Namespace()
    make_defect_entries(args)
    names = {str(name) for name in Path(".").glob("*")}
    assert names == {
        'Va_He1_-1', 'defect_in.yaml', 'perfect', 'Va_He1_0',
        'supercell_info.json'
    }

    perfect_structure = Structure.from_file(str(Path("perfect") / "POSCAR"))
    assert perfect_structure == supercell_info.structure

    file_names = {
        str(file_name.name)
        for file_name in Path("Va_He1_-1").glob("*")
    }
    assert file_names == {"POSCAR", "defect_entry.json", "prior_info.yaml"}

    expected = """charge: -1
"""
    assert Path("Va_He1_-1/prior_info.yaml").read_text() == expected
예제 #34
0
def test_lone_molecule():
    mofchecker = MOFChecker(
        Structure.from_file(
            os.path.join(THIS_DIR, "test_files", "ABAVIJ_clean.cif")))
    assert mofchecker.has_lone_molecule == False

    mofchecker = MOFChecker(
        Structure.from_file(
            os.path.join(THIS_DIR, "test_files", "HKUST_floating.cif")))
    assert mofchecker.has_lone_molecule == True

    assert mofchecker.lone_molecule_indices == [[144]]

    atoms = read(os.path.join(THIS_DIR, "test_files", "overvalent_h.cif"))
    mofchecker = MOFChecker.from_ase(atoms, primitive=False)
    assert len(mofchecker.lone_molecule_indices) == 3
예제 #35
0
def test_get_poscar_from_mp(tmpdir):
    args = Namespace(mpid="mp-110",
                     poscar="POSCAR",
                     prior_info=Path("prior_info.yaml"))
    tmpdir.chdir()
    get_poscar_from_mp(args)
    expected = """Mg1
1.0
-1.789645  1.789645  1.789645
 1.789645 -1.789645  1.789645
 1.789645  1.789645 -1.789645
1
direct
0.000000 0.000000 0.000000 Mg
"""
    assert Structure.from_file("POSCAR") == Structure.from_str(expected,
                                                               fmt="POSCAR")
    assert Path("prior_info.yaml").read_text() == """band_gap: 0.0
data_source: mp-110
icsd_ids:
- 180455
- 642652
total_magnetization: 0.0001585
"""
    # Need to remove file to avoid the side effect for other unittests.
    os.remove("prior_info.yaml")
예제 #36
0
    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)
예제 #37
0
    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"},
        )
예제 #38
0
    def setUp(self):
        """
        1) Basic check for pymatgen configurations.
        2) Setup all test workflow.
        """
        super(TestNudgedElasticBandWorkflow, self).setUp()
        # Structures used for test:
        parent = PymatgenTest.get_structure("Li2O")
        parent.remove_oxidation_states()
        parent.make_supercell(2)
        ep0, ep1 = get_endpoints_from_index(parent, [0, 1])
        neb_dir = [os.path.join(module_dir, "..", "..", "test_files", "neb_wf", "4", "inputs", "{:02}",
                                "POSCAR").format(i) for i in range(5)]
        self.structures = [Structure.from_file(n) for n in neb_dir]

        # Run fake vasp
        test_yaml = os.path.join(module_dir, "../../test_files/neb_wf/config/neb_unittest.yaml")
        with open(test_yaml, 'r') as stream:
            self.config = yaml.safe_load(stream)
            # Use scratch directory as destination directory for testing
            self.config["common_params"]["_fw_env"] = {"run_dest_root": self.scratch_dir}

        # Config 1: The parent structure & two endpoint indexes provided; need relaxation first.
        self.config_1 = copy.deepcopy(self.config)
        self.config_1["common_params"]["is_optimized"] = False
        self.config_1["common_params"]["wf_name"] = "NEB_test_1"

        # Config 2: The parent structure & two endpoint indexes provided; no need to relax.
        self.config_2 = copy.deepcopy(self.config)
        del self.config_2["fireworks"][0]
        self.config_2["common_params"]["is_optimized"] = True
        self.config_2["common_params"]["wf_name"] = "NEB_test_2"

        # Config 3: Two endpoints provided; need to relax two endpoints.
        self.config_3 = copy.deepcopy(self.config)
        del self.config_3["fireworks"][0]
        self.config_3["common_params"]["is_optimized"] = False
        self.config_3["common_params"]["wf_name"] = "NEB_test_3"

        # Config 4: Two relaxed endpoints provided; no need to relax two endpoints.
        self.config_4 = copy.deepcopy(self.config_3)
        del self.config_4["fireworks"][0]
        self.config_4["common_params"]["is_optimized"] = True
        self.config_4["common_params"]["wf_name"] = "NEB_test_4"

        # Config 5: All images including two endpoints are provided.
        self.config_5 = copy.deepcopy(self.config)
        del self.config_5["fireworks"][0: 2]
        self.config_5["common_params"]["wf_name"] = "NEB_test_5"

        self.wf_1 = wf_nudged_elastic_band([parent], parent, self.config_1)
        self.wf_2 = wf_nudged_elastic_band([parent], parent, self.config_2)
        self.wf_3 = wf_nudged_elastic_band([ep0, ep1], parent, self.config_3)
        self.wf_4 = wf_nudged_elastic_band([ep0, ep1], parent, self.config_4)
        self.wf_5 = wf_nudged_elastic_band(self.structures, parent, self.config_5)

        # Workflow without the config file
        self.wf_6 = wf_nudged_elastic_band(self.structures, parent)
예제 #39
0
    def setUp(self):
        filepath = os.path.join(test_dir, 'Li.cif')
        self.s = Structure.from_file(filepath)

        self.bulk = MVLGBSet(self.s)
        self.slab = MVLGBSet(self.s, slab_mode=True)

        self.d_bulk = self.bulk.all_input
        self.d_slab = self.slab.all_input
예제 #40
0
    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)
예제 #41
0
    def setUp(self):
        filepath = self.TEST_FILES_DIR / 'Li.cif'
        self.s = Structure.from_file(filepath)

        self.bulk = MVLGBSet(self.s)
        self.slab = MVLGBSet(self.s, slab_mode=True)

        self.d_bulk = self.bulk.get_vasp_input()
        self.d_slab = self.slab.get_vasp_input()
        warnings.simplefilter("ignore")
예제 #42
0
파일: events.py 프로젝트: rousseab/pymatgen
 def handle_input_event(self, abiinput, outdir, event):
     try:
         old_abiinput = abiinput.deepcopy()
         # Read the last structure dumped by ABINIT before aborting.
         filepath = outdir.has_abiext("DILATMX_STRUCT.nc")
         last_structure = Structure.from_file(filepath)
         abiinput.set_structure(last_structure)
         return Correction(self, self.compare_inputs(abiinput, old_abiinput), event, False)
     except Exception as exc:
         logger.warning('Error while trying to apply the handler {}.'.format(str(self)), exc)
         return None
예제 #43
0
 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)
예제 #44
0
    def test_ordering_enumeration(self):
        
        # simple afm
        structure = Structure.from_file(
            os.path.join(test_dir, "magnetic_orderings/LaMnO3.json"))
        enumerator = MagneticStructureEnumerator(structure)
        self.assertEqual(enumerator.input_origin, "afm")

        # ferrimagnetic (Cr produces net spin)
        structure = Structure.from_file(
            os.path.join(test_dir, "magnetic_orderings/Cr2NiO4.json"))
        enumerator = MagneticStructureEnumerator(structure)
        self.assertEqual(enumerator.input_origin, "ferri_by_Cr")

        # antiferromagnetic on single magnetic site
        structure = Structure.from_file(
            os.path.join(test_dir, "magnetic_orderings/Cr2WO6.json"))
        enumerator = MagneticStructureEnumerator(structure)
        self.assertEqual(enumerator.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"))
        # enumerator = MagneticOrderingsenumerator(structure, default_magmoms={'Cu': 1.73},
        #                         transformation_kwargs={'max_cell_size': 4})
        # self.assertEqual(enumerator.input_origin, "afm")

        # antiferromagnetic by structural motif
        structure = Structure.from_file(
            os.path.join(test_dir, "magnetic_orderings/Ca3Co2O6.json"))
        enumerator = MagneticStructureEnumerator(
            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(enumerator.input_origin, "afm_by_motif_2a")
예제 #45
0
    def setup(self):
        """
        Performs initial setup for VaspJob, including overriding any settings
        and backing up.
        """
        files = os.listdir(".")
        num_structures = 0
        if not set(files).issuperset({"INCAR", "POSCAR", "POTCAR", "KPOINTS"}):
            for f in files:
                try:
                    struct = Structure.from_file(f)
                    num_structures += 1
                except:
                    pass
            if num_structures != 1:
                raise RuntimeError("{} structures found. Unable to continue."
                                   .format(num_structures))
            else:
                self.default_vis.write_input(struct, ".")

        if self.backup:
            for f in VASP_INPUT_FILES:
                shutil.copy(f, "{}.orig".format(f))

        if self.auto_npar:
            try:
                incar = Incar.from_file("INCAR")
                #Only optimized NPAR for non-HF and non-RPA calculations.
                if not (incar.get("LHFCALC") or incar.get("LRPA") or
                        incar.get("LEPSILON")):
                    if incar.get("IBRION") in [5, 6, 7, 8]:
                        # NPAR should not be set for Hessian matrix
                        # calculations, whether in DFPT or otherwise.
                        del incar["NPAR"]
                    else:
                        import multiprocessing
                        # try sge environment variable first
                        # (since multiprocessing counts cores on the current machine only)
                        ncores = os.environ.get('NSLOTS') or multiprocessing.cpu_count()
                        ncores = int(ncores)
                        for npar in range(int(round(math.sqrt(ncores))),
                                          ncores):
                            if ncores % npar == 0:
                                incar["NPAR"] = npar
                                break
                    incar.write_file("INCAR")
            except:
                pass

        if self.settings_override is not None:
            VaspModder().apply_actions(self.settings_override)
예제 #46
0
파일: events.py 프로젝트: sonium0/pymatgen
    def correct(self, task):
        #Idea: decrease dilatxm and restart from the last structure.
        #We would like to end up with a structures optimized with dilatmx 1.01
        #that will be used for phonon calculations.

        # Read the last structure dumped by ABINIT before aborting.
        print("in dilatmx")
        filepath = task.outdir.has_abiext("DILATMX_STRUCT.nc")
        last_structure = Structure.from_file(filepath)

        task._change_structure(last_structure)
        #changes = task._modify_vars(dilatmx=1.05)
        task.history.append("Take last structure from DILATMX_STRUCT.nc, will try to restart")
        return 1
예제 #47
0
    def test_incar(self):
        filepath = os.path.join(test_dir, 'Li.cif')
        structure = Structure.from_file(filepath)

        vis = MPNMRSet(structure)
        self.assertTrue(vis.incar.get("LCHIMAG", None))
        self.assertEqual(vis.incar.get("QUAD_EFG", None), None)

        vis = MPNMRSet(structure, mode="efg")
        self.assertFalse(vis.incar.get("LCHIMAG", None))
        self.assertEqual(vis.incar.get("QUAD_EFG", None), [-0.808])

        vis = MPNMRSet(structure, mode="efg", isotopes=["Li-7"])
        self.assertFalse(vis.incar.get("LCHIMAG", None))
        self.assertEqual(vis.incar.get("QUAD_EFG", None), [-40.1])
예제 #48
0
    def test_ln_magmom(self):
        YAML_PATH = os.path.join(os.path.dirname(__file__), "../VASPIncarBase.yaml")
        MAGMOM_SETTING = loadfn(YAML_PATH)["MAGMOM"]
        structure = Structure.from_file(os.path.join(test_dir, "La4Fe4O12.cif"))
        structure.add_oxidation_state_by_element({"La": +3, "Fe": +3, "O": -2})
        for ion in MAGMOM_SETTING:
            s = structure.copy()
            s.replace_species({"La3+": ion})
            vis = MPRelaxSet(s)
            fe_pos = vis.poscar.comment.index("Fe")
            if fe_pos == 0:
                magmom_ans = [5] * 4 + [MAGMOM_SETTING[ion]] * 4 + [0.6] * 12
            else:
                magmom_ans = [MAGMOM_SETTING[ion]] * 4 + [5] * 4 + [0.6] * 12

            self.assertEqual(vis.incar["MAGMOM"], magmom_ans)
예제 #49
0
    def test_predict(self):
        p = DLSVolumePredictor()

        fen = Structure.from_file(os.path.join(dir_path, "FeN_mp-6988.cif"))
        self.assertAlmostEquals(p.predict(fen), 18.2252568873)
        fen.scale_lattice(3.0)
        self.assertAlmostEquals(p.predict(fen), 18.2252568873)
        fen.scale_lattice(0.24)
        self.assertAlmostEquals(p.predict(fen), 18.2252568873)

        lfpo = PymatgenTest.get_structure("LiFePO4")
        lfpo.scale_lattice(10.1)
        self.assertAlmostEqual(p.predict(lfpo), 291.62094410192924)
        lfpo.scale_lattice(0.2)
        self.assertAlmostEqual(p.predict(lfpo), 291.62094410192924)
        lmpo = PymatgenTest.get_structure("LiFePO4")
        lmpo.replace_species({"Fe": "Mn"})
        self.assertAlmostEquals(p.predict(lmpo), 290.795329052)
예제 #50
0
파일: events.py 프로젝트: ychaojia/pymatgen
    def handle_task_event(self, task, event):
        # Read the last structure dumped by ABINIT before aborting.
        filepath = task.outdir.has_abiext("DILATMX_STRUCT.nc")
        last_structure = Structure.from_file(filepath)

        task._change_structure(last_structure)

        #read the suggested dilatmx
        # new_dilatmx = 1.05
        # if new_dilatmx > self.max_dilatmx:
        #     msg = "Suggested dilatmx ({}) exceeds maximux configured value ({}).".format(new_dilatmx, self.max_dilatmx)
        #     return self.NOT_FIXED
        # task.strategy.abinit_input.set_vars(dilatmx=new_dilatmx)
        msg = "Take last structure from DILATMX_STRUCT.nc, will try to restart with dilatmx %s" % task.get_inpvar("dilatmx")
        task.log_correction(event, msg)
        # Note that we change the structure but we don't try restart from the previous WFK|DEN file
        # because Abinit called mpi_abort and therefore no final WFK|DEN file has been produced.

        return self.FIXED
예제 #51
0
    def _get_cgcnn_data(task="classification"):
        """
        Get cgcnn sample data.
        Args:
            task (str): Classification or regression,
                        decided which sample data to return.

        Returns:
            id_prop_data (list): List of property data.
            elem_embedding (list): List of element features.
            struct_list (list): List of structure object.
        """
        if task == "classification":
            cgcnn_data_path = os.path.join(os.path.dirname(cgcnn.__file__),
                                           "..", "data", "sample-classification")
        else:
            cgcnn_data_path = os.path.join(os.path.dirname(cgcnn.__file__),
                                           "..", "data", "sample-regression")

        struct_list = list()
        cif_list = list()
        with open(os.path.join(cgcnn_data_path, "id_prop.csv")) as f:
            reader = csv.reader(f)
            id_prop_data = [row[1] for row in reader]
        with open(os.path.join(cgcnn_data_path, "atom_init.json")) as f:
            elem_embedding = json.load(f)

        for file in os.listdir(cgcnn_data_path):
            if file.endswith('.cif'):
                cif_list.append(int(file[:-4]))
                cif_list = sorted(cif_list)
        for cif_name in cif_list:
            crystal = Structure.from_file(os.path.join(cgcnn_data_path,
                                                       '{}.cif'.format(
                                                           cif_name)))
            struct_list.append(crystal)
        return id_prop_data, elem_embedding, struct_list
예제 #52
0
#!/usr/bin/env python

from Generate_Surface import get_SD_along_vector
from Classes_Pymatgen import Poscar
from pymatgen.core import Structure
import argparse

parser = argparse.ArgumentParser()

parser.add_argument('lower_bound', help='vector to begin freezing at',
                    default=None, type=float)
parser.add_argument('upper_bound', help='vector to end freezing at',
                    default=None, type=float)
parser.add_argument('--vector', help='Vector to Freeze along (default = 2)',
                    default=2, type=int)
parser.add_argument('--input', help='file to read (default = CONTCAR)',
                    default='CONTCAR', type=str)
parser.add_argument('--output', help='file to write (default = CONTCAR.sd)',
                    default='CONTCAR.sd', type=str)
args = parser.parse_args()

lb = args.lower_bound
ub = args.upper_bound
v = args.vector

s = Structure.from_file(args.input)
sd = get_SD_along_vector(s, v, [lb, ub])
Poscar(s, selective_dynamics=sd).write_file(args.output)
예제 #53
0
 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))
예제 #54
0
                              adsorb_on_species=iface.adsorb_on_species,
                              primitive=False, from_ase=True,
                              x_shift=x, y_shift=y)
            iface.create_interface()
            energy = iface.calc_energy()
            iface.sort()
            if energy < ecut:
                ifaces.append((energy, iface))
                # ifaces.zip(energy, iface)
    return ifaces


if __name__ == '__main__':
    # PbS 100 surface with single hydrazine as ligand
    # sample pre-relaxed structure files for Bulk (strt) and Molecule
    strt = Structure.from_file("POSCAR_PbS")
    mol_struct = Structure.from_file("POSCAR_Hydrazine")
    mol = Molecule(mol_struct.species, mol_struct.cart_coords)
    hydrazine = Ligand([mol])

    # intital supercell, this wont be the final supercell if
    # surface coverage is specified
    supercell = [1, 1, 1]

    # miller index
    hkl = [1, 0, 0]

    # minimum slab thickness in Angstroms
    min_thick = 19

    # minimum vacuum thickness in Angstroms
예제 #55
0
from pymatgen.io.abinitio.works import RelaxWork
from pymatgen.io.abinitio.tasks import TaskManager
from pymatgen.io.abinitio.flows import Flow
from pymatgen.io.abinitio.strategies import RelaxStrategy
from pymatgen.io.abinitio.abiobjects import KSampling, RelaxationMethod, AbiStructure

from pymatgen.core import Structure

from myscripts.pseudos import all_pseudos

scratchdir = '/p/lscratchd/damewood'
basename = '2014_Trilayer/abinit_6z'
workdir = os.path.join(scratchdir,basename)
logging.basicConfig()
structure = Structure.from_file('trilayer_6z.json')
manager = TaskManager.from_user_config()
ksampling = KSampling(mode='monkhorst',kpts=((6,6,2),), kpt_shifts=((0.5,0.5,0.5),(0.5,0.0,0.0),(0.0,0.5,0.0),(0.0,0.0,0.5)))
relax_ion = RelaxationMethod(ionmov = 2, optcell = 0)
relax_ioncell = RelaxationMethod(ionmov = 2, optcell = 1)

pseudos = all_pseudos()
flow = Flow(manager = manager, workdir = os.path.join(workdir, 'trilayer_6z'))
spins = numpy.zeros([len(structure),3])
spins[:4,2] = 3.
ion_input = RelaxStrategy(structure, pseudos, ksampling,
    relax_ion, accuracy="high", smearing = "fermi_dirac:0.025 eV",
    ecut = 40., pawecutdg = 80., chkprim = 0, tolmxf = 5.e-6, spinat = spins,
    restartxf = -2, nband = 60, nstep = 100)
ioncell_input = ion_input.copy()
ioncell_input.relax_algo = relax_ioncell
예제 #56
0
    def run_task(self, fw_spec):

        label = self["label"]
        assert label in ["parent", "ep0", "ep1"] or "neb" in label, "Unknown label!"

        d_img = float(self.get("d_img", 0.7))  # Angstrom
        wf_name = fw_spec["wf_name"]
        src_dir = os.path.abspath(".")
        dest_dir = os.path.join(fw_spec["_fw_env"]["run_dest_root"], wf_name, label)
        shutil.copytree(src_dir, dest_dir)

        # Update fw_spec based on the type of calculations.
        if "neb" in label:
            # Update all relaxed images.
            subs = glob.glob("[0-2][0-9]")
            nimages = len(subs)
            concar_list = ["{:02}/CONTCAR".format(i) for i in range(nimages)[1:-1]]
            images = [Structure.from_file(contcar) for contcar in concar_list]

            # Update the two ending "images".
            images.insert(0, Structure.from_file("00/POSCAR"))
            images.append(Structure.from_file("{:02}/POSCAR".format(nimages - 1)))
            images = [s.as_dict() for s in images]
            neb = fw_spec.get("neb")
            neb.append(images)
            update_spec = {"neb": neb, "_queueadapter": {"nnodes": str(len(images) - 2),
                                                         "nodes": str(len(images) - 2)}}
            # Use neb walltime if it is in fw_spec
            if fw_spec["neb_walltime"] is not None:
                update_spec["_queueadapter"].update({"walltime": fw_spec.get("neb_walltime")})

        elif label in ["ep0", "ep1"]:
            # Update relaxed endpoint structures.
            file = glob.glob("CONTCAR*")[0]
            ep = Structure.from_file(file, False)  # One endpoint

            if fw_spec.get("incar_images"):  # "incar_images": pre-defined image number.
                update_spec = {label: ep.as_dict(),
                               "_queueadapter": {"nnodes": fw_spec["incar_images"],
                                                 "nodes": fw_spec["incar_images"]}}
            else:
                # Calculate number of images if "IMAGES" tag is not provided.
                index = int(label[-1])
                ep_1_dict = fw_spec.get("ep{}".format(1 - index))  # Another endpoint
                try:
                    ep_1 = Structure.from_dict(ep_1_dict)
                except:
                    ep_1 = ep_1_dict

                max_dist = max(get_endpoint_dist(ep, ep_1))
                nimages = round(max_dist / d_img) or 1
                update_spec = {label: ep, "_queueadapter": {"nnodes": int(nimages),
                                                            "nodes": int(nimages)}}
            # Use neb walltime if it is in fw_spec
            if fw_spec["neb_walltime"] is not None:
                update_spec["_queueadapter"].update({"walltime": fw_spec.get("neb_walltime")})

        else:  # label == "parent"
            f = glob.glob("CONTCAR*")[0]
            s = Structure.from_file(f, False)
            ep0, ep1 = get_endpoints_from_index(s, fw_spec["site_indices"])

            update_spec = {"parent": s.as_dict(), "ep0": ep0.as_dict(), "ep1": ep1.as_dict()}

        # Clear current directory.
        for d in os.listdir(src_dir):
            try:
                os.remove(os.path.join(src_dir, d))
            except:
                shutil.rmtree(os.path.join(src_dir, d))

        return FWAction(update_spec=update_spec)
예제 #57
0
import sys

from pymatgen.core import Molecule, Structure
from pymatgen.io.vasp.inputs import Poscar

from mpinterfaces.interface import Interface, Ligand

if __name__ == '__main__':
    # PbS 100 surface with single hydrazine as ligand
    # strt=get_struct_from_mp("PbS",MAPI_KEY=MAPI_KEY) 
    # using smiles_to_xyz.py you can obtain molecule xyz
    # using openbabel.  
    # example structure files are provided and set in dev_scripts
    # bulk structure of slab
    strt = Structure.from_file("dev_scripts/POSCAR_PbS")
    # pre-relaxed Ligand in a box
    mol_struct = Structure.from_file("dev_scripts/POSCAR_TCPO")
    mol = Molecule(mol_struct.species, mol_struct.cart_coords)
    hydrazine = Ligand([mol])

    # intital supercell, this wont be the final supercell if
    # surface coverage is specified
    supercell = [1, 1, 1]

    # miller index
    hkl = [1, 0, 0]

    # minimum slab thickness in Angstroms
    min_thick = 19
예제 #58
0
import sys

from pymatgen.core import Structure
from pymatgen.io.vasp.inputs import Poscar

from mpinterfaces.interface import Interface

 
if __name__=='__main__':
    # input structure file: bulk
    fin = 'POSCAR.bulk'
    # output file name
    fout = 'POSCAR'
    hkl = [0,0,1] # hkl wrt the input structure
    min_thick = 15 # angstroms
    min_vac = 30 # angstroms
    #use ase to create an orthogonal slab
    bulk = Structure.from_file(fin) 
    iface = Interface(bulk, hkl=hkl, 
                      min_thick=min_thick, min_vac=min_vac,
                      primitive= False, from_ase = True)
    iface.create_interface()
    iface.sort()
    #set selective dynamics flags
    # 1 --> T and 0 --> F
    sd_flags = [[1,1,1]  for i in iface.sites]
    iface_poscar = Poscar(iface, selective_dynamics= sd_flags)
    #write to file
    iface_poscar.write_file(fout)
"""
import shutil as shu

from pymatgen.io.vaspio.vasp_input import Incar, Poscar, Potcar, Kpoints
from pymatgen.core import Structure, Molecule


from mpinterfaces.interface import Interface, Ligand

        


#create ligand, interface and slab from the starting POSCARs


strt= Structure.from_file("POSCAR_PbS_bulk_with_vdw")  #using POSCAR of vdW relaxed PbS
mol_struct= Structure.from_file("POSCAR_DMF")    #using POSCAR of vdW relaxed PbS
mol= Molecule(mol_struct.species, mol_struct.cart_coords)
DMF= Ligand([mol])   #create Ligand DMF 
supercell = [1,1,1]
# slab thickness and vacuum set manual for now to converged values, surface coverage fixed at 0.014 ligand/sq.Angstrom 
#for consistency, best ligand spacing at the coverage 
min_thick= 19
min_vac= 12
surface_coverage= 0.014
#hkl of facet to reproduce
hkl= [1,0,0]
# specify the species on slab to adsorb over 
slab_species= 'Pb'
# specify the species onb ligand serving as the bridge atom 
adatom_on_ligand= 'O' 
예제 #60
0
    def test_sublattice_generation(self):
        struc = PymatgenTest.get_structure("CsCl")
        sc_struc = struc.copy()
        sc_struc.make_supercell(3)

        # test for vacancy and sub (should not change structure)
        Cs_index = sc_struc.indices_from_symbol("Cs")[0]
        cs_vac = Vacancy(sc_struc, sc_struc[Cs_index])
        decorated_cs_vac = create_saturated_interstitial_structure(cs_vac)
        self.assertEqual(len(decorated_cs_vac), len(sc_struc))

        Cl_index = sc_struc.indices_from_symbol("Cl")[0]

        cl_vac = Vacancy(sc_struc, sc_struc[Cl_index])
        decorated_cl_vac = create_saturated_interstitial_structure(cl_vac)
        self.assertEqual(len(decorated_cl_vac), len(sc_struc))

        sub_site = PeriodicSite("Sr", sc_struc[Cs_index].coords, sc_struc.lattice,
                                coords_are_cartesian=True)

        sub = Substitution(sc_struc, sub_site)
        decorated_sub = create_saturated_interstitial_structure(sub)
        self.assertEqual(len(decorated_sub), len(sc_struc))

        # test interstitial in symmorphic structure type
        inter_site = PeriodicSite("H", [0., 1.05225, 2.1045], struc.lattice,
                                  coords_are_cartesian=True)  # voronoi type
        interstitial = Interstitial(struc, inter_site)
        decorated_inter = create_saturated_interstitial_structure(interstitial)
        self.assertEqual(len(decorated_inter), 14)

        inter_site = PeriodicSite("H", [0.10021429, 0.10021429, 2.1045], struc.lattice,
                                  coords_are_cartesian=True)  # InFit type
        interstitial = Interstitial(struc, inter_site)
        decorated_inter = create_saturated_interstitial_structure(interstitial)
        self.assertEqual(len(decorated_inter), 14)

        inter_site = PeriodicSite("H", [4.10878571, 1.10235714, 2.1045], struc.lattice,
                                  coords_are_cartesian=True)  # InFit type
        interstitial = Interstitial(struc, inter_site)
        decorated_inter = create_saturated_interstitial_structure(interstitial)
        self.assertEqual(len(decorated_inter), 26)

        inter_site = PeriodicSite("H", [0., 0., 0.5], struc.lattice,
                                  coords_are_cartesian=False)  # a reasonable guess type
        interstitial = Interstitial(struc, inter_site)
        decorated_inter = create_saturated_interstitial_structure(interstitial)
        self.assertEqual(len(decorated_inter), 5)

        # test interstitial in non-symmorphic structure type
        # (voronoi and InFit generator of different types...)
        ns_struc = Structure.from_file(os.path.join(test_dir, "CuCl.cif"))

        inter_site = PeriodicSite("H", [0.45173594, 0.41157895, 5.6604067], ns_struc.lattice,
                                  coords_are_cartesian=True)  # InFit type
        interstitial = Interstitial(ns_struc, inter_site)
        decorated_inter = create_saturated_interstitial_structure(interstitial)
        self.assertEqual(len(decorated_inter), 40)

        inter_site = PeriodicSite("H", [0.47279906, 0.82845998, 5.62015285], ns_struc.lattice,
                                  coords_are_cartesian=True)  # InFit type
        interstitial = Interstitial(ns_struc, inter_site)
        decorated_inter = create_saturated_interstitial_structure(interstitial)
        self.assertEqual(len(decorated_inter), 40)

        inter_site = PeriodicSite("H", [0.70845255, 6.50298148, 5.16979425], ns_struc.lattice,
                                  coords_are_cartesian=True)  # InFit type
        interstitial = Interstitial(ns_struc, inter_site)
        decorated_inter = create_saturated_interstitial_structure(interstitial)
        self.assertEqual(len(decorated_inter), 40)

        inter_site = PeriodicSite("H", [0.98191329, 0.36460337, 4.64718203], ns_struc.lattice,
                                  coords_are_cartesian=True)  # InFit type
        interstitial = Interstitial(ns_struc, inter_site)
        decorated_inter = create_saturated_interstitial_structure(interstitial)
        self.assertEqual(len(decorated_inter), 40)

        inter_site = PeriodicSite("H", [0.39286561, 3.92702149, 1.05802631], ns_struc.lattice,
                                  coords_are_cartesian=True)  # InFit type
        interstitial = Interstitial(ns_struc, inter_site)
        decorated_inter = create_saturated_interstitial_structure(interstitial)
        self.assertEqual(len(decorated_inter), 40)