Esempio n. 1
0
    def test_execute_remote(self, QE_TOKEN, QE_URL):
        """Test Execute remote.

        If all correct some should exists.
        """
        provider = IBMQProvider(QE_TOKEN, QE_URL)
        backend = provider.available_backends({'simulator': True})[0]
        qubit_reg = qiskit.QuantumRegister(2)
        clbit_reg = qiskit.ClassicalRegister(2)
        qc = qiskit.QuantumCircuit(qubit_reg, clbit_reg)
        qc.h(qubit_reg[0])
        qc.cx(qubit_reg[0], qubit_reg[1])
        qc.measure(qubit_reg, clbit_reg)

        job = execute(qc, backend)
        results = job.result()
        self.assertIsInstance(results, Result)
Esempio n. 2
0
def operador_controlado(V):
    '''
    Lab2 - questão 2
    :param V: matriz unitária 2 x 2
    :return: circuito quântico com dois qubits aplicando o
             o operador V controlado.
    '''
    #Decomponsição de V

    x00 = np.angle(V[0][0])
    x01 = np.angle(V[0][1])
    x10 = np.angle(V[1][0])
    x11 = np.angle(V[1][1])

    A = np.array([[1, -0.5, -0.5], [1, -0.5, 0.5], [1, 0.5, -0.5]])
    B = np.array([x00, x01 + np.pi, x10])
    X = np.linalg.inv(A).dot(B)    

    alpha = X[0]
    beta = X[1]
    gamma = np.arccos(np.abs(V[0][0]))*2
    delta = X[2]

    #-------Matrizes------#
    #A = Rz(beta)*Ry(gamma/2)
    #B = Ry(-1*gamma/2)*Rz(-1*(delta + beta)/2)
    #C = Rz((delta-beta)/2)

    #-------Circuito------#
    circuito = qiskit.QuantumCircuit(2)
    #C
    circuito.rz((delta-beta)/2, 1)
    #cx
    circuito.cx(0,1)
    #B
    circuito.rz(-1*(delta + beta)/2, 1)
    circuito.ry(-1*gamma/2, 1)
    #cx
    circuito.cx(0,1)
    #A
    circuito.ry(gamma/2, 1)
    circuito.rz(beta, 1)
    #Operador [[1,0],[0,e**(1j*alpha)]] -> U3=0,0,alpha
    circuito.u3(theta=0, phi=0, lam=alpha, qubit=0)
    circuito.draw()
    return circuito
Esempio n. 3
0
    def test_compile_run_remote(self, QE_TOKEN, QE_URL, hub=None, group=None, project=None):
        """Test Compiler and run remote.

        If all correct some should exists.
        """
        provider = IBMQProvider(QE_TOKEN, QE_URL, hub, group, project)
        backend = provider.available_backends({'simulator': True})[0]
        qubit_reg = qiskit.QuantumRegister(2, name='q')
        clbit_reg = qiskit.ClassicalRegister(2, name='c')
        qc = qiskit.QuantumCircuit(qubit_reg, clbit_reg, name="bell")
        qc.h(qubit_reg[0])
        qc.cx(qubit_reg[0], qubit_reg[1])
        qc.measure(qubit_reg, clbit_reg)
        qobj = qiskit._compiler.compile(qc, backend)
        result = backend.run(qiskit.QuantumJob(qobj, backend=backend,
                                               preformatted=True)).result()
        self.assertIsInstance(result, Result)
Esempio n. 4
0
    def test_hellinger_fidelity_same(self):
        """Test hellinger fidelity is one for same dist."""
        qc = qiskit.QuantumCircuit(5, 5)
        qc.h(2)
        qc.cx(2, 1)
        qc.cx(2, 3)
        qc.cx(3, 4)
        qc.cx(1, 0)
        qc.measure(range(5), range(5))

        sim = BasicAer.get_backend('qasm_simulator')

        res = qiskit.execute(qc, sim).result()

        ans = hellinger_fidelity(res.get_counts(), res.get_counts())

        self.assertEqual(ans, 1.0)
