def test_run(self):
     backend = self._provider.get_backend('local_qasm_simulator_py')
     qobj = qiskit._compiler.compile(self._qc, backend)
     quantum_job = QuantumJob(qobj, backend, preformatted=True)
     job = backend.run(quantum_job)
     result = job.result()
     counts_qx = result.get_counts(result.get_names()[0])
     counts_ex = {'00': 512, '11': 512}
     states = counts_qx.keys() | counts_ex.keys()
     # contingency table
     ctable = numpy.array([[counts_qx.get(key, 0) for key in states],
                           [counts_ex.get(key, 0) for key in states]])
     contingency = chi2_contingency(ctable)
     self.log.info('chi2_contingency: %s', str(contingency))
     self.assertGreater(contingency[1], 0.01)
예제 #2
0
    def setUp(self):
        self.seed = 88
        self.qasm_filename = self._get_resource_path('qasm/example.qasm')
        with open(self.qasm_filename, 'r') as qasm_file:
            self.qasm_text = qasm_file.read()
            self.qasm_ast = qiskit.qasm.Qasm(data=self.qasm_text).parse()
            self.qasm_be = qiskit.unroll.CircuitBackend(['u1', 'u2', 'u3', 'id', 'cx'])
            self.qasm_circ = qiskit.unroll.Unroller(self.qasm_ast, self.qasm_be).execute()
        qr = QuantumRegister(2, 'q')
        cr = ClassicalRegister(2, 'c')
        qc = QuantumCircuit(qr, cr)
        qc.h(qr[0])
        qc.measure(qr[0], cr[0])
        self.qc = qc
        # create qobj
        compiled_circuit1 = qiskit._compiler.compile_circuit(self.qc, format='json')
        compiled_circuit2 = qiskit._compiler.compile_circuit(self.qasm_circ, format='json')
        self.qobj = {'id': 'test_qobj',
                     'config': {
                         'max_credits': 3,
                         'shots': 2000,
                         'backend_name': 'local_qasm_simulator_cpp',
                         'seed': 1111
                     },
                     'circuits': [
                         {
                             'name': 'test_circuit1',
                             'compiled_circuit': compiled_circuit1,
                             'basis_gates': 'u1,u2,u3,cx,id',
                             'layout': None,
                         },
                         {
                             'name': 'test_circuit2',
                             'compiled_circuit': compiled_circuit2,
                             'basis_gates': 'u1,u2,u3,cx,id',
                             'layout': None,
                         }
                     ]}
        # Simulator backend
        try:
            self.backend = QasmSimulatorCpp()
        except FileNotFoundError as fnferr:
            raise unittest.SkipTest(
                'cannot find {} in path'.format(fnferr))

        self.q_job = QuantumJob(self.qobj,
                                backend=self.backend,
                                preformatted=True)
    def test_run_async_device(self):
        backends = self._provider.available_backends({'simulator': False})
        backend = lowest_pending_jobs(backends)
        self.log.info('submitting to backend %s', backend.name)
        num_qubits = 5
        qr = QuantumRegister(num_qubits, 'qr')
        cr = ClassicalRegister(num_qubits, 'cr')
        qc = QuantumCircuit(qr, cr)
        for i in range(num_qubits - 1):
            qc.cx(qr[i], qr[i + 1])
        qc.measure(qr, cr)
        qobj = qiskit._compiler.compile(qc, backend)
        quantum_job = QuantumJob(qobj, backend, preformatted=True)
        num_jobs = 3
        job_array = [backend.run(quantum_job) for _ in range(num_jobs)]
        time.sleep(3)  # give time for jobs to start (better way?)
        job_status = [job.status['status'] for job in job_array]
        num_init = sum(
            [status == JobStatus.INITIALIZING for status in job_status])
        num_queued = sum([status == JobStatus.QUEUED for status in job_status])
        num_running = sum(
            [status == JobStatus.RUNNING for status in job_status])
        num_done = sum([status == JobStatus.DONE for status in job_status])
        num_error = sum([status == JobStatus.ERROR for status in job_status])
        self.log.info('number of currently initializing jobs: %d/%d', num_init,
                      num_jobs)
        self.log.info('number of currently queued jobs: %d/%d', num_queued,
                      num_jobs)
        self.log.info('number of currently running jobs: %d/%d', num_running,
                      num_jobs)
        self.log.info('number of currently done jobs: %d/%d', num_done,
                      num_jobs)
        self.log.info('number of errored jobs: %d/%d', num_error, num_jobs)
        self.assertTrue(num_jobs - num_error - num_done > 0)

        # Wait for all the results.
        result_array = [job.result() for job in job_array]

        # Ensure all jobs have finished.
        self.assertTrue(all([job.done for job in job_array]))
        self.assertTrue(
            all([
                result.get_status() == 'COMPLETED' for result in result_array
            ]))

        # Ensure job ids are unique.
        job_ids = [job.job_id for job in job_array]
        self.assertEqual(sorted(job_ids), sorted(list(set(job_ids))))
