python类iscomplexobj()的实例源码

signal_models.py 文件源码 项目:parametrix 作者: vincentchoqueuse 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def plot(self,**kwargs):
        """ Plot a realisation of the signal waveform """
        y=self.rvs()

        if np.iscomplexobj(y) == True:
            plt.plot(np.arange(self.N)/self.Fe,np.real(y))
            plt.ylabel("Signal (Real part)")
        else:
            plt.plot(np.arange(self.N)/self.Fe,y)
            plt.ylabel("Signal")

        plt.xlabel("Time")
inverse.py 文件源码 项目:decoding_challenge_cortana_2016_3rd 作者: kingjr 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
def combine_xyz(vec, square=False):
    """Compute the three Cartesian components of a vector or matrix together

    Parameters
    ----------
    vec : 2d array of shape [3 n x p]
        Input [ x1 y1 z1 ... x_n y_n z_n ] where x1 ... z_n
        can be vectors

    Returns
    -------
    comb : array
        Output vector [sqrt(x1^2+y1^2+z1^2), ..., sqrt(x_n^2+y_n^2+z_n^2)]
    """
    if vec.ndim != 2:
        raise ValueError('Input must be 2D')
    if (vec.shape[0] % 3) != 0:
        raise ValueError('Input must have 3N rows')

    n, p = vec.shape
    if np.iscomplexobj(vec):
        vec = np.abs(vec)
    comb = vec[0::3] ** 2
    comb += vec[1::3] ** 2
    comb += vec[2::3] ** 2
    if not square:
        comb = np.sqrt(comb)
    return comb
core.py 文件源码 项目:Alfred 作者: jkachhadia 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def var(self, axis=None, dtype=None, out=None, ddof=0):
        ""
        # Easy case: nomask, business as usual
        if self._mask is nomask:
            return self._data.var(axis=axis, dtype=dtype, out=out, ddof=ddof)
        # Some data are masked, yay!
        cnt = self.count(axis=axis) - ddof
        danom = self.anom(axis=axis, dtype=dtype)
        if iscomplexobj(self):
            danom = umath.absolute(danom) ** 2
        else:
            danom *= danom
        dvar = divide(danom.sum(axis), cnt).view(type(self))
        # Apply the mask if it's not a scalar
        if dvar.ndim:
            dvar._mask = mask_or(self._mask.all(axis), (cnt <= 0))
            dvar._update_from(self)
        elif getattr(dvar, '_mask', False):
            # Make sure that masked is returned when the scalar is masked.
            dvar = masked
            if out is not None:
                if isinstance(out, MaskedArray):
                    out.flat = 0
                    out.__setmask__(True)
                elif out.dtype.kind in 'biu':
                    errmsg = "Masked data information would be lost in one or "\
                             "more location."
                    raise MaskError(errmsg)
                else:
                    out.flat = np.nan
                return out
        # In case with have an explicit output
        if out is not None:
            # Set the data
            out.flat = dvar
            # Set the mask if needed
            if isinstance(out, MaskedArray):
                out.__setmask__(dvar.mask)
            return out
        return dvar
raputil.py 文件源码 项目:onsager_deep_learning 作者: mborgerding 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def __init__(self, Nr=64, C=7, Nu=64, Ns=64, beta=.01,L=5,ang=10,rice_k_dB=10,ple=4,SNR_dB=10.0,ambig=False,scramble=False,S=None,cpx=False,mmv2d=False,normS=None):
        """
        Nr : number of Rx antennas
        C : number of cells (>1 indicates there are "far" users)
        Nu : max # users per cell
        Ns : spreading code length
        beta :  user load (i.e.,expected active / total user ratio)
        L : paths per cluster
        ang : angular spread within cluster (in degrees)
        rice_k_dB : rice k parameter in dB
        ple : path-loss exponent: gain = 1/(1+d^ple) for distance d
        S : set of spreading codes, shape=(Ns,C*Nu) """
        if S is None:
            S = random_qpsk(Ns,C*Nu)
        self.Nr = Nr
        self.C = C
        self.Nu = Nu
        self.Ns = Ns
        self.beta = beta
        self.L = L
        self.ang = ang
        self.rice_k_dB = rice_k_dB
        self.ple = ple
        self.SNR_dB = SNR_dB
        self.ambig = ambig
        self.scramble = scramble
        self.cpx = cpx
        self.mmv2d = mmv2d

        if self.cpx == np.iscomplexobj(S):
            self.S = S
        else:
            if not self.cpx:
                top = np.concatenate( (S.real, -S.imag),axis=1 )
                btm = np.concatenate( (S.imag, S.real),axis=1 )
                self.S = np.concatenate( (top,btm),axis=0 )
            else:
                assert False,'WHY!?'

        if self.cpx:
            assert self.S.shape == (Ns,C*Nu)
        else:
            assert self.S.shape == (2*Ns,2*C*Nu)

        if normS is not None:
            dnorm = np.asarray(normS) / np.sqrt( np.square(self.S).sum(axis=0) )
            self.S = self.S * dnorm
        self.timegen = 0 # time spent waiting for generation of YX (does NOT count subprocess cpus time if nsubprocs>0
