python类complex()的实例源码

test_umath.py 文件源码 项目:krpcScripts 作者: jwvanderbeck 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def test_complex_nan_comparisons():
    nans = [complex(np.nan, 0), complex(0, np.nan), complex(np.nan, np.nan)]
    fins = [complex(1, 0), complex(-1, 0), complex(0, 1), complex(0, -1),
            complex(1, 1), complex(-1, -1), complex(0, 0)]

    with np.errstate(invalid='ignore'):
        for x in nans + fins:
            x = np.array([x])
            for y in nans + fins:
                y = np.array([y])

                if np.isfinite(x) and np.isfinite(y):
                    continue

                assert_equal(x < y, False, err_msg="%r < %r" % (x, y))
                assert_equal(x > y, False, err_msg="%r > %r" % (x, y))
                assert_equal(x <= y, False, err_msg="%r <= %r" % (x, y))
                assert_equal(x >= y, False, err_msg="%r >= %r" % (x, y))
                assert_equal(x == y, False, err_msg="%r == %r" % (x, y))
test_multiarray.py 文件源码 项目:krpcScripts 作者: jwvanderbeck 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def test_basic(self):
        dt_numeric = np.typecodes['AllFloat'] + np.typecodes['AllInteger']
        dt_complex = np.typecodes['Complex']

        # test real
        a = np.eye(3)
        for dt in dt_numeric + 'O':
            b = a.astype(dt)
            res = np.vdot(b, b)
            assert_(np.isscalar(res))
            assert_equal(np.vdot(b, b), 3)

        # test complex
        a = np.eye(3) * 1j
        for dt in dt_complex + 'O':
            b = a.astype(dt)
            res = np.vdot(b, b)
            assert_(np.isscalar(res))
            assert_equal(np.vdot(b, b), 3)

        # test boolean
        b = np.eye(3, dtype=np.bool)
        res = np.vdot(b, b)
        assert_(np.isscalar(res))
        assert_equal(np.vdot(b, b), True)
pac.py 文件源码 项目:dyfunconn 作者: makism 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def estimate(self, phases, phases_lohi):
        num_ts, ts_len = np.shape(phases)

        self.pairs = [(r1, r2) for r1 in xrange(0, num_ts) for r2 in xrange(r1, num_ts)]

        pacs_ts = np.zeros((num_ts, num_ts, ts_len), dtype=np.complex)
        pacs_avg = np.zeros((num_ts, num_ts))

        for pair in self.pairs:
            p1, p2 = pair
            phase1 = phases[p1, ]
            phase1_lohi = phases_lohi[p2, ]

            ts, avg = self.estimator.estimate_pair(phase1, phase1_lohi)

            pacs_ts[pair] = ts
            pacs_avg[pair] = avg

        return pacs_ts, pacs_avg
base.py 文件源码 项目:pumpp 作者: bmcfee 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def fill_value(dtype):
    '''Get a fill-value for a given dtype

    Parameters
    ----------
    dtype : type

    Returns
    -------
    `np.nan` if `dtype` is real or complex

    0 otherwise
    '''
    if np.issubdtype(dtype, np.float) or np.issubdtype(dtype, np.complex):
        return dtype(np.nan)

    return dtype(0)
mslin2circ.py 文件源码 项目:PiLL 作者: lofar-astron 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def mslin2circ(incol, outcol, outms, skipmetadata):
  tc = pt.table(outms, readonly=False, ack=False)
  dataXY = tc.getcol(incol)
  I=numpy.complex(0.0,1.0)
  dataRL = 0.5* numpy.transpose(numpy.array([
           +dataXY[:,:,0]-I*dataXY[:,:,1]+I*dataXY[:,:,2]+dataXY[:,:,3],
           +dataXY[:,:,0]+I*dataXY[:,:,1]+I*dataXY[:,:,2]-dataXY[:,:,3],
           +dataXY[:,:,0]-I*dataXY[:,:,1]-I*dataXY[:,:,2]-dataXY[:,:,3],
           +dataXY[:,:,0]+I*dataXY[:,:,1]-I*dataXY[:,:,2]+dataXY[:,:,3]]),
           (1,2,0))
  tc.putcol(outcol,dataRL)

  #Change metadata information to be circular feeds
  if not skipmetadata:
    feed = pt.table(tc.getkeyword('FEED'),readonly=False,ack=False)
    for tpart in feed.iter('ANTENNA_ID'):
        tpart.putcell('POLARIZATION_TYPE',0,['R','L'])

    polariz = pt.table(tc.getkeyword('POLARIZATION'),readonly=False,ack=False)
    polariz.putcell('CORR_TYPE',0,[5,6,7,8])

  tc.close()
