Пример #1
0
    def test_run_program_map(self):
        """Test run_program_map.

        If all correct should return 10010.
        """
        QP_program = QuantumProgram()
        QP_program.set_api(API_TOKEN, URL)
        backend = 'local_qasm_simulator'  # the backend to run on
        shots = 100  # the number of shots in the experiment.
        max_credits = 3
        coupling_map = {0: [1], 1: [2], 2: [3], 3: [4]}
        initial_layout = {
            ("q", 0): ("q", 0),
            ("q", 1): ("q", 1),
            ("q", 2): ("q", 2),
            ("q", 3): ("q", 3),
            ("q", 4): ("q", 4)
        }
        QP_program.load_qasm_file(QASM_FILE_PATH_2, name="circuit-dev")
        circuits = ["circuit-dev"]
        qobj = QP_program.compile(circuits,
                                  backend=backend,
                                  shots=shots,
                                  max_credits=max_credits,
                                  seed=65,
                                  coupling_map=coupling_map,
                                  initial_layout=initial_layout)
        result = QP_program.run(qobj)
        self.assertEqual(result.get_counts("circuit-dev"), {'10010': 100})
Пример #2
0
    def test_json_output(self):
        qp = QuantumProgram()
        qp.load_qasm_file(self.QASM_FILE_PATH, name="example")

        basis_gates = []  # unroll to base gates, change to test
        unroller = unroll.Unroller(qasm.Qasm(data=qp.get_qasm("example")).parse(),
                                   unroll.JsonBackend(basis_gates))
        circuit = unroller.execute()
        self.log.info('test_json_ouptut: %s', circuit)
Пример #3
0
    def test_json_output(self):
        qprogram = QuantumProgram()
        qprogram.load_qasm_file(self.qasm_file_path, name="example")

        basis_gates = []  # unroll to base gates, change to test
        unroller = unroll.Unroller(qasm.Qasm(data=qprogram.get_qasm("example")).parse(),
                                   unroll.JsonBackend(basis_gates))
        circuit = unroller.execute()
        self.log.info('test_json_ouptut: %s', circuit)
Пример #4
0
    def test_json_output(self):
        seed = 88
        qp = QuantumProgram()
        qp.load_qasm_file(self.QASM_FILE_PATH, name="example")

        basis_gates = []  # unroll to base gates, change to test
        unroller = unroll.Unroller(
            qasm.Qasm(data=qp.get_qasm("example")).parse(),
            unroll.JsonBackend(basis_gates))
        circuit = unroller.execute()
        logging.info('test_json_ouptut: {0}'.format(circuit))
class LocalQasmSimulatorTest(QiskitTestCase):
    """Test local qasm simulator."""
    def setUp(self):
        self.seed = 88
        self.qasm_filename = self._get_resource_path('qasm/simple.qasm')
        self.qp = QuantumProgram()
        self.qp.load_qasm_file(self.qasm_filename, name='example')
        basis_gates = []  # unroll to base gates
        unroller = unroll.Unroller(
            qasm.Qasm(data=self.qp.get_qasm('example')).parse(),
            unroll.JsonBackend(basis_gates))
        circuit = unroller.execute()
        circuit_config = {
            'coupling_map': None,
            'basis_gates': 'u1,u2,u3,cx,id',
            'layout': None,
            'seed': self.seed
        }
        resources = {'max_credits': 3, 'wait': 5, 'timeout': 120}
        self.qobj = {
            'id':
            'test_sim_single_shot',
            'config': {
                'max_credits': resources['max_credits'],
                'shots': 1024,
                'backend': 'local_sympy_qasm_simulator',
            },
            'circuits': [{
                'name': 'test',
                'compiled_circuit': circuit,
                'compiled_circuit_qasm': None,
                'config': circuit_config
            }]
        }
        self.q_job = QuantumJob(self.qobj,
                                backend='local_sympy_qasm_simulator',
                                circuit_config=circuit_config,
                                seed=self.seed,
                                resources=resources,
                                preformatted=True)

    def test_qasm_simulator(self):
        """Test data counts output for single circuit run against reference."""
        result = SympyQasmSimulator().run(self.q_job)
        actual = result.get_data('test')['quantum_state']
        self.assertEqual(result.get_status(), 'COMPLETED')
        self.assertEqual(actual[0], sqrt(2) / 2)
        self.assertEqual(actual[1], 0)
        self.assertEqual(actual[2], 0)
        self.assertEqual(actual[3], sqrt(2) / 2)
Пример #6
0
def use_sympy_backends():
    qprogram = QuantumProgram()
    current_dir = os.path.dirname(os.path.realpath(__file__))
    qasm_file = current_dir + "/../qasm/simple.qasm"
    qasm_circuit = qprogram.load_qasm_file(qasm_file)
    print("analyzing: " + qasm_file)
    print(qprogram.get_qasm(qasm_circuit))

    # sympy statevector simulator
    backend = 'local_sympy_qasm_simulator'
    result = qprogram.execute([qasm_circuit],
                              backend=backend,
                              shots=1,
                              timeout=300)
    print("final quantum amplitude vector: ")
    print(result.get_data(qasm_circuit)['quantum_state'])

    # sympy unitary simulator
    backend = 'local_sympy_unitary_simulator'
    result = qprogram.execute([qasm_circuit],
                              backend=backend,
                              shots=1,
                              timeout=300)
    print("\nunitary matrix of the circuit: ")
    print(result.get_data(qasm_circuit)['unitary'])
Пример #7
0
class MapperTest(QiskitTestCase):
    """Test the mapper."""
    def setUp(self):
        self.seed = 42
        self.qp = QuantumProgram()

    def tearDown(self):
        pass

    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 avoid
        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
        })
class StatevectorSimulatorSympyTest(QiskitTestCase):
    """Test local statevector simulator."""

    def setUp(self):
        self.qasm_filename = self._get_resource_path('qasm/simple.qasm')
        self.qp = QuantumProgram()
        self.qp.load_qasm_file(self.qasm_filename, name='example')
        basis_gates = []  # unroll to base gates
        unroller = unroll.Unroller(
            qasm.Qasm(data=self.qp.get_qasm('example')).parse(),
            unroll.JsonBackend(basis_gates))
        circuit = unroller.execute()
        circuit_config = {'coupling_map': None,
                          'basis_gates': 'u1,u2,u3,cx,id',
                          'layout': None}
        resources = {'max_credits': 3}
        self.qobj = {'id': 'test_sim_single_shot',
                     'config': {
                         'max_credits': resources['max_credits'],
                         'shots': 1024,
                         'backend_name': 'local_statevector_simulator_sympy',
                     },
                     'circuits': [
                         {
                             'name': 'test',
                             'compiled_circuit': circuit,
                             'compiled_circuit_qasm': None,
                             'config': circuit_config
                         }
                     ]}
        self.q_job = QuantumJob(self.qobj,
                                backend=StatevectorSimulatorSympy(),
                                circuit_config=circuit_config,
                                resources=resources,
                                preformatted=True)

    def test_statevector_simulator_sympy(self):
        """Test data counts output for single circuit run against reference."""
        result = StatevectorSimulatorSympy().run(self.q_job).result()
        actual = result.get_data('test')['statevector']
        self.assertEqual(result.get_status(), 'COMPLETED')
        self.assertEqual(actual[0], sqrt(2)/2)
        self.assertEqual(actual[1], 0)
        self.assertEqual(actual[2], 0)
        self.assertEqual(actual[3], sqrt(2)/2)
    def test_execute_program_map(self):
        """Test execute_program_map.

        If all correct should return 10010.
        """
        QP_program = QuantumProgram()
        QP_program.set_api(API_TOKEN, URL)
        backend = 'local_qasm_simulator'  # the backend to run on
        shots = 100  # the number of shots in the experiment.
        max_credits = 3
        coupling_map = {0: [1], 1: [2], 2: [3], 3: [4]}
        initial_layout = {("q", 0): ("q", 0), ("q", 1): ("q", 1),
                          ("q", 2): ("q", 2), ("q", 3): ("q", 3),
                          ("q", 4): ("q", 4)}
        QP_program.load_qasm_file(QASM_FILE_PATH_2, "circuit-dev")
        circuits = ["circuit-dev"]
        result = QP_program.execute(circuits, backend=backend, shots=shots,
                                    max_credits=max_credits,
                                    coupling_map=coupling_map,
                                    initial_layout=initial_layout, seed=5455)
        self.assertEqual(result.get_counts("circuit-dev"), {'10010': 100})
    def test_load_qasm_file(self):
        """Test load_qasm_file and get_circuit.

        If all is correct we should get the qasm file loaded in QASM_FILE_PATH

        Previusly:
            Libraries:
                from qiskit import QuantumProgram
        """
        QP_program = QuantumProgram()
        name = QP_program.load_qasm_file(QASM_FILE_PATH, name="",
                                         verbose=False)
        result = QP_program.get_circuit(name)
        to_check = result.qasm()
        # print(to_check)
        self.assertEqual(len(to_check), 554)
    def test_load_qasm_file(self):
        """Test load_qasm_file and get_circuit.

        If all is correct we should get the qasm file loaded in QASM_FILE_PATH

        Previusly:
            Libraries:
                from qiskit import QuantumProgram
        """
        QP_program = QuantumProgram()
        name = QP_program.load_qasm_file(QASM_FILE_PATH, name="",
                                         verbose=False)
        result = QP_program.get_circuit(name)
        to_check = result.qasm()
        # print(to_check)
        self.assertEqual(len(to_check), 554)
Пример #12
0
def use_sympy_backends():
    qprogram = QuantumProgram()
    current_dir = os.path.dirname(os.path.realpath(__file__))
    qasm_file = current_dir + "/../qasm/simple.qasm"
    qasm_circuit = qprogram.load_qasm_file(qasm_file)
    print("analyzing: " + qasm_file)
    print(qprogram.get_qasm(qasm_circuit))
    
    # sympy statevector simulator
    backend = 'local_statevector_simulator_sympy'
    result = qprogram.execute([qasm_circuit], backend=backend, shots=1, timeout=300)
    print("final quantum amplitude vector: ")
    print(result.get_data(qasm_circuit)['statevector'])

    # sympy unitary simulator
    backend = 'local_unitary_simulator_sympy'
    result = qprogram.execute([qasm_circuit], backend=backend, shots=1, timeout=300)
    print("\nunitary matrix of the circuit: ")
    print(result.get_data(qasm_circuit)['unitary'])
Пример #13
0
def execute(argv, verbose=False):
    from qiskit import QuantumProgram
    # Create the quantum program
    qp = QuantumProgram()

    # Load from filename
    circuit = qp.load_qasm_file(filename)

    # Get qasm source
    source = qp.get_qasm(circuit)
    if verbose:
        print(source)

    # Compile and run
    backend = 'local_qasm_simulator'
    qobj = qp.compile([circuit], backend)  # Compile your program
    result = qp.run(qobj, wait=2, timeout=240)

    if verbose:
        print(result)

    print(result.get_counts(circuit))