utils.py 文件源码 项目:radar 作者: amoose136 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
def assert_array_almost_equal_nulp(x, y, nulp=1):
    """
    Compare two arrays relatively to their spacing.

    This is a relatively robust method to compare two arrays whose amplitude
    is variable.

    Parameters
    ----------
    x, y : array_like
        Input arrays.
    nulp : int, optional
        The maximum number of unit in the last place for tolerance (see Notes).
        Default is 1.

    Returns
    -------
    None

    Raises
    ------
    AssertionError
        If the spacing between `x` and `y` for one or more elements is larger
        than `nulp`.

    See Also
    --------
    assert_array_max_ulp : Check that all items of arrays differ in at most
        N Units in the Last Place.
    spacing : Return the distance between x and the nearest adjacent number.

    Notes
    -----
    An assertion is raised if the following condition is not met::

        abs(x - y) <= nulps * spacing(maximum(abs(x), abs(y)))

    Examples
    --------
    >>> x = np.array([1., 1e-10, 1e-20])
    >>> eps = np.finfo(x.dtype).eps
    >>> np.testing.assert_array_almost_equal_nulp(x, x*eps/2 + x)

    >>> np.testing.assert_array_almost_equal_nulp(x, x*eps + x)
    Traceback (most recent call last):
      ...
    AssertionError: X and Y are not equal to 1 ULP (max is 2)

    """
    __tracebackhide__ = True  # Hide traceback for py.test
    import numpy as np
    ax = np.abs(x)
    ay = np.abs(y)
    ref = nulp * np.spacing(np.where(ax > ay, ax, ay))
    if not np.all(np.abs(x-y) <= ref):
        if np.iscomplexobj(x) or np.iscomplexobj(y):
            msg = "X and Y are not equal to %d ULP" % nulp
        else:
            max_nulp = np.max(nulp_diff(x, y))
            msg = "X and Y are not equal to %d ULP (max is %g)" % (nulp, max_nulp)
        raise AssertionError(msg)
utils.py 文件源码 项目:radar 作者: amoose136 项目源码 文件源码 阅读 36 收藏 0 点赞 0 评论 0
def nulp_diff(x, y, dtype=None):
    """For each item in x and y, return the number of representable floating
    points between them.

    Parameters
    ----------
    x : array_like
        first input array
    y : array_like
        second input array
    dtype : dtype, optional
        Data-type to convert `x` and `y` to if given. Default is None.

    Returns
    -------
    nulp : array_like
        number of representable floating point numbers between each item in x
        and y.

    Examples
    --------
    # By definition, epsilon is the smallest number such as 1 + eps != 1, so
    # there should be exactly one ULP between 1 and 1 + eps
    >>> nulp_diff(1, 1 + np.finfo(x.dtype).eps)
    1.0
    """
    import numpy as np
    if dtype:
        x = np.array(x, dtype=dtype)
        y = np.array(y, dtype=dtype)
    else:
        x = np.array(x)
        y = np.array(y)

    t = np.common_type(x, y)
    if np.iscomplexobj(x) or np.iscomplexobj(y):
        raise NotImplementedError("_nulp not implemented for complex array")

    x = np.array(x, dtype=t)
    y = np.array(y, dtype=t)

    if not x.shape == y.shape:
        raise ValueError("x and y do not have the same shape: %s - %s" %
                         (x.shape, y.shape))

    def _diff(rx, ry, vdt):
        diff = np.array(rx-ry, dtype=vdt)
        return np.abs(diff)

    rx = integer_repr(x)
    ry = integer_repr(y)
    return _diff(rx, ry, t)