mslin2circ.py 文件源码 项目:PiLL 作者: lofar-astron 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def mscirc2lin(incol, outcol, outms, skipmetadata):
  tc = pt.table(outms,readonly=False, ack=False)
  dataRL = tc.getcol(incol)
  I=numpy.complex(0.0,1.0)
  dataXY = 0.5* numpy.transpose(numpy.array([
              +dataRL[:,:,0]+dataRL[:,:,1]+dataRL[:,:,2]+dataRL[:,:,3],
           I*(+dataRL[:,:,0]-dataRL[:,:,1]+dataRL[:,:,2]-dataRL[:,:,3]),
           I*(-dataRL[:,:,0]-dataRL[:,:,1]+dataRL[:,:,2]+dataRL[:,:,3]),
              +dataRL[:,:,0]-dataRL[:,:,1]-dataRL[:,:,2]+dataRL[:,:,3] ]),
           (1,2,0))
  tc.putcol(outcol,dataXY)

  #Change metadata information to be circular feeds
  if not skipmetadata:
    feed = pt.table(tc.getkeyword('FEED'),readonly=False, ack=False)
    for tpart in feed.iter('ANTENNA_ID'):
        tpart.putcell('POLARIZATION_TYPE',0,['X','Y'])

    polariz = pt.table(tc.getkeyword('POLARIZATION'),readonly=False, ack=False)
    polariz.putcell('CORR_TYPE',0,[9,10,11,12])

  tc.close()
beamforming.py 文件源码 项目:nn_mask 作者: ZitengWang 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
def get_gev_vector(target_psd_matrix, noise_psd_matrix):
    """
    Returns the GEV beamforming vector.
    :param target_psd_matrix: Target PSD matrix
        with shape (bins, sensors, sensors)
    :param noise_psd_matrix: Noise PSD matrix
        with shape (bins, sensors, sensors)
    :return: Set of beamforming vectors with shape (bins, sensors)
    """
    bins, sensors, _ = target_psd_matrix.shape
    beamforming_vector = np.empty((bins, sensors), dtype=np.complex)
    for f in range(bins):
        try:
            eigenvals, eigenvecs = eigh(target_psd_matrix[f, :, :],
                                        noise_psd_matrix[f, :, :])
        except np.linalg.LinAlgError:
            eigenvals, eigenvecs = eig(target_psd_matrix[f, :, :],
                                       noise_psd_matrix[f, :, :])
        beamforming_vector[f, :] = eigenvecs[:, np.argmax(eigenvals)]
    return beamforming_vector
beamforming.py 文件源码 项目:nn_mask 作者: ZitengWang 项目源码 文件源码 阅读 37 收藏 0 点赞 0 评论 0
def apply_sdw_mwf(mix, target_psd_matrix, noise_psd_matrix, mu=1, corr=None):
    """
    Apply speech distortion weighted MWF: h = Tpsd * e1 / (Tpsd + mu*Npsd) 
    :param mix: the signal complex FFT
    :param target_psd_matrix (bins, sensors, sensors) 
    :param noise_psd_matrix
    :param mu: the lagrange factor
    :return 
    """
    bins, sensors, frames = mix.shape
    ref_vector = np.zeros((sensors,1), dtype=np.float)    
    if corr is None:
        ref_ch = 0
    else: # choose the channel with highest correlation with the others
        corr=corr.tolist()        
        while len(corr) > sensors:
            corr.remove(np.min(corr))
        ref_ch=np.argmax(corr)
    ref_vector[ref_ch,0]=1 

    mwf_vector = solve(target_psd_matrix + mu*noise_psd_matrix, target_psd_matrix[:,:,ref_ch])
    return np.einsum('...a,...at->...t', mwf_vector.conj(), mix)
