Beispiel #1
0
 def test_write(self):
     ref_log = Logfile.from_file(os.path.join(tests_fol, "log-HCN.yaml"))
     lname = "dummy.yaml"
     ref_log.write(lname)
     new_log = Logfile.from_file(lname)
     for log1, log2 in zip(ref_log, new_log):
         assert log1.inputparams == log2.inputparams
         assert log1.posinp == log2.posinp
     os.remove(lname)
def run(posinp, i, args, param, pseudos):
    try:
        os.makedirs("{}_{:06}".format(args.name, i))
        os.chdir("{}_{:06}".format(args.name, i))
        job = Job(name=args.name,
                  posinp=posinp,
                  inputparams=param,
                  pseudos=pseudos)
        job.run(nmpi=args.nmpi)
        copyfile(
            "forces_{}.xyz".format(args.name),
            "../../saved_results/{:06}.xyz".format(i),
        )
        os.chdir("../")
    except OSError:
        os.chdir("{}_{:06}".format(args.name, i))
        try:
            log = Logfile.from_file("log-" + args.name + ".yaml")
            print("Calculation {:06} was complete.\n".format(i))
        except:
            job = Job(name=args.name,
                      posinp=posinp,
                      inputparams=param,
                      pseudos=pseudos)
            job.run(args.nmpi, restart_if_incomplete=True)
            copyfile(
                "forces_{}.xyz".format(args.name),
                "../../saved_results/{:06}.xyz".format(i),
            )
        os.chdir("../")
Beispiel #3
0
 def test_run_with_dry_run(self):
     with Job(inputparams=self.inp, name="dry_run", run_dir="tests") as job:
         # Run the calculation
         job.clean()
         assert not job.is_completed
         job.run(dry_run=True, nmpi=2, nomp=4)
         assert job.is_completed
         # There must be input and output files afterwards
         new_inp = InputParams.from_file(job.input_name)
         assert new_inp == self.inp
         new_pos = Posinp.from_file(job.posinp_name)
         assert new_pos == self.pos
         bigdft_tool_log = Logfile.from_file(job.logfile_name)
         assert bigdft_tool_log.energy is None
Beispiel #4
0
 def test_run_with_dry_run_with_posinp(self):
     with Job(inputparams=self.inp,
              posinp=self.pos,
              name="dry_run",
              run_dir="tests") as job:
         job.clean()
         assert not job.is_completed
         job.run(dry_run=True, nmpi=2, nomp=4)
         assert job.is_completed
         # Make sure that input, posinp and output files are created
         new_inp = InputParams.from_file(job.input_name)
         assert new_inp == self.inp
         new_pos = Posinp.from_file(job.posinp_name)
         assert new_pos == self.pos
         bigdft_tool_log = Logfile.from_file(job.logfile_name)
         assert bigdft_tool_log.energy is None