transform.py 文件源码 项目:pisap 作者: neurospin 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
def synthesis(self):
        """ Reconstruct a real or complex signal from the wavelet coefficients
        using ISAP.

        Returns
        -------
        data: pisap.Image
            the reconstructed data/signal.
        """
        # Checks
        if self._analysis_data is None:
            raise ValueError("Please specify first the decomposition "
                             "coefficients array.")
        if self.use_wrapping and self._analysis_header is None:
            raise ValueError("Please specify first the decomposition "
                             "coefficients header.")

        # Message
        if self.verbose > 1:
            print("[info] Synthesis header:")
            pprint(self._analysis_header)

        # Reorganize the coefficents with ISAP convention
        # TODO: do not backup the list of bands
        if self.use_wrapping:
            analysis_buffer = numpy.zeros(
                self._analysis_buffer_shape, dtype=self.analysis_data[0].dtype)
            for scale, nb_bands in enumerate(self.nb_band_per_scale):
                for band in range(nb_bands):
                    self._set_linear_band(scale, band, analysis_buffer,
                                          self.band_at(scale, band))
            _saved_analysis_data = self._analysis_data
            self._analysis_data = analysis_buffer
            self._analysis_data = [self.unflatten_fct(self)]

        # Synthesis
        if numpy.iscomplexobj(self._analysis_data[0]):
            data_real = self._synthesis(
                [arr.real for arr in self._analysis_data],
                self._analysis_header)
            data_imag = self._synthesis(
                [arr.imag for arr in self._analysis_data],
                self._analysis_header)
            data = data_real + 1.j * data_imag
        else:
            data = self._synthesis(
                self._analysis_data, self._analysis_header)

        # TODO: remove this code asap
        if self.use_wrapping:
            self._analysis_data = _saved_analysis_data

        return pisap.Image(data=data, metadata=self._image_metadata)
utils.py 文件源码 项目:krpcScripts 作者: jwvanderbeck 项目源码 文件源码 阅读 35 收藏 0 点赞 0 评论 0
def assert_array_almost_equal_nulp(x, y, nulp=1):
    """
    Compare two arrays relatively to their spacing.

    This is a relatively robust method to compare two arrays whose amplitude
    is variable.

    Parameters
    ----------
    x, y : array_like
        Input arrays.
    nulp : int, optional
        The maximum number of unit in the last place for tolerance (see Notes).
        Default is 1.

    Returns
    -------
    None

    Raises
    ------
    AssertionError
        If the spacing between `x` and `y` for one or more elements is larger
        than `nulp`.

    See Also
    --------
    assert_array_max_ulp : Check that all items of arrays differ in at most
        N Units in the Last Place.
    spacing : Return the distance between x and the nearest adjacent number.

    Notes
    -----
    An assertion is raised if the following condition is not met::

        abs(x - y) <= nulps * spacing(maximum(abs(x), abs(y)))

    Examples
    --------
    >>> x = np.array([1., 1e-10, 1e-20])
    >>> eps = np.finfo(x.dtype).eps
    >>> np.testing.assert_array_almost_equal_nulp(x, x*eps/2 + x)

    >>> np.testing.assert_array_almost_equal_nulp(x, x*eps + x)
    Traceback (most recent call last):
      ...
    AssertionError: X and Y are not equal to 1 ULP (max is 2)

    """
    __tracebackhide__ = True  # Hide traceback for py.test
    import numpy as np
    ax = np.abs(x)
    ay = np.abs(y)
    ref = nulp * np.spacing(np.where(ax > ay, ax, ay))
    if not np.all(np.abs(x-y) <= ref):
        if np.iscomplexobj(x) or np.iscomplexobj(y):
            msg = "X and Y are not equal to %d ULP" % nulp
        else:
            max_nulp = np.max(nulp_diff(x, y))
            msg = "X and Y are not equal to %d ULP (max is %g)" % (nulp, max_nulp)
        raise AssertionError(msg)