예제 #4
0
 def test_init_quantum_job_qobj(self):
     formatted_circuit = self.qasm_text
     backend = QasmSimulator()
     qobj = {'id': 'qobj_init',
             'config': {
                 'max_credits': 3,
                 'shots': 1024,
                 'seed': None,
                 'backend': backend},
             'circuits': [
                 {'name': 'example',
                  'compiled_circuit': formatted_circuit,
                  'layout': None,
                  'seed': None}
             ]}
     _ = QuantumJob(qobj, preformatted=True)
예제 #5
0
 def test_gate_x(self):
     shots = 100
     qr = QuantumRegister(1)
     cr = ClassicalRegister(1)
     qc = QuantumCircuit(qr, cr, name='test_gate_x')
     qc.x(qr[0])
     qc.measure(qr, cr)
     qobj = qiskit._compiler.compile([qc], pq_simulator, shots=shots)
     q_job = QuantumJob(
         qobj,
         pq_simulator,
         preformatted=True,
         resources={'max_credits': qobj['config']['max_credits']})
     job = pq_simulator.run(q_job)
     result_pq = job.result(timeout=30)
     self.assertEqual(result_pq.get_counts(result_pq.get_names()[0]),
                      {'1': shots})
 def setUp(self):
     self.seed = 88
     self.qasm_filename = os.path.join(qiskit.__path__[0],
                                       '../test/python/qasm/example.qasm')
     with open(self.qasm_filename, 'r') as qasm_file:
         self.qasm_text = qasm_file.read()
         self.qasm_ast = qiskit.qasm.Qasm(data=self.qasm_text).parse()
         self.qasm_be = qiskit.unroll.CircuitBackend(
             ['u1', 'u2', 'u3', 'id', 'cx'])
         self.qasm_circ = qiskit.unroll.Unroller(self.qasm_ast,
                                                 self.qasm_be).execute()
     qr = QuantumRegister('q', 2)
     cr = ClassicalRegister('c', 2)
     qc = QuantumCircuit(qr, cr)
     qc.h(qr[0])
     qc.measure(qr[0], cr[0])
     self.qc = qc
     # create qobj
     compiled_circuit1 = openquantumcompiler.compile(self.qc, format='json')
     compiled_circuit2 = openquantumcompiler.compile(self.qasm_circ,
                                                     format='json')
     self.qobj = {
         'id':
         'test_qobj',
         'config': {
             'max_credits': 3,
             'shots': 100,
             'backend': 'local_qiskit_simulator',
             'seed': 1111
         },
         'circuits': [{
             'name': 'test_circuit1',
             'compiled_circuit': compiled_circuit1,
             'basis_gates': 'u1,u2,u3,cx,id',
             'layout': None,
         }, {
             'name': 'test_circuit2',
             'compiled_circuit': compiled_circuit2,
             'basis_gates': 'u1,u2,u3,cx,id',
             'layout': None,
         }]
     }
     self.q_job = QuantumJob(self.qobj,
                             backend='local_qiskit_simulator',
                             preformatted=True)
예제 #7
0
 def test_cancel(self):
     if not self._using_hub:
         self.skipTest('job cancellation currently only available on hubs')
     backends = self._provider.available_backends({'simulator': False})
     self.log.info('devices: %s', [b.name for b in backends])
     backend = backends[0]
     self.log.info('using backend: %s', backend.name)
     num_qubits = 5
     qr = QuantumRegister(num_qubits, 'qr')
     cr = ClassicalRegister(num_qubits, 'cr')
     qc = QuantumCircuit(qr, cr)
     for i in range(num_qubits - 1):
         qc.cx(qr[i], qr[i + 1])
     qc.measure(qr, cr)
     qobj = qiskit._compiler.compile(qc, backend)
     quantum_job = QuantumJob(qobj, backend, preformatted=True)
     num_jobs = 3
     job_array = [backend.run(quantum_job) for _ in range(num_jobs)]
     success = False
     self.log.info('jobs submitted: %s', num_jobs)
     while any([
             job.status['status'] == JobStatus.INITIALIZING
             for job in job_array
     ]):
         self.log.info('jobs initializing')
         time.sleep(1)
     for job in job_array:
         job.cancel()
     while not success:
         job_status = [job.status for job in job_array]
         for status in job_status:
             self.log.info(status)
         if any([
                 status['status'] == JobStatus.CANCELLED
                 for status in job_status
         ]):
             success = True
         if all(
             [status['status'] == JobStatus.DONE for status in job_status]):
             raise IBMQJobError(
                 'all jobs completed before any could be cancelled')
         self.log.info('-' * 20)
         time.sleep(2)
     self.assertTrue(success)