Пример #14
0
class TestLocalQasmSimulatorPy(QiskitTestCase):
    """Test local_qasm_simulator_py."""
    @classmethod
    def setUpClass(cls):
        super().setUpClass()
        if do_profiling:
            cls.pdf = PdfPages(cls.moduleName + '.pdf')

    @classmethod
    def tearDownClass(cls):
        if do_profiling:
            cls.pdf.close()

    def setUp(self):
        self.seed = 88
        self.qasm_filename = self._get_resource_path('qasm/example.qasm')
        self.qp = QuantumProgram()
        self.qp.load_qasm_file(self.qasm_filename, name='example')
        basis_gates = []  # unroll to base gates
        unroller = unroll.Unroller(
            qasm.Qasm(data=self.qp.get_qasm('example')).parse(),
            unroll.JsonBackend(basis_gates))
        circuit = unroller.execute()
        circuit_config = {
            'coupling_map': None,
            'basis_gates': 'u1,u2,u3,cx,id',
            'layout': None,
            'seed': self.seed
        }
        resources = {'max_credits': 3}
        self.qobj = {
            'id':
            'test_sim_single_shot',
            'config': {
                'max_credits': resources['max_credits'],
                'shots': 1024,
                'backend_name': 'local_qasm_simulator_py',
            },
            'circuits': [{
                'name': 'test',
                'compiled_circuit': circuit,
                'compiled_circuit_qasm': None,
                'config': circuit_config
            }]
        }
        self.q_job = QuantumJob(self.qobj,
                                backend=QasmSimulatorPy(),
                                circuit_config=circuit_config,
                                seed=self.seed,
                                resources=resources,
                                preformatted=True)

    def tearDown(self):
        pass

    def test_qasm_simulator_single_shot(self):
        """Test single shot run."""
        shots = 1
        self.qobj['config']['shots'] = shots
        result = QasmSimulatorPy().run(self.q_job).result()
        self.assertEqual(result.get_status(), 'COMPLETED')

    def test_qasm_simulator(self):
        """Test data counts output for single circuit run against reference."""
        result = QasmSimulatorPy().run(self.q_job).result()
        shots = 1024
        threshold = 0.04 * shots
        counts = result.get_counts('test')
        target = {
            '100 100': shots / 8,
            '011 011': shots / 8,
            '101 101': shots / 8,
            '111 111': shots / 8,
            '000 000': shots / 8,
            '010 010': shots / 8,
            '110 110': shots / 8,
            '001 001': shots / 8
        }
        self.assertDictAlmostEqual(counts, target, threshold)

    def test_if_statement(self):
        self.log.info('test_if_statement_x')
        shots = 100
        max_qubits = 3
        qp = QuantumProgram()
        qr = qp.create_quantum_register('qr', max_qubits)
        cr = qp.create_classical_register('cr', max_qubits)
        circuit_if_true = qp.create_circuit('test_if_true', [qr], [cr])
        circuit_if_true.x(qr[0])
        circuit_if_true.x(qr[1])
        circuit_if_true.measure(qr[0], cr[0])
        circuit_if_true.measure(qr[1], cr[1])
        circuit_if_true.x(qr[2]).c_if(cr, 0x3)
        circuit_if_true.measure(qr[0], cr[0])
        circuit_if_true.measure(qr[1], cr[1])
        circuit_if_true.measure(qr[2], cr[2])
        circuit_if_false = qp.create_circuit('test_if_false', [qr], [cr])
        circuit_if_false.x(qr[0])
        circuit_if_false.measure(qr[0], cr[0])
        circuit_if_false.measure(qr[1], cr[1])
        circuit_if_false.x(qr[2]).c_if(cr, 0x3)
        circuit_if_false.measure(qr[0], cr[0])
        circuit_if_false.measure(qr[1], cr[1])
        circuit_if_false.measure(qr[2], cr[2])
        basis_gates = []  # unroll to base gates
        unroller = unroll.Unroller(
            qasm.Qasm(data=qp.get_qasm('test_if_true')).parse(),
            unroll.JsonBackend(basis_gates))
        ucircuit_true = unroller.execute()
        unroller = unroll.Unroller(
            qasm.Qasm(data=qp.get_qasm('test_if_false')).parse(),
            unroll.JsonBackend(basis_gates))
        ucircuit_false = unroller.execute()
        qobj = {
            'id':
            'test_if_qobj',
            'config': {
                'max_credits': 3,
                'shots': shots,
                'backend_name': 'local_qasm_simulator_py',
            },
            'circuits': [{
                'name': 'test_if_true',
                'compiled_circuit': ucircuit_true,
                'compiled_circuit_qasm': None,
                'config': {
                    'coupling_map': None,
                    'basis_gates': 'u1,u2,u3,cx,id',
                    'layout': None,
                    'seed': None
                }
            }, {
                'name': 'test_if_false',
                'compiled_circuit': ucircuit_false,
                'compiled_circuit_qasm': None,
                'config': {
                    'coupling_map': None,
                    'basis_gates': 'u1,u2,u3,cx,id',
                    'layout': None,
                    'seed': None
                }
            }]
        }
        q_job = QuantumJob(qobj, backend=QasmSimulatorPy(), preformatted=True)
        result = QasmSimulatorPy().run(q_job).result()
        result_if_true = result.get_data('test_if_true')
        self.log.info('result_if_true circuit:')
        self.log.info(circuit_if_true.qasm())
        self.log.info('result_if_true=%s', result_if_true)

        result_if_false = result.get_data('test_if_false')
        self.log.info('result_if_false circuit:')
        self.log.info(circuit_if_false.qasm())
        self.log.info('result_if_false=%s', result_if_false)
        self.assertTrue(result_if_true['counts']['111'] == 100)
        self.assertTrue(result_if_false['counts']['001'] == 100)

    @unittest.skipIf(version_info.minor == 5,
                     "Due to gate ordering issues with Python 3.5 \
                                         we have to disable this test until fixed"
                     )
    def test_teleport(self):
        """test teleportation as in tutorials"""

        self.log.info('test_teleport')
        pi = np.pi
        shots = 1000
        qp = QuantumProgram()
        qr = qp.create_quantum_register('qr', 3)
        cr0 = qp.create_classical_register('cr0', 1)
        cr1 = qp.create_classical_register('cr1', 1)
        cr2 = qp.create_classical_register('cr2', 1)
        circuit = qp.create_circuit('teleport', [qr], [cr0, cr1, cr2])
        circuit.h(qr[1])
        circuit.cx(qr[1], qr[2])
        circuit.ry(pi / 4, qr[0])
        circuit.cx(qr[0], qr[1])
        circuit.h(qr[0])
        circuit.barrier(qr)
        circuit.measure(qr[0], cr0[0])
        circuit.measure(qr[1], cr1[0])
        circuit.z(qr[2]).c_if(cr0, 1)
        circuit.x(qr[2]).c_if(cr1, 1)
        circuit.measure(qr[2], cr2[0])
        backend = 'local_qasm_simulator_py'
        qobj = qp.compile('teleport',
                          backend=backend,
                          shots=shots,
                          seed=self.seed)
        results = qp.run(qobj)
        data = results.get_counts('teleport')
        alice = {}
        bob = {}
        alice['00'] = data['0 0 0'] + data['1 0 0']
        alice['01'] = data['0 1 0'] + data['1 1 0']
        alice['10'] = data['0 0 1'] + data['1 0 1']
        alice['11'] = data['0 1 1'] + data['1 1 1']
        bob['0'] = data['0 0 0'] + data['0 1 0'] + data['0 0 1'] + data['0 1 1']
        bob['1'] = data['1 0 0'] + data['1 1 0'] + data['1 0 1'] + data['1 1 1']
        self.log.info('test_telport: circuit:')
        self.log.info(circuit.qasm())
        self.log.info('test_teleport: data %s', data)
        self.log.info('test_teleport: alice %s', alice)
        self.log.info('test_teleport: bob %s', bob)
        alice_ratio = 1 / np.tan(pi / 8)**2
        bob_ratio = bob['0'] / float(bob['1'])
        error = abs(alice_ratio - bob_ratio) / alice_ratio
        self.log.info('test_teleport: relative error = %s', error)
        self.assertLess(error, 0.05)

    @unittest.skipIf(not do_profiling, "skipping simulator profiling.")
    def profile_qasm_simulator(self):
        """Profile randomly generated circuits.

        Writes profile results to <this_module>.prof as well as recording
        to the log file.

        number of circuits = 100.
        number of operations/circuit in [1, 40]
        number of qubits in [1, 5]
        """
        seed = 88
        shots = 1024
        n_circuits = 100
        min_depth = 1
        max_depth = 40
        min_qubits = 1
        max_qubits = 5
        pr = cProfile.Profile()
        random_circuits = RandomQasmGenerator(seed,
                                              min_qubits=min_qubits,
                                              max_qubits=max_qubits,
                                              min_depth=min_depth,
                                              max_depth=max_depth)
        random_circuits.add_circuits(n_circuits)
        self.qp = random_circuits.get_program()
        pr.enable()
        self.qp.execute(self.qp.get_circuit_names(),
                        backend='local_qasm_simulator_py',
                        shots=shots)
        pr.disable()
        sout = io.StringIO()
        ps = pstats.Stats(pr, stream=sout).sort_stats('cumulative')
        self.log.info('------- start profiling QasmSimulatorPy -----------')
        ps.print_stats()
        self.log.info(sout.getvalue())
        self.log.info('------- stop profiling QasmSimulatorPy -----------')
        sout.close()
        pr.dump_stats(self.moduleName + '.prof')

    @unittest.skipIf(not do_profiling, "skipping simulator profiling.")
    def profile_nqubit_speed_grow_depth(self):
        """simulation time vs the number of qubits

        where the circuit depth is 10x the number of simulated
        qubits. Also creates a pdf file with this module name showing a
        plot of the results. Compilation is not included in speed.
        """
        import matplotlib.pyplot as plt
        from matplotlib.ticker import MaxNLocator
        qubit_range_max = 15
        n_qubit_list = range(1, qubit_range_max + 1)
        n_circuits = 10
        shots = 1024
        seed = 88
        max_time = 30  # seconds; timing stops when simulation time exceeds this number
        fmt_str1 = 'profile_nqubit_speed::nqubits:{0}, backend:{1}, elapsed_time:{2:.2f}'
        fmt_str2 = 'backend:{0}, circuit:{1}, numOps:{2}, result:{3}'
        fmt_str3 = 'minDepth={minDepth}, maxDepth={maxDepth}, num circuits={nCircuits},' \
                   'shots={shots}'
        backend_list = [
            'local_qasm_simulator_py', 'local_unitary_simulator_py'
        ]
        if shutil.which('qasm_simulator'):
            backend_list.append('local_qasm_simulator_cpp')
        else:
            self.log.info('profile_nqubit_speed::\"qasm_simulator\" executable'
                          'not in path...skipping')
        fig = plt.figure(0)
        plt.clf()
        ax = fig.add_axes((0.1, 0.25, 0.8, 0.6))
        for _, backend in enumerate(backend_list):
            elapsed_time = np.zeros(len(n_qubit_list))
            if backend == 'local_unitary_simulator_py':
                do_measure = False
            else:
                do_measure = True
            j, timed_out = 0, False
            while j < qubit_range_max and not timed_out:
                n_qubits = n_qubit_list[j]
                random_circuits = RandomQasmGenerator(seed,
                                                      min_qubits=n_qubits,
                                                      max_qubits=n_qubits,
                                                      min_depth=n_qubits * 10,
                                                      max_depth=n_qubits * 10)
                random_circuits.add_circuits(n_circuits, do_measure=do_measure)
                qp = random_circuits.get_program()
                c_names = qp.get_circuit_names()
                qobj = qp.compile(c_names,
                                  backend=backend,
                                  shots=shots,
                                  seed=seed)
                start = time.perf_counter()
                results = qp.run(qobj)
                stop = time.perf_counter()
                elapsed_time[j] = stop - start
                if elapsed_time[j] > max_time:
                    timed_out = True
                self.log.info(
                    fmt_str1.format(n_qubits, backend, elapsed_time[j]))
                if backend != 'local_unitary_simulator_py':
                    for name in c_names:
                        log_str = fmt_str2.format(backend, name,
                                                  len(qp.get_circuit(name)),
                                                  results.get_data(name))
                        self.log.info(log_str)
                j += 1
            ax.xaxis.set_major_locator(MaxNLocator(integer=True))
            if backend == 'local_unitary_simulator_py':
                ax.plot(n_qubit_list[:j],
                        elapsed_time[:j],
                        label=backend,
                        marker='o')
            else:
                ax.plot(n_qubit_list[:j],
                        elapsed_time[:j] / shots,
                        label=backend,
                        marker='o')
            ax.set_yscale('log', basey=10)
            ax.set_xlabel('number of qubits')
            ax.set_ylabel('process time/shot')
            ax.set_title('profile_nqubit_speed_grow_depth')
            fig.text(
                0.1, 0.05,
                fmt_str3.format(minDepth='10*nQubits',
                                maxDepth='10*nQubits',
                                nCircuits=n_circuits,
                                shots=shots))
            ax.legend()
        self.pdf.savefig(fig)

    @unittest.skipIf(not do_profiling, "skipping simulator profiling.")
    def profile_nqubit_speed_constant_depth(self):
        """simulation time vs the number of qubits

        where the circuit depth is fixed at 40. Also creates a pdf file
        with this module name showing a plot of the results. Compilation
        is not included in speed.
        """
        import matplotlib.pyplot as plt
        from matplotlib.ticker import MaxNLocator
        qubit_range_max = 15
        n_qubit_list = range(1, qubit_range_max + 1)
        max_depth = 40
        min_depth = 40
        n_circuits = 10
        shots = 1024
        seed = 88
        max_time = 30  # seconds; timing stops when simulation time exceeds this number
        fmt_str1 = 'profile_nqubit_speed::nqubits:{0}, backend:{1},' \
                   'elapsed_time:{2:.2f}'
        fmt_str2 = 'backend:{0}, circuit:{1}, numOps:{2}, result:{3}'
        fmt_str3 = 'minDepth={minDepth}, maxDepth={maxDepth},' \
                   'num circuits={nCircuits}, shots={shots}'
        backend_list = [
            'local_qasm_simulator_py', 'local_unitary_simulator_py'
        ]
        if shutil.which('qasm_simulator'):
            backend_list.append('local_qasm_simulator_cpp')
        else:
            self.log.info('profile_nqubit_speed::\"qasm_simulator\" executable'
                          'not in path...skipping')
        fig = plt.figure(0)
        plt.clf()
        ax = fig.add_axes((0.1, 0.2, 0.8, 0.6))
        for _, backend in enumerate(backend_list):
            elapsedTime = np.zeros(len(n_qubit_list))
            if backend == 'local_unitary_simulator_py':
                doMeasure = False
            else:
                doMeasure = True
            j, timedOut = 0, False
            while j < qubit_range_max and not timedOut:
                nQubits = n_qubit_list[j]
                randomCircuits = RandomQasmGenerator(seed,
                                                     min_qubits=nQubits,
                                                     max_qubits=nQubits,
                                                     min_depth=min_depth,
                                                     max_depth=max_depth)
                randomCircuits.add_circuits(n_circuits, do_measure=doMeasure)
                qp = randomCircuits.get_program()
                cnames = qp.get_circuit_names()
                qobj = qp.compile(cnames,
                                  backend=backend,
                                  shots=shots,
                                  seed=seed)
                start = time.perf_counter()
                results = qp.run(qobj)
                stop = time.perf_counter()
                elapsedTime[j] = stop - start
                if elapsedTime[j] > max_time:
                    timedOut = True
                self.log.info(fmt_str1.format(nQubits, backend,
                                              elapsedTime[j]))
                if backend != 'local_unitary_simulator_py':
                    for name in cnames:
                        log_str = fmt_str2.format(backend, name,
                                                  len(qp.get_circuit(name)),
                                                  results.get_data(name))
                        self.log.info(log_str)
                j += 1
            ax.xaxis.set_major_locator(MaxNLocator(integer=True))
            if backend == 'local_unitary_simulator_py':
                ax.plot(n_qubit_list[:j],
                        elapsedTime[:j],
                        label=backend,
                        marker='o')
            else:
                ax.plot(n_qubit_list[:j],
                        elapsedTime[:j] / shots,
                        label=backend,
                        marker='o')
            ax.set_yscale('log', basey=10)
            ax.set_xlabel('number of qubits')
            ax.set_ylabel('process time/shot')
            ax.set_title('profile_nqubit_speed_constant_depth')
            fig.text(
                0.1, 0.05,
                fmt_str3.format(minDepth=min_depth,
                                maxDepth=max_depth,
                                nCircuits=n_circuits,
                                shots=shots))
            ax.legend()
        self.pdf.savefig(fig)
