Python numpy.iscomplex() Examples

The following are 15 code examples for showing how to use numpy.iscomplex(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module numpy , or try the search function .

Example 1
Project: pylops   Author: equinor   File: test_linearoperator.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
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) 
Example 2
Project: vnpy_crypto   Author: birforce   File: discrete_model.py    License: MIT License 5 votes vote down vote up
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 
Example 3
Project: trax   Author: google   File: math_ops.py    License: Apache License 2.0 5 votes vote down vote up
def iscomplex(x):
  return array_ops.imag(x) != 0 
Example 4
Project: qiskit-terra   Author: Qiskit   File: qasmlexer.py    License: Apache License 2.0 5 votes vote down vote up
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 
Example 5
Project: cupy   Author: cupy   File: type_test.py    License: MIT License 5 votes vote down vote up
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) 
Example 6
Project: cupy   Author: cupy   File: type_test.py    License: MIT License 5 votes vote down vote up
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' 
Example 7
Project: cupy   Author: cupy   File: type_test.py    License: MIT License 5 votes vote down vote up
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) 
Example 8
Project: thewalrus   Author: XanaduAI   File: test_hafnian_repeated.py    License: Apache License 2.0 5 votes vote down vote up
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) 
Example 9
Project: PyTorchWavelets   Author: tomrunia   File: network.py    License: MIT License 5 votes vote down vote up
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 
Example 10
Project: Carnets   Author: holzschu   File: test_quantity_non_ufuncs.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_iscomplex(self):
        self.check(np.iscomplex)
        assert np.iscomplex([1. + 1j]*u.m) 
Example 11
Project: PointNetGPD   Author: lianghongzhuo   File: sdf.py    License: MIT License 4 votes vote down vote up
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 
Example 12
Project: meshpy   Author: BerkeleyAutomation   File: sdf.py    License: Apache License 2.0 4 votes vote down vote up
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 
Example 13
Project: PyRAT   Author: birgander2   File: Coregister.py    License: Mozilla Public License 2.0 4 votes vote down vote up
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 
Example 14
Project: piradar   Author: scivision   File: CWsubspace.py    License: GNU Affero General Public License v3.0 4 votes vote down vote up
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) 
Example 15
Project: piradar   Author: scivision   File: CWsubspace.py    License: GNU Affero General Public License v3.0 4 votes vote down vote up
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