Esempio n. 1
0
    def test_distance(self, molecule, control_filepath, delete_tmp_dir):
        ms = MoleculeSystem(molecule, frozen_indices={2, 3})
        ms.add_distance(0, 1, weights=1.0, value=2.5)
        assert ms.has_inconsistencies()

        with temp_dir(delete_tmp_dir) as tmp_dir:
            ms.to_file("coord", fmt="coord")
            shutil.copy2(control_filepath, "control")
            dr = DefineRunner(parameters=dr_parameters)
            assert dr.run_update_internal_coords()

            ms_new = MoleculeSystem.from_file("coord")
            assert not ms_new.has_inconsistencies()

            # check that intdef is present and that the value has been updated
            assert len(ms_new.int_def) == 1
            assert ms_new.int_def[0].value == pytest.approx(
                ms.int_def[0].value, abs=1e-4)

            # check that there are the same user-defined bonds
            assert ms.user_defined_bonds == ms_new.user_defined_bonds

            # check that in redundant the coordinate has been taken into account
            dg = DataGroups.from_file("coord")
            redundant = dg.sdg("redundant", strict=True)
            assert re.search(r"\d+\s+f\s+1\.0+\s+stre\s+1\s+2\s+val=\s*2.5",
                             redundant)

            # check the presence of the same frozen atoms
            assert ms.frozen_indices == ms_new.frozen_indices

            assert str(ms_new.int_def[0])

            assert_MSONable(ms_new)
Esempio n. 2
0
    def test_from_file(self, control):
        """Testing instantiation."""

        # Check that we are actually getting an instance of Control
        assert isinstance(control, Control)

        dg_list_ref = [
            '$title\n', '$operating system unix\n', '$symmetry c1\n',
            '$user-defined bonds    file=coord\n', '$coord    file=coord\n',
            '$optimize\n'
            ' internal   off\n'
            ' redundant  off\n'
            ' cartesian  on\n'
            ' global     off\n'
            ' basis      off\n', '$end\n'
        ]
        assert control.dg_list == dg_list_ref
        assert str(control) == ''.join(dg_list_ref)
        assert_MSONable(control)

        # Test to_file and from_file
        with tempfile.TemporaryDirectory() as tmpdir:
            fname = os.path.join(tmpdir, 'control_test')
            control.to_file(filename=fname)
            control_from_file = Control.from_file(filename=fname)
            assert control.dg_list == control_from_file.dg_list
Esempio n. 3
0
def test_state():
    s = State(0.05, "a1", 1, Fraction(1), "a")
    s1 = State(0.05, "a1", 1, Fraction(1), "a")
    s2 = State(0.05, "t1", 1, Fraction(2))
    assert s != 1
    assert s == s1
    assert s.max_occupation == 1
    assert re.match(
        r"Eigenvalue: [.\d]+, irrep: a1, index: 1, spin: a, occupation: 1",
        str(s))
    assert s2.has_fractional_occ
    assert s2.max_occupation == 6
    assert_MSONable(s)
    assert_MSONable(s2)
Esempio n. 4
0
    def test_energy_mp2(self, testdir, delete_tmp_dir):
        with temp_dir(delete_tmp_dir):
            shutil.copy2(os.path.join(testdir, 'control', 'energy_test-mp2'),
                         'energy')
            energy = Energy.from_file()
            assert len(energy.scf) == 1
            assert energy.scf[0] == pytest.approx(-75.93827460490)
            assert energy.scfkin[0] == pytest.approx(75.9346807)
            assert energy.scfpot[0] == pytest.approx(-151.872955)
            assert energy.mp2[0] == pytest.approx(-0.1869672633349)
            assert energy.mp2[0] + energy.scf[0] == energy.total[0]
            assert energy.delta_e is None

            assert_MSONable(energy)

            if has_matplotlib():
                assert energy.plot(show=False)
