当前位置: 首页>>代码示例>>Python>>正文


Python numpy.iscomplex方法代码示例

本文整理汇总了Python中numpy.iscomplex方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.iscomplex方法的具体用法?Python numpy.iscomplex怎么用?Python numpy.iscomplex使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在numpy的用法示例。


在下文中一共展示了numpy.iscomplex方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_eigs

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import iscomplex [as 别名]
def test_eigs(par):
    """Eigenvalues and condition number estimate with ARPACK
    """
    # explicit=True
    diag = np.arange(par['nx'], 0, -1) +\
           par['imag'] * np.arange(par['nx'], 0, -1)
    Op = MatrixMult(np.vstack((np.diag(diag),
                               np.zeros((par['ny'] - par['nx'], par['nx'])))))
    eigs = Op.eigs()
    assert_array_almost_equal(diag[:eigs.size], eigs, decimal=3)

    cond = Op.cond()
    assert_array_almost_equal(np.real(cond), par['nx'], decimal=3)

    # explicit=False
    Op = Diagonal(diag, dtype=par['dtype'])
    if par['ny'] > par['nx']:
        Op = VStack([Op, Zero(par['ny'] - par['nx'], par['nx'])])
    eigs = Op.eigs()
    assert_array_almost_equal(diag[:eigs.size], eigs, decimal=3)

    # uselobpcg cannot be used for square non-symmetric complex matrices
    if np.iscomplex(Op):
        eigs1 = Op.eigs(uselobpcg=True)
        assert_array_almost_equal(eigs, eigs1, decimal=3)

    cond = Op.cond()
    assert_array_almost_equal(np.real(cond), par['nx'], decimal=3)

    # uselobpcg cannot be used for square non-symmetric complex matrices
    if np.iscomplex(Op):
        cond1 = Op.cond(uselobpcg=True, niter=100)
        assert_array_almost_equal(np.real(cond), np.real(cond1), decimal=3) 
开发者ID:equinor,项目名称:pylops,代码行数:35,代码来源:test_linearoperator.py

示例2: _ll_nbin

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import iscomplex [as 别名]
def _ll_nbin(self, params, alpha, Q=0):
        if np.any(np.iscomplex(params)) or np.iscomplex(alpha):
            gamma_ln = loggamma
        else:
            gamma_ln = gammaln
        endog = self.endog
        mu = self.predict(params)
        size = 1/alpha * mu**Q
        prob = size/(size+mu)
        coeff = (gamma_ln(size+endog) - gamma_ln(endog+1) -
                 gamma_ln(size))
        llf = coeff + size*np.log(prob) + endog*np.log(1-prob)
        return llf 
开发者ID:birforce,项目名称:vnpy_crypto,代码行数:15,代码来源:discrete_model.py

示例3: iscomplex

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import iscomplex [as 别名]
def iscomplex(x):
  return array_ops.imag(x) != 0 
开发者ID:google,项目名称:trax,代码行数:4,代码来源:math_ops.py

示例4: t_REAL

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import iscomplex [as 别名]
def t_REAL(self, t):
        r'(([0-9]+|([0-9]+)?\.[0-9]+|[0-9]+\.)[eE][+-]?[0-9]+)|(([0-9]+)?\.[0-9]+|[0-9]+\.)'
        if np.iscomplex(t):
            return t.real
        else:
            return t 
开发者ID:Qiskit,项目名称:qiskit-terra,代码行数:8,代码来源:qasmlexer.py

示例5: iscomplex

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import iscomplex [as 别名]
def iscomplex(x):
    """Returns a bool array, where True if input element is complex.

    What is tested is whether the input has a non-zero imaginary part, not if
    the input type is complex.

    Args:
        x (cupy.ndarray): Input array.

    Returns:
        cupy.ndarray: Boolean array of the same shape as ``x``.

    .. seealso::
        :func:`isreal`, :func:`iscomplexobj`

    Examples
    --------
    >>> cupy.iscomplex(cupy.array([1+1j, 1+0j, 4.5, 3, 2, 2j]))
    array([ True, False, False, False, False,  True])

    """
    if numpy.isscalar(x):
        return numpy.iscomplex(x)
    if not isinstance(x, cupy.ndarray):
        return cupy.asarray(numpy.iscomplex(x))
    if x.dtype.kind == 'c':
        return x.imag != 0
    return cupy.zeros(x.shape, bool) 
