Beispiel #1
0
def test_c2pk_cell_opt() -> None:
    """Test CP2K cell optimization calculations with the :class:`CP2K_MM` class."""
    mol = Molecule(PATH / 'cspbbr3_3d.xyz')

    s = Settings()
    s.specific.cp2k += cell_opt.specific.cp2k_mm.copy()
    s.specific.cp2k.motion.cell_opt.max_iter = 10
    s.specific.cp2k.motion.print['forces low'].filename = ''

    s.gmax = [22, 22, 22]
    s.cell_parameters = [25.452, 35.995, 24.452]
    s.charge = {
        'param': 'charge',
        'Cs': 0.2,
        'Pb': 0.4,
        'Br': -0.2,
    }
    s.lennard_jones = {
        'param': ('sigma', 'epsilon'),
        'unit': ('nm', 'kjmol'),
        'Cs Cs': (0.585, 1),
        'Cs Pb': (0.510, 1),
        'Br Se': (0.385, 1),
        'Pb Pb': (0.598, 1),
        'Br Pb': (0.290, 1),
        'Br Br': (0.426, 1),
    }

    job = cp2k_mm(settings=s, mol=mol, job_name='cp2k_mm_cell_opt')
    result = run(job, path=PATH)
    assertion.eq(result.status, 'successful')
Beispiel #2
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')
Beispiel #3
0
def test_float() -> None:
    """Tests for :meth:`NDRepr.repr_float`."""
    assertion.eq('5.0000', aNDRepr.repr(5.0))
    assertion.eq('5.0000', aNDRepr.repr(5.00000000000))
    assertion.eq('5.0000', aNDRepr.repr(5.0000))
    assertion.eq('5.0000e+10', aNDRepr.repr(5.0 * 10**10))
    assertion.eq('5.0000e-10', aNDRepr.repr(5.0 * 10**-10))
Beispiel #4
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
Beispiel #5
0
def test_lig_mapping() -> None:
    """Tests for :func:`nanoCAT.bde.dissociate_xyn._lig_mapping`."""
    lig_mapping = _lig_mapping(MOL, LIG_IDX)
    ref = {
        127: [124, 125, 126, 127, 128, 129, 130],
        134: [131, 132, 133, 134, 135, 136, 137],
        141: [138, 139, 140, 141, 142, 143, 144],
        148: [145, 146, 147, 148, 149, 150, 151],
        155: [152, 153, 154, 155, 156, 157, 158],
        162: [159, 160, 161, 162, 163, 164, 165],
        169: [166, 167, 168, 169, 170, 171, 172],
        176: [173, 174, 175, 176, 177, 178, 179],
        183: [180, 181, 182, 183, 184, 185, 186],
        190: [187, 188, 189, 190, 191, 192, 193],
        197: [194, 195, 196, 197, 198, 199, 200],
        204: [201, 202, 203, 204, 205, 206, 207],
        211: [208, 209, 210, 211, 212, 213, 214],
        218: [215, 216, 217, 218, 219, 220, 221],
        225: [222, 223, 224, 225, 226, 227, 228],
        232: [229, 230, 231, 232, 233, 234, 235],
        239: [236, 237, 238, 239, 240, 241, 242],
        246: [243, 244, 245, 246, 247, 248, 249],
        253: [250, 251, 252, 253, 254, 255, 256],
        260: [257, 258, 259, 260, 261, 262, 263],
        267: [264, 265, 266, 267, 268, 269, 270],
        274: [271, 272, 273, 274, 275, 276, 277],
        281: [278, 279, 280, 281, 282, 283, 284],
        288: [285, 286, 287, 288, 289, 290, 291],
        295: [292, 293, 294, 295, 296, 297, 298],
        302: [299, 300, 301, 302, 303, 304, 305]
    }
    assertion.eq(lig_mapping, ref)
Beispiel #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')
Beispiel #7
0
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})")
Beispiel #8
0
def test_map_psf_atoms() -> None:
    """Tests for :func:`map_psf_atoms`."""
    ref = {
        'C331': 'C',
        'C321': 'C',
        'C2O3': 'C',
        'O2D2': 'O',
        'HGA2': 'H',
        'HGA3': 'H'
    }

    path_like = PATH_MOLECULES / 'mol.psf'
    file_like = StringIO(PSF_STR)
    assertion.eq(map_psf_atoms(path_like), ref)
    assertion.eq(map_psf_atoms(file_like), ref)

    # Incorrect input types
    assertion.assert_(map_psf_atoms, None, exception=TypeError)
    assertion.assert_(map_psf_atoms, {1: 1}, exception=TypeError)
    assertion.assert_(map_psf_atoms, 'bob.psf', exception=FileNotFoundError)

    # Incorrect mode (bytes)
    file_bytes = BytesIO(PSF_STR.encode())
    assertion.assert_(map_psf_atoms,
                      file_bytes,
                      mode='rb',
                      exception=TypeError)

    # The !NATOM will now be missing
    file_wrong1 = StringIO(PSF_STR[24:])
    assertion.assert_(map_psf_atoms, file_wrong1, exception=ValueError)

    # Rows [5:] will now be missing
    file_wrong2 = StringIO('\n'.join(i[:25] for i in PSF_STR.splitlines()))
    assertion.assert_(map_psf_atoms, file_wrong2, exception=ValueError)