Пример #15
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)
Пример #16
0
class LocalUnitarySimulatorTest(QiskitTestCase):
    """Test local unitary simulator."""
    def setUp(self):
        self.seed = 88
        self.qasmFileName = self._get_resource_path('qasm/example.qasm')
        self.qp = QuantumProgram()

    def tearDown(self):
        pass

    def test_unitary_simulator(self):
        """test generation of circuit unitary"""
        shots = 1024
        self.qp.load_qasm_file(self.qasmFileName, name='example')
        basis_gates = []  # unroll to base gates
        unroller = unroll.Unroller(
            qasm.Qasm(data=self.qp.get_qasm('example')).parse(),
            unroll.JsonBackend(basis_gates))
        circuit = unroller.execute()
        #strip measurements from circuit to avoid warnings
        circuit['operations'] = [
            op for op in circuit['operations'] if op['name'] != 'measure'
        ]
        # the simulator is expecting a JSON format, so we need to convert it back to JSON
        qobj = {
            'id':
            'unitary',
            'config': {
                'max_credits': None,
                'shots': 1,
                'backend': 'local_unitary_simulator'
            },
            'circuits': [{
                'name': 'test',
                'compiled_circuit': circuit,
                'compiled_circuit_qasm': self.qp.get_qasm('example'),
                'config': {
                    'coupling_map': None,
                    'basis_gates': None,
                    'layout': None,
                    'seed': None
                }
            }]
        }
        # numpy.savetxt currently prints complex numbers in a way
        # loadtxt can't read. To save file do,
        # fmtstr=['% .4g%+.4gj' for i in range(numCols)]
        # np.savetxt('example_unitary_matrix.dat', numpyMatrix, fmt=fmtstr, delimiter=',')
        expected = np.loadtxt(
            self._get_resource_path('example_unitary_matrix.dat'),
            dtype='complex',
            delimiter=',')
        result = UnitarySimulator(qobj).run()
        self.assertTrue(
            np.allclose(result.get_data('test')['unitary'],
                        expected,
                        rtol=1e-3))

    def profile_unitary_simulator(self):
        """Profile randomly generated circuits.

        Writes profile results to <this_module>.prof as well as recording
        to the log file.

        number of circuits = 100.
        number of operations/circuit in [1, 40]
        number of qubits in [1, 5]
        """
        nCircuits = 100
        maxDepth = 40
        maxQubits = 5
        pr = cProfile.Profile()
        randomCircuits = RandomQasmGenerator(seed=self.seed,
                                             maxDepth=maxDepth,
                                             maxQubits=maxQubits)
        randomCircuits.add_circuits(nCircuits, doMeasure=False)
        self.qp = randomCircuits.getProgram()
        pr.enable()
        self.qp.execute(self.qp.get_circuit_names(),
                        backend='local_unitary_simulator')
        pr.disable()
        sout = io.StringIO()
        ps = pstats.Stats(pr, stream=sout).sort_stats('cumulative')
        self.log.info('------- start profiling UnitarySimulator -----------')
        ps.print_stats()
        self.log.info(sout.getvalue())
        self.log.info('------- stop profiling UnitarySimulator -----------')
        sout.close()
        pr.dump_stats(self.moduleName + '.prof')
Пример #17
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]])
class LocalUnitarySimulatorTest(unittest.TestCase):
    """Test local unitary simulator."""

    def setUp(self):
        self.seed = 88
        self.qasmFileName = os.path.join(qiskit.__path__[0],
                                         '../test/python/qasm/example.qasm')
        self.qp = QuantumProgram()
        self.moduleName = os.path.splitext(__file__)[0]
        self.modulePath = os.path.dirname(__file__)
        logFileName = self.moduleName + '.log'
        logging.basicConfig(filename=logFileName, level=logging.INFO)

    def tearDown(self):
        pass

    def test_unitary_simulator(self):
        """test generation of circuit unitary"""
        shots = 1024
        self.qp.load_qasm_file(self.qasmFileName, name='example')
        basis_gates = []  # unroll to base gates
        unroller = unroll.Unroller(
            qasm.Qasm(data=self.qp.get_qasm("example")).parse(),
                      unroll.JsonBackend(basis_gates))
        circuit = unroller.execute()
	# if we want to manipulate the circuit, we have to convert it to a dict
        circuit = json.loads(circuit.decode())
        #strip measurements from circuit to avoid warnings
        circuit['operations'] = [op for op in circuit['operations']
                                 if op['name'] != 'measure']
	# the simulator is expecting a JSON format, so we need to convert it back to JSON
        job = {'compiled_circuit': json.dumps(circuit).encode()}
        # numpy savetxt is currently prints complex numbers in a way
        # loadtxt can't read. To save file do,
        # fmtstr=['% .4g%+.4gj' for i in range(numCols)]
        # np.savetxt('example_unitary_matrix.dat', numpyMatrix, fmt=fmtstr, delimiter=',')
        expected = np.loadtxt(os.path.join(self.modulePath,
                                           'example_unitary_matrix.dat'),
                              dtype='complex', delimiter=',')
        result = UnitarySimulator(job).run()
        self.assertTrue(np.allclose(result['data']['unitary'], expected,
                                    rtol=1e-3))

    def profile_unitary_simulator(self):
        """Profile randomly generated circuits.

        Writes profile results to <this_module>.prof as well as recording
        to the log file.

        number of circuits = 100.
        number of operations/circuit in [1, 40]
        number of qubits in [1, 5]
        """
        nCircuits = 100
        maxDepth = 40
        maxQubits = 5
        pr = cProfile.Profile()
        randomCircuits = RandomQasmGenerator(seed=self.seed,
                                             maxDepth=maxDepth,
                                             maxQubits=maxQubits)
        randomCircuits.add_circuits(nCircuits, doMeasure=False)
        self.qp = randomCircuits.getProgram()
        pr.enable()
        self.qp.execute(self.qp.get_circuit_names(),
                        backend='local_unitary_simulator')
        pr.disable()
        sout = io.StringIO()
        ps = pstats.Stats(pr, stream=sout).sort_stats('cumulative')
        logging.info('------- start profiling UnitarySimulator -----------')
        ps.print_stats()
        logging.info(sout.getvalue())
        logging.info('------- stop profiling UnitarySimulator -----------')
        sout.close()
        pr.dump_stats(self.moduleName + '.prof')
class LocalSimulatorTest(unittest.TestCase):
    """
    Test interface to local simulators.
    """

    @classmethod
    def setUpClass(cls):
        cls.moduleName = os.path.splitext(__file__)[0]
        cls.log = logging.getLogger(__name__)
        cls.log.setLevel(logging.INFO)
        logFileName = cls.moduleName + '.log'
        handler = logging.FileHandler(logFileName)
        handler.setLevel(logging.INFO)
        log_fmt = ('{}.%(funcName)s:%(levelname)s:%(asctime)s:'
                   ' %(message)s'.format(cls.__name__))
        formatter = logging.Formatter(log_fmt)
        handler.setFormatter(formatter)
        cls.log.addHandler(handler)

    @classmethod
    def tearDownClass(cls):
        #cls.pdf.close()
        pass

    def setUp(self):
        self.seed = 88
        self.qasmFileName = os.path.join(qiskit.__path__[0],
                                         '../test/python/qasm/example.qasm')
        self.qp = QuantumProgram()
        shots = 1
        self.qp.load_qasm_file(self.qasmFileName, name='example')
        basis_gates = []  # unroll to base gates
        unroller = unroll.Unroller(
            qasm.Qasm(data=self.qp.get_qasm("example")).parse(),
                      unroll.JsonBackend(basis_gates))
        circuit = unroller.execute()
        self.job = {'compiled_circuit': circuit,
                    'config': {'shots': shots, 'seed': random.randint(0, 10)}
                   }

    def tearDown(self):
        pass

    def test_local_configuration_present(self):
        self.assertTrue(_localsimulator.local_configuration)

    def test_local_configurations(self):
        required_keys = ['name',
                         'url',
                         'simulator',
                         'description',
                         'coupling_map',
                         'basis_gates']
        for conf in _localsimulator.local_configuration:
            for key in required_keys:
                self.assertIn(key, conf.keys())

    def test_simulator_classes(self):
        cdict = _localsimulator._simulator_classes
        cdict = getattr(_localsimulator, '_simulator_classes')
        self.log.info('found local simulators: {0}'.format(repr(cdict)))
        self.assertTrue(cdict)

    def test_local_backends(self):
        backends = _localsimulator.local_backends()
        self.log.info('found local backends: {0}'.format(repr(backends)))
        self.assertTrue(backends)

    def test_instantiation(self):
        """
        Test instantiation of LocalSimulator
        """
        backend_list = _localsimulator.local_backends()
        for backend_name in backend_list:
            backend = _localsimulator.LocalSimulator(backend_name, self.job)
Пример #20
0
class LocalSimulatorTest(QiskitTestCase):
    """
    Test interface to local simulators.
    """
    def setUp(self):
        self.seed = 88
        self.qasmFileName = self._get_resource_path('qasm/example.qasm')
        self.qp = QuantumProgram()
        shots = 1
        self.qp.load_qasm_file(self.qasmFileName, name='example')
        basis_gates = []  # unroll to base gates
        unroller = unroll.Unroller(
            qasm.Qasm(data=self.qp.get_qasm("example")).parse(),
            unroll.JsonBackend(basis_gates))
        circuit = unroller.execute()
        self.qobj = {
            'id':
            'test_qobj',
            'config': {
                'max_credits': 3,
                'shots': 100,
                'backend': 'local_qasm_simulator',
            },
            'circuits': [{
                'name': 'test_circuit',
                'compiled_circuit': circuit,
                'basis_gates': 'u1,u2,u3,cx,id',
                'layout': None,
                'seed': None
            }]
        }

    def tearDown(self):
        pass

    def test_local_configuration_present(self):
        self.assertTrue(_localsimulator.local_configuration)

    def test_local_configurations(self):
        required_keys = [
            'name', 'url', 'simulator', 'description', 'coupling_map',
            'basis_gates'
        ]
        for conf in _localsimulator.local_configuration:
            for key in required_keys:
                self.assertIn(key, conf.keys())

    def test_simulator_classes(self):
        cdict = _localsimulator._simulator_classes
        cdict = getattr(_localsimulator, '_simulator_classes')
        self.log.info('found local simulators: {0}'.format(repr(cdict)))
        self.assertTrue(cdict)

    def test_local_backends(self):
        backends = _localsimulator.local_backends()
        self.log.info('found local backends: {0}'.format(repr(backends)))
        self.assertTrue(backends)

    def test_instantiation(self):
        """
        Test instantiation of LocalSimulator
        """
        backend_list = _localsimulator.local_backends()
        for backend_name in backend_list:
            backend = _localsimulator.LocalSimulator(self.qobj)