开发者ID:cupy,项目名称:cupy,代码行数:30,代码来源:type_test.py

示例6: iscomplexobj

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import iscomplex [as 别名]
def iscomplexobj(x):
    """Check for a complex type or an array of complex numbers.

    The type of the input is checked, not the value. Even if the input
    has an imaginary part equal to zero, `iscomplexobj` evaluates to True.

    Args:
        x (cupy.ndarray): Input array.

    Returns:
        bool: The return value, True if ``x`` is of a complex type or
        has at least one complex element.

    .. seealso::
        :func:`isrealobj`, :func:`iscomplex`

    Examples
    --------
    >>> cupy.iscomplexobj(cupy.array([3, 1+0j, True]))
    True
    >>> cupy.iscomplexobj(cupy.array([3, 1, True]))
    False

    """
    if not isinstance(x, cupy.ndarray):
        return numpy.iscomplexobj(x)
    return x.dtype.kind == 'c' 
开发者ID:cupy,项目名称:cupy,代码行数:29,代码来源:type_test.py

示例7: isreal

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import iscomplex [as 别名]
def isreal(x):
    """Returns a bool array, where True if input element is real.

    If element has complex type with zero complex part, the return value
    for that element is True.

    Args:
        x (cupy.ndarray): Input array.

    Returns:
        cupy.ndarray: Boolean array of same shape as ``x``.

    .. seealso::
        :func:`iscomplex`, :func:`isrealobj`

    Examples
    --------
    >>> cupy.isreal(cp.array([1+1j, 1+0j, 4.5, 3, 2, 2j]))
    array([False,  True,  True,  True,  True, False])

    """
    if numpy.isscalar(x):
        return numpy.isreal(x)
    if not isinstance(x, cupy.ndarray):
        return cupy.asarray(numpy.isreal(x))
    if x.dtype.kind == 'c':
        return x.imag == 0
    return cupy.ones(x.shape, bool) 
开发者ID:cupy,项目名称:cupy,代码行数:30,代码来源:type_test.py

示例8: test_outer_product

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import iscomplex [as 别名]
def test_outer_product(self, n, dtype):
        r"""Check that hafnian(x \otimes x) = hafnian(J_2n)*prod(x)"""
        x = np.random.rand(2 * n) + 1j * np.random.rand(2 * n)

        if not np.iscomplex(dtype()):
            x = x.real

        x = dtype(x)
        A = np.outer(x, x)

        rpt = np.ones([2 * n], dtype=np.int32)
        haf = hafnian_repeated(A, rpt)
        expected = np.prod(x) * fac(2 * n) / (fac(n) * (2 ** n))
        assert np.allclose(haf, expected) 
开发者ID:XanaduAI,项目名称:thewalrus,代码行数:16,代码来源:test_hafnian_repeated.py

示例9: set_filters

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import iscomplex [as 别名]
def set_filters(self, filters, padding_type='SAME'):
        """
        Given a list of temporal 1D filters of variable size, this method creates a
        list of nn.conv1d objects that collectively form the filter bank.

        :param filters: list, collection of filters each a np.ndarray
        :param padding_type: str, should be SAME or VALID
        :return:
        """

        assert isinstance(filters, list)
        assert padding_type in ['SAME', 'VALID']

        self._filters = [None]*len(filters)
        for ind, filt in enumerate(filters):

            assert filt.dtype in (np.float32, np.float64, np.complex64, np.complex128)

            if np.iscomplex(filt).any():
                chn_out = 2
                filt_weights = np.asarray([np.real(filt), np.imag(filt)], np.float32)
            else:
                chn_out = 1
                filt_weights = filt.astype(np.float32)[None,:]

            filt_weights = np.expand_dims(filt_weights, 1)  # append chn_in dimension
            filt_size = filt_weights.shape[-1]              # filter length
            padding = self._get_padding(padding_type, filt_size)

            conv = nn.Conv1d(1, chn_out, kernel_size=filt_size, padding=padding, bias=False)
            conv.weight.data = torch.from_numpy(filt_weights)
            conv.weight.requires_grad_(False)

            if self._cuda: conv.cuda()
            self._filters[ind] = conv 
