def perform_walk_lollipop(N, iter, sh,bck,genQASM):
    Q_program = QuantumProgram()
    if (bck == "1"):
        backnd = 'local_qasm_simulator'
    else:
        backnd = 'ibmqx2'
        Q_program.set_api(Qconfig.APItoken, Qconfig.config['url'])


    print("Trwa generowanie obwodu kwantowego...")
    build_circuit_lollipop(Q_program, N, iter)
    QASM=None
    if (genQASM):
        qobj = Q_program.compile(['walk'], backend=backnd)
        QASM = Q_program.get_compiled_qasm(qobj, 'walk')
    print("Obwód kwantowy wygenerowany. Trwa uruchamianie spaceru...")
    result = Q_program.execute(["walk"], backend=backnd, shots=sh, silent=True)
    print("Spacer zakończony.")
    return result.get_counts('walk'), QASM
    def test_get_compiled_qasm(self):
        """Test get_compiled_qasm.

        If all correct should return lenght  dictionary.
        """
        QP_program = QuantumProgram(specs=QPS_SPECS)
        qc = QP_program.get_circuit("circuitName")
        qr = QP_program.get_quantum_register("qname")
        cr = QP_program.get_classical_register("cname")
        qc.h(qr[0])
        qc.cx(qr[0], qr[1])
        qc.measure(qr[0], cr[0])
        qc.measure(qr[1], cr[1])
        backend = 'local_qasm_simulator'
        coupling_map = None
        qobj = QP_program.compile(['circuitName'], backend=backend,
                                  coupling_map=coupling_map)
        result = QP_program.get_compiled_qasm(qobj, 'circuitName',)
        # print(result)
        self.assertEqual(len(result), 184)
    def test_get_compiled_qasm(self):
        """Test get_compiled_qasm.

        If all correct should return lenght  dictionary.
        """
        QP_program = QuantumProgram(specs=QPS_SPECS)
        qc = QP_program.get_circuit("circuitName")
        qr = QP_program.get_quantum_register("qname")
        cr = QP_program.get_classical_register("cname")
        qc.h(qr[0])
        qc.cx(qr[0], qr[1])
        qc.measure(qr[0], cr[0])
        qc.measure(qr[1], cr[1])
        backend = 'local_qasm_simulator'
        coupling_map = None
        qobj = QP_program.compile(['circuitName'], backend=backend,
                                  coupling_map=coupling_map)
        result = QP_program.get_compiled_qasm(qobj, 'circuitName',)
        # print(result)
        self.assertEqual(len(result), 184)
Esempio n. 4
0
for j in range(n):
    qc.measure(b[j], ans[j])
qc.measure(cout[0], ans[n])

###############################################################
# Set up the API and execute the program.
###############################################################
result = qp.set_api(Qconfig.APItoken, Qconfig.config["url"])
if not result:
    print("Error setting API")
    sys.exit(1)

# First version: not compiled
result = qp.execute(["rippleadd"],
                    device=device,
                    coupling_map=None,
                    shots=1024)
print(result)
print(qp.get_counts("rippleadd"))

# Second version: compiled to 2x8 array coupling graph
qp.compile(["rippleadd"], device=device, coupling_map=coupling_map, shots=1024)
# qp.print_execution_list(verbose=True)
result = qp.run()

print(result)
print(qp.get_compiled_qasm("rippleadd"))
print(qp.get_counts("rippleadd"))

# Both versions should give the same distribution
Esempio n. 5
0
class MapperTest(QiskitTestCase):
    """Test the mapper."""
    def setUp(self):
        self.seed = 42
        self.qp = QuantumProgram()

    def test_mapper_overoptimization(self):
        """
        The mapper should not change the semantics of the input. An overoptimization introduced
        the issue #81: https://github.com/QISKit/qiskit-terra/issues/81
        """
        self.qp.load_qasm_file(
            self._get_resource_path('qasm/overoptimization.qasm'), name='test')
        coupling_map = [[0, 2], [1, 2], [2, 3]]
        result1 = self.qp.execute(["test"],
                                  backend="local_qasm_simulator",
                                  coupling_map=coupling_map)
        count1 = result1.get_counts("test")
        result2 = self.qp.execute(["test"],
                                  backend="local_qasm_simulator",
                                  coupling_map=None)
        count2 = result2.get_counts("test")
        self.assertEqual(
            count1.keys(),
            count2.keys(),
        )

    def test_math_domain_error(self):
        """
        The math library operates over floats and introduce floating point errors that should be
        avoided.
        See: https://github.com/QISKit/qiskit-terra/issues/111
        """
        self.qp.load_qasm_file(
            self._get_resource_path('qasm/math_domain_error.qasm'),
            name='test')
        coupling_map = [[0, 2], [1, 2], [2, 3]]
        shots = 2000
        result = self.qp.execute("test",
                                 backend="local_qasm_simulator",
                                 coupling_map=coupling_map,
                                 seed=self.seed,
                                 shots=shots)
        counts = result.get_counts("test")
        target = {'0001': shots / 2, '0101': shots / 2}
        threshold = 0.04 * shots
        self.assertDictAlmostEqual(counts, target, threshold)

    def test_optimize_1q_gates_issue159(self):
        """Test change in behavior for optimize_1q_gates that removes u1(2*pi) rotations.

        See: https://github.com/QISKit/qiskit-terra/issues/159
        """
        self.qp = QuantumProgram()
        qr = self.qp.create_quantum_register('qr', 2)
        cr = self.qp.create_classical_register('cr', 2)
        qc = self.qp.create_circuit('Bell', [qr], [cr])
        qc.h(qr[0])
        qc.cx(qr[1], qr[0])
        qc.cx(qr[1], qr[0])
        qc.cx(qr[1], qr[0])
        qc.measure(qr[0], cr[0])
        qc.measure(qr[1], cr[1])
        backend = 'local_qasm_simulator'
        coupling_map = [[1, 0], [2, 0], [2, 1], [2, 4], [3, 2], [3, 4]]
        initial_layout = {('qr', 0): ('q', 1), ('qr', 1): ('q', 0)}
        qobj = self.qp.compile(["Bell"],
                               backend=backend,
                               initial_layout=initial_layout,
                               coupling_map=coupling_map)

        self.assertEqual(self.qp.get_compiled_qasm(qobj, "Bell"),
                         EXPECTED_QASM_1Q_GATES_3_5)

    def test_random_parameter_circuit(self):
        """Run a circuit with randomly generated parameters."""
        self.qp.load_qasm_file(
            self._get_resource_path('qasm/random_n5_d5.qasm'), name='rand')
        coupling_map = [[0, 1], [1, 2], [2, 3], [3, 4]]
        shots = 1024
        result1 = self.qp.execute(["rand"],
                                  backend="local_qasm_simulator",
                                  coupling_map=coupling_map,
                                  shots=shots,
                                  seed=self.seed)
        counts = result1.get_counts("rand")
        expected_probs = {
            '00000': 0.079239867254200971,
            '00001': 0.032859032998526903,
            '00010': 0.10752610993531816,
            '00011': 0.018818532050952699,
            '00100': 0.054830807251011054,
            '00101': 0.0034141983951965164,
            '00110': 0.041649309748902276,
            '00111': 0.039967731207338125,
            '01000': 0.10516937819949743,
            '01001': 0.026635620063700002,
            '01010': 0.0053475143548793866,
            '01011': 0.01940513314416064,
            '01100': 0.0044028405481225047,
            '01101': 0.057524760052126644,
            '01110': 0.010795354134597078,
            '01111': 0.026491296821535528,
            '10000': 0.094827455395274859,
            '10001': 0.0008373965072688836,
            '10010': 0.029082297894094441,
            '10011': 0.012386622870598416,
            '10100': 0.018739140061148799,
            '10101': 0.01367656456536896,
            '10110': 0.039184170706009248,
            '10111': 0.062339335178438288,
            '11000': 0.00293674365989009,
            '11001': 0.012848433960739968,
            '11010': 0.018472497159499782,
            '11011': 0.0088903691234912003,
            '11100': 0.031305389080034329,
            '11101': 0.0004788556283690458,
            '11110': 0.002232419390471667,
            '11111': 0.017684822659235985
        }
        target = {key: shots * val for key, val in expected_probs.items()}
        threshold = 0.04 * shots
        self.assertDictAlmostEqual(counts, target, threshold)

    def test_symbolic_unary(self):
        """Test symbolic math in DAGBackend and optimizer with a prefix.

        See: https://github.com/QISKit/qiskit-terra/issues/172
        """
        ast = qasm.Qasm(filename=self._get_resource_path(
            'qasm/issue172_unary.qasm')).parse()
        unr = unroll.Unroller(ast,
                              backend=unroll.DAGBackend(
                                  ["cx", "u1", "u2", "u3"]))
        unr.execute()
        circ = mapper.optimize_1q_gates(unr.backend.circuit)
        self.assertEqual(circ.qasm(qeflag=True), EXPECTED_QASM_SYMBOLIC_UNARY)

    def test_symbolic_binary(self):
        """Test symbolic math in DAGBackend and optimizer with a binary operation.

        See: https://github.com/QISKit/qiskit-terra/issues/172
        """
        ast = qasm.Qasm(filename=self._get_resource_path(
            'qasm/issue172_binary.qasm')).parse()

        unr = unroll.Unroller(ast,
                              backend=unroll.DAGBackend(
                                  ["cx", "u1", "u2", "u3"]))
        unr.execute()
        circ = mapper.optimize_1q_gates(unr.backend.circuit)
        self.assertEqual(circ.qasm(qeflag=True), EXPECTED_QASM_SYMBOLIC_BINARY)

    def test_symbolic_extern(self):
        """Test symbolic math in DAGBackend and optimizer with an external function.

        See: https://github.com/QISKit/qiskit-terra/issues/172
        """
        ast = qasm.Qasm(filename=self._get_resource_path(
            'qasm/issue172_extern.qasm')).parse()
        unr = unroll.Unroller(ast,
                              backend=unroll.DAGBackend(
                                  ["cx", "u1", "u2", "u3"]))
        unr.execute()
        circ = mapper.optimize_1q_gates(unr.backend.circuit)
        self.assertEqual(circ.qasm(qeflag=True), EXPECTED_QASM_SYMBOLIC_EXTERN)

    def test_symbolic_power(self):
        """Test symbolic math in DAGBackend and optimizer with a power (^).

        See: https://github.com/QISKit/qiskit-terra/issues/172
        """
        ast = qasm.Qasm(data=QASM_SYMBOLIC_POWER).parse()
        unr = unroll.Unroller(ast,
                              backend=unroll.DAGBackend(
                                  ["cx", "u1", "u2", "u3"]))
        unr.execute()
        circ = mapper.optimize_1q_gates(unr.backend.circuit)
        self.assertEqual(circ.qasm(qeflag=True), EXPECTED_QASM_SYMBOLIC_POWER)

    def test_already_mapped(self):
        """Test that if the circuit already matches the backend topology, it is not remapped.

        See: https://github.com/QISKit/qiskit-terra/issues/342
        """
        self.qp = QuantumProgram()
        qr = self.qp.create_quantum_register('qr', 16)
        cr = self.qp.create_classical_register('cr', 16)
        qc = self.qp.create_circuit('native_cx', [qr], [cr])
        qc.cx(qr[3], qr[14])
        qc.cx(qr[5], qr[4])
        qc.h(qr[9])
        qc.cx(qr[9], qr[8])
        qc.x(qr[11])
        qc.cx(qr[3], qr[4])
        qc.cx(qr[12], qr[11])
        qc.cx(qr[13], qr[4])
        for j in range(16):
            qc.measure(qr[j], cr[j])
        backend = 'local_qasm_simulator'
        coupling_map = [[1, 0], [1, 2], [2, 3], [3, 4],
                        [3, 14], [5, 4], [6, 5], [6, 7], [6, 11], [7, 10],
                        [8, 7], [9, 8], [9, 10], [11, 10], [12, 5], [12, 11],
                        [12, 13], [13, 4], [13, 14], [15, 0], [15,
                                                               2], [15, 14]]
        qobj = self.qp.compile(["native_cx"],
                               backend=backend,
                               coupling_map=coupling_map)
        cx_qubits = [
            x.qubits for x in qobj.experiments[0].instructions
            if x.name == "cx"
        ]

        self.assertEqual(sorted(cx_qubits),
                         [[3, 4], [3, 14], [5, 4], [9, 8], [12, 11], [13, 4]])

    def test_yzy_zyz_cases(self):
        """Test mapper function yzy_to_zyz works in previously failed cases.

        See: https://github.com/QISKit/qiskit-terra/issues/607
        """
        backend = FakeQX4BackEnd()
        circ1 = load_qasm_string(yzy_zyz_1)
        qobj1 = qiskit.wrapper.compile(circ1, backend)
        self.assertIsInstance(qobj1, Qobj)
        circ2 = load_qasm_string(yzy_zyz_2)
        qobj2 = qiskit.wrapper.compile(circ2, backend)
        self.assertIsInstance(qobj2, Qobj)