Пример #21
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)
class UnitarySimulatorSympyTest(QiskitTestCase):
    """Test local unitary simulator sympy."""

    def setUp(self):
        self.seed = 88
        self.qasm_filename = self._get_resource_path('qasm/simple.qasm')
        self.qp = QuantumProgram()

    def test_unitary_simulator(self):
        """test generation of circuit unitary"""
        self.qp.load_qasm_file(self.qasm_filename, name='example')
        basis_gates = []  # unroll to base gates
        unroller = unroll.Unroller(
            qasm.Qasm(data=self.qp.get_qasm('example')).parse(),
            unroll.JsonBackend(basis_gates))
        circuit = unroller.execute()
        # strip measurements from circuit to avoid warnings
        circuit['operations'] = [op for op in circuit['operations']
                                 if op['name'] != 'measure']
        # the simulator is expecting a JSON format, so we need to convert it
        # back to JSON
        qobj = {
            'id': 'unitary',
            'config': {
                'max_credits': None,
                'shots': 1,
                'backend_name': 'local_sympy_unitary_simulator'
            },
            'circuits': [
                {
                    'name': 'test',
                    'compiled_circuit': circuit,
                    'compiled_circuit_qasm': self.qp.get_qasm('example'),
                    'config': {
                        'coupling_map': None,
                        'basis_gates': None,
                        'layout': None,
                        'seed': None
                    }
                }
            ]
        }

        q_job = QuantumJob(qobj,
                           backend=UnitarySimulatorSympy(),
                           preformatted=True)

        result = UnitarySimulatorSympy().run(q_job).result()
        actual = result.get_data('test')['unitary']

        self.assertEqual(actual[0][0], sqrt(2)/2)
        self.assertEqual(actual[0][1], sqrt(2)/2)
        self.assertEqual(actual[0][2], 0)
        self.assertEqual(actual[0][3], 0)
        self.assertEqual(actual[1][0], 0)
        self.assertEqual(actual[1][1], 0)
        self.assertEqual(actual[1][2], sqrt(2)/2)
        self.assertEqual(actual[1][3], -sqrt(2)/2)
        self.assertEqual(actual[2][0], 0)
        self.assertEqual(actual[2][1], 0)
        self.assertEqual(actual[2][2], sqrt(2)/2)
        self.assertEqual(actual[2][3], sqrt(2)/2)
        self.assertEqual(actual[3][0], sqrt(2)/2)
        self.assertEqual(actual[3][1], -sqrt(2)/2)
        self.assertEqual(actual[3][2], 0)
        self.assertEqual(actual[3][3], 0)
class TestLocalQasmSimulatorPy(QiskitTestCase):
    """Test local_qasm_simulator_py."""

    @classmethod
    def setUpClass(cls):
        super().setUpClass()
        if do_profiling:
            cls.pdf = PdfPages(cls.moduleName + '.pdf')

    @classmethod
    def tearDownClass(cls):
        if do_profiling:
            cls.pdf.close()

    def setUp(self):
        self.seed = 88
        self.qasm_filename = self._get_resource_path('qasm/example.qasm')
        self.qp = QuantumProgram()
        self.qp.load_qasm_file(self.qasm_filename, name='example')
        basis_gates = []  # unroll to base gates
        unroller = unroll.Unroller(
            qasm.Qasm(data=self.qp.get_qasm('example')).parse(),
            unroll.JsonBackend(basis_gates))
        circuit = unroller.execute()
        circuit_config = {'coupling_map': None,
                          'basis_gates': 'u1,u2,u3,cx,id',
                          'layout': None,
                          'seed': self.seed}
        resources = {'max_credits': 3}
        self.qobj = {'id': 'test_sim_single_shot',
                     'config': {
                         'max_credits': resources['max_credits'],
                         'shots': 1024,
                         'backend_name': 'local_qasm_simulator_py',
                     },
                     'circuits': [
                         {
                             'name': 'test',
                             'compiled_circuit': circuit,
                             'compiled_circuit_qasm': None,
                             'config': circuit_config
                         }
                     ]}
        self.q_job = QuantumJob(self.qobj,
                                backend=QasmSimulatorPy(),
                                circuit_config=circuit_config,
                                seed=self.seed,
                                resources=resources,
                                preformatted=True)

    def tearDown(self):
        pass

    def test_qasm_simulator_single_shot(self):
        """Test single shot run."""
        shots = 1
        self.qobj['config']['shots'] = shots
        result = QasmSimulatorPy().run(self.q_job).result()
        self.assertEqual(result.get_status(), 'COMPLETED')

    def test_qasm_simulator(self):
        """Test data counts output for single circuit run against reference."""
        result = QasmSimulatorPy().run(self.q_job).result()
        shots = 1024
        threshold = 0.04 * shots
        counts = result.get_counts('test')
        target = {'100 100': shots / 8, '011 011': shots / 8,
                  '101 101': shots / 8, '111 111': shots / 8,
                  '000 000': shots / 8, '010 010': shots / 8,
                  '110 110': shots / 8, '001 001': shots / 8}
        self.assertDictAlmostEqual(counts, target, threshold)

    def test_if_statement(self):
        self.log.info('test_if_statement_x')
        shots = 100
        max_qubits = 3
        qp = QuantumProgram()
        qr = qp.create_quantum_register('qr', max_qubits)
        cr = qp.create_classical_register('cr', max_qubits)
        circuit_if_true = qp.create_circuit('test_if_true', [qr], [cr])
        circuit_if_true.x(qr[0])
        circuit_if_true.x(qr[1])
        circuit_if_true.measure(qr[0], cr[0])
        circuit_if_true.measure(qr[1], cr[1])
        circuit_if_true.x(qr[2]).c_if(cr, 0x3)
        circuit_if_true.measure(qr[0], cr[0])
        circuit_if_true.measure(qr[1], cr[1])
        circuit_if_true.measure(qr[2], cr[2])
        circuit_if_false = qp.create_circuit('test_if_false', [qr], [cr])
        circuit_if_false.x(qr[0])
        circuit_if_false.measure(qr[0], cr[0])
        circuit_if_false.measure(qr[1], cr[1])
        circuit_if_false.x(qr[2]).c_if(cr, 0x3)
        circuit_if_false.measure(qr[0], cr[0])
        circuit_if_false.measure(qr[1], cr[1])
        circuit_if_false.measure(qr[2], cr[2])
        basis_gates = []  # unroll to base gates
        unroller = unroll.Unroller(
            qasm.Qasm(data=qp.get_qasm('test_if_true')).parse(),
            unroll.JsonBackend(basis_gates))
        ucircuit_true = unroller.execute()
        unroller = unroll.Unroller(
            qasm.Qasm(data=qp.get_qasm('test_if_false')).parse(),
            unroll.JsonBackend(basis_gates))
        ucircuit_false = unroller.execute()
        qobj = {
            'id': 'test_if_qobj',
            'config': {
                'max_credits': 3,
                'shots': shots,
                'backend_name': 'local_qasm_simulator_py',
            },
            'circuits': [
                {
                    'name': 'test_if_true',
                    'compiled_circuit': ucircuit_true,
                    'compiled_circuit_qasm': None,
                    'config': {
                        'coupling_map': None,
                        'basis_gates': 'u1,u2,u3,cx,id',
                        'layout': None,
                        'seed': None
                    }
                },
                {
                    'name': 'test_if_false',
                    'compiled_circuit': ucircuit_false,
                    'compiled_circuit_qasm': None,
                    'config': {
                        'coupling_map': None,
                        'basis_gates': 'u1,u2,u3,cx,id',
                        'layout': None,
                        'seed': None
                    }
                }
            ]
        }
        q_job = QuantumJob(qobj, backend=QasmSimulatorPy(), preformatted=True)
        result = QasmSimulatorPy().run(q_job).result()
        result_if_true = result.get_data('test_if_true')
        self.log.info('result_if_true circuit:')
        self.log.info(circuit_if_true.qasm())
        self.log.info('result_if_true=%s', result_if_true)

        result_if_false = result.get_data('test_if_false')
        self.log.info('result_if_false circuit:')
        self.log.info(circuit_if_false.qasm())
        self.log.info('result_if_false=%s', result_if_false)
        self.assertTrue(result_if_true['counts']['111'] == 100)
        self.assertTrue(result_if_false['counts']['001'] == 100)

    @unittest.skipIf(version_info.minor == 5, "Due to gate ordering issues with Python 3.5 \
                                         we have to disable this test until fixed")
    def test_teleport(self):
        """test teleportation as in tutorials"""

        self.log.info('test_teleport')
        pi = np.pi
        shots = 1000
        qp = QuantumProgram()
        qr = qp.create_quantum_register('qr', 3)
        cr0 = qp.create_classical_register('cr0', 1)
        cr1 = qp.create_classical_register('cr1', 1)
        cr2 = qp.create_classical_register('cr2', 1)
        circuit = qp.create_circuit('teleport', [qr],
                                    [cr0, cr1, cr2])
        circuit.h(qr[1])
        circuit.cx(qr[1], qr[2])
        circuit.ry(pi/4, qr[0])
        circuit.cx(qr[0], qr[1])
        circuit.h(qr[0])
        circuit.barrier(qr)
        circuit.measure(qr[0], cr0[0])
        circuit.measure(qr[1], cr1[0])
        circuit.z(qr[2]).c_if(cr0, 1)
        circuit.x(qr[2]).c_if(cr1, 1)
        circuit.measure(qr[2], cr2[0])
        backend = 'local_qasm_simulator_py'
        qobj = qp.compile('teleport', backend=backend, shots=shots,
                          seed=self.seed)
        results = qp.run(qobj)
        data = results.get_counts('teleport')
        alice = {}
        bob = {}
        alice['00'] = data['0 0 0'] + data['1 0 0']
        alice['01'] = data['0 1 0'] + data['1 1 0']
        alice['10'] = data['0 0 1'] + data['1 0 1']
        alice['11'] = data['0 1 1'] + data['1 1 1']
        bob['0'] = data['0 0 0'] + data['0 1 0'] + data['0 0 1'] + data['0 1 1']
        bob['1'] = data['1 0 0'] + data['1 1 0'] + data['1 0 1'] + data['1 1 1']
        self.log.info('test_telport: circuit:')
        self.log.info(circuit.qasm())
        self.log.info('test_teleport: data %s', data)
        self.log.info('test_teleport: alice %s', alice)
        self.log.info('test_teleport: bob %s', bob)
        alice_ratio = 1/np.tan(pi/8)**2
        bob_ratio = bob['0']/float(bob['1'])
        error = abs(alice_ratio - bob_ratio) / alice_ratio
        self.log.info('test_teleport: relative error = %s', error)
        self.assertLess(error, 0.05)

    @unittest.skipIf(not do_profiling, "skipping simulator profiling.")
    def profile_qasm_simulator(self):
        """Profile randomly generated circuits.

        Writes profile results to <this_module>.prof as well as recording
        to the log file.

        number of circuits = 100.
        number of operations/circuit in [1, 40]
        number of qubits in [1, 5]
        """
        seed = 88
        shots = 1024
        n_circuits = 100
        min_depth = 1
        max_depth = 40
        min_qubits = 1
        max_qubits = 5
        pr = cProfile.Profile()
        random_circuits = RandomQasmGenerator(seed,
                                              min_qubits=min_qubits,
                                              max_qubits=max_qubits,
                                              min_depth=min_depth,
                                              max_depth=max_depth)
        random_circuits.add_circuits(n_circuits)
        self.qp = random_circuits.get_program()
        pr.enable()
        self.qp.execute(self.qp.get_circuit_names(),
                        backend='local_qasm_simulator_py',
                        shots=shots)
        pr.disable()
        sout = io.StringIO()
        ps = pstats.Stats(pr, stream=sout).sort_stats('cumulative')
        self.log.info('------- start profiling QasmSimulatorPy -----------')
        ps.print_stats()
        self.log.info(sout.getvalue())
        self.log.info('------- stop profiling QasmSimulatorPy -----------')
        sout.close()
        pr.dump_stats(self.moduleName + '.prof')

    @unittest.skipIf(not do_profiling, "skipping simulator profiling.")
    def profile_nqubit_speed_grow_depth(self):
        """simulation time vs the number of qubits

        where the circuit depth is 10x the number of simulated
        qubits. Also creates a pdf file with this module name showing a
        plot of the results. Compilation is not included in speed.
        """
        import matplotlib.pyplot as plt
        from matplotlib.ticker import MaxNLocator
        qubit_range_max = 15
        n_qubit_list = range(1, qubit_range_max + 1)
        n_circuits = 10
        shots = 1024
        seed = 88
        max_time = 30  # seconds; timing stops when simulation time exceeds this number
        fmt_str1 = 'profile_nqubit_speed::nqubits:{0}, backend:{1}, elapsed_time:{2:.2f}'
        fmt_str2 = 'backend:{0}, circuit:{1}, numOps:{2}, result:{3}'
        fmt_str3 = 'minDepth={minDepth}, maxDepth={maxDepth}, num circuits={nCircuits},' \
                   'shots={shots}'
        backend_list = ['local_qasm_simulator_py', 'local_unitary_simulator_py']
        if shutil.which('qasm_simulator'):
            backend_list.append('local_qasm_simulator_cpp')
        else:
            self.log.info('profile_nqubit_speed::\"qasm_simulator\" executable'
                          'not in path...skipping')
        fig = plt.figure(0)
        plt.clf()
        ax = fig.add_axes((0.1, 0.25, 0.8, 0.6))
        for _, backend in enumerate(backend_list):
            elapsed_time = np.zeros(len(n_qubit_list))
            if backend == 'local_unitary_simulator_py':
                do_measure = False
            else:
                do_measure = True
            j, timed_out = 0, False
            while j < qubit_range_max and not timed_out:
                n_qubits = n_qubit_list[j]
                random_circuits = RandomQasmGenerator(seed,
                                                      min_qubits=n_qubits,
                                                      max_qubits=n_qubits,
                                                      min_depth=n_qubits * 10,
                                                      max_depth=n_qubits * 10)
                random_circuits.add_circuits(n_circuits, do_measure=do_measure)
                qp = random_circuits.get_program()
                c_names = qp.get_circuit_names()
                qobj = qp.compile(c_names, backend=backend, shots=shots,
                                  seed=seed)
                start = time.perf_counter()
                results = qp.run(qobj)
                stop = time.perf_counter()
                elapsed_time[j] = stop - start
                if elapsed_time[j] > max_time:
                    timed_out = True
                self.log.info(fmt_str1.format(n_qubits, backend, elapsed_time[j]))
                if backend != 'local_unitary_simulator_py':
                    for name in c_names:
                        log_str = fmt_str2.format(
                            backend, name, len(qp.get_circuit(name)),
                            results.get_data(name))
                        self.log.info(log_str)
                j += 1
            ax.xaxis.set_major_locator(MaxNLocator(integer=True))
            if backend == 'local_unitary_simulator_py':
                ax.plot(n_qubit_list[:j], elapsed_time[:j], label=backend, marker='o')
            else:
                ax.plot(n_qubit_list[:j], elapsed_time[:j]/shots, label=backend,
                        marker='o')
            ax.set_yscale('log', basey=10)
            ax.set_xlabel('number of qubits')
            ax.set_ylabel('process time/shot')
            ax.set_title('profile_nqubit_speed_grow_depth')
            fig.text(0.1, 0.05,
                     fmt_str3.format(minDepth='10*nQubits', maxDepth='10*nQubits',
                                     nCircuits=n_circuits, shots=shots))
            ax.legend()
        self.pdf.savefig(fig)

    @unittest.skipIf(not do_profiling, "skipping simulator profiling.")
    def profile_nqubit_speed_constant_depth(self):
        """simulation time vs the number of qubits

        where the circuit depth is fixed at 40. Also creates a pdf file
        with this module name showing a plot of the results. Compilation
        is not included in speed.
        """
        import matplotlib.pyplot as plt
        from matplotlib.ticker import MaxNLocator
        qubit_range_max = 15
        n_qubit_list = range(1, qubit_range_max + 1)
        max_depth = 40
        min_depth = 40
        n_circuits = 10
        shots = 1024
        seed = 88
        max_time = 30  # seconds; timing stops when simulation time exceeds this number
        fmt_str1 = 'profile_nqubit_speed::nqubits:{0}, backend:{1},' \
                   'elapsed_time:{2:.2f}'
        fmt_str2 = 'backend:{0}, circuit:{1}, numOps:{2}, result:{3}'
        fmt_str3 = 'minDepth={minDepth}, maxDepth={maxDepth},' \
                   'num circuits={nCircuits}, shots={shots}'
        backend_list = ['local_qasm_simulator_py', 'local_unitary_simulator_py']
        if shutil.which('qasm_simulator'):
            backend_list.append('local_qasm_simulator_cpp')
        else:
            self.log.info('profile_nqubit_speed::\"qasm_simulator\" executable'
                          'not in path...skipping')
        fig = plt.figure(0)
        plt.clf()
        ax = fig.add_axes((0.1, 0.2, 0.8, 0.6))
        for _, backend in enumerate(backend_list):
            elapsedTime = np.zeros(len(n_qubit_list))
            if backend == 'local_unitary_simulator_py':
                doMeasure = False
            else:
                doMeasure = True
            j, timedOut = 0, False
            while j < qubit_range_max and not timedOut:
                nQubits = n_qubit_list[j]
                randomCircuits = RandomQasmGenerator(seed,
                                                     min_qubits=nQubits,
                                                     max_qubits=nQubits,
                                                     min_depth=min_depth,
                                                     max_depth=max_depth)
                randomCircuits.add_circuits(n_circuits, do_measure=doMeasure)
                qp = randomCircuits.get_program()
                cnames = qp.get_circuit_names()
                qobj = qp.compile(cnames, backend=backend, shots=shots, seed=seed)
                start = time.perf_counter()
                results = qp.run(qobj)
                stop = time.perf_counter()
                elapsedTime[j] = stop - start
                if elapsedTime[j] > max_time:
                    timedOut = True
                self.log.info(fmt_str1.format(nQubits, backend, elapsedTime[j]))
                if backend != 'local_unitary_simulator_py':
                    for name in cnames:
                        log_str = fmt_str2.format(
                            backend, name, len(qp.get_circuit(name)),
                            results.get_data(name))
                        self.log.info(log_str)
                j += 1
            ax.xaxis.set_major_locator(MaxNLocator(integer=True))
            if backend == 'local_unitary_simulator_py':
                ax.plot(n_qubit_list[:j], elapsedTime[:j], label=backend, marker='o')
            else:
                ax.plot(n_qubit_list[:j], elapsedTime[:j]/shots, label=backend,
                        marker='o')
            ax.set_yscale('log', basey=10)
            ax.set_xlabel('number of qubits')
            ax.set_ylabel('process time/shot')
            ax.set_title('profile_nqubit_speed_constant_depth')
            fig.text(0.1, 0.05,
                     fmt_str3.format(minDepth=min_depth, maxDepth=max_depth,
                                     nCircuits=n_circuits, shots=shots))
            ax.legend()
        self.pdf.savefig(fig)