예제 #8
0
def execute(circuits,
            backend,
            config=None,
            basis_gates=None,
            coupling_map=None,
            initial_layout=None,
            shots=1024,
            max_credits=10,
            seed=None,
            qobj_id=None,
            hpc=None,
            skip_translation=False):
    """Executes a set of circuits.

    Args:
        circuits (QuantumCircuit or list[QuantumCircuit]): circuits to execute
        backend (BaseBackend or str): a backend to execute the circuits on
        config (dict): dictionary of parameters (e.g. noise) used by runner
        basis_gates (str): comma-separated basis gate set to compile to
        coupling_map (list): coupling map (perhaps custom) to target in mapping
        initial_layout (list): initial layout of qubits in mapping
        shots (int): number of repetitions of each circuit, for sampling
        max_credits (int): maximum credits to use
        seed (int): random seed for simulators
        qobj_id (int): identifier for the generated qobj
        hpc (dict): HPC simulator parameters
        skip_translation (bool): skip most of the compile steps and produce qobj directly

    Returns:
        BaseJob: returns job instance derived from BaseJob
    """
    if isinstance(backend, str):
        backend = _DEFAULT_PROVIDER.get_backend(backend)
    qobj = compile(circuits, backend, config, basis_gates, coupling_map,
                   initial_layout, shots, max_credits, seed, qobj_id, hpc,
                   skip_translation)
    # XXX When qobj is done this should replace q_job
    q_job = QuantumJob(
        qobj,
        backend=backend,
        preformatted=True,
        resources={'max_credits': qobj['config']['max_credits']})
    return backend.run(q_job)
예제 #9
0
 def test_init_quantum_job_qobj(self):
     formatted_circuit = self.qasm_text
     backend = get_backend('local_qasm_simulator')
     qobj = {
         'id':
         'qobj_init',
         'config': {
             'max_credits': 3,
             'shots': 1024,
             'seed': None,
             'backend_name': backend.configuration['name']
         },
         'circuits': [{
             'name': 'example',
             'compiled_circuit': formatted_circuit,
             'layout': None,
             'seed': None
         }]
     }
     _ = QuantumJob(qobj, backend=backend, preformatted=True)
 def test_run_async(self):
     if sys.platform == 'darwin':
         LocalJob._executor = futures.ThreadPoolExecutor(max_workers=2)
     else:
         LocalJob._executor = futures.ProcessPoolExecutor(max_workers=2)
     try:
         backend = self._provider.get_backend('local_qasm_simulator_cpp')
     except KeyError:
         backend = self._provider.get_backend('local_qasm_simulator_py')
     num_qubits = 15
     qr = QuantumRegister(num_qubits, 'q')
     cr = ClassicalRegister(num_qubits, 'c')
     qc = QuantumCircuit(qr, cr)
     for i in range(num_qubits - 1):
         qc.cx(qr[i], qr[i + 1])
     qc.measure(qr, cr)
     qobj = qiskit._compiler.compile(qc, backend)
     quantum_job = QuantumJob(qobj, backend, preformatted=True)
     num_jobs = 5
     job_array = [backend.run(quantum_job) for _ in range(num_jobs)]
     found_async_jobs = False
     timeout = 30
     start_time = time.time()
     self.log.info('testing with simulator: %s', backend.name)
     while not found_async_jobs:
         check = sum([job.running for job in job_array])
         if check >= 2:
             self.log.info('found %d simultaneous jobs', check)
             found_async_jobs = True
         if all([job.done for job in job_array]):
             self.log.warning('all jobs completed before simultaneous jobs '
                              'could be detected')
             break
         for job in job_array:
             self.log.info('%s %s %s', job.status['status'], job.running,
                           check)
         self.log.info('%s %.4f', '-' * 20, time.time() - start_time)
         if time.time() - start_time > timeout:
             raise TimeoutError('failed to see multiple running jobs after '
                                '{0} s'.format(timeout))
         time.sleep(1)
예제 #11
0
 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)
예제 #12
0
    def test_mix_local_remote_jobs(self):
        """test mixing local and remote jobs

        Internally local jobs execute in seperate processes since
        they are CPU bound and remote jobs execute in seperate threads
        since they are I/O bound. The module gets results from potentially
        both kinds in one list. Test that this works.
        """
        njobs = 6
        job_list = []
        backend_type = ['local_qasm_simulator', 'ibmqx_qasm_simulator']
        i = 0
        for circuit in self.rqg.get_circuits(format_='QuantumCircuit')[:njobs]:
            compiled_circuit = openquantumcompiler.compile(circuit.qasm())
            backend = backend_type[i % len(backend_type)]
            self.log.info(backend)
            quantum_job = QuantumJob(compiled_circuit,
                                     backend=backend)
            job_list.append(quantum_job)
            i += 1
        jp = jobprocessor.JobProcessor(job_list, max_workers=None,
                                       callback=None)
        jp.submit()
