当前位置: 首页>>代码示例>>Python>>正文


Python qiskit.QuantumCircuit类代码示例

本文整理汇总了Python中qiskit.QuantumCircuit的典型用法代码示例。如果您正苦于以下问题:Python QuantumCircuit类的具体用法?Python QuantumCircuit怎么用?Python QuantumCircuit使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了QuantumCircuit类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_sympy

 def test_sympy(self):
     desired_vector = [
         0,
         math.cos(math.pi / 3) * complex(0, 1) / math.sqrt(4),
         math.sin(math.pi / 3) / math.sqrt(4),
         0,
         0,
         0,
         0,
         0,
         1 / math.sqrt(8) * complex(1, 0),
         1 / math.sqrt(8) * complex(0, 1),
         0,
         0,
         0,
         0,
         1 / math.sqrt(4),
         1 / math.sqrt(4) * complex(0, 1)]
     qr = QuantumRegister(4, "qr")
     qc = QuantumCircuit(qr)
     qc.initialize(desired_vector, [qr[0], qr[1], qr[2], qr[3]])
     job = wrapper.execute(qc, 'local_statevector_simulator')
     result = job.result()
     statevector = result.get_statevector()
     fidelity = state_fidelity(statevector, desired_vector)
     self.assertGreater(
         fidelity, self._desired_fidelity,
         "Initializer has low fidelity {0:.2g}.".format(fidelity))
开发者ID:christians94,项目名称:qiskit-sdk-py,代码行数:28,代码来源:test_initializer.py

示例2: setUp

 def setUp(self):
     qr = QuantumRegister(2, name="qr2")
     cr = ClassicalRegister(2, name=None)
     qc = QuantumCircuit(qr, cr, name="qc10")
     qc.h(qr[0])
     qc.measure(qr[0], cr[0])
     self.qr_name = qr.name
     self.cr_name = cr.name
     self.circuits = [qc]
开发者ID:christians94,项目名称:qiskit-sdk-py,代码行数:9,代码来源:test_identifiers.py

示例3: qc_approx_sim

def qc_approx_sim(x, t1, t2):
    theta1 = x - t1;
    theta2 = x - t2;

    q = QuantumRegister(2, 'q')
    c = ClassicalRegister(2, 'c')
    qc = QuantumCircuit(q, c)

    qc.h( q[0] )
    qc.h( q[1] )

    qc.u3(t1, 0.0, 0.0, q[0]);
    qc.u3(t2, 0.0, 0.0, q[1]);

    qc.barrier( q )
    #qc.measure(q,c)
    qc.measure( q[0], c[0] )
    qc.measure( q[1], c[1] )

    job = execute(qc, backend, shots=1024)

    rslt = job.result()
    #counts = rslt.get_counts(qc)
    #print(counts)

    outputstate = rslt.get_statevector( qc, decimals=13 )
    #print(outputstate)

    qval = outputstate;

    return qval;
开发者ID:qMSUZ,项目名称:QCS,代码行数:31,代码来源:qapprox.py

示例4: test_single_qubit

 def test_single_qubit(self):
     desired_vector = [1/math.sqrt(3), math.sqrt(2)/math.sqrt(3)]
     qr = QuantumRegister(1, "qr")
     qc = QuantumCircuit(qr)
     qc.initialize(desired_vector, [qr[0]])
     job = wrapper.execute(qc, 'local_statevector_simulator')
     result = job.result()
     statevector = result.get_statevector()
     fidelity = state_fidelity(statevector, desired_vector)
     self.assertGreater(
         fidelity, self._desired_fidelity,
         "Initializer has low fidelity {0:.2g}.".format(fidelity))
开发者ID:christians94,项目名称:qiskit-sdk-py,代码行数:12,代码来源:test_initializer.py

示例5: test_deterministic_state

 def test_deterministic_state(self):
     desired_vector = [0, 1, 0, 0]
     qr = QuantumRegister(2, "qr")
     qc = QuantumCircuit(qr)
     qc.initialize(desired_vector, [qr[0], qr[1]])
     job = wrapper.execute(qc, 'local_statevector_simulator')
     result = job.result()
     statevector = result.get_statevector()
     fidelity = state_fidelity(statevector, desired_vector)
     self.assertGreater(
         fidelity, self._desired_fidelity,
         "Initializer has low fidelity {0:.2g}.".format(fidelity))
开发者ID:christians94,项目名称:qiskit-sdk-py,代码行数:12,代码来源:test_initializer.py

示例6: test_cancel

    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, preformatted=True)
        num_jobs = 10
        timeout = 10
        start_time = time.time()
        self.log.info('testing with simulator: %s', backend.name)
        job_array = [backend.run(quantum_job) for _ in range(num_jobs)]
        for job in job_array:
            job.cancel()
        found_cancelled = False
        while not found_cancelled:
            check = sum([job.cancelled for job in job_array])
            if check >= 1:
                self.log.info('found %d cancelled jobs', check)
                found_cancelled = 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.cancelled,
                              check)
            self.log.info('{0} {1:0.2f}'.format('-'*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)

        # Wait for all the jobs to finish.
        _ = [job.result() for job in job_array if not job.cancelled]
开发者ID:christians94,项目名称:qiskit-sdk-py,代码行数:52,代码来源:test_localjob.py

示例7: test_gate_x

 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})
