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


Python numpy.isrealobj函数代码示例

本文整理汇总了Python中numpy.isrealobj函数的典型用法代码示例。如果您正苦于以下问题:Python isrealobj函数的具体用法?Python isrealobj怎么用?Python isrealobj使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


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

示例1: _coherence_bavg

def _coherence_bavg(fxy, fxx, fyy):
    r"""
    Compute the band-averaged coherency between the spectra of two time series.
    input to this function is in the frequency domain

    Parameters
    ----------

    fxy : float array
         The cross-spectrum of the time series

    fyy,fxx : float array
         The spectra of the signals

    Returns
    -------

    float :
        the band-averaged coherence
    """
    if not np.isrealobj(fxx):
        fxx = np.real(fxx)
    if not np.isrealobj(fyy):
        fyy = np.real(fyy)

    return (np.abs(fxy.sum()) ** 2) / (fxx.sum() * fyy.sum())
开发者ID:Eric89GXL,项目名称:nitime,代码行数:26,代码来源:cohere.py

示例2: coherence_spec

def coherence_spec(fxy, fxx, fyy):
    r"""
    Compute the coherence between the spectra of two time series.

    Parameters of this function are in the frequency domain.

    Parameters
    ----------

    fxy : array
         The cross-spectrum of the time series

    fyy, fxx : array
         The spectra of the signals

    Returns
    -------

    float : a frequency-band-dependent measure of the linear association
        between the two time series

    See also
    --------
    :func:`coherence`
    """
    if not np.isrealobj(fxx):
        fxx = np.real(fxx)
    if not np.isrealobj(fyy):
        fyy = np.real(fyy)
    c = np.abs(fxy) ** 2 / (fxx * fyy)
    return c
开发者ID:Eric89GXL,项目名称:nitime,代码行数:31,代码来源:cohere.py

示例3: fftconv

def fftconv(a, b, axes=(0, 1)):
    """
    Compute a multi-dimensional convolution via the Discrete Fourier Transform.

    Parameters
    ----------
    a : array_like
      Input array
    b : array_like
      Input array
    axes : sequence of ints, optional (default (0, 1))
      Axes on which to perform convolution

    Returns
    -------
    ab : ndarray
      Convolution of input arrays, a and b, along specified axes
    """

    if np.isrealobj(a) and np.isrealobj(b):
        fft = rfftn
        ifft = irfftn
    else:
        fft = fftn
        ifft = ifftn
    dims = np.maximum([a.shape[i] for i in axes], [b.shape[i] for i in axes])
    af = fft(a, dims, axes)
    bf = fft(b, dims, axes)
    return ifft(af * bf, dims, axes)
开发者ID:bwohlberg,项目名称:sporco,代码行数:29,代码来源:linalg.py

示例4: same_upto_phase_factor

 def same_upto_phase_factor(self, *others, **kwargs):
     if sanity_checking_enabled:
         if not np.isrealobj(self) or any(not np.isrealobj(o) for o in others):
             raise NotImplementedError("phase factor detection complex Tensors is not yet implemented")
     cutoff = kwargs.pop('cutoff', Tensor.same_tensor_cutoff)
     for other in others:
         if (abs(other - self) > cutoff).any() and (abs(other + self) > cutoff).any():
             return False
     return True
开发者ID:keceli,项目名称:psi4release,代码行数:9,代码来源:tensor.py

示例5: evaluate

    def evaluate(self, ind, **kwargs):
        """
        Note that math functions used in the solutions are imported from either
        utilities.fitness.math_functions or called from numpy.

        :param ind: An individual to be evaluated.
        :param kwargs: An optional parameter for problems with training/test
        data. Specifies the distribution (i.e. training or test) upon which
        evaluation is to be performed.
        :return: The fitness of the evaluated individual.
        """

        dist = kwargs.get('dist', 'training')

        if dist == "training":
            # Set training datasets.
            x = self.training_in
            y = self.training_exp

        elif dist == "test":
            # Set test datasets.
            x = self.test_in
            y = self.test_exp

        else:
            raise ValueError("Unknown dist: " + dist)

        if params['OPTIMIZE_CONSTANTS']:
            # if we are training, then optimize the constants by
            # gradient descent and save the resulting phenotype
            # string as ind.phenotype_with_c0123 (eg x[0] +
            # c[0] * x[1]**c[1]) and values for constants as
            # ind.opt_consts (eg (0.5, 0.7). Later, when testing,
            # use the saved string and constants to evaluate.
            if dist == "training":
                return optimize_constants(x, y, ind)

            else:
                # this string has been created during training
                phen = ind.phenotype_consec_consts
                c = ind.opt_consts
                # phen will refer to x (ie test_in), and possibly to c
                yhat = eval(phen)
                assert np.isrealobj(yhat)

                # let's always call the error function with the
                # true values first, the estimate second
                return params['ERROR_METRIC'](y, yhat)

        else:
            # phenotype won't refer to C
            yhat = eval(ind.phenotype)
            assert np.isrealobj(yhat)

            # let's always call the error function with the true
            # values first, the estimate second
            return params['ERROR_METRIC'](y, yhat)