Esempio n. 6
0
class MapperTest(QiskitTestCase):
    """Test the mapper."""

    def setUp(self):
        self.seed = 42
        self.qp = QuantumProgram()

    def test_mapper_overoptimization(self):
        """
        The mapper should not change the semantics of the input. An overoptimization introduced
        the issue #81: https://github.com/QISKit/qiskit-sdk-py/issues/81
        """
        self.qp.load_qasm_file(self._get_resource_path('qasm/overoptimization.qasm'), name='test')
        coupling_map = [[0, 2], [1, 2], [2, 3]]
        result1 = self.qp.execute(["test"], backend="local_qasm_simulator",
                                  coupling_map=coupling_map)
        count1 = result1.get_counts("test")
        result2 = self.qp.execute(["test"], backend="local_qasm_simulator", coupling_map=None)
        count2 = result2.get_counts("test")
        self.assertEqual(count1.keys(), count2.keys(), )

    def test_math_domain_error(self):
        """
        The math library operates over floats and introduce floating point errors that should be
        avoided.
        See: https://github.com/QISKit/qiskit-sdk-py/issues/111
        """
        self.qp.load_qasm_file(self._get_resource_path('qasm/math_domain_error.qasm'), name='test')
        coupling_map = [[0, 2], [1, 2], [2, 3]]
        result1 = self.qp.execute(["test"], backend="local_qasm_simulator",
                                  coupling_map=coupling_map, seed=self.seed)

        self.assertEqual(result1.get_counts("test"), {'0001': 480, '0101': 544})

    def test_optimize_1q_gates_issue159(self):
        """Test change in behavior for optimize_1q_gates that removes u1(2*pi) rotations.

        See: https://github.com/QISKit/qiskit-sdk-py/issues/159
        """
        self.qp = QuantumProgram()
        qr = self.qp.create_quantum_register('qr', 2)
        cr = self.qp.create_classical_register('cr', 2)
        qc = self.qp.create_circuit('Bell', [qr], [cr])
        qc.h(qr[0])
        qc.cx(qr[1], qr[0])
        qc.cx(qr[1], qr[0])
        qc.cx(qr[1], qr[0])
        qc.measure(qr[0], cr[0])
        qc.measure(qr[1], cr[1])
        backend = 'local_qasm_simulator'
        coupling_map = [[1, 0], [2, 0], [2, 1], [2, 4], [3, 2], [3, 4]]
        initial_layout = {('qr', 0): ('q', 1), ('qr', 1): ('q', 0)}
        qobj = self.qp.compile(["Bell"], backend=backend,
                               initial_layout=initial_layout, coupling_map=coupling_map)

        self.assertEqual(self.qp.get_compiled_qasm(qobj, "Bell"), EXPECTED_QASM_1Q_GATES_3_5)

    def test_random_parameter_circuit(self):
        """Run a circuit with randomly generated parameters."""
        self.qp.load_qasm_file(self._get_resource_path('qasm/random_n5_d5.qasm'), name='rand')
        coupling_map = [[0, 1], [1, 2], [2, 3], [3, 4]]
        result1 = self.qp.execute(["rand"], backend="local_qasm_simulator",
                                  coupling_map=coupling_map, seed=self.seed)
        res = result1.get_counts("rand")

        print(res)

        expected_result = {'10000': 92, '10100': 27, '01000': 99, '00001': 37,
                           '11100': 31, '01001': 27, '10111': 79, '00111': 43,
                           '00000': 88, '00010': 104, '11111': 14, '00110': 52,
                           '00100': 50, '01111': 21, '10010': 34, '01011': 21,
                           '00011': 15, '01101': 53, '10110': 32, '10101': 12,
                           '01100': 8, '01010': 7, '10011': 15, '11010': 26,
                           '11011': 8, '11110': 4, '01110': 14, '11001': 6,
                           '11000': 1, '11101': 2, '00101': 2}
        # TODO It's ugly, I know. But we are getting different results from Python 3.5
        # and Python 3.6. So let's trick this until we fix all testing
        if expected_result != res:
            expected_result = {'00001': 31, '01111': 23, '10010': 24, '01001': 29,
                               '11000': 4, '10111': 74, '00101': 3, '11010': 21,
                               '01100': 11, '11110': 2, '11101': 2, '11001': 18,
                               '01011': 17, '00100': 45, '01010': 1, '11111': 13,
                               '00011': 20, '00110': 35, '00000': 87, '10101': 12,
                               '01110': 11, '00010': 122, '10100': 21, '10000': 88,
                               '10110': 34, '01000': 108, '11011': 8, '10011': 14,
                               '01101': 58, '00111': 48, '11100': 40}

        self.assertEqual(res, expected_result)

    def test_symbolic_unary(self):
        """Test symbolic math in DAGBackend and optimizer with a prefix.

        See: https://github.com/QISKit/qiskit-sdk-py/issues/172
        """
        ast = qasm.Qasm(filename=self._get_resource_path(
            'qasm/issue172_unary.qasm')).parse()
        unr = unroll.Unroller(ast, backend=unroll.DAGBackend(["cx", "u1", "u2", "u3"]))
        unr.execute()
        circ = mapper.optimize_1q_gates(unr.backend.circuit)
        self.assertEqual(circ.qasm(qeflag=True), EXPECTED_QASM_SYMBOLIC_UNARY)

    def test_symbolic_binary(self):
        """Test symbolic math in DAGBackend and optimizer with a binary operation.

        See: https://github.com/QISKit/qiskit-sdk-py/issues/172
        """
        ast = qasm.Qasm(filename=self._get_resource_path(
            'qasm/issue172_binary.qasm')).parse()

        unr = unroll.Unroller(ast, backend=unroll.DAGBackend(["cx", "u1", "u2", "u3"]))
        unr.execute()
        circ = mapper.optimize_1q_gates(unr.backend.circuit)
        self.assertEqual(circ.qasm(qeflag=True), EXPECTED_QASM_SYMBOLIC_BINARY)

    def test_symbolic_extern(self):
        """Test symbolic math in DAGBackend and optimizer with an external function.

        See: https://github.com/QISKit/qiskit-sdk-py/issues/172
        """
        ast = qasm.Qasm(filename=self._get_resource_path(
            'qasm/issue172_extern.qasm')).parse()
        unr = unroll.Unroller(ast, backend=unroll.DAGBackend(["cx", "u1", "u2", "u3"]))
        unr.execute()
        circ = mapper.optimize_1q_gates(unr.backend.circuit)
        self.assertEqual(circ.qasm(qeflag=True), EXPECTED_QASM_SYMBOLIC_EXTERN)

    def test_symbolic_power(self):
        """Test symbolic math in DAGBackend and optimizer with a power (^).

        See: https://github.com/QISKit/qiskit-sdk-py/issues/172
        """
        ast = qasm.Qasm(data=QASM_SYMBOLIC_POWER).parse()
        unr = unroll.Unroller(ast, backend=unroll.DAGBackend(["cx", "u1", "u2", "u3"]))
        unr.execute()
        circ = mapper.optimize_1q_gates(unr.backend.circuit)
        self.assertEqual(circ.qasm(qeflag=True), EXPECTED_QASM_SYMBOLIC_POWER)

    def test_already_mapped(self):
        """Test that if the circuit already matches the backend topology, it is not remapped.

        See: https://github.com/QISKit/qiskit-sdk-py/issues/342
        """
        self.qp = QuantumProgram()
        qr = self.qp.create_quantum_register('qr', 16)
        cr = self.qp.create_classical_register('cr', 16)
        qc = self.qp.create_circuit('native_cx', [qr], [cr])
        qc.cx(qr[3], qr[14])
        qc.cx(qr[5], qr[4])
        qc.h(qr[9])
        qc.cx(qr[9], qr[8])
        qc.x(qr[11])
        qc.cx(qr[3], qr[4])
        qc.cx(qr[12], qr[11])
        qc.cx(qr[13], qr[4])
        for j in range(16):
            qc.measure(qr[j], cr[j])
        backend = 'local_qasm_simulator'
        coupling_map = [[1, 0], [1, 2], [2, 3], [3, 4], [3, 14], [5, 4],
                        [6, 5], [6, 7], [6, 11], [7, 10], [8, 7], [9, 8],
                        [9, 10], [11, 10], [12, 5], [12, 11], [12, 13],
                        [13, 4], [13, 14], [15, 0], [15, 2], [15, 14]]
        qobj = self.qp.compile(["native_cx"], backend=backend, coupling_map=coupling_map)
        cx_qubits = [x["qubits"]
                     for x in qobj["circuits"][0]["compiled_circuit"]["operations"]
                     if x["name"] == "cx"]

        self.assertEqual(sorted(cx_qubits), [[3, 4], [3, 14], [5, 4], [9, 8], [12, 11], [13, 4]])