beamforming.py 文件源码 项目:nn_mask 作者: ZitengWang 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def get_gevd_vals_vecs(target_psd_matrix, noise_psd_matrix):
    """
    Returns the eigenvalues and eigenvectors of GEVD
    :param target_psd_matrix: Target PSD matrix
        with shape (bins, sensors, sensors)
    :param noise_psd_matrix: Noise PSD matrix
        with shape (bins, sensors, sensors)
    :return: Set of eigen values  with shape (bins, sensors)
             eigenvectors (bins, sensors, sensors)
    """
    bins, sensors, _ = target_psd_matrix.shape
    eigen_values = np.empty((bins, sensors), dtype=np.complex)
    eigen_vectors = np.empty((bins, sensors, sensors), dtype=np.complex)
    for f in range(bins):
        try:
            eigenvals, eigenvecs = eigh(target_psd_matrix[f, :, :],
                                        noise_psd_matrix[f, :, :])
        except np.linalg.LinAlgError:
            eigenvals, eigenvecs = eig(target_psd_matrix[f, :, :],
                                       noise_psd_matrix[f, :, :])
        # values in increasing order                                       
        eigen_values[f,:] = eigenvals
        eigen_vectors[f, :] = eigenvecs
    return eigen_values, eigen_vectors
test_numeric.py 文件源码 项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda 作者: SignalMedia 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def test_simple_complex(self):
        #Test native complex input with native double scalar min/max.
        #Test native input with complex double scalar min/max.
        a = 3 * self._generate_data_complex(self.nr, self.nc)
        m = -0.5
        M = 1.
        ac = self.fastclip(a, m, M)
        act = self.clip(a, m, M)
        assert_array_strict_equal(ac, act)

        #Test native input with complex double scalar min/max.
        a = 3 * self._generate_data(self.nr, self.nc)
        m = -0.5 + 1.j
        M = 1. + 2.j
        ac = self.fastclip(a, m, M)
        act = self.clip(a, m, M)
        assert_array_strict_equal(ac, act)
test_umath.py 文件源码 项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda 作者: SignalMedia 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def test_against_cmath(self):
        import cmath

        points = [-1-1j, -1+1j, +1-1j, +1+1j]
        name_map = {'arcsin': 'asin', 'arccos': 'acos', 'arctan': 'atan',
                    'arcsinh': 'asinh', 'arccosh': 'acosh', 'arctanh': 'atanh'}
        atol = 4*np.finfo(np.complex).eps
        for func in self.funcs:
            fname = func.__name__.split('.')[-1]
            cname = name_map.get(fname, fname)
            try:
                cfunc = getattr(cmath, cname)
            except AttributeError:
                continue
            for p in points:
                a = complex(func(np.complex_(p)))
                b = cfunc(p)
                assert_(abs(a - b) < atol, "%s %s: %s; cmath: %s" % (fname, p, a, b))
test_umath.py 文件源码 项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda 作者: SignalMedia 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def test_complex_nan_comparisons():
    nans = [complex(np.nan, 0), complex(0, np.nan), complex(np.nan, np.nan)]
    fins = [complex(1, 0), complex(-1, 0), complex(0, 1), complex(0, -1),
            complex(1, 1), complex(-1, -1), complex(0, 0)]

    with np.errstate(invalid='ignore'):
        for x in nans + fins:
            x = np.array([x])
            for y in nans + fins:
                y = np.array([y])

                if np.isfinite(x) and np.isfinite(y):
                    continue

                assert_equal(x < y, False, err_msg="%r < %r" % (x, y))
                assert_equal(x > y, False, err_msg="%r > %r" % (x, y))
                assert_equal(x <= y, False, err_msg="%r <= %r" % (x, y))
                assert_equal(x >= y, False, err_msg="%r >= %r" % (x, y))
                assert_equal(x == y, False, err_msg="%r == %r" % (x, y))