예제 #13
0
    def test_run_async(self):
        backend = self._provider.get_backend('local_qasm_simulator_py')
        num_qubits = 5
        qr = QuantumRegister(num_qubits, 'q')
        cr = ClassicalRegister(num_qubits, 'c')
        qc = QuantumCircuit(qr, cr)
        for i in range(num_qubits - 1):
            qc.cx(qr[i], qr[i + 1])
        qc.measure(qr, cr)
        qobj = qiskit._compiler.compile(qc, backend)
        quantum_job = QuantumJob(qobj, backend, shots=1e5, preformatted=True)
        num_jobs = 5
        job_array = [backend.run(quantum_job) for _ in range(num_jobs)]

        # Wait for all the results.
        result_array = [job.result() for job in job_array]

        # Ensure all jobs have finished.
        self.assertTrue(all([job.done for job in job_array]))
        self.assertTrue(
            all([
                result.get_status() == 'COMPLETED' for result in result_array
            ]))
예제 #14
0
    def test_qobj_measure_opt_flag(self):
        filename = self._get_resource_path('qobj/cpp_measure_opt_flag.json')
        with open(filename, 'r') as file:
            q_job = QuantumJob(json.load(file),
                               backend=self.backend,
                               preformatted=True)
        result = self.backend.run(q_job).result()
        shots = q_job.qobj['config']['shots']
        sampled_measurements = {
            'measure (sampled)': True,
            'trivial (sampled)': True,
            'reset1 (shots)': False,
            'reset2 (shots)': False,
            'reset3 (shots)': False,
            'gate1 (shots)': False,
            'gate2 (shots)': False,
            'gate3 (shots)': False,
            'gate4 (shots)': False
        }

        for name in sampled_measurements:
            snapshots = result.get_snapshots(name)
            # Check snapshot keys
            self.assertEqual(set(snapshots), {'0'},
                             msg=name + ' snapshot keys')
            # Check number of snapshots
            # there should be 1 for measurement sampling optimization
            # and there should be >1 for each shot beign simulated.
            num_snapshots = len(snapshots['0'].get('statevector', []))
            if sampled_measurements[name] is True:
                self.assertEqual(num_snapshots,
                                 1,
                                 msg=name + ' snapshot length')
            else:
                self.assertEqual(num_snapshots,
                                 shots,
                                 msg=name + ' snapshot length')
예제 #15
0
    def test_conditionals(self):
        filename = self._get_resource_path('qobj/cpp_conditionals.json')
        with open(filename, 'r') as file:
            q_job = QuantumJob(json.load(file),
                               backend=self.backend,
                               preformatted=True)
        result = self.backend.run(q_job).result()
        expected_data = {
            'single creg (c0=0)': {
                'statevector': np.array([1, 0, 0, 0])
            },
            'single creg (c0=1)': {
                'statevector': np.array([0, 0, 0, 1])
            },
            'two creg (c1=0)': {
                'statevector': np.array([1, 0, 0, 0])
            },
            'two creg (c1=1)': {
                'statevector': np.array([0, 0, 0, 1])
            }
        }

        for name in expected_data:
            # Check snapshot
            snapshots = result.get_snapshots(name)
            self.assertEqual(set(snapshots), {'0'},
                             msg=name + ' snapshot keys')
            self.assertEqual(len(snapshots['0']),
                             1,
                             msg=name + ' snapshot length')
            state = snapshots['0']['statevector'][0]
            expected_state = expected_data[name]['statevector']
            fidelity = np.abs(expected_state.dot(state.conj()))**2
            self.assertAlmostEqual(fidelity,
                                   1.0,
                                   places=10,
                                   msg=name + ' snapshot fidelity')
예제 #16
0
    def test_error_in_job(self):
        def job_done_callback(results):
            try:
                for result in results:
                    self.log.info(pprint.pformat(result))
                    self.assertTrue(result.get_status() == 'ERROR')
            except Exception as e:
                self.job_processor_exception = e
            finally:
                self.job_processor_finished = True

        njobs = 5
        job_list = []
        for i in range(njobs):
            compiled_circuit = openquantumcompiler.compile(self.qc.qasm())
            quantum_job = QuantumJob(compiled_circuit,
                                     backend='local_qasm_simulator')
            job_list.append(quantum_job)

        self.job_processor_finished = False
        self.job_processor_exception = None
        jp = jobprocessor.JobProcessor(job_list,
                                       max_workers=None,
                                       callback=job_done_callback)
        tmp = jobprocessor.run_local_backend
        jobprocessor.run_local_backend = mock_run_local_backend

        jp.submit(silent=True)
        jobprocessor.run_local_backend = tmp

        while not self.job_processor_finished:
            # Wait until the job_done_callback is invoked and completed.
            pass

        if self.job_processor_exception:
            raise self.job_processor_exception
 def test_qobj_reset(self):
     filename = self._get_resource_path('qobj/cpp_reset.json')
     with open(filename, 'r') as file:
         q_job = QuantumJob(json.load(file),
                            backend='local_qasm_simulator_cpp',
                            preformatted=True)
     result = self.backend.run(q_job)
     expected_data = {
         'reset': {
             'quantum_state': np.array([1, 0])
         },
         'x reset': {
             'quantum_state': np.array([1, 0])
         },
         'y reset': {
             'quantum_state': np.array([1, 0])
         },
         'h reset': {
             'quantum_state': np.array([1, 0])
         }
     }
     for name in expected_data:
         # Check snapshot is |0> state
         snapshots = result.get_data(name).get('snapshots', {})
         self.assertEqual(set(snapshots), {'0'},
                          msg=name + ' snapshot keys')
         self.assertEqual(len(snapshots['0']),
                          1,
                          msg=name + ' snapshot length')
         state = snapshots['0']['quantum_state'][0]
         expected_state = expected_data[name]['quantum_state']
         fidelity = np.abs(expected_state.dot(state.conj()))**2
         self.assertAlmostEqual(fidelity,
                                1.0,
                                places=10,
                                msg=name + ' snapshot fidelity')
