How to use the qiskit.BasicAer function in qiskit

To help you get started, we’ve selected a few qiskit examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github Qiskit / qiskit-aqua / test / aqua / test_operator.py View on Github external
def test_real_eval(self):
        """ real eval test """
        depth = 1
        var_form = RYRZ(self.qubit_op.num_qubits, depth)
        circuit = var_form.construct_circuit(np.array(np.random.randn(var_form.num_parameters)))
        run_config_ref = RunConfig(shots=1)
        run_config = RunConfig(shots=10000)
        reference = self.qubit_op.eval('matrix',
                                       circuit,
                                       BasicAer.get_backend('statevector_simulator'),
                                       run_config=run_config_ref)[0]
        reference = reference.real
        backend = BasicAer.get_backend('qasm_simulator')
        paulis_mode = self.qubit_op.eval('paulis', circuit, backend, run_config=run_config)
        grouped_paulis_mode = self.qubit_op.eval('grouped_paulis',
                                                 circuit, backend,
                                                 run_config=run_config)

        paulis_mode_p_3sigma = paulis_mode[0] + 3 * paulis_mode[1]
        paulis_mode_m_3sigma = paulis_mode[0] - 3 * paulis_mode[1]

        grouped_paulis_mode_p_3sigma = grouped_paulis_mode[0] + 3 * grouped_paulis_mode[1]
        grouped_paulis_mode_m_3sigma = grouped_paulis_mode[0] - 3 * grouped_paulis_mode[1]
        self.assertLessEqual(reference, paulis_mode_p_3sigma.real)
        self.assertGreaterEqual(reference, paulis_mode_m_3sigma.real)
        self.assertLessEqual(reference, grouped_paulis_mode_p_3sigma.real)
github Qiskit / qiskit-aqua / test / aqua / test_mcr.py View on Github external
q_o = QuantumRegister(1, name='o')
        allsubsets = list(chain(*[combinations(range(num_controls), ni) for
                                  ni in range(num_controls + 1)]))
        for subset in allsubsets:
            control_int = 0
            lam = aqua_globals.random.random_sample(1)[0] * pi
            qc = QuantumCircuit(q_o, c)
            for idx in subset:
                control_int += 2**idx
                qc.x(c[idx])
            qc.mcrz(lam, [c[i] for i in range(num_controls)], q_o[0],
                    use_basis_gates=use_basis_gates)
            for idx in subset:
                qc.x(c[idx])

            mat_mcu = execute(qc, BasicAer.get_backend(
                'unitary_simulator')).result().get_unitary(qc)

            dim = 2**(num_controls+1)
            pos = dim - 2*(control_int+1)
            mat_groundtruth = np.eye(dim, dtype=complex)
            rot_mat = np.array([[1, 0],
                                [0, np.exp(1j * lam)]],
                               dtype=complex)
            mat_groundtruth[pos:pos + 2, pos:pos + 2] = rot_mat
            self.assertTrue(np.allclose(mat_mcu, mat_groundtruth))
github Qiskit / qiskit-aqua / test / aqua / test_qgan.py View on Github external
'snapshot_dir': None
                                                     },
                              'discriminative_network': {'name': 'NumpyDiscriminator',
                                                         'n_features': len(num_qubits)}
                              }

        # Initialize qGAN
        self.qgan = QGAN(self._real_data,
                         self._bounds,
                         num_qubits,
                         batch_size,
                         num_epochs,
                         snapshot_dir=None)
        self.qgan.seed = 7
        # Set quantum instance to run the quantum generator
        self.qi_statevector = QuantumInstance(backend=BasicAer.get_backend('statevector_simulator'),
                                              seed_simulator=2,
                                              seed_transpiler=2)
        self.qi_qasm = QuantumInstance(backend=BasicAer.get_backend('qasm_simulator'),
                                       shots=1000,
                                       seed_simulator=2,
                                       seed_transpiler=2)
        # Set entangler map
        entangler_map = [[0, 1]]

        # Set an initial state for the generator circuit
        init_dist = UniformDistribution(sum(num_qubits), low=self._bounds[0], high=self._bounds[1])
        q = QuantumRegister(sum(num_qubits), name='q')
        qc = QuantumCircuit(q)
        init_dist.build(qc, q)
        init_distribution = Custom(num_qubits=sum(num_qubits), circuit=qc)
        # Set variational form
github Qiskit / qiskit-aqua / test / aqua / test_vqe.py View on Github external
def test_vqe(self):
        """ VQE test """
        result = VQE(self.qubit_op,
                     RYRZ(self.qubit_op.num_qubits),
                     L_BFGS_B()).run(
                         QuantumInstance(BasicAer.get_backend('statevector_simulator'),
                                         basis_gates=['u1', 'u2', 'u3', 'cx', 'id'],
                                         coupling_map=[[0, 1]],
                                         seed_simulator=aqua_globals.random_seed,
                                         seed_transpiler=aqua_globals.random_seed))
        self.assertAlmostEqual(result['energy'], -1.85727503)
        np.testing.assert_array_almost_equal(result['eigvals'], [-1.85727503], 5)
        ref_opt_params = [-0.58294401, -1.86141794, -1.97209632, -0.54796022,
                          -0.46945572, 2.60114794, -1.15637845, 1.40498879,
                          1.14479635, -0.48416694, -0.66608349, -1.1367579,
                          -2.67097002, 3.10214631, 3.10000313, 0.37235089]
        np.testing.assert_array_almost_equal(result['opt_params'], ref_opt_params, 5)
        self.assertIn('eval_count', result)
        self.assertIn('eval_time', result)
