Convert a QuantumFlow circuit to a pyQuil program
358717
def circuit_to_pyquil(circuit: Circuit) -> pyquil.Program:
    """"""
    prog = pyquil.Program()

    for elem in circuit.elements:
        if isinstance(elem, Gate) and elem.name in QUIL_GATES:
            params = list(elem.params.values()) if elem.params else []
            prog.gate(elem.name, params, elem.qubits)
        elif isinstance(elem, Measure):
            prog.measure(elem.qubit, elem.cbit)
        else:
            # FIXME: more informative error message
            raise ValueError('Cannot convert operation to pyquil')

    return prog
1243227
def do_gate_matrix(self, matrix: np.ndarray,
                       qubits: Sequence[int]) -> 'AbstractQuantumSimulator':
        
        # e.g. 2-qubit matrix is 4x4; turns into (2,2,2,2) tensor.
        tensor = np.reshape(matrix, (2,) * len(qubits) * 2)

        # Note to developers: you can use either einsum- or tensordot- based functions.
        # tensordot seems a little faster, but feel free to experiment.
        # self.wf = targeted_einsum(gate=gate_matrix, wf=self.wf, wf_target_inds=qubits)
        self.wf = targeted_tensordot(gate=tensor, wf=self.wf, wf_target_inds=qubits)
        return self
665377
def flow2magang(flow, dtype=uint8):
    
    fx, fy = flow[..., 0], flow[..., 1]
    return hypot(fx, fy).astype(dtype), arctan2(fy, fx) + pi
663062
def QCapsulate(self, widget, name, blocking = False, nude = False):
        

        class QuickWindow(QtWidgets.QMainWindow):

            class Signals(QtCore.QObject):
                close = QtCore.Signal()
                show  = QtCore.Signal()

            def __init__(self, blocking = False, parent = None, nude = False):
                super().__init__(parent)
                self.propagate = True # send signals or not
                self.setStyleSheet(style.main_gui)
                if (blocking):
                    self.setWindowModality(QtCore.Qt.ApplicationModal)
                if (nude):
                    # http://doc.qt.io/qt-5/qt.html#WindowType-enum
                    # TODO: create a widget for a proper splashscreen (omitting X11 and centering manually)
                    # self.setWindowFlags(QtCore.Qt.Popup) # Qt 5.9+ : setFlags()
                    # self.setWindowFlags(QtCore.Qt.SplashScreen | QtCore.Qt.WindowStaysOnTopHint)
                    self.setWindowFlags(QtCore.Qt.Dialog)
                self.signals = self.Signals()
                

            def closeEvent(self, e):
                if (self.propagate):
                    self.signals.close.emit()
                e.accept()
                
            def showEvent(self, e):
                if (self.propagate):
                    self.signals.show.emit()
                e.accept()
                
            def setPropagate(self):
                self.propagate = True
                
            def unSetPropagate(self):
                self.propagate = False
                

        win = QuickWindow(blocking = blocking, nude = nude)
        win.setCentralWidget(widget)
        win.setLayout(QtWidgets.QHBoxLayout())
        win.setWindowTitle(name)
        return win
101941
def run(self, ket: State) -> State:
        """"""
        qubits = self.qubits
        indices = [ket.qubits.index(q) for q in qubits]
        tensor = bk.tensormul(self.tensor, ket.tensor, indices)
        return State(tensor, ket.qubits, ket.memory)
235382
def createrawtransaction(self, inputs, outputs):
        """"""
        if not isinstance(outputs, dict):
            raise TypeError("outputs variable must be a dictionary")
        if not isinstance(inputs, list):
            raise TypeError("inputs variable must be a list")
        return self.req("createrawtransaction", [inputs, outputs])
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
1069438
def copy(self, copy_backends=True, copy_default_backend=True,
             copy_cache=None, copy_history=None):
        
        copied = Circuit(self.n_qubits, self.ops.copy())
        if copy_backends:
            copied._backends = {k: v.copy() for k, v in self._backends.items()}
        if copy_default_backend:
            copied._default_backend = self._default_backend

        # Warn for deprecated options
        if copy_cache is not None:
            warnings.warn("copy_cache is deprecated. Use copy_backends instead.",
                          DeprecationWarning)
        if copy_history is not None:
            warnings.warn("copy_history is deprecated.", DeprecationWarning)

        return copied