Пример #24
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]])
class LocalUnitarySimulatorTest(QiskitTestCase):
    """Test local unitary simulator."""

    def setUp(self):
        self.seed = 88
        self.qasm_filename = self._get_resource_path('qasm/example.qasm')
        self.qp = QuantumProgram()

    def tearDown(self):
        pass

    def test_unitary_simulator(self):
        """test generation of circuit unitary"""
        self.qp.load_qasm_file(self.qasm_filename, name='example')
        basis_gates = []  # unroll to base gates
        unroller = unroll.Unroller(
            qasm.Qasm(data=self.qp.get_qasm('example')).parse(),
            unroll.JsonBackend(basis_gates))
        circuit = unroller.execute()
        # strip measurements from circuit to avoid warnings
        circuit['operations'] = [op for op in circuit['operations']
                                 if op['name'] != 'measure']
        # the simulator is expecting a JSON format, so we need to convert it
        # back to JSON
        qobj = {
            'id': 'unitary',
            'config': {
                'max_credits': None,
                'shots': 1,
                'backend_name': 'local_unitary_simulator_py'
            },
            'circuits': [
                {
                    'name': 'test',
                    'compiled_circuit': circuit,
                    'compiled_circuit_qasm': self.qp.get_qasm('example'),
                    'config': {
                        'coupling_map': None,
                        'basis_gates': None,
                        'layout': None,
                        'seed': None
                    }
                }
            ]
        }
        # numpy.savetxt currently prints complex numbers in a way
        # loadtxt can't read. To save file do,
        # fmtstr=['% .4g%+.4gj' for i in range(numCols)]
        # np.savetxt('example_unitary_matrix.dat', numpyMatrix, fmt=fmtstr,
        # delimiter=',')
        expected = np.loadtxt(self._get_resource_path('example_unitary_matrix.dat'),
                              dtype='complex', delimiter=',')
        q_job = QuantumJob(qobj,
                           backend=UnitarySimulatorPy(),
                           preformatted=True)

        result = UnitarySimulatorPy().run(q_job).result()
        self.assertTrue(np.allclose(result.get_unitary('test'),
                                    expected,
                                    rtol=1e-3))

    def test_two_unitary_simulator(self):
        """test running two circuits

        This test is similar to one in test_quantumprogram but doesn't use
        multiprocessing.
        """
        qr = QuantumRegister(2)
        cr = ClassicalRegister(1)
        qc1 = QuantumCircuit(qr, cr)
        qc2 = QuantumCircuit(qr, cr)
        qc1.h(qr)
        qc2.cx(qr[0], qr[1])
        backend = UnitarySimulatorPy()
        qobj = compile([qc1, qc2], backend=backend)
        job = backend.run(QuantumJob(qobj, backend=backend, preformatted=True))
        unitary1 = job.result().get_unitary(qc1)
        unitary2 = job.result().get_unitary(qc2)
        unitaryreal1 = np.array([[0.5, 0.5, 0.5, 0.5], [0.5, -0.5, 0.5, -0.5],
                                 [0.5, 0.5, -0.5, -0.5],
                                 [0.5, -0.5, -0.5, 0.5]])
        unitaryreal2 = np.array([[1, 0, 0, 0], [0, 0, 0, 1],
                                 [0., 0, 1, 0], [0, 1, 0, 0]])
        norm1 = np.trace(np.dot(np.transpose(np.conj(unitaryreal1)), unitary1))
        norm2 = np.trace(np.dot(np.transpose(np.conj(unitaryreal2)), unitary2))
        self.assertAlmostEqual(norm1, 4)
        self.assertAlmostEqual(norm2, 4)

    def profile_unitary_simulator(self):
        """Profile randomly generated circuits.

        Writes profile results to <this_module>.prof as well as recording
        to the log file.

        number of circuits = 100.
        number of operations/circuit in [1, 40]
        number of qubits in [1, 5]
        """
        n_circuits = 100
        max_depth = 40
        max_qubits = 5
        pr = cProfile.Profile()
        random_circuits = RandomQasmGenerator(seed=self.seed,
                                              max_depth=max_depth,
                                              max_qubits=max_qubits)
        random_circuits.add_circuits(n_circuits, do_measure=False)
        self.qp = random_circuits.get_program()
        pr.enable()
        self.qp.execute(self.qp.get_circuit_names(),
                        backend=UnitarySimulatorPy())
        pr.disable()
        sout = io.StringIO()
        ps = pstats.Stats(pr, stream=sout).sort_stats('cumulative')
        self.log.info('------- start profiling UnitarySimulatorPy -----------')
        ps.print_stats()
        self.log.info(sout.getvalue())
        self.log.info('------- stop profiling UnitarySimulatorPy -----------')
        sout.close()
        pr.dump_stats(self.moduleName + '.prof')
class LocalUnitarySimulatorTest(unittest.TestCase):
    """Test local unitary simulator."""
    @classmethod
    def setUpClass(cls):
        cls.moduleName = os.path.splitext(__file__)[0]
        cls.log = logging.getLogger(__name__)
        cls.log.setLevel(logging.INFO)
        logFileName = cls.moduleName + '.log'
        handler = logging.FileHandler(logFileName)
        handler.setLevel(logging.INFO)
        log_fmt = ('{}.%(funcName)s:%(levelname)s:%(asctime)s:'
                   ' %(message)s'.format(cls.__name__))
        formatter = logging.Formatter(log_fmt)
        handler.setFormatter(formatter)
        cls.log.addHandler(handler)

    def setUp(self):
        self.seed = 88
        self.qasmFileName = os.path.join(qiskit.__path__[0],
                                         '../test/python/qasm/example.qasm')
        self.modulePath = os.path.dirname(__file__)
        self.qp = QuantumProgram()

    def tearDown(self):
        pass

    def test_unitary_simulator(self):
        """test generation of circuit unitary"""
        shots = 1024
        self.qp.load_qasm_file(self.qasmFileName, name='example')
        basis_gates = []  # unroll to base gates
        unroller = unroll.Unroller(
            qasm.Qasm(data=self.qp.get_qasm("example")).parse(),
            unroll.JsonBackend(basis_gates))
        circuit = unroller.execute()
        # if we want to manipulate the circuit, we have to convert it to a dict
        circuit = json.loads(circuit.decode())
        #strip measurements from circuit to avoid warnings
        circuit['operations'] = [
            op for op in circuit['operations'] if op['name'] != 'measure'
        ]
        # the simulator is expecting a JSON format, so we need to convert it back to JSON
        job = {'compiled_circuit': json.dumps(circuit).encode()}
        # numpy savetxt is currently prints complex numbers in a way
        # loadtxt can't read. To save file do,
        # fmtstr=['% .4g%+.4gj' for i in range(numCols)]
        # np.savetxt('example_unitary_matrix.dat', numpyMatrix, fmt=fmtstr, delimiter=',')
        expected = np.loadtxt(os.path.join(self.modulePath,
                                           'example_unitary_matrix.dat'),
                              dtype='complex',
                              delimiter=',')
        result = UnitarySimulator(job).run()
        self.assertTrue(
            np.allclose(result['data']['unitary'], expected, rtol=1e-3))

    def profile_unitary_simulator(self):
        """Profile randomly generated circuits.

        Writes profile results to <this_module>.prof as well as recording
        to the log file.

        number of circuits = 100.
        number of operations/circuit in [1, 40]
        number of qubits in [1, 5]
        """
        nCircuits = 100
        maxDepth = 40
        maxQubits = 5
        pr = cProfile.Profile()
        randomCircuits = RandomQasmGenerator(seed=self.seed,
                                             maxDepth=maxDepth,
                                             maxQubits=maxQubits)
        randomCircuits.add_circuits(nCircuits, doMeasure=False)
        self.qp = randomCircuits.getProgram()
        pr.enable()
        self.qp.execute(self.qp.get_circuit_names(),
                        backend='local_unitary_simulator')
        pr.disable()
        sout = io.StringIO()
        ps = pstats.Stats(pr, stream=sout).sort_stats('cumulative')
        self.log.info('------- start profiling UnitarySimulator -----------')
        ps.print_stats()
        self.log.info(sout.getvalue())
        self.log.info('------- stop profiling UnitarySimulator -----------')
        sout.close()
        pr.dump_stats(self.moduleName + '.prof')