Esempio n. 5
0
def bernstein_vazirani_oracle(n, f_str):
    qc = qiskit.QuantumCircuit(n + 1)

    qc.x(n)
    qc.h(n)

    for i, bit in enumerate(f_str):
        if bit == '1':
            qc.cx(n - i - 1, n)

    qc.h(n)
    qc.x(n)

    print(qc.draw())
    gate = qc.to_gate()
    gate.name = "BV_O"
    return gate
Esempio n. 6
0
def _GHZ_3qubits_6_params_cx1(params, barriers=False):
    """ Returns function handle for 6 param ghz state 1 swap"""
    logical_qubits = qk.QuantumRegister(3, 'logicals')
    c = qk.QuantumCircuit(logical_qubits)
    c.ry(params[2], 0)
    c.rx(params[1], 1)
    c.rx(params[0], 2)
    c.swap(0, 2)
    if barriers: c.barrier()
    c.cx(0, 2)
    c.cx(1, 2)
    if barriers: c.barrier()
    c.rx(params[3], 0)
    c.rx(params[4], 1)
    c.ry(params[5], 2)
    if barriers: c.barrier()
    return c
Esempio n. 7
0
def circuit_2():
    circuit = q.QuantumCircuit(2)  # 2 quibits
    # h - superposion of qbit
    circuit.h(0)
    circuit.cx(0, 1)
    circuit.measure_all()
    IBMQ.load_account()
    access_provider = IBMQ.get_provider()

    backend = access_provider.get_backend("ibmq_qasm_simulator")
    job = q.execute(circuit, backend=backend, shots=500)
    job_monitor(job)
    result = job.result()
    counts = result.get_counts(circuit)

    plot_histogram([counts])
    plt.show()
Esempio n. 8
0
def export_to_qiskit(circuit: _circuit.Circuit) -> qiskit.QuantumCircuit:
    q_circuit = qiskit.QuantumCircuit(circuit.n_qubits)
    custom_names = {
        gate_def.gate_name for gate_def in circuit.collect_custom_gate_definitions()
    }
    q_triplets = [
        _export_gate_to_qiskit(
            gate_op.gate,
            applied_qubit_indices=gate_op.qubit_indices,
            n_qubits_in_circuit=circuit.n_qubits,
            custom_names=custom_names,
        )
        for gate_op in circuit.operations
    ]
    for q_gate, q_qubits, q_clbits in q_triplets:
        q_circuit.append(q_gate, q_qubits, q_clbits)
    return q_circuit
Esempio n. 9
0
    def test_execute_in_aer(self):
        """Test executing a circuit in an Aer simulator"""
        qr = qiskit.QuantumRegister(1)
        cr = qiskit.ClassicalRegister(1)
        circuit = qiskit.QuantumCircuit(qr, cr)
        circuit.h(qr[0])
        circuit.measure(qr, cr)

        backend = qiskit.Aer.get_backend('qasm_simulator')
        shots = 2000
        results = qiskit.execute(circuit, backend, shots=shots).result()
        self.assertDictAlmostEqual({
            '0': 1000,
            '1': 1000
        },
                                   results.get_counts(),
                                   delta=100)
def qft(circuit, qregister):
    """QFT. 

    Parameters
    ------------------------------------------------
    circuit(qiskit.QuantumCircuit): Quantum Circuit.
    qregister(qiskit.QuantumRegister): Quantum register for the rotation.

    Output
    ------------------------------------------------
    circuit(qiskit.QuantumCircuit): Quantum Circuit with
                                    qft.
    
    """
    qft_circuit = _qft(qsk.QuantumCircuit(qregister, name='QFT'), qregister)
    circuit.append(qft_circuit, qregister)
    return circuit
