Verify that the Kraus operators are of the correct shape and satisfy the correct normalization.

    :param int n: Number of qubits
    :param list|tuple kraus_ops: The Kraus operators as numpy.ndarrays.
15557
def _check_kraus_ops(n, kraus_ops):
    
    for k in kraus_ops:
        if not np.shape(k) == (2 ** n, 2 ** n):
            raise ValueError(
                "Kraus operators for {0} qubits must have shape {1}x{1}: {2}".format(n, 2 ** n, k))

    kdk_sum = sum(np.transpose(k).conjugate().dot(k) for k in kraus_ops)
    if not np.allclose(kdk_sum, np.eye(2 ** n), atol=1e-3):
        raise ValueError(
            "Kraus operator not correctly normalized: sum_j K_j^*K_j == {}".format(kdk_sum))
198258
def calculate_batch_normalization_output_shapes(operator):
    '''
    
    '''
    check_input_and_output_numbers(operator, input_count_range=1, output_count_range=1)
    check_input_and_output_types(operator, good_input_types=[FloatTensorType])

    input_shape = operator.inputs[0].type.shape
    if len(input_shape) not in [2, 4]:
        raise RuntimeError('Input must be a 2-D or a 4-D tensor')

    operator.outputs[0].type.shape = copy.deepcopy(operator.inputs[0].type.shape)
439727
def spin_z_op(param, oper):
    """"""
    slaves = param['slaves']
    oper['Sz'] = np.array([spin_z(slaves, spin) for spin in range(slaves)])
    oper['Sz+1/2'] = oper['Sz'] + 0.5*np.eye(2**slaves)
    oper['sumSz2'] = oper['Sz'].sum(axis=0)**2  # because Sz is diagonal
    Sz_mat_shape = oper['Sz'].reshape(param['orbitals'], 2, 2**slaves, 2**slaves)
    oper['sumSz-sp2'] = (Sz_mat_shape.sum(axis=1)**2).sum(axis=0)
    oper['sumSz-or2'] = (Sz_mat_shape.sum(axis=0)**2).sum(axis=0)
380204
def to_matrix(self, n_qubits=-1):
        """"""
        if n_qubits == -1:
            n_qubits = self.max_n() + 1
        return sum(term.to_matrix(n_qubits) for term in self.terms)
67152
def to_kraus(self):
        
        return [k.data.toarray() for k in qt.to_kraus(self.sop)]
445126
def channel_to_kraus(chan: Channel) -> 'Kraus':
    """"""
    qubits = chan.qubits
    N = chan.qubit_nb

    choi = asarray(chan.choi())
    evals, evecs = np.linalg.eig(choi)
    evecs = np.transpose(evecs)

    assert np.allclose(evals.imag, 0.0)  # FIXME exception
    assert np.all(evals.real >= 0.0)     # FIXME exception

    values = np.sqrt(evals.real)

    ops = []
    for i in range(2**(2*N)):
        if not np.isclose(values[i], 0.0):
            mat = np.reshape(evecs[i], (2**N, 2**N))*values[i]
            g = Gate(mat, qubits)
            ops.append(g)

    return Kraus(ops)
545405
def _nbOperations(n):
    
    if n < 2:
        return 0
    else:
        n0 = (n + 2) // 3
        n02 = n0 + n // 3
        return 3 * (n02) + n0 + _nbOperations(n02)
795037
def program_unitary(program, n_qubits):
    
    umat = np.eye(2 ** n_qubits)
    for instruction in program:
        if isinstance(instruction, Gate):
            unitary = lifted_gate(gate=instruction, n_qubits=n_qubits)
            umat = unitary.dot(umat)
        else:
            raise ValueError("Can only compute program unitary for programs composed of `Gate`s")
    return umat
225628
def do_gate_matrix(self, matrix: np.ndarray,
                       qubits: Sequence[int]) -> 'AbstractQuantumSimulator':
        
        unitary = lifted_gate_matrix(matrix=matrix, qubit_inds=qubits, n_qubits=self.n_qubits)
        self.density = unitary.dot(self.density).dot(np.conj(unitary).T)
        return self
1243927
def dephasing_kraus_map(p=0.10):
    
    return [np.sqrt(1 - p) * np.eye(2), np.sqrt(p) * np.diag([1, -1])]
670662
def factoring_qaoa(n_step, num, minimizer=None, sampler=None, verbose=True):
    
    def get_nbit(n):
        m = 1
        while 2**m < n:
            m += 1
        return m

    n1_bits = get_nbit(int(num**0.5)) - 1
    n2_bits = get_nbit(int(num**0.5))

    def mk_expr(offset, n):
        expr = pauli.Expr.from_number(1)
        for i in range(n):
            expr = expr + 2**(i + 1) * q(i + offset)
        return expr

    def bitseparator(bits):
        assert len(bits) == n1_bits + n2_bits
        p = 1
        m = 1
        for b in bits[:n1_bits]:
            if b:
                p += 2**m
            m += 1
        q = 1
        m = 1
        for b in bits[n1_bits:]:
            if b:
                q += 2**m
            m += 1
        return p, q

    hamiltonian = (num - mk_expr(0, n1_bits) * mk_expr(n1_bits, n2_bits))**2
    return vqe.Vqe(vqe.QaoaAnsatz(hamiltonian, n_step), minimizer, sampler), bitseparator
436233
def disjunct_hs_zero(cls, ops, kwargs):
    
    from qnet.algebra.core.hilbert_space_algebra import TrivialSpace
    from qnet.algebra.core.operator_algebra import ZeroOperator
    hilbert_spaces = []
    for op in ops:
        try:
            hs = op.space
        except AttributeError:  # scalars
            hs = TrivialSpace
        for hs_prev in hilbert_spaces:
            if not hs.isdisjoint(hs_prev):
                return ops, kwargs
        hilbert_spaces.append(hs)
    return ZeroOperator
905717
def operators(self, ignore=0):
        
        return [k for k, v in self._operatorMap.items() if not v.flags & ignore]
1022008
def get_diagonalizing_basis(list_of_pauli_terms):
    
    qubit_ops = set(reduce(lambda x, y: x + y,
                       [list(term._ops.items()) for term in list_of_pauli_terms]))
    qubit_ops = sorted(list(qubit_ops), key=lambda x: x[0])

    return PauliTerm.from_list(list(map(lambda x: tuple(reversed(x)), qubit_ops)))
58523
def aschannel(self) -> Channel:
        """"""
        qubits = self.qubits
        N = len(qubits)
        ident = Gate(np.eye(2**N), qubits=qubits).aschannel()

        channels = [op.aschannel() @ ident for op in self.operators]
        if self.weights is not None:
            channels = [c*w for c, w in zip(channels, self.weights)]
        channel = reduce(add, channels)
        return channel
1090896
def issorted(list_, op=operator.le):
    
    return all(op(list_[ix], list_[ix + 1]) for ix in range(len(list_) - 1))
193402
def almost_identity(gate: Gate) -> bool:
    """"""
    N = gate.qubit_nb
    return np.allclose(asarray(gate.asoperator()), np.eye(2**N))