class LocalQasmSimulatorTest(unittest.TestCase):
    """Test local qasm simulator."""

    @classmethod
    def setUpClass(cls):
        cls.moduleName = os.path.splitext(__file__)[0]
        cls.pdf = PdfPages(cls.moduleName + '.pdf')
        cls.log = logging.getLogger(__name__)
        cls.log.setLevel(logging.INFO)
        logFileName = cls.moduleName + '.log'
        handler = logging.FileHandler(logFileName)
        handler.setLevel(logging.INFO)
        log_fmt = ('{}.%(funcName)s:%(levelname)s:%(asctime)s:'
                   ' %(message)s'.format(cls.__name__))
        formatter = logging.Formatter(log_fmt)
        handler.setFormatter(formatter)
        cls.log.addHandler(handler)

    @classmethod
    def tearDownClass(cls):
        cls.pdf.close()

    def setUp(self):
        self.seed = 88
        self.qasmFileName = os.path.join(qiskit.__path__[0],
                                         '../test/python/qasm/example.qasm')
        self.qp = QuantumProgram()

    def tearDown(self):
        pass

    def test_qasm_simulator_single_shot(self):
        """Test single shot run."""
        shots = 1
        self.qp.load_qasm_file(self.qasmFileName, name='example')
        basis_gates = []  # unroll to base gates
        unroller = unroll.Unroller(
            qasm.Qasm(data=self.qp.get_qasm("example")).parse(),
                      unroll.JsonBackend(basis_gates))
        circuit = unroller.execute()
        config = {'shots': shots, 'seed': self.seed}
        job = {'compiled_circuit': circuit, 'config': config}
        result = QasmSimulator(job).run()
        self.assertEqual(result['status'], 'DONE')

    def test_qasm_simulator(self):
        """Test data counts output for single circuit run against reference."""
        shots = 1024
        self.qp.load_qasm_file(self.qasmFileName, name='example')
        basis_gates = []  # unroll to base gates
        unroller = unroll.Unroller(
            qasm.Qasm(data=self.qp.get_qasm("example")).parse(),
                      unroll.JsonBackend(basis_gates))
        circuit = unroller.execute()
        config = {'shots': shots, 'seed': self.seed}
        job = {'compiled_circuit': circuit, 'config': config}
        result = QasmSimulator(job).run()
        expected = {'100 100': 137, '011 011': 131, '101 101': 117, '111 111': 127,
                    '000 000': 131, '010 010': 141, '110 110': 116, '001 001': 124}
        self.assertEqual(result['data']['counts'], expected)

    def test_if_statement(self):
        self.log.info('test_if_statement_x')
        shots = 100
        max_qubits = 3
        qp = QuantumProgram()
        qr = qp.create_quantum_register('qr', max_qubits)
        cr = qp.create_classical_register('cr', max_qubits)
        circuit = qp.create_circuit('test_if', [qr], [cr])
        circuit.x(qr[0])
        circuit.x(qr[1])
        circuit.measure(qr[0], cr[0])
        circuit.measure(qr[1], cr[1])
        circuit.x(qr[2]).c_if(cr, 0x3)
        circuit.measure(qr[0], cr[0])
        circuit.measure(qr[1], cr[1])
        circuit.measure(qr[2], cr[2])
        circuit2 = qp.create_circuit('test_if_case_2', [qr], [cr])
        circuit2.x(qr[0])
        circuit2.measure(qr[0], cr[0])
        circuit2.measure(qr[1], cr[1])
        circuit2.x(qr[2]).c_if(cr, 0x3)
        circuit2.measure(qr[0], cr[0])
        circuit2.measure(qr[1], cr[1])
        circuit2.measure(qr[2], cr[2])
        basis_gates = []  # unroll to base gates
        unroller = unroll.Unroller(
            qasm.Qasm(data=qp.get_qasm('test_if')).parse(),
            unroll.JsonBackend(basis_gates))
        ucircuit = unroller.execute()
        unroller = unroll.Unroller(
            qasm.Qasm(data=qp.get_qasm('test_if_case_2')).parse(),
            unroll.JsonBackend(basis_gates))
        ucircuit2 = unroller.execute()
        config = {'shots': shots, 'seed': self.seed}
        job = {'compiled_circuit': ucircuit, 'config': config}
        result_if_true = QasmSimulator(job).run()
        job = {'compiled_circuit': ucircuit2, 'config': config}
        result_if_false = QasmSimulator(job).run()

        self.log.info('result_if_true circuit:')
        self.log.info(circuit.qasm())
        self.log.info('result_if_true={0}'.format(result_if_true))

        del circuit.data[1]
        self.log.info('result_if_false circuit:')
        self.log.info(circuit.qasm())
        self.log.info('result_if_false={0}'.format(result_if_false))
        self.assertTrue(result_if_true['data']['counts']['111'] == 100)
        self.assertTrue(result_if_false['data']['counts']['001'] == 100)

    def test_teleport(self):
        """test teleportation as in tutorials"""

        self.log.info('test_teleport')
        pi = np.pi
        shots = 1000
        qp = QuantumProgram()
        qr = qp.create_quantum_register('qr', 3)
        cr0 = qp.create_classical_register('cr0', 1)
        cr1 = qp.create_classical_register('cr1', 1)
        cr2 = qp.create_classical_register('cr2', 1)
        circuit = qp.create_circuit('teleport', [qr],
                                    [cr0, cr1, cr2])
        circuit.h(qr[1])
        circuit.cx(qr[1], qr[2])
        circuit.ry(pi/4, qr[0])
        circuit.cx(qr[0], qr[1])
        circuit.h(qr[0])
        circuit.barrier(qr)
        circuit.measure(qr[0], cr0[0])
        circuit.measure(qr[1], cr1[0])
        circuit.z(qr[2]).c_if(cr0, 1)
        circuit.x(qr[2]).c_if(cr1, 1)
        circuit.measure(qr[2], cr2[0])
        backend = 'local_qasm_simulator'
        qobj = qp.compile('teleport', backend=backend, shots=shots,
                   seed=self.seed)
        results = qp.run(qobj)
        data = results.get_counts('teleport')
        alice = {}
        bob = {}
        alice['00'] = data['0 0 0'] + data['1 0 0']
        alice['01'] = data['0 1 0'] + data['1 1 0']
        alice['10'] = data['0 0 1'] + data['1 0 1']
        alice['11'] = data['0 1 1'] + data['1 1 1']
        bob['0'] = data['0 0 0'] + data['0 1 0'] +  data['0 0 1'] + data['0 1 1']
        bob['1'] = data['1 0 0'] + data['1 1 0'] +  data['1 0 1'] + data['1 1 1']
        self.log.info('test_telport: circuit:')
        self.log.info( circuit.qasm() )
        self.log.info('test_teleport: data {0}'.format(data))
        self.log.info('test_teleport: alice {0}'.format(alice))
        self.log.info('test_teleport: bob {0}'.format(bob))
        alice_ratio = 1/np.tan(pi/8)**2
        bob_ratio = bob['0']/float(bob['1'])
        error = abs(alice_ratio - bob_ratio) / alice_ratio
        self.log.info('test_teleport: relative error = {0:.4f}'.format(error))
        self.assertLess(error, 0.05)

    def profile_qasm_simulator(self):
        """Profile randomly generated circuits.

        Writes profile results to <this_module>.prof as well as recording
        to the log file.

        number of circuits = 100.
        number of operations/circuit in [1, 40]
        number of qubits in [1, 5]
        """
        seed = 88
        shots = 1024
        nCircuits = 100
        minDepth = 1
        maxDepth = 40
        minQubits = 1
        maxQubits = 5
        pr = cProfile.Profile()
        randomCircuits = RandomQasmGenerator(seed,
                                             minQubits=minQubits,
                                             maxQubits=maxQubits,
                                             minDepth=minDepth,
                                             maxDepth=maxDepth)
        randomCircuits.add_circuits(nCircuits)
        self.qp = randomCircuits.getProgram()
        pr.enable()
        self.qp.execute(self.qp.get_circuit_names(),
                        backend='local_qasm_simulator',
                        shots=shots)
        pr.disable()
        sout = io.StringIO()
        ps = pstats.Stats(pr, stream=sout).sort_stats('cumulative')
        self.log.info('------- start profiling QasmSimulator -----------')
        ps.print_stats()
        self.log.info(sout.getvalue())
        self.log.info('------- stop profiling QasmSimulator -----------')
        sout.close()
        pr.dump_stats(self.moduleName + '.prof')

    def profile_nqubit_speed_grow_depth(self):
        """simulation time vs the number of qubits

        where the circuit depth is 10x the number of simulated
        qubits. Also creates a pdf file with this module name showing a
        plot of the results. Compilation is not included in speed.
        """
        import matplotlib.pyplot as plt
        from matplotlib.ticker import MaxNLocator
        qubitRangeMax = 15
        nQubitList = range(1,qubitRangeMax + 1)
        nCircuits = 10
        shots = 1024
        seed = 88
        maxTime = 30 # seconds; timing stops when simulation time exceeds this number
        fmtStr1 = 'profile_nqubit_speed::nqubits:{0}, backend:{1}, elapsed_time:{2:.2f}'
        fmtStr2 = 'backend:{0}, circuit:{1}, numOps:{2}, result:{3}'
        fmtStr3 = 'minDepth={minDepth}, maxDepth={maxDepth}, num circuits={nCircuits}, shots={shots}'
        backendList = ['local_qasm_simulator', 'local_unitary_simulator']
        if shutil.which('qasm_simulator'):
            backendList.append('local_qasm_cpp_simulator')
        else:
            self.log.info('profile_nqubit_speed::\"qasm_simulator\" executable not in path...skipping')
        fig = plt.figure(0)
        plt.clf()
        ax = fig.add_axes((0.1, 0.25, 0.8, 0.6))
        for i, backend in enumerate(backendList):
            elapsedTime = np.zeros(len(nQubitList))
            if backend is 'local_unitary_simulator':
                doMeasure = False
            else:
                doMeasure = True
            j, timedOut = 0, False
            while j < qubitRangeMax and not timedOut:
                nQubits = nQubitList[j]
                randomCircuits = RandomQasmGenerator(seed,
                                                     minQubits=nQubits,
                                                     maxQubits=nQubits,
                                                     minDepth=nQubits*10,
                                                     maxDepth=nQubits*10)
                randomCircuits.add_circuits(nCircuits, doMeasure=doMeasure)
                qp = randomCircuits.getProgram()
                cnames = qp.get_circuit_names()
                qobj = qp.compile(cnames, backend=backend, shots=shots,
                                  seed=seed)
                start = time.perf_counter()
                results = qp.run(qobj)
                stop = time.perf_counter()
                elapsedTime[j] = stop - start
                if elapsedTime[j] > maxTime:
                    timedOut = True
                self.log.info(fmtStr1.format(nQubits, backend, elapsedTime[j]))
                if backend is not 'local_unitary_simulator':
                    for name in cnames:
                        self.log.info(fmtStr2.format(
                            backend, name, len(qp.get_circuit(name)),
                            results.get_data(name)))
                j += 1
            ax.xaxis.set_major_locator(MaxNLocator(integer=True))
            if backend is 'local_unitary_simulator':
                ax.plot(nQubitList[:j], elapsedTime[:j], label=backend, marker='o')
            else:
                ax.plot(nQubitList[:j], elapsedTime[:j]/shots, label=backend,
                        marker='o')
            ax.set_yscale('log', basey=10)
            ax.set_xlabel('number of qubits')
            ax.set_ylabel('process time/shot')
            ax.set_title('profile_nqubit_speed_grow_depth')
            fig.text(0.1, 0.05,
                     fmtStr3.format(minDepth='10*nQubits', maxDepth='10*nQubits',
                                    nCircuits=nCircuits, shots=shots))
            ax.legend()
        self.pdf.savefig(fig)

    def profile_nqubit_speed_constant_depth(self):
        """simulation time vs the number of qubits

        where the circuit depth is fixed at 40. Also creates a pdf file
        with this module name showing a plot of the results. Compilation
        is not included in speed.
        """
        import matplotlib.pyplot as plt
        from matplotlib.ticker import MaxNLocator
        qubitRangeMax = 15
        nQubitList = range(1,qubitRangeMax + 1)
        maxDepth = 40
        minDepth = 40
        nCircuits = 10
        shots = 1024
        seed = 88
        maxTime = 30 # seconds; timing stops when simulation time exceeds this number
        fmtStr1 = 'profile_nqubit_speed::nqubits:{0}, backend:{1}, elapsed_time:{2:.2f}'
        fmtStr2 = 'backend:{0}, circuit:{1}, numOps:{2}, result:{3}'
        fmtStr3 = 'minDepth={minDepth}, maxDepth={maxDepth}, num circuits={nCircuits}, shots={shots}'
        backendList = ['local_qasm_simulator', 'local_unitary_simulator']
        if shutil.which('qasm_simulator'):
            backendList.append('local_qasm_cpp_simulator')
        else:
            self.log.info('profile_nqubit_speed::\"qasm_simulator\" executable not in path...skipping')
        fig = plt.figure(0)
        plt.clf()
        ax = fig.add_axes((0.1, 0.2, 0.8, 0.6))
        for i, backend in enumerate(backendList):
            elapsedTime = np.zeros(len(nQubitList))
            if backend is 'local_unitary_simulator':
                doMeasure = False
            else:
                doMeasure = True
            j, timedOut = 0, False
            while j < qubitRangeMax and not timedOut:
                nQubits = nQubitList[j]
                randomCircuits = RandomQasmGenerator(seed,
                                                     minQubits=nQubits,
                                                     maxQubits=nQubits,
                                                     minDepth=minDepth,
                                                     maxDepth=maxDepth)
                randomCircuits.add_circuits(nCircuits, doMeasure=doMeasure)
                qp = randomCircuits.getProgram()
                cnames = qp.get_circuit_names()
                qobj = qp.compile(cnames, backend=backend, shots=shots, seed=seed)
                start = time.perf_counter()
                results = qp.run(qobj)
                stop = time.perf_counter()
                elapsedTime[j] = stop - start
                if elapsedTime[j] > maxTime:
                    timedOut = True
                self.log.info(fmtStr1.format(nQubits, backend, elapsedTime[j]))
                if backend is not 'local_unitary_simulator':
                    for name in cnames:
                        self.log.info(fmtStr2.format(
                            backend, name, len(qp.get_circuit(name)),
                            results.get_data(name)))
                j += 1
            ax.xaxis.set_major_locator(MaxNLocator(integer=True))
            if backend is 'local_unitary_simulator':
                ax.plot(nQubitList[:j], elapsedTime[:j], label=backend, marker='o')
            else:
                ax.plot(nQubitList[:j], elapsedTime[:j]/shots, label=backend,
                        marker='o')
            ax.set_yscale('log', basey=10)
            ax.set_xlabel('number of qubits')
            ax.set_ylabel('process time/shot')
            ax.set_title('profile_nqubit_speed_constant_depth')
            fig.text(0.1, 0.05,
                     fmtStr3.format(minDepth=minDepth, maxDepth=maxDepth,
                                    nCircuits=nCircuits, shots=shots))
            ax.legend()
        self.pdf.savefig(fig)