utils.py 文件源码 项目:krpcScripts 作者: jwvanderbeck 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def nulp_diff(x, y, dtype=None):
    """For each item in x and y, return the number of representable floating
    points between them.

    Parameters
    ----------
    x : array_like
        first input array
    y : array_like
        second input array
    dtype : dtype, optional
        Data-type to convert `x` and `y` to if given. Default is None.

    Returns
    -------
    nulp : array_like
        number of representable floating point numbers between each item in x
        and y.

    Examples
    --------
    # By definition, epsilon is the smallest number such as 1 + eps != 1, so
    # there should be exactly one ULP between 1 and 1 + eps
    >>> nulp_diff(1, 1 + np.finfo(x.dtype).eps)
    1.0
    """
    import numpy as np
    if dtype:
        x = np.array(x, dtype=dtype)
        y = np.array(y, dtype=dtype)
    else:
        x = np.array(x)
        y = np.array(y)

    t = np.common_type(x, y)
    if np.iscomplexobj(x) or np.iscomplexobj(y):
        raise NotImplementedError("_nulp not implemented for complex array")

    x = np.array(x, dtype=t)
    y = np.array(y, dtype=t)

    if not x.shape == y.shape:
        raise ValueError("x and y do not have the same shape: %s - %s" %
                         (x.shape, y.shape))

    def _diff(rx, ry, vdt):
        diff = np.array(rx-ry, dtype=vdt)
        return np.abs(diff)

    rx = integer_repr(x)
    ry = integer_repr(y)
    return _diff(rx, ry, t)
