Exemple #1
0
 def __pow__(self, val):
     if not isscalar(val) or int(val) != val or val < 0:
         raise ValueError("Power to non-negative integers only.")
     res = [1]
     for _ in range(val):
         res = polymul(self.coeffs, res)
     return poly1d(res)
 def __pow__(self, val):
     if not isscalar(val) or int(val) != val or val < 0:
         raise ValueError("Power to non-negative integers only.")
     res = [1]
     for _ in range(val):
         res = polymul(self.coeffs, res)
     return poly1d(res)
Exemple #3
0
 def __itruediv__(self, other, stream=0):
     if self.__device_manager__ == 'host':
         if isscalar(other) or isinstance(other, np.ndarray):
             self._data /= other
         elif isinstance(other, self.__class__):
             self._data /= other.to_host().data
         else:
             raise NotImplementedError
     elif self.__device_manager__ == 'gpu':
         if isinstance(other, self.__class__):
             cuda_itruediv_with_array(self._data,
                                      other.to_device(stream).data, stream)
         elif isinstance(other, DeviceNDArray):
             cuda_itruediv_with_array(self._data, other, stream)
         elif isinstance(other, np.ndarray):
             cuda_itruediv_with_array(self._data, cuda.to_device(other),
                                      stream)
         elif isscalar(other):
             cuda_itruediv_with_scale(self._data, other, stream)
         else:
             raise NotImplementedError
     else:
         raise NotImplementedError
     return self
Exemple #4
0
def assert_equal(actual,desired,err_msg='',verbose=True):
    """
    Raise an assertion if two objects are not equal.

    Given two objects (lists, tuples, dictionaries or numpy arrays), check
    that all elements of these objects are equal. An exception is raised at
    the first conflicting values.

    Parameters
    ----------
    actual : list, tuple, dict or ndarray
      The object to check.
    desired : list, tuple, dict or ndarray
      The expected object.
    err_msg : string
      The error message to be printed in case of failure.
    verbose : bool
      If True, the conflicting values are appended to the error message.

    Raises
    ------
    AssertionError
      If actual and desired are not equal.

    Examples
    --------
    >>> np.testing.assert_equal([4,5], [4,6])
    ...
    <type 'exceptions.AssertionError'>:
    Items are not equal:
    item=1
     ACTUAL: 5
     DESIRED: 6

    """
    if isinstance(desired, dict):
        if not isinstance(actual, dict) :
            raise AssertionError(repr(type(actual)))
        assert_equal(len(actual),len(desired),err_msg,verbose)
        for k,i in desired.items():
            if k not in actual :
                raise AssertionError(repr(k))
            assert_equal(actual[k], desired[k], 'key=%r\n%s' % (k,err_msg), verbose)
        return
    if isinstance(desired, (list,tuple)) and isinstance(actual, (list,tuple)):
        assert_equal(len(actual),len(desired),err_msg,verbose)
        for k in range(len(desired)):
            assert_equal(actual[k], desired[k], 'item=%r\n%s' % (k,err_msg), verbose)
        return
    from numpy.core import ndarray, isscalar, signbit
    from numpy.lib import iscomplexobj, real, imag
    if isinstance(actual, ndarray) or isinstance(desired, ndarray):
        return assert_array_equal(actual, desired, err_msg, verbose)
    msg = build_err_msg([actual, desired], err_msg, verbose=verbose)

    # Handle complex numbers: separate into real/imag to handle
    # nan/inf/negative zero correctly
    # XXX: catch ValueError for subclasses of ndarray where iscomplex fail
    try:
        usecomplex = iscomplexobj(actual) or iscomplexobj(desired)
    except ValueError:
        usecomplex = False

    if usecomplex:
        if iscomplexobj(actual):
            actualr = real(actual)
            actuali = imag(actual)
        else:
            actualr = actual
            actuali = 0
        if iscomplexobj(desired):
            desiredr = real(desired)
            desiredi = imag(desired)
        else:
            desiredr = desired
            desiredi = 0
        try:
            assert_equal(actualr, desiredr)
            assert_equal(actuali, desiredi)
        except AssertionError:
            raise AssertionError(msg)

    # Inf/nan/negative zero handling
    try:
        # isscalar test to check cases such as [np.nan] != np.nan
        if isscalar(desired) != isscalar(actual):
            raise AssertionError(msg)

        # If one of desired/actual is not finite, handle it specially here:
        # check that both are nan if any is a nan, and test for equality
        # otherwise
        if not (gisfinite(desired) and gisfinite(actual)):
            isdesnan = gisnan(desired)
            isactnan = gisnan(actual)
            if isdesnan or isactnan:
                if not (isdesnan and isactnan):
                    raise AssertionError(msg)
            else:
                if not desired == actual:
                    raise AssertionError(msg)
            return
        elif desired == 0 and actual == 0:
            if not signbit(desired) == signbit(actual):
                raise AssertionError(msg)
    # If TypeError or ValueError raised while using isnan and co, just handle
    # as before
    except (TypeError, ValueError, NotImplementedError):
        pass
    if desired != actual :
        raise AssertionError(msg)
 def __rdiv__(self, other):
     if isscalar(other):
         return poly1d(other / self.coeffs)
     else:
         other = poly1d(other)
         return polydiv(other, self)
 def __div__(self, other):
     if isscalar(other):
         return poly1d(self.coeffs / other)
     else:
         other = poly1d(other)
         return polydiv(self, other)
 def __rmul__(self, other):
     if isscalar(other):
         return poly1d(other * self.coeffs)
     else:
         other = poly1d(other)
         return poly1d(polymul(self.coeffs, other.coeffs))