Beispiel #9
0
def test_yaml2Settings():
    """Test the conversion from yaml to settings."""
    s1 = yaml2Settings(CP2K_PBE_GUESS)
    s2 = yaml2Settings(CP2K_PBE_GUESS.encode())

    assertion.eq(s1.specific, REF.specific)
    assertion.eq(s2.specific, REF.specific)
Beispiel #10
0
def test_freq():
    """Do some constraint optimizations then launch a freq calc."""
    mol = Molecule(PATH_MOLECULES / "ethene.xyz", "xyz")
    geo_opt = dftb(templates.geometry, mol)
    freq_calc = dftb(templates.freq, geo_opt.molecule, job_name="freq")
    r = run(freq_calc)
    assertion.eq(int(r.frequencies[0]), 831)
    assertion.len_eq(r.frequencies, 12)
Beispiel #11
0
def test_index_other() -> None:
    """Test :func:`dataCAT.update_hdf5_log`."""
    copyfile(HDF5_READ, HDF5_TMP)

    with h5py.File(HDF5_TMP, 'r+') as f:
        scale = f['ligand/index']
        group = PDBContainer.create_hdf5_group(f, 'test', scale=scale)
        dset = group['atoms']
        assertion.eq(scale, dset.dims[0]['index'])
Beispiel #12
0
def test_multiple_geometries():
    """Test the reading of multiples molecular geometries from a file."""
    path_xyz = PATH / "molecules" / "five_points_ethylene.xyz"

    with open(path_xyz, 'r') as f:
        ls = f.readlines()

    xs = [''.join(x) for x in chunked(ls, 8)]

    assertion.eq(list(map(parse_string_xyz, xs)), manyXYZ(path_xyz))
Beispiel #13
0
def test_eval_param() -> None:
    """Tests for :func:`_eval_param`."""
    msg1 = 'Angles          '
    msg2 = 'Urey-Bradley    '

    out1 = _eval_param(msg1)
    out2 = _eval_param(msg2)

    assertion.eq(out1, msg1.rstrip())
    assertion.is_(out2, None)
Beispiel #14
0
def test_eval_charge() -> None:
    """Tests for :func:`_eval_charge`."""
    msg1 = 'bob  1.2    '
    msg2 = 'bob  1.02   '

    out1 = _eval_charge(msg1)
    out2 = _eval_charge(msg2)

    assertion.eq(out1, msg1.rstrip())
    assertion.is_(out2, None)
Beispiel #15
0
def test_log_to_dataframe() -> None:
    """Test :func:`dataCAT.log_to_dataframe`."""
    copyfile(HDF5_READ, HDF5_TMP)

    with h5py.File(HDF5_TMP, 'r+', libver='latest') as f:
        group = f['ligand/logger']
        reset_hdf5_log(group)
        df = log_to_dataframe(group)
        dct = {k: v.dtype for k, v in df.items()}
        assertion.eq(dct, REF_COLUMNS)
Beispiel #16
0
def test_exception() -> None:
    """Tests for :meth:`NDRepr.repr_exception`."""
    repr_instance = NDRepr()
    repr_instance.maxException = 80

    exc1 = repr_instance.repr(TypeError('bob'))
    exc2 = repr_instance.repr(TypeError('bob' * 100))
    ref1 = 'TypeError(bob)'
    ref2 = 'TypeError(bobbobbobbobbobbobbobbobbobbobbobbobbobbobbobbobbobbobbobbobbobbobbobbobbobbobbo...)'  # noqa: E501
    assertion.eq(exc1, ref1)
    assertion.eq(exc2, ref2)
Beispiel #17
0
def test_fail_orca(tmpdir):
    """Orca package should returns ``None`` if the computation fails."""
    methanol = Molecule(PATH_MOLECULES / 'methanol.xyz')

    s = Settings()
    s.specific.orca.main = "RKS The_Cow_Functional SVP Opt TightSCF SmallPrint"

    opt = orca(s, methanol, job_name='fail_orca')

    result = run(opt.molecule, path=tmpdir)
    assertion.eq(result, None)