예제 #18
0
    def test_cancel(self):
        """Test the cancelation of jobs.

        Since only Jobs that are still in the executor queue pending to be
        executed can be cancelled, this test launches a lot of jobs, passing
        if some of them can be cancelled.
        """
        # Force the number of workers to 1, as only Jobs that are still in
        # the executor queue can be canceled.
        if sys.platform == 'darwin':
            LocalJob._executor = futures.ThreadPoolExecutor(max_workers=1)
        else:
            LocalJob._executor = futures.ProcessPoolExecutor(max_workers=1)

        backend = self._provider.get_backend('local_qasm_simulator_py')
        num_qubits = 5
        qr = QuantumRegister(num_qubits, 'q')
        cr = ClassicalRegister(num_qubits, 'c')
        qc = QuantumCircuit(qr, cr)
        for i in range(num_qubits - 1):
            qc.cx(qr[i], qr[i + 1])
        qc.measure(qr, cr)
        qobj = qiskit._compiler.compile(qc, backend)
        quantum_job = QuantumJob(qobj, backend, shots=1e5, preformatted=True)
        num_jobs = 50
        job_array = [backend.run(quantum_job) for _ in range(num_jobs)]

        # Try to cancel them in the reverse order they were launched: the
        # most recent job is the one with more chances of still being in the
        # queue.
        for job in reversed(job_array):
            job.cancel()
        num_cancelled = sum([job.cancelled for job in job_array])
        self.log.info('number of successfully cancelled jobs: %d/%d',
                      num_cancelled, num_jobs)
        self.assertTrue(num_cancelled > 0)
예제 #19
0
 def test_run_local_backend_compile(self):
     quantum_job = QuantumJob(self.qasm_text,
                              do_compile=True,
                              backend='local_qasm_simulator')
     jobprocessor.run_local_backend(quantum_job.qobj)
예제 #20
0
 def test_run_local_backend_unitary(self):
     compiled_circuit = openquantumcompiler.compile(self.qc.qasm())
     quantum_job = QuantumJob(compiled_circuit,
                              do_compile=False,
                              backend='local_unitary_simulator')
     jobprocessor.run_local_backend(quantum_job.qobj)
예제 #21
0
 def test_init_quantum_job(self):
     quantum_job = QuantumJob(self.qc)
예제 #22
0
    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)
예제 #23
0
 def test_backend_not_found(self):
     compiled_circuit = openquantumcompiler.compile(self.qc.qasm())
     job = QuantumJob(compiled_circuit,
                      backend='non_existing_backend')
     self.assertRaises(QISKitError, jobprocessor.JobProcessor, [job],
                       callback=None)
