示例#1
0
def test_create_csv() -> None:
    """Test :func:`dataCAT.create_database.create_csv`."""
    dtype1 = {'hdf5 index': int, 'formula': str, 'settings': str, 'opt': bool}
    dtype2 = {'hdf5 index': int, 'settings': str, 'opt': bool}

    filename1 = create_csv(PATH, 'ligand')
    filename2 = create_csv(PATH, 'qd')
    assertion.eq(filename1, LIGAND_PATH)
    assertion.eq(filename2, QD_PATH)
    df1 = pd.read_csv(LIGAND_PATH,
                      index_col=[0, 1],
                      header=[0, 1],
                      dtype=dtype1)
    df2 = pd.read_csv(QD_PATH,
                      index_col=[0, 1, 2, 3],
                      header=[0, 1],
                      dtype=dtype2)

    assertion.eq(df1.shape, (1, 4))
    assertion.eq(df2.shape, (1, 5))
    assertion.eq(df1.index.names, ['smiles', 'anchor'])
    assertion.eq(df2.index.names,
                 ['core', 'core anchor', 'ligand smiles', 'ligand anchor'])
    assertion.eq(df1.columns.names, ['index', 'sub index'])
    assertion.eq(df2.columns.names, ['index', 'sub index'])
    assertion.contains(df1.index, ('-', '-'))
    assertion.contains(df2.index, ('-', '-', '-', '-'))

    np.testing.assert_array_equal(
        df1.values, np.array([[-1, 'str', False, 'str']], dtype=object))
    np.testing.assert_array_equal(
        df2.values, np.array([[-1, -1, False, 'str', 'str']], dtype=object))

    assertion.assert_(create_csv, PATH, 'bob', exception=ValueError)
示例#2
0
def test_cp2k_singlepoint_mock(mocker: MockFixture):
    """Mock a call to CP2K."""
    # single point calculation
    s = fill_cp2k_defaults(templates.singlepoint)

    # print orbitals
    s.specific.cp2k.force_eval.dft.print.mo.filename = (
        PATH / "orbitals.out").as_posix()
    s.specific.cp2k.force_eval.dft.print.mo.mo_index_range = "7 46"
    s.specific.cp2k.force_eval.dft.scf.added_mos = 20

    # Construct a result objects
    job = cp2k(s, ETHYLENE)
    jobname = "cp2k_job"
    run_mocked = mock_runner(mocker, jobname)
    rs = run_mocked(job)

    # electronic energy
    assertion.isfinite(rs.energy)

    # Molecular orbitals
    orbs = rs.orbitals
    assertion.assert_(np.isfinite, orbs.eigenvectors,
                      post_process=np.all)  # eigenvalues
    assertion.shape_eq(orbs.eigenvectors, (46, 40))
示例#3
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)
示例#4
0
def test_init() -> None:
    """Test :meth:`PDBContainer.__init__`."""
    atoms = [(True, 1, 'Cad', 'LIG', 'A', 1, -5.231, 0.808, -0.649, 1, 0, 'C',
              0, 0)]
    bonds = [(1, 2, 1)]
    assertion.assert_(PDBContainer, atoms, bonds, 1, 1)

    index = range(1)
    assertion.assert_(PDBContainer, atoms, bonds, 1, 1, index)
示例#5
0
def test_combine_sigma() -> None:
    """Test :func:`FOX.functions.lj_uff.combine_sigma`."""
    ref = np.load(PATH / 'uff_sigma.npy')
    sigma = np.array([
        combine_sigma(at1, at2) for at1, at2 in combinations(UFF_DF.index, r=2)
    ])

    np.testing.assert_allclose(sigma, ref)
    assertion.assert_(combine_sigma, 'a', 'b', exception=ValueError)
示例#6
0
def test_charge_tolerance() -> None:
    """Test ``param.validation.charge_tolerance``."""
    file = PATH / 'armc_ref.yaml'
    with open(file, 'r') as f:
        dct = yaml.load(f.read(), Loader=UniqueLoader)

    dct = dct.copy()
    dct['param']['charge']['Cd'] = 2
    assertion.assert_(dict_to_armc, dct, exception=ValueError)

    dct['param']['validation']['charge_tolerance'] = 'inf'
    assertion.assert_(dict_to_armc, dct)