开发者ID:tomrunia,项目名称:PyTorchWavelets,代码行数:37,代码来源:network.py

示例10: test_iscomplex

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import iscomplex [as 别名]
def test_iscomplex(self):
        self.check(np.iscomplex)
        assert np.iscomplex([1. + 1j]*u.m) 
开发者ID:holzschu,项目名称:Carnets,代码行数:5,代码来源:test_quantity_non_ufuncs.py

示例11: find_zero_crossing_quadratic

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import iscomplex [as 别名]
def find_zero_crossing_quadratic(x1, y1, x2, y2, x3, y3, eps=1.0):
        """ Find zero crossing using quadratic approximation along 1d line"""
        # compute coords along 1d line
        v = x2 - x1
        v = v / np.linalg.norm(v)
        if v[v != 0].shape[0] == 0:
            logging.error('Difference is 0. Probably a bug')

        t1 = 0
        t2 = (x2 - x1)[v != 0] / v[v != 0]
        t2 = t2[0]
        t3 = (x3 - x1)[v != 0] / v[v != 0]
        t3 = t3[0]

        # solve for quad approx
        x1_row = np.array([t1 ** 2, t1, 1])
        x2_row = np.array([t2 ** 2, t2, 1])
        x3_row = np.array([t3 ** 2, t3, 1])
        X = np.array([x1_row, x2_row, x3_row])
        y_vec = np.array([y1, y2, y3])
        try:
            w = np.linalg.solve(X, y_vec)
        except np.linalg.LinAlgError:
            logging.error('Singular matrix. Probably a bug')
            return None

        # get positive roots
        possible_t = np.roots(w)
        t_zc = None
        for i in range(possible_t.shape[0]):
            if 0 <= possible_t[i] <= 10 and not np.iscomplex(possible_t[i]):
                t_zc = possible_t[i]

        # if no positive roots find min
        if np.abs(w[0]) < 1e-10:
            return None

        if t_zc is None:
            t_zc = -w[1] / (2 * w[0])

        if t_zc < -eps or t_zc > eps:
            return None

        x_zc = x1 + t_zc * v
        return x_zc 
开发者ID:lianghongzhuo,项目名称:PointNetGPD,代码行数:47,代码来源:sdf.py

示例12: find_zero_crossing_quadratic

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import iscomplex [as 别名]
def find_zero_crossing_quadratic(x1, y1, x2, y2, x3, y3, eps = 1.0):
        """ Find zero crossing using quadratic approximation along 1d line"""
        # compute coords along 1d line
        v = x2 - x1
        v = v / np.linalg.norm(v)
        if v[v!=0].shape[0] == 0:
            logging.error('Difference is 0. Probably a bug')
            
        t1 = 0
        t2 = (x2 - x1)[v!=0] / v[v!=0]
        t2 = t2[0]
        t3 = (x3 - x1)[v!=0] / v[v!=0]
        t3 = t3[0]
            
        # solve for quad approx
        x1_row = np.array([t1**2, t1, 1])
        x2_row = np.array([t2**2, t2, 1])
        x3_row = np.array([t3**2, t3, 1])
        X = np.array([x1_row, x2_row, x3_row])
        y_vec = np.array([y1, y2, y3])
        try:
            w = np.linalg.solve(X, y_vec)
        except np.linalg.LinAlgError:
            logging.error('Singular matrix. Probably a bug')
            return None

        # get positive roots
        possible_t = np.roots(w)
        t_zc = None
        for i in range(possible_t.shape[0]):
            if possible_t[i] >= 0 and possible_t[i] <= 10 and not np.iscomplex(possible_t[i]):
                t_zc = possible_t[i]

        # if no positive roots find min
        if np.abs(w[0]) < 1e-10:
            return None

        if t_zc is None:
            t_zc = -w[1] / (2 * w[0])

        if t_zc < -eps or t_zc > eps:
            return None

        x_zc = x1 + t_zc * v
        return x_zc 