예제 #24
0
 def setUpClass(cls):
     super(TestProjectQCppSimulator, cls).setUpClass()
     n_circuits = 20
     min_depth = 1
     max_depth = 10
     min_qubits = 1
     max_qubits = 4
     random_circuits = RandomCircuitGenerator(min_qubits=min_qubits,
                                              max_qubits=max_qubits,
                                              min_depth=min_depth,
                                              max_depth=max_depth,
                                              seed=None)
     for _ in range(n_circuits):
         basis = list(
             random.sample(random_circuits.op_signature.keys(),
                           random.randint(2, 7)))
         if 'reset' in basis:
             basis.remove('reset')
         random_circuits.add_circuits(1, basis=basis)
     cls.rqg = random_circuits
     cls.seed = 88
     cls.qasm_filename = cls._get_resource_path('qasm/example.qasm')
     with open(cls.qasm_filename, 'r') as qasm_file:
         cls.qasm_text = qasm_file.read()
         qr1 = QuantumRegister('q1', 2)
         qr2 = QuantumRegister('q2', 3)
         cr = ClassicalRegister('c', 2)
         qcs = QuantumCircuit(qr1, qr2, cr)
         qcs.h(qr1[0])
         qcs.h(qr2[2])
         qcs.measure(qr1[0], cr[0])
         cls.qcs = qcs
         # create qobj
     compiled_circuit1 = openquantumcompiler.compile(cls.qcs.qasm(),
                                                     format='json')
     compiled_circuit2 = openquantumcompiler.compile(cls.qasm_text,
                                                     format='json')
     cls.qobj = {
         'id':
         'test_qobj',
         'config': {
             'max_credits': 3,
             'shots': 100,
             'backend': 'local_projectq_simulator',
             'seed': 1111
         },
         'circuits': [{
             'name': 'test_circuit1',
             'compiled_circuit': compiled_circuit1,
             'basis_gates': 'u1,u2,u3,cx,id',
             'layout': None,
         }, {
             'name': 'test_circuit2',
             'compiled_circuit': compiled_circuit2,
             'basis_gates': 'u1,u2,u3,cx,id',
             'layout': None,
         }]
     }
     cls.q_job = QuantumJob(cls.qobj,
                            backend='local_projectq_simulator',
                            preformatted=True)
예제 #25
0
 def test_compile_job(self):
     """Test compilation as part of job"""
     quantum_job = QuantumJob(self.qasm_text, do_compile=True,
                              backend='local_qasm_simulator')
     jp = jobprocessor.JobProcessor([quantum_job], callback=None)
     jp.submit()
예제 #26
0
 def test_run_remote_simulator_compile(self):
     quantum_job = QuantumJob(self.qc, do_compile=True,
                              backend='ibmqx_qasm_simulator')
     jobprocessor.run_backend(quantum_job)
예제 #27
0
 def test_run_remote_simulator(self):
     compiled_circuit = openquantumcompiler.compile(self.qc.qasm())
     quantum_job = QuantumJob(compiled_circuit, do_compile=False,
                              backend='ibmqx_qasm_simulator')
     jobprocessor.run_backend(quantum_job)
예제 #28
0
    def test_qobj_two_qubit_gates(self):
        filename = self._get_resource_path('qobj/cpp_two_qubit_gates.json')
        with open(filename, 'r') as file:
            q_job = QuantumJob(json.load(file),
                               backend=self.backend,
                               preformatted=True)
        result = self.backend.run(q_job).result()
        expected_data = {
            'h0 CX01': {
                'statevector': np.array([1 / np.sqrt(2), 0, 0, 1 / np.sqrt(2)])
            },
            'h0 CX10': {
                'statevector': np.array([1 / np.sqrt(2), 1 / np.sqrt(2), 0, 0])
            },
            'h1 CX01': {
                'statevector': np.array([1 / np.sqrt(2), 0, 1 / np.sqrt(2), 0])
            },
            'h1 CX10': {
                'statevector': np.array([1 / np.sqrt(2), 0, 0, 1 / np.sqrt(2)])
            },
            'h0 cx01': {
                'statevector': np.array([1 / np.sqrt(2), 0, 0, 1 / np.sqrt(2)])
            },
            'h0 cx10': {
                'statevector': np.array([1 / np.sqrt(2), 1 / np.sqrt(2), 0, 0])
            },
            'h1 cx01': {
                'statevector': np.array([1 / np.sqrt(2), 0, 1 / np.sqrt(2), 0])
            },
            'h1 cx10': {
                'statevector': np.array([1 / np.sqrt(2), 0, 0, 1 / np.sqrt(2)])
            },
            'h0 cz01': {
                'statevector': np.array([1 / np.sqrt(2), 1 / np.sqrt(2), 0, 0])
            },
            'h0 cz10': {
                'statevector': np.array([1 / np.sqrt(2), 1 / np.sqrt(2), 0, 0])
            },
            'h1 cz01': {
                'statevector': np.array([1 / np.sqrt(2), 0, 1 / np.sqrt(2), 0])
            },
            'h1 cz10': {
                'statevector': np.array([1 / np.sqrt(2), 0, 1 / np.sqrt(2), 0])
            },
            'h0 h1 cz01': {
                'statevector': np.array([0.5, 0.5, 0.5, -0.5])
            },
            'h0 h1 cz10': {
                'statevector': np.array([0.5, 0.5, 0.5, -0.5])
            },
            'h0 rzz01': {
                'statevector':
                np.array([1 / np.sqrt(2), 1j / np.sqrt(2), 0, 0])
            },
            'h0 rzz10': {
                'statevector':
                np.array([1 / np.sqrt(2), 1j / np.sqrt(2), 0, 0])
            },
            'h1 rzz01': {
                'statevector':
                np.array([1 / np.sqrt(2), 0, 1j / np.sqrt(2), 0])
            },
            'h1 rzz10': {
                'statevector':
                np.array([1 / np.sqrt(2), 0, 1j / np.sqrt(2), 0])
            },
            'h0 h1 rzz01': {
                'statevector': np.array([0.5, 0.5j, 0.5j, 0.5])
            },
            'h0 h1 rzz10': {
                'statevector': np.array([0.5, 0.5j, 0.5j, 0.5])
            }
        }

        for name in expected_data:
            # Check snapshot
            snapshots = result.get_snapshots(name)
            self.assertEqual(set(snapshots), {'0'},
                             msg=name + ' snapshot keys')
            self.assertEqual(len(snapshots['0']),
                             1,
                             msg=name + ' snapshot length')
            state = snapshots['0']['statevector'][0]
            expected_state = expected_data[name]['statevector']
            fidelity = np.abs(expected_state.dot(state.conj()))**2
            self.assertAlmostEqual(fidelity,
                                   1.0,
                                   places=10,
                                   msg=name + ' snapshot fidelity')
