Esempio n. 1
0
def _val_iter(mapping: Mapping[KT, Any],
              k_type: Union[Type[KT], Tuple[Type[KT], ...]]) -> None:
    """Validate the :meth:`~collections.abc.Mapping.__iter__` method of **mapping**."""
    iterator = iter(mapping)
    assertion.isinstance(iterator, abc.Iterator)
    for k in iterator:
        assertion.isinstance(k, k_type)
Esempio n. 2
0
def _val_values(mapping: Mapping[Any, VT],
                v_type: Union[Type[VT], Tuple[Type[VT], ...]]) -> None:
    """Validate the :meth:`~collections.abc.Mapping.values` method of **mapping**."""
    values = mapping.values()
    assertion.isinstance(values, abc.ValuesView)
    for v in values:
        assertion.isinstance(v, v_type)
Esempio n. 3
0
def test_adf_mock(mocker: MockFixture):
    """Mock the ADF output."""
    mol = Molecule(PATH_MOLECULES / "acetonitrile.xyz")
    job = adf(templates.geometry, mol)

    run_mocked = mocker.patch("qmflows.run")
    jobname = "ADFjob"
    dill_path = WORKDIR / jobname / "ADFjob.dill"
    plams_dir = WORKDIR / jobname
    run_mocked.return_value = ADF_Result(templates.geometry,
                                         mol,
                                         jobname,
                                         dill_path=dill_path,
                                         work_dir=plams_dir,
                                         plams_dir=plams_dir)
    rs = run_mocked(job)
    assertion.isfinite(rs.energy)
    assertion.isfinite(rs.h**o)
    assertion.isfinite(rs.lumo)
    # Array of runtime for each optimization
    assertion.isfinite(rs.runtime[-1])
    # 3-dimensional vector
    assertion.len_eq(rs.dipole, 3)
    # number of steps until convergence
    assertion.eq(rs.optcycles, 8)

    # Test molecule
    # Molecule
    mol = rs.molecule
    assertion.isinstance(mol, Molecule)
    assertion.len_eq(mol, 6)  # there are 6 atoms
Esempio n. 4
0
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')
Esempio n. 5
0
 def test_warns(self, tmp_path: Path) -> None:
     """Test that whether appropiate warning is issued."""
     with pytest.warns(RuntimeWarning) as record:
         get_compkf("bob", tmp_path)
     cause: None | BaseException = getattr(record[0].message, "__cause__",
                                           None)
     assertion.isinstance(cause, RuntimeError)
Esempio n. 6
0
def test_package_wrapper() -> None:
    """Tests for :class:`PackageWrapper<qmflows.packages.package_wrapper.PackageWrapper>`."""
    s1 = Settings()
    s1.input.ams.Task = 'GeometryOptimization'
    s1.input.ams.GeometryOptimization.Convergence.Gradients = 1.0e-4
    s1.input.ams.Properties.NormalModes = 'true'
    s1.input.DFTB.Model = 'DFTB3'
    s1.input.DFTB.ResourcesDir = 'DFTB.org/3ob-3-1'

    s2 = Settings()
    s2.input.basis.type = 'DZP'
    s2.input.basis.core = 'None'
    s2.input.basis.createoutput = 'None'

    mol = from_smiles('O')  # H2O

    job1 = PackageWrapper(AMSJob)(s1, mol, name='amsjob')
    result1 = _get_result(job1, AMSJob)
    assertion.isinstance(result1, ResultWrapper)
    assertion.eq(result1.results.job.status, 'successful')

    job2 = PackageWrapper(ADFJob)(s2, mol, name='adfjob')
    result2 = _get_result(job2, ADFJob)
    assertion.isinstance(result2, ADF_Result)
    assertion.eq(result2.results.job.status, 'successful')
Esempio n. 7
0
def _val_keys(mapping: Mapping[KT, Any],
              k_type: Union[Type[KT], Tuple[Type[KT], ...]]) -> None:
    """Validate the :meth:`~collections.abc.Mapping.keys` method of **mapping**."""
    keys = mapping.keys()
    assertion.isinstance(keys, abc.KeysView)
    for k in keys:
        assertion.isinstance(k, k_type)
Esempio n. 8
0
def _val_get(mapping: Mapping[KT, VT], key: KT,
             v_type: Union[Type[VT], Tuple[Type[VT], ...]]) -> None:
    """Validate the :meth:`~collections.abc.Mapping.get` method of **mapping**."""
    v = mapping.get(key, default=True)  # type: ignore
    _v = mapping.get(_Key, default=True)  # type: ignore
    assertion.isinstance(v, v_type)
    assertion.is_(_v, True)