开发者ID:jmmcd,项目名称:PonyGE2,代码行数:57,代码来源:supervised_learning.py

示例6: eigenConcat

    def eigenConcat(omega, Q, AB, BB, k):
        """
        Find the eigen update of a matrix [A, B]'[A B] where  A'A = V diag(s) V*
        and AB = A*B, BB = B*B. Q is the set of eigenvectors of A*A and s is the
        vector of eigenvalues. 
        """
        #logging.debug("< eigenConcat >")
        Parameter.checkInt(k, 0, omega.shape[0])
        if not numpy.isrealobj(omega) or not numpy.isrealobj(Q):
            raise ValueError("Eigenvalues and eigenvectors must be real")
        if not numpy.isrealobj(AB) or not numpy.isrealobj(BB):
            raise ValueError("AB and BB must be real")
        if omega.ndim != 1:
            raise ValueError("omega must be 1-d array")
        if omega.shape[0] != Q.shape[1]:
            raise ValueError("Must have same number of eigenvalues and eigenvectors")
        if Q.shape[0] != AB.shape[0]:
            raise ValueError("Q must have the same number of rows as AB")
        if AB.shape[1] != BB.shape[0] or  BB.shape[0]!=BB.shape[1]:
            raise ValueError("AB must have the same number of cols/rows as BB")

        #Check Q is orthogonal
        if __debug__:
            Parameter.checkOrthogonal(Q, tol=EigenUpdater.tol, softCheck=True, arrayInfo = "input Q in eigenConcat()")

        m = Q.shape[0]
        p = BB.shape[0]

        inds = numpy.flipud(numpy.argsort(numpy.abs(omega)))
        Q = Q[:, inds[0:k]]
        omega = omega[inds[0:k]]
        Omega = numpy.diag(omega)

        QAB = Q.conj().T.dot(AB)

        F = numpy.c_[numpy.r_[Omega, QAB.conj().T], numpy.r_[QAB, BB]]
        D = numpy.c_[numpy.r_[Q, numpy.zeros((p, Q.shape[1]))], numpy.r_[numpy.zeros((m, p)), numpy.eye(p)]]

        pi, H = scipy.linalg.eigh(F)

        inds = numpy.flipud(numpy.argsort(numpy.abs(pi)))
        inds = inds[numpy.abs(pi)>EigenUpdater.tol]

        H = H[:, inds[0:k]]
        pi = pi[inds[0:k]]

        V = numpy.dot(D, H)

        #logging.debug("</ eigenConcat >")
        return pi, V
开发者ID:charanpald,项目名称:sandbox,代码行数:50,代码来源:EigenUpdater.py

示例7: __setitem__

 def __setitem__(self, name, value):
     if not isinstance(value, ndarray):
         value   = array(value)
     if not isrealobj(value):                
         self.__matlab_object.handle.PutFullMatrix(name, self.__name_space, value.real, value.imag)                
     else:
         self.__matlab_object.handle.PutWorkspaceData(name, self.__name_space, value)
开发者ID:VanDeng95,项目名称:WaveSyn,代码行数:7,代码来源:client.py

示例8: irfft