Esempio n. 11
0
    def test_statevector(self):
        """statevector from a bell state"""
        qr = qiskit.QuantumRegister(2)
        circuit = qiskit.QuantumCircuit(qr)
        circuit.h(qr[0])
        circuit.cx(qr[0], qr[1])

        sim_cpp = LegacySimulators.get_backend('statevector_simulator')
        sim_py = Simulators.get_backend('statevector_simulator')
        result_cpp = execute(circuit, sim_cpp).result()
        result_py = execute(circuit, sim_py).result()
        statevector_cpp = result_cpp.get_statevector()
        statevector_py = result_py.get_statevector()
        fidelity = state_fidelity(statevector_cpp, statevector_py)
        self.assertGreater(
            fidelity, self._desired_fidelity,
            "cpp vs. py statevector has low fidelity{0:.2g}.".format(fidelity))
Esempio n. 12
0
def test_execute_with_pec_qiskit_trivial_decomposition():
    qreg = qiskit.QuantumRegister(1)
    circuit = qiskit.QuantumCircuit(qreg)
    _ = circuit.x(qreg)
    rep = OperationRepresentation(
        circuit, basis_expansion={NoisyOperation(circuit): 1.0})
    unmitigated = serial_executor(circuit)

    mitigated = execute_with_pec(
        circuit,
        serial_executor,
        representations=[rep],
        num_samples=10,
        random_state=1,
    )

    assert np.isclose(unmitigated, mitigated)
Esempio n. 13
0
def test_qiskit_measurement_order_is_preserved_single_register(order):
    """Tests measurement order is preserved when folding, i.e., the dictionary
    of counts is the same as the original circuit on a noiseless simulator.
    """
    qreg, creg = (
        qiskit.QuantumRegister(len(order)),
        qiskit.ClassicalRegister(len(order)),
    )
    circuit = qiskit.QuantumCircuit(qreg, creg)

    circuit.x(qreg[0])
    for i in order:
        circuit.measure(qreg[i], creg[i])

    folded = scaling.fold_gates_at_random(circuit, scale_factor=1.0)

    assert get_counts(folded) == get_counts(circuit)
Esempio n. 14
0
    def test_execute_remote(self, QE_TOKEN, QE_URL):
        """Test Execute remote.

        If all correct some should exists.
        """
        provider = IBMQProvider(QE_TOKEN, QE_URL)
        my_backend = provider.get_backend('ibmqx_qasm_simulator')

        qubit_reg = qiskit.QuantumRegister(2)
        clbit_reg = qiskit.ClassicalRegister(2)
        qc = qiskit.QuantumCircuit(qubit_reg, clbit_reg)
        qc.h(qubit_reg[0])
        qc.cx(qubit_reg[0], qubit_reg[1])
        qc.measure(qubit_reg, clbit_reg)

        results = qiskit._compiler.execute(qc, my_backend)
        self.assertIsInstance(results, Result)
Esempio n. 15
0
def ampcal_cx_circuits(max_reps, qubits, control_qubits):
    """
    Generates circuit for measuring the amplitude error of
    the cx gate

    The cx gate is repeatedly applied
    and we look at the population of the target
    qubit in the xy axis (amplitude erorr amplification sequence)

    X(control)-X90(target)-(CX)^n

    Note: the circuit may not behave as intended if the
    target-control pairs are not in the coupling map

    Args:
       max_reps: the maximum number of repetitions. Circuits will increment
       by 1 rep up to max_rep
       qubits (list of integers): indices of the target qubits
       to perform the calibration on
       contorl_qubits (list of integers): indices of the control qubits
       to perform the calibration on
    Returns:
       A list of QuantumCircuit
       xdata: a list of gate repetitions
    """
    xdata = np.arange(max_reps)

    qr = qiskit.QuantumRegister(max([max(qubits), max(control_qubits)]) + 1)
    cr = qiskit.ClassicalRegister(len(qubits))

    circuits = []

    for circ_index, circ_length in enumerate(xdata):
        circ = qiskit.QuantumCircuit(qr, cr)
        circ.name = 'ampcalcxcircuit_' + str(circ_index) + '_0'
        for qind, qubit in enumerate(qubits):
            circ.x(qr[control_qubits[qind]])
            circ.u2(-np.pi / 2, np.pi / 2, qr[qubit])  # X90p
            for _ in range(circ_length):
                circ.cx(qr[control_qubits[qind]], qr[qubit])

        for qind, qubit in enumerate(qubits):
            circ.measure(qr[qubit], cr[qind])
        circuits.append(circ)

    return circuits, xdata