stt_utils.py 文件源码 项目:deepspeech.mxnet 作者: samsungsds-rnd 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
def spectrogram(samples, fft_length=256, sample_rate=2, hop_length=128):
    """
    Compute the spectrogram for a real signal.
    The parameters follow the naming convention of
    matplotlib.mlab.specgram
    Args:
        samples (1D array): input audio signal
        fft_length (int): number of elements in fft window
        sample_rate (scalar): sample rate
        hop_length (int): hop length (relative offset between neighboring
            fft windows).
    Returns:
        x (2D array): spectrogram [frequency x time]
        freq (1D array): frequency of each row in x
    Note:
        This is a truncating computation e.g. if fft_length=10,
        hop_length=5 and the signal has 23 elements, then the
        last 3 elements will be truncated.
    """
    assert not np.iscomplexobj(samples), "Must not pass in complex numbers"

    window = np.hanning(fft_length)[:, None]
    window_norm = np.sum(window ** 2)

    # The scaling below follows the convention of
    # matplotlib.mlab.specgram which is the same as
    # matlabs specgram.
    scale = window_norm * sample_rate

    trunc = (len(samples) - fft_length) % hop_length
    x = samples[:len(samples) - trunc]

    # "stride trick" reshape to include overlap
    nshape = (fft_length, (len(x) - fft_length) // hop_length + 1)
    nstrides = (x.strides[0], x.strides[0] * hop_length)
    x = as_strided(x, shape=nshape, strides=nstrides)

    # window stride sanity check
    assert np.all(x[:, 1] == samples[hop_length:(hop_length + fft_length)])

    # broadcast window, compute fft over columns and square mod
    # This function computes the one-dimensional n-point discrete Fourier Transform (DFT) of a real-valued array by means of an efficient algorithm called the Fast Fourier Transform (FFT).
    x = np.fft.rfft(x * window, axis=0)
    x = np.absolute(x) ** 2

    # scale, 2.0 for everything except dc and fft_length/2
    x[1:-1, :] *= (2.0 / scale)
    x[(0, -1), :] /= scale

    freqs = float(sample_rate) / fft_length * np.arange(x.shape[0])

    return x, freqs
utils.py 文件源码 项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda 作者: SignalMedia 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def assert_array_almost_equal_nulp(x, y, nulp=1):
    """
    Compare two arrays relatively to their spacing.

    This is a relatively robust method to compare two arrays whose amplitude
    is variable.

    Parameters
    ----------
    x, y : array_like
        Input arrays.
    nulp : int, optional
        The maximum number of unit in the last place for tolerance (see Notes).
        Default is 1.

    Returns
    -------
    None

    Raises
    ------
    AssertionError
        If the spacing between `x` and `y` for one or more elements is larger
        than `nulp`.

    See Also
    --------
    assert_array_max_ulp : Check that all items of arrays differ in at most
        N Units in the Last Place.
    spacing : Return the distance between x and the nearest adjacent number.

    Notes
    -----
    An assertion is raised if the following condition is not met::

        abs(x - y) <= nulps * spacing(maximum(abs(x), abs(y)))

    Examples
    --------
    >>> x = np.array([1., 1e-10, 1e-20])
    >>> eps = np.finfo(x.dtype).eps
    >>> np.testing.assert_array_almost_equal_nulp(x, x*eps/2 + x)

    >>> np.testing.assert_array_almost_equal_nulp(x, x*eps + x)
    Traceback (most recent call last):
      ...
    AssertionError: X and Y are not equal to 1 ULP (max is 2)

    """
    __tracebackhide__ = True  # Hide traceback for py.test
    import numpy as np
    ax = np.abs(x)
    ay = np.abs(y)
    ref = nulp * np.spacing(np.where(ax > ay, ax, ay))
    if not np.all(np.abs(x-y) <= ref):
        if np.iscomplexobj(x) or np.iscomplexobj(y):
            msg = "X and Y are not equal to %d ULP" % nulp
        else:
            max_nulp = np.max(nulp_diff(x, y))
            msg = "X and Y are not equal to %d ULP (max is %g)" % (nulp, max_nulp)
        raise AssertionError(msg)
utils.py 文件源码 项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda 作者: SignalMedia 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def nulp_diff(x, y, dtype=None):
    """For each item in x and y, return the number of representable floating
    points between them.

    Parameters
    ----------
    x : array_like
        first input array
    y : array_like
        second input array
    dtype : dtype, optional
        Data-type to convert `x` and `y` to if given. Default is None.

    Returns
    -------
    nulp : array_like
        number of representable floating point numbers between each item in x
        and y.

    Examples
    --------
    # By definition, epsilon is the smallest number such as 1 + eps != 1, so
    # there should be exactly one ULP between 1 and 1 + eps
    >>> nulp_diff(1, 1 + np.finfo(x.dtype).eps)
    1.0
    """
    import numpy as np
    if dtype:
        x = np.array(x, dtype=dtype)
        y = np.array(y, dtype=dtype)
    else:
        x = np.array(x)
        y = np.array(y)

    t = np.common_type(x, y)
    if np.iscomplexobj(x) or np.iscomplexobj(y):
        raise NotImplementedError("_nulp not implemented for complex array")

    x = np.array(x, dtype=t)
    y = np.array(y, dtype=t)

    if not x.shape == y.shape:
        raise ValueError("x and y do not have the same shape: %s - %s" %
                         (x.shape, y.shape))

    def _diff(rx, ry, vdt):
        diff = np.array(rx-ry, dtype=vdt)
        return np.abs(diff)

    rx = integer_repr(x)
    ry = integer_repr(y)
    return _diff(rx, ry, t)
utils.py 文件源码 项目:aws-lambda-numpy 作者: vitolimandibhrata 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def assert_array_almost_equal_nulp(x, y, nulp=1):
    """
    Compare two arrays relatively to their spacing.

    This is a relatively robust method to compare two arrays whose amplitude
    is variable.

    Parameters
    ----------
    x, y : array_like
        Input arrays.
    nulp : int, optional
        The maximum number of unit in the last place for tolerance (see Notes).
        Default is 1.

    Returns
    -------
    None

    Raises
    ------
    AssertionError
        If the spacing between `x` and `y` for one or more elements is larger
        than `nulp`.

    See Also
    --------
    assert_array_max_ulp : Check that all items of arrays differ in at most
        N Units in the Last Place.
    spacing : Return the distance between x and the nearest adjacent number.

    Notes
    -----
    An assertion is raised if the following condition is not met::

        abs(x - y) <= nulps * spacing(maximum(abs(x), abs(y)))

    Examples
    --------
    >>> x = np.array([1., 1e-10, 1e-20])
    >>> eps = np.finfo(x.dtype).eps
    >>> np.testing.assert_array_almost_equal_nulp(x, x*eps/2 + x)

    >>> np.testing.assert_array_almost_equal_nulp(x, x*eps + x)
    Traceback (most recent call last):
      ...
    AssertionError: X and Y are not equal to 1 ULP (max is 2)

    """
    __tracebackhide__ = True  # Hide traceback for py.test
    import numpy as np
    ax = np.abs(x)
    ay = np.abs(y)
    ref = nulp * np.spacing(np.where(ax > ay, ax, ay))
    if not np.all(np.abs(x-y) <= ref):
        if np.iscomplexobj(x) or np.iscomplexobj(y):
            msg = "X and Y are not equal to %d ULP" % nulp
        else:
            max_nulp = np.max(nulp_diff(x, y))
            msg = "X and Y are not equal to %d ULP (max is %g)" % (nulp, max_nulp)
        raise AssertionError(msg)
utils.py 文件源码 项目:aws-lambda-numpy 作者: vitolimandibhrata 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def nulp_diff(x, y, dtype=None):
    """For each item in x and y, return the number of representable floating
    points between them.

    Parameters
    ----------
    x : array_like
        first input array
    y : array_like
        second input array
    dtype : dtype, optional
        Data-type to convert `x` and `y` to if given. Default is None.

    Returns
    -------
    nulp : array_like
        number of representable floating point numbers between each item in x
        and y.

    Examples
    --------
    # By definition, epsilon is the smallest number such as 1 + eps != 1, so
    # there should be exactly one ULP between 1 and 1 + eps
    >>> nulp_diff(1, 1 + np.finfo(x.dtype).eps)
    1.0
    """
    import numpy as np
    if dtype:
        x = np.array(x, dtype=dtype)
        y = np.array(y, dtype=dtype)
    else:
        x = np.array(x)
        y = np.array(y)

    t = np.common_type(x, y)
    if np.iscomplexobj(x) or np.iscomplexobj(y):
        raise NotImplementedError("_nulp not implemented for complex array")

    x = np.array(x, dtype=t)
    y = np.array(y, dtype=t)

    if not x.shape == y.shape:
        raise ValueError("x and y do not have the same shape: %s - %s" %
                         (x.shape, y.shape))

    def _diff(rx, ry, vdt):
        diff = np.array(rx-ry, dtype=vdt)
        return np.abs(diff)

    rx = integer_repr(x)
    ry = integer_repr(y)
    return _diff(rx, ry, t)
utils.py 文件源码 项目:lambda-numba 作者: rlhotovy 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def assert_array_almost_equal_nulp(x, y, nulp=1):
    """
    Compare two arrays relatively to their spacing.

    This is a relatively robust method to compare two arrays whose amplitude
    is variable.

    Parameters
    ----------
    x, y : array_like
        Input arrays.
    nulp : int, optional
        The maximum number of unit in the last place for tolerance (see Notes).
        Default is 1.

    Returns
    -------
    None

    Raises
    ------
    AssertionError
        If the spacing between `x` and `y` for one or more elements is larger
        than `nulp`.

    See Also
    --------
    assert_array_max_ulp : Check that all items of arrays differ in at most
        N Units in the Last Place.
    spacing : Return the distance between x and the nearest adjacent number.

    Notes
    -----
    An assertion is raised if the following condition is not met::

        abs(x - y) <= nulps * spacing(maximum(abs(x), abs(y)))

    Examples
    --------
    >>> x = np.array([1., 1e-10, 1e-20])
    >>> eps = np.finfo(x.dtype).eps
    >>> np.testing.assert_array_almost_equal_nulp(x, x*eps/2 + x)

    >>> np.testing.assert_array_almost_equal_nulp(x, x*eps + x)
    Traceback (most recent call last):
      ...
    AssertionError: X and Y are not equal to 1 ULP (max is 2)

    """
    __tracebackhide__ = True  # Hide traceback for py.test
    import numpy as np
    ax = np.abs(x)
    ay = np.abs(y)
    ref = nulp * np.spacing(np.where(ax > ay, ax, ay))
    if not np.all(np.abs(x-y) <= ref):
        if np.iscomplexobj(x) or np.iscomplexobj(y):
            msg = "X and Y are not equal to %d ULP" % nulp
        else:
            max_nulp = np.max(nulp_diff(x, y))
            msg = "X and Y are not equal to %d ULP (max is %g)" % (nulp, max_nulp)
        raise AssertionError(msg)
utils.py 文件源码 项目:lambda-numba 作者: rlhotovy 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def nulp_diff(x, y, dtype=None):
    """For each item in x and y, return the number of representable floating
    points between them.

    Parameters
    ----------
    x : array_like
        first input array
    y : array_like
        second input array
    dtype : dtype, optional
        Data-type to convert `x` and `y` to if given. Default is None.

    Returns
    -------
    nulp : array_like
        number of representable floating point numbers between each item in x
        and y.

    Examples
    --------
    # By definition, epsilon is the smallest number such as 1 + eps != 1, so
    # there should be exactly one ULP between 1 and 1 + eps
    >>> nulp_diff(1, 1 + np.finfo(x.dtype).eps)
    1.0
    """
    import numpy as np
    if dtype:
        x = np.array(x, dtype=dtype)
        y = np.array(y, dtype=dtype)
    else:
        x = np.array(x)
        y = np.array(y)

    t = np.common_type(x, y)
    if np.iscomplexobj(x) or np.iscomplexobj(y):
        raise NotImplementedError("_nulp not implemented for complex array")

    x = np.array(x, dtype=t)
    y = np.array(y, dtype=t)

    if not x.shape == y.shape:
        raise ValueError("x and y do not have the same shape: %s - %s" %
                         (x.shape, y.shape))

    def _diff(rx, ry, vdt):
        diff = np.array(rx-ry, dtype=vdt)
        return np.abs(diff)

    rx = integer_repr(x)
    ry = integer_repr(y)
    return _diff(rx, ry, t)
core.py 文件源码 项目:lambda-numba 作者: rlhotovy 项目源码 文件源码 阅读 40 收藏 0 点赞 0 评论 0
def var(self, axis=None, dtype=None, out=None, ddof=0,
            keepdims=np._NoValue):
        """
        Returns the variance of the array elements along given axis.

        Masked entries are ignored, and result elements which are not
        finite will be masked.

        Refer to `numpy.var` for full documentation.

        See Also
        --------
        ndarray.var : corresponding function for ndarrays
        numpy.var : Equivalent function
        """
        kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims}

        # Easy case: nomask, business as usual
        if self._mask is nomask:
            return self._data.var(axis=axis, dtype=dtype, out=out,
                                  ddof=ddof, **kwargs)
        # Some data are masked, yay!
        cnt = self.count(axis=axis, **kwargs) - ddof
        danom = self - self.mean(axis, dtype, keepdims=True)
        if iscomplexobj(self):
            danom = umath.absolute(danom) ** 2
        else:
            danom *= danom
        dvar = divide(danom.sum(axis, **kwargs), cnt).view(type(self))
        # Apply the mask if it's not a scalar
        if dvar.ndim:
            dvar._mask = mask_or(self._mask.all(axis, **kwargs), (cnt <= 0))
            dvar._update_from(self)
        elif getattr(dvar, '_mask', False):
            # Make sure that masked is returned when the scalar is masked.
            dvar = masked
            if out is not None:
                if isinstance(out, MaskedArray):
                    out.flat = 0
                    out.__setmask__(True)
                elif out.dtype.kind in 'biu':
                    errmsg = "Masked data information would be lost in one or "\
                             "more location."
                    raise MaskError(errmsg)
                else:
                    out.flat = np.nan
                return out
        # In case with have an explicit output
        if out is not None:
            # Set the data
            out.flat = dvar
            # Set the mask if needed
            if isinstance(out, MaskedArray):
                out.__setmask__(dvar.mask)
            return out
        return dvar
