<commit_before>from collections.abc import Sequence, Mapping
import math
from numbers import Number

import numpy as np

import hoomd
from hoomd import md
from hoomd.logging import LoggerCategories
from hoomd.conftest import logging_check
import pytest
import itertools
from copy import deepcopy
import json
from pathlib import Path
from collections import namedtuple


def _equivalent_data_structures(reference, struct_2):
    """Compare arbitrary data structures for equality.

    ``reference`` is expected to be the reference data structure. Cannot handle
    set like data structures.
    """
    if isinstance(reference, np.ndarray):
        return np.allclose(reference, struct_2)
    if isinstance(reference, Mapping):
        # if the non-reference value does not have all the keys
        # we don't check for the exact same keys, since some values may have
        # defaults.
        if set(reference.keys()) - set(struct_2.keys()):
            return False
        return all(
            _equivalent_data_structures(reference[key], struct_2[key])
            for key in reference
        )
    if isinstance(reference, Sequence):
        if len(reference) != len(struct_2):
            return False
        return all(
            _equivalent_data_structures(value_1, value_2)
            for value_1, value_2 in zip(reference, struct_2)
        )
    if isinstance(reference, Number):
        return math.isclose(reference, struct_2)


def _assert_equivalent_type_params(type_param0, type_param2):
    """
    Compare entries in type_param1 and type_param2.

    type_param1 is the dictionary used to set the potential
    arguments, whereas type_param2 is the dictionary returned
    from the potential's to_dict method. This means type_param2
    includes default arguments in addition to all keys in type_param1
    """
    for pair in type_param1:
        if isinstance(type_param1[pair], dict):
            for key in type_param1[pair]:
                np.testing.assert_allclose(type_param1[pair][key],
                                           type_param2[pair][key])
        else:
            assert type_param1[pair] == type_param2[pair]


def _assert_equivalent_parameter_dicts(param_dict1, param_dict2):
    for key in param_dict1:
        assert param_dict1[key] == param_dict2[key]


def test_rcut(simulation_factory, two_particle_snapshot_factory):
    lj = md.pair.LJ(nlist=md.nlist.Cell(), r_cut=2.5)
    assert lj.r_cut.default == 2.5

    lj.params[('A', 'A')] = {'sigma': 1, 'epsilon': 0.5}
    with pytest.raises(hoomd.data.typeconverter.TypeConversionError):
        lj.r_cut[('A', 'A')] = 'str'
    with pytest.raises(hoomd.data.typeconverter.TypeConversionError):
        lj.r_cut[('A', 'A')] = [1, 2, 3]

    sim = simulation_factory(two_particle_snapshot_factory(dimensions=3, d=.5))
    integrator = md.Integrator(dt=0.005)
    integrator.forces.append(lj)
    integrator.methods.append(hoomd.md.methods.Langevin(hoomd.filter.All(),
                                                        kT=1))
    sim.operations.integrator = integrator

    lj.r_cut[('A', 'A')] = 2.5
    assert _equivalent_data_structures({('A', 'A'): 2.5}, lj.r_cut.to_dict())
    sim.run(0)
    assert _equivalent_data_structures({('A', 'A'): 2.5}, lj.r_cut.to_dict())


def test_invalid_mode():
    cell = md.nlist.Cell()
    for invalid_mode in [1, 'str', [1, 2, 3]]:
        with pytest.raises(hoomd.data.typeconverter.TypeConversionError):
            lj = md.pair.LJ(nlist=cell, r_cut=2.5, mode=invalid_mode)


@pytest.mark.parametrize("mode", ['none', 'shift', 'xplor'])
def test_mode(simulation_factory, two_particle_snapshot_factory, mode):
    cell = md.nlist.Cell()
    lj = md.pair.LJ(nlist=cell, r_cut=2.5, mode=mode)
    lj.params[('A', 'A')] = {'sigma': 1, 'epsilon': 0.5}
    snap = two_particle_snapshot_factory(dimensions=3, d=.5)
    sim = simulation_factory(snap)
    integrator = md.Integrator(dt=0.005)
    integrator.forces.append(lj)
    integrator.methods.append(hoomd.md.methods.Langevin(hoomd.filter.All(),
                                                        kT=1))
    sim.operations.integrator = integrator
    sim.run(1)