Beispiel #5
0
class TestJob:

    # Extract the input and posinp from an N2 calculation of bad quality
    logname = os.path.join("tests", "log-warnings.yaml")
    log = Logfile.from_file(logname)
    inp = log.inputparams
    pos = log.posinp
    job = Job(inputparams=inp, posinp=pos)
    job_with_name = Job(inputparams=inp, posinp=pos, name="test")

    @pytest.mark.parametrize("attr, expected", [("inputparams", inp),
                                                ("posinp", pos),
                                                ("is_completed", False),
                                                ("input_name", "input.yaml"),
                                                ("posinp_name", "posinp.xyz"),
                                                ("logfile", {}),
                                                ("logfile_name", "log.yaml"),
                                                ("data_dir", "data"),
                                                ("ref_data_dir", None),
                                                ("run_dir", "MyBigDFT")])
    def test_init(self, attr, expected):
        if "_dir" in attr and attr != "ref_data_dir":
            value = getattr(self.job, attr)
            value = os.path.basename(os.path.normpath(value))
            assert value == expected
        else:
            assert getattr(self.job, attr) == expected

    @pytest.mark.parametrize("attr, expected", [
        ("inputparams", inp),
        ("posinp", pos),
        ("is_completed", False),
        ("input_name", "test.yaml"),
        ("posinp_name", "test.xyz"),
        ("logfile", {}),
        ("logfile_name", "log-test.yaml"),
        ("data_dir", "data-test"),
        ("ref_data_dir", None),
        ("run_dir", "MyBigDFT"),
    ])
    def test_init_with_name(self, attr, expected):
        if "_dir" in attr and attr != "ref_data_dir":
            value = getattr(self.job_with_name, attr)
            value = os.path.basename(os.path.normpath(value))
            assert value == expected
        else:
            assert getattr(self.job_with_name, attr) == expected

    def test_init_with_posinp_only(self):
        assert Job(posinp=self.pos).inputparams == {}

    def test_init_with_skip(self):
        j = Job(inputparams=self.inp, skip=True)
        cmd = j.bigdft_cmd
        to_str = "{} " * len(cmd)
        cmd = to_str.format(*cmd)
        assert "-s Yes" in cmd

    def test_init_without_posinp_raises_ValueError(self):
        with pytest.raises(ValueError, match="provide initial positions"):
            Job()

    def test_init_with_different_posinp_in_inputparams_raises_ValueError(self):
        with pytest.raises(ValueError, match="do not define the same posinp."):
            Job(inputparams=self.inp,
                posinp=Posinp.from_file("tests/surface.xyz"))

    @pytest.mark.parametrize("attr", [
        "inputparams",
        "posinp",
        "logfile",
        "ref_data_dir",
        "is_completed",
        "input_name",
        "posinp_name",
        "logfile_name",
        "bigdft_cmd",
        "bigdft_tool_cmd",
        "init_dir",
        "run_dir",
        "data_dir",
    ])
    def test_cannot_set_attributes(self, attr):
        with pytest.raises(AttributeError):
            setattr(self.job, attr, 1)

    @pytest.mark.filterwarnings("ignore::UserWarning")
    def test_run(self):
        with Job(inputparams=self.inp, run_dir="tests",
                 name='warnings') as job:
            job.run()
        assert job.is_completed
        assert self.inp["dft"].get("inputpsiid") is None
        assert np.isclose(job.logfile.energy, -191.74377352940274)

    @pytest.mark.filterwarnings("ignore::UserWarning")
    def test_run_with_force_run(self):
        new_inp = deepcopy(self.inp)
        new_inp["output"] = {"orbitals": "binary"}
        with Job(inputparams=new_inp, run_dir="tests",
                 name="write_orbs") as job:
            assert not job.is_completed
            job.run(force_run=True, nmpi=2, nomp=4)
            assert job.is_completed
            job.clean()
        assert self.inp["dft"].get("inputpsiid") is None
        assert np.isclose(job.logfile.energy, -191.74377352940274)

    @pytest.mark.filterwarnings("ignore::UserWarning")
    def test_run_with_force_run_and_inp_and_pos(self):
        with Job(inputparams=self.inp,
                 posinp=self.pos,
                 run_dir="tests",
                 name="runtest") as job:
            assert not job.is_completed
            job.run(force_run=True)
            assert job.is_completed
        assert self.inp["dft"].get("inputpsiid") is None
        assert np.isclose(job.logfile.energy, -191.74377352940274)

    @pytest.mark.filterwarnings("ignore::UserWarning")
    def test_run_with_ref_data_dir(self):
        with Job(inputparams=self.inp,
                 posinp=self.pos,
                 ref_data_dir="data-write_orbs",
                 run_dir="tests",
                 name="with_ref_data_dir") as job:
            assert self.inp["dft"].get("inputpsiid") is None
            assert job.inputparams["dft"].get("inputpsiid") is None
            assert not job.is_completed
            job.run(force_run=True)
            assert job.is_completed
            assert job.inputparams["dft"].get("inputpsiid") == 2
            assert self.inp["dft"].get("inputpsiid") is None
            job.run(force_run=True)
            assert job.is_completed
        assert np.isclose(job.logfile.energy, -191.74377352940274)

    @pytest.mark.filterwarnings("ignore::UserWarning")
    def test_run_with_non_existing_ref_data_dir(self):
        with Job(inputparams=self.inp,
                 posinp=self.pos,
                 ref_data_dir="unknown_data_dir",
                 run_dir="tests",
                 name="with_unknown_ref_data_dir") as job:
            assert self.inp["dft"].get("inputpsiid") is None
            assert job.inputparams["dft"].get("inputpsiid") is None
            assert not job.is_completed
            assert job.ref_data_dir is not None
            assert not os.path.exists(job.ref_data_dir)
            job.run(force_run=True)
            assert job.is_completed
        assert np.isclose(job.logfile.energy, -191.74377352940274)

    def test_run_raises_ValueError_when_incomplete_logfile(self):
        with Job(inputparams=self.inp,
                 posinp=self.pos,
                 run_dir="tests",
                 name="incomplete") as job:
            shutil.copyfile(job.logfile_name + ".ref", job.logfile_name)
            with pytest.raises(ValueError,
                               message="The logfile is incomplete!"):
                job.run(restart_if_incomplete=False)

    @pytest.mark.filterwarnings("ignore::UserWarning")
    def test_run_restart_if_incomplete(self):
        with Job(inputparams=self.inp,
                 posinp=self.pos,
                 run_dir="tests",
                 name="incomplete") as job:
            shutil.copyfile(job.logfile_name + ".ref", job.logfile_name)
            assert not job.is_completed
            job.run(restart_if_incomplete=True)
            assert job.is_completed
            job.clean()
        assert np.isclose(job.logfile.energy, -191.74377352940274)

    def test_run_exceeds_timeout_raises_RuntimeError(self):
        inp = InputParams({"dft": {"rmult": [9, 12], "hgrids": 0.25}})
        with Job(inputparams=inp,
                 posinp=self.pos,
                 run_dir="tests",
                 name="long-run") as job:
            job.clean()
            assert not job.is_completed
            with pytest.raises(RuntimeError):
                job.run(timeout=1.5 / 60, force_run=True)

    def test_clean(self):
        with Job(inputparams=self.inp, name="dry_run", run_dir="tests") as job:
            job.write_input_files()
            job.clean(logfiles_dir=True, data_dir=True)
            assert not os.path.exists(job.posinp_name)
            assert not os.path.exists(job.input_name)
            assert not os.path.exists(job.logfile_name)
            assert not os.path.exists("logfiles")
            assert not os.path.exists("data-dry_run")
            assert not job.is_completed

    @pytest.mark.filterwarnings("ignore::UserWarning")
    def test_run_with_dry_run(self):
        with Job(inputparams=self.inp, name="dry_run", run_dir="tests") as job:
            # Run the calculation
            job.clean()
            assert not job.is_completed
            job.run(dry_run=True, nmpi=2, nomp=4)
            assert job.is_completed
            # There must be input and output files afterwards
            new_inp = InputParams.from_file(job.input_name)
            assert new_inp == self.inp
            new_pos = Posinp.from_file(job.posinp_name)
            assert new_pos == self.pos
            bigdft_tool_log = Logfile.from_file(job.logfile_name)
            assert bigdft_tool_log.energy is None

    @pytest.mark.filterwarnings("ignore::UserWarning")
    def test_run_with_dry_run_with_posinp(self):
        with Job(inputparams=self.inp,
                 posinp=self.pos,
                 name="dry_run",
                 run_dir="tests") as job:
            job.clean()
            assert not job.is_completed
            job.run(dry_run=True, nmpi=2, nomp=4)
            assert job.is_completed
            # Make sure that input, posinp and output files are created
            new_inp = InputParams.from_file(job.input_name)
            assert new_inp == self.inp
            new_pos = Posinp.from_file(job.posinp_name)
            assert new_pos == self.pos
            bigdft_tool_log = Logfile.from_file(job.logfile_name)
            assert bigdft_tool_log.energy is None

    def test__check_logfile_posinp(self):
        pos_name = os.path.join("tests", "surface.xyz")
        pos = Posinp.from_file(pos_name)
        with pytest.raises(UserWarning):
            with Job(posinp=pos, run_dir="tests") as job:
                job.run()

    @pytest.mark.filterwarnings("ignore::UserWarning")
    def test__check_logfile_inputparams(self):
        with pytest.raises(UserWarning):
            with Job(inputparams=InputParams(),
                     posinp=self.pos,
                     name="warnings",
                     run_dir="tests") as job:
                job.run()

    def test_posinp_with_inf(self):
        new_inp = InputParams({
            "posinp": {
                "units":
                "angstroem",
                "cell": [40, ".inf", 40],
                "positions": [
                    {
                        'N': [
                            2.97630782434901e-23, 6.87220595204354e-23,
                            0.0107161998748779
                        ]
                    },
                    {
                        'N': [
                            -1.10434491945017e-23, -4.87342174483075e-23,
                            1.10427379608154
                        ]
                    },
                ]
            }
        })
        with Job(inputparams=new_inp, name="test") as job:
            job.run(nmpi=6, nomp=3, dry_run=True)
            job.clean()
        assert job.logfile.boundary_conditions == 'surface'

    def test_run_raises_RuntimeError(self):
        # Error because two ".inf" in cell
        new_inp = InputParams({
            "posinp": {
                "units":
                "angstroem",
                "cell": [40, ".inf", ".inf"],
                "positions": [
                    {
                        'N': [
                            2.97630782434901e-23, 6.87220595204354e-23,
                            0.0107161998748779
                        ]
                    },
                    {
                        'N': [
                            -1.10434491945017e-23, -4.87342174483075e-23,
                            1.10427379608154
                        ]
                    },
                ]
            }
        })
        with pytest.raises(RuntimeError):
            with Job(inputparams=new_inp, run_dir="tests/dummy") as job:
                job.run(force_run=True)

    def test_dry_run_raises_RuntimeError(self):
        # Error because two ".inf" in cell
        new_inp = InputParams({
            "posinp": {
                "units":
                "angstroem",
                "cell": [40, ".inf", ".inf"],
                "positions": [
                    {
                        'N': [
                            2.97630782434901e-23, 6.87220595204354e-23,
                            0.0107161998748779
                        ]
                    },
                    {
                        'N': [
                            -1.10434491945017e-23, -4.87342174483075e-23,
                            1.10427379608154
                        ]
                    },
                ]
            }
        })
        with pytest.raises(RuntimeError):
            with Job(inputparams=new_inp, run_dir="tests/dummy") as job:
                job.run(dry_run=True)