initial_layout_1 = {
    ("qr", 0): ("q", 0),
    ("qr", 1): ("q", 1),
    ("qr", 2): ("q", 2)
}
initial_layout_2 = {
    ("qr2", 0): ("q", 0),
    ("qr2", 1): ("q", 1),
    ("qr2", 2): ("q", 2)
}
coupling_map = [[1, 0], [2, 0], [2, 1], [3, 2], [3, 4], [4, 2]]

#Compile the circuit to ibmqx4 to test
#FTSWAP_comp = Q_program.compile(['FTSWAP'],coupling_map=coupling_map ,initial_layout=initial_layout_1)
FTSWAP_comp = Q_program.compile(['FTSWAP'], backend=backendreal)
print(Q_program.get_compiled_qasm(FTSWAP_comp, 'FTSWAP'))
print(Q_program.get_compiled_configuration(FTSWAP_comp, 'FTSWAP'))

#Compile non compiled version of circuit to ibmqx4 to test
#FTSWAPnoncomp_comp = Q_program.compile(['FTSWAPnoncomp'],coupling_map=coupling_map ,initial_layout=initial_layout_2)
FTSWAPnoncomp_comp = Q_program.compile(['FTSWAPnoncomp'], backend=backendreal)
print(Q_program.get_compiled_qasm(FTSWAPnoncomp_comp, 'FTSWAPnoncomp'))
print(Q_program.get_compiled_configuration(FTSWAPnoncomp_comp,
                                           'FTSWAPnoncomp'))

################################################################################
# Create tomo set and tomo circuits; put them in the quantum program
tomo_set = tomo.process_tomography_set([1, 0], 'Pauli', 'Pauli')
tomo_circuits = tomo.create_tomography_circuits(Q_program, 'FTSWAP', q, c,
                                                tomo_set)
Esempio n. 8
0
class MapperTest(QiskitTestCase):
    """Test the mapper."""
    def setUp(self):
        self.seed = 42
        self.qp = QuantumProgram()

    def test_mapper_overoptimization(self):
        """
        The mapper should not change the semantics of the input. An overoptimization introduced
        the issue #81: https://github.com/QISKit/qiskit-sdk-py/issues/81
        """
        self.qp.load_qasm_file(
            self._get_resource_path('qasm/overoptimization.qasm'), name='test')
        coupling_map = {0: [2], 1: [2], 2: [3], 3: []}
        result1 = self.qp.execute(["test"],
                                  backend="local_qasm_simulator",
                                  coupling_map=coupling_map)
        count1 = result1.get_counts("test")
        result2 = self.qp.execute(["test"],
                                  backend="local_qasm_simulator",
                                  coupling_map=None)
        count2 = result2.get_counts("test")
        self.assertEqual(
            count1.keys(),
            count2.keys(),
        )

    def test_math_domain_error(self):
        """
        The math library operates over floats and introduce floating point errors that should be
        avoided.
        See: https://github.com/QISKit/qiskit-sdk-py/issues/111
        """
        self.qp.load_qasm_file(
            self._get_resource_path('qasm/math_domain_error.qasm'),
            name='test')
        coupling_map = {0: [2], 1: [2], 2: [3], 3: []}
        result1 = self.qp.execute(["test"],
                                  backend="local_qasm_simulator",
                                  coupling_map=coupling_map,
                                  seed=self.seed)

        # TODO: the circuit produces different results under different versions
        # of Python, which defeats the purpose of the "seed" parameter. A proper
        # fix should be issued - this is a workaround for this particular test.
        if version_info.minor == 5:  # Python 3.5
            self.assertEqual(result1.get_counts("test"), {
                '0001': 507,
                '0101': 517
            })
        else:  # Python 3.6 and higher
            self.assertEqual(result1.get_counts("test"), {
                '0001': 517,
                '0101': 507
            })

    def test_optimize_1q_gates_issue159(self):
        """Test change in behavior for optimize_1q_gates that removes u1(2*pi) rotations.

        See: https://github.com/QISKit/qiskit-sdk-py/issues/159
        """
        self.qp = QuantumProgram()
        qr = self.qp.create_quantum_register('qr', 2)
        cr = self.qp.create_classical_register('cr', 2)
        qc = self.qp.create_circuit('Bell', [qr], [cr])
        qc.h(qr[0])
        qc.cx(qr[1], qr[0])
        qc.cx(qr[1], qr[0])
        qc.cx(qr[1], qr[0])
        qc.measure(qr[0], cr[0])
        qc.measure(qr[1], cr[1])
        backend = 'local_qasm_simulator'
        cmap = {1: [0], 2: [0, 1, 4], 3: [2, 4]}
        qobj = self.qp.compile(["Bell"], backend=backend, coupling_map=cmap)

        # TODO: Python 3.5 produces an equivalent but different QASM, with the
        # last lines swapped. This assertion compares the output with the two
        # expected programs, but proper revision should be done.
        self.assertIn(self.qp.get_compiled_qasm(qobj, "Bell"),
                      (EXPECTED_QASM_1Q_GATES, EXPECTED_QASM_1Q_GATES_3_5))

    def test_random_parameter_circuit(self):
        """Run a circuit with randomly generated parameters."""
        self.qp.load_qasm_file(
            self._get_resource_path('qasm/random_n5_d5.qasm'), name='rand')
        coupling_map = {0: [1], 1: [2], 2: [3], 3: [4]}
        result1 = self.qp.execute(["rand"],
                                  backend="local_qasm_simulator",
                                  coupling_map=coupling_map,
                                  seed=self.seed)
        res = result1.get_counts("rand")

        expected_result = {
            '10000': 97,
            '00011': 24,
            '01000': 120,
            '10111': 59,
            '01111': 37,
            '11010': 14,
            '00001': 34,
            '00100': 42,
            '10110': 41,
            '00010': 102,
            '00110': 48,
            '10101': 19,
            '01101': 61,
            '00111': 46,
            '11100': 28,
            '01100': 1,
            '00000': 86,
            '11111': 14,
            '11011': 9,
            '10010': 35,
            '10100': 20,
            '01001': 21,
            '01011': 19,
            '10011': 10,
            '11001': 13,
            '00101': 4,
            '01010': 2,
            '01110': 17,
            '11000': 1
        }

        # TODO: the circuit produces different results under different versions
        # of Python and NetworkX package, which defeats the purpose of the
        # "seed" parameter. A proper fix should be issued - this is a workaround
        # for this particular test.
        if version_info.minor == 5:  # Python 3.5
            import networkx
            if networkx.__version__ == '1.11':
                expected_result = {
                    '01001': 41,
                    '10010': 25,
                    '00111': 53,
                    '01101': 68,
                    '10101': 11,
                    '10110': 34,
                    '01110': 6,
                    '11100': 27,
                    '00100': 54,
                    '11010': 20,
                    '10100': 20,
                    '01100': 1,
                    '10000': 96,
                    '11000': 1,
                    '11011': 9,
                    '10011': 15,
                    '00101': 3,
                    '00001': 25,
                    '00010': 113,
                    '01011': 16,
                    '11111': 19,
                    '11001': 16,
                    '00011': 22,
                    '00000': 89,
                    '00110': 40,
                    '01000': 110,
                    '10111': 60,
                    '11110': 4,
                    '01010': 9,
                    '01111': 17
                }
            else:
                expected_result = {
                    '01001': 32,
                    '11110': 1,
                    '10010': 36,
                    '11100': 34,
                    '11011': 10,
                    '00001': 41,
                    '00000': 83,
                    '10000': 94,
                    '11001': 15,
                    '01011': 24,
                    '00100': 43,
                    '11000': 5,
                    '11010': 9,
                    '01100': 5,
                    '10100': 23,
                    '01101': 54,
                    '01110': 6,
                    '00011': 13,
                    '10101': 12,
                    '00111': 36,
                    '00110': 40,
                    '01000': 119,
                    '11111': 19,
                    '01010': 8,
                    '10111': 61,
                    '10110': 52,
                    '01111': 23,
                    '00010': 110,
                    '00101': 2,
                    '10011': 14
                }

        self.assertEqual(res, expected_result)

    def test_symbolic_unary(self):
        """Test symbolic math in DAGBackend and optimizer with a prefix.

        See: https://github.com/QISKit/qiskit-sdk-py/issues/172
        """
        ast = qasm.Qasm(filename=self._get_resource_path(
            'qasm/issue172_unary.qasm')).parse()
        unr = unroll.Unroller(ast,
                              backend=unroll.DAGBackend(
                                  ["cx", "u1", "u2", "u3"]))
        unr.execute()
        circ = mapper.optimize_1q_gates(unr.backend.circuit)
        self.assertEqual(circ.qasm(qeflag=True), EXPECTED_QASM_SYMBOLIC_UNARY)

    def test_symbolic_binary(self):
        """Test symbolic math in DAGBackend and optimizer with a binary operation.

        See: https://github.com/QISKit/qiskit-sdk-py/issues/172
        """
        ast = qasm.Qasm(filename=self._get_resource_path(
            'qasm/issue172_binary.qasm')).parse()

        unr = unroll.Unroller(ast,
                              backend=unroll.DAGBackend(
                                  ["cx", "u1", "u2", "u3"]))
        unr.execute()
        circ = mapper.optimize_1q_gates(unr.backend.circuit)
        self.assertEqual(circ.qasm(qeflag=True), EXPECTED_QASM_SYMBOLIC_BINARY)

    def test_symbolic_extern(self):
        """Test symbolic math in DAGBackend and optimizer with an external function.

        See: https://github.com/QISKit/qiskit-sdk-py/issues/172
        """
        ast = qasm.Qasm(filename=self._get_resource_path(
            'qasm/issue172_extern.qasm')).parse()
        unr = unroll.Unroller(ast,
                              backend=unroll.DAGBackend(
                                  ["cx", "u1", "u2", "u3"]))
        unr.execute()
        circ = mapper.optimize_1q_gates(unr.backend.circuit)
        self.assertEqual(circ.qasm(qeflag=True), EXPECTED_QASM_SYMBOLIC_EXTERN)

    def test_symbolic_power(self):
        """Test symbolic math in DAGBackend and optimizer with a power (^).

        See: https://github.com/QISKit/qiskit-sdk-py/issues/172
        """
        ast = qasm.Qasm(data=QASM_SYMBOLIC_POWER).parse()
        unr = unroll.Unroller(ast,
                              backend=unroll.DAGBackend(
                                  ["cx", "u1", "u2", "u3"]))
        unr.execute()
        circ = mapper.optimize_1q_gates(unr.backend.circuit)
        self.assertEqual(circ.qasm(qeflag=True), EXPECTED_QASM_SYMBOLIC_POWER)