Esempio n. 16
0
    def test_execute(self):
        """Test Execute.

        If all correct some should exists.
        """
        my_backend = QasmSimulator()

        qubit_reg = qiskit.QuantumRegister(2)
        clbit_reg = qiskit.ClassicalRegister(2)
        qc = qiskit.QuantumCircuit(qubit_reg, clbit_reg)
        qc.h(qubit_reg[0])
        qc.cx(qubit_reg[0], qubit_reg[1])
        qc.measure(qubit_reg, clbit_reg)

        results = qiskit._compiler.execute(qc, my_backend)

        self.assertIsInstance(results, Result)
Esempio n. 17
0
    def test_compile_run_remote(self, QE_TOKEN, QE_URL):
        """Test Compiler and run remote.

        If all correct some should exists.
        """
        provider = IBMQProvider(QE_TOKEN, QE_URL)
        my_backend = provider.get_backend('ibmqx_qasm_simulator')
        qubit_reg = qiskit.QuantumRegister(2, name='q')
        clbit_reg = qiskit.ClassicalRegister(2, name='c')
        qc = qiskit.QuantumCircuit(qubit_reg, clbit_reg, name="bell")
        qc.h(qubit_reg[0])
        qc.cx(qubit_reg[0], qubit_reg[1])
        qc.measure(qubit_reg, clbit_reg)

        qobj = qiskit._compiler.compile(qc, my_backend)
        result = my_backend.run(qiskit.QuantumJob(qobj, preformatted=True))
        self.assertIsInstance(result, Result)
Esempio n. 18
0
    def test_compile_run(self):
        """Test Compiler and run.

        If all correct some should exists.
        """
        backend = get_backend('local_qasm_simulator')

        qubit_reg = qiskit.QuantumRegister(2, name='q')
        clbit_reg = qiskit.ClassicalRegister(2, name='c')
        qc = qiskit.QuantumCircuit(qubit_reg, clbit_reg, name="bell")
        qc.h(qubit_reg[0])
        qc.cx(qubit_reg[0], qubit_reg[1])
        qc.measure(qubit_reg, clbit_reg)

        qobj = transpiler.compile(qc, backend)
        result = backend.run(qobj).result()
        self.assertIsInstance(result, Result)
    def test_statevector(self):
        """statevector from a bell state"""
        q = qk.QuantumRegister(2)
        circ = qk.QuantumCircuit(q)
        circ.h(q[0])
        circ.cx(q[0], q[1])

        sim_cpp = 'local_statevector_simulator_cpp'
        sim_py = 'local_statevector_simulator_py'
        result_cpp = execute(circ, sim_cpp)
        result_py = execute(circ, sim_py)
        statevector_cpp = result_cpp.get_statevector()
        statevector_py = result_py.get_statevector()
        fidelity = state_fidelity(statevector_cpp, statevector_py)
        self.assertGreater(
            fidelity, self._desired_fidelity,
            "cpp vs. py statevector has low fidelity{0:.2g}.".format(fidelity))