utils.py 文件源码 项目:deliver 作者: orchestor 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def assert_array_almost_equal_nulp(x, y, nulp=1):
    """
    Compare two arrays relatively to their spacing.

    This is a relatively robust method to compare two arrays whose amplitude
    is variable.

    Parameters
    ----------
    x, y : array_like
        Input arrays.
    nulp : int, optional
        The maximum number of unit in the last place for tolerance (see Notes).
        Default is 1.

    Returns
    -------
    None

    Raises
    ------
    AssertionError
        If the spacing between `x` and `y` for one or more elements is larger
        than `nulp`.

    See Also
    --------
    assert_array_max_ulp : Check that all items of arrays differ in at most
        N Units in the Last Place.
    spacing : Return the distance between x and the nearest adjacent number.

    Notes
    -----
    An assertion is raised if the following condition is not met::

        abs(x - y) <= nulps * spacing(maximum(abs(x), abs(y)))

    Examples
    --------
    >>> x = np.array([1., 1e-10, 1e-20])
    >>> eps = np.finfo(x.dtype).eps
    >>> np.testing.assert_array_almost_equal_nulp(x, x*eps/2 + x)

    >>> np.testing.assert_array_almost_equal_nulp(x, x*eps + x)
    Traceback (most recent call last):
      ...
    AssertionError: X and Y are not equal to 1 ULP (max is 2)

    """
    __tracebackhide__ = True  # Hide traceback for py.test
    import numpy as np
    ax = np.abs(x)
    ay = np.abs(y)
    ref = nulp * np.spacing(np.where(ax > ay, ax, ay))
    if not np.all(np.abs(x-y) <= ref):
        if np.iscomplexobj(x) or np.iscomplexobj(y):
            msg = "X and Y are not equal to %d ULP" % nulp
        else:
            max_nulp = np.max(nulp_diff(x, y))
            msg = "X and Y are not equal to %d ULP (max is %g)" % (nulp, max_nulp)
        raise AssertionError(msg)