예제 #29
0
    def test_qobj_single_qubit_gates(self):
        filename = self._get_resource_path('qobj/cpp_single_qubit_gates.json')
        with open(filename, 'r') as file:
            q_job = QuantumJob(json.load(file),
                               backend=self.backend,
                               preformatted=True)
        result = self.backend.run(q_job).result()
        expected_data = {
            'snapshot': {
                'statevector': np.array([1, 0])
            },
            'id(U)': {
                'statevector': np.array([1, 0])
            },
            'id(u3)': {
                'statevector': np.array([1, 0])
            },
            'id(u1)': {
                'statevector': np.array([1, 0])
            },
            'id(direct)': {
                'statevector': np.array([1, 0])
            },
            'x(U)': {
                'statevector': np.array([0, 1])
            },
            'x(u3)': {
                'statevector': np.array([0, 1])
            },
            'x(direct)': {
                'statevector': np.array([0, 1])
            },
            'y(U)': {
                'statevector': np.array([0, 1j])
            },
            'y(u3)': {
                'statevector': np.array([0, 1j])
            },
            'y(direct)': {
                'statevector': np.array([0, 1j])
            },
            'h(U)': {
                'statevector': np.array([1 / np.sqrt(2), 1 / np.sqrt(2)])
            },
            'h(u3)': {
                'statevector': np.array([1 / np.sqrt(2), 1 / np.sqrt(2)])
            },
            'h(u2)': {
                'statevector': np.array([1 / np.sqrt(2), 1 / np.sqrt(2)])
            },
            'h(direct)': {
                'statevector': np.array([1 / np.sqrt(2), 1 / np.sqrt(2)])
            },
            'h(direct) z(U)': {
                'statevector': np.array([1 / np.sqrt(2), -1 / np.sqrt(2)])
            },
            'h(direct) z(u3)': {
                'statevector': np.array([1 / np.sqrt(2), -1 / np.sqrt(2)])
            },
            'h(direct) z(u1)': {
                'statevector': np.array([1 / np.sqrt(2), -1 / np.sqrt(2)])
            },
            'h(direct) z(direct)': {
                'statevector': np.array([1 / np.sqrt(2), -1 / np.sqrt(2)])
            },
            'h(direct) s(U)': {
                'statevector': np.array([1 / np.sqrt(2), 1j / np.sqrt(2)])
            },
            'h(direct) s(u3)': {
                'statevector': np.array([1 / np.sqrt(2), 1j / np.sqrt(2)])
            },
            'h(direct) s(u1)': {
                'statevector': np.array([1 / np.sqrt(2), 1j / np.sqrt(2)])
            },
            'h(direct) s(direct)': {
                'statevector': np.array([1 / np.sqrt(2), 1j / np.sqrt(2)])
            },
            'h(direct) sdg(U)': {
                'statevector': np.array([1 / np.sqrt(2), -1j / np.sqrt(2)])
            },
            'h(direct) sdg(u3)': {
                'statevector': np.array([1 / np.sqrt(2), -1j / np.sqrt(2)])
            },
            'h(direct) sdg(u1)': {
                'statevector': np.array([1 / np.sqrt(2), -1j / np.sqrt(2)])
            },
            'h(direct) sdg(direct)': {
                'statevector': np.array([1 / np.sqrt(2), -1j / np.sqrt(2)])
            },
            'h(direct) t(U)': {
                'statevector': np.array([1 / np.sqrt(2), 0.5 + 0.5j])
            },
            'h(direct) t(u3)': {
                'statevector': np.array([1 / np.sqrt(2), 0.5 + 0.5j])
            },
            'h(direct) t(u1)': {
                'statevector': np.array([1 / np.sqrt(2), 0.5 + 0.5j])
            },
            'h(direct) t(direct)': {
                'statevector': np.array([1 / np.sqrt(2), 0.5 + 0.5j])
            },
            'h(direct) tdg(U)': {
                'statevector': np.array([1 / np.sqrt(2), 0.5 - 0.5j])
            },
            'h(direct) tdg(u3)': {
                'statevector': np.array([1 / np.sqrt(2), 0.5 - 0.5j])
            },
            'h(direct) tdg(u1)': {
                'statevector': np.array([1 / np.sqrt(2), 0.5 - 0.5j])
            },
            'h(direct) tdg(direct)': {
                'statevector': np.array([1 / np.sqrt(2), 0.5 - 0.5j])
            }
        }

        for name in expected_data:
            # Check snapshot
            snapshots = result.get_snapshots(name)
            self.assertEqual(set(snapshots), {'0'},
                             msg=name + ' snapshot keys')
            self.assertEqual(len(snapshots['0']),
                             1,
                             msg=name + ' snapshot length')
            state = snapshots['0']['statevector'][0]
            expected_state = expected_data[name]['statevector']
            inner_product = expected_state.dot(state.conj())
            self.assertAlmostEqual(inner_product,
                                   1.0,
                                   places=10,
                                   msg=name + ' snapshot fidelity')