Esempio n. 20
0
def local_sim():
    qc = qk.QuantumCircuit(3, 3)

    # q[0]: qubit to be teleported. Given to Alice after the secret unitary is
    #    applied.
    # q[1]: Alice's second qubit. Her piece of Bell pair.
    # q[2]: Bob's qubit. destination of the teleportation.

    # apply the secret unitary
    apply_secret_unitary(secret_unitary, qc.qubits[0], qc, dagger=False)
    qc.barrier()

    # generate the entangled pair
    qc.h(1)
    qc.cx(1, 2)
    qc.barrier()

    # apply the teleportation protocol
    qc.cx(0, 1)
    qc.h(0)
    qc.measure(0, 0)
    qc.measure(1, 1)

    # call Bob the result and Bob apply the corresponding gates
    qc.cx(1, 2)
    qc.cz(0, 2)
    qc.barrier()

    # If the teleportation works, then q[2] = secret_unitary |0>. Therefore
    # we can apply its inverse to recover q[2] = |0>
    apply_secret_unitary(secret_unitary, qc.qubits[2], qc, dagger=True)
    qc.measure(2, 2)

    # save circuit image
    qc.draw(output='mpl').savefig('teleportation_circuit_local.png')

    # local simulation

    backend = qk.Aer.get_backend('qasm_simulator')
    job_sim = qk.execute(qc, backend)
    sim_result = job_sim.result()

    measurement_result = sim_result.get_counts(qc)
    print(measurement_result)
    qk.visualization.plot_histogram(measurement_result).savefig(
        'transportation_local_sim.png')
Esempio n. 21
0
    def __init__(self,
                 n_qubits,
                 init_state,
                 n_layers,
                 backend,
                 shots=None,
                 savefig=False):
        '''
        Parameters:
            init_state  : state to initialize the quantum circuit
            n_layers    : number of layers of identity block to be used
            backend     : to be used for running the simulation
            savefig     : to save the metrics collected during training
            shots       : if sometime we want to collect the measurement
        '''
        #First of all lets define the circuit
        assert n_qubits == 4, "Qubit should be 4 as per the problem"
        self.n_qubits = n_qubits
        self.circuit = qiskit.QuantumCircuit(self.n_qubits)

        #Initialzing the circuit with the given random state
        self.init_state = init_state
        self.init_state_vec = self._encode_input_state()
        self.circuit.initialize(self.init_state_vec,
                                list(range(self.n_qubits)))

        #Now lets apply the even and odd blocks
        self.n_layers = n_layers
        self.sym_thetas = {}
        for layer_num in range(n_layers):
            self.circuit = IdentityBlock(self.n_qubits, self.circuit,
                                         layer_num, self.sym_thetas).circuit
        #Collecting the names of each thetas
        self.thetas_name = list(self.sym_thetas.keys())

        #Finally lets measure the circuit
        #self.circuit.measure_all()

        #Initialiing the backend to be used
        self.backend = backend
        self.shots = shots

        #Initializing the variables which will hold our metrics for viz
        self.all_cost = []  #The loss value at each epoch
        self.step = 0  #The epoch number
        self.savefig = savefig
def test_transform_cregs(nbits, with_ops, measure):
    qreg = qiskit.QuantumRegister(nbits)
    creg = qiskit.ClassicalRegister(nbits)
    circ = qiskit.QuantumCircuit(qreg, creg)
    if with_ops:
        circ.h(qreg)
    if measure:
        circ.measure(qreg, creg)

    orig = circ.copy()

    new_cregs = [qiskit.ClassicalRegister(1) for _ in range(nbits)]
    _transform_registers(circ, new_cregs=new_cregs)

    assert circ.cregs == new_cregs
    assert circ.qregs == orig.qregs
    assert _equal(from_qiskit(circ), from_qiskit(orig))
