Ejemplo n.º 1
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)
    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))
Ejemplo n.º 3
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)
Ejemplo n.º 4
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)
Ejemplo n.º 5
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 = 'statevector_simulator'
        sim_py = 'statevector_simulator_py'
        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))
Ejemplo n.º 6
0
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))
Ejemplo n.º 7
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
Ejemplo n.º 8
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)
Ejemplo n.º 9
0
def test_to_qiskit_assign_qregs(qreg_sizes):
    nbits = sum(qreg_sizes)
    cirq_circuit = cirq.testing.random_circuit(nbits,
                                               n_moments=5,
                                               op_density=1,
                                               random_state=10)

    qregs = [qiskit.QuantumRegister(s) for s in qreg_sizes]
    qiskit_circuit = to_qiskit(cirq_circuit, qregs=qregs)

    assert qiskit_circuit.qregs == qregs
    assert qiskit_circuit.cregs == []
    cirq.testing.assert_allclose_up_to_global_phase(
        cirq.unitary(from_qiskit(qiskit_circuit)),
        cirq.unitary(cirq_circuit),
        atol=1e-5,
    )
Ejemplo n.º 10
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)
Ejemplo n.º 11
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
Ejemplo n.º 12
0
    def _generate_circuit(self):
        """ """

        N = self._nb_qubits
        barriers = True

        if self._qubit_names == None:
            qc = qk.QuantumCircuit(N)
        else:
            logical_qubits = qk.QuantumRegister(3, self._qubit_names)
            qc = qk.QuantumCircuit(logical_qubits)

        egate = qc.cx  # entangle with CNOTs

        param_counter = 0
        for r in range(self._depth):

            # add parameterised single qubit rotations
            for q in range(N):
                qc.u2(*[self._params[param_counter + i] for i in range(2)], q)
                param_counter += 2

            # add entangling gates
            l, r = 2 * np.arange(N // 2), 2 * np.arange(N // 2) + 1
            if len(l) == 1:
                egate(l[0], r[0])
            elif len(l) > 1:
                egate(l, r)
            l, r = 2 * np.arange(N // 2 - 1 +
                                 (N % 2)) + 1, 2 * np.arange(N // 2 - 1 +
                                                             (N % 2)) + 2
            if len(l) == 1:
                egate(l[0], r[0])
            elif len(l) > 1:
                egate(l, r)
            if self._cyclic:
                egate(0, self._nb_qubits - 1)
            if barriers:
                qc.barrier()

        # add final round of parameterised single qubit rotations
        for q in range(N):
            qc.u2(*[self._params[param_counter + i] for i in range(2)], q)
            param_counter += 2

        return qc
Ejemplo n.º 13
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)
Ejemplo n.º 14
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)
Ejemplo n.º 15
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)
Ejemplo n.º 16
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)
Ejemplo n.º 17
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)
Ejemplo n.º 18
0
    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
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
    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)
Ejemplo n.º 21
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 __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
Ejemplo n.º 23
0
def test_qiskit_noisy_basis():
    rng = np.random.RandomState(seed=1)

    qreg = qiskit.QuantumRegister(1)
    xcirc = qiskit.QuantumCircuit(qreg)
    _ = xcirc.x(qreg)
    zcirc = qiskit.QuantumCircuit(qreg)
    _ = zcirc.z(qreg)

    noisy_basis = NoisyBasis(
        NoisyOperation(ideal=xcirc, real=rng.rand(4, 4)),
        NoisyOperation(ideal=zcirc, real=rng.rand(4, 4)),
    )
    assert len(noisy_basis) == 2

    for op in noisy_basis.elements:
        assert isinstance(op.ideal_circuit(), qiskit.QuantumCircuit)
        assert isinstance(op._ideal, cirq.Circuit)