Beispiel #6
0
class TestPosinp:

    # Posinp with surface boundary conditions
    surface_filename = os.path.join(tests_fol, "surface.xyz")
    pos = Posinp.from_file(surface_filename)
    # Posinp with free boundary conditions
    free_filename = os.path.join(tests_fol, "free.xyz")
    free_pos = Posinp.from_file(free_filename)
    # Posinp read from a string
    string = """\
4   atomic
free
C    0.6661284109   0.000000000   1.153768252
C    3.330642055    0.000000000   1.153768252
C    4.662898877    0.000000000   3.461304757
C    7.327412521    0.000000000   3.461304757"""
    str_pos = Posinp.from_string(string)
    # Posinp read from an N2 calculation of bad quality
    log_pos = Logfile.from_file(logname).posinp
    # Posinp read from an InputParams instance with surface BC
    surf_inp = InputParams({
        'posinp': {
            'units': 'angstroem',
            'cell': [8.0, '.inf', 8.0],
            'positions': [{
                'C': [0.0, 0.0, 0.0]
            }]
        }
    })
    surf_pos = surf_inp.posinp
    # Posinp read from an InputParams instance with periodic BC
    per_inp = InputParams({
        'posinp': {
            'units': 'angstroem',
            'cell': [8.0, 1.0, 8.0],
            'positions': [{
                'C': [0.0, 0.0, 0.0]
            }]
        }
    })
    per_pos = per_inp.posinp

    @pytest.mark.parametrize("value, expected", [
        (len(pos), 4),
        (pos.units, "reduced"),
        (len(pos), 4),
        (pos.boundary_conditions, "surface"),
        (pos.cell, [8.07007483423, 'inf', 4.65925987792]),
        (pos[0], Atom('C', [0.08333333333, 0.5, 0.25])),
    ])
    def test_from_file(self, value, expected):
        assert value == expected

    @pytest.mark.parametrize("value, expected", [
        (len(log_pos), 2),
        (log_pos.units, "angstroem"),
        (len(log_pos), 2),
        (log_pos.boundary_conditions, "free"),
        (log_pos.cell, None),
        (log_pos[0],
         Atom('N', [
             2.9763078243490115e-23, 6.872205952043537e-23, 0.01071619987487793
         ])),
    ])
    def test_from_Logfile(self, value, expected):
        assert value == expected

    @pytest.mark.parametrize("value, expected", [
        (len(surf_pos), 1),
        (surf_pos.units, "angstroem"),
        (len(surf_pos), 1),
        (surf_pos.boundary_conditions, "surface"),
        (surf_pos.cell, [8, "inf", 8]),
        (surf_pos[0], Atom('C', [0, 0, 0])),
    ])
    def test_from_surface_InputParams(self, value, expected):
        assert value == expected

    @pytest.mark.parametrize("value, expected", [
        (len(per_pos), 1),
        (per_pos.units, "angstroem"),
        (len(per_pos), 1),
        (per_pos.boundary_conditions, "periodic"),
        (per_pos.cell, [8, 1.0, 8]),
        (per_pos[0], Atom('C', [0, 0, 0])),
    ])
    def test_from_periodic_InputParams(self, value, expected):
        assert value == expected

    def test_from_string(self):
        assert self.str_pos == self.free_pos

    def test_repr(self):
        atoms = [Atom('C', [0, 0, 0]), Atom('N', [0, 0, 1])]
        new_pos = Posinp(atoms, units="angstroem", boundary_conditions="free")
        msg = "Posinp([Atom('C', [0.0, 0.0, 0.0]), Atom('N', [0.0, 0.0, "\
              "1.0])], 'angstroem', 'free', cell=None)"
        assert repr(new_pos) == msg

    def test_write(self):
        fname = os.path.join(tests_fol, "test.xyz")
        self.pos.write(fname)
        assert self.pos == Posinp.from_file(fname)
        os.remove(fname)

    def test_free_boundary_conditions_has_no_cell(self):
        assert self.free_pos.cell is None

    def test_translate_atom(self):
        new_pos = self.pos.translate_atom(0, [0.5, 0, 0])
        assert new_pos != self.pos
        assert new_pos[0] == Atom("C", [0.58333333333, 0.5, 0.25])

    @pytest.mark.parametrize("fname", [
        "free_reduced.xyz",
        "missing_atom.xyz",
        "additional_atom.xyz",
    ])
    def test_init_raises_ValueError(self, fname):
        with pytest.raises(ValueError):
            Posinp.from_file(os.path.join(tests_fol, fname))

    @pytest.mark.parametrize("to_evaluate", [
        "Posinp([Atom('C', [0, 0, 0])], 'bohr', 'periodic')",
        "Posinp([Atom('C', [0, 0, 0])], 'bohr', 'periodic', cell=[1, 1])",
        "Posinp([Atom('C', [0, 0, 0])], 'bohr', 'periodic', cell=[1,'inf',1])",
    ])
    def test_init_raises_ValueError2(self, to_evaluate):
        with pytest.raises(ValueError):
            eval(to_evaluate)

    def test_positions(self):
        expected = [7.327412521, 0.0, 3.461304757]
        pos1 = Posinp([Atom('C', expected)],
                      units="angstroem",
                      boundary_conditions="free")
        pos2 = pos1.translate_atom(0, [-7.327412521, 0.0, -3.461304757])
        assert np.allclose(pos1.positions, expected)
        assert np.allclose(pos2.positions, [0, 0, 0])

    def test___eq__(self):
        atom1 = Atom('N', [0.0, 0.0, 0.0])
        atom2 = Atom('N', [0.0, 0.0, 1.1])
        pos1 = Posinp([atom1, atom2], 'angstroem', 'free')
        pos2 = Posinp([atom2, atom1], 'angstroem', 'free')
        assert pos1 == pos2  # The order of the atoms in the list do not count
        assert pos1 != 1  # No error if other object is not a posinp

    def test_with_surface_boundary_conditions(self):
        # Two Posinp instances with surface BC are the same even if they
        # have a different cell size along y-axis
        pos_with_inf = Posinp([
            Atom('N', [
                2.97630782434901e-23, 6.87220595204354e-23, 0.0107161998748779
            ]),
            Atom('N', [
                -1.10434491945017e-23, -4.87342174483075e-23, 1.10427379608154
            ])
        ],
                              'angstroem',
                              'surface',
                              cell=[40, ".inf", 40])
        pos_wo_inf = Posinp([
            Atom('N', [
                2.97630782434901e-23, 6.87220595204354e-23, 0.0107161998748779
            ]),
            Atom('N', [
                -1.10434491945017e-23, -4.87342174483075e-23, 1.10427379608154
            ])
        ],
                            'angstroem',
                            'surface',
                            cell=[40, 40, 40])
        assert pos_with_inf == pos_wo_inf
        # They are obviously different if the cell size along the other
        # directions are not the same
        pos2_wo_inf = Posinp([
            Atom('N', [
                2.97630782434901e-23, 6.87220595204354e-23, 0.0107161998748779
            ]),
            Atom('N', [
                -1.10434491945017e-23, -4.87342174483075e-23, 1.10427379608154
            ])
        ],
                             'angstroem',
                             'surface',
                             cell=[20, "inf", 40])
        assert pos_with_inf != pos2_wo_inf
        # They still have the same BC
        assert \
            pos2_wo_inf.boundary_conditions == pos_with_inf.boundary_conditions
        # You can only have a cell with ".inf" in 2nd positiion to
        # initialize a calculation with surface BC without using a
        # Posinp instance
        inp_with_inf = InputParams({
            "posinp": {
                "units":
                "angstroem",
                "cell": [40, ".inf", 40],
                "positions": [
                    {
                        'N': [
                            2.97630782434901e-23, 6.87220595204354e-23,
                            0.0107161998748779
                        ]
                    },
                    {
                        'N': [
                            -1.10434491945017e-23, -4.87342174483075e-23,
                            1.10427379608154
                        ]
                    },
                ]
            }
        })
        assert pos_with_inf == inp_with_inf.posinp

    def test_to_centroid(self):
        atoms = [Atom('N', [0, 0, 0]), Atom('N', [0, 0, 1.1])]
        pos = Posinp(atoms, units="angstroem", boundary_conditions="free")
        expected_atoms = [Atom('N', [0, 0, -0.55]), Atom('N', [0, 0, 0.55])]
        expected_pos = Posinp(expected_atoms,
                              units="angstroem",
                              boundary_conditions="free")
        assert pos.to_centroid() == expected_pos

    def test_to_barycenter(self):
        atoms = [Atom('N', [0, 0, 0]), Atom('N', [0, 0, 1.1])]
        pos = Posinp(atoms, units="angstroem", boundary_conditions="free")
        expected_atoms = [Atom('N', [0, 0, -0.55]), Atom('N', [0, 0, 0.55])]
        expected_pos = Posinp(expected_atoms,
                              units="angstroem",
                              boundary_conditions="free")
        assert pos.to_barycenter() == expected_pos