Esempio n. 23
0
    def test_compile_run(self):
        """Test Compiler and run.

        If all correct some should exists.
        """
        my_backend = QasmSimulator()

        qubit_reg = qiskit.QuantumRegister(2, name='q')
        clbit_reg = qiskit.ClassicalRegister(2, name='c')
        qc = qiskit.QuantumCircuit(qubit_reg, clbit_reg, name="bell")
        qc.h(qubit_reg[0])
        qc.cx(qubit_reg[0], qubit_reg[1])
        qc.measure(qubit_reg, clbit_reg)

        qobj = qiskit._compiler.compile(qc, my_backend)
        result = my_backend.run(qiskit.QuantumJob(qobj, preformatted=True))
        self.assertIsInstance(result, Result)
    def __init__(self, number_of_qubits, number_of_shots=8192):
        """
        :param number_of_qubits: The amount of qubits involved in the Quantum Process you want to do QPT on.
        :param number_of_shots: The number of shots to do for every individual experiment, default is 8192.

        In this function the tools that are being used throughout the class are being initialized.
        """
        self.n = number_of_qubits
        self.backend = Aer.get_backend('qasm_simulator')
        self.shots = number_of_shots

        # Setting up some tools which are used for the calculations
        self.cardinal_states = [
            np.array([1, 0]),
            np.array([0, 1]), 1 / np.sqrt(2) * np.array([1, 1]),
            1 / np.sqrt(2) * np.array([1, -1]),
            1 / np.sqrt(2) * np.array([1, complex(0, 1)]),
            1 / np.sqrt(2) * np.array([1, complex(0, -1)])
        ]
        self.directions = ['I', 'X', 'Y', 'Z']
        self.pauli_vector_string = self.compute_pauli_vector_string(
        )  # Contains the combined direction labels

        # Creating initial arrays so they are ready for computations
        self.qubit_inputs = np.zeros(
            (len(self.cardinal_states)**self.n, self.n, 2), dtype=np.complex_)
        for state_index in range(np.shape(self.qubit_inputs)[0]):
            for qubit_index in range(np.shape(self.qubit_inputs)[1]):
                self.qubit_inputs[state_index, qubit_index, :] = np.array(
                    [0, 0])  # Init. with an empty bloch vector

        self.pauli_input_matrix = np.zeros(
            (len(self.directions)**self.n, len(self.cardinal_states)**self.n))
        self.pauli_output_matrix = np.zeros(
            (len(self.directions)**self.n, len(self.cardinal_states)**self.n))
        self.theoretical_output_matrix = np.zeros(
            (len(self.directions)**self.n, len(self.cardinal_states)**self.n))
        self.pauli_transfer_matrix = np.zeros((4**self.n, 4**self.n))
        self.theoretical_transfer_matrix = np.zeros((4**self.n, 4**self.n))

        # Initializing the circuit
        self.qubits = qk.QuantumRegister(self.n)
        self.classical_bits = qk.ClassicalRegister(self.n)
        self.circuit = qk.QuantumCircuit(
            self.qubits, self.classical_bits)  # Changes per experiment
    def random_circuit(self, width=3, depth=3, max_operands=3):
        """Generate random circuit of arbitrary size.
        Note: the depth is the layers of independent operation. true depth
        in the image may be more for visualization purposes, if gates overlap.

        Args:
            width (int): number of quantum wires
            depth (int): layers of operations
            max_operands (int): maximum operands of each gate

        Returns:
            QuantumCircuit: constructed circuit
        """
        qr = qiskit.QuantumRegister(width, "q")
        qc = qiskit.QuantumCircuit(qr)

        one_q_ops = "iden,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz"
        two_q_ops = "cx,cy,cz,ch,crz,cu1,cu3,swap"
        three_q_ops = "ccx"

        # apply arbitrary random operations at every depth
        for _ in range(depth):
            # choose either 1, 2, or 3 qubits for the operation
            remaining_qubits = list(range(width))
            while remaining_qubits:
                max_possible_operands = min(len(remaining_qubits), max_operands)
                num_operands = random.choice(range(max_possible_operands)) + 1
                operands = random.sample(remaining_qubits, num_operands)
                remaining_qubits = [q for q in remaining_qubits if q not in operands]
                if num_operands == 1:
                    operation = random.choice(one_q_ops.split(','))
                elif num_operands == 2:
                    operation = random.choice(two_q_ops.split(','))
                elif num_operands == 3:
                    operation = random.choice(three_q_ops.split(','))
                # every gate is defined as a method of the QuantumCircuit class
                # the code below is so we can call a gate by its name
                gate = getattr(qiskit.QuantumCircuit, operation)
                op_args = list(signature(gate).parameters.keys())
                num_angles = len(op_args) - num_operands - 1  # -1 for the 'self' arg
                angles = [random.uniform(0, 3.14) for x in range(num_angles)]
                register_operands = [qr[i] for i in operands]
                gate(qc, *angles, *register_operands)

        return qc
