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


Python cvxpy.trace方法代码示例

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


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

示例1: tracenorm

# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import trace [as 别名]
def tracenorm(A):
    """
    Compute the trace norm of matrix A given by:

      Tr( sqrt{ A^dagger * A } )

    Parameters
    ----------
    A : numpy array
        The matrix to compute the trace norm of.
    """
    if _np.linalg.norm(A - _np.conjugate(A.T)) < 1e-8:
        #Hermitian, so just sum eigenvalue magnitudes
        return _np.sum(_np.abs(_np.linalg.eigvals(A)))
    else:
        #Sum of singular values (positive by construction)
        return _np.sum(_np.linalg.svd(A, compute_uv=False)) 
开发者ID:pyGSTio,项目名称:pyGSTi,代码行数:19,代码来源:optools.py

示例2: jtracedist

# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import trace [as 别名]
def jtracedist(A, B, mxBasis='pp'):  # Jamiolkowski trace distance:  Tr(|J(A)-J(B)|)
    """
    Compute the Jamiolkowski trace distance between operation matrices A and B,
    given by:

      D = 0.5 * Tr( sqrt{ (J(A)-J(B))^2 } )

    where J(.) is the Jamiolkowski isomorphism map that maps a operation matrix
    to it's corresponding Choi Matrix.

    Parameters
    ----------
    A, B : numpy array
        The matrices to compute the distance between.

    mxBasis : {'std', 'gm', 'pp', 'qt'} or Basis object
        The source and destination basis, respectively.  Allowed
        values are Matrix-unit (std), Gell-Mann (gm), Pauli-product (pp),
        and Qutrit (qt) (or a custom basis object).
    """
    JA = _jam.fast_jamiolkowski_iso_std(A, mxBasis)
    JB = _jam.fast_jamiolkowski_iso_std(B, mxBasis)
    return tracedist(JA, JB) 
开发者ID:pyGSTio,项目名称:pyGSTi,代码行数:25,代码来源:optools.py

示例3: povm_jtracedist

# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import trace [as 别名]
def povm_jtracedist(model, targetModel, povmlbl):
    """
    Computes the Jamiolkowski trace distance between POVM maps using :func:`jtracedist`.

    Parameters
    ----------
    model, targetModel : Model
        Models containing the two POVMs to compare.

    povmlbl : str
        The POVM label

    Returns
    -------
    float
    """
    povm_mx = get_povm_map(model, povmlbl)
    target_povm_mx = get_povm_map(targetModel, povmlbl)
    return jtracedist(povm_mx, target_povm_mx, targetModel.basis) 
开发者ID:pyGSTio,项目名称:pyGSTi,代码行数:21,代码来源:optools.py

示例4: partial_trace_super

# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import trace [as 别名]
def partial_trace_super(dim1: int, dim2: int) -> np.array:
    """
    Return the partial trace superoperator in the column-major basis.

    This returns the superoperator S_TrB such that:
        S_TrB * vec(rho_AB) = vec(rho_A)
    for rho_AB = kron(rho_A, rho_B)

    Args:
        dim1: the dimension of the system not being traced
        dim2: the dimension of the system being traced over

    Returns:
        A Numpy array of the partial trace superoperator S_TrB.
    """

    iden = sps.identity(dim1)
    ptr = sps.csr_matrix((dim1 * dim1, dim1 * dim2 * dim1 * dim2))

    for j in range(dim2):
        v_j = sps.coo_matrix(([1], ([0], [j])), shape=(1, dim2))
        tmp = sps.kron(iden, v_j.tocsr())
        ptr += sps.kron(tmp, tmp)

    return ptr 
开发者ID:Qiskit,项目名称:qiskit-ignis,代码行数:27,代码来源:cvx_fit.py

示例5: purity

# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import trace [as 别名]
def purity(rho: np.ndarray, dim_renorm=False, tol: float = 1000) -> float:
    """
    Calculates the purity :math:`P = tr[ρ^2]` of a quantum state ρ.

    As stated above lower value of the purity depends on the dimension of ρ's Hilbert space. For
    some applications this can be undesirable. For this reason we introduce an optional dimensional
    renormalization flag with the following behavior

    If the dimensional renormalization flag is FALSE (default) then  1/dim ≤ P ≤ 1.
    If the dimensional renormalization flag is TRUE then 0 ≤ P ≤ 1.

    where dim is the dimension of ρ's Hilbert space.

    :param rho: Is a dim by dim positive matrix with unit trace.
    :param dim_renorm: Boolean, default False.
    :param tol: Tolerance in machine epsilons for np.real_if_close.
    :return: P the purity of the state.
    """
    p = np.trace(rho @ rho)
    if dim_renorm:
        dim = rho.shape[0]
        p = (dim / (dim - 1.0)) * (p - 1.0 / dim)
    return np.ndarray.item(np.real_if_close(p, tol)) 