Esempio n. 5
0
def test_closed(mo_dirpath, delete_tmp_dir):
    with temp_dir(delete_tmp_dir):
        for f in ["mos", "control"]:
            shutil.copy2(os.path.join(mo_dirpath, f), f)

        s = States.from_file()

        assert len(s) == 14
        assert s[0].eigenvalue == pytest.approx(-13.968369531218)

        assert_MSONable(s)

        eiger_out = EigerOutput.from_file(os.path.join(mo_dirpath, "eiger"))

        assert eiger_out.compare_states(s) is None

        assert not s.is_uhf
        assert not s.has_hole

        assert s.total_electrons == 10
        assert s.irreps[0] == "a1"
        assert s.occupations[0] == 2
        assert s.spins[0] is None
        assert s.eigenvalues[-1] == pytest.approx(2.55164050421)
        assert s.irrep_indices[0] == 1

        assert str(s)

        # test filter
        s = States.from_file()
        with pytest.raises(ValueError):
            s.filter_states(spin="a", irrep="a1")

        assert len(s.filter_states(irrep="z")) == 0
        filtered = s.filter_states(irrep="a1")
        assert filtered[0].irrep == "a1"

        # test get_shells
        s = States.from_file()
        with pytest.raises(ValueError):
            s.get_shells(spin="a")

        shell = s.get_shells()
        assert shell.occupations[0] == 2
        assert shell.states[0] == ("a1", 1)
Esempio n. 6
0
    def test_gradient(self, testdir, delete_tmp_dir):
        with temp_dir(delete_tmp_dir):
            shutil.copy2(
                os.path.join(testdir, 'control', 'gradient_test-gradient'),
                'gradient')
            g = Gradient.from_file()
            assert len(g.molecules) == 6
            assert g.gradients[0, 1, 0] == pytest.approx(-0.02705094211381)
            assert g.energies[-1] == pytest.approx(-76.3449460148)
            assert g.norms[1] == pytest.approx(0.013946816251742454)
            assert g.max_gradients[-1] == pytest.approx(3.8028925027729e-05)
            assert g.n_steps == 6
            assert g.last_grad_norm == pytest.approx(5.145114095400708e-05)
            assert g.last_grad_max == pytest.approx(3.8028925027729e-05)

            assert_MSONable(g)

            if has_matplotlib():
                assert g.plot(show=False)
Esempio n. 7
0
    def test_uhf(self, testdir):
        alpha = """
 a1      1-3                                    ( 1 )
 b1      1                                      ( 1 )
 b2      1                                      ( 1 )        
        """
        s = Shells.from_string(alpha)
        assert len(s.states) == 5
        assert s.states[0] == ("a1", 1)
        assert s.states[3] == ("b1", 1)
        assert s.occupations[0] == 1
        assert s.total_electrons == 5
        assert check_equivalent_dg(alpha, s.to_datagroup())
        assert_MSONable(s)

        beta = """
 a1      1-3                                    ( 1 )
 b1      1,3                                    ( 1 )
        """

        s = Shells.from_string(beta)
        assert len(s.states) == 5
        assert s.states[4] == ("b1", 3)
        assert s.total_electrons == 5
        assert check_equivalent_dg(beta, s.to_datagroup())

        alpha = """
a1      1,3-5,7-8                              ( 1 )
a1      9                                      ( 1 / 2 )
b2      1-2,5,7,10-12                          ( 0.5 )        
       """
        s = Shells.from_string(alpha)
        assert len(s.states) == 14
        assert s.states[0] == ("a1", 1)
        assert s.states[3] == ("a1", 5)
        assert s.states[6] == ("a1", 9)
        assert s.states[9] == ("b2", 5)
        assert s.occupations[0] == 1
        assert s.occupations[6] == Fraction("1/2")
        assert s.occupations[9] == Fraction("1/2")
        assert s.total_electrons == 10
        assert check_equivalent_dg(alpha, s.to_datagroup())