Esempio n. 9
0
def test_dftb_opt_mock(mocker: MockFixture):
    """Mock a geometry optimization using DFTB."""
    jobname = "dftb_geometry"
    job = dftb(templates.geometry, WATER, job_name=jobname)

    run_mocked = mock_runner(mocker, jobname)
    rs = run_mocked(job)

    # check the properties
    assertion.isfinite(rs.energy)
    assertion.len_eq(rs.dipole, 3)
    assertion.isinstance(rs.molecule, Molecule)
Esempio n. 10
0
def test_empty() -> None:
    """Tests for :mod:`nanoutils.empty`."""
    assertion.isinstance(EMPTY_SEQUENCE, abc.Sequence)
    assertion.isinstance(EMPTY_MAPPING, abc.Mapping)
    assertion.isinstance(EMPTY_COLLECTION, abc.Collection)
    assertion.isinstance(EMPTY_SET, abc.Set)
    assertion.isinstance(EMPTY_CONTAINER, abc.Container)
    assertion.not_(EMPTY_SEQUENCE)
    assertion.not_(EMPTY_MAPPING)
    assertion.not_(EMPTY_COLLECTION)
    assertion.not_(EMPTY_SET)
    assertion.not_(EMPTY_CONTAINER)
Esempio n. 11
0
def test_input_validation():
    """Test the input validation schema."""
    schemas = ("absorption_spectrum", "derivative_couplings")
    paths = [
        PATH_TEST / x for x in [
            "input_test_absorption_spectrum.yml",
            "input_fast_test_derivative_couplings.yml"
        ]
    ]
    for s, p in zip(schemas, paths):
        d = process_input(p, s)
        assertion.isinstance(d, dict)
Esempio n. 12
0
def test_from_pdb_array() -> None:
    """Test :func:`dataCAT.functions.as_pdb_array`."""
    mol = molkit.readpdb(join(PATH, 'Methanol.pdb'))

    pdb_ar = as_pdb_array([mol], warn=False)[0]
    out1 = from_pdb_array(pdb_ar, warn=False)
    assertion.isinstance(out1, Chem.Mol)

    out2 = from_pdb_array(pdb_ar, rdmol=False, warn=False)
    for at1, at2 in zip(out2, mol):
        assertion.eq(at1.coords, at2.coords)
        assertion.eq(at1.atnum, at2.atnum)
Esempio n. 13
0
def test_version_info() -> None:
    """Tests for :func:`nanoutils.VersionInfo`."""
    tup1 = VersionInfo(0, 1, 2)
    tup2 = VersionInfo.from_str('0.1.2')
    assertion.eq(tup1, (0, 1, 2))
    assertion.eq(tup2, (0, 1, 2))

    assertion.eq(tup1.micro, tup1.patch)

    assertion.assert_(VersionInfo.from_str, b'0.1.2', exception=TypeError)
    assertion.assert_(VersionInfo.from_str, '0.1.2a', exception=ValueError)
    assertion.assert_(VersionInfo.from_str, '0.1.2.3.4', exception=ValueError)

    assertion.isinstance(version_info, VersionInfo)
Esempio n. 14
0
 def test_mol_properties(self, generate_output: Output) -> None:
     """Validate the properties of the output molecules."""
     mol_list, *_ = generate_output
     ex_dict = {}
     for i, mol in enumerate(mol_list):
         smiles: None | str = mol.properties.get("smiles")
         anchor: None | str = mol.properties.get("anchor")
         name = smiles if smiles is not None else mol.get_formula()
         try:
             assertion.isinstance(smiles, str, message=f"{name} smiles")
             assertion.isinstance(anchor, str, message=f"{name} anchor")
         except AssertionError as ex:
             ex_dict[name] = ex
     eval_ex_dict(ex_dict, 1 + i)
Esempio n. 15
0
def test_CP2K_KEYS_ALIAS() -> None:
    """Tests for :data:`CP2K_KEYS_ALIAS`."""
    key_exclude = {'lennard_jones'}

    assertion.isinstance(CP2K_KEYS_ALIAS, dict)

    for k, v in CP2K_KEYS_ALIAS.items():
        if k.endswith('14'):
            k = k[:-2]
        if k in key_exclude:
            continue

        assertion.eq(k, v[-1])
        assertion.isinstance(v, tuple)
        assertion.eq(v[:2], ('specific', 'cp2k'))
Esempio n. 16
0
def test_cp2k_opt(tmp_path: PathLike):
    """Run a simple molecular optimization."""
    s = fill_cp2k_defaults(templates.geometry)

    # Do a single step
    s.specific.cp2k.motion.geo_opt.max_iter = 1
    s.specific.cp2k.force_eval.dft.scf.eps_scf = 1e-1

    water = Molecule(PATH_MOLECULES / "h2o.xyz",
                     'xyz',
                     charge=0,
                     multiplicity=1)

    job = cp2k(s, water)
    mol = run(job, folder=tmp_path)
    assertion.isinstance(mol.molecule, Molecule)