开发者ID:BerkeleyAutomation,项目名称:meshpy,代码行数:47,代码来源:sdf.py

示例13: filter

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import iscomplex [as 别名]
def filter(self, array, *args, **kwargs):
        arr1 = array[0]
        arr2 = array[1]
        ny, nx = arr1.shape
        dy, dx = 2 ** (int(np.log(min(ny, 4096)) / np.log(2))), 2 ** (int(np.log(min(nx, 4096)) / np.log(2)))
        offset = coreg(arr1[(ny - dy) / 2:(ny + dy) / 2, (nx - dx) / 2:(nx + dx) / 2],
                       arr2[(ny - dy) / 2:(ny + dy) / 2, (nx - dx) / 2:(nx + dx) / 2])
        logging.info('Global offset : ' + str(int(offset[0])) + ' / ' + str(int(offset[1])))

        paty = np.arange(12) * ny / 12
        patx = np.arange(12) * nx / 12
        dy = 2 ** (int(np.log(ny / 12) / np.log(2)))
        dx = 2 ** (int(np.log(nx / 12) / np.log(2)))
        offy = np.zeros((10, 10))
        offx = np.zeros((10, 10))

        for y, yp in enumerate(paty[1:11]):
            for x, xp in enumerate(patx[1:11]):
                amp1 = np.abs(arr1[yp:yp + dy, xp:xp + dx])
                amp2 = np.abs(
                    arr2[yp - int(offset[0]):yp + dy - int(offset[0]), xp - int(offset[1]):xp + dx - int(offset[1])])

                foo = coreg(amp1, amp2, sub=True)
                offy[y, x] = foo[0] + offset[0]
                offx[y, x] = foo[1] + offset[1]

        # pdb.set_trace()
        xx, yy = np.meshgrid(patx[1:11], paty[1:11])
        cx = polyfit2d(yy.flatten(), xx.flatten(), offx.flatten(), order=2)
        cy = polyfit2d(yy.flatten(), xx.flatten(), offy.flatten(), order=2)
        #cx = polyfit2d(xx.flatten(), yy.flatten(), offx.flatten(), order=3)
        #cy = polyfit2d(xx.flatten(), yy.flatten(), offy.flatten(), order=3)

        ny, nx = arr2.shape
        xx, yy = np.meshgrid(np.arange(nx), np.arange(ny))
        px = polyval2d(yy, xx, cx)
        py = polyval2d(yy, xx, cy)
        #px = polyval2d(xx, yy, cx)
        #py = polyval2d(xx, yy, cy)
        if np.iscomplex(arr2):
            arr2 = ndimage.map_coordinates(arr2.real, np.rollaxis(np.dstack([yy - py, xx - px]), 2)) + \
                   1j * ndimage.map_coordinates(arr2.imag, np.rollaxis(np.dstack([yy - py, xx - px]), 2))
        else:
            arr2 = ndimage.map_coordinates(arr2, np.rollaxis(np.dstack([yy - py, xx - px]), 2))
        #pdb.set_trace()
        #arr2 = np.roll(np.roll(arr2, int(offset[0]), axis=0), int(offset[1]), axis=1)

        return arr2 
开发者ID:birgander2,项目名称:PyRAT,代码行数:50,代码来源:Coregister.py

