<commit_before>import numpy
import unittest

from chainer import cuda
from chainer import function
from chainer import functions
from chainer.testing import condition
from chainer import variable

try:
    from chainer.testing import attr
    _error = attr.get_error()
except ImportError as e:
    _error = e


def is_available():
    return _error is None


def check_available():
    if _error is not None:
        raise RuntimeError('''\
{} is not available.

Reason: {}: {}'''.format(__name__, type(_error).__name__, _error))


def _func_name(func):
    if isinstance(func, function.Function):
        return func.__class__.__name__.lower()
    else:
        return func.__name__


def _func_class(func):
    if isinstance(func, function.Function):
        return func.__class__
    else:
        name = func.__name__.capitalize()
        return getattr(functions, name, None)


def _make_data_default(shape, dtype):
    x = numpy.random.uniform(-1, 1, shape).astype(dtype)
    gy = numpy.random.uniform(-1, 1, shape).astype(dtype)
    ggx = numpy.random.uniform(-1, 1, shape).astype(dtype)
    return x, gy, ggx


def unary_math_function_unittest(func, func_expected=None, label_expected=None,
                                 make_data=None):
    """Decorator for testing unary mathematical Chainer functions.

    This decorator makes test classes test unary mathematical Chainer
    functions. Tested are forward and backward, including double backward,
    computations on CPU and GPU across parameterized ``shape`` and ``dtype``.

    Args:
        func(function or ~chainer.Function): Chainer function to be tested by
            the decorated test class. Taking :class:`~chainer.Function` is for
            backward compatibility.
        func_expected: Function used to provide expected values for
            testing forward computation. If not given, a corresponsing numpy
            function for ``func`` is implicitly picked up by its name.
        label_expected(string): String used to test labels of Chainer
            functions. If not given, the name of ``func`` is implicitly used.
        make_data: Function to customize input and gradient data used
            in the tests. It takes ``shape`` and ``dtype`` as its arguments,
            and returns a tuple of input, gradient and double gradient data. By
            default, uniform destribution ranged ``[-1, 1]`` is used for all of
            them.

    The decorated test class tests forward, backward and double backward
    computations on CPU and GPU across the following
    :func:`~chainer.testing.parameterize` ed parameters:

    - shape: rank of zero, and rank of more than zero
    - dtype: ``numpy.float16``, ``numpy.float32`` and ``numpy.float64``

    Additionally, it tests the label of the Chainer function.

    Chainer functions tested by the test class decorated with the decorator
    should have the following properties:

    - Unary, taking one parameter and returning one value
    - ``dtype`` of input and output are the same
    - Elementwise operation for the supplied ndarray

    .. admonition:: Example

       The following code defines a test class that tests
       :func:`~chainer.functions.sin` Chainer function, which takes a parameter
       with ``dtype`` of float and returns a value with the same ``dtype``.

       .. doctest::

          >>> import unittest
          >>> from chainer import testing
          >>> from chainer import functions as F
          >>>
          >>> @testing.unary_math_function_unittest(F.sin)
          ... class TestSin(unittest.TestCase):
          ...     pass

       Because the test methods are implicitly injected to ``TestSin`` class by
       the decorator, it is enough to place ``pass`` in the class definition.

       Now the test is run with ``nose`` module.

       .. doctest::

          >>> import nose
          >>> nose.run(
          ...     defaultTest=__name__, argv=['', '-a', '!gpu'], exit=False)
          True

       To customize test data, ``make_data`` optional parameter can be used.
       The following is an example of testing ``sqrt`` Chainer function, which
       is tested in positive value domain here instead of the default input.

       .. doctest::

          >>> import numpy
          >>>
          >>> def make_data(shape, dtype):
          ...     x = numpy.random.uniform(0.1, 1, shape).astype(dtype)
          ...     gy = numpy.random.uniform(-1, 1, shape).astype(dtype)
          ...     ggx = numpy.random.uniform(-1, 1, shape).astype(dtype)
          ...     return x, gy, ggx
          ...
          >>> @testing.unary_math_function_unittest(F.sqrt,
          ...                                       make_data=make_data)
          ... class TestSqrt(unittest.TestCase):
          ...     pass
          ...
          >>> nose.run(
          ...     defaultTest=__name__, argv=['', '-a', '!gpu'], exit=False)
          True

       ``make_data`` function which returns input, gradient and double gradient
       data generated in proper value domains with given ``shape`` and
       ``dtype`` parameters is defined, then passed to the decorator's
       ``make_data`` parameter.

    """
    check_available()

    # TODO(takagi) In the future, the Chainer functions that could be tested
    #     with the decorator would be extended as:
    #
    #     - Multiple input parameters
    #     - Multiple output values
    #     - Other types than float: integer
    #     - Other operators other than analytic math: basic math

    # Import here to avoid mutual import.
    from chainer import gradient_check<commit_msg>remove interactive test example<commit_after>import numpy