Esempio n. 9
0
class QC():
    '''
    class QC
    '''
    # pylint: disable=too-many-instance-attributes
    def __init__(self, backend='local_qasm_simulator', remote=False, qubits=3):
        # private member
        # __qp
        self.__qp = None

        # calc phase
        self.phase = [
            ['0', 'initialized.']
            ]
        # config
        self.backend = backend
        self.remote = remote
        self.qubits = qubits
        # circuits variable
        self.shots = 2
        # async
        self.wait = False
        self.last = ['init', 'None']

        self.load()

    def load(self, api_info=True):
        '''
        load
        '''
        self.__qp = QuantumProgram()
        if self.remote:
            try:
                import Qconfig
                self.__qp.set_api(Qconfig.APItoken, Qconfig.config["url"],
                                  hub=Qconfig.config["hub"],
                                  group=Qconfig.config["group"],
                                  project=Qconfig.config["project"])

            except ImportError as ex:
                msg = 'Error in loading Qconfig.py!. Error = {}\n'.format(ex)
                sys.stdout.write(msg)
                sys.stdout.flush()
                return False

            if api_info is True:
                api = self.__qp.get_api()
                sys.stdout.write('<IBM Quantum Experience API information>\n')
                sys.stdout.flush()
                sys.stdout.write('Version: {0}\n'.format(api.api_version()))
                sys.stdout.write('User jobs (last 5):\n')
                jobs = api.get_jobs(limit=500)

                def format_date(job_item):
                    '''
                    format
                    '''
                    return datetime.strptime(job_item['creationDate'],
                                             '%Y-%m-%dT%H:%M:%S.%fZ')
                sortedjobs = sorted(jobs,
                                    key=format_date)
                sys.stdout.write('  {0:<32} {1:<24} {2:<9} {3}\n'
                                 .format('id',
                                         'creationDate',
                                         'status',
                                         'backend'))
                sys.stdout.write('{:-^94}\n'.format(""))
                for job in sortedjobs[-5:]:
                    sys.stdout.write('  {0:<32} {1:<24} {2:<9} {3}\n'
                                     .format(job['id'],
                                             job['creationDate'],
                                             job['status'],
                                             job['backend']['name']))
                sys.stdout.write('There are {0} jobs on the server\n'
                                 .format(len(jobs)))
                sys.stdout.write('Credits: {0}\n'
                                 .format(api.get_my_credits()))
                sys.stdout.flush()

        self.backends = self.__qp.available_backends()
        status = self.__qp.get_backend_status(self.backend)

        if 'available' in status:
            if status['available'] is False:
                return False
        return True

    def set_config(self, config=None):
        '''
        set config
        '''
        if config is None:
            config = {}

        if 'backend' in config:
            self.backend = str(config['backend'])
            if 'local_' in self.backend:
                self.remote = False
            else:
                self.remote = True

        if 'remote' in config:
            self.remote = config['remote']

        if 'qubits' in config:
            self.qubits = int(config['qubits'])

        return True

    def _progress(self, phasename, text):
        self.phase.append([str(phasename), str(text)])
        text = "Phase {0}: {1}".format(phasename, text)
        sys.stdout.write("{}\n".format(text))
        sys.stdout.flush()

    def _init_circuit(self):
        self._progress('1', 'Initialize quantum registers and circuit')
        qubits = self.qubits

        quantum_registers = [
            {"name": "cin", "size": 1},
            {"name": "qa", "size": qubits},
            {"name": "qb", "size": qubits},
            {"name": "cout", "size": 1}
            ]

        classical_registers = [
            {"name": "ans", "size": qubits + 1}
            ]

        if 'cin' in self.__qp.get_quantum_register_names():
            self.__qp.destroy_quantum_registers(quantum_registers)
            self.__qp.destroy_classical_registers(classical_registers)

        q_r = self.__qp.create_quantum_registers(quantum_registers)
        c_r = self.__qp.create_classical_registers(classical_registers)

        self.__qp.create_circuit("qcirc", q_r, c_r)

    def _create_circuit_qadd(self):
        # quantum ripple-carry adder from Cuccaro et al, quant-ph/0410184
        def majority(circuit, q_a, q_b, q_c):
            '''
            majority
            '''
            circuit.cx(q_c, q_b)
            circuit.cx(q_c, q_a)
            circuit.ccx(q_a, q_b, q_c)

        def unmaj(circuit, q_a, q_b, q_c):
            '''
            unmajority
            '''
            circuit.ccx(q_a, q_b, q_c)
            circuit.cx(q_c, q_a)
            circuit.cx(q_a, q_b)

        def adder(circuit, c_in, q_a, q_b, c_out, qubits):
            '''
            adder
            '''
            # pylint: disable=too-many-arguments
            majority(circuit, c_in[0], q_b[0], q_a[0])
            for i in range(qubits - 1):
                majority(circuit, q_a[i], q_b[i + 1], q_a[i + 1])

            circuit.cx(q_a[qubits - 1], c_out[0])

            for i in range(qubits - 1)[::-1]:
                unmaj(circuit, q_a[i], q_b[i + 1], q_a[i + 1])
            unmaj(circuit, c_in[0], q_b[0], q_a[0])

        if 'add' not in self.__qp.get_circuit_names():
            [c_in, q_a, q_b, c_out] = map(self.__qp.get_quantum_register,
                                          ["cin", "qa", "qb", "cout"])
            ans = self.__qp.get_classical_register('ans')
            qadder = self.__qp.create_circuit("qadd",
                                              [c_in, q_a, q_b, c_out],
                                              [ans])
            adder(qadder, c_in, q_a, q_b, c_out, self.qubits)

        return 'add' in self.__qp.get_circuit_names()

    def _create_circuit_qsub(self):
        circuit_names = self.__qp.get_circuit_names()
        if 'qsub' not in circuit_names:
            if 'qadd' not in circuit_names:
                self._create_circuit_qadd()

            # subtractor circuit
            self.__qp.add_circuit('qsub', self.__qp.get_circuit('qadd'))
            qsubtractor = self.__qp.get_circuit('qsub')
            qsubtractor.reverse()
        return 'qsub' in self.__qp.get_circuit_names()

    def _qadd(self, input_a, input_b=None, subtract=False, observe=False):
        # pylint: disable=too-many-locals

        def measure(circuit, q_b, c_out, ans):
            '''
            measure
            '''
            circuit.barrier()
            for i in range(self.qubits):
                circuit.measure(q_b[i], ans[i])
            circuit.measure(c_out[0], ans[self.qubits])

        def char2q(circuit, cbit, qbit):
            '''
            char2q
            '''
            if cbit == '1':
                circuit.x(qbit)
            elif cbit == 'H':
                circuit.h(qbit)
                self.shots = 5 * (2**self.qubits)

        def input_state(circuit, input_a, input_b=None):
            '''
            input state
            '''
            input_a = input_a[::-1]
            for i in range(self.qubits):
                char2q(circuit, input_a[i], q_a[i])

            if input_b is not None:
                input_b = input_b[::-1]
                for i in range(self.qubits):
                    char2q(circuit, input_b[i], q_b[i])

        def reset_input(circuit, c_in, q_a, c_out):
            '''
            reset input
            '''
            circuit.reset(c_in)
            circuit.reset(c_out)
            for i in range(self.qubits):
                circuit.reset(q_a[i])

        # get registers
        [c_in, q_a, q_b, c_out] = map(self.__qp.get_quantum_register,
                                      ["cin", "qa", "qb", "cout"])
        ans = self.__qp.get_classical_register('ans')
        qcirc = self.__qp.get_circuit('qcirc')

        self._progress('2',
                       'Define input state ({})'
                       .format('QADD' if subtract is False else 'QSUB'))
        if input_b is not None:
            if subtract is True:
                # subtract
                input_state(qcirc, input_b, input_a)
            else:
                # add
                input_state(qcirc, input_a, input_b)
        else:
            reset_input(qcirc, c_in, q_a, c_out)
            input_state(qcirc, input_a)

        self._progress('3',
                       'Define quantum circuit ({})'
                       .format('QADD' if subtract is False else 'QSUB'))
        if subtract is True:
            self._create_circuit_qsub()
            qcirc.extend(self.__qp.get_circuit('qsub'))
        else:
            self._create_circuit_qadd()
            qcirc.extend(self.__qp.get_circuit('qadd'))

        if observe is True:
            measure(qcirc, q_b, c_out, ans)

    def _qsub(self, input_a, input_b=None, observe=False):
        self._qadd(input_a, input_b, subtract=True, observe=observe)

    def _qope(self, input_a, operator, input_b=None, observe=False):
        if operator == '+':
            return self._qadd(input_a, input_b, observe=observe)
        elif operator == '-':
            return self._qsub(input_a, input_b, observe=observe)
        return None

    def _compile(self, name, cross_backend=None, print_qasm=False):
        self._progress('4', 'Compile quantum circuit')

        coupling_map = None
        if cross_backend is not None:
            backend_conf = self.__qp.get_backend_configuration(cross_backend)
            coupling_map = backend_conf.get('coupling_map', None)
            if coupling_map is None:
                sys.stdout.write('backend: {} coupling_map not found'
                                 .format(cross_backend))

        qobj = self.__qp.compile([name],
                                 backend=self.backend,
                                 shots=self.shots,
                                 seed=1,
                                 coupling_map=coupling_map)

        if print_qasm is True:
            sys.stdout.write(self.__qp.get_compiled_qasm(qobj, 'qcirc'))
            sys.stdout.flush()
        return qobj

    def _run(self, qobj):
        self._progress('5', 'Run quantum circuit (wait for answer)')
        result = self.__qp.run(qobj, wait=5, timeout=100000)
        return result

    def _run_async(self, qobj):
        '''
        _run_async
        '''
        self._progress('5', 'Run quantum circuit')
        self.wait = True

        def async_result(result):
            '''
            async call back
            '''
            self.wait = False
            self.last = self.result_parse(result)

        self.__qp.run_async(qobj,
                            wait=5, timeout=100000, callback=async_result)

    def _is_regular_number(self, numstring, base):
        '''
        returns input binary format string or None.
        '''
        if base == 'bin':
            binstring = numstring
        elif base == 'dec':
            if numstring == 'H':
                binstring = 'H'*self.qubits
            else:
                binstring = format(int(numstring), "0{}b".format(self.qubits))

        if len(binstring) != self.qubits:
            return None

        return binstring

    def get_seq(self, text, base='dec'):
        '''
        convert seq and check it
        if text is invalid, return the list of length 0.
        '''
        operators = u'(\\+|\\-)'
        seq = re.split(operators, text)

        # length check
        if len(seq) % 2 == 0 or len(seq) == 1:
            return []

        # regex
        if base == 'bin':
            regex = re.compile(r'[01H]+')
        else:
            regex = re.compile(r'(^(?!.H)[0-9]+|H)')

        for i in range(0, len(seq), 2):
            match = regex.match(seq[i])
            if match is None:
                return []
            num = match.group(0)
            seq[i] = self._is_regular_number(num, base)

            if seq[i] is None:
                return []

        return seq

    def result_parse(self, result):
        '''
        result_parse
        '''
        data = result.get_data("qcirc")
        sys.stdout.write("job id: {0}\n".format(result.get_job_id()))
        sys.stdout.write("raw result: {0}\n".format(data))
        sys.stdout.write("{:=^40}\n".format("answer"))

        counts = data['counts']
        sortedcounts = sorted(counts.items(),
                              key=lambda x: -x[1])

        sortedans = []
        for count in sortedcounts:
            if count[0][0] == '1':
                ans = 'OR'
            else:
                ans = str(int(count[0][-self.qubits:], 2))
            sortedans.append(ans)
            sys.stdout.write('Dec: {0:>2} Bin: {1} Count: {2} \n'
                             .format(ans, str(count[0]), str(count[1])))

        sys.stdout.write('{0:d} answer{1}\n'
                         .format(len(sortedans),
                                 '' if len(sortedans) == 1 else 's'))
        sys.stdout.write("{:=^40}\n".format(""))
        if 'time' in data:
            sys.stdout.write("time: {0:<3} sec\n".format(data['time']))
        sys.stdout.write("All process done.\n")
        sys.stdout.flush()

        uniqanswer = sorted(set(sortedans), key=sortedans.index)

        ans = ",".join(uniqanswer)

        return [str(result), ans]

    def exec_calc(self, text, base='dec', wait_result=False):
        '''
        exec_calc
        '''
        seq = self.get_seq(text, base)
        print('QC seq:', seq)
        if seq == []:
            return ["Syntax error", None]

        # fail message
        fail_msg = None

        try:
            self._init_circuit()
            numbers = seq[0::2]     # slice even index
            i = 1
            observe = False
            for oper in seq[1::2]:  # slice odd index
                if i == len(numbers) - 1:
                    observe = True
                if i == 1:
                    self._qope(numbers[0], oper, numbers[1], observe=observe)
                else:
                    self._qope(numbers[i], oper, observe=observe)
                i = i + 1

            qobj = self._compile('qcirc')

            if wait_result is True:
                [status, ans] = self.result_parse(self._run(qobj))
            else:
                self._run_async(qobj)
                [status, ans] = [
                    'Wait. Calculating on {0}'.format(self.backend),
                    '...'
                    ]

        except QISKitError as ex:
            fail_msg = ('There was an error in the circuit!. Error = {}\n'
                        .format(ex))
        except RegisterSizeError as ex:
            fail_msg = ('Error in the number of registers!. Error = {}\n'
                        .format(ex))

        if fail_msg is not None:
            sys.stdout.write(fail_msg)
            sys.stdout.flush()
            return ["FAIL", None]

        return [status, ans]