Esempio n. 8
0
    def test_dummy_atoms(self, molecule_filepath):
        ms = MoleculeSystem.from_file(molecule_filepath, fmt="coord")
        mol = ms.molecule
        print(mol[-1].specie)
        print(mol[-1].specie.__class__)
        # Pymatgen's Specie and DummySpecie have been changed to Species and
        # DummySpecies in v2020.10.9. We keep testing both for backward compatibility.
        assert isinstance(mol[-1].specie, (DummySpecies, DummySpecie))
        assert mol[-1].specie.symbol == "Q"

        test_value2 = """
0.00000000000000 0.00000000000000 -0.12178983933899 o
1.41713420892173 0.00000000000000 0.96657854674257 h
-1.41713420892173 0.00000000000000 0.96657854674257 h
0.00000000000000 0.00000000000000 0.00000000000000 q
"""
        dg = DataGroups(ms.to_coord_string())
        assert len(dg.dg_list) == 2
        check_dg(dg.sdg("coord", strict=True), test_value2)

        assert_MSONable(ms)
Esempio n. 9
0
    def test_energy_scf(self, testdir, delete_tmp_dir):
        with temp_dir(delete_tmp_dir):
            shutil.copy2(
                os.path.join(testdir, 'control', 'energy_test-energy'),
                'energy')
            energy = Energy.from_file()
            assert len(energy.scf) == 4
            assert energy.n_steps == 4
            assert energy.scf[0] == pytest.approx(-10.48350884610)
            assert energy.scfkin[2] == pytest.approx(37.86647200156)
            assert energy.scfpot[1] == pytest.approx(-59.35016151450)
            assert energy.delta_e == pytest.approx(9.99999999577)
            assert energy.mp2 is None
            assert np.all(energy.scf == energy.total)

            assert_MSONable(energy)

            if has_matplotlib():
                assert energy.plot(show=False)

            energy_string = '      SCF               SCFKIN            SCFPOT\n' \
                            '1   -10.48350884610    39.86550149370   -50.34901033980\n' \
                            '2   -20.48350872544    38.86665278906   -59.35016151450\n' \
                            '\n' \
                            '3   -30.48350875500    37.86647200156   -68.34998075656\n' \
                            '4   -40.48350875077    36.86649728669   -77.35000603747\n'
            energy = Energy.from_string(energy_string)
            assert len(energy.scf) == 4
            assert energy.n_steps == 4
            assert energy.scf[0] == pytest.approx(-10.48350884610)
            assert energy.scfkin[2] == pytest.approx(37.86647200156)
            assert energy.scfpot[1] == pytest.approx(-59.35016151450)
            assert energy.delta_e == pytest.approx(9.99999999577)
            assert energy.mp2 is None
            assert np.all(energy.scf == energy.total)

            assert_MSONable(energy)

            if has_matplotlib():
                assert energy.plot(show=False)
Esempio n. 10
0
    def test_closed(self, testdir, delete_tmp_dir):
        with temp_dir(delete_tmp_dir):
            shutil.copy2(
                os.path.join(testdir, 'control', 'control_test-subfiles'),
                "control")
            with pytest.raises(ValueError):
                Shells.from_file("alpha")
            s = Shells.from_file("closed")

            assert len(s.states) == 3
            assert s.states[0] == ("a1", 1)
            assert s.occupations[0] == 2
            assert "a1" in s.irreps
            assert "t2" in s.irreps
            assert len(s.irreps) == 2
            assert s.total_electrons == 10

            original = Control.from_file().sdg("closed shells")
            generated = s.to_datagroup()
            assert check_equivalent_dg(original, generated)

            assert_MSONable(s)
