Beispiel #1
0
def test_setattr() -> None:
    """Test :class:`~nanoutils.SetAttr`."""
    assertion.is_(OBJ.obj, _Test)
    assertion.eq(OBJ.name, 'a')
    assertion.is_(OBJ.value, False)

    assertion.is_(OBJ.attr, _Test.a)
    try:
        OBJ.attr = False
        assertion.is_(OBJ.attr, False)
    finally:
        OBJ.attr = True

    assertion.contains(repr(OBJ), SetAttr.__name__)
    assertion.contains(repr(OBJ), object.__repr__(OBJ.obj))
    assertion.contains(repr(OBJ), reprlib.repr(OBJ.value))
    assertion.contains(repr(OBJ), 'a')

    obj2 = SetAttr(_Test, 'a', False)
    obj3 = SetAttr(_Test, 'a', True)
    assertion.eq(OBJ, obj2)
    assertion.ne(OBJ, obj3)
    assertion.ne(OBJ, 0)

    assertion.assert_(OBJ.__reduce__, exception=TypeError)
    assertion.is_(copy.copy(OBJ), OBJ)
    assertion.is_(copy.deepcopy(OBJ), OBJ)
    assertion.truth(hash(OBJ))
    assertion.eq(hash(OBJ), OBJ._hash)

    with OBJ:
        assertion.is_(_Test.a, False)
    assertion.is_(_Test.a, True)
Beispiel #2
0
def test_templates():
    """Test that the yaml files are read properly."""
    b1 = freq == transform(freq)
    b2 = geometry == transform(geometry)
    b3 = singlepoint == transform(singlepoint)
    b4 = ts == transform(ts)

    assertion.truth(all((b1, b2, b3, b4)))
Beispiel #3
0
def check_couplings(config: DictConfig, tmp_hdf5: str,
                    orbitals_type: str) -> None:
    """Check that the couplings have meaningful values."""
    def create_paths(keyword: str) -> list:
        return [
            os.path.join(orbitals_type, f'{keyword}_{x}')
            for x in range(len(config.geometries) - 1)
        ]

    overlaps = create_paths('overlaps')
    couplings = create_paths('coupling')

    # Check that couplings and overlaps exists
    assertion.truth(is_data_in_hdf5(tmp_hdf5, overlaps))
    assertion.truth(is_data_in_hdf5(tmp_hdf5, couplings))

    # All the elements are different of inifinity or nan
    tensor_couplings = np.stack(retrieve_hdf5_data(tmp_hdf5, couplings))
    assertion.truth(np.isfinite(tensor_couplings).all())

    # Check that the couplings are anti-symetric
    for mtx in tensor_couplings[:]:
        assertion(np.allclose(mtx, -mtx.T))

    # Check that there are not NaN
    assertion.truth(not np.all(np.isnan(tensor_couplings)))
def run_single_point(tmp_path: Path, input_file: str):
    """Run a single point calculation using cp2k."""
    file_path = PATH_TEST / input_file
    config = process_input(file_path, 'single_points')
    config["scratch_path"] = tmp_path
    tmp_hdf5 = os.path.join(tmp_path, 'single_points.hdf5')
    config['path_hdf5'] = tmp_hdf5
    Path(tmp_hdf5).touch()
    try:
        path_orbitals, path_energies = workflow_single_points(config)
        print("path_orbitals: ", path_orbitals)
        print("path_energies: ", path_energies)
        if config["compute_orbitals"]:
            assertion.truth(is_data_in_hdf5(tmp_hdf5, path_orbitals[0]))
    finally:
        remove_files()