def test_ron(simulation_factory, two_particle_snapshot_factory):
    lj = md.pair.LJ(nlist=md.nlist.Cell(), mode='xplor', r_cut=2.5)
    lj.params[('A', 'A')] = {'sigma': 1, 'epsilon': 0.5}
    with pytest.raises(hoomd.data.typeconverter.TypeConversionError):
        lj.r_on[('A', 'A')] = 'str'
    with pytest.raises(hoomd.data.typeconverter.TypeConversionError):
        lj.r_on[('A', 'A')] = [1, 2, 3]

    sim = simulation_factory(two_particle_snapshot_factory(dimensions=3, d=.5))
    integrator = md.Integrator(dt=0.005)
    integrator.forces.append(lj)
    integrator.methods.append(hoomd.md.methods.Langevin(hoomd.filter.All(),
                                                        kT=1))
    sim.operations.integrator = integrator
    assert lj.r_on.to_dict() == {}

    lj.r_on[('A', 'A')] = 1.5
    assert _equivalent_data_structures({('A', 'A'): 1.5}, lj.r_on.to_dict())
    sim.run(0)
    assert _equivalent_data_structures({('A', 'A'): 1.5}, lj.r_on.to_dict())

    lj.r_on[('A', 'A')] = 1.0
    assert _equivalent_data_structures({('A', 'A'): 1.0}, lj.r_on.to_dict())


def _make_invalid_param_dict(valid_dict):
    """This could potential be fragile if multiple types are allowed for a key."""
    invalid_dicts = [valid_dict] * len(valid_dict.keys()) * 2
    count = 0
    for key in valid_dict.keys():
        invalid_count = 0
        # Set one invalid argument per dictionary
        # Set two invalid arguments per key
        valid_value = invalid_dicts[count][key]
        if not (isinstance(valid_value, list) or isinstance(valid_value, np.ndarray)):
            invalid_dicts[count][key] = [1, 2]
            invalid_count += 1
        if not (isinstance(valid_value, str) or isinstance(valid_value, np.ndarray)):
            invalid_dicts[count + 1][key] = 'str'
            invalid_count += 1
        if invalid_count == 2:
            break
        if not isinstance(valid_value, float):
            invalid_dicts[count][key] = 1.0
            invalid_count += 1
        if invalid_count == 2:
            break
        if not isinstance(valid_value, bool):
            invalid_dicts[count + 1][key] = False
            invalid_count += 1
        if invalid_count != 2:
            raise RuntimeError("Unable to generate 2 invalid dict entries.")
        count += 2
    return invalid_dicts


paramtuple = namedtuple('paramtuple',
                        ['pair_potential',
                         'pair_potential_params',
                         'extra_args'])
<commit_msg>Shorten check for numpy array or list in _make_invalid_param_dict<commit_after>from collections.abc import Sequence, Mapping
import math
from numbers import Number

import numpy as np

import hoomd
from hoomd import md
from hoomd.logging import LoggerCategories
from hoomd.conftest import logging_check
import pytest
import itertools
from copy import deepcopy
import json
from pathlib import Path
from collections import namedtuple


def _equivalent_data_structures(reference, struct_2):
    """Compare arbitrary data structures for equality.

    ``reference`` is expected to be the reference data structure. Cannot handle
    set like data structures.
    """
    if isinstance(reference, np.ndarray):
        return np.allclose(reference, struct_2)
    if isinstance(reference, Mapping):
        # if the non-reference value does not have all the keys
        # we don't check for the exact same keys, since some values may have
        # defaults.
        if set(reference.keys()) - set(struct_2.keys()):
            return False
        return all(
            _equivalent_data_structures(reference[key], struct_2[key])
            for key in reference
        )
    if isinstance(reference, Sequence):
        if len(reference) != len(struct_2):
            return False
        return all(
            _equivalent_data_structures(value_1, value_2)
            for value_1, value_2 in zip(reference, struct_2)
        )
    if isinstance(reference, Number):
        return math.isclose(reference, struct_2)


def _assert_equivalent_type_params(type_param0, type_param2):
    """
    Compare entries in type_param1 and type_param2.

    type_param1 is the dictionary used to set the potential
    arguments, whereas type_param2 is the dictionary returned
    from the potential's to_dict method. This means type_param2
    includes default arguments in addition to all keys in type_param1
    """
    for pair in type_param1:
        if isinstance(type_param1[pair], dict):
            for key in type_param1[pair]:
                np.testing.assert_allclose(type_param1[pair][key],
                                           type_param2[pair][key])
        else:
            assert type_param1[pair] == type_param2[pair]


def _assert_equivalent_parameter_dicts(param_dict1, param_dict2):
    for key in param_dict1:
        assert param_dict1[key] == param_dict2[key]