utils.py 文件源码 项目:deliver 作者: orchestor 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def nulp_diff(x, y, dtype=None):
    """For each item in x and y, return the number of representable floating
    points between them.

    Parameters
    ----------
    x : array_like
        first input array
    y : array_like
        second input array
    dtype : dtype, optional
        Data-type to convert `x` and `y` to if given. Default is None.

    Returns
    -------
    nulp : array_like
        number of representable floating point numbers between each item in x
        and y.

    Examples
    --------
    # By definition, epsilon is the smallest number such as 1 + eps != 1, so
    # there should be exactly one ULP between 1 and 1 + eps
    >>> nulp_diff(1, 1 + np.finfo(x.dtype).eps)
    1.0
    """
    import numpy as np
    if dtype:
        x = np.array(x, dtype=dtype)
        y = np.array(y, dtype=dtype)
    else:
        x = np.array(x)
        y = np.array(y)

    t = np.common_type(x, y)
    if np.iscomplexobj(x) or np.iscomplexobj(y):
        raise NotImplementedError("_nulp not implemented for complex array")

    x = np.array(x, dtype=t)
    y = np.array(y, dtype=t)

    if not x.shape == y.shape:
        raise ValueError("x and y do not have the same shape: %s - %s" %
                         (x.shape, y.shape))

    def _diff(rx, ry, vdt):
        diff = np.array(rx-ry, dtype=vdt)
        return np.abs(diff)

    rx = integer_repr(x)
    ry = integer_repr(y)
    return _diff(rx, ry, t)