github Qiskit / qiskit-terra / test / python / basicaer / test_basicaer_backends.py View on Github external
def test_deprecated(self):
        """Test that deprecated names map the same backends as the new names.
        """
        def _get_first_available_backend(provider, backend_names):
            """Gets the first available backend."""
            if isinstance(backend_names, str):
                backend_names = [backend_names]
            for backend_name in backend_names:
                try:
                    return provider.get_backend(backend_name).name()
                except QiskitBackendNotFoundError:
                    pass
            return None

        deprecated_names = BasicAer._deprecated_backend_names()
        for oldname, newname in deprecated_names.items():
            expected = "WARNING:qiskit.providers.providerutils:Backend '%s' is deprecated. " \
                       "Use '%s'." % (oldname, newname)
            with self.subTest(oldname=oldname, newname=newname):
                with self.assertLogs('qiskit.providers.providerutils', level='WARNING') as context:
                    resolved_newname = _get_first_available_backend(BasicAer, newname)
                    real_backend = BasicAer.get_backend(resolved_newname)
                    self.assertEqual(BasicAer.backends(oldname)[0], real_backend)
                self.assertEqual(context.output, [expected])
github Qiskit / qiskit-terra / test / python / compiler / test_compiler.py View on Github external
def setUp(self):
        self.seed_simulator = 42
        self.backend = BasicAer.get_backend("qasm_simulator")
github Qiskit / qiskit-aqua / test / aqua / test_qpe.py View on Github external
exact_eigensolver = ExactEigensolver(qubit_op, k=1)
        results = exact_eigensolver.run()

        ref_eigenval = results['eigvals'][0]
        ref_eigenvec = results['eigvecs'][0]
        self.log.debug('The exact eigenvalue is:       %s', ref_eigenval)
        self.log.debug('The corresponding eigenvector: %s', ref_eigenvec)

        state_in = Custom(qubit_op.num_qubits, state_vector=ref_eigenvec)
        iqft = Standard(n_ancillae)

        qpe = QPE(qubit_op, state_in, iqft, num_time_slices, n_ancillae,
                  expansion_mode='suzuki', expansion_order=2,
                  shallow_circuit_concat=True)

        backend = BasicAer.get_backend(simulator)
        quantum_instance = QuantumInstance(backend, shots=100)

        # run qpe
        result = qpe.run(quantum_instance)

        # report result
        self.log.debug('top result str label:         %s', result['top_measurement_label'])
        self.log.debug('top result in decimal:        %s', result['top_measurement_decimal'])
        self.log.debug('stretch:                      %s', result['stretch'])
        self.log.debug('translation:                  %s', result['translation'])
        self.log.debug('final eigenvalue from QPE:    %s', result['energy'])
        self.log.debug('reference eigenvalue:         %s', ref_eigenval)
        self.log.debug('ref eigenvalue (transformed): %s',
                       (ref_eigenval + result['translation']) * result['stretch'])
        self.log.debug('reference binary str label:   %s', decimal_to_binary(
            (ref_eigenval.real + result['translation']) * result['stretch'],
github Qiskit / qiskit-aqua / test / aqua / operators / test_weighted_pauli_operator.py View on Github external
def setUp(self):
        super().setUp()
        seed = 0
        aqua_globals.random_seed = seed

        self.num_qubits = 3
        paulis = [Pauli.from_label(pauli_label)
                  for pauli_label in itertools.product('IXYZ', repeat=self.num_qubits)]
        weights = aqua_globals.random.random_sample(len(paulis))
        self.qubit_op = WeightedPauliOperator.from_list(paulis, weights)
        self.var_form = RYRZ(self.qubit_op.num_qubits, 1)

        qasm_simulator = BasicAer.get_backend('qasm_simulator')
        self.quantum_instance_qasm = QuantumInstance(qasm_simulator, shots=65536,
                                                     seed_simulator=seed, seed_transpiler=seed)
        statevector_simulator = BasicAer.get_backend('statevector_simulator')
        self.quantum_instance_statevector = \
            QuantumInstance(statevector_simulator, shots=1,
                            seed_simulator=seed, seed_transpiler=seed)
github Qiskit / qiskit-terra / test / python / basicaer / test_basicaer_backends.py View on Github external
for backend_name in backend_names:
                try:
                    return provider.get_backend(backend_name).name()
                except QiskitBackendNotFoundError:
                    pass
            return None

        deprecated_names = BasicAer._deprecated_backend_names()
        for oldname, newname in deprecated_names.items():
            expected = "WARNING:qiskit.providers.providerutils:Backend '%s' is deprecated. " \
                       "Use '%s'." % (oldname, newname)
            with self.subTest(oldname=oldname, newname=newname):
                with self.assertLogs('qiskit.providers.providerutils', level='WARNING') as context:
                    resolved_newname = _get_first_available_backend(BasicAer, newname)
                    real_backend = BasicAer.get_backend(resolved_newname)
                    self.assertEqual(BasicAer.backends(oldname)[0], real_backend)
                self.assertEqual(context.output, [expected])
github HuangJunye / QPong / viz / unitary_grid.py View on Github external
def set_circuit(self, circuit):
        backend_unit_sim = BasicAer.get_backend('unitary_simulator')
        job_sim = execute(circuit, backend_unit_sim)
        result_sim = job_sim.result()

        unitary = result_sim.get_unitary(circuit, decimals=3)
        # print('unitary: ', unitary)

        self.image = pygame.Surface([100 + len(unitary) * 50, 100 + len(unitary) * 50])
        self.image.convert()
        self.image.fill(WHITE)
        self.rect = self.image.get_rect()

        block_size = 30
        x_offset = 50
        y_offset = 50
        for y in range(len(unitary)):
            text_surface = ARIAL_16.render(self.basis_states[y], False, (0, 0, 0))