test_multiarray.py 文件源码 项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda 作者: SignalMedia 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def test_basic(self):
        dt_numeric = np.typecodes['AllFloat'] + np.typecodes['AllInteger']
        dt_complex = np.typecodes['Complex']

        # test real
        a = np.eye(3)
        for dt in dt_numeric + 'O':
            b = a.astype(dt)
            res = np.vdot(b, b)
            assert_(np.isscalar(res))
            assert_equal(np.vdot(b, b), 3)

        # test complex
        a = np.eye(3) * 1j
        for dt in dt_complex + 'O':
            b = a.astype(dt)
            res = np.vdot(b, b)
            assert_(np.isscalar(res))
            assert_equal(np.vdot(b, b), 3)

        # test boolean
        b = np.eye(3, dtype=np.bool)
        res = np.vdot(b, b)
        assert_(np.isscalar(res))
        assert_equal(np.vdot(b, b), True)
test_11_ComplexProperties.py 文件源码 项目:core-framework 作者: RedhawkSDR 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def _queryDefaults(self, component):
        defaults = {"boolean"   : component.complexBooleanProp,
                    "ulong"     : component.complexULongProp,
                    "short"     : component.complexShortProp,
                    "float"     : component.complexFloatProp,
                    "octet"     : component.complexOctetProp,
                    "ushort"    : component.complexUShort,
                    "double"    : component.complexDouble,
                    "long"      : component.complexLong,
                    "longlong"  : component.complexLongLong,
                    "ulonglong" : component.complexULongLong}
        # TODO: char
        #"char"      : component.complexCharProp,
        #"char"      : numpy.complex(0,1),
        return defaults
sph.py 文件源码 项目:sound_field_analysis-py 作者: QULab 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def spbessel(n, kr):
    """Spherical Bessel function (first kind) of order n at kr

    Parameters
    ----------
    n : array_like
       Order
    kr: array_like
       Argument

    Returns
    -------
    J : complex float
       Spherical Bessel
    """
    n, kr = scalar_broadcast_match(n, kr)

    if _np.any(n < 0) | _np.any(kr < 0) | _np.any(_np.mod(n, 1) != 0):
        J = _np.zeros(kr.shape, dtype=_np.complex_)

        kr_non_zero = kr != 0
        J[kr_non_zero] = _np.lib.scimath.sqrt(_np.pi / 2 / kr[kr_non_zero]) * besselj(n[kr_non_zero] + 0.5, kr[kr_non_zero])
        J[_np.logical_and(kr == 0, n == 0)] = 1
    else:
        J = scy.spherical_jn(n.astype(_np.int), kr)
    return _np.squeeze(J)
sph.py 文件源码 项目:sound_field_analysis-py 作者: QULab 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def spneumann(n, kr):
    """Spherical Neumann (Bessel second kind) of order n at kr

    Parameters
    ----------
    n : array_like
       Order
    kr: array_like
       Argument

    Returns
    -------
    Yv : complex float
       Spherical Neumann (Bessel second kind)
    """
    n, kr = scalar_broadcast_match(n, kr)

    if _np.any(n < 0) | _np.any(_np.mod(n, 1) != 0):
        Yv = _np.full(kr.shape, _np.nan, dtype=_np.complex_)

        kr_non_zero = kr != 0
        Yv[kr_non_zero] = _np.lib.scimath.sqrt(_np.pi / 2 / kr[kr_non_zero]) * neumann(n[kr_non_zero] + 0.5, kr[kr_non_zero])
        Yv[kr < 0] = -Yv[kr < 0]
    else:
        Yv = scy.spherical_yn(n.astype(_np.int), kr)
        Yv[_np.isinf(Yv)] = _np.nan  # return possible infs as nan to stay consistent
    return _np.squeeze(Yv)