Beispiel #7
0
 def test_GeoptLogfile(self):
     log_HCN = Logfile.from_file(os.path.join(tests_fol, "log-HCN.yaml"))
     assert isinstance(log_HCN, GeoptLogfile)
     assert len(log_HCN) == 9
     assert all([pos != log_HCN[0].posinp for pos in log_HCN.posinps[1:]])
     assert all([log_HCN.inputparams == doc.inputparams for doc in log_HCN])
Beispiel #8
0
 def test_test_GeoptLogfile_acceptable_though_incomplete(self):
     fname = os.path.join(tests_fol,
                          "log-geopt-acceptable-though-incomplete.yaml")
     log_H3CCN = Logfile.from_file(fname)
     assert isinstance(log_H3CCN, GeoptLogfile)
     assert len(log_H3CCN) == 15
Beispiel #9
0
 def test_init_log_with_warnings_warns_UserWarnings(self):
     with pytest.warns(UserWarning):
         Logfile.from_file("tests/log-warnings.yaml")
Beispiel #10
0
 def test_write(self):
     fname = os.path.join(tests_fol, "log-test.yaml")
     self.log.write(fname)
     log2 = Logfile.from_file(fname)
     assert log2 == self.log
Beispiel #11
0
 def test_init_raises_ValueError(self):
     incomplete_log = os.path.join(tests_fol, "log-incomplete.yaml.ref")
     with pytest.raises(ValueError):
         Logfile.from_file(incomplete_log)