Пример #28
0
class LocalSimulatorTest(unittest.TestCase):
    """
    Test interface to local simulators.
    """
    @classmethod
    def setUpClass(cls):
        cls.moduleName = os.path.splitext(__file__)[0]
        cls.logFileName = cls.moduleName + '.log'
        log_fmt = 'LocalSimulatorTest:%(levelname)s:%(asctime)s: %(message)s'
        logging.basicConfig(filename=cls.logFileName,
                            level=logging.INFO,
                            format=log_fmt)

    @classmethod
    def tearDownClass(cls):
        #cls.pdf.close()
        pass

    def setUp(self):
        self.seed = 88
        self.qasmFileName = os.path.join(qiskit.__path__[0],
                                         '../test/python/qasm/example.qasm')
        self.qp = QuantumProgram()
        shots = 1
        self.qp.load_qasm_file(self.qasmFileName, name='example')
        basis_gates = []  # unroll to base gates
        unroller = unroll.Unroller(
            qasm.Qasm(data=self.qp.get_qasm("example")).parse(),
            unroll.JsonBackend(basis_gates))
        circuit = unroller.execute()
        self.job = {
            'compiled_circuit': circuit,
            'config': {
                'shots': shots,
                'seed': random.randint(0, 10)
            }
        }

    def tearDown(self):
        pass

    def test_local_configuration_present(self):
        self.assertTrue(_localsimulator.local_configuration)

    def test_local_configurations(self):
        required_keys = [
            'name', 'url', 'simulator', 'description', 'coupling_map',
            'basis_gates'
        ]
        for conf in _localsimulator.local_configuration:
            for key in required_keys:
                self.assertIn(key, conf.keys())

    def test_simulator_classes(self):
        cdict = _localsimulator._simulator_classes
        cdict = getattr(_localsimulator, '_simulator_classes')
        logging.info('found local simulators: {0}'.format(repr(cdict)))
        self.assertTrue(cdict)

    def test_local_backends(self):
        backends = _localsimulator.local_backends()
        logging.info('found local backends: {0}'.format(repr(backends)))
        self.assertTrue(backends)

    def test_instantiation(self):
        """
        Test instantiation of LocalSimulator
        """
        backend_list = _localsimulator.local_backends()
        for backend_name in backend_list:
            backend = _localsimulator.LocalSimulator(backend_name, self.job)
Пример #29
0
class LocalQasmSimulatorTest(unittest.TestCase):
    """Test local qasm simulator."""
    @classmethod
    def setUpClass(cls):
        cls.moduleName = os.path.splitext(__file__)[0]
        cls.pdf = PdfPages(cls.moduleName + '.pdf')
        cls.log = logging.getLogger(__name__)
        cls.log.setLevel(logging.INFO)
        logFileName = cls.moduleName + '.log'
        handler = logging.FileHandler(logFileName)
        handler.setLevel(logging.INFO)
        log_fmt = ('{}.%(funcName)s:%(levelname)s:%(asctime)s:'
                   ' %(message)s'.format(cls.__name__))
        formatter = logging.Formatter(log_fmt)
        handler.setFormatter(formatter)
        cls.log.addHandler(handler)

    @classmethod
    def tearDownClass(cls):
        cls.pdf.close()

    def setUp(self):
        self.seed = 88
        self.qasmFileName = os.path.join(qiskit.__path__[0],
                                         '../test/python/qasm/example.qasm')
        self.qp = QuantumProgram()

    def tearDown(self):
        pass

    def test_qasm_simulator_single_shot(self):
        """Test single shot run."""
        shots = 1
        self.qp.load_qasm_file(self.qasmFileName, name='example')
        basis_gates = []  # unroll to base gates
        unroller = unroll.Unroller(
            qasm.Qasm(data=self.qp.get_qasm("example")).parse(),
            unroll.JsonBackend(basis_gates))
        circuit = unroller.execute()
        config = {'shots': shots, 'seed': self.seed}
        job = {'compiled_circuit': circuit, 'config': config}
        result = QasmSimulator(job).run()
        self.assertEqual(result['status'], 'DONE')

    def test_qasm_simulator(self):
        """Test data counts output for single circuit run against reference."""
        shots = 1024
        self.qp.load_qasm_file(self.qasmFileName, name='example')
        basis_gates = []  # unroll to base gates
        unroller = unroll.Unroller(
            qasm.Qasm(data=self.qp.get_qasm("example")).parse(),
            unroll.JsonBackend(basis_gates))
        circuit = unroller.execute()
        config = {'shots': shots, 'seed': self.seed}
        job = {'compiled_circuit': circuit, 'config': config}
        result = QasmSimulator(job).run()
        expected = {
            '100 100': 137,
            '011 011': 131,
            '101 101': 117,
            '111 111': 127,
            '000 000': 131,
            '010 010': 141,
            '110 110': 116,
            '001 001': 124
        }
        self.assertEqual(result['data']['counts'], expected)

    def test_if_statement(self):
        self.log.info('test_if_statement_x')
        shots = 100
        max_qubits = 3
        qp = QuantumProgram()
        qr = qp.create_quantum_register('qr', max_qubits)
        cr = qp.create_classical_register('cr', max_qubits)
        circuit = qp.create_circuit('test_if', [qr], [cr])
        circuit.x(qr[0])
        circuit.x(qr[1])
        circuit.measure(qr[0], cr[0])
        circuit.measure(qr[1], cr[1])
        circuit.x(qr[2]).c_if(cr, 0x3)
        circuit.measure(qr[0], cr[0])
        circuit.measure(qr[1], cr[1])
        circuit.measure(qr[2], cr[2])
        circuit2 = qp.create_circuit('test_if_case_2', [qr], [cr])
        circuit2.x(qr[0])
        circuit2.measure(qr[0], cr[0])
        circuit2.measure(qr[1], cr[1])
        circuit2.x(qr[2]).c_if(cr, 0x3)
        circuit2.measure(qr[0], cr[0])
        circuit2.measure(qr[1], cr[1])
        circuit2.measure(qr[2], cr[2])
        basis_gates = []  # unroll to base gates
        unroller = unroll.Unroller(
            qasm.Qasm(data=qp.get_qasm('test_if')).parse(),
            unroll.JsonBackend(basis_gates))
        ucircuit = unroller.execute()
        unroller = unroll.Unroller(
            qasm.Qasm(data=qp.get_qasm('test_if_case_2')).parse(),
            unroll.JsonBackend(basis_gates))
        ucircuit2 = unroller.execute()
        config = {'shots': shots, 'seed': self.seed}
        job = {'compiled_circuit': ucircuit, 'config': config}
        result_if_true = QasmSimulator(job).run()
        job = {'compiled_circuit': ucircuit2, 'config': config}
        result_if_false = QasmSimulator(job).run()

        self.log.info('result_if_true circuit:')
        self.log.info(circuit.qasm())
        self.log.info('result_if_true={0}'.format(result_if_true))

        del circuit.data[1]
        self.log.info('result_if_false circuit:')
        self.log.info(circuit.qasm())
        self.log.info('result_if_false={0}'.format(result_if_false))
        self.assertTrue(result_if_true['data']['counts']['111'] == 100)
        self.assertTrue(result_if_false['data']['counts']['001'] == 100)

    def test_teleport(self):
        """test teleportation as in tutorials"""

        self.log.info('test_teleport')
        pi = np.pi
        shots = 1000
        qp = QuantumProgram()
        qr = qp.create_quantum_register('qr', 3)
        cr0 = qp.create_classical_register('cr0', 1)
        cr1 = qp.create_classical_register('cr1', 1)
        cr2 = qp.create_classical_register('cr2', 1)
        circuit = qp.create_circuit('teleport', [qr], [cr0, cr1, cr2])
        circuit.h(qr[1])
        circuit.cx(qr[1], qr[2])
        circuit.ry(pi / 4, qr[0])
        circuit.cx(qr[0], qr[1])
        circuit.h(qr[0])
        circuit.barrier(qr)
        circuit.measure(qr[0], cr0[0])
        circuit.measure(qr[1], cr1[0])
        circuit.z(qr[2]).c_if(cr0, 1)
        circuit.x(qr[2]).c_if(cr1, 1)
        circuit.measure(qr[2], cr2[0])
        backend = 'local_qasm_simulator'
        qobj = qp.compile('teleport',
                          backend=backend,
                          shots=shots,
                          seed=self.seed)
        results = qp.run(qobj)
        data = results.get_counts('teleport')
        alice = {}
        bob = {}
        alice['00'] = data['0 0 0'] + data['1 0 0']
        alice['01'] = data['0 1 0'] + data['1 1 0']
        alice['10'] = data['0 0 1'] + data['1 0 1']
        alice['11'] = data['0 1 1'] + data['1 1 1']
        bob['0'] = data['0 0 0'] + data['0 1 0'] + data['0 0 1'] + data['0 1 1']
        bob['1'] = data['1 0 0'] + data['1 1 0'] + data['1 0 1'] + data['1 1 1']
        self.log.info('test_telport: circuit:')
        self.log.info(circuit.qasm())
        self.log.info('test_teleport: data {0}'.format(data))
        self.log.info('test_teleport: alice {0}'.format(alice))
        self.log.info('test_teleport: bob {0}'.format(bob))
        alice_ratio = 1 / np.tan(pi / 8)**2
        bob_ratio = bob['0'] / float(bob['1'])
        error = abs(alice_ratio - bob_ratio) / alice_ratio
        self.log.info('test_teleport: relative error = {0:.4f}'.format(error))
        self.assertLess(error, 0.05)

    def profile_qasm_simulator(self):
        """Profile randomly generated circuits.

        Writes profile results to <this_module>.prof as well as recording
        to the log file.

        number of circuits = 100.
        number of operations/circuit in [1, 40]
        number of qubits in [1, 5]
        """
        seed = 88
        shots = 1024
        nCircuits = 100
        minDepth = 1
        maxDepth = 40
        minQubits = 1
        maxQubits = 5
        pr = cProfile.Profile()
        randomCircuits = RandomQasmGenerator(seed,
                                             minQubits=minQubits,
                                             maxQubits=maxQubits,
                                             minDepth=minDepth,
                                             maxDepth=maxDepth)
        randomCircuits.add_circuits(nCircuits)
        self.qp = randomCircuits.getProgram()
        pr.enable()
        self.qp.execute(self.qp.get_circuit_names(),
                        backend='local_qasm_simulator',
                        shots=shots)
        pr.disable()
        sout = io.StringIO()
        ps = pstats.Stats(pr, stream=sout).sort_stats('cumulative')
        self.log.info('------- start profiling QasmSimulator -----------')
        ps.print_stats()
        self.log.info(sout.getvalue())
        self.log.info('------- stop profiling QasmSimulator -----------')
        sout.close()
        pr.dump_stats(self.moduleName + '.prof')

    def profile_nqubit_speed_grow_depth(self):
        """simulation time vs the number of qubits

        where the circuit depth is 10x the number of simulated
        qubits. Also creates a pdf file with this module name showing a
        plot of the results. Compilation is not included in speed.
        """
        import matplotlib.pyplot as plt
        from matplotlib.ticker import MaxNLocator
        qubitRangeMax = 15
        nQubitList = range(1, qubitRangeMax + 1)
        nCircuits = 10
        shots = 1024
        seed = 88
        maxTime = 30  # seconds; timing stops when simulation time exceeds this number
        fmtStr1 = 'profile_nqubit_speed::nqubits:{0}, backend:{1}, elapsed_time:{2:.2f}'
        fmtStr2 = 'backend:{0}, circuit:{1}, numOps:{2}, result:{3}'
        fmtStr3 = 'minDepth={minDepth}, maxDepth={maxDepth}, num circuits={nCircuits}, shots={shots}'
        backendList = ['local_qasm_simulator', 'local_unitary_simulator']
        if shutil.which('qasm_simulator'):
            backendList.append('local_qasm_cpp_simulator')
        else:
            self.log.info(
                'profile_nqubit_speed::\"qasm_simulator\" executable not in path...skipping'
            )
        fig = plt.figure(0)
        plt.clf()
        ax = fig.add_axes((0.1, 0.25, 0.8, 0.6))
        for i, backend in enumerate(backendList):
            elapsedTime = np.zeros(len(nQubitList))
            if backend is 'local_unitary_simulator':
                doMeasure = False
            else:
                doMeasure = True
            j, timedOut = 0, False
            while j < qubitRangeMax and not timedOut:
                nQubits = nQubitList[j]
                randomCircuits = RandomQasmGenerator(seed,
                                                     minQubits=nQubits,
                                                     maxQubits=nQubits,
                                                     minDepth=nQubits * 10,
                                                     maxDepth=nQubits * 10)
                randomCircuits.add_circuits(nCircuits, doMeasure=doMeasure)
                qp = randomCircuits.getProgram()
                cnames = qp.get_circuit_names()
                qobj = qp.compile(cnames,
                                  backend=backend,
                                  shots=shots,
                                  seed=seed)
                start = time.perf_counter()
                results = qp.run(qobj)
                stop = time.perf_counter()
                elapsedTime[j] = stop - start
                if elapsedTime[j] > maxTime:
                    timedOut = True
                self.log.info(fmtStr1.format(nQubits, backend, elapsedTime[j]))
                if backend is not 'local_unitary_simulator':
                    for name in cnames:
                        self.log.info(
                            fmtStr2.format(backend, name,
                                           len(qp.get_circuit(name)),
                                           results.get_data(name)))
                j += 1
            ax.xaxis.set_major_locator(MaxNLocator(integer=True))
            if backend is 'local_unitary_simulator':
                ax.plot(nQubitList[:j],
                        elapsedTime[:j],
                        label=backend,
                        marker='o')
            else:
                ax.plot(nQubitList[:j],
                        elapsedTime[:j] / shots,
                        label=backend,
                        marker='o')
            ax.set_yscale('log', basey=10)
            ax.set_xlabel('number of qubits')
            ax.set_ylabel('process time/shot')
            ax.set_title('profile_nqubit_speed_grow_depth')
            fig.text(
                0.1, 0.05,
                fmtStr3.format(minDepth='10*nQubits',
                               maxDepth='10*nQubits',
                               nCircuits=nCircuits,
                               shots=shots))
            ax.legend()
        self.pdf.savefig(fig)

    def profile_nqubit_speed_constant_depth(self):
        """simulation time vs the number of qubits

        where the circuit depth is fixed at 40. Also creates a pdf file
        with this module name showing a plot of the results. Compilation
        is not included in speed.
        """
        import matplotlib.pyplot as plt
        from matplotlib.ticker import MaxNLocator
        qubitRangeMax = 15
        nQubitList = range(1, qubitRangeMax + 1)
        maxDepth = 40
        minDepth = 40
        nCircuits = 10
        shots = 1024
        seed = 88
        maxTime = 30  # seconds; timing stops when simulation time exceeds this number
        fmtStr1 = 'profile_nqubit_speed::nqubits:{0}, backend:{1}, elapsed_time:{2:.2f}'
        fmtStr2 = 'backend:{0}, circuit:{1}, numOps:{2}, result:{3}'
        fmtStr3 = 'minDepth={minDepth}, maxDepth={maxDepth}, num circuits={nCircuits}, shots={shots}'
        backendList = ['local_qasm_simulator', 'local_unitary_simulator']
        if shutil.which('qasm_simulator'):
            backendList.append('local_qasm_cpp_simulator')
        else:
            self.log.info(
                'profile_nqubit_speed::\"qasm_simulator\" executable not in path...skipping'
            )
        fig = plt.figure(0)
        plt.clf()
        ax = fig.add_axes((0.1, 0.2, 0.8, 0.6))
        for i, backend in enumerate(backendList):
            elapsedTime = np.zeros(len(nQubitList))
            if backend is 'local_unitary_simulator':
                doMeasure = False
            else:
                doMeasure = True
            j, timedOut = 0, False
            while j < qubitRangeMax and not timedOut:
                nQubits = nQubitList[j]
                randomCircuits = RandomQasmGenerator(seed,
                                                     minQubits=nQubits,
                                                     maxQubits=nQubits,
                                                     minDepth=minDepth,
                                                     maxDepth=maxDepth)
                randomCircuits.add_circuits(nCircuits, doMeasure=doMeasure)
                qp = randomCircuits.getProgram()
                cnames = qp.get_circuit_names()
                qobj = qp.compile(cnames,
                                  backend=backend,
                                  shots=shots,
                                  seed=seed)
                start = time.perf_counter()
                results = qp.run(qobj)
                stop = time.perf_counter()
                elapsedTime[j] = stop - start
                if elapsedTime[j] > maxTime:
                    timedOut = True
                self.log.info(fmtStr1.format(nQubits, backend, elapsedTime[j]))
                if backend is not 'local_unitary_simulator':
                    for name in cnames:
                        self.log.info(
                            fmtStr2.format(backend, name,
                                           len(qp.get_circuit(name)),
                                           results.get_data(name)))
                j += 1
            ax.xaxis.set_major_locator(MaxNLocator(integer=True))
            if backend is 'local_unitary_simulator':
                ax.plot(nQubitList[:j],
                        elapsedTime[:j],
                        label=backend,
                        marker='o')
            else:
                ax.plot(nQubitList[:j],
                        elapsedTime[:j] / shots,
                        label=backend,
                        marker='o')
            ax.set_yscale('log', basey=10)
            ax.set_xlabel('number of qubits')
            ax.set_ylabel('process time/shot')
            ax.set_title('profile_nqubit_speed_constant_depth')
            fig.text(
                0.1, 0.05,
                fmtStr3.format(minDepth=minDepth,
                               maxDepth=maxDepth,
                               nCircuits=nCircuits,
                               shots=shots))
            ax.legend()
        self.pdf.savefig(fig)
