Return the Pauli sigma_Z operator acting on the given qubit
1828
def sZ(qubit: Qubit, coefficient: complex = 1.0) -> Pauli:
    """"""
    return Pauli.sigma(qubit, 'Z', coefficient)
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)))
359022
def from_pauli(pauli, coeff=1.0):
        """"""
        if pauli.is_identity or coeff == 0:
            return Term((), coeff)
        return Term((pauli,), coeff)
361022
def _one_q_state_prep(oneq_state: _OneQState):
    
    label = oneq_state.label
    if label == 'SIC':
        return _one_q_sic_prep(oneq_state.index, oneq_state.qubit)
    elif label in ['X', 'Y', 'Z']:
        return _one_q_pauli_prep(label, oneq_state.index, oneq_state.qubit)
    else:
        raise ValueError(f"Bad state label: {label}")
76587
def _one_body_mapping(a_i, a_j, threshold=0.000001):
        
        pauli_list = []
        for alpha in range(2):
            for beta in range(2):
                pauli_prod = Pauli.sgn_prod(a_i[alpha], a_j[beta])
                coeff = 1.0/4 * pauli_prod[1] * np.power(-1j, alpha) * np.power(1j, beta)
                pauli_term = [coeff, pauli_prod[0]]
                if np.absolute(pauli_term[0]) > threshold:
                    pauli_list.append(pauli_term)
        return Operator(paulis=pauli_list)
975235
def to_matrix(self, n_qubits=-1):
        """"""
        if self.is_identity:
            if n_qubits == -1:
                return self.matrix
            else:
                return reduce(np.kron, [I.matrix for _ in range(n_qubits)])
        if n_qubits == -1:
            n_qubits = _n(self) + 1
        if _n(self) == 0:
            mat = self.matrix
        else:
            mat = reduce(np.kron, [I.matrix for _ in range(_n(self))])
            mat = np.kron(mat, self.matrix)
        if n_qubits > _n(self) + 1:
            mat = reduce(np.kron, [I.matrix for _ in range(n_qubits - _n(self) - 1)], mat)
        return mat
1259628
def ghz_state(qubits: Union[int, Qubits]) -> State:
    """"""
    N, qubits = qubits_count_tuple(qubits)
    ket = np.zeros(shape=[2] * N)
    ket[(0, ) * N] = 1 / sqrt(2)
    ket[(1, ) * N] = 1 / sqrt(2)
    return State(ket, qubits)
1252699
def get_measure_probabilities(wf, qubit):
    
    n_qubits = len(wf.shape)
    all_inds = list(range(n_qubits))

    return np.einsum(np.conj(wf), all_inds,
                     wf, all_inds,
                     [int(qubit)])
1202196
def bloch_decomposition(gate: Gate) -> Circuit:
    
    if gate.qubit_nb != 1:
        raise ValueError('Expected 1-qubit gate')

    U = asarray(gate.asoperator())
    U /= np.linalg.det(U) ** (1/2)

    nx = - U[0, 1].imag
    ny = - U[0, 1].real
    nz = - U[0, 0].imag
    N = np.sqrt(nx**2 + ny**2 + nz**2)
    if N == 0:  # Identity
        nx, ny, nz = 1, 1, 1
    else:
        nx /= N
        ny /= N
        nz /= N
    sin_halftheta = N
    cos_halftheta = U[0, 0].real
    theta = 2 * np.arctan2(sin_halftheta, cos_halftheta)

    # We return a Circuit (rather than just a gate) to keep the
    # interface of decomposition routines uniform.
    return Circuit([RN(theta, nx, ny, nz, *gate.qubits)])
756248
def calc_z(bands, filling, interaction, hund_cu, name):
    """"""

    while True:
        try:
            data = np.load(name+'.npz')
            break
        except IOError:
            dopout = []
            for dop in filling:
                slsp = Spinon(slaves=2*bands, orbitals=bands, \
                             hopping=[0.5]*2*bands, populations=[dop]*2*bands)
                dopout.append(solve_loop(slsp, interaction, hund_cu)[0][0])
            np.savez(name, zeta=dopout, u_int=interaction, doping=filling, hund=hund_cu)

    return data
1046371
def simplify_pauli_sum(pauli_sum):
    """"""

    # You might want to use a defaultdict(list) here, but don't because
    # we want to do our best to preserve the order of terms.
    like_terms = OrderedDict()
    for term in pauli_sum.terms:
        key = term.operations_as_set()
        if key in like_terms:
            like_terms[key].append(term)
        else:
            like_terms[key] = [term]

    terms = []
    for term_list in like_terms.values():
        first_term = term_list[0]
        if len(term_list) == 1 and not np.isclose(first_term.coefficient, 0.0):
            terms.append(first_term)
        else:
            coeff = sum(t.coefficient for t in term_list)
            for t in term_list:
                if list(t._ops.items()) != list(first_term._ops.items()):
                    warnings.warn("The term {} will be combined with {}, but they have different "
                                  "orders of operations. This doesn't matter for QVM or "
                                  "wavefunction simulation but may be important when "
                                  "running on an actual device."
                                  .format(t.id(sort_ops=False), first_term.id(sort_ops=False)))

            if not np.isclose(coeff, 0.0):
                terms.append(term_with_coeff(term_list[0], coeff))
    return PauliSum(terms)
876339
def numpartition_qaoa(n_step, nums, minimizer=None, sampler=None):
    
    hamiltonian = pauli.Expr.zero()
    for i, x in enumerate(nums):
        hamiltonian += pauli.Z[i] * x
    hamiltonian = (hamiltonian ** 2).simplify()

    return vqe.Vqe(vqe.QaoaAnsatz(hamiltonian, n_step), minimizer, sampler)
734044
def pauli_product(*elements: Pauli) -> Pauli:
    """"""
    result_terms = []

    for terms in product(*elements):
        coeff = reduce(mul, [term[1] for term in terms])
        ops = (term[0] for term in terms)
        out = []
        key = itemgetter(0)
        for qubit, qops in groupby(heapq.merge(*ops, key=key), key=key):
            res = next(qops)[1]  # Operator: X Y Z
            for op in qops:
                pair = res + op[1]
                res, rescoeff = PAULI_PROD[pair]
                coeff *= rescoeff
            if res != 'I':
                out.append((qubit, res))

        p = Pauli(((tuple(out), coeff),))
        result_terms.append(p)

    return pauli_sum(*result_terms)
418535
def partial_trace(self, qubits: Qubits) -> 'Density':
        """"""
        vec = self.vec.partial_trace(qubits)
        return Density(vec.tensor, vec.qubits, self._memory)
226810
def expand(self):
        
        return self.element_wise(
            lambda o: o.expand() if isinstance(o, QuantumExpression) else o)
1117186
def pauli_basis(nq=1):
    
    basis = tensor_product_basis(*[
        TomographyBasis(
            gell_mann_basis(2).data[[0, 2, 3, 1]],
            [2],
            [u'𝟙', r'\sigma_x', r'\sigma_y', r'\sigma_z']
        )
    ] * nq)

    basis._name = 'pauli_basis'
    return basis
372773
def partial_trace(self, qubits: Qubits) -> 'Channel':
        """"""
        vec = self.vec.partial_trace(qubits)
        return Channel(vec.tensor, vec.qubits)