示例#7
0
def test_param_sorting() -> None:
    """Tests for :func:`FOX.armc.sanitization._sort_atoms`"""
    df1 = DF.copy()
    df1.loc[6, "atoms"] = "Se Cd"
    df1.loc[13, "atoms"] = "Se O_1"
    _sort_atoms(df1)
    np.testing.assert_array_equal(df1, DF)

    df2 = DF.copy()
    df2.loc[4, "atoms"] = "Se Cd"
    df2.loc[5, "atoms"] = "Cd Se"
    df2.loc[6, "atoms"] = "Se Cd"
    assertion.assert_(_sort_atoms, df2, exception=ValueError)
示例#8
0
def test_get_sphinx_domain() -> None:
    """Tests for :func:`~assertionlib.functions.get_sphinx_domain`."""
    v1 = get_sphinx_domain(int)
    v2 = get_sphinx_domain(list.count)
    v3 = get_sphinx_domain(OrderedDict)
    v4 = get_sphinx_domain(OrderedDict.keys)
    v5 = get_sphinx_domain(isinstance)

    assertion.eq(v1, ':class:`int<python:int>`')
    assertion.eq(v2, ':meth:`list.count()<python:list.count>`')
    assertion.eq(v3, ':class:`~collections.OrderedDict`')
    assertion.eq(v4, ':meth:`~collections.OrderedDict.keys`')
    assertion.eq(v5, ':func:`isinstance()<python:isinstance>`')

    assertion.assert_(get_sphinx_domain, 1, exception=TypeError)
示例#9
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'))
示例#10
0
def test_get_key_path() -> None:
    """Tests for :func:`_get_key_path`."""
    # Pass a string with a valid key path alias
    assertion.eq(_get_key_path('bond'), CP2K_KEYS_ALIAS['bond'])
    assertion.eq(_get_key_path('lennard-jones'),
                 CP2K_KEYS_ALIAS['lennard-jones'])
    assertion.eq(_get_key_path('genpot14'), CP2K_KEYS_ALIAS['genpot14'])

    # Directly pass a key path
    ref = ('specific', 'cp2k', 'a', 'b', 'c')
    assertion.eq(_get_key_path(('a', 'b', 'c')), ref)
    assertion.eq(_get_key_path(('specific', 'cp2k', 'a', 'b', 'c')), ref)
    assertion.eq(_get_key_path(('input', 'a', 'b', 'c')), ref)

    # Don't know these keys
    assertion.assert_(_get_key_path, 'bob', exception=KeyError)
    assertion.assert_(_get_key_path, 5, exception=KeyError)
示例#11
0
def test_degree_of_separation():
    """Test :func:`degree_of_separation`."""
    ref1 = np.load(PATH / 'degree_of_separation.npy')
    ref2 = ref1.copy()
    ref2[ref1 > 1] = np.inf

    mat1 = degree_of_separation(MOL)
    mat2 = degree_of_separation(MOL, bond_mat=MOL.bond_matrix())
    mat3 = degree_of_separation(MOL, limit=1)

    np.testing.assert_array_equal(mat1, ref1)
    np.testing.assert_array_equal(mat2, ref1)
    np.testing.assert_array_equal(mat3, ref2)

    mol = MOL.copy()
    mol.delete_all_bonds()
    assertion.assert_(degree_of_separation, mol, exception=MoleculeError)
示例#12
0
def test_prm_to_df() -> None:
    """Tests for :func:`prm_to_df`."""
    s = Settings()
    s.lennard_jones = {
        'param': ('epsilon', 'sigma'),
        'unit': ('kcalmol', 'angstrom'),
        'Cs': (1, 1),
        'Cd': (2, 2),
        'O': (3, 3),
        'H': (4, 4)
    }

    ref = {
        'param': {
            'epsilon': 'epsilon',
            'sigma': 'sigma'
        },
        'unit': {
            'epsilon': 'kcalmol',
            'sigma': 'angstrom'
        },
        'Cs': {
            'epsilon': 1.0,
            'sigma': 1.0
        },
        'Cd': {
            'epsilon': 2.0,
            'sigma': 2.0
        },
        'O': {
            'epsilon': 3.0,
            'sigma': 3.0
        },
        'H': {
            'epsilon': 4.0,
            'sigma': 4.0
        }
    }
    prm_to_df(s)
    assertion.eq(s['lennard_jones'].to_dict(), ref)

    # The 'param' key is missing
    s2 = {'lennard-jones': {'Cs': (1, 2)}}
    assertion.assert_(prm_to_df, s2, exception=KeyError)