Esempio n. 26
0
def matrix_to_sycamore_operations(
        target_qubits: List[cirq.GridQubit],
        matrix: np.ndarray) -> Tuple[cirq.OP_TREE, List[cirq.GridQubit]]:
    """A method to convert a unitary matrix to a list of Sycamore operations.

    This method will return a list of `cirq.Operation`s using the qubits and (optionally) ancilla
    qubits to implement the unitary matrix `matrix` on the target qubits `qubits`.
    The operations are also supported by `cirq.google.gate_sets.SYC_GATESET`.

    Args:
        target_qubits: list of qubits the returned operations will act on. The qubit order defined by the list
            is assumed to be used by the operations to implement `matrix`.
        matrix: a matrix that is guaranteed to be unitary and of size (2**len(qs), 2**len(qs)).
    Returns:
        A tuple of operations and ancilla qubits allocated.
            Operations: In case the matrix is supported, a list of operations `ops` is returned.
                `ops` acts on `qs` qubits and for which `cirq.unitary(ops)` is equal to `matrix` up
                 to certain tolerance. In case the matrix is not supported, it might return NotImplemented to
                 reduce the noise in the judge output.
            Ancilla qubits: In case ancilla qubits are allocated a list of ancilla qubits. Otherwise
                an empty list.
        .
    """
    if len(target_qubits) > 4:
        return NotImplemented, []

    # Converting the Unitary to Operations using Qiskit
    qc = qiskit.QuantumCircuit(len(target_qubits))
    qc.unitary(matrix, list(range(len(target_qubits))))
    qc = qiskit.transpile(qc, basis_gates=['cx', 'u3'])
    # Converting Qiskit to Cirq
    from cirq.contrib import qasm_import
    qasm = qc.qasm()
    qx = cirq.Circuit(qasm_import.circuit_from_qasm(qasm))
    # Compiling down to the Sycamore hardware
    convertor = cirq.google.ConvertToSycamoreGates()
    qz = convertor.convert(qx)
    # Running an optimization pass
    qy = cirq.Circuit(qz)
    qy = cirq.google.optimized_for_sycamore(qy)
    qy = list(qy.all_operations())

    ans = qz if len(qy) > len(
        qz) else qy  # Check if optimizations are doing better
    return ans, []
def get_readout_err(experimental_backend, number_of_shots):
    '''
    Function that returns the calibration array for a given backend.
    '''
    #DEFINE HELPING ARRAY M
    M = np.array([[1, 1], [1, -1]])

    results = np.zeros((2, 1))
    print('Calibration has begun.\n')
    n = 0
    for i in range(2):

        #initialise circuit
        q = qk.QuantumRegister(1)
        c = qk.ClassicalRegister(1)
        circuit = qk.QuantumCircuit(q, c)

        #initialise 0 1  state
        circuit.initialize(np.array([1 - i, i]), 0)

        circuit.measure(q, c)

        # Define the experiment
        qi_job = qk.execute(circuit,
                            backend=experimental_backend,
                            shots=number_of_shots)
        qi_result = qi_job.result()

        #results
        histogram = qi_result.get_counts(circuit)

        #calculate expected_value IZ ZI ZZ
        expected_value = 0
        for state, counts in histogram.items():
            expected_value += (-1)**(int(state[0])) * int(counts)

        expected_value = expected_value / number_of_shots

        results[n, :] = expected_value
        n = n + 1

    Bd = 1 / 2 * np.dot(M, results)

    print('Calibration done!\n')
    return Bd
