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


Python linalg.sqrtm方法代码示例

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


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

示例1: random_normal_draw

# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import sqrtm [as 别名]
def random_normal_draw(history, nb_samples, **kwargs):
    """Random normal distributed draws
    
    Arguments:
        history: numpy 2D array, with history along axis=0 and parameters 
            along axis=1
        nb_samples: number of samples to draw
        
    Returns:
        numpy 2D array, with samples along axis=0 and parameters along axis=1
    """
    scaler = StandardScaler()
    scaler.fit(history)
    scaled = scaler.transform(history)
    sqrt_cov = sqrtm(empirical_covariance(scaled)).real
    
    #Draw correlated random variables
    #draws are generated transposed for convenience of the dot operation
    draws = np.random.standard_normal((history.shape[-1], nb_samples))
    draws = np.dot(sqrt_cov, draws)
    draws = np.transpose(draws)
    return scaler.inverse_transform(draws) 
开发者ID:Andres-Hernandez,项目名称:CalibrationNN,代码行数:24,代码来源:instruments.py

示例2: test_round_trip_random_float

# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import sqrtm [as 别名]
def test_round_trip_random_float(self):
        np.random.seed(1234)
        for n in range(1, 6):
            M_unscaled = np.random.randn(n, n)
            for scale in np.logspace(-4, 4, 9):
                M = M_unscaled * scale

                # Eigenvalues are related to the branch cut.
                W = np.linalg.eigvals(M)
                err_msg = 'M:{0} eivals:{1}'.format(M, W)

                # Check sqrtm round trip because it is used within logm.
                M_sqrtm, info = sqrtm(M, disp=False)
                M_sqrtm_round_trip = M_sqrtm.dot(M_sqrtm)
                assert_allclose(M_sqrtm_round_trip, M)

                # Check logm round trip.
                M_logm, info = logm(M, disp=False)
                M_logm_round_trip = expm(M_logm)
                assert_allclose(M_logm_round_trip, M, err_msg=err_msg) 
开发者ID:ktraunmueller,项目名称:Computable,代码行数:22,代码来源:test_matfuncs.py

示例3: test_bad

# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import sqrtm [as 别名]
def test_bad(self):
        # See http://www.maths.man.ac.uk/~nareports/narep336.ps.gz
        e = 2**-5
        se = sqrt(e)
        a = array([[1.0,0,0,1],
                   [0,e,0,0],
                   [0,0,e,0],
                   [0,0,0,1]])
        sa = array([[1,0,0,0.5],
                    [0,se,0,0],
                    [0,0,se,0],
                    [0,0,0,1]])
        n = a.shape[0]
        assert_array_almost_equal(dot(sa,sa),a)
        # Check default sqrtm.
        esa = sqrtm(a, disp=False, blocksize=n)[0]
        assert_array_almost_equal(dot(esa,esa),a)
        # Check sqrtm with 2x2 blocks.
        esa = sqrtm(a, disp=False, blocksize=2)[0]
        assert_array_almost_equal(dot(esa,esa),a) 
开发者ID:ktraunmueller,项目名称:Computable,代码行数:22,代码来源:test_matfuncs.py

示例4: test_sqrtm_type_conversion_mixed_sign_or_complex_spectrum

# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import sqrtm [as 别名]
def test_sqrtm_type_conversion_mixed_sign_or_complex_spectrum(self):
        complex_dtype_chars = ('F', 'D', 'G')
        for matrix_as_list in (
                [[1, 0], [0, -1]],
                [[0, 1], [1, 0]],
                [[0, 1, 0], [0, 0, 1], [1, 0, 0]]):

            # check that the spectrum has the expected properties
            W = scipy.linalg.eigvals(matrix_as_list)
            assert_(any(w.imag or w.real < 0 for w in W))

            # check complex->complex
            A = np.array(matrix_as_list, dtype=complex)
            A_sqrtm, info = sqrtm(A, disp=False)
            assert_(A_sqrtm.dtype.char in complex_dtype_chars)

            # check float->complex
            A = np.array(matrix_as_list, dtype=float)
            A_sqrtm, info = sqrtm(A, disp=False)
            assert_(A_sqrtm.dtype.char in complex_dtype_chars) 
开发者ID:ktraunmueller,项目名称:Computable,代码行数:22,代码来源:test_matfuncs.py

示例5: test_al_mohy_higham_2012_experiment_1

# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import sqrtm [as 别名]
def test_al_mohy_higham_2012_experiment_1(self):
        # Fractional powers of a tricky upper triangular matrix.
        A = _get_al_mohy_higham_2012_experiment_1()

        # Test remainder matrix power.
        A_funm_sqrt, info = funm(A, np.sqrt, disp=False)
        A_sqrtm, info = sqrtm(A, disp=False)
        A_rem_power = _matfuncs_inv_ssq._remainder_matrix_power(A, 0.5)
        A_power = fractional_matrix_power(A, 0.5)
        assert_array_equal(A_rem_power, A_power)
        assert_allclose(A_sqrtm, A_power)
        assert_allclose(A_sqrtm, A_funm_sqrt)

        # Test more fractional powers.
        for p in (1/2, 5/3):
            A_power = fractional_matrix_power(A, p)
            A_round_trip = fractional_matrix_power(A_power, 1/p)
            assert_allclose(A_round_trip, A, rtol=1e-2)
            assert_allclose(np.tril(A_round_trip, 1), np.tril(A, 1)) 
开发者ID:ktraunmueller,项目名称:Computable,代码行数:21,代码来源:test_matfuncs.py

示例6: starting_point

# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import sqrtm [as 别名]
def starting_point(self, random=False):
        """Heuristic to find a starting point candidate

        Parameters
        ----------
        random : `bool`
            Use a random orthogonal matrix instead of identity

        Returns
        -------
        startint_point : `np.ndarray`, shape=(n_nodes, n_nodes)
            A starting point candidate
        """
        sqrt_C = sqrtm(self.covariance)
        sqrt_L = np.sqrt(self.mean_intensity)
        if random:
            random_matrix = np.random.rand(self.n_nodes, self.n_nodes)
            M, _ = qr(random_matrix)
        else:
            M = np.eye(self.n_nodes)
        initial = np.dot(np.dot(sqrt_C, M), np.diag(1. / sqrt_L))
        return initial 
开发者ID:X-DataInitiative,项目名称:tick,代码行数:24,代码来源:hawkes_cumulant_matching.py

示例7: get_subsystem_fidelity

# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import sqrtm [as 别名]
def get_subsystem_fidelity(statevector, trace_systems, subsystem_state):
    """
    Compute the fidelity of the quantum subsystem.

    Args:
        statevector (list|array): The state vector of the complete system
        trace_systems (list|range): The indices of the qubits to be traced.
            to trace qubits 0 and 4 trace_systems = [0,4]
        subsystem_state (list|array): The ground-truth state vector of the subsystem

    Returns:
        numpy.ndarray: The subsystem fidelity
    """
    rho = np.outer(np.conj(statevector), statevector)
    rho_sub = partial_trace(rho, trace_systems).data
    rho_sub_in = np.outer(np.conj(subsystem_state), subsystem_state)
    fidelity = np.trace(
        sqrtm(
            np.dot(
                np.dot(sqrtm(rho_sub), rho_sub_in),
                sqrtm(rho_sub)
            )
        )
    ) ** 2
    return fidelity 
开发者ID:Qiskit,项目名称:qiskit-aqua,代码行数:27,代码来源:subsystem.py

示例8: __init__

# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import sqrtm [as 别名]
def __init__(self, dim, C=1.0):
        self._dim = dim
        if np.isscalar(C):
            # Scalar
            self._C2 = np.sqrt(C)
            self._generator = lambda n: self._C2 * randcn((self._dim, n))
        elif C.ndim == 1:
            # Vector
            if C.size != dim:
                raise ValueError('The size of C must be {0}.'.format(dim))
            self._C2 = np.sqrt(C).reshape((-1, 1))
            self._generator = lambda n: self._C2 * randcn((self._dim, n))
        elif C.ndim == 2:
            # Matrix
            if C.shape[0] != dim or C.shape[1] != dim:
                raise ValueError('The shape of C must be ({0}, {0}).'.format(dim))
            self._C2 = sqrtm(C)
            self._generator = lambda n: self._C2 @ randcn((self._dim, n))
        else:
            raise ValueError(
                'The covariance must be specified by a scalar, a vector of'
                'size {0}, or a matrix of {0}x{0}.'.format(dim)
            )
        self._C = C 
开发者ID:morriswmz,项目名称:doatools.py,代码行数:26,代码来源:signals.py

示例9: rand_map_with_BCSZ_dist

# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import sqrtm [as 别名]
def rand_map_with_BCSZ_dist(dim: int, kraus_rank: int) -> np.ndarray:
    """
    Given a Hilbert space dimension dim and a Kraus rank K, returns a dim^2 by dim^2 Choi
    matrix J(Λ) of a channel drawn from the BCSZ distribution with Kraus rank K [RQO]_.

    .. [RQO] Random quantum operations.
          Bruzda et al.
          Physics Letters A 373, 320 (2009).
          https://doi.org/10.1016/j.physleta.2008.11.043
          https://arxiv.org/abs/0804.2361

    :param dim: Hilbert space dimension.
    :param kraus_rank: The number of Kraus operators in the operator sum description of the channel.
    :return: dim^2 by dim^2 Choi matrix, drawn from the BCSZ distribution with Kraus rank K.
    """
    # TODO: this ^^ is CPTP, might want a flag that allows for just CP quantum operations.
    X = ginibre_matrix_complex(dim ** 2, kraus_rank)
    rho = X @ X.conj().T
    rho_red = partial_trace(rho, [0], [dim, dim])
    # Note that Eqn. 8 of [RQO] uses a *row* stacking convention so in that case we would write
    # Q = np.kron(np.eye(D), sqrtm(la.inv(rho_red)))
    # But as we use column stacking we need:
    Q = np.kron(sqrtm(la.inv(rho_red)), np.eye(dim))
    Z = Q @ rho @ Q
    return Z 
开发者ID:rigetti,项目名称:forest-benchmarking,代码行数:27,代码来源:random_operators.py

示例10: norm1

# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import sqrtm [as 别名]
def norm1(matr):
    """
    Returns the 1 norm of a matrix
    """
    return float(_np.real(_np.trace(_sqrtm(_np.dot(matr.conj().T, matr))))) 
开发者ID:pyGSTio,项目名称:pyGSTi,代码行数:7,代码来源:matrixtools.py

示例11: _hack_sqrtm

# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import sqrtm [as 别名]
def _hack_sqrtm(A):
    sqrt, _ = _spl.sqrtm(A, disp=False)  # Travis found this scipy function
    # to be incorrect in certain cases (we need a workaround)
    if _np.any(_np.isnan(sqrt)):  # this is sometimes a good fallback when sqrtm doesn't work.
        ev, U = _np.linalg.eig(A)
        sqrt = _np.dot(U, _np.dot(_np.diag(_np.sqrt(ev)), _np.linalg.inv(U)))

    return sqrt 
开发者ID:pyGSTio,项目名称:pyGSTi,代码行数:10,代码来源:optools.py

示例12: test_round_trip_random_complex

# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import sqrtm [as 别名]
def test_round_trip_random_complex(self):
        np.random.seed(1234)
        for n in range(1, 6):
            M_unscaled = np.random.randn(n, n) + 1j * np.random.randn(n, n)
            for scale in np.logspace(-4, 4, 9):
                M = M_unscaled * scale
                M_sqrtm, info = sqrtm(M, disp=False)
                M_sqrtm_round_trip = M_sqrtm.dot(M_sqrtm)
                assert_allclose(M_sqrtm_round_trip, M) 
开发者ID:ktraunmueller,项目名称:Computable,代码行数:11,代码来源:test_matfuncs.py

示例13: test_blocksizes

# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import sqrtm [as 别名]
def test_blocksizes(self):
        # Make sure I do not goof up the blocksizes when they do not divide n.
        np.random.seed(1234)
        for n in range(1, 8):
            A = np.random.rand(n, n) + 1j*np.random.randn(n, n)
            A_sqrtm_default, info = sqrtm(A, disp=False, blocksize=n)
            assert_allclose(A, np.linalg.matrix_power(A_sqrtm_default, 2))
            for blocksize in range(1, 10):
                A_sqrtm_new, info = sqrtm(A, disp=False, blocksize=blocksize)
                assert_allclose(A_sqrtm_default, A_sqrtm_new) 
开发者ID:ktraunmueller,项目名称:Computable,代码行数:12,代码来源:test_matfuncs.py

示例14: test_strict_upper_triangular

# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import sqrtm [as 别名]
def test_strict_upper_triangular(self):
        # This matrix has no square root.
        A = np.array([
            [0, 3, 0, 0],
            [0, 0, 3, 0],
            [0, 0, 0, 3],
            [0, 0, 0, 0]], dtype=float)
        A_sqrtm, info = sqrtm(A, disp=False)
        assert_(np.isnan(A_sqrtm).all()) 
开发者ID:ktraunmueller,项目名称:Computable,代码行数:11,代码来源:test_matfuncs.py

示例15: test_weird_matrix

# 需要导入模块: from scipy import linalg [as 别名]
# 或者: from scipy.linalg import sqrtm [as 别名]
def test_weird_matrix(self):
        # The square root of matrix B exists.
        A = np.array([
            [0, 0, 1],
            [0, 0, 0],
            [0, 1, 0]], dtype=float)
        B = np.array([
            [0, 1, 0],
            [0, 0, 0],
            [0, 0, 0]], dtype=float)
        assert_array_equal(B, A.dot(A))

        # But scipy sqrtm is not clever enough to find it.
        B_sqrtm, info = sqrtm(B, disp=False)
        assert_(np.isnan(B_sqrtm).all()) 
开发者ID:ktraunmueller,项目名称:Computable,代码行数:17,代码来源:test_matfuncs.py


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