示例#13
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)
示例#14
0
def test_identify_surface() -> None:
    """Tests for :func:`nanoCAT.bde.guess_core_dist.guess_core_core_dist`."""
    idx_superset = np.array([i for i, atom in enumerate(MOL) if atom.symbol == 'Cd'])
    xyz = np.array(MOL)[idx_superset]

    idx_subset = idx_superset[identify_surface(xyz)]
    ref = [3, 4, 5, 6, 13, 14, 16, 23, 26, 32, 33, 34, 36, 41, 46, 48, 53, 54, 55, 56, 57, 58, 62,
           63, 65, 68, 69, 74, 77, 79, 80, 82, 83, 86, 92, 93, 94, 95, 96, 99, 101, 105, 106, 111,
           112, 113, 118, 119, 120, 126, 128, 129, 135, 138, 143, 144, 146, 147, 153, 155, 156, 157,
           158, 159, 160, 161, 162, 163, 167, 168, 170, 171, 172, 173, 174, 175, 176, 177, 179, 181,
           183, 186, 187, 188, 190, 191, 192, 193, 196, 199, 200, 201, 205, 206, 210, 212, 217, 221,
           226, 227, 228, 229, 234, 235, 237, 238, 239, 240, 241, 242, 243, 244, 247, 250, 252, 253,
           254, 255, 258, 260, 263, 264, 265, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277,
           283, 285, 288, 289, 290, 291, 294, 295, 297, 300, 301, 302, 303, 305, 306, 307, 308, 309,
           311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 325, 327, 328, 330, 331,
           333, 335, 337, 338, 340, 348, 349, 353, 354, 355, 356, 357, 358, 359]
    np.testing.assert_array_equal(idx_subset, ref)

    assertion.assert_(identify_surface, MOL, max_dist=1, exception=ValueError)
示例#15
0
def test_get_importable() -> None:
    """Tests for :func:`nanoutils.get_importable`."""
    class Test:
        split = True

    assertion.is_(get_importable('builtins.dict'), dict)
    assertion.is_(get_importable('builtins.dict', validate=isclass), dict)

    assertion.assert_(get_importable, None, exception=TypeError)
    assertion.assert_(get_importable, Test, exception=TypeError)
    assertion.assert_(get_importable, 'builtins.len', validate=isclass, exception=RuntimeError)
    assertion.assert_(get_importable, 'builtins.len', validate=partial(isclass),
                      exception=RuntimeError)
示例#16
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)
示例#17
0
def test_get_pairs_closest() -> None:
    """Tests for :meth:`MolDissociater.get_pairs_closest`."""
    dissociate = MolDissociater(MOL, CORE_IDX, ligand_count=2)
    pair1 = dissociate.get_pairs_closest(LIG_IDX, n_pairs=1)
    pair2 = dissociate.get_pairs_closest(LIG_IDX, n_pairs=2)
    pair3 = dissociate.get_pairs_closest(LIG_IDX, n_pairs=3)

    dissociate.ligand_count = 4
    pair4 = dissociate.get_pairs_closest(LIG_IDX, n_pairs=1)
    pair5 = dissociate.get_pairs_closest(LIG_IDX, n_pairs=2)
    pair6 = dissociate.get_pairs_closest(LIG_IDX, n_pairs=3)

    assertion.assert_(dissociate.get_pairs_closest,
                      LIG_IDX,
                      0,
                      exception=ValueError)

    pairs = (pair1, pair2, pair3, pair4, pair5, pair6)
    for i, pair in enumerate(pairs, 1):
        ref = np.load(PATH / f'get_pairs_closest_{i}.npy')
        np.testing.assert_array_equal(pair, ref)