Esempio n. 10
0
def create_experiment(Q_program: QuantumProgram, inputA: str, inputB: str,
                      name: str, backend: str) -> Tuple[str, str]:
    # qubit mapping
    index_a1 = 2
    index_a2 = 4
    index_b1 = 0
    index_b2 = 3

    # input build
    q = Q_program.create_quantum_register("q", 5)
    ans = Q_program.create_classical_register("ans", 5)
    qc: QuantumCircuit = Q_program.create_circuit(name, [q], [ans])

    a1 = q[index_a1]
    a2 = q[index_a2]
    b1 = q[index_b1]
    b2 = q[index_b2]
    expected = list("00000")
    expected_result = (int(a, 2) + int(b, 2)) % 4
    expected[index_a1] = str(int(expected_result / 2) % 2)
    expected[index_a2] = str(int(expected_result / 1) % 2)
    expected[index_b1] = b[2]
    expected[index_b2] = b[3]
    expected = "".join(reversed(expected))
    print("Job: %s + %s = %s. Expecting answer: %s" %
          (a, b, bin(expected_result), expected))

    # circuit setup
    if a[2] == "1":
        print("a1 setting to 1")
        qc.x(a1)
    if a[3] == "1":
        print("a2 setting to 1")
        qc.x(a2)
    if b[2] == "1":
        print("b1 setting to 1")
        qc.x(b1)
    if b[3] == "1":
        print("b2 setting to 1")
        qc.x(b2)

    # circuit algorithm
    qc.h(a1)
    qc.crk(2, a1, a2, cnot_back=True)
    qc.h(a2)

    qc.crk(1, a2, b2)
    qc.crk(2, a1, b2)
    qc.crk(1, a1, b1, cnot_back=True)

    qc.h(a2)
    qc.crk(-2, a1, a2, cnot_back=True)
    qc.h(a1)

    qc.measure(q, ans)

    # job parameters
    processor = "ibmqx4"
    print("Compile & Run manually for '%s' using backend '%s':" %
          (processor, backend))

    qobj_id = "@%s: %s(%s,%s) -> %s" % (
        datetime.now().strftime('%Y-%m-%d %H:%M:%S'), name, a, b, expected)

    conf = Q_program.get_backend_configuration(processor, list_format=False)
    qobj = Q_program.compile(name_of_circuits=[name],
                             backend=backend,
                             shots=shots,
                             config=conf,
                             max_credits=3,
                             qobj_id=qobj_id)
    qasm = Q_program.get_compiled_qasm(qobj, name)
    measurements = list(filter(lambda r: "measure" in r, qasm.split('\n')))
    instructions = list(filter(lambda r: "measure" not in r, qasm.split('\n')))

    qasm = "\n".join(["// draper(%s,%s)->%s" % (a, b, expected)] +
                     instructions + measurements)
    return qasm, expected
