Convert to pauli operators of universal gate model.
	Requires blueqat.
8555
def pauli(qubo):
	
	from blueqat.pauli import qubo_bit
	h = 0.0
	assert all(len(q) == len(qubo) for q in qubo)
	for i in range(len(qubo)):
		h += qubo_bit(i) * qubo[i][i]
		for j in range(i + 1, len(qubo)):
			h += qubo_bit(i)*qubo_bit(j) * (qubo[i][j] + qubo[j][i])
	return h
1032023
def from_dict(d):
        
        return ISA(
            qubits=sorted([Qubit(id=int(qid),
                                 type=q.get("type", DEFAULT_QUBIT_TYPE),
                                 dead=q.get("dead", False))
                           for qid, q in d["1Q"].items()],
                          key=lambda qubit: qubit.id),
            edges=sorted([Edge(targets=[int(q) for q in eid.split('-')],
                               type=e.get("type", DEFAULT_EDGE_TYPE),
                               dead=e.get("dead", False))
                          for eid, e in d["2Q"].items()],
                         key=lambda edge: edge.targets),
        )
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
548313
def objective_fun(theta, hamiltonian=None,
                  quantum_resource=QVMConnection(sync_endpoint='http://localhost:5000')):
    
    if hamiltonian is None:
        # Hamiltonian is Identity
        return 1.0

    if isinstance(hamiltonian, PauliSum):
        result = estimate_locally_commuting_operator(ucc_circuit(theta), hamiltonian,
                                                     1.0E-6, quantum_resource=quantum_resource)
        result = result[0][0].real  # first output is expected value, second is variance, third is shots
    elif isinstance(hamiltonian, np.ndarray) and isinstance(quantum_resource, QVMConnection):
        wf = quantum_resource.wavefunction(ucc_circuit(theta))
        wf = wf.amplitudes.reshape((-1, 1))
        result = np.conj(wf).T.dot(hamiltonian).dot(wf)[0, 0].real
        print(result)
    else:
        raise TypeError("type of hamiltonian or qvm is unrecognized")

    return result
572297
def almost_hermitian(gate: Gate) -> bool:
    """"""
    return np.allclose(asarray(gate.asoperator()),
                       asarray(gate.H.asoperator()))
1143565
def asgate(self) -> Gate:
        
        gate = identity_gate(self.qubits)
        for elem in self.elements:
            gate = elem.asgate() @ gate
        return gate
579159
def crt(self, mp, mq):
        
        u = (mq - mp) * self.p_inverse % self.q
        return mp + (u * self.p)
1325392
def num_qubits(self) -> Optional[int]:
        """"""
        if not self:
            return None
        any_gate = next(iter(self))
        return any_gate.num_qubits()
982409
def _non_local_part(q0: ops.Qid,
                    q1: ops.Qid,
                    interaction_coefficients: Tuple[float, float, float],
                    allow_partial_czs: bool,
                    atol: float = 1e-8):
    """"""

    x, y, z = interaction_coefficients

    if (allow_partial_czs or
        all(_is_trivial_angle(e, atol) for e in [x, y, z])):
        return [
            _parity_interaction(q0, q1, x, atol, ops.Y**-0.5),
            _parity_interaction(q0, q1, y, atol, ops.X**0.5),
            _parity_interaction(q0, q1, z, atol)
        ]

    if abs(z) >= atol:
        return _xx_yy_zz_interaction_via_full_czs(q0, q1, x, y, z)

    if y >= atol:
        return _xx_yy_interaction_via_full_czs(q0, q1, x, y)

    return _xx_interaction_via_full_czs(q0, q1, x)
1197745
def get_rotation_program(pauli_term: PauliTerm) -> Program:
    
    meas_basis_change = Program()
    for index, gate in pauli_term:
        if gate == 'X':
            meas_basis_change.inst(RY(-np.pi / 2, index))
        elif gate == 'Y':
            meas_basis_change.inst(RX(np.pi / 2, index))
        elif gate == 'Z':
            pass
        else:
            raise ValueError()

    return meas_basis_change
588645
def isa_from_graph(graph: nx.Graph, oneq_type='Xhalves', twoq_type='CZ') -> ISA:
    
    all_qubits = list(range(max(graph.nodes) + 1))
    qubits = [Qubit(i, type=oneq_type, dead=i not in graph.nodes) for i in all_qubits]
    edges = [Edge(sorted((a, b)), type=twoq_type, dead=False) for a, b in graph.edges]
    return ISA(qubits, edges)
1257079
def expect(qubits, meas):
    ""
    result = {}
    i = np.arange(len(qubits))
    meas = tuple(meas)

    def to_mask(n):
        return reduce(lambda acc, im: acc | (n & (1 << im[0])) << (im[1] - im[0]), enumerate(meas), 0)

    def to_key(k):
        return tuple(1 if k & (1 << i) else 0 for i in meas)

    mask = reduce(lambda acc, v: acc | (1 << v), meas, 0)

    cnt = defaultdict(float)
    for i, v in enumerate(qubits):
        p = v.real ** 2 + v.imag ** 2
        if p != 0.0:
            cnt[i & mask] += p
    return {to_key(k): v for k, v in cnt.items()}
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}")
88682
def identity_gate(qubits: Union[int, Qubits]) -> Gate:
    """"""
    _, qubits = qubits_count_tuple(qubits)
    return I(*qubits)
994813
def fermionic_constraints(a):
    
    substitutions = {}
    for i, ai in enumerate(a):
        substitutions[ai ** 2] = 0
        substitutions[Dagger(ai) ** 2] = 0
        substitutions[ai * Dagger(ai)] = 1.0 - Dagger(ai) * ai
        for aj in a[i+1:]:
            # substitutions[ai*Dagger(aj)] = -Dagger(ai)*aj
            substitutions[ai*Dagger(aj)] = -Dagger(aj)*ai
            substitutions[Dagger(ai)*aj] = -aj*Dagger(ai)
            substitutions[ai*aj] = -aj*ai
            substitutions[Dagger(ai) * Dagger(aj)] = - Dagger(aj) * Dagger(ai)

    return substitutions
979520
def kronecker_decomposition(gate: Gate) -> Circuit:
    
    # An alternative approach would be to take partial traces, but
    # this approach appears to be more robust.

    if gate.qubit_nb != 2:
        raise ValueError('Expected 2-qubit gate')

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

    R = np.stack([U[0:2, 0:2].reshape(4),
                  U[0:2, 2:4].reshape(4),
                  U[2:4, 0:2].reshape(4),
                  U[2:4, 2:4].reshape(4)])
    u, s, vh = np.linalg.svd(R)
    v = vh.transpose()
    A = (np.sqrt(s[0]) * u[:, 0]).reshape(2, 2)
    B = (np.sqrt(s[0]) * v[:, 0]).reshape(2, 2)

    q0, q1 = gate.qubits
    g0 = Gate(A, qubits=[q0])
    g1 = Gate(B, qubits=[q1])

    if not gates_close(gate, Circuit([g0, g1]).asgate()):
        raise ValueError("Gate cannot be decomposed into two 1-qubit gates")

    circ = Circuit()
    circ += zyz_decomposition(g0)
    circ += zyz_decomposition(g1)

    assert gates_close(gate, circ.asgate())  # Sanity check

    return circ
817536
def sX(qubit: Qubit, coefficient: complex = 1.0) -> Pauli:
    """"""
    return Pauli.sigma(qubit, 'X', coefficient)