import unittest

from chainer import cuda
from chainer import function
from chainer import functions
from chainer.testing import condition
from chainer import variable

try:
    from chainer.testing import attr
    _error = attr.get_error()
except ImportError as e:
    _error = e


def is_available():
    return _error is None


def check_available():
    if _error is not None:
        raise RuntimeError('''\
{} is not available.

Reason: {}: {}'''.format(__name__, type(_error).__name__, _error))


def _func_name(func):
    if isinstance(func, function.Function):
        return func.__class__.__name__.lower()
    else:
        return func.__name__


def _func_class(func):
    if isinstance(func, function.Function):
        return func.__class__
    else:
        name = func.__name__.capitalize()
        return getattr(functions, name, None)


def _make_data_default(shape, dtype):
    x = numpy.random.uniform(-1, 1, shape).astype(dtype)
    gy = numpy.random.uniform(-1, 1, shape).astype(dtype)
    ggx = numpy.random.uniform(-1, 1, shape).astype(dtype)
    return x, gy, ggx


def unary_math_function_unittest(func, func_expected=None, label_expected=None,
                                 make_data=None):
    """Decorator for testing unary mathematical Chainer functions.

    This decorator makes test classes test unary mathematical Chainer
    functions. Tested are forward and backward, including double backward,
    computations on CPU and GPU across parameterized ``shape`` and ``dtype``.

    Args:
        func(function or ~chainer.Function): Chainer function to be tested by
            the decorated test class. Taking :class:`~chainer.Function` is for
            backward compatibility.
        func_expected: Function used to provide expected values for
            testing forward computation. If not given, a corresponsing numpy
            function for ``func`` is implicitly picked up by its name.
        label_expected(string): String used to test labels of Chainer
            functions. If not given, the name of ``func`` is implicitly used.
        make_data: Function to customize input and gradient data used
            in the tests. It takes ``shape`` and ``dtype`` as its arguments,
            and returns a tuple of input, gradient and double gradient data. By
            default, uniform destribution ranged ``[-1, 1]`` is used for all of
            them.

    The decorated test class tests forward, backward and double backward
    computations on CPU and GPU across the following
    :func:`~chainer.testing.parameterize` ed parameters:

    - shape: rank of zero, and rank of more than zero
    - dtype: ``numpy.float16``, ``numpy.float32`` and ``numpy.float64``

    Additionally, it tests the label of the Chainer function.

    Chainer functions tested by the test class decorated with the decorator
    should have the following properties:

    - Unary, taking one parameter and returning one value
    - ``dtype`` of input and output are the same
    - Elementwise operation for the supplied ndarray

    .. admonition:: Example

       The following code defines a test class that tests
       :func:`~chainer.functions.sin` Chainer function, which takes a parameter
       with ``dtype`` of float and returns a value with the same ``dtype``.

       .. doctest::

          >>> import unittest
          >>> from chainer import testing
          >>> from chainer import functions as F
          >>>
          >>> @testing.unary_math_function_unittest(F.sin)
          ... class TestSin(unittest.TestCase):
          ...     pass

       Because the test methods are implicitly injected to ``TestSin`` class by
       the decorator, it is enough to place ``pass`` in the class definition.

       To customize test data, ``make_data`` optional parameter can be used.
       The following is an example of testing ``sqrt`` Chainer function, which
       is tested in positive value domain here instead of the default input.

       .. doctest::

          >>> import numpy
          >>>
          >>> def make_data(shape, dtype):
          ...     x = numpy.random.uniform(0.1, 1, shape).astype(dtype)
          ...     gy = numpy.random.uniform(-1, 1, shape).astype(dtype)
          ...     ggx = numpy.random.uniform(-1, 1, shape).astype(dtype)
          ...     return x, gy, ggx
          ...
          >>> @testing.unary_math_function_unittest(F.sqrt,
          ...                                       make_data=make_data)
          ... class TestSqrt(unittest.TestCase):
          ...     pass

       ``make_data`` function which returns input, gradient and double gradient
       data generated in proper value domains with given ``shape`` and
       ``dtype`` parameters is defined, then passed to the decorator's
       ``make_data`` parameter.

    """
    check_available()

    # TODO(takagi) In the future, the Chainer functions that could be tested
    #     with the decorator would be extended as:
    #
    #     - Multiple input parameters
    #     - Multiple output values
    #     - Other types than float: integer
    #     - Other operators other than analytic math: basic math

    # Import here to avoid mutual import.
    from chainer import gradient_check
{'fraction_non_alphanumeric': 0.08845590925722649, 'fraction_numerical': 0.0038419319429198683, 'mean_word_length': 2.458715596330275, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 66, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 6, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7238550', 'n_tokens_mistral': 2880, 'n_tokens_neox': 2788, 'n_words': 1113}