Exemple #8
0
 def __rdiv__(self, other):
     if isscalar(other):
         return poly1d(other/self.coeffs)
     else:
         other = poly1d(other)
         return polydiv(other, self)
Exemple #9
0
 def __div__(self, other):
     if isscalar(other):
         return poly1d(self.coeffs/other)
     else:
         other = poly1d(other)
         return polydiv(self, other)
Exemple #10
0
 def __rmul__(self, other):
     if isscalar(other):
         return poly1d(other * self.coeffs)
     else:
         other = poly1d(other)
         return poly1d(polymul(self.coeffs, other.coeffs))
Exemple #11
0
def assert_equal(actual,desired,err_msg='',verbose=True):
    """
    Raise an assertion if two objects are not equal.

    Given two objects (lists, tuples, dictionaries or numpy arrays), check
    that all elements of these objects are equal. An exception is raised at
    the first conflicting values.

    Parameters
    ----------
    actual : list, tuple, dict or ndarray
      The object to check.
    desired : list, tuple, dict or ndarray
      The expected object.
    err_msg : string
      The error message to be printed in case of failure.
    verbose : bool
      If True, the conflicting values are appended to the error message.

    Raises
    ------
    AssertionError
      If actual and desired are not equal.

    Examples
    --------
    >>> np.testing.assert_equal([4,5], [4,6])
    ...
    <type 'exceptions.AssertionError'>:
    Items are not equal:
    item=1
     ACTUAL: 5
     DESIRED: 6

    """
    if isinstance(desired, dict):
        if not isinstance(actual, dict) :
            raise AssertionError(repr(type(actual)))
        assert_equal(len(actual),len(desired),err_msg,verbose)
        for k,i in desired.items():
            if k not in actual :
                raise AssertionError(repr(k))
            assert_equal(actual[k], desired[k], 'key=%r\n%s' % (k,err_msg), verbose)
        return
    if isinstance(desired, (list,tuple)) and isinstance(actual, (list,tuple)):
        assert_equal(len(actual),len(desired),err_msg,verbose)
        for k in range(len(desired)):
            assert_equal(actual[k], desired[k], 'item=%r\n%s' % (k,err_msg), verbose)
        return
    from numpy.core import ndarray, isscalar, signbit
    from numpy.lib import iscomplexobj, real, imag
    if isinstance(actual, ndarray) or isinstance(desired, ndarray):
        return assert_array_equal(actual, desired, err_msg, verbose)
    msg = build_err_msg([actual, desired], err_msg, verbose=verbose)

    # Handle complex numbers: separate into real/imag to handle
    # nan/inf/negative zero correctly
    # XXX: catch ValueError for subclasses of ndarray where iscomplex fail
    try:
        usecomplex = iscomplexobj(actual) or iscomplexobj(desired)
    except ValueError:
        usecomplex = False

    if usecomplex:
        if iscomplexobj(actual):
            actualr = real(actual)
            actuali = imag(actual)
        else:
            actualr = actual
            actuali = 0
        if iscomplexobj(desired):
            desiredr = real(desired)
            desiredi = imag(desired)
        else:
            desiredr = desired
            desiredi = 0
        try:
            assert_equal(actualr, desiredr)
            assert_equal(actuali, desiredi)
        except AssertionError:
            raise AssertionError("Items are not equal:\n" \
                    "ACTUAL: %s\n" \
                    "DESIRED: %s\n" % (str(actual), str(desired)))

    # Inf/nan/negative zero handling
    try:
        # isscalar test to check cases such as [np.nan] != np.nan
        if isscalar(desired) != isscalar(actual):
            raise AssertionError(msg)

        # If one of desired/actual is not finite, handle it specially here:
        # check that both are nan if any is a nan, and test for equality
        # otherwise
        if not (gisfinite(desired) and gisfinite(actual)):
            isdesnan = gisnan(desired)
            isactnan = gisnan(actual)
            if isdesnan or isactnan:
                if not (isdesnan and isactnan):
                    raise AssertionError(msg)
            else:
                if not desired == actual:
                    raise AssertionError(msg)
            return
        elif desired == 0 and actual == 0:
            if not signbit(desired) == signbit(actual):
                raise AssertionError(msg)
    # If TypeError or ValueError raised while using isnan and co, just handle
    # as before
    except TypeError:
        pass
    except ValueError:
        pass
    if desired != actual :
        raise AssertionError(msg)