utils.py 文件源码 项目:Alfred 作者: jkachhadia 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def assert_array_almost_equal_nulp(x, y, nulp=1):
    """
    Compare two arrays relatively to their spacing.

    This is a relatively robust method to compare two arrays whose amplitude
    is variable.

    Parameters
    ----------
    x, y : array_like
        Input arrays.
    nulp : int, optional
        The maximum number of unit in the last place for tolerance (see Notes).
        Default is 1.

    Returns
    -------
    None

    Raises
    ------
    AssertionError
        If the spacing between `x` and `y` for one or more elements is larger
        than `nulp`.

    See Also
    --------
    assert_array_max_ulp : Check that all items of arrays differ in at most
        N Units in the Last Place.
    spacing : Return the distance between x and the nearest adjacent number.

    Notes
    -----
    An assertion is raised if the following condition is not met::

        abs(x - y) <= nulps * spacing(maximum(abs(x), abs(y)))

    Examples
    --------
    >>> x = np.array([1., 1e-10, 1e-20])
    >>> eps = np.finfo(x.dtype).eps
    >>> np.testing.assert_array_almost_equal_nulp(x, x*eps/2 + x)

    >>> np.testing.assert_array_almost_equal_nulp(x, x*eps + x)
    Traceback (most recent call last):
      ...
    AssertionError: X and Y are not equal to 1 ULP (max is 2)

    """
    __tracebackhide__ = True  # Hide traceback for py.test
    import numpy as np
    ax = np.abs(x)
    ay = np.abs(y)
    ref = nulp * np.spacing(np.where(ax > ay, ax, ay))
    if not np.all(np.abs(x-y) <= ref):
        if np.iscomplexobj(x) or np.iscomplexobj(y):
            msg = "X and Y are not equal to %d ULP" % nulp
        else:
            max_nulp = np.max(nulp_diff(x, y))
            msg = "X and Y are not equal to %d ULP (max is %g)" % (nulp, max_nulp)
        raise AssertionError(msg)


问题


面经


文章

微信
公众号

扫码关注公众号