Esempio n. 17
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. 18
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')
Esempio n. 19
0
def test_validate() -> None:
    """Test :meth:`PDBContainer.validate_hdf5`."""
    with h5py.File(HDF5_TMP, 'a', libver='latest') as f:
        group = f.create_group('test')

        try:
            PDB.from_hdf5(group)
        except AssertionError as ex:
            assertion.isinstance(ex.__context__, KeyError)
            dset = group.create_dataset('atoms', data=[1])
        else:
            raise AssertionError("Failed to raise an AssertionError")

        try:
            PDB.to_hdf5(group, None)
        except AssertionError as ex:
            assertion.isinstance(ex.__context__, RuntimeError)
            scale = group.create_dataset('index', data=[1], maxshape=(None, ))
            scale.make_scale('index')
            dset.dims[0].attach_scale(scale)
        else:
            raise AssertionError("Failed to raise an AssertionError")

        try:
            PDB.to_hdf5(group, None)
        except AssertionError as ex:
            assertion.isinstance(ex.__context__, IndexError)
        else:
            raise AssertionError("Failed to raise an AssertionError")
Esempio n. 20
0
def _val_items(mapping: Mapping[KT, VT], k_type: Union[Type[KT],
                                                       Tuple[Type[KT], ...]],
               v_type: Union[Type[VT], Tuple[Type[VT], ...]]) -> None:
    """Validate the :meth:`~collections.abc.Mapping.items` method of **mapping**."""
    items = mapping.items()
    assertion.isinstance(items, abc.ItemsView)
    for k, v in mapping.items():
        assertion.isinstance(k, k_type)
        assertion.isinstance(v, v_type)
Esempio n. 21
0
def test_file_to_context() -> None:
    """Tests for :func:`file_to_context`."""
    path_like = PATH_MOLECULES / 'mol.psf'
    file_like = StringIO(PSF_STR)

    cm1 = file_to_context(path_like)
    cm2 = file_to_context(file_like)
    assertion.isinstance(cm1, AbstractContextManager)
    assertion.isinstance(cm2, AbstractContextManager)
    assertion.isinstance(cm1.__enter__(), TextIOBase)
    assertion.isinstance(cm2.__enter__(), TextIOBase)

    sequence = range(10)
    assertion.assert_(file_to_context, sequence, require_iterator=False)
    assertion.assert_(file_to_context, sequence, require_iterator=True, exception=TypeError)

    assertion.assert_(file_to_context, None, exception=TypeError)
    assertion.assert_(file_to_context, [1, 2], exception=TypeError)
    assertion.assert_(file_to_context, 5.0, exception=TypeError)
Esempio n. 22
0
def test_orca_parse_molecule():
    """Test the reading of the molecule from the output."""
    mol = parse_molecule(PATH_OUTPUT)
    assertion.isinstance(mol, plams.Molecule)
    assertion.len_eq(mol, 6)
Esempio n. 23
0
def test_Distance():
    """Test Distance reactivity functionality."""
    d = reactivity.Distance(1, 2)
    s = d.get_settings(mol=mol)

    assertion.isinstance(s, Settings)
Esempio n. 24
0
 def test_getitem_slice(self, seq: Sequence[int], view: SequenceView[int],
                        i: int) -> None:
     assertion.eq(view[:i], seq[:i])
     assertion.eq(view[i:], seq[i:])
     assertion.eq(view[::i], seq[::i])
     assertion.isinstance(view[:], SequenceView)
Esempio n. 25
0
 def test_getitem_int(self, seq: Sequence[int], view: SequenceView[int],
                      i: int) -> None:
     assertion.eq(view[i], seq[i])
     assertion.isinstance(view[i], type(seq[i]))
Esempio n. 26
0
def test_Angle():
    """Test Angle reactivity functionality."""
    ang = reactivity.Angle(1, 2, 3)
    s = ang.get_settings(mol=mol)

    assertion.isinstance(s, Settings)
Esempio n. 27
0
def test_Dihedral():
    """Test Angle reactivity functionality."""
    dihed = reactivity.Dihedral(1, 2, 3, 4)
    s = dihed.get_settings(mol=mol)

    assertion.isinstance(s, Settings)
Esempio n. 28
0
def _val_len(mapping: Mapping) -> None:
    """Validate the :meth:`~collections.abc.Mapping.__len__` method of **mapping**."""
    length = len(mapping)
    assertion.isinstance(length, int)
Esempio n. 29
0
def _val_getitem(mapping: Mapping[KT, VT], key: KT,
                 v_type: Union[Type[VT], Tuple[Type[VT], ...]]) -> None:
    """Validate the :meth:`~collections.abc.Mapping.__getitem__` method of **mapping**."""
    v = mapping[key]
    assertion.isinstance(v, v_type)
Esempio n. 30
0
def _val_class(mapping: Mapping) -> None:
    """Validate the :class:`type` of **mapping**."""
    assertion.isinstance(mapping, abc.Mapping)