def irfft(x, n=None, axis=-1, overwrite_x=0):
    """ irfft(x, n=None, axis=-1, overwrite_x=0) -> y

    Return inverse discrete Fourier transform of real sequence x.
    The contents of x is interpreted as the output of rfft(..)
    function.

    The returned real array contains
      [y(0),y(1),...,y(n-1)]
    where for n is even
      y(j) = 1/n (sum[k=1..n/2-1] (x[2*k-1]+sqrt(-1)*x[2*k])
                                   * exp(sqrt(-1)*j*k* 2*pi/n)
                  + c.c. + x[0] + (-1)**(j) x[n-1])
    and for n is odd
      y(j) = 1/n (sum[k=1..(n-1)/2] (x[2*k-1]+sqrt(-1)*x[2*k])
                                   * exp(sqrt(-1)*j*k* 2*pi/n)
                  + c.c. + x[0])
    c.c. denotes complex conjugate of preceeding expression.

    Optional input: see rfft.__doc__
    """
    tmp = asarray(x)
    if not numpy.isrealobj(tmp):
        raise TypeError,"1st argument must be real sequence"
    if istype(tmp, numpy.float32):
        work_function = fftpack.rfft
    else:
        work_function = fftpack.drfft
    return _raw_fft(tmp,n,axis,-1,overwrite_x,work_function)
开发者ID:richardxy,项目名称:scipy3,代码行数:29,代码来源:basic.py

示例9: app_luinv_to_spmat

def app_luinv_to_spmat(alu_solve, Z):
    """ compute A.-1*Z  where A comes factored

    and with a solve routine for possibly complex Z

    Parameters
    ----------
    alu_solve : callable f(v)
        returning a matrix inverse applied to `v`
    Z : (N,K) ndarray, real or complex
        the inverse is to be applied to

    Returns
    -------
    , : (N,K) ndarray
        matrix inverse applied to ndarray

    """

    Z.tocsc()
    # ainvz = np.zeros(Z.shape)
    ainvzl = []  # to allow for complex values
    for ccol in range(Z.shape[1]):
        zcol = Z[:, ccol].toarray().flatten()
        if np.isrealobj(zcol):
            ainvzl.append(alu_solve(zcol))
        else:
            ainvzl.append(alu_solve(zcol.real) +
                          1j*alu_solve(zcol.imag))

    return np.asarray(ainvzl).T
开发者ID:highlando,项目名称:sadptprj_riclyap_adi,代码行数:31,代码来源:lin_alg_utils.py

示例10: rfft

def rfft(x, n=None, axis=-1, overwrite_x=False,
        planner_effort=None, threads=None,
        auto_align_input=True, auto_contiguous=True):
    '''Perform a 1D real FFT.

    The first three arguments are as per :func:`scipy.fftpack.rfft`;
    the rest of the arguments are documented
    in the :ref:`additional argument docs<interfaces_additional_args>`.
    '''
    if not numpy.isrealobj(x):
        raise TypeError('Input array must be real to maintain '
                'compatibility with scipy.fftpack.rfft.')

    x = numpy.asanyarray(x)
    planner_effort = _default_effort(planner_effort)
    threads = _default_threads(threads)

    complex_output = numpy_fft.rfft(x, n, axis, None, overwrite_x,
            planner_effort, threads, auto_align_input, auto_contiguous)

    output_shape = list(x.shape)
    if n is not None:
        output_shape[axis] = n

    return _complex_to_rfft_output(complex_output, output_shape, axis)
开发者ID:grlee77,项目名称:pyFFTW,代码行数:25,代码来源:scipy_fftpack.py

示例11: irfft

def irfft(
    x,
    n=None,
    axis=-1,
    overwrite_x=False,
    planner_effort="FFTW_MEASURE",
    threads=1,
    auto_align_input=True,
    auto_contiguous=True,
):
    """Perform a 1D real inverse FFT.
    
    The first three arguments are as per :func:`scipy.fftpack.irfft`; 
    the rest of the arguments are documented 
    in the :ref:`additional argument docs<interfaces_additional_args>`.
    """
    if not numpy.isrealobj(x):
        raise TypeError("Input array must be real to maintain " "compatibility with scipy.fftpack.irfft.")

    x = numpy.asanyarray(x)

    if n is None:
        n = x.shape[axis]

    complex_input = _irfft_input_to_complex(x, axis)

    return numpy_fft.irfft(
        complex_input, n, axis, overwrite_x, planner_effort, threads, auto_align_input, auto_contiguous
    )
开发者ID:rajath,项目名称:pyFFTW,代码行数:29,代码来源:scipy_fftpack.py