sph.py 文件源码 项目:sound_field_analysis-py 作者: QULab 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def spherical_extrapolation(order, array_configuration, k_mic, k_scatter=None, k_dual=None):
    """ Factor that relate signals recorded on a sphere to it's center.

    Parameters
    ----------
    order : int
       Order
    array_configuration : ArrayConfiguration
       List/Tuple/ArrayConfiguration, see io.ArrayConfiguration
    k_mic : array_like
       K vector for microphone array
    k_scatter: array_like, optional
       K vector for scatterer  (Default: same as k_mic)

    Returns
    -------
    b : array, complex
    """
    array_configuration = ArrayConfiguration(*array_configuration)

    if array_configuration.array_type is 'open':
        if array_configuration.transducer_type is 'omni':
            return bn_open_omni(order, k_mic)
        elif array_configuration.transducer_type is 'cardioid':
            return bn_open_cardioid(order, k_mic)
    elif array_configuration.array_type is 'rigid':
        if array_configuration.transducer_type is 'omni':
            return bn_rigid_omni(order, k_mic, k_scatter)
        elif array_configuration.transducer_type is 'cardioid':
            return bn_rigid_cardioid(order, k_mic, k_scatter)
    elif array_configuration.array_type is 'dual':
        return bn_dual_open_omni(order, k_mic, k_dual)
sph.py 文件源码 项目:sound_field_analysis-py 作者: QULab 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
def sph_harm(m, n, az, el, type='complex'):
    '''Compute sphercial harmonics

    Parameters
    ----------
    m : (int)
        Order of the spherical harmonic. abs(m) <= n

    n : (int)
        Degree of the harmonic, sometimes called l. n >= 0

    az: (float)
        Azimuthal (longitudinal) coordinate [0, 2pi], also called Theta.

    el : (float)
        Elevation (colatitudinal) coordinate [0, pi], also called Phi.

    Returns
    -------
    y_mn : (complex float)
        Complex spherical harmonic of order m and degree n,
        sampled at theta = az, phi = el
    '''
    if type == 'legacy':
        return scy.sph_harm(m, n, az, el)
    elif type == 'real':
        Lnm = scy.lpmv(_np.abs(m), n, _np.cos(el))

        factor_1 = (2 * n + 1) / (4 * _np.pi)
        factor_2 = scy.factorial(n - _np.abs(m)) / scy.factorial(n + abs(m))

        if m != 0:
            factor_1 = 2 * factor_1

        if m < 0:
            return (-1) ** m * _np.sqrt(factor_1 * factor_2) * Lnm * _np.sin(m * az)
        else:
            return (-1) ** m * _np.sqrt(factor_1 * factor_2) * Lnm * _np.cos(m * az)
    else:
        # For the correct Condon–Shortley phase, all m>0 need to be increased by 1
        return (-1) ** _np.float_(m - (m < 0) * (m % 2)) * scy.sph_harm(m, n, az, el)
caustics.py 文件源码 项目:MulensModel 作者: rpoleski 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def _solve_lens_equation(self, complex_value):
        """
        Solve the lens equation for the given point (in complex coordinates).
        """
        complex_conjugate = np.conjugate(complex_value)
        return complex_value - (1. / (1. + self.q)) * (
            (1./complex_conjugate) + (self.q / (complex_conjugate - self.s)))
qerbt.py 文件源码 项目:untwist 作者: IoSR-Surrey 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def make_filterbank(self):
        erb_max = hz2erb(self.sr/2.0)
        erb_freqs = np.arange(0, self.n_bins) * erb_max / float(self.n_bins - 1)
        self.hz_freqs = erb2hz(erb_freqs)
        self.widths = np.round(0.5 * (self.n_bins - 1) / erb_max * 
            9.26 * 0.00437 * self.sr * np.exp(-erb_freqs / 9.26) - 0.5)
        self.filters = []
        for b in range(self.n_bins):
            w = self.widths[b]
            f = self.hz_freqs[b]
            exponential = np.exp(
                np.complex(0,1) * 2 * np.pi * f / self.sr * 
                np.arange(-w, w + 1))
            self.filters.append(np.hanning(2 * w + 1) * exponential)


问题


面经


文章

微信
公众号

扫码关注公众号