Exemple #12
0
def assert_almost_equal(actual,
                        desired,
                        rtol=1e-7,
                        atol=0,
                        ignored_values=None,
                        err_msg='',
                        verbose=True):
    """
    Function imported from numpy.testing: assert_equal. Version 16.2.
    Two key modifications compared to the original implementation:
    1) allow comparison of numbers with a tolerance on the difference (other functions
        in numpy that allow a tolerance as an argument do not support comparison
        between dictionaries).
    2) allow to skip the explicit comparison of some attributes in dictionaries.

    Raises an AssertionError if two objects are not equal within the required tolerances.
    Given two objects (scalars, lists, tuples, dictionaries or numpy arrays),
    check that all elements of these objects are almost equal. An exception is raised
    at the first conflicting values.
    Comparison for numerical values is performed with assert_allclose

    Args:
        actual: the object to check.
        desired : the expected object.
        rtol (float): relative tolerance.
        atol (float): absolute tolerance.
        ignored_values (list): if a comparison between two dictionaries, keywords contained
            in this list will not be compared (the key should still exist in both the
            dictionaries though).
        err_msg (str): the error message to be printed in case of failure.
        verbose (bool): if True, the conflicting values are appended to the error message.

    Raises:
        AssertionError: if actual and desired are not equal.
    """
    __tracebackhide__ = True  # Hide traceback for py.test
    if isinstance(desired, dict):
        if not isinstance(actual, dict):
            raise AssertionError(repr(type(actual)))
        assert_almost_equal(len(actual), len(desired), rtol, atol,
                            ignored_values, err_msg, verbose)

        if ignored_values is None:
            ignored_values = []

        for k, i in desired.items():
            if k not in actual:
                raise AssertionError(repr(k))

            # don't check nested values if the key belong to the list to skip
            if k in ignored_values:
                continue

            assert_almost_equal(actual[k], desired[k], rtol, atol,
                                ignored_values, 'key=%r\n%s' % (k, err_msg),
                                verbose)
        return
    if isinstance(desired,
                  (list, tuple)) and isinstance(actual, (list, tuple)):
        assert_almost_equal(len(actual), len(desired), rtol, atol,
                            ignored_values, err_msg, verbose)
        for k in range(len(desired)):
            assert_almost_equal(actual[k], desired[k], rtol, atol,
                                ignored_values, 'item=%r\n%s' % (k, err_msg),
                                verbose)
        return
    from numpy.core import ndarray, isscalar, signbit
    from numpy.lib import iscomplexobj, real, imag
    if isinstance(actual, ndarray) or isinstance(desired, ndarray):
        return np.testing.assert_allclose(actual,
                                          desired,
                                          rtol=rtol,
                                          atol=atol,
                                          err_msg=err_msg,
                                          verbose=verbose)
    msg = np.testing.build_err_msg([actual, desired], err_msg, verbose=verbose)

    # Handle complex numbers: separate into real/imag to handle
    # nan/inf/negative zero correctly
    # XXX: catch ValueError for subclasses of ndarray where iscomplex fail
    try:
        usecomplex = iscomplexobj(actual) or iscomplexobj(desired)
    except (ValueError, TypeError):
        usecomplex = False

    if usecomplex:
        if iscomplexobj(actual):
            actualr = real(actual)
            actuali = imag(actual)
        else:
            actualr = actual
            actuali = 0
        if iscomplexobj(desired):
            desiredr = real(desired)
            desiredi = imag(desired)
        else:
            desiredr = desired
            desiredi = 0
        try:
            np.testing.assert_allclose(actualr, desiredr, rtol=rtol, atol=atol)
            np.testing.assert_allclose(actuali, desiredi, rtol=rtol, atol=atol)
        except AssertionError:
            raise AssertionError(msg)

    # isscalar test to check cases such as [np.nan] != np.nan
    if isscalar(desired) != isscalar(actual):
        raise AssertionError(msg)

    a_is_number = isinstance(actual, numbers.Number)
    d_is_number = isinstance(desired, numbers.Number)

    if a_is_number != d_is_number:
        raise AssertionError(msg)

    if a_is_number:
        if np.isclose(actual, desired, rtol=rtol, atol=atol):
            return
        else:
            raise AssertionError(msg)

    # Inf/nan/negative zero handling
    try:
        isdesnan = gisnan(desired)
        isactnan = gisnan(actual)
        if isdesnan and isactnan:
            return  # both nan, so equal

        # allow 0.0 and -0.0 to match
        if desired == 0 and actual == 0:
            return
            # if not signbit(desired) == signbit(actual):
            #     raise AssertionError(msg)

    except (TypeError, ValueError, NotImplementedError):
        pass

    try:
        isdesnat = np.core.isnat(desired)
        isactnat = np.core.isnat(actual)
        dtypes_match = np.array(desired).dtype.type == np.array(
            actual).dtype.type
        if isdesnat and isactnat:
            # If both are NaT (and have the same dtype -- datetime or
            # timedelta) they are considered equal.
            if dtypes_match:
                return
            else:
                raise AssertionError(msg)

    except (TypeError, ValueError, NotImplementedError):
        pass

    try:
        # First check if they are equal with ==. If not Use assert allclose instead of __eq__
        if not (desired == actual):
            raise AssertionError(msg)
            # try:
            #     np.testing.assert_allclose(actual, desired, rtol=rtol, atol=atol)
            # except (AssertionError, TypeError):
            #     raise AssertionError(msg)

    except (DeprecationWarning, FutureWarning) as e:
        # this handles the case when the two types are not even comparable
        if 'elementwise == comparison' in e.args[0]:
            raise AssertionError(msg)
        else:
            raise