Esempio n. 11
0
    def test_add_distance(self, molecule):
        ms = MoleculeSystem(molecule)
        ms.add_distance(1, 2)
        assert not ms.has_inconsistencies()
        assert len(ms.user_defined_bonds) == 1
        ms.add_distance(0,
                        1,
                        status="k",
                        add_user_def_bonds=False,
                        value=2.058455873547)
        assert not ms.has_inconsistencies()
        assert len(ms.user_defined_bonds) == 1

        ms.add_distance(2, 3, value=10, weights=1.0)
        assert ms.has_inconsistencies()

        ms.add_distance([0, 1], [2, 3])
        assert len(ms.int_def[-1].indices) == 2

        with pytest.raises(ValueError):
            ms.add_distance([1, 2, 3], [1, 2])

        assert_MSONable(ms)
Esempio n. 12
0
    def test_from_string(self):
        # basic test
        string = """
$coord
 .00000000000000       .00000000000000       .00000000000000      n       
-1.15103063747470     -1.99364354517457       .00000000000000      o       
2.30206127494940       .00000000000000       .00000000000000      o       
-1.15103063747470      1.99364354517457       .00000000000000      o       
$end        
"""

        ms = MoleculeSystem.from_string(string=string, fmt="coord")

        mol = ms.molecule
        assert mol[1].coords[0] == pytest.approx(-0.6090991821345737)
        assert len(mol) == 4

        assert len(ms.frozen_indices) == 0

        assert_MSONable(ms)

        # no coord
        with pytest.raises(ValueError,
                           match=r'^The string does not contain \$coord!$'):
            MoleculeSystem.from_string(string="$end", fmt="coord")

        # with frozen and internal definitions
        string = """
$coord
 .00000000000000       .00000000000000       .00000000000000      n  f
-1.15103063747470     -1.99364354517457       .00000000000000      o       
2.30206127494940       .00000000000000       .00000000000000      o       
-1.15103063747470      1.99364354517457       .00000000000000      o f       
$intdef
# definitions of internal coordinates

1 k  1.0000000000000 stre    1    2           val=   2.43987
2 f  1.0000000000000 bend    1    2  3        
     -0.5000000000000 bend    2    3  4        
$end        
"""
        ms = MoleculeSystem.from_string(string=string, fmt="coord")
        mol = ms.molecule
        assert mol[1].coords[0] == pytest.approx(-0.6090991821345737)
        assert len(mol) == 4

        assert ms.frozen_indices == {0, 3}

        assert len(ms.int_def) == 2
        assert ms.int_def[0].value == pytest.approx(2.43987)
        assert ms.int_def[1].value == None
        assert ms.int_def[0].status == "k"
        assert ms.int_def[1].status == "f"
        assert ms.int_def[0].indices[0] == [0, 1]
        assert len(ms.int_def[1].indices) == 2
        assert ms.int_def[1].weights[1] == pytest.approx(-0.5)

        dg = DataGroups(ms.to_coord_string())
        dg_ref = DataGroups(string)
        assert len(dg.dg_list) == 3
        check_dg(dg.sdg("coord", strict=True), dg_ref.sdg("coord",
                                                          strict=True))
        check_dg(dg.sdg("intdef", strict=True),
                 dg_ref.sdg("intdef", strict=True))

        # with user-defined bonds
        string = """
$coord
 .00000000000000       .00000000000000       .00000000000000      n 
-1.15103063747470     -1.99364354517457       .00000000000000      o       
2.30206127494940       .00000000000000       .00000000000000      o       
-1.15103063747470      1.99364354517457       .00000000000000      o       
$user-defined bonds
1-2, 2 - 3,3|4      
$end        
"""
        ms = MoleculeSystem.from_string(string=string, fmt="coord")
        mol = ms.molecule
        assert mol[1].coords[0] == pytest.approx(-0.6090991821345737)
        assert len(mol) == 4

        assert ms.user_defined_bonds == {(0, "-", 1), (1, "-", 2), (2, "|", 3)}
        dg = DataGroups(ms.to_coord_string())
        dg_ref = DataGroups(string)
        assert len(dg.dg_list) == 3
        check_dg(dg.sdg("coord", strict=True), dg_ref.sdg("coord",
                                                          strict=True))
        check_user_defined_bonds_dg(
            dg.sdg("user-defined bonds", strict=True),
            dg_ref.sdg("user-defined bonds", strict=True))

        # malformed user-defined bonds
        string = """
$coord
 .00000000000000       .00000000000000       .00000000000000      n 
-1.15103063747470     -1.99364354517457       .00000000000000      o       
2.30206127494940       .00000000000000       .00000000000000      o       
-1.15103063747470      1.99364354517457       .00000000000000      o       
$user-defined bonds
1-2, 2 3,3|4      
$end        
"""
        with pytest.raises(ValueError,
                           match="Cannot parse user-defined bonds.*"):
            MoleculeSystem.from_string(string=string, fmt="coord")

        # from xyz format
        ms = MoleculeSystem.from_string(mol.to(fmt="xyz"), fmt="xyz")
        assert ms.molecule[1].coords[0] == pytest.approx(-0.6090991821345737)