Esempio n. 11
0
class MapperTest(QiskitTestCase):
    """Test the mapper."""

    def setUp(self):
        self.seed = 42
        self.qp = QuantumProgram()

    def test_mapper_overoptimization(self):
        """
        The mapper should not change the semantics of the input. An overoptimization introduced
        the issue #81: https://github.com/QISKit/qiskit-sdk-py/issues/81
        """
        self.qp.load_qasm_file(self._get_resource_path('qasm/overoptimization.qasm'), name='test')
        coupling_map = {0: [2], 1: [2], 2: [3], 3: []}
        result1 = self.qp.execute(["test"], backend="local_qasm_simulator",
                                  coupling_map=coupling_map)
        count1 = result1.get_counts("test")
        result2 = self.qp.execute(["test"], backend="local_qasm_simulator", coupling_map=None)
        count2 = result2.get_counts("test")
        self.assertEqual(count1.keys(), count2.keys(), )

    def test_math_domain_error(self):
        """
        The math library operates over floats and introduce floating point errors that should be
        avoided.
        See: https://github.com/QISKit/qiskit-sdk-py/issues/111
        """
        self.qp.load_qasm_file(self._get_resource_path('qasm/math_domain_error.qasm'), name='test')
        coupling_map = {0: [2], 1: [2], 2: [3], 3: []}
        result1 = self.qp.execute(["test"], backend="local_qasm_simulator",
                                  coupling_map=coupling_map, seed=self.seed)

        self.assertEqual(result1.get_counts("test"), {'0001': 507, '0101': 517})

    def test_optimize_1q_gates_issue159(self):
        """Test change in behavior for optimize_1q_gates that removes u1(2*pi) rotations.

        See: https://github.com/QISKit/qiskit-sdk-py/issues/159
        """
        self.qp = QuantumProgram()
        qr = self.qp.create_quantum_register('qr', 2)
        cr = self.qp.create_classical_register('cr', 2)
        qc = self.qp.create_circuit('Bell', [qr], [cr])
        qc.h(qr[0])
        qc.cx(qr[1], qr[0])
        qc.cx(qr[1], qr[0])
        qc.cx(qr[1], qr[0])
        qc.measure(qr[0], cr[0])
        qc.measure(qr[1], cr[1])
        backend = 'local_qasm_simulator'
        cmap = {1: [0], 2: [0, 1, 4], 3: [2, 4]}
        qobj = self.qp.compile(["Bell"], backend=backend, coupling_map=cmap)

        self.assertEqual(self.qp.get_compiled_qasm(qobj, "Bell"), EXPECTED_QASM_1Q_GATES_3_5)

    def test_random_parameter_circuit(self):
        """Run a circuit with randomly generated parameters."""
        self.qp.load_qasm_file(self._get_resource_path('qasm/random_n5_d5.qasm'), name='rand')
        coupling_map = {0: [1], 1: [2], 2: [3], 3: [4]}
        result1 = self.qp.execute(["rand"], backend="local_qasm_simulator",
                                  coupling_map=coupling_map, seed=self.seed)
        res = result1.get_counts("rand")
        expected_result = {'10000': 97, '00011': 24, '01000': 120, '10111': 59, '01111': 37,
                           '11010': 14, '00001': 34, '00100': 42, '10110': 41, '00010': 102,
                           '00110': 48, '10101': 19, '01101': 61, '00111': 46, '11100': 28,
                           '01100': 1, '00000': 86, '11111': 14, '11011': 9, '10010': 35,
                           '10100': 20, '01001': 21, '01011': 19, '10011': 10, '11001': 13,
                           '00101': 4, '01010': 2, '01110': 17, '11000': 1}

        self.assertEqual(res, expected_result)

    def test_symbolic_unary(self):
        """Test symbolic math in DAGBackend and optimizer with a prefix.

        See: https://github.com/QISKit/qiskit-sdk-py/issues/172
        """
        ast = qasm.Qasm(filename=self._get_resource_path(
            'qasm/issue172_unary.qasm')).parse()
        unr = unroll.Unroller(ast, backend=unroll.DAGBackend(["cx", "u1", "u2", "u3"]))
        unr.execute()
        circ = mapper.optimize_1q_gates(unr.backend.circuit)
        self.assertEqual(circ.qasm(qeflag=True), EXPECTED_QASM_SYMBOLIC_UNARY)

    def test_symbolic_binary(self):
        """Test symbolic math in DAGBackend and optimizer with a binary operation.

        See: https://github.com/QISKit/qiskit-sdk-py/issues/172
        """
        ast = qasm.Qasm(filename=self._get_resource_path(
            'qasm/issue172_binary.qasm')).parse()

        unr = unroll.Unroller(ast, backend=unroll.DAGBackend(["cx", "u1", "u2", "u3"]))
        unr.execute()
        circ = mapper.optimize_1q_gates(unr.backend.circuit)
        self.assertEqual(circ.qasm(qeflag=True), EXPECTED_QASM_SYMBOLIC_BINARY)

    def test_symbolic_extern(self):
        """Test symbolic math in DAGBackend and optimizer with an external function.

        See: https://github.com/QISKit/qiskit-sdk-py/issues/172
        """
        ast = qasm.Qasm(filename=self._get_resource_path(
            'qasm/issue172_extern.qasm')).parse()
        unr = unroll.Unroller(ast, backend=unroll.DAGBackend(["cx", "u1", "u2", "u3"]))
        unr.execute()
        circ = mapper.optimize_1q_gates(unr.backend.circuit)
        self.assertEqual(circ.qasm(qeflag=True), EXPECTED_QASM_SYMBOLIC_EXTERN)

    def test_symbolic_power(self):
        """Test symbolic math in DAGBackend and optimizer with a power (^).

        See: https://github.com/QISKit/qiskit-sdk-py/issues/172
        """
        ast = qasm.Qasm(data=QASM_SYMBOLIC_POWER).parse()
        unr = unroll.Unroller(ast, backend=unroll.DAGBackend(["cx", "u1", "u2", "u3"]))
        unr.execute()
        circ = mapper.optimize_1q_gates(unr.backend.circuit)
        self.assertEqual(circ.qasm(qeflag=True), EXPECTED_QASM_SYMBOLIC_POWER)
Esempio n. 12
0
    def create_experiment(self, qp: QuantumProgram,
                          input) -> Tuple[str, dict, str]:
        a, b = input
        qm = self.qubit_mapping
        name = self.name
        algorithm = self.algorithm
        backend = self.backend

        # qubit mapping
        if qm is None:
            index_a1 = 2
            index_a2 = 1
            index_b1 = 3
            index_b2 = 0
        else:
            index_a1 = qm["a1"]
            index_a2 = qm["a2"]
            index_b1 = qm["b1"]
            index_b2 = qm["b2"]

        # input build
        q: QuantumRegister = qp.create_quantum_register("q", 5)
        ans = qp.create_classical_register("ans", 5)
        qc: QuantumCircuit = qp.create_circuit(name, [q], [ans])

        a1: Tuple[QuantumRegister, int] = q[index_a1]
        a2: Tuple[QuantumRegister, int] = q[index_a2]
        b1: Tuple[QuantumRegister, int] = q[index_b1]
        b2: Tuple[QuantumRegister, int] = q[index_b2]
        expected = list("00000")
        expected_result = (int(a, 2) + int(b, 2)) % 4
        expected[index_a1] = str(int(expected_result / 2) % 2)
        expected[index_a2] = str(int(expected_result / 1) % 2)
        expected[index_b1] = b[2]
        expected[index_b2] = b[3]
        expected = "".join(reversed(expected))

        # circuit setup
        if a[2] == "1":
            qc.x(a1)
        if a[3] == "1":
            qc.x(a2)
        if b[2] == "1":
            qc.x(b1)
        if b[3] == "1":
            qc.x(b2)

        processor = self.backend
        conf = qp.get_backend_configuration(processor, list_format=False)
        coupling_map = conf["coupling_map"]

        algorithm(qc, a1, a2, b1, b2, coupling_map)

        qc.measure(q, ans)

        # compilation
        qobj = qp.compile(name_of_circuits=[name],
                          backend=backend,
                          config=conf,
                          max_credits=3)
        qasm = qp.get_compiled_qasm(qobj, name)
        qasm_lines = self.qasm((a, b), expected) + qasm.split("\n")

        qasm = "\n".join(filter(lambda x: len(x) > 0, qasm_lines))

        return qasm, qobj, expected