开发者ID:rigetti,项目名称:forest-benchmarking,代码行数:25,代码来源:distance_measures.py

示例6: impurity

# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import trace [as 别名]
def impurity(rho: np.ndarray, dim_renorm=False, tol: float = 1000) -> float:
    """
    Calculates the impurity (or linear entropy) :math:`L = 1 - tr[ρ^2]` of a quantum state ρ.

    As stated above the lower value of the impurity depends on the dimension of ρ's Hilbert space.
    For some applications this can be undesirable. For this reason we introduce an optional
    dimensional renormalization flag with the following behavior

    If the dimensional renormalization flag is FALSE (default) then  0 ≤ L ≤ 1/dim.
    If the dimensional renormalization flag is TRUE then 0 ≤ L ≤ 1.

    where dim is the dimension of ρ's Hilbert space.

    :param rho: Is a dim by dim positive matrix with unit trace.
    :param dim_renorm: Boolean, default False.
    :param tol: Tolerance in machine epsilons for np.real_if_close.
    :return: L the impurity of the state.
    """
    imp = 1 - np.trace(rho @ rho)
    if dim_renorm:
        dim = rho.shape[0]
        imp = (dim / (dim - 1.0)) * imp
    return np.ndarray.item(np.real_if_close(imp, tol)) 
开发者ID:rigetti,项目名称:forest-benchmarking,代码行数:25,代码来源:distance_measures.py

示例7: fidelity

# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import trace [as 别名]
def fidelity(rho: np.ndarray, sigma: np.ndarray, tol: float = 1000) -> float:
    r"""
    Computes the fidelity :math:`F(\rho, \sigma)` between two quantum states rho and sigma.

    If the states are pure the expression reduces to

    .. math::

        F(|psi>,|phi>) = |<psi|phi>|^2

    The fidelity obeys :math:`0 ≤ F(\rho, \sigma) ≤ 1`, where
    :math:`F(\rho, \sigma)=1 iff \rho = \sigma`.

    :param rho: Is a dim by dim positive matrix with unit trace.
    :param sigma: Is a dim by dim positive matrix with unit trace.
    :param tol: Tolerance in machine epsilons for np.real_if_close.
    :return: Fidelity which is a scalar.
    """
    sqrt_rho = sqrtm_psd(rho)
    fid = (np.trace(sqrtm_psd(sqrt_rho @ sigma @ sqrt_rho))) ** 2
    return np.ndarray.item(np.real_if_close(fid, tol)) 
开发者ID:rigetti,项目名称:forest-benchmarking,代码行数:23,代码来源:distance_measures.py

示例8: bures_angle

# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import trace [as 别名]
def bures_angle(rho: np.ndarray, sigma: np.ndarray) -> float:
    r"""
    Computes the Bures angle (AKA Bures arc or Bures length) between two states rho and sigma:

    .. math::

        D_A(\rho, \sigma) = \arccos(\sqrt{F(\rho, \sigma)})

    where :math:`F(\rho, \sigma)` is the fidelity.

    The Bures angle is a measure of statistical distance between quantum states.

    :param rho: Is a dim by dim positive matrix with unit trace.
    :param sigma: Is a dim by dim positive matrix with unit trace.
    :return: Bures angle which is a scalar.
    """
    return np.arccos(np.sqrt(fidelity(rho, sigma))) 
开发者ID:rigetti,项目名称:forest-benchmarking,代码行数:19,代码来源:distance_measures.py

示例9: hilbert_schmidt_ip

# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import trace [as 别名]
def hilbert_schmidt_ip(A: np.ndarray, B: np.ndarray, tol: float = 1000) -> float:
    r"""
    Computes the Hilbert-Schmidt (HS) inner product between two operators A and B.

    This inner product is defined as

    .. math::

        HS = (A|B) = Tr[A^\dagger B]

    where :math:`|B) = vec(B)` and :math:`(A|` is the dual vector to :math:`|A)`.

    :param A: Is a dim by dim positive matrix with unit trace.
    :param B: Is a dim by dim positive matrix with unit trace.
    :param tol: Tolerance in machine epsilons for np.real_if_close.
    :return: HS inner product which is a scalar.
    """
    hs_ip = np.trace(np.matmul(np.transpose(np.conj(A)), B))
    return np.ndarray.item(np.real_if_close(hs_ip, tol)) 
开发者ID:rigetti,项目名称:forest-benchmarking,代码行数:21,代码来源:distance_measures.py

示例10: smith_fidelity

# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import trace [as 别名]
def smith_fidelity(rho: np.ndarray, sigma: np.ndarray, power) -> float:
    r"""
    Computes the Smith fidelity :math:`F_S(\rho, \sigma, power)` between two quantum states rho and
    sigma.

    The Smith fidelity is  defined as :math:`F_S = \sqrt{F^{power}}`, where F is  standard fidelity
    :math:`F = fidelity(\rho, \sigma)`. Since the power is only defined for values less than 2,
    it is always true that :math:`F_S > F`.

    At present there is no known operational interpretation of the Smith fidelity for an arbitrary
    power.

    :param rho: Is a dim by dim positive matrix with unit trace.
    :param sigma: Is a dim by dim positive matrix with unit trace.
    :param power: Is a positive scalar less than 2.
    :return: Smith Fidelity which is a scalar.
    """
    if power < 0:
        raise ValueError("Power must be positive")
    if power >= 2:
        raise ValueError("Power must be less than 2")
    return np.sqrt(fidelity(rho, sigma)) ** power 
开发者ID:rigetti,项目名称:forest-benchmarking,代码行数:24,代码来源:distance_measures.py

示例11: _project

# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import trace [as 别名]
def _project(self, matrix):
        """The largest value in each row is set to 1.
        """
        result = np.zeros(self.shape)
        for i in range(self.shape[0]):
            idx = np.argmax(matrix[i,:])
            result[i, idx] = 1
        return result
        # ordering = self.a.T.dot(result)
        # indices = np.argsort(ordering)
        # return result[:,indices]
        # import cvxpy as cvx
        # X = cvx.Bool(self.shape)
        # constr = [cvx.sum(X, axis=1) == 1, cvx.diff((self.a.T*X).T) >= 0]
        # prob = cvx.Problem(cvx.Maximize(cvx.trace(matrix.T*X)), constr)
        # prob.solve(solver=cvx.GUROBI, timeLimit=10)
        # return X.value

    # def _neighbors(self, matrix):
    #     neighbors_list = []
    #     idxs = np.argmax(matrix, axis=1)
    #     for i in range(self.shape[0]):
    #         for j in range(self.shape[1]):
    #             if j != idxs[i]:
    #                 new_mat = matrix.copy()
    #                 new_mat[i,j] = 1
    #                 new_mat[i,idxs[i]] = 0
    #                 neighbors_list += [new_mat]
    #     return neighbors_list 
开发者ID:cvxgrp,项目名称:ncvx,代码行数:31,代码来源:partition.py

示例12: tracedist

# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import trace [as 别名]
def tracedist(A, B):
    """
    Compute the trace distance between matrices A and B,
    given by:

      D = 0.5 * Tr( sqrt{ (A-B)^dagger * (A-B) } )

    Parameters
    ----------
    A, B : numpy array
        The matrices to compute the distance between.
    """
    return 0.5 * tracenorm(A - B) 
开发者ID:pyGSTio,项目名称:pyGSTi,代码行数:15,代码来源:optools.py

示例13: entanglement_fidelity

# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import trace [as 别名]
def entanglement_fidelity(A, B, mxBasis='pp'):
    """
    Returns the "entanglement" process fidelity between gate
    matrices A and B given by :

      F = Tr( sqrt{ sqrt(J(A)) * J(B) * sqrt(J(A)) } )^2

    where J(.) is the Jamiolkowski isomorphism map that maps a operation matrix
    to it's corresponding Choi Matrix.

    Parameters
    ----------
    A, B : numpy array
        The matrices to compute the fidelity between.

    mxBasis : {'std', 'gm', 'pp', 'qt'} or Basis object
        The basis of the matrices.  Allowed values are Matrix-unit (std),
        Gell-Mann (gm), Pauli-product (pp), and Qutrit (qt)
        (or a custom basis object).
    """
    d2 = A.shape[0]
    def isTP(x): return _np.isclose(x[0, 0], 1.0) and all(
        [_np.isclose(x[0, i], 0) for i in range(d2)])

    def isUnitary(x): return _np.allclose(_np.identity(d2, 'd'), _np.dot(x, x.conjugate().T))

    if isTP(A) and isTP(B) and isUnitary(B):  # then assume TP-like gates & use simpler formula
        TrLambda = _np.trace(_np.dot(A, B.conjugate().T))  # same as using _np.linalg.inv(B)
        d2 = A.shape[0]
        return TrLambda / d2

    JA = _jam.jamiolkowski_iso(A, mxBasis, mxBasis)
    JB = _jam.jamiolkowski_iso(B, mxBasis, mxBasis)
    return fidelity(JA, JB) 
开发者ID:pyGSTio,项目名称:pyGSTi,代码行数:36,代码来源:optools.py

示例14: gate_error

# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import trace [as 别名]
def gate_error(channel, target=None, require_cp=True, require_tp=False):
    r"""Return the gate error of a noisy quantum channel.

    The gate error :math:`E` is given by the average gate infidelity

    .. math::
        E(\mathcal{E}, U) = 1 - F_{\text{ave}}(\mathcal{E}, U)

    where :math:`F_{\text{ave}}(\mathcal{E}, U)` is the
    :meth:`~qiskit.quantum_info.average_gate_fidelity` of the input
    quantum *channel* :math:`\mathcal{E}` with a *target* unitary
    :math:`U`.

    Args:
        channel (QuantumChannel): noisy quantum channel.
        target (Operator or None): target unitary operator.
            If `None` target is the identity operator [Default: None].
        require_cp (bool): require channel to be completely-positive
            [Default: True].
        require_tp (bool): require channel to be trace-preserving
            [Default: False].

    Returns:
        float: The average gate error :math:`E`.

    Raises:
        QiskitError: if the channel and target do not have the same dimensions,
                     or have different input and output dimensions.
        QiskitError: if the channel and target or are not completely-positive
                     (with ``require_cp=True``) or not trace-preserving
                     (with ``require_tp=True``).
    """
    return 1 - average_gate_fidelity(
        channel, target=target, require_cp=require_cp, require_tp=require_tp) 
开发者ID:Qiskit,项目名称:qiskit-terra,代码行数:36,代码来源:measures.py

示例15: test_sdp

# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import trace [as 别名]
def test_sdp(self):
        tf.random.set_seed(5)

        n = 3
        p = 3
        C = cp.Parameter((n, n))
        A = [cp.Parameter((n, n)) for _ in range(p)]
        b = [cp.Parameter((1, 1)) for _ in range(p)]

        C_tf = tf.Variable(tf.random.normal((n, n), dtype=tf.float64))
        A_tf = [tf.Variable(tf.random.normal((n, n), dtype=tf.float64))
                for _ in range(p)]
        b_tf = [tf.Variable(tf.random.normal((1, 1), dtype=tf.float64))
                for _ in range(p)]

        X = cp.Variable((n, n), symmetric=True)
        constraints = [X >> 0]
        constraints += [
            cp.trace(A[i]@X) == b[i] for i in range(p)
        ]
        problem = cp.Problem(cp.Minimize(
            cp.trace(C @ X) - cp.log_det(X) + cp.sum_squares(X)),
            constraints)
        layer = CvxpyLayer(problem, [C] + A + b, [X])
        values = [C_tf] + A_tf + b_tf
        with tf.GradientTape() as tape:
            soln = layer(*values,
                         solver_args={'eps': 1e-10, 'max_iters': 10000})[0]
            summed = tf.math.reduce_sum(soln)
        grads = tape.gradient(summed, values)

        def f():
            problem.solve(cp.SCS, eps=1e-10, max_iters=10000)
            return np.sum(X.value)

        numgrads = numerical_grad(f, [C] + A + b, values, delta=1e-4)
        for g, ng in zip(grads, numgrads):
            np.testing.assert_allclose(g, ng, atol=1e-1) 
开发者ID:cvxgrp,项目名称:cvxpylayers,代码行数:40,代码来源:test_cvxpylayer.py


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