Пример #30
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)
Пример #31
0
class LocalUnitarySimulatorTest(QiskitTestCase):
    """Test local unitary simulator."""
    def setUp(self):
        self.seed = 88
        self.qasm_filename = self._get_resource_path('qasm/example.qasm')
        self.qp = QuantumProgram()

    def tearDown(self):
        pass

    def test_unitary_simulator(self):
        """test generation of circuit unitary"""
        self.qp.load_qasm_file(self.qasm_filename, name='example')
        basis_gates = []  # unroll to base gates
        unroller = unroll.Unroller(
            qasm.Qasm(data=self.qp.get_qasm('example')).parse(),
            unroll.JsonBackend(basis_gates))
        circuit = unroller.execute()
        # strip measurements from circuit to avoid warnings
        circuit['operations'] = [
            op for op in circuit['operations'] if op['name'] != 'measure'
        ]
        # the simulator is expecting a JSON format, so we need to convert it
        # back to JSON
        qobj = {
            'id':
            'unitary',
            'config': {
                'max_credits': None,
                'shots': 1,
                'backend_name': 'local_unitary_simulator_py'
            },
            'circuits': [{
                'name': 'test',
                'compiled_circuit': circuit,
                'compiled_circuit_qasm': self.qp.get_qasm('example'),
                'config': {
                    'coupling_map': None,
                    'basis_gates': None,
                    'layout': None,
                    'seed': None
                }
            }]
        }
        # numpy.savetxt currently prints complex numbers in a way
        # loadtxt can't read. To save file do,
        # fmtstr=['% .4g%+.4gj' for i in range(numCols)]
        # np.savetxt('example_unitary_matrix.dat', numpyMatrix, fmt=fmtstr,
        # delimiter=',')
        expected = np.loadtxt(
            self._get_resource_path('example_unitary_matrix.dat'),
            dtype='complex',
            delimiter=',')
        q_job = QuantumJob(qobj,
                           backend=UnitarySimulatorPy(),
                           preformatted=True)

        result = UnitarySimulatorPy().run(q_job).result()
        self.assertTrue(
            np.allclose(result.get_unitary('test'), expected, rtol=1e-3))

    def test_two_unitary_simulator(self):
        """test running two circuits

        This test is similar to one in test_quantumprogram but doesn't use
        multiprocessing.
        """
        qr = QuantumRegister(2)
        cr = ClassicalRegister(1)
        qc1 = QuantumCircuit(qr, cr)
        qc2 = QuantumCircuit(qr, cr)
        qc1.h(qr)
        qc2.cx(qr[0], qr[1])
        backend = UnitarySimulatorPy()
        qobj = compile([qc1, qc2], backend=backend)
        job = backend.run(QuantumJob(qobj, backend=backend, preformatted=True))
        unitary1 = job.result().get_unitary(qc1)
        unitary2 = job.result().get_unitary(qc2)
        unitaryreal1 = np.array([[0.5, 0.5, 0.5, 0.5], [0.5, -0.5, 0.5, -0.5],
                                 [0.5, 0.5, -0.5, -0.5],
                                 [0.5, -0.5, -0.5, 0.5]])
        unitaryreal2 = np.array([[1, 0, 0, 0], [0, 0, 0, 1], [0., 0, 1, 0],
                                 [0, 1, 0, 0]])
        norm1 = np.trace(np.dot(np.transpose(np.conj(unitaryreal1)), unitary1))
        norm2 = np.trace(np.dot(np.transpose(np.conj(unitaryreal2)), unitary2))
        self.assertAlmostEqual(norm1, 4)
        self.assertAlmostEqual(norm2, 4)

    def profile_unitary_simulator(self):
        """Profile randomly generated circuits.

        Writes profile results to <this_module>.prof as well as recording
        to the log file.

        number of circuits = 100.
        number of operations/circuit in [1, 40]
        number of qubits in [1, 5]
        """
        n_circuits = 100
        max_depth = 40
        max_qubits = 5
        pr = cProfile.Profile()
        random_circuits = RandomQasmGenerator(seed=self.seed,
                                              max_depth=max_depth,
                                              max_qubits=max_qubits)
        random_circuits.add_circuits(n_circuits, do_measure=False)
        self.qp = random_circuits.get_program()
        pr.enable()
        self.qp.execute(self.qp.get_circuit_names(),
                        backend=UnitarySimulatorPy())
        pr.disable()
        sout = io.StringIO()
        ps = pstats.Stats(pr, stream=sout).sort_stats('cumulative')
        self.log.info('------- start profiling UnitarySimulatorPy -----------')
        ps.print_stats()
        self.log.info(sout.getvalue())
        self.log.info('------- stop profiling UnitarySimulatorPy -----------')
        sout.close()
        pr.dump_stats(self.moduleName + '.prof')
Пример #32
0
class UnitarySimulatorSympyTest(QiskitTestCase):
    """Test local unitary simulator sympy."""
    def setUp(self):
        self.seed = 88
        self.qasm_filename = self._get_resource_path('qasm/simple.qasm')
        self.qp = QuantumProgram()

    def test_unitary_simulator(self):
        """test generation of circuit unitary"""
        self.qp.load_qasm_file(self.qasm_filename, name='example')
        basis_gates = []  # unroll to base gates
        unroller = unroll.Unroller(
            qasm.Qasm(data=self.qp.get_qasm('example')).parse(),
            unroll.JsonBackend(basis_gates))
        circuit = unroller.execute()
        # strip measurements from circuit to avoid warnings
        circuit['operations'] = [
            op for op in circuit['operations'] if op['name'] != 'measure'
        ]
        # the simulator is expecting a JSON format, so we need to convert it
        # back to JSON
        qobj = {
            'id':
            'unitary',
            'config': {
                'max_credits': None,
                'shots': 1,
                'backend_name': 'local_sympy_unitary_simulator'
            },
            'circuits': [{
                'name': 'test',
                'compiled_circuit': circuit,
                'compiled_circuit_qasm': self.qp.get_qasm('example'),
                'config': {
                    'coupling_map': None,
                    'basis_gates': None,
                    'layout': None,
                    'seed': None
                }
            }]
        }

        q_job = QuantumJob(qobj,
                           backend=UnitarySimulatorSympy(),
                           preformatted=True)

        result = UnitarySimulatorSympy().run(q_job).result()
        actual = result.get_data('test')['unitary']

        self.assertEqual(actual[0][0], sqrt(2) / 2)
        self.assertEqual(actual[0][1], sqrt(2) / 2)
        self.assertEqual(actual[0][2], 0)
        self.assertEqual(actual[0][3], 0)
        self.assertEqual(actual[1][0], 0)
        self.assertEqual(actual[1][1], 0)
        self.assertEqual(actual[1][2], sqrt(2) / 2)
        self.assertEqual(actual[1][3], -sqrt(2) / 2)
        self.assertEqual(actual[2][0], 0)
        self.assertEqual(actual[2][1], 0)
        self.assertEqual(actual[2][2], sqrt(2) / 2)
        self.assertEqual(actual[2][3], sqrt(2) / 2)
        self.assertEqual(actual[3][0], sqrt(2) / 2)
        self.assertEqual(actual[3][1], -sqrt(2) / 2)
        self.assertEqual(actual[3][2], 0)
        self.assertEqual(actual[3][3], 0)