示例14: cwplot

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import iscomplex [as 别名]
def cwplot(fb_est, rx, t, fs: int, fn) -> None:
    #%% time
    fg, axs = subplots(1, 2, figsize=(12, 6))
    ax = axs[0]
    ax.plot(t, rx.T.real)
    ax.set_xlabel("time [sec]")
    ax.set_ylabel("amplitude")
    ax.set_title("Noisy, jammed receive signal")
    #%% periodogram
    if DTPG >= (t[-1] - t[0]):
        dt = (t[-1] - t[0]) / 4
    else:
        dt = DTPG

    dtw = 2 * dt  #  seconds to window
    tstep = ceil(dt * fs)
    wind = ceil(dtw * fs)
    Nfft = zeropadfactor * wind

    f, Sraw = signal.welch(
        rx.ravel(), fs, nperseg=wind, noverlap=tstep, nfft=Nfft, return_onesided=False
    )

    if np.iscomplex(rx).any():
        f = np.fft.fftshift(f)
        Sraw = np.fft.fftshift(Sraw)

    ax = axs[1]
    ax.plot(f, Sraw, "r", label="raw signal")

    fc_est = f[Sraw.argmax()]

    # ax.set_yscale('log')
    ax.set_xlim([fc_est - 200, fc_est + 200])
    ax.set_xlabel("frequency [Hz]")
    ax.set_ylabel("amplitude")
    ax.legend()

    esttxt = ""

    if fn is None:  # simulation
        ax.axvline(ft + fb0, color="red", linestyle="--", label="true freq.")
        esttxt += f"true: {ft+fb0} Hz "

    for e in fb_est:
        ax.axvline(e, color="blue", linestyle="--", label="est. freq.")

    esttxt += " est: " + str(fb_est) + " Hz"

    ax.set_title(esttxt) 
开发者ID:scivision,项目名称:piradar,代码行数:52,代码来源:CWsubspace.py

示例15: cw_est

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import iscomplex [as 别名]
def cw_est(rx, fs: int, Ntone: int, method: str = "esprit", usepython=False, useall=False):
    """
    estimate beat frequency using subspace frequency estimation techniques.
    This is much faster in Fortran, but to start using Python alone doesn't require compiling Fortran.

    ESPRIT and RootMUSIC are two popular subspace techniques.

    Matlab's rootmusic is a far inferior FFT-based method with very poor accuracy vs. my implementation.
    """
    assert isinstance(method, str)
    method = method.lower()

    tic = time()
    if method == "esprit":
        #%% ESPRIT
        if rx.ndim == 2:
            assert usepython, "Fortran not yet configured for multi-pulse case"
            Ntone *= 2

        if usepython or (Sc is None and Sr is None):
            print("Python ESPRIT")
            fb_est, sigma = esprit(rx, Ntone, Nblockest, fs)
        elif np.iscomplex(rx).any():
            print("Fortran complex64 ESPRIT")
            fb_est, sigma = Sc.subspace.esprit(rx, Ntone, Nblockest, fs)
        else:  # real signal
            print("Fortran float32 ESPRIT")
            fb_est, sigma = Sr.subspace.esprit(rx, Ntone, Nblockest, fs)

        fb_est = abs(fb_est)
    #%% ROOTMUSIC
    elif method == "rootmusic":
        fb_est, sigma = rootmusic(rx, Ntone, Nblockest, fs)
    else:
        raise ValueError(f"unknown estimation method: {method}")
    print(f"computed via {method} in {time()-tic:.1f} seconds.")
    #%% improvised process for CW only without notch filter
    # assumes first two results have largest singular values (from SVD)
    if not useall:
        i = sigma > 0.001  # arbitrary
        fb_est = fb_est[i]
        sigma = sigma[i]

    #        if fb_est.size>1:
    #            ii = np.argpartition(sigma, Ntone-1)[:Ntone-1]
    #            fb_est = fb_est[ii]
    #            sigma = sigma[ii]

    return fb_est, sigma 
开发者ID:scivision,项目名称:piradar,代码行数:51,代码来源:CWsubspace.py


注:本文中的numpy.iscomplex方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。