def validate_prop_group(group: h5py.Group) -> None: """Validate the passed hdf5 **group**, ensuring it is compatible with :func:`create_prop_group` and :func:`create_prop_group`. This method is called automatically when an exception is raised by :func:`update_prop_dset`. Parameters ---------- group : :class:`h5py.Group` The to-be validated hdf5 Group. Raises ------ :exc:`AssertionError` Raised if the validation process fails. """ # noqa: E501 assertion.isinstance(group, h5py.Group) idx_ref = group.attrs['index'] idx = group.file[idx_ref] iterator = ((k, v) for k, v in group.items() if not k.endswith('_names')) for name, dset in iterator: assertion.le(len(dset), len(idx), message=f'{name!r} invalid dataset length') assertion.contains(dset.dims[0].keys(), 'index', message=f'{name!r} missing dataset scale') assertion.eq(dset.dims[0]['index'], idx, message=f'{name!r} invalid dataset scale')
def test_xyz_reader(): """Test the xyz parser from a file.""" path_qd = PATH_MOLECULES / "Cd68Cl26Se55__26_acetate.xyz" mol = readXYZ(path_qd) for atom in mol: assertion.le(len(atom.symbol), 2) assertion.len_eq(atom.xyz, 3)
def test_le() -> None: """Test :meth:`AssertionManager.le`.""" assertion.le(5, 6) assertion.le(5, 5) assertion.le(6, 5, invert=True) assertion.le(5, 6, 7, 8, exception=TypeError) assertion.le([], 6, exception=TypeError)
def _validate(atom: str, value: float, param: pd.Series) -> None: """Validate the moves of :func:`test_constraint_blocks`.""" ident = f"{atom}={value}" assertion.isclose(param[atom], value, abs_tol=0.001, message=f'{atom} ({ident})') for min_, max_, (key, v) in zip(PRM_MIN, PRM_MAX, param.items()): assertion.le(min_, v, message=f'{key} ({ident})') assertion.ge(max_, v, message=f'{key} ({ident})') assertion.isclose((param * COUNT).sum(), 0, abs_tol=0.001, message=f"net charge ({ident})") for key in EXCLUDE: assertion.eq(param[key], PARAM[key], message=f'{key} ({ident})') idx1 = ATOM_COEFS[0].index idx2 = ATOM_COEFS[1].index v1 = (param[idx1] * ATOM_COEFS[0]).sum() v2 = (param[idx2] * ATOM_COEFS[1]).sum() assertion.isclose(v1, v2, abs_tol=0.001, message=f"{idx1} and {idx2} ({ident})")
def test_read_basis(): """Test that the basis are read correctly.""" BASIS_FILE = PATH / "BASIS_MOLOPT" for key, data in zip(*readCp2KBasis(BASIS_FILE)): # The formats contains a list assertion.len(key.basisFormat) # Atoms are either 1 or two characters assertion.le(len(key.atom), 2) # All basis are MOLOPT assertion.contains(key.basis, "MOLOPT") # There is a list of exponents and coefficinets assertion.len(data.exponents) assertion.len(data.coefficients[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)
def test_geometry() -> None: """Test CP2K geometry optimization calculations with the :class:`CP2K_MM` class.""" s = SETTINGS.copy() s.specific.cp2k += geometry.specific.cp2k_mm job = cp2k_mm(settings=s, mol=MOL, job_name='cp2k_mm_opt') result = run(job, path=PATH) assertion.eq(result.status, 'successful') # Compare energies ref = -16.865587192150834 assertion.isclose(result.energy, ref, rel_tol=10**-4) # Compare geometries xyz_ref = np.load(PATH_MOLECULES / 'Cd68Cl26Se55__26_acetate.npy') _xyz = np.array(result.geometry) _xyz -= _xyz.mean(axis=0)[None, ...] xyz = overlap_coords(_xyz, xyz_ref) r_mean = np.linalg.norm(xyz - xyz_ref, axis=1).mean() assertion.le(r_mean, 0.1)
def test_c2pk_opt_mock(mocker: MockFixture) -> None: """Mock a call to CP2K.""" s = SETTINGS.copy() s.specific.cp2k += singlepoint.specific.cp2k_mm job = cp2k_mm(s, MOL) run_mocked = mock_runner(mocker, settings=s, jobname="cp2k_mm_opt") result = run_mocked(job) assertion.eq(result.status, 'successful') # Compare energies ref = -16.865587192150834 energy = result.energy assertion.isclose(energy, ref, rel_tol=10**-4) # Compare geometries xyz_ref = np.load(PATH_MOLECULES / 'Cd68Cl26Se55__26_acetate.npy') _xyz = np.array(result.geometry) _xyz -= _xyz.mean(axis=0)[None, ...] xyz = overlap_coords(_xyz, xyz_ref) r_mean = np.linalg.norm(xyz - xyz_ref, axis=1).mean() assertion.le(r_mean, 0.1)