當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。