示例#18
0
def test_get_pairs_distance() -> None:
    """Tests for :meth:`MolDissociater.get_pairs_distance`."""
    dissociate = MolDissociater(MOL, CORE_IDX, ligand_count=2)
    pair1 = dissociate.get_pairs_distance(LIG_IDX, max_dist=5.0)
    pair2 = dissociate.get_pairs_distance(LIG_IDX, max_dist=7.5)

    dissociate.ligand_count = 4
    pair3 = dissociate.get_pairs_distance(LIG_IDX, max_dist=7.5)
    pair4 = dissociate.get_pairs_distance(LIG_IDX, max_dist=10.0)

    assertion.assert_(dissociate.get_pairs_distance,
                      LIG_IDX,
                      0,
                      exception=ValueError)
    assertion.assert_(dissociate.get_pairs_distance,
                      LIG_IDX,
                      1.0,
                      exception=MoleculeError)
    dissociate.ligand_count = 99
    assertion.assert_(dissociate.get_pairs_distance,
                      LIG_IDX,
                      5.0,
                      exception=MoleculeError)

    pairs = (pair1, pair2, pair3, pair4)
    for i, pair in enumerate(pairs, 1):
        ref = np.load(PATH / f'get_pairs_distance_{i}.npy')
        np.testing.assert_array_equal(pair, ref)
示例#19
0
def test_split_dict() -> None:
    """Test :func:`nanoutils.split_dict`."""
    dct1 = {1: 1, 2: 2, 3: 3, 4: 4, 5: 5}
    dct2 = dct1.copy()
    dct3 = dct1.copy()
    dct4 = dct1.copy()
    dct5 = dct1.copy()
    dct6 = dct1.copy()
    dct7 = dct1.copy()
    dct8 = dct1.copy()

    ref1 = {1: 1, 2: 2}
    ref2 = {3: 3, 4: 4, 5: 5}

    split_dict(dct1, keep_keys=[1, 2])
    split_dict(dct2, keep_keys={1, 2})
    split_dict(dct3, keep_keys=iter({1, 2}))
    split_dict(dct4, keep_keys=[1, 2], preserve_order=True)
    assertion.eq(dct1, ref1)
    assertion.eq(dct2, ref1)
    assertion.eq(dct3, ref1)
    assertion.eq(dct4, ref1)
    if sys.version_info[1] > 6:
        assertion.eq(list(dct4.keys()), [1, 2])

    split_dict(dct5, disgard_keys=[1, 2])
    split_dict(dct6, disgard_keys={1, 2})
    split_dict(dct7, disgard_keys=iter({1, 2}))
    split_dict(dct8, disgard_keys=[1, 2], preserve_order=True)
    assertion.eq(dct5, ref2)
    assertion.eq(dct6, ref2)
    assertion.eq(dct7, ref2)
    assertion.eq(dct8, ref2)
    if sys.version_info[1] > 6:
        assertion.eq(list(dct8.keys()), [3, 4, 5])

    assertion.assert_(split_dict, {}, exception=TypeError)
    assertion.assert_(split_dict, {}, keep_keys=[], disgard_keys=[], exception=TypeError)
示例#20
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)
示例#21
0
def test_get_exc_message() -> None:
    """Test :meth:`AssertionManager._get_exc_message`."""
    ex = TypeError("object of type 'int' has no len()")
    func1 = len
    args = (1,)

    str1: str = assertion._get_exc_message(ex, func1, *args, invert=False, output=None)  # type: ignore[attr-defined]  # noqa: E501
    str2: str = assertion._get_exc_message(ex, func1, *args, invert=True, output=None)  # type: ignore[attr-defined]  # noqa: E501
    ref1 = """output = len(obj); assert output

exception: TypeError = "object of type 'int' has no len()"

output: NoneType = None
obj: int = 1"""
    ref2 = """output = not len(obj); assert output

exception: TypeError = "object of type 'int' has no len()"

output: NoneType = None
obj: int = 1"""

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

    func2: Callable = assertion._get_exc_message  # type: ignore[attr-defined]
    assertion.assert_(func2, ex, 1, exception=TypeError)

    func3 = partial(len)
    str3 = assertion._get_exc_message(ex, func3)  # type: ignore[attr-defined]
    assertion.contains(str3, 'functools.partial(<built-in function len>)')

    class Func():
        def __call__(self): pass

    str4: str = assertion._get_exc_message(ex, Func())  # type: ignore[attr-defined]
    assertion.contains(str4, 'output = func(); assert output')