Beispiel #5
0
def test_assert_() -> None:
    """Test :meth:`AssertionManager.assert_`."""
    assertion.assert_(len, [1])
    assertion.assert_(len, [], invert=True)
    assertion.assert_(len, 1, exception=TypeError)
    assertion.assert_(len, [1], [1], exception=TypeError)
    assertion.assert_(len, [1], bob=1, exception=TypeError)

    try:
        assertion.assert_(len, [1], exception=bool)
    except TypeError:
        pass
    else:
        raise AssertionError('Failed to raise a TypeError')

    try:
        assertion.assert_(len, [1], exception=AssertionError)
    except ValueError:
        pass
    else:
        raise AssertionError('Failed to raise a ValueError')

    try:
        assertion.eq(1, 1, exception=TypeError, message='<MARKER>')
    except AssertionError as ex:
        assertion.contains(str(ex), '<MARKER>')
    else:
        raise AssertionError('Failed to raise an AssertionError')

    try:
        assertion.contains(1, 1, exception=ValueError)
    except AssertionError as ex:
        assertion.isinstance(ex.__cause__, TypeError)
    else:
        raise AssertionError('Failed to raise an AssertionError')

    func = operator.__invert__
    assertion(False, post_process=func)
    assertion(True, invert=True, post_process=func)

    try:
        assertion.truth(False, message='Funcy custom message')
    except AssertionError as ex:
        assertion.contains(str(ex), 'Funcy custom message')
    else:
        raise AssertionError('Failed to raise am AssertionError')
Beispiel #6
0
def test_orca_init_hessian():
    """Test the translation from settings to CP2K specific keywords."""
    # Read Hessian from DFTB
    PATH_RKF = PATH / "output_dftb" / "dftb_freq" / "dftb.rkf"
    assertion.truth(PATH_RKF.exists())
    hess = kfreader(PATH_RKF, section="AMSResults", prop="Hessian")
    water = molkit.from_smiles('[OH2]', forcefield='mmff')

    # Tess Hessian initialization
    s = Settings()
    hess = np.array(hess).reshape(9, 9)
    s.inithess = hess
    ORCA.handle_special_keywords(s, "inithess", hess, water)

    # Test that the hessian is readable
    new_hess = parse_hessian(s.specific.orca.geom.InHessName)
    new_hess = np.array(new_hess, dtype=np.float64)
    assertion.truth(np.allclose(hess, new_hess, atol=1e-5))
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))
Beispiel #8
0
def test_update_hdf5_log1() -> None:
    """Test :func:`dataCAT.update_hdf5_log`."""
    copyfile(HDF5_READ, HDF5_TMP)

    with h5py.File(HDF5_TMP, 'r+', libver='latest') as f:
        group = f['ligand/logger']

        i = len(group['date'])
        n0 = group.attrs['n']
        assertion.truth(n0)

        i += group.attrs['n_step']
        group.attrs['n'] = 100
        update_hdf5_log(group, index=[0])

        n1 = group.attrs['n']
        assertion.eq(n1, 101)
        for name, dset in group.items():
            if name != 'version_names':
                assertion.len_eq(dset, i)
Beispiel #9
0
def check_hamiltonians(hamiltonians: Sequence[str]) -> None:
    """Check that the hamiltonians were written correctly."""
    energies = np.stack([np.diag(np.loadtxt(ts[1])) for ts in hamiltonians])
    couplings = np.stack([np.loadtxt(ts[0]) for ts in hamiltonians])

    # check that energies and couplings are finite values
    assertion.truth(np.isfinite(energies).all())
    assertion.truth(np.isfinite(couplings).all())

    # Check that the couplings diagonal is zero
    assertion.truth(abs(np.einsum('jii->', couplings)) < 1e-16)
Beispiel #10
0
def test_parse_cp2k_warnings():
    """Parse CP2K warnings."""
    OUTPUT_FILE = PATH / "output_cp2k" / "cp2k_job" / "cp2k_job.out"
    map_warns = parse_cp2k_warnings(OUTPUT_FILE, cp2k_warnings)
    assertion.truth(all((val == QMFlows_Warning)
                        for val in map_warns.values()))
Beispiel #11
0
def test_truth_np() -> None:
    """Test :meth:`AssertionManager.truth` with a NumPy array."""
    array: np.ndarray = np.random.rand(10)
    assertion.truth(array, exception=ValueError)
Beispiel #12
0
def test_truth() -> None:
    """Test :meth:`AssertionManager.truth`."""
    assertion.truth(5)
    assertion.truth(0, invert=True)
    assertion.truth(5, 6, 7, 8, exception=TypeError)