Esempio n. 13
0
 def get_compiled_qasm(self):
     if self._qobj is None:
         self.compile()
     return QuantumProgram.get_compiled_qasm(self, self._qobj,
                                             self._circuit_name)
Esempio n. 14
0
def create_experiment(Q_program: QuantumProgram,
                      a: str,
                      b: str,
                      experiment: Experiment,
                      silent=True) -> Tuple[str, dict, str]:

    qm = experiment.qubit_mapping
    name = experiment.name
    algorithm = experiment.algorithm
    backend = experiment.backend

    # qubit mapping
    if qm is None:
        index_a1 = 2
        index_a2 = 1
        index_b1 = 3
        index_b2 = 0
    else:
        index_a1 = qm["a1"]
        index_a2 = qm["a2"]
        index_b1 = qm["b1"]
        index_b2 = qm["b2"]

    # input build
    q: QuantumRegister = Q_program.create_quantum_register("q", 5)
    ans = Q_program.create_classical_register("ans", 5)
    qc: QuantumCircuit = Q_program.create_circuit(name, [q], [ans])

    a1: Tuple[QuantumRegister, int] = q[index_a1]
    a2: Tuple[QuantumRegister, int] = q[index_a2]
    b1: Tuple[QuantumRegister, int] = q[index_b1]
    b2: Tuple[QuantumRegister, int] = q[index_b2]
    expected = list("00000")
    expected_result = (int(a, 2) + int(b, 2)) % 4
    expected[index_a1] = str(int(expected_result / 2) % 2)
    expected[index_a2] = str(int(expected_result / 1) % 2)
    expected[index_b1] = b[2]
    expected[index_b2] = b[3]
    expected = "".join(reversed(expected))
    if not silent:
        print("Job: %s + %s = %s. Expecting answer: %s" %
              (a, b, bin(expected_result), expected))

    # circuit setup
    if a[2] == "1":
        if not silent: print("a1 setting to 1")
        qc.x(a1)
    if a[3] == "1":
        if not silent: print("a2 setting to 1")
        qc.x(a2)
    if b[2] == "1":
        if not silent: print("b1 setting to 1")
        qc.x(b1)
    if b[3] == "1":
        if not silent: print("b2 setting to 1")
        qc.x(b2)

    processor = "ibmqx4"
    conf = Q_program.get_backend_configuration(processor, list_format=False)
    coupling_map = conf["coupling_map"]

    algorithm(qc, a1, a2, b1, b2, coupling_map)

    qc.measure(q, ans)

    # compilation
    qobj = Q_program.compile(name_of_circuits=[name],
                             backend=backend,
                             config=conf,
                             max_credits=3)
    qasm = Q_program.get_compiled_qasm(qobj, name)
    qasm_lines = experiment.qasm((a, b), expected) + qasm.split("\n")

    qasm = "\n".join(filter(lambda x: len(x) > 0, qasm_lines))

    return qasm, qobj, expected
Esempio n. 15
0
# Insert a barrier before measurement
qc.barrier()
# Measure all of the qubits in the standard basis
for j in range(n):
    qc.measure(q[j], ans[j])
    qc.measure(r[j], ans[j + n])

###############################################################
# Set up the API and execute the program.
###############################################################
result = qp.set_api(Qconfig.APItoken, Qconfig.config["url"])
if not result:
    print("Error setting API")
    sys.exit(1)

# First version: not compiled
result = qp.execute(["swapping"], device=device, coupling_map=None, shots=1024)
print(qp.get_compiled_qasm("swapping"))
print(qp.get_counts("swapping"))

# Second version: compiled to coupling graph
result = qp.execute(["swapping"],
                    device=device,
                    coupling_map=coupling_map,
                    shots=1024)
print(qp.get_compiled_qasm("swapping"))
print(qp.get_counts("swapping"))

# Both versions should give the same distribution
Esempio n. 16
0
# quantum register for the first circuit
q_register1 = program.create_quantum_register('q_register1', 4)
c_register1 = program.create_classical_register('c_register1', 4)
# quantum register for the second circuit
q_register2 = program.create_quantum_register('q_register2', 4)
c_register2 = program.create_classical_register('c_register2', 4)

# making the first circuits
circuit1 = program.create_circuit('GHZ', [q_register1], [c_register1])
circuit2 = program.create_circuit('superpostion', [q_register2], [c_register2])
circuit1.h(q_register1[0])
circuit1.cx(q_register1[0], q_register1[1])
circuit1.cx(q_register1[1], q_register1[2])
circuit1.cx(q_register1[2], q_register1[3])
for i in range(4):
    circuit1.measure(q_register1[i], c_register1[i])

# making the second circuits
circuit2.h(q_register2)
for i in range(2):
    circuit2.measure(q_register2[i], c_register2[i])
# printing the circuits
print(program.get_qasm('GHZ'))
print(program.get_qasm('superpostion'))

object = program.compile(['GHZ','superpostion'], backend='local_qasm_simulator')
program.get_execution_list(object, verbose=True)

print(program.get_compiled_configuration(object, 'GHZ'))
print(program.get_compiled_qasm(object, 'GHZ'))
Esempio n. 17
0
qc.measure(q[1], c1[0])

# Apply a correction
qc.z(q[2]).c_if(c0, 1)
qc.x(q[2]).c_if(c1, 1)
qc.measure(q[2], c2[0])

###############################################################
# Set up the API and execute the program.
###############################################################
result = qp.set_api(Qconfig.APItoken, Qconfig.config["url"])
if not result:
    print("Error setting API")
    sys.exit(1)

# Experiment does not support feedback, so we use the simulator

# First version: not compiled
result = qp.execute(["teleport"], device=device, coupling_map=None, shots=1024)
print(qp.get_counts("teleport"))

# Second version: compiled to qx5qv2 coupling graph
result = qp.execute(["teleport"],
                    device=device,
                    coupling_map=coupling_map,
                    shots=1024)
print(qp.get_compiled_qasm("teleport"))
print(qp.get_counts("teleport"))