示例#22
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)
示例#23
0
def test_validate_unit() -> None:
    """Tests for :func:`_validate_unit`."""
    columns = ['1', '2']

    # Valid inputs
    unit_iter1 = ['a', 'b']
    unit_iter2 = repeat('a')
    assertion.assert_(_validate_unit, unit_iter1, columns, invert=True)
    assertion.assert_(_validate_unit, unit_iter2, columns, invert=True)

    # *unit_iter3* is too short; should raise a LengthError
    unit_iter3 = ['a']
    assertion.assert_(_validate_unit,
                      unit_iter3,
                      columns,
                      exception=LengthError)
示例#24
0
def test_allow_non_existent() -> None:
    """Test ``param.validation.allow_non_existent``."""
    file = PATH / 'armc_ref.yaml'
    with open(file, 'r') as f:
        dct = yaml.load(f.read(), Loader=UniqueLoader)

    # Test `param.validation.allow_non_existent`
    dct['param']['charge']['Cl'] = -1
    assertion.assert_(dict_to_armc, dct, exception=RuntimeError)

    del dct['psf']
    del dct['param']['charge']['constraints'][0]
    assertion.assert_(dict_to_armc, dct, exception=RuntimeError)

    with warnings.catch_warnings():
        warnings.simplefilter("ignore", RuntimeWarning)
        dct['param']['validation']['allow_non_existent'] = True
        dct['param']['validation']['charge_tolerance'] = 'inf'
        assertion.assert_(dict_to_armc, dct)
示例#25
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)
示例#26
0
def test_sparse_bond_matrix():
    """Test :func:`sparse_bond_matrix`."""
    ref1 = np.load(PATH / 'sparse_bond_matrix.npy')
    ref2 = ref1.astype(int)
    ref3 = ref1.astype(bool)

    mat1 = sparse_bond_matrix(MOL, dtype=float)
    mat2 = sparse_bond_matrix(MOL, dtype=int)
    mat3 = sparse_bond_matrix(MOL)

    np.testing.assert_array_equal(mat1.toarray(), ref1)
    np.testing.assert_array_equal(mat2.toarray(), ref2)
    np.testing.assert_array_equal(mat3.toarray(), ref3)

    sparse_type_tup = (bsr_matrix, coo_matrix, csr_matrix, csc_matrix,
                       dia_matrix, dok_matrix, lil_matrix)

    with warnings.catch_warnings():
        warnings.simplefilter('ignore',
                              category=np.VisibleDeprecationWarning())

        for sparse_type in sparse_type_tup:
            mat_n = sparse_bond_matrix(MOL, sparse_type=sparse_type)
            np.testing.assert_array_equal(mat_n.toarray(), ref3)

    assertion.assert_(sparse_bond_matrix,
                      MOL,
                      dtype='bob',
                      exception=TypeError)
    assertion.assert_(sparse_bond_matrix,
                      MOL,
                      sparse_type='bob',
                      exception=TypeError)
    assertion.assert_(sparse_bond_matrix,
                      MOL,
                      sparse_type=int,
                      exception=TypeError)
示例#27
0
def test_none_exception() -> None:
    """Test :class:`_NoneException`."""
    assertion.assert_(_NoneException, exception=TypeError)
    assertion.issubclass(_NoneException, Exception, invert=True)