Beispiel #18
0
def test_c2pk_md_mock(mocker: MockFixture) -> None:
    """Mock a call to CP2K."""
    s = SETTINGS.copy()
    s.specific.cp2k += md.specific.cp2k_mm

    job = cp2k_mm(s, MOL)
    run_mocked = mock_runner(mocker, settings=s, jobname="cp2k_mm_md")

    result = run_mocked(job)
    assertion.eq(result.status, 'successful')

    assertion.isfile(result.results['cp2k-1_1000.restart'])
Beispiel #19
0
def test_get_nan_row() -> None:
    """Test :func:`dataCAT.functions.get_nan_row`."""
    df = pd.DataFrame(index=pd.RangeIndex(0, 10))
    df[0] = None
    df[1] = 0
    df[2] = 0.0
    df[3] = False
    df[4] = np.datetime64('2005-02-25')

    out = get_nan_row(df)
    ref = [None, -1, np.nan, False, None]
    assertion.eq(out, ref)
Beispiel #20
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)
Beispiel #21
0
def test_ndarray() -> None:
    """Tests for :meth:`NDRepr.repr_ndarray`."""
    ar1 = np.ones((10, 10), dtype=float)
    ar2 = np.ones((10, 10), dtype=int)

    ref1 = 'array([[1.0000, 1.0000, 1.0000, ..., 1.0000, 1.0000, 1.0000],\n       [1.0000, 1.0000, 1.0000, ..., 1.0000, 1.0000, 1.0000],\n       [1.0000, 1.0000, 1.0000, ..., 1.0000, 1.0000, 1.0000],\n       ...,\n       [1.0000, 1.0000, 1.0000, ..., 1.0000, 1.0000, 1.0000],\n       [1.0000, 1.0000, 1.0000, ..., 1.0000, 1.0000, 1.0000],\n       [1.0000, 1.0000, 1.0000, ..., 1.0000, 1.0000, 1.0000]])'  # noqa
    ref2 = 'array([[1, 1, 1, ..., 1, 1, 1],\n       [1, 1, 1, ..., 1, 1, 1],\n       [1, 1, 1, ..., 1, 1, 1],\n       ...,\n       [1, 1, 1, ..., 1, 1, 1],\n       [1, 1, 1, ..., 1, 1, 1],\n       [1, 1, 1, ..., 1, 1, 1]])'  # noqa
    str1 = aNDRepr.repr(ar1)
    str2 = aNDRepr.repr(ar2)

    assertion.eq(str1, ref1)
    assertion.eq(str2, ref2)
Beispiel #22
0
def test_signature() -> None:
    """Tests for :meth:`NDRepr.repr_Signature`."""
    sgn1 = inspect.signature(len)
    sgn2 = inspect.signature(np.testing.assert_allclose)

    ref1 = '(obj, /)'
    ref2 = "(actual, desired, rtol=1e-07, atol=0, equal_nan=True, ...)"
    str1 = aNDRepr.repr(sgn1)
    str2 = aNDRepr.repr(sgn2)

    assertion.eq(str1, ref1)
    assertion.eq(str2, ref2)
Beispiel #23
0
def test_even_index() -> None:
    """Test :func:`dataCAT.functions.even_index`."""
    df1 = pd.DataFrame(np.random.rand(10, 5))
    df2 = pd.DataFrame(np.random.rand(20, 5))

    out1 = even_index(df1, df2)
    assertion.eq(out1.shape, df2.shape)
    np.testing.assert_array_equal(out1.index, df2.index)
    assert np.isnan(out1.values[10:, :]).all()

    out2 = even_index(df1, df1.copy())
    assertion.is_(df1, out2)
Beispiel #24
0
def test_nullcontext():
    """Tests for :class:`nullcontext` and :data:`_NullContextBackup`."""
    if sys.version_info.minor >= 7:
        assertion.eq(nullcontext.__module__, 'contextlib')
    else:
        assertion.eq(nullcontext.__module__, 'qmflows.backports')

    cm = _NullContextBackup(True)
    with cm as bool_:
        assertion.is_(bool_, True)
    with cm as bool_:
        assertion.is_(bool_, True)
Beispiel #25
0
def test_freeze_with_dftb():
    """Test freeze keyword for DFTB."""
    mol = molkit.from_smiles('CO')
    s = Settings()
    s.freeze = ["C", "O"]
    expected_settings = Settings(
        {'freeze': ['C', 'O'], 'specific': dftb_const})
    assertion.eq(str(dftb.generic2specific(s, mol)), str(expected_settings))
    s.freeze = [1, 2]
    expected_settings = Settings(
        {'freeze': [1, 2], 'specific': dftb_const})
    assertion.eq(str(dftb.generic2specific(s, mol)), str(expected_settings))
