Esempio n. 1
0
def test_cp2k_singlepoint_mock(mocker: MockFixture):
    """Mock a call to CP2K."""
    # single point calculation
    s = fill_cp2k_defaults(templates.singlepoint)

    # print orbitals
    s.specific.cp2k.force_eval.dft.print.mo.filename = (
        PATH / "orbitals.out").as_posix()
    s.specific.cp2k.force_eval.dft.print.mo.mo_index_range = "7 46"
    s.specific.cp2k.force_eval.dft.scf.added_mos = 20

    # Construct a result objects
    job = cp2k(s, ETHYLENE)
    jobname = "cp2k_job"
    run_mocked = mock_runner(mocker, jobname)
    rs = run_mocked(job)

    # electronic energy
    assertion.isfinite(rs.energy)

    # Molecular orbitals
    orbs = rs.orbitals
    assertion.assert_(np.isfinite, orbs.eigenvectors,
                      post_process=np.all)  # eigenvalues
    assertion.shape_eq(orbs.eigenvectors, (46, 40))
Esempio n. 2
0
def test_shape_eq() -> None:
    """Test :meth:`AssertionManager.shape_eq`."""
    ar1: np.ndarray = np.random.rand(10, 10)
    ar2: np.ndarray = np.random.rand(10, 10)
    shape = ar1.shape

    assertion.shape_eq(ar1, ar2)
    assertion.shape_eq(ar1, shape)
    assertion.shape_eq(ar1, (5,), invert=True)

    assertion.shape_eq(ar1, ar1, ar1, ar1, exception=TypeError)
    assertion.shape_eq(shape, ar1, exception=AttributeError)
Esempio n. 3
0
def test_orca_mock(mocker: MockFixture):
    """Mock a call to orca."""
    methanol = Molecule(PATH_MOLECULES / "methanol.xyz")

    s = Settings()
    s.specific.orca.main = "RKS B3LYP SVP Opt NumFreq TightSCF SmallPrint"
    # print the orbitals
    s.specific.orca.scf = " print[p_mos] 1"
    job = orca(s, methanol)

    run_mocked = mocker.patch("qmflows.run")
    jobname = "ORCAjob"
    dill_path = WORKDIR / jobname / "ORCAjob.dill"
    plams_dir = WORKDIR / jobname
    run_mocked.return_value = ORCA_Result(s,
                                          methanol,
                                          jobname,
                                          dill_path=dill_path,
                                          plams_dir=plams_dir)
    rs = run_mocked(job)

    assertion.isfinite(rs.energy)
    assertion.isfinite(rs.runtime)
    assertion.isfinite(np.sum(rs.dipole))
    # steps until convergence
    assertion.eq(rs.optcycles, 8)

    # Check that hessian is symmetric
    hess = rs.hessian
    assertion.isclose(np.sum(hess - hess.T), 0.0)

    # frequencies
    frequencies = rs.frequencies
    assertion.len_eq(frequencies, 18)

    # Normal modes
    normal_modes = rs.normal_modes
    assertion.shape_eq(normal_modes, (18, 18))

    # Orbitals
    orbs = rs.orbitals
    assert np.isfinite(np.sum(orbs.eigenvalues))  # eigenvalues

    # Molecule
    mol = rs.molecule
    assertion.isinstance(mol, Molecule)
    assertion.len_eq(mol, 6)  # there are 6 atoms
Esempio n. 4
0
def test_cp2k_md():
    """Test :mod:`FOX.examples.cp2k_md`."""
    file = join(PATH, 'armc.yaml')

    with open(file, 'r') as f:
        dct = yaml.load(f.read(), Loader=yaml.SafeLoader)
    armc, job_kwarg = dict_to_armc(dct)

    assertion.isinstance(armc, ARMC)
    validate_mapping(armc, key_type=tuple, value_type=np.ndarray)

    assertion.eq(armc._data, {})
    assertion.eq(armc.hdf5_file,
                 os.path.abspath('tests/test_files/MM_MD_workdir/armc.hdf5'))
    assertion.eq(armc.iter_len, 50000)
    assertion.is_(armc.keep_files, False)
    assertion.isinstance(armc.logger, Logger)

    for mol in armc.molecule:
        assertion.isinstance(mol, MultiMolecule)
        assertion.shape_eq(mol, (4905, 227, 3))
        assertion.eq(mol.dtype, float)

    iterator = (i for v in armc.package_manager.values() for i in v)
    for job_dict in iterator:
        assertion.isinstance(job_dict['settings'], QmSettings)
        np.testing.assert_allclose(np.array(job_dict['molecule']),
                                   armc.molecule[0][0])
        assertion.is_(job_dict['type'], cp2k_mm)

    assertion.isinstance(armc.pes['rdf.0'], functools.partial)
    assertion.eq(armc.pes['rdf.0'].keywords,
                 {'atom_subset': ['Cd', 'Se', 'O']})
    assertion.eq(armc.pes['rdf.0'].args, (MultiMolecule.init_rdf, ))

    phi_ref = PhiUpdater(a_target=0.25, gamma=2.0, phi=1.0, func=np.add)
    assertion.eq(armc.phi, phi_ref)

    assertion.eq(armc.sub_iter_len, 100)

    for i in job_kwarg['psf']:
        assertion.isinstance(i, PSFContainer)
    assertion.eq(job_kwarg['folder'], 'MM_MD_workdir')
    assertion.assert_(str.endswith, job_kwarg['path'],
                      join('tests', 'test_files'))
    assertion.assert_(str.endswith, job_kwarg['logfile'],
                      join('tests', 'test_files', 'MM_MD_workdir', 'armc.log'))