示例#28
0
def test_coordination_number() -> None:
    """Tests for :func:`nanoCAT.recipes.coordination_number`."""

    out_inner = coordination_number(MOL, shell='inner')

    out_outer = coordination_number(MOL, shell='outer', d_outer=5.2)

    ref_inner = {
        'Cd': {
            3: [
                30, 31, 34, 35, 36, 46, 47, 52, 53, 54, 57, 58, 59, 60, 63, 64,
                65, 67, 69, 70, 71, 75, 78, 79
            ],
            4: [
                1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 32, 33,
                37, 38, 39, 40, 41, 42, 43, 44, 45, 48, 49, 50, 51, 55, 56, 61,
                62, 66, 68, 72, 73, 74, 76, 77, 80, 81
            ]
        },
        'Se': {
            3: [
                82, 84, 87, 88, 90, 91, 92, 95, 96, 97, 99, 100, 101, 102, 103,
                106, 107, 108, 118, 119, 120, 121, 122, 123
            ],
            4: [
                17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 83, 85, 86,
                89, 93, 94, 98, 104, 105, 109, 110, 111, 112, 113, 114, 115,
                116, 117
            ]
        },
        'Cl': {
            2: [
                124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135,
                136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147,
                148, 149
            ]
        }
    }

    ref_outer = {
        'Cd': {
            6: [33, 59, 65, 66],
            7: [5, 6, 8, 13, 39, 77],
            8: [
                30, 31, 32, 34, 35, 36, 46, 47, 52, 53, 54, 57, 58, 60, 63, 64,
                67, 69, 70, 71, 75, 78, 79, 81
            ],
            9: [4, 11, 40, 41, 48, 49, 50, 51, 55, 73, 76, 80],
            10: [7, 10, 12, 15, 42, 44, 45, 56],
            11: [2, 16, 43, 68],
            12: [1, 3, 9, 14, 37, 38, 61, 62, 72, 74]
        },
        'Se': {
            6: [102, 121],
            7: [84, 87, 97, 99, 103, 106, 108, 118],
            8: [88, 90, 91, 92, 95, 96, 100, 101, 107, 119, 120, 122],
            9: [82, 104, 115, 123],
            10: [98, 109, 110],
            11: [86, 105],
            12: [20, 22, 27, 28, 83, 113, 114],
            13: [18, 19, 24, 26, 85, 117],
            14: [17, 21, 25, 29, 89, 93, 94, 111, 112, 116],
            16: [23]
        },
        'Cl': {
            7: [124, 128],
            9: [127, 132, 133, 136, 144, 148],
            10: [
                125, 126, 129, 130, 131, 134, 135, 137, 138, 139, 140, 141,
                142, 143, 145, 146, 147, 149
            ]
        }
    }

    np.testing.assert_equal(out_inner, ref_inner)
    np.testing.assert_equal(out_outer, ref_outer)

    assertion.assert_(coordination_number,
                      MOL,
                      shell='bob',
                      exception=ValueError)
    assertion.assert_(coordination_number,
                      MOL,
                      shell='outer',
                      d_outer=None,
                      exception=TypeError)
示例#29
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)
示例#30
0
def test_construct_df() -> None:
    """Tests for :func:`_construct_df`."""
    dict1 = {'Cs': (1, 1), 'Cd': (2, 2), 'O': (3, 3), 'H': (4, 4)}
    dict2 = {'Cs': 1, 'Cd': 2, 'O': 3, 'H': 4}
    dict3 = {'Cs': 1, 'Cd': 2, 'O': (3, 3), 'H': (4, 4)}
    dict4 = {k: set(v) for k, v in dict1.items()}
    c1 = ['a', 'b']
    c2 = 'a'

    ref1 = np.array([v for v in dict1.values()], dtype=str).astype(object)
    ref2 = np.array([v for v in dict2.values()],
                    dtype=str).astype(object)[..., None]

    np.testing.assert_array_equal(_construct_df(c1, dict1), ref1)
    np.testing.assert_array_equal(_construct_df(c2, dict2), ref2)

    # No mixing of scalars and sequences allowed
    assertion.assert_(_construct_df, c1, dict2, exception=TypeError)
    assertion.assert_(_construct_df, c2, dict1, exception=TypeError)
    assertion.assert_(_construct_df, c1, dict3, exception=TypeError)
    assertion.assert_(_construct_df, c1, dict3, exception=TypeError)

    # The dict values are now either too long or too short
    assertion.assert_(_construct_df, [c2], dict1, exception=LengthError)
    assertion.assert_(_construct_df, [c2, c2, c2],
                      dict1,
                      exception=LengthError)

    # Collections (e.g. a set) are not allowed as dictionary values; requires a proper Sequence
    assertion.assert_(_construct_df, c1, dict4, exception=TypeError)