コード例 #1
0
def test_with_cp2k(name: str, dir_name: str) -> None:
    """Test :class:`ARMC` and :class:`ARMCPT`."""
    with open(f'tests/test_files/{name}', 'r') as f:
        dct = yaml.load(f.read(), Loader=UniqueLoader)
    dct["monte_carlo"]["keep_files"] = True
    armc, job_kwargs = dict_to_armc(dct)

    try:
        run_armc(armc, restart=False, **job_kwargs)
    except Exception as ex:
        err_file = PATH / dir_name / 'md' / 'md.err'
        out_file = PATH / dir_name / 'md' / 'md.out'
        has_err_file = os.path.isfile(err_file)
        has_out_file = os.path.isfile(out_file)

        if not (has_err_file or has_out_file):
            raise

        msg = ""
        if has_err_file:
            with open(err_file, 'r', encoding='utf-8') as f:
                msg += f"{err_file}:\n{f.read()}"
        if out_file:
            with open(out_file, 'r', encoding='utf-8') as f:
                msg += f"{out_file}:\n{f.read()}"

        raise AssertionError(msg) from ex
コード例 #2
0
def test_armc_guess() -> None:
    file = PATH / 'armc_ref.yaml'
    with open(file, 'r') as f:
        dct = yaml.load(f.read(), Loader=UniqueLoader)

    sigma = dct['param']['lennard_jones'][1]
    del sigma['Cd Cd']
    sigma['frozen'] = {'guess': 'uff'}

    armc, job_kwargs = dict_to_armc(dct)
    param = armc.param.param.loc[('lennard_jones', 'sigma'), 0]

    # The expected `sigma` parameters
    ref = np.array([
        0.30504372,
        0.3654912,
        0.25372795,
        0.20704486,
        0.2471,
        0.294,
        0.26749234,
        0.3526,
        0.4852,
    ])
    np.testing.assert_allclose(param.values, ref)
コード例 #3
0
def test_yaml_armc(name: str) -> None:
    """Tests for :meth:`FOX.armc.ARMC.to_yaml_dict`."""
    file = PATH / name
    with open(file, 'r') as f:
        _dct = yaml.load(f.read(), Loader=UniqueLoader)

    armc1, job_kwargs1 = dict_to_armc(_dct)
    dct1 = armc1.to_yaml_dict(
        path=job_kwargs1['path'],
        folder=job_kwargs1['folder'],
        logfile=job_kwargs1['logfile'],
        psf=job_kwargs1['psf'],
    )

    armc2, job_kwargs2 = dict_to_armc(dct1)
    dct2 = armc2.to_yaml_dict(
        path=job_kwargs2['path'],
        folder=job_kwargs2['folder'],
        logfile=job_kwargs2['logfile'],
        psf=job_kwargs2['psf'],
    )

    assertion.eq(armc1, armc2)
    assertion.eq(dct1, dct2)
コード例 #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'))
コード例 #5
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)
コード例 #6
0
def test_enforce_constraints() -> None:
    """Test ``param.validation.enforce_constraints``."""
    file = PATH / 'armc_ref.yaml'
    with open(file, 'r') as f:
        dct = yaml.load(f.read(), Loader=UniqueLoader)
        dct['param']['validation']['enforce_constraints'] = True
        dct['param']['validation']['charge_tolerance'] = 'inf'

    dct['param']['charge']['CG2O3'] = 10
    assertion.assert_(dict_to_armc, dct, exception=RuntimeError)

    dct['param']['charge']['CG2O3'] = -10
    assertion.assert_(dict_to_armc, dct, exception=RuntimeError)

    dct['param']['charge']['CG2O3'] = 0.4524
    dct['param']['charge']['Cd'] = 2
    assertion.assert_(dict_to_armc, dct, exception=RuntimeError)

    with pytest.warns(RuntimeWarning):
        dct['param']['validation']['enforce_constraints'] = False
        _ = dict_to_armc(dct)
コード例 #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)
コード例 #8
0
"""Test ARMC input."""

import yaml
import shutil
from FOX.armc import dict_to_armc
# from FOX.armc.run_armc import run_armc

file = 'armc_new.yaml'
with open(file, 'r') as f:
    dct = yaml.load(f.read(), Loader=yaml.FullLoader)

try:
    shutil.rmtree('MM_MD_workdir')
except Exception:
    pass

try:
    armc, kwargs = dict_to_armc(dct)
except Exception as ex:
    exc = ex
    raise ex

# run_armc(armc, **kwargs)
コード例 #9
0
from scm.plams import add_to_class, Cp2kJob

from FOX.armc import dict_to_armc, run_armc


@add_to_class(Cp2kJob)
def get_runscript(self):
    inp, out = self._filename('inp'), self._filename('out')
    return f'cp2k.ssmp -i {inp} -o {out}'


# Prepare the ARMC settings
file = 'armc_new.yaml'
with open(file, 'r') as f:
    dct = yaml.load(f.read(), Loader=yaml.FullLoader)

try:
    armc, job_kwargs = dict_to_armc(dct)
except Exception as ex:
    exc = ex
    raise ex

# Start ARMC
try:
    workdir = os.path.join(job_kwargs['path'], job_kwargs['folder'])
    shutil.rmtree(workdir)
except FileNotFoundError:
    pass

run_armc(armc, restart=False, **job_kwargs)