Beispiel #12
0
class TestLogfile:

    # Logfile of an N2 calculation of bad quality
    log = Logfile.from_file(logname)

    @pytest.mark.parametrize("key, value", [
        ("Energy (Hartree)", -191.74377352940274),
        ("Number of MPI tasks", 2),
        ("OpenMP parallelization", True),
        ("Maximal OpenMP threads per MPI task", 16),
        ("Force Norm (Hartree/Bohr)", 448.63530538041755),
        ("Walltime since initialization", 1.835567),
    ])
    def test_from_file(self, key, value):
        assert self.log[key] == value

    @pytest.mark.parametrize("attr, value", [
        ("_walltime", 1.835567),
        ("_energy", -191.74377352940274),
        ("_n_at", 2),
        ("_boundary_conditions", "free"),
        ("_dipole", [0.69649, 0.69649, -2.4954]),
        ("_sdos", None),
        ("_magnetization", None),
        ("_pressure", None),
        ("_atom_types", ['N']),
    ])
    def test_attributes(self, attr, value):
        # Two asserts as one can get both attributes (say, _n_at and n_at)
        assert getattr(self.log, attr) == value
        assert getattr(self.log, attr[1:]) == value

    @pytest.mark.parametrize("attr, value", [
        ("_walltime", None),
        ("_energy", None),
        ("_n_at", None),
        ("_boundary_conditions", None),
        ("_dipole", None),
        ("_sdos", None),
        ("_magnetization", None),
        ("_pressure", None),
        ("_atom_types", None),
    ])
    def test_empty_logfile_attributes(self, attr, value):
        empty = Logfile()
        # Two asserts as one can get both attributes (say, _n_at and n_at)
        assert getattr(empty, attr) == value
        assert getattr(empty, attr[1:]) == value

    @pytest.mark.parametrize("name", ["n_at", "forces", "walltime"])
    def test_set_base_attributes_raises_AttributeError(self, name):
        with pytest.raises(AttributeError):
            setattr(self.log, name, getattr(self.log, name))

    def test_init_raises_ValueError(self):
        incomplete_log = os.path.join(tests_fol, "log-incomplete.yaml.ref")
        with pytest.raises(ValueError):
            Logfile.from_file(incomplete_log)

    def test_cannot_set_values_of_log_attr(self):
        with pytest.raises(TypeError):
            self.log['Walltime since initialization'] = 0

    def test_len(self):
        assert len(self.log) == 90

    @pytest.mark.filterwarnings("ignore::UserWarning")
    def test_write(self):
        fname = os.path.join(tests_fol, "log-test.yaml")
        self.log.write(fname)
        log2 = Logfile.from_file(fname)
        assert log2 == self.log

    def test_init_wrong_ixc_warns_UserWarning(self):
        self.log["dft"]["ixc"] = -101130
        with pytest.warns(UserWarning):
            self.log._check_psppar()
        self.log["dft"]["ixc"] = 1

    @pytest.mark.skipif(sys.version_info < (3, 0),
                        reason="requires python3 or higher; see: "
                        "https://github.com/pytest-dev/pytest/issues/2917")
    def test_init_log_with_warnings_warns_UserWarnings(self):
        with pytest.warns(UserWarning):
            Logfile.from_file("tests/log-warnings.yaml")

    @pytest.mark.parametrize("attr", [
        "n_at", "dipole", "forces", "pressure", "sdos", "energy",
        "boundary_conditions", "cell", "fermi_level", "astruct", "evals",
        "kpts", "gnrm_cv"
    ])
    def test___dir__(self, attr):
        assert attr in dir(self.log) and "_" + attr not in dir(self.log)

    @pytest.mark.filterwarnings("ignore::UserWarning")
    def test_inputparams(self):
        inp = log.inputparams
        expected = InputParams({
            'dft': {
                'rmult': [2, 4],
                'hgrids': 2.5,
                'itermax': 1,
                'disablesym': True
            },
            'posinp': {
                'units':
                'angstroem',
                'positions': [{
                    'N': [
                        2.9763078243490115e-23, 6.872205952043537e-23,
                        0.01071619987487793
                    ]
                }, {
                    'N': [
                        -1.1043449194501671e-23, -4.873421744830746e-23,
                        1.104273796081543
                    ]
                }],
                'properties': {
                    'format': 'xyz',
                    'source': 'N2.xyz'
                }
            }
        })
        assert inp == expected

    @pytest.mark.filterwarnings("ignore::UserWarning")
    def test_GeoptLogfile(self):
        log_HCN = Logfile.from_file(os.path.join(tests_fol, "log-HCN.yaml"))
        assert isinstance(log_HCN, GeoptLogfile)
        assert len(log_HCN) == 9
        assert all([pos != log_HCN[0].posinp for pos in log_HCN.posinps[1:]])
        assert all([log_HCN.inputparams == doc.inputparams for doc in log_HCN])

    @pytest.mark.filterwarnings("ignore::UserWarning")
    def test_test_GeoptLogfile_acceptable_though_incomplete(self):
        fname = os.path.join(tests_fol,
                             "log-geopt-acceptable-though-incomplete.yaml")
        log_H3CCN = Logfile.from_file(fname)
        assert isinstance(log_H3CCN, GeoptLogfile)
        assert len(log_H3CCN) == 15
Beispiel #13
0
from __future__ import absolute_import
import os
import sys
import pytest
import numpy as np
from mybigdft import InputParams, Posinp, Logfile, Atom
from mybigdft.iofiles.logfiles import GeoptLogfile

tests_fol = "tests"
# Result of an N2 calculation of very bad quality
logname = os.path.join(tests_fol, "log-warnings.yaml")
log = Logfile.from_file(logname)


class TestInputParams:

    filename = os.path.join(tests_fol, "test.yaml")

    @pytest.mark.parametrize("params, expected", [
        ({
            "dft": {
                "hgrids": 0.35
            }
        }, {
            "dft": {
                "hgrids": 0.35
            }
        }),
        ({
            "dft": {
                "hgrids": [0.45] * 3,