Beispiel #26
0
def test_singlepoint() -> None:
    """Test CP2K singlepoint calculations with the :class:`CP2K_MM` class."""
    s = SETTINGS.copy()
    s.specific.cp2k += singlepoint.specific.cp2k_mm

    job = cp2k_mm(settings=s, mol=MOL, job_name='cp2k_mm_sp')
    result = run(job, path=PATH)
    assertion.eq(result.status, 'successful')

    # Compare energies
    ref = -15.4431781758
    assertion.isclose(result.energy, ref, rel_tol=10**-4)
Beispiel #27
0
def test_freeze_with_adf():
    """Test the freeze keyword with ADF."""
    mol = molkit.from_smiles('CO')
    s = Settings()
    s.freeze = ["C", "O"]
    expected_settings = Settings(
        {'freeze': ["C", "O"], 'specific': adf_const})
    assertion.eq(str(adf.generic2specific(s, mol)), str(expected_settings))
    s.freeze = [1, 2]
    expected_settings = Settings(
        {'freeze': [1, 2], 'specific': adf_const})
    assertion.eq(str(adf.generic2specific(s, mol)), str(expected_settings))
Beispiel #28
0
def test_dataframe() -> None:
    """Tests for :meth:`NDRepr.repr_DataFrame`."""
    df1 = pd.DataFrame(np.ones((10, 10), dtype=float))
    df2 = pd.DataFrame(np.ones((10, 10), dtype=int))

    ref1 = '     0    1    2  ...    7    8    9\n0  1.0  1.0  1.0  ...  1.0  1.0  1.0\n1  1.0  1.0  1.0  ...  1.0  1.0  1.0\n2  1.0  1.0  1.0  ...  1.0  1.0  1.0\n3  1.0  1.0  1.0  ...  1.0  1.0  1.0\n4  1.0  1.0  1.0  ...  1.0  1.0  1.0\n5  1.0  1.0  1.0  ...  1.0  1.0  1.0\n6  1.0  1.0  1.0  ...  1.0  1.0  1.0\n7  1.0  1.0  1.0  ...  1.0  1.0  1.0\n8  1.0  1.0  1.0  ...  1.0  1.0  1.0\n9  1.0  1.0  1.0  ...  1.0  1.0  1.0\n\n[10 rows x 10 columns]'  # noqa: E501
    ref2 = '   0  1  2  ...  7  8  9\n0  1  1  1  ...  1  1  1\n1  1  1  1  ...  1  1  1\n2  1  1  1  ...  1  1  1\n3  1  1  1  ...  1  1  1\n4  1  1  1  ...  1  1  1\n5  1  1  1  ...  1  1  1\n6  1  1  1  ...  1  1  1\n7  1  1  1  ...  1  1  1\n8  1  1  1  ...  1  1  1\n9  1  1  1  ...  1  1  1\n\n[10 rows x 10 columns]'  # noqa: E501
    str1 = aNDRepr.repr(df1)
    str2 = aNDRepr.repr(df2)

    assertion.eq(str1, ref1)
    assertion.eq(str2, ref2)
Beispiel #29
0
def test_selected_atoms_with_dftb():
    """Test the DFTB selection atoms funcionality."""
    mol = molkit.from_smiles('CO')
    s = Settings()
    s.selected_atoms = ["H"]
    expected_settings = Settings(
        {'selected_atoms': ['H'], 'specific': dftb_const})
    assertion.eq(dftb.generic2specific(s, mol), expected_settings)
    s.selected_atoms = indices
    expected_settings = Settings(
        {'selected_atoms': indices, 'specific': dftb_const})
    assertion.eq(str(dftb.generic2specific(s, mol)), str(expected_settings))
Beispiel #30
0
def test_series() -> None:
    """Tests for :meth:`NDRepr.repr_Series`."""
    s1 = pd.Series(np.ones(10, dtype='float64'))
    s2 = pd.Series(np.ones(10, dtype='int64'))

    ref1 = '0    1.0\n1    1.0\n2    1.0\n3    1.0\n4    1.0\n5    1.0\n6    1.0\n7    1.0\n8    1.0\n9    1.0\ndtype: float64'  # noqa: E501
    ref2 = '0    1\n1    1\n2    1\n3    1\n4    1\n5    1\n6    1\n7    1\n8    1\n9    1\ndtype: int64'  # noqa: E501
    str1 = aNDRepr.repr(s1)
    str2 = aNDRepr.repr(s2)

    assertion.eq(str1, ref1)
    assertion.eq(str2, ref2)