开发者ID:christians94,项目名称:qiskit-sdk-py,代码行数:14,代码来源:test_qasm_simulator_projectq.py

示例8: test_run_async

    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)

        # Wait for all the jobs to finish.
        # TODO: this causes the test to wait until the 15 qubit jobs are
        # finished, which might take long (hence the @slow_test). Waiting for
        # the result is needed as otherwise the jobs would still be running
        # once the test is completed, causing failures in subsequent tests as
        # the executor's queue might be overloaded.

        _ = [job.result() for job in job_array]
开发者ID:christians94,项目名称:qiskit-sdk-py,代码行数:50,代码来源:test_localjob.py

示例9: setUp

    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)
开发者ID:christians94,项目名称:qiskit-sdk-py,代码行数:48,代码来源:test_qasm_simulator_cpp.py

示例10: setUp

 def setUp(self):
     self.q = QuantumRegister(3, "q")
     self.r = QuantumRegister(3, "r")
     self.s = QuantumRegister(3, "s")
     self.c = ClassicalRegister(3, "c")
     self.circuit = QuantumCircuit(self.q, self.r, self.s, self.c)
     self.c_header = 80  # lenght of the header
开发者ID:christians94,项目名称:qiskit-sdk-py,代码行数:7,代码来源:test_extensions_standard.py

示例11: test_run_async_simulator

    def test_run_async_simulator(self):
        IBMQJob._executor = futures.ThreadPoolExecutor(max_workers=2)
        backend = self._provider.get_backend('ibmq_qasm_simulator')
        self.log.info('submitting to backend %s', backend.name)
        num_qubits = 16
        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]*10, 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()
        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)
                break
            if all([job.done for job in job_array]):
                # done too soon? don't generate error
                self.log.warning('all jobs completed before simultaneous jobs '
                                 'could be detected')
                break
            for job in job_array:
                self.log.info('%s %s %s %s', job.status['status'], job.running,
                              check, job.job_id)
            self.log.info('-'*20 + ' ' + str(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(0.2)

        result_array = [job.result() for job in job_array]
        self.log.info('got back all job results')
        # 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))))
开发者ID:christians94,项目名称:qiskit-sdk-py,代码行数:46,代码来源:test_ibmqjob.py

示例12: test_run_async_device

    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))))
开发者ID:christians94,项目名称:qiskit-sdk-py,代码行数:44,代码来源:test_ibmqjob.py

示例13: setUp

 def setUp(self):
     self.seed = 88
     self.qasmFileName = os.path.join(qiskit.__path__[0],
                                      '../test/python/qasm/example.qasm')
     with open(self.qasmFileName, 'r') as qasm_file:
         self.qasm_text = qasm_file.read()
     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.qasm(),
                                                     format='json')
     compiled_circuit2 = openquantumcompiler.compile(self.qasm_text,
                                                     format='json')
     self.qobj = {'id': 'test_qobj',
                  'config': {
                      'max_credits': 3,
                      'shots': 100,
                      'backend': 'local_qasm_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_qasm_cpp_simulator',
                             preformatted=True)
开发者ID:LuisCarlosEiras,项目名称:qiskit-sdk-py,代码行数:42,代码来源:test_local_qasm_cpp_simulator.py

示例14: test_random_3qubit

 def test_random_3qubit(self):
     desired_vector = [
         1 / math.sqrt(16) * complex(0, 1),
         1 / math.sqrt(8) * complex(1, 0),
         1 / math.sqrt(16) * complex(1, 1),
         0,
         0,
         1 / math.sqrt(8) * complex(1, 2),
         1 / math.sqrt(16) * complex(1, 0),
         0]
     qr = QuantumRegister(3, "qr")
     qc = QuantumCircuit(qr)
     qc.initialize(desired_vector, [qr[0], qr[1], qr[2]])
     job = wrapper.execute(qc, 'local_statevector_simulator')
     result = job.result()
     statevector = result.get_statevector()
     fidelity = state_fidelity(statevector, desired_vector)
     self.assertGreater(
         fidelity, self._desired_fidelity,
         "Initializer has low fidelity {0:.2g}.".format(fidelity))
开发者ID:christians94,项目名称:qiskit-sdk-py,代码行数:20,代码来源:test_initializer.py

示例15: test_two_unitary_simulator

    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)
开发者ID:christians94,项目名称:qiskit-sdk-py,代码行数:26,代码来源:test_unitary_simulator_py.py


注:本文中的qiskit.QuantumCircuit类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。