593493
def _run(
        self,
        circuit: circuits.Circuit,
        param_resolver: study.ParamResolver,
        repetitions: int) -> Dict[str, List[np.ndarray]]:
        """"""
        param_resolver = param_resolver or study.ParamResolver({})
        resolved_circuit = protocols.resolve_parameters(circuit, param_resolver)
        def measure_or_mixture(op):
            return protocols.is_measurement(op) or protocols.has_mixture(op)
        if circuit.are_all_matches_terminal(measure_or_mixture):
            return self._run_sweep_sample(resolved_circuit, repetitions)
        else:
            return self._run_sweep_repeat(resolved_circuit, repetitions)
92956
def make_oracle(input_qubits,
                output_qubit,
                secret_factor_bits,
                secret_bias_bit):
    """"""

    if secret_bias_bit:
        yield cirq.X(output_qubit)

    for qubit, bit in zip(input_qubits, secret_factor_bits):
        if bit:
            yield cirq.CNOT(qubit, output_qubit)
954403
def reset(self):
        
        self.wf.fill(0)
        self.wf[(0,) * self.n_qubits] = complex(1.0, 0)
        return self
195620
def load(self, binary: pyquil.Program) -> 'QuantumFlowQVM':
        

        assert self.status in ['connected', 'done']
        prog = quil_to_program(str(binary))

        self._prog = prog
        self.program = binary
        self.status = 'loaded'

        return self
858392
def _run(
        self,
        circuit: circuits.Circuit,
        param_resolver: study.ParamResolver,
        repetitions: int,
    ) -> Dict[str, List[np.ndarray]]:
        """"""

        circuit = protocols.resolve_parameters(circuit, param_resolver)
        _verify_xmon_circuit(circuit)

        # Delegate to appropriate method based on contents.
        if circuit.are_all_measurements_terminal():
            return self._run_sweep_sample(circuit, repetitions)
        else:
            return self._run_sweep_repeat(circuit, repetitions)
272641
def zyz_decomposition(gate: Gate) -> Circuit:
    
    if gate.qubit_nb != 1:
        raise ValueError('Expected 1-qubit gate')

    q, = gate.qubits

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

    if abs(U[0, 0]) > abs(U[1, 0]):
        theta1 = 2 * np.arccos(min(abs(U[0, 0]), 1))
    else:
        theta1 = 2 * np.arcsin(min(abs(U[1, 0]), 1))

    cos_halftheta1 = np.cos(theta1/2)
    if not np.isclose(cos_halftheta1, 0.0):
        phase = U[1, 1] / cos_halftheta1
        theta0_plus_theta2 = 2 * np.arctan2(np.imag(phase), np.real(phase))
    else:
        theta0_plus_theta2 = 0.0

    sin_halftheta1 = np.sin(theta1/2)
    if not np.isclose(sin_halftheta1, 0.0):
        phase = U[1, 0] / sin_halftheta1
        theta0_sub_theta2 = 2 * np.arctan2(np.imag(phase), np.real(phase))
    else:
        theta0_sub_theta2 = 0.0

    theta0 = (theta0_plus_theta2 + theta0_sub_theta2) / 2
    theta2 = (theta0_plus_theta2 - theta0_sub_theta2) / 2

    t0 = theta0/np.pi
    t1 = theta1/np.pi
    t2 = theta2/np.pi

    circ1 = Circuit()
    circ1 += TZ(t2, q)
    circ1 += TY(t1, q)
    circ1 += TZ(t0, q)

    return circ1
579980
def _q_iteration(self, Q, Bpp_solver, Vm, Va, pq):
        
        dVm = -Bpp_solver.solve(Q)

        # Update voltage.
        Vm[pq] = Vm[pq] + dVm
        V = Vm * exp(1j * Va)

        return V, Vm, Va
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
472599
def _run_gates(self, gates, n_qubits, ctx):
        """"""
        for gate in gates:
            action = self._get_action(gate)
            if action is not None:
                ctx = action(gate, ctx)
            else:
                ctx = self._run_gates(gate.fallback(n_qubits), n_qubits, ctx)
        return ctx