Esempio n. 5
0
def test_quadropole(tmp_path):
    """Test the calculation of a quadrupole."""
    file_path = PATH_TEST / "input_test_single_points.yml"
    config = process_input(file_path, 'single_points')
    path_original_hdf5 = config.path_hdf5
    path_test_hdf5 = (Path(tmp_path) / "multipoles.hdf5").as_posix()

    # copy the precomputed data to the temporal HDF5
    shutil.copyfile(path_original_hdf5, path_test_hdf5)
    config.path_hdf5 = path_test_hdf5

    mol = readXYZ((PATH_TEST / "ethylene.xyz").as_posix())
    matrix = compute_matrix_multipole(mol, config, "quadrupole")
    # The matrix contains the overlap + dipole + quadrupole
    assertion.shape_eq(matrix, (10, 46, 46))
    # Check that the matrices are symmetric
    for i in range(10):
        arr = matrix[i].reshape(46, 46)
        assertion.truth(np.allclose(arr, arr.T))
Esempio n. 6
0
def test_armc(name: str) -> None:
    """Test :class:`ARMC` and :class:`ARMCPT`."""
    file = PATH / name
    with open(file, 'r') as f:
        dct = yaml.load(f.read(), Loader=UniqueLoader)

    armc, job_kwargs = dict_to_armc(dct)
    if name == 'armc_ref.yaml':
        REF = ARMC_REF
        armc.package_manager.hook = iter(load_results(ARMC_REF, n=1))
    else:
        iterator = _get_phi_iter()

        def swap_phi(*args: Any, **kwargs: Any) -> List[Tuple[int, int]]:
            return next(iterator)

        REF = ARMCPT_REF
        armc.swap_phi = swap_phi
        armc.package_manager.hook = iter(load_results(ARMCPT_REF, n=3))

    hdf5_ref = REF / 'armc.hdf5'
    hdf5 = PATH / job_kwargs['folder'] / 'armc.hdf5'

    run_armc(armc, restart=False, **job_kwargs)
    assertion.assert_(next, armc.package_manager.hook, exception=StopIteration)
    with h5py.File(hdf5, 'r') as f1, h5py.File(hdf5_ref, 'r') as f2:
        compare_hdf5(f1, f2, skip={'/param', '/aux_error_mod'})
        assertion.shape_eq(f1['param'], f2['param'])
        assertion.shape_eq(f1['aux_error_mod'], f2['aux_error_mod'])
        assertion.eq(f1['param'].dtype, f2['param'].dtype)
        assertion.eq(f1['aux_error_mod'].dtype, f2['aux_error_mod'].dtype)

    # Validate that the non-charges are updated independently of each other
    with h5py.File(hdf5, 'r') as f1:
        _index = f1['param'].attrs['index'][0] != b"charge"
        index = np.nonzero(_index)[0]
        param = f1['param'][..., index]

        grad = param[:, 1:] - param[:, :-1]
        grad[grad < 1e-8] = 0
        assertion.le(np.count_nonzero(grad, axis=-1), 2, post_process=np.all)
Esempio n. 7
0
def test_armc_restart(name: str) -> None:
    """Test the restart functionality of :class:`ARMC` and :class:`ARMCPT`."""
    file = PATH / name
    with open(file, 'r') as f:
        dct = yaml.load(f.read(), Loader=UniqueLoader)

    sub_iter = 5
    super_iter = 8
    i = 2 + (super_iter * 10 + sub_iter)

    armc, job_kwargs = dict_to_armc(dct)
    if name == 'armc_ref.yaml':
        REF = ARMC_REF
        armc.package_manager.hook = iter(load_results(ARMC_REF, n=1)[i:])
    else:
        iterator = _get_phi_iter()

        def swap_phi(*args: Any, **kwargs: Any) -> List[Tuple[int, int]]:
            return next(iterator)

        REF = ARMCPT_REF
        armc.swap_phi = swap_phi
        armc.package_manager.hook = iter(load_results(ARMCPT_REF, n=3)[i:])

    _prepare_restart(REF, PATH / job_kwargs['folder'], super_iter, sub_iter)
    hdf5_ref = REF / 'armc.hdf5'
    hdf5 = PATH / job_kwargs['folder'] / 'armc.hdf5'

    run_armc(armc, restart=True, **job_kwargs)
    assertion.assert_(next, armc.package_manager.hook, exception=StopIteration)
    with h5py.File(hdf5, 'r') as f1, h5py.File(hdf5_ref, 'r') as f2:
        compare_hdf5(f1, f2, skip={'/param', '/aux_error_mod'})
        assertion.shape_eq(f1['param'], f2['param'])
        assertion.shape_eq(f1['aux_error_mod'], f2['aux_error_mod'])
        assertion.eq(f1['param'].dtype, f2['param'].dtype)
        assertion.eq(f1['aux_error_mod'].dtype, f2['aux_error_mod'].dtype)
Esempio n. 8
0
def test_orca_parse_hessian():
    """Check Hessian reader."""
    hess = parse_hessian(PATH_OPT, "$hessian_approx")
    assertion.shape_eq(hess, (18, 18))