示例12: __init__

    def __init__(
        self,
        shape=None,
        dtype=None,
        data=None,
        shape_out=None,
        axes=None,
        normalize="rescale",
        stream=None,
    ):
        if not(__have_cufft__) or not(__have_cufft__):
            raise ImportError("Please install pycuda and scikit-cuda to use the CUDA back-end")

        super(CUFFT, self).__init__(
            shape=shape,
            dtype=dtype,
            data=data,
            shape_out=shape_out,
            axes=axes,
            normalize=normalize,
        )
        self.cufft_stream = stream
        self.backend = "cufft"

        self.configure_batched_transform()
        self.allocate_arrays()
        self.real_transform = np.isrealobj(self.data_in)
        self.compute_forward_plan()
        self.compute_inverse_plan()
        self.refs = {
            "data_in": self.data_in,
            "data_out": self.data_out,
        }
        self.configure_normalization()
开发者ID:vasole,项目名称:silx,代码行数:34,代码来源:cufft.py

示例13: pressureResponse

def pressureResponse(sim, forcex, forcez):

	nz = sim.nz
	nx = sim.nx

	transform = False
	if(np.isrealobj(forcex)):
		forcex = sim.makeSpect(forcex)
		forcez = sim.makeSpect(forcez)
		transform = True

	sim.assertDkx(forcex)
	sim.assertDkz(forcex)

	div = forcex * sim.dkx + forcez * sim.dkz

	pres = div / (sim.dkz**2 + sim.dkx**2)
	pres[0,0,0] = 0
 	solx = -pres * sim.dkx
	solz = -pres * sim.dkz

	if (transform == True):
		solx = np.fft.irfftn(solx)
		solz = np.fft.irfftn(solz)
		pres = np.fft.irfftn(pres)

	return [solx,solz,pres]
开发者ID:BenByington,项目名称:PythonTools,代码行数:27,代码来源:tubeDynamics2.py

示例14: rfft

def rfft(x, n=None, axis=-1, overwrite_x=0):
    """ rfft(x, n=None, axis=-1, overwrite_x=0) -> y

    Return discrete Fourier transform of real sequence x.

    The returned real arrays contains
      [y(0),Re(y(1)),Im(y(1)),...,Re(y(n/2))]              if n is even
      [y(0),Re(y(1)),Im(y(1)),...,Re(y(n/2)),Im(y(n/2))]   if n is odd
    where
      y(j) = sum[k=0..n-1] x[k] * exp(-sqrt(-1)*j*k* 2*pi/n)
      j = 0..n-1
    Note that y(-j) = y(n-j).

    Optional input:
      n
        Defines the length of the Fourier transform. If n is not
        specified then n=x.shape[axis] is set. If n<x.shape[axis],
        x is truncated. If n>x.shape[axis], x is zero-padded.
      axis
        The transform is applied along the given axis of the input
        array (or the newly constructed array if n argument was used).
      overwrite_x
        If set to true, the contents of x can be destroyed.

    Notes:
      y == rfft(irfft(y)) within numerical accuracy.
    """
    tmp = asarray(x)
    if not numpy.isrealobj(tmp):
        raise TypeError,"1st argument must be real sequence"
    work_function = fftpack.drfft
    return _raw_fft(tmp,n,axis,1,overwrite_x,work_function)
开发者ID:AndreI11,项目名称:SatStressGui,代码行数:32,代码来源:basic.py

示例15: acorr

def acorr(x, axis=-1, onesided=False, scale='none'):
    """Compute autocorrelation of x along given axis.

    Parameters
    ----------
        x : array-like
            signal to correlate.
        axis : int
            axis along which autocorrelation is computed.
        onesided: bool, optional
            if True, only returns the right side of the autocorrelation.
        scale: {'none', 'coeff'}
            scaling mode. If 'coeff', the correlation is normalized such as the
            0-lag is equal to 1.

    Notes
    -----
        Use fft for computation: is more efficient than direct computation for
        relatively large n.
    """
    if not np.isrealobj(x):
        raise ValueError("Complex input not supported yet")
    if not scale in ['none', 'coeff']:
        raise ValueError("scale mode %s not understood" % scale)

    maxlag = x.shape[axis]
    nfft = 2 ** nextpow2(2 * maxlag - 1)

    if axis != -1:
        x = np.swapaxes(x, -1, axis)
    a = _acorr_last_axis(x, nfft, maxlag, onesided, scale)
    if axis != -1:
        a = np.swapaxes(a, -1, axis)
    return a
开发者ID:Lathomas42,项目名称:Envelope_Detection,代码行数:34,代码来源:correlations.py


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