예제 #30
0
    def test_qobj_measure_opt(self):
        filename = self._get_resource_path('qobj/cpp_measure_opt.json')
        with open(filename, 'r') as file:
            q_job = QuantumJob(json.load(file),
                               backend=self.backend,
                               preformatted=True)
        result = self.backend.run(q_job).result()
        shots = q_job.qobj['config']['shots']
        expected_data = {
            'measure (opt)': {
                'deterministic': True,
                'counts': {
                    '00': shots
                },
                'statevector': np.array([1, 0, 0, 0])
            },
            'x0 measure (opt)': {
                'deterministic': True,
                'counts': {
                    '01': shots
                },
                'statevector': np.array([0, 1, 0, 0])
            },
            'x1 measure (opt)': {
                'deterministic': True,
                'counts': {
                    '10': shots
                },
                'statevector': np.array([0, 0, 1, 0])
            },
            'x0 x1 measure (opt)': {
                'deterministic': True,
                'counts': {
                    '11': shots
                },
                'statevector': np.array([0, 0, 0, 1])
            },
            'y0 measure (opt)': {
                'deterministic': True,
                'counts': {
                    '01': shots
                },
                'statevector': np.array([0, 1j, 0, 0])
            },
            'y1 measure (opt)': {
                'deterministic': True,
                'counts': {
                    '10': shots
                },
                'statevector': np.array([0, 0, 1j, 0])
            },
            'y0 y1 measure (opt)': {
                'deterministic': True,
                'counts': {
                    '11': shots
                },
                'statevector': np.array([0, 0, 0, -1j])
            },
            'h0 measure (opt)': {
                'deterministic': False,
                'counts': {
                    '00': shots / 2,
                    '01': shots / 2
                },
                'statevector': np.array([1 / np.sqrt(2), 1 / np.sqrt(2), 0, 0])
            },
            'h1 measure (opt)': {
                'deterministic': False,
                'counts': {
                    '00': shots / 2,
                    '10': shots / 2
                },
                'statevector': np.array([1 / np.sqrt(2), 0, 1 / np.sqrt(2), 0])
            },
            'h0 h1 measure (opt)': {
                'deterministic': False,
                'counts': {
                    '00': shots / 4,
                    '01': shots / 4,
                    '10': shots / 4,
                    '11': shots / 4
                },
                'statevector': np.array([0.5, 0.5, 0.5, 0.5])
            },
            'bell measure (opt)': {
                'deterministic': False,
                'counts': {
                    '00': shots / 2,
                    '11': shots / 2
                },
                'statevector': np.array([1 / np.sqrt(2), 0, 0, 1 / np.sqrt(2)])
            }
        }

        for name in expected_data:
            # Check counts:
            counts = result.get_counts(name)
            expected_counts = expected_data[name]['counts']
            if expected_data[name].get('deterministic', False):
                self.assertEqual(counts, expected_counts, msg=name + ' counts')
            else:
                threshold = 0.04 * shots
                self.assertDictAlmostEqual(counts,
                                           expected_counts,
                                           threshold,
                                           msg=name + 'counts')
            # Check snapshot
            snapshots = result.get_snapshots(name)
            self.assertEqual(set(snapshots), {'0'},
                             msg=name + ' snapshot keys')
            self.assertEqual(len(snapshots['0']),
                             3,
                             msg=name + ' snapshot length')
            state = snapshots['0']['statevector'][0]
            expected_state = expected_data[name]['statevector']
            fidelity = np.abs(expected_state.dot(state.conj()))**2
            self.assertAlmostEqual(fidelity,
                                   1.0,
                                   places=10,
                                   msg=name + ' snapshot fidelity')
            rho = snapshots['0']['density_matrix']
            self.assertAlmostEqual(np.trace(rho), 1)
            prob = snapshots['0']['probabilities']
            self.assertAlmostEqual(np.sum(prob), 1)