def test_rcut(simulation_factory, two_particle_snapshot_factory):
    lj = md.pair.LJ(nlist=md.nlist.Cell(), r_cut=2.5)
    assert lj.r_cut.default == 2.5

    lj.params[('A', 'A')] = {'sigma': 1, 'epsilon': 0.5}
    with pytest.raises(hoomd.data.typeconverter.TypeConversionError):
        lj.r_cut[('A', 'A')] = 'str'
    with pytest.raises(hoomd.data.typeconverter.TypeConversionError):
        lj.r_cut[('A', 'A')] = [1, 2, 3]

    sim = simulation_factory(two_particle_snapshot_factory(dimensions=3, d=.5))
    integrator = md.Integrator(dt=0.005)
    integrator.forces.append(lj)
    integrator.methods.append(hoomd.md.methods.Langevin(hoomd.filter.All(),
                                                        kT=1))
    sim.operations.integrator = integrator

    lj.r_cut[('A', 'A')] = 2.5
    assert _equivalent_data_structures({('A', 'A'): 2.5}, lj.r_cut.to_dict())
    sim.run(0)
    assert _equivalent_data_structures({('A', 'A'): 2.5}, lj.r_cut.to_dict())


def test_invalid_mode():
    cell = md.nlist.Cell()
    for invalid_mode in [1, 'str', [1, 2, 3]]:
        with pytest.raises(hoomd.data.typeconverter.TypeConversionError):
            lj = md.pair.LJ(nlist=cell, r_cut=2.5, mode=invalid_mode)


@pytest.mark.parametrize("mode", ['none', 'shift', 'xplor'])
def test_mode(simulation_factory, two_particle_snapshot_factory, mode):
    cell = md.nlist.Cell()
    lj = md.pair.LJ(nlist=cell, r_cut=2.5, mode=mode)
    lj.params[('A', 'A')] = {'sigma': 1, 'epsilon': 0.5}
    snap = two_particle_snapshot_factory(dimensions=3, d=.5)
    sim = simulation_factory(snap)
    integrator = md.Integrator(dt=0.005)
    integrator.forces.append(lj)
    integrator.methods.append(hoomd.md.methods.Langevin(hoomd.filter.All(),
                                                        kT=1))
    sim.operations.integrator = integrator
    sim.run(1)


def test_ron(simulation_factory, two_particle_snapshot_factory):
    lj = md.pair.LJ(nlist=md.nlist.Cell(), mode='xplor', r_cut=2.5)
    lj.params[('A', 'A')] = {'sigma': 1, 'epsilon': 0.5}
    with pytest.raises(hoomd.data.typeconverter.TypeConversionError):
        lj.r_on[('A', 'A')] = 'str'
    with pytest.raises(hoomd.data.typeconverter.TypeConversionError):
        lj.r_on[('A', 'A')] = [1, 2, 3]

    sim = simulation_factory(two_particle_snapshot_factory(dimensions=3, d=.5))
    integrator = md.Integrator(dt=0.005)
    integrator.forces.append(lj)
    integrator.methods.append(hoomd.md.methods.Langevin(hoomd.filter.All(),
                                                        kT=1))
    sim.operations.integrator = integrator
    assert lj.r_on.to_dict() == {}

    lj.r_on[('A', 'A')] = 1.5
    assert _equivalent_data_structures({('A', 'A'): 1.5}, lj.r_on.to_dict())
    sim.run(0)
    assert _equivalent_data_structures({('A', 'A'): 1.5}, lj.r_on.to_dict())

    lj.r_on[('A', 'A')] = 1.0
    assert _equivalent_data_structures({('A', 'A'): 1.0}, lj.r_on.to_dict())


def _make_invalid_param_dict(valid_dict):
    """This could potential be fragile if multiple types are allowed for a key."""
    invalid_dicts = [valid_dict] * len(valid_dict.keys()) * 2
    count = 0
    for key in valid_dict.keys():
        invalid_count = 0
        # Set one invalid argument per dictionary
        # Set two invalid arguments per key
        valid_value = invalid_dicts[count][key]
        if not (isinstance(valid_value, (list, np.ndarray)):
            invalid_dicts[count][key] = [1, 2]
            invalid_count += 1
        if not (isinstance(valid_value, str) or isinstance(valid_value, np.ndarray)):
            invalid_dicts[count + 1][key] = 'str'
            invalid_count += 1
        if invalid_count == 2:
            break
        if not isinstance(valid_value, float):
            invalid_dicts[count][key] = 1.0
            invalid_count += 1
        if invalid_count == 2:
            break
        if not isinstance(valid_value, bool):
            invalid_dicts[count + 1][key] = False
            invalid_count += 1
        if invalid_count != 2:
            raise RuntimeError("Unable to generate 2 invalid dict entries.")
        count += 2
    return invalid_dicts


paramtuple = namedtuple('paramtuple',
                        ['pair_potential',
                         'pair_potential_params',
                         'extra_args'])

{'fraction_non_alphanumeric': 0.11918995665819758, 'fraction_numerical': 0.017635629950680017, 'mean_word_length': 2.7794408359220557, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 16, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '501863', 'n_tokens_mistral': 4443, 'n_tokens_neox': 4234, 'n_words': 972}