Esempio n. 28
0
def run(angles, num_shots):

    qr = qk.QuantumRegister(3)
    cr = qk.ClassicalRegister(3)

    # create a circuit
    qc = qk.QuantumCircuit(qr, cr)

    #Creating the Hadamard State
    qc.h(qr[0])
    qc.h(qr[1])

    i = 0
    # for every angle, add to the circuit the encoding of that angle
    for ang in angles:

        # to make sure we are transforming the correct vector, need to NOT certain qubits
        qc.x(qr[0])

        if (i % 2 == 0):
            qc.x(qr[1])

        # The C^2-Ry operation
        qc.cu3(ang, 0, 0, qr[0], qr[2])
        qc.cx(qr[0], qr[1])
        qc.cu3(-ang, 0, 0, qr[1], qr[2])
        qc.cx(qr[0], qr[1])
        qc.cu3(ang, 0, 0, qr[1], qr[2])

        i += 1

    qc.barrier(qr)
    qc.measure(qr, cr)

    # run the circuit
    backend_sim = Aer.get_backend('qasm_simulator')
    job_sim = execute(qc, backend_sim, shots=num_shots)
    result_sim = job_sim.result()

    # get the dictionary that contains number of times each outcome was measured
    counts = result_sim.get_counts(qc)

    new_angles = probs(counts, num_shots)

    return new_angles
    def buildQuantumCircuits(self) -> None:
        """
        This method clears and attempts to (re-)build the set of quantum circuits used to generate random integers by this factory
        Each integer is the result of a single collapsing qubit's quantum state and there are only five qubits per processor
        More than five bits means that a set of experiments will have to be set up, each with five bits, and the results concatenated together
        """

        # Initialize self.quantumCircuits to an empty list and iterater over self.numberOfBits, five at a time
        self.quantumCircuts = []
        for i in range(0, self.numberOfBits, self.qubitsPerCircuit):
            # This top-level iteration represents the set of quantum circuits needed to generate this random number
            # Each time through this loop, a new quantum circuit object will be created and added to self.quantumCircuits

            # Compute the number of qubits needed in this quantum circuit, then initialize the apprporiate-sized registers
            # If this is the last(only) circuit required, the number of qubits could be few as one
            # If the factory is generating integers larger than five bits, all circuits except the last one will all have five qubits
            numberOfQubits = min([(self.numberOfBits - i),
                                  self.qubitsPerCircuit])
            quantumRegister = qiskit.QuantumRegister(numberOfQubits)
            classicalRegister = qiskit.ClassicalRegister(numberOfQubits)

            # Initialize the circuit and apply a Hadamard gate to each qubit in the quantum register
            quantumCircuit = qiskit.QuantumCircuit(quantumRegister,
                                                   classicalRegister)
            quantumCircuit.h(quantumRegister)

            # Itearate over the number of qubits in this circuit and set up a series of H-U1-H gates to each
            for j in range(numberOfQubits):

                # Set the bit number (index) and then use a U1 gate to rotatethe qubit the desired amount
                # If this bit does not have any weighting, the default quibit rotation is half (50%) of PI
                # If the bit is weighted, the qubit rotation is the weight's value is a number between 0 - 100 and is treated as a percentage of PI
                index = i + j
                quantumCircuit.u1(
                    ((self.bitWeights[index] if
                      (index in self.bitWeights) else 50) * numpy.pi) / 100,
                    quantumRegister[j])

            # Finish up the quantum circuit with a Hadamard gate to each qubit in the quantum register, and then measure each qubit to collapse
            # its superposition into either a zero or a one
            quantumCircuit.h(quantumRegister)
            quantumCircuit.measure(quantumRegister, classicalRegister)

            # Add the newly-created quatum circuit to self.quatumCircuits
            self.quantumCircuits.append(quantumCircuit)
Esempio n. 30
0
def toffoli():
    '''
    Lab2 - questão 3
    :param n: número de controles
    :param V:
    :return: circuito quântico com n+1 qubits + n-1 qubits auxiliares
            que aplica o operador nCV.
    '''
    controles = qiskit.QuantumRegister(2)
    alvo = qiskit.QuantumRegister(1)

    circuito = qiskit.QuantumCircuit(controles, alvo)

    #------------------------
    # Seu código aqui
    # ------------------------

    return circuito