Esempio n. 13
0
def test_uhf(mo_dirpath, delete_tmp_dir):
    with temp_dir(delete_tmp_dir):
        for f in ["alpha", "beta", "control"]:
            shutil.copy2(os.path.join(mo_dirpath, f), f)

        s = States.from_file()

        assert len(s) == 28
        assert s.n_states == 28
        assert s[0].eigenvalue == pytest.approx(-14.457427310212)

        assert_MSONable(s)

        eiger_out = EigerOutput.from_file(os.path.join(mo_dirpath, "eiger"))
        eiger_wrong_val = EigerOutput.from_file(
            os.path.join(mo_dirpath, "eiger_wrong_val"))
        eiger_wrong_length = EigerOutput.from_file(
            os.path.join(mo_dirpath, "eiger_wrong_length"))
        eiger_wrong_gap = EigerOutput.from_file(
            os.path.join(mo_dirpath, "eiger_wrong_gap"))
        eiger_wrong_nel = EigerOutput.from_file(
            os.path.join(mo_dirpath, "eiger_wrong_nelec"))
        eiger_wrong_occ = EigerOutput.from_file(
            os.path.join(mo_dirpath, "eiger_wrong_occ"))
        eiger_wrong_match = EigerOutput.from_file(
            os.path.join(mo_dirpath, "eiger_wrong_match"))

        assert eiger_out.compare_states(s) is None
        assert "gap" in eiger_wrong_gap.compare_states(s)
        assert "states" in eiger_wrong_length.compare_states(s)
        assert "eigenvalue" in eiger_wrong_val.compare_states(s)
        assert "electrons" in eiger_wrong_nel.compare_states(s)
        assert "occupation" in eiger_wrong_occ.compare_states(s)
        assert "match" in eiger_wrong_match.compare_states(s)

        assert s.is_uhf
        assert not s.has_hole

        assert s.total_electrons == 9
        assert s.irreps[0] == "a1"
        assert s.occupations[0] == 1
        assert s.spins[0] == "a"
        assert s.eigenvalues[-1] == pytest.approx(2.1425788573507)
        assert s.irrep_indices[0] == 1

        assert str(s)

        s.pop(0)
        assert len(s) == 27

        s[0] = s[1]
        assert s[0] == s[1]
        s.insert(0, s[-1])
        assert s[0] == s[-1]

        # test filter
        s = States.from_file()
        assert len(s.filter_states(irrep="z")) == 0
        filtered = s.filter_states(spin="b", irrep="a1")
        assert filtered[0].spin == "b"
        assert filtered[0].irrep == "a1"

        # test get_shells
        s = States.from_file()
        with pytest.raises(ValueError):
            s.get_shells(spin=None)

        shell = s.get_shells(spin="a")
        assert shell.occupations[0] == 1
        assert shell.states[0] == ("a1", 1)
Esempio n. 14
0
 def test_assert_MSONable(self):
     m = MSONableExample(1, 2)
     assert_MSONable(m)