# Both versions should give the same distribution
Esempio n. 18
0
class MapperTest(QiskitTestCase):
    """Test the mapper."""

    def setUp(self):
        self.seed = 42
        self.qp = QuantumProgram()

    def test_mapper_overoptimization(self):
        """
        The mapper should not change the semantics of the input. An overoptimization introduced
        the issue #81: https://github.com/QISKit/qiskit-sdk-py/issues/81
        """
        self.qp.load_qasm_file(self._get_resource_path('qasm/overoptimization.qasm'), name='test')
        coupling_map = [[0, 2], [1, 2], [2, 3]]
        result1 = self.qp.execute(["test"], backend="local_qasm_simulator",
                                  coupling_map=coupling_map)
        count1 = result1.get_counts("test")
        result2 = self.qp.execute(["test"], backend="local_qasm_simulator", coupling_map=None)
        count2 = result2.get_counts("test")
        self.assertEqual(count1.keys(), count2.keys(), )

    def test_math_domain_error(self):
        """
        The math library operates over floats and introduce floating point errors that should be
        avoided.
        See: https://github.com/QISKit/qiskit-sdk-py/issues/111
        """
        self.qp.load_qasm_file(self._get_resource_path('qasm/math_domain_error.qasm'), name='test')
        coupling_map = [[0, 2], [1, 2], [2, 3]]
        shots = 2000
        result = self.qp.execute("test", backend="local_qasm_simulator",
                                 coupling_map=coupling_map,
                                 seed=self.seed, shots=shots)
        counts = result.get_counts("test")
        target = {'0001': shots / 2, '0101':  shots / 2}
        threshold = 0.04 * shots
        self.assertDictAlmostEqual(counts, target, threshold)

    def test_optimize_1q_gates_issue159(self):
        """Test change in behavior for optimize_1q_gates that removes u1(2*pi) rotations.

        See: https://github.com/QISKit/qiskit-sdk-py/issues/159
        """
        self.qp = QuantumProgram()
        qr = self.qp.create_quantum_register('qr', 2)
        cr = self.qp.create_classical_register('cr', 2)
        qc = self.qp.create_circuit('Bell', [qr], [cr])
        qc.h(qr[0])
        qc.cx(qr[1], qr[0])
        qc.cx(qr[1], qr[0])
        qc.cx(qr[1], qr[0])
        qc.measure(qr[0], cr[0])
        qc.measure(qr[1], cr[1])
        backend = 'local_qasm_simulator'
        coupling_map = [[1, 0], [2, 0], [2, 1], [2, 4], [3, 2], [3, 4]]
        initial_layout = {('qr', 0): ('q', 1), ('qr', 1): ('q', 0)}
        qobj = self.qp.compile(["Bell"], backend=backend,
                               initial_layout=initial_layout, coupling_map=coupling_map)

        self.assertEqual(self.qp.get_compiled_qasm(qobj, "Bell"), EXPECTED_QASM_1Q_GATES_3_5)

    def test_random_parameter_circuit(self):
        """Run a circuit with randomly generated parameters."""
        self.qp.load_qasm_file(self._get_resource_path('qasm/random_n5_d5.qasm'), name='rand')
        coupling_map = [[0, 1], [1, 2], [2, 3], [3, 4]]
        shots = 1024
        result1 = self.qp.execute(["rand"], backend="local_qasm_simulator",
                                  coupling_map=coupling_map, shots=shots, seed=self.seed)
        counts = result1.get_counts("rand")
        expected_probs = {
            '00000': 0.079239867254200971,
            '00001': 0.032859032998526903,
            '00010': 0.10752610993531816,
            '00011': 0.018818532050952699,
            '00100': 0.054830807251011054,
            '00101': 0.0034141983951965164,
            '00110': 0.041649309748902276,
            '00111': 0.039967731207338125,
            '01000': 0.10516937819949743,
            '01001': 0.026635620063700002,
            '01010': 0.0053475143548793866,
            '01011': 0.01940513314416064,
            '01100': 0.0044028405481225047,
            '01101': 0.057524760052126644,
            '01110': 0.010795354134597078,
            '01111': 0.026491296821535528,
            '10000': 0.094827455395274859,
            '10001': 0.0008373965072688836,
            '10010': 0.029082297894094441,
            '10011': 0.012386622870598416,
            '10100': 0.018739140061148799,
            '10101': 0.01367656456536896,
            '10110': 0.039184170706009248,
            '10111': 0.062339335178438288,
            '11000': 0.00293674365989009,
            '11001': 0.012848433960739968,
            '11010': 0.018472497159499782,
            '11011': 0.0088903691234912003,
            '11100': 0.031305389080034329,
            '11101': 0.0004788556283690458,
            '11110': 0.002232419390471667,
            '11111': 0.017684822659235985
        }
        target = {key: shots * val for key, val in expected_probs.items()}
        threshold = 0.04 * shots
        self.assertDictAlmostEqual(counts, target, threshold)

    def test_symbolic_unary(self):
        """Test symbolic math in DAGBackend and optimizer with a prefix.

        See: https://github.com/QISKit/qiskit-sdk-py/issues/172
        """
        ast = qasm.Qasm(filename=self._get_resource_path(
            'qasm/issue172_unary.qasm')).parse()
        unr = unroll.Unroller(ast, backend=unroll.DAGBackend(["cx", "u1", "u2", "u3"]))
        unr.execute()
        circ = mapper.optimize_1q_gates(unr.backend.circuit)
        self.assertEqual(circ.qasm(qeflag=True), EXPECTED_QASM_SYMBOLIC_UNARY)

    def test_symbolic_binary(self):
        """Test symbolic math in DAGBackend and optimizer with a binary operation.

        See: https://github.com/QISKit/qiskit-sdk-py/issues/172
        """
        ast = qasm.Qasm(filename=self._get_resource_path(
            'qasm/issue172_binary.qasm')).parse()

        unr = unroll.Unroller(ast, backend=unroll.DAGBackend(["cx", "u1", "u2", "u3"]))
        unr.execute()
        circ = mapper.optimize_1q_gates(unr.backend.circuit)
        self.assertEqual(circ.qasm(qeflag=True), EXPECTED_QASM_SYMBOLIC_BINARY)

    def test_symbolic_extern(self):
        """Test symbolic math in DAGBackend and optimizer with an external function.

        See: https://github.com/QISKit/qiskit-sdk-py/issues/172
        """
        ast = qasm.Qasm(filename=self._get_resource_path(
            'qasm/issue172_extern.qasm')).parse()
        unr = unroll.Unroller(ast, backend=unroll.DAGBackend(["cx", "u1", "u2", "u3"]))
        unr.execute()
        circ = mapper.optimize_1q_gates(unr.backend.circuit)
        self.assertEqual(circ.qasm(qeflag=True), EXPECTED_QASM_SYMBOLIC_EXTERN)

    def test_symbolic_power(self):
        """Test symbolic math in DAGBackend and optimizer with a power (^).

        See: https://github.com/QISKit/qiskit-sdk-py/issues/172
        """
        ast = qasm.Qasm(data=QASM_SYMBOLIC_POWER).parse()
        unr = unroll.Unroller(ast, backend=unroll.DAGBackend(["cx", "u1", "u2", "u3"]))
        unr.execute()
        circ = mapper.optimize_1q_gates(unr.backend.circuit)
        self.assertEqual(circ.qasm(qeflag=True), EXPECTED_QASM_SYMBOLIC_POWER)

    def test_already_mapped(self):
        """Test that if the circuit already matches the backend topology, it is not remapped.

        See: https://github.com/QISKit/qiskit-sdk-py/issues/342
        """
        self.qp = QuantumProgram()
        qr = self.qp.create_quantum_register('qr', 16)
        cr = self.qp.create_classical_register('cr', 16)
        qc = self.qp.create_circuit('native_cx', [qr], [cr])
        qc.cx(qr[3], qr[14])
        qc.cx(qr[5], qr[4])
        qc.h(qr[9])
        qc.cx(qr[9], qr[8])
        qc.x(qr[11])
        qc.cx(qr[3], qr[4])
        qc.cx(qr[12], qr[11])
        qc.cx(qr[13], qr[4])
        for j in range(16):
            qc.measure(qr[j], cr[j])
        backend = 'local_qasm_simulator'
        coupling_map = [[1, 0], [1, 2], [2, 3], [3, 4], [3, 14], [5, 4],
                        [6, 5], [6, 7], [6, 11], [7, 10], [8, 7], [9, 8],
                        [9, 10], [11, 10], [12, 5], [12, 11], [12, 13],
                        [13, 4], [13, 14], [15, 0], [15, 2], [15, 14]]
        qobj = self.qp.compile(["native_cx"], backend=backend, coupling_map=coupling_map)
        cx_qubits = [x["qubits"]
                     for x in qobj["circuits"][0]["compiled_circuit"]["operations"]
                     if x["name"] == "cx"]

        self.assertEqual(sorted(cx_qubits), [[3, 4], [3, 14], [5, 4], [9, 8], [12, 11], [13, 4]])
Esempio n. 19
0
def Grover():
    if sys.version_info < (3, 5):
        raise Exception('Please use Python version 3.5 or greater.')

    #Create an object
    qp = QuantumProgram()
    backend = 'local_qasm_simulator'
    # backend = 'ibmqx4'
    max_credits = 15

    QX_TOKEN = "ee6100e19629678494bd4c9f4f0f3dc3038fe389b08eee456b8a8be280e08884f6b6228825afa60dda60bf7ee5995ce9e5ae6473f31137a0e94780669bce9707"
    QX_URL = "https://quantumexperience.ng.bluemix.net/api"

    # Set up the API and execute the program.

    # qp.set_api(QX_TOKEN, QX_URL)

    # quantum register for the circuit(3->5)
    q1 = qp.create_quantum_register('q1', 5)
    c1 = qp.create_classical_register('c1', 5)

    # making the circuit
    qc1 = qp.create_circuit('Grover', [q1], [c1])

    # line one
    qc1.x(q1[0])

    # line two
    qc1.h(q1[0])
    qc1.h(q1[1])
    qc1.h(q1[2])

    # line three
    qc1.x(q1[0])
    qc1.x(q1[1])

    # line four
    qc1.ccx(q1[2], q1[1], q1[0])

    qc1.x(q1[2])
    # qc1.x(q1[1])

    # line five
    qc1.h(q1[2])
    qc1.h(q1[1])

    # line six
    qc1.x(q1[2])
    qc1.x(q1[1])

    # line seven
    qc1.h(q1[1])

    # line eight
    qc1.cx(q1[2], q1[1])

    # line nine
    qc1.h(q1[1])

    # line ten
    qc1.x(q1[2])
    qc1.x(q1[1])

    # line eleven
    qc1.h(q1[0])
    qc1.h(q1[1])
    qc1.h(q1[2])

    # Measure
    for i in range(5):
        qc1.measure(q1[i], c1[i])

    # printing the circuits
    print(qp.get_qasm('Grover'))
    qobj = qp.compile('Grover', backend=backend, shots=1000, max_credits=15)
    qp.get_execution_list(qobj)
    qp.get_execution_list(qobj, verbose=True)
    qp.get_compiled_configuration(qobj, 'Grover')

    #new
    result = qp.execute('Grover', backend=backend, shots=1000, max_credits=15)

    #print result:
    print(qp.get_compiled_qasm(qobj, 'Grover'))

    #print info:
    #print(api.backend_status(backend))
    #print(api.backend_parameters(backend))

    #new
    # print(result)
    # print(result.get_data("Grover"))

    #Record information in text.txt(Create text.txt file in your repository)

    res = result.get_data("Grover")
    quasm = qp.get_qasm('Grover')
    b = ascii(res)
    c = ascii(quasm)
    with open('Fourth(111).txt', 'w') as ouf:
        ouf.write('\n' + b)
Esempio n. 20
0
# Print the QASM code to actually execute
# (This QASM code is generated by qiskit)
print("\nQASM Code to be executed by the local_qasm_simulator:\n")
print(qft3.qasm())

# Simulate the execution of the qft3 circuit
simulate = Q_program.execute(["qft3"], backend="local_qasm_simulator", shots=1024)

# Print the result of the simulation
print("Simulation Result:")
print(simulate.get_counts("qft3"))
## Plot a histogram of the results
#plot_histogram(simulate.get_counts("qft3"))

# Determine QASM code needed for 'real' ibmqx4 machine.
# First, get the ibmqx4 coupling map:
ibmqx4_backend = Q_program.get_backend_configuration('ibmqx4')
ibmqx4_coupling = ibmqx4_backend['coupling_map']
# Second, compile the program with ibmqx4_coupling:
qobj=Q_program.compile(["qft3"], backend="local_qasm_simulator", coupling_map=ibmqx4_coupling)
# Last, get the new QASM source, and print it:
QASM_source = Q_program.get_compiled_qasm(qobj,'qft3')
print("\nQASM Code needed for real ibmqx4:\n")
print(QASM_source)

# How to run on a real ibmqx4 machine.
if real_run:
    run = Q_program.execute(["qft3"], backend="ibmqx4", coupling_map=ibmqx4_coupling, shots=1024, max_credits=3, wait=10, timeout=240)
    plot_histogram(run.get_counts("qft3"))