Ejemplo n.º 24
0
    def test_from_qiskit(self):
        # Given
        register = qiskit.QuantumRegister(3)
        index = 1
        qubit = qiskit.circuit.Qubit(register, index)
        target_qubit_dict = {
            "index": index,
            "info": {
                "label": "qiskit",
                "num": index
            },
        }

        # When
        recreated_qubit = Qubit.from_qiskit(qubit, index)

        # Then
        self.assertDictEqual(recreated_qubit.to_dict(), target_qubit_dict)
Ejemplo n.º 25
0
    def test_qasm(self):
        """counts from a GHZ state"""
        qr = qiskit.QuantumRegister(3)
        cr = qiskit.ClassicalRegister(3)
        circuit = qiskit.QuantumCircuit(qr, cr)
        circuit.h(qr[0])
        circuit.cx(qr[0], qr[1])
        circuit.cx(qr[1], qr[2])
        circuit.measure(qr, cr)

        sim_cpp = Aer.get_backend('qasm_simulator')
        sim_py = Aer.get_backend('qasm_simulator_py')
        shots = 2000
        result_cpp = execute(circuit, sim_cpp, shots=shots).result()
        result_py = execute(circuit, sim_py, shots=shots).result()
        counts_cpp = result_cpp.get_counts()
        counts_py = result_py.get_counts()
        self.assertDictAlmostEqual(counts_cpp, counts_py, shots * 0.08)
Ejemplo n.º 26
0
def test_transform_qregs_random_circuit(new_reg_sizes, measure):
    nbits = sum(new_reg_sizes)
    circ = to_qiskit(
        cirq.testing.random_circuit(
            nbits, n_moments=5, op_density=1, random_state=10
        )
    )
    creg = qiskit.ClassicalRegister(nbits)
    circ.add_register(creg)
    if measure:
        circ.measure(circ.qregs[0], creg)
    orig = circ.copy()

    new_qregs = [qiskit.QuantumRegister(s) for s in new_reg_sizes]
    _transform_registers(circ, new_qregs=new_qregs)

    assert circ.qregs == new_qregs
    assert _equal(from_qiskit(circ), from_qiskit(orig))
Ejemplo n.º 27
0
    def test_compile(self):
        """Test Compiler.

        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)

        # FIXME should test against the qobj when defined
        self.assertEqual(len(qobj), 3)
Ejemplo n.º 28
0
    def test_execute_two(self):
        """Test execute two.

        If all correct some should exists.
        """
        backend = get_backend('local_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)
        qc_extra = qiskit.QuantumCircuit(qubit_reg, clbit_reg)
        qc_extra.measure(qubit_reg, clbit_reg)
        job = execute([qc, qc_extra], backend)
        results = job.result()
        self.assertIsInstance(results, Result)
Ejemplo n.º 29
0
    def test_qasm(self):
        """counts from a GHZ state"""
        qr = qiskit.QuantumRegister(3)
        cr = qiskit.ClassicalRegister(3)
        circuit = qiskit.QuantumCircuit(qr, cr)
        circuit.h(qr[0])
        circuit.cx(qr[0], qr[1])
        circuit.cx(qr[1], qr[2])
        circuit.measure(qr, cr)

        sim_cpp = qiskit.providers.aer.QasmSimulator()
        sim_py = qiskit.providers.builtinsimulators.QasmSimulatorPy()
        shots = 2000
        result_cpp = execute(circuit, sim_cpp, shots=shots).result()
        result_py = execute(circuit, sim_py, shots=shots).result()
        counts_cpp = result_cpp.get_counts()
        counts_py = result_py.get_counts()
        self.assertDictAlmostEqual(counts_cpp, counts_py, shots * 0.08)
Ejemplo n.º 30
0
    def test_execute_remote(self, qe_token, qe_url):
        """Test Execute remote.

        If all correct some should exists.
        """
        register(qe_token, qe_url)
        backend = available_backends({'local': False, 'simulator': True})[0]
        backend = get_backend(backend)
        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, seed=TestCompiler.seed)
        results = job.result()
        self.assertIsInstance(results, Result)