How to use the qiskit.execute 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-terra / test / python / circuit / test_initializer.py View on Github external
def test_initialize_one_by_one(self):
        """Initializing qubits individually into product state same as initializing the pair."""
        qubit_0_state = [1, 0]
        qubit_1_state = [1 / math.sqrt(2), 1 / math.sqrt(2)]
        qr = QuantumRegister(2, "qr")
        qc_a = QuantumCircuit(qr)
        qc_a.initialize(np.kron(qubit_1_state, qubit_0_state), qr)

        qc_b = QuantumCircuit(qr)
        qc_b.initialize(qubit_0_state, [qr[0]])
        qc_b.initialize(qubit_1_state, [qr[1]])

        job = execute([qc_a, qc_b], BasicAer.get_backend('statevector_simulator'))
        result = job.result()
        statevector_a = result.get_statevector(0)
        statevector_b = result.get_statevector(1)
        fidelity = state_fidelity(statevector_a, statevector_b)
        self.assertGreater(
            fidelity, self._desired_fidelity,
            "Initializer has low fidelity {0:.2g}.".format(fidelity))
github Qiskit / qiskit-aer / test / terra / backends / test_statevector_simulator.py View on Github external
def test_cu3_gate_deterministic_default_basis_gates(self):
        """Test cu3-gate circuits compiling to backend default basis_gates."""
        circuits = ref_non_clifford.cu3_gate_circuits_deterministic(final_measure=False)
        targets = ref_non_clifford.cu3_gate_statevector_deterministic()
        job = execute(circuits, StatevectorSimulator(), shots=1)
        result = job.result()
        self.assertTrue(getattr(result, 'success', False))
        self.compare_statevector(result, circuits, targets)
github Qiskit / qiskit-aer / test / terra / backends / test_unitary_simulator.py View on Github external
def test_sdg_gate_deterministic_minimal_basis_gates(self):
        """Test sdg-gate gate circuits compiling to u3,cx"""
        circuits = ref_1q_clifford.sdg_gate_circuits_deterministic(
            final_measure=False)
        targets = ref_1q_clifford.sdg_gate_unitary_deterministic()
        job = execute(circuits,
                      UnitarySimulator(),
                      shots=1,
                      basis_gates=['u3', 'cx'])
        result = job.result()
        self.assertTrue(getattr(result, 'success', False))
        self.compare_unitary(result, circuits, targets)
github Qiskit / qiskit-terra / test / python / test_mapper.py View on Github external
circ.y(qr[0])
        circ.z(qr[2])
        circ.h(qr[2])
        circ.cx(qr[1], qr[0])
        circ.y(qr[2])
        circ.t(qr[2])
        circ.z(qr[2])
        circ.cx(qr[1], qr[2])
        circ.measure(qr[0], cr[0])
        circ.measure(qr[1], cr[1])
        circ.measure(qr[2], cr[2])
        circ.measure(qr[3], cr[3])

        coupling_map = [[0, 2], [1, 2], [2, 3]]
        shots = 2000
        job = execute(circ, backend=self.backend,
                      coupling_map=coupling_map, seed=self.seed, shots=shots)
        counts = job.result().get_counts()
        target = {'0001': shots / 2, '0101': shots / 2}
        threshold = 0.04 * shots
        self.assertDictAlmostEqual(counts, target, threshold)
github Qiskit / qiskit-aqua / repeat-until-successs / rus_circuits.py View on Github external
def test_gearbox(vals, plot=False):
    q = QuantumRegister(len(vals)+1)
    c = ClassicalRegister(len(vals))

    qc = QuantumCircuit(q, c)

    input_gearbox(qc, vals, [q[i] for i in range(len(q)-1)],
            q[len(q)-1])
    
    if plot: plot_circuit(qc)
    qc.snapshot("1")
    for i in range(len(vals)):
        qc.measure(q[i], c[i])

    result = execute(qc, "local_qasm_simulator", config={"data":
        ["quantum_state_ket"]}, shots=1).result()
    res = cleanup_ket(result.get_snapshot("1").get("quantum_state_ket")[0])
    return get_x_angle(res)
github Qiskit / qiskit-aqua / qiskit_aqua / algorithms / single_sample / hhl / lookup_rotation.py View on Github external
if '1' not in d.split()[-1][:-1]:
                                num = -0.5
                    else:
                        num = sum([2 ** -(i + 1)
                            for i, e in enumerate(reversed(d.split()[-1])) if e == "1"])
                    if self._evo_time is not None:
                        num *= 2*np.pi/self._evo_time
                    if d.split()[0] == '1':
                        res_dict.append(("Anc 1",num, sv[d][0],d))
                    else:
                        res_dict.append(("Anc 0",num, sv[d][0],d))
            self._ret = res_dict
            return res_dict
        elif backend == "local_qasm_simulator":
            self._set_measurement()
            result = execute(self._circuit,
                             backend=backend, shots=shots).result()

            rd = result.get_counts(self._circuit)
            rets = sorted([[rd[k], k, k] for k in rd])[::-1]
            # return rets
            for d in rets:
                print(d)
                d[0] /= shots
                d[0] = np.sqrt(d[0])
                # split registers which are white space separated and decode
                c1, c2 = d[2].split()
                c2_ = sum([2 ** -(i + 1)
                           for i, e in enumerate(reversed(c2)) if e == "1"])
                d[2] = ' '.join([c1, str(c2_)])
            self._ret = rets
            return rets
github primaryobjects / quantum / superposition.py View on Github external
parser = RawConfigParser()
        parser.read('config.ini')
        IBMQ.enable_account(parser.get('IBM', 'key'))
        run.isInit = True

    # Set the backend server.
    backend = qiskit.providers.ibmq.least_busy(qiskit.IBMQ.backends(simulator=False))

    # Execute the program on the quantum machine.
    print("Running on", backend.name())
    job = qiskit.execute(program, backend)
    return job.result().get_counts()
  else:
    # Execute the program in the simulator.
    print("Running on the simulator.")
    job = qiskit.execute(program, qiskit.Aer.get_backend('qasm_simulator'), shots=shots)
    return job.result().get_counts()
github Qiskit / qiskit-terra / qiskit / tools / apps / optimization.py View on Github external
a list of Pauli operators grouped into tpb sets.
        input_circuit (QuantumCircuit): input circuit.
        shots (int): number of shots considered in the averaging. If 1 the
            averaging is exact.
        device (str): the backend used to run the simulation.
    Returns:
        float: Average value of the Hamiltonian or observable.
    """
    energy = 0
    circuits = []

    if 'statevector' in device:
        circuits.append(input_circuit)
        # Hamiltonian is not a pauli_list grouped into tpb sets
        if not isinstance(hamiltonian, list):
            result = execute(circuits, device, shots=shots).result()
            statevector = result.get_statevector()
            # Diagonal Hamiltonian represented by 1D array
            if (hamiltonian.shape[0] == 1 or
                    np.shape(np.shape(np.array(hamiltonian))) == (1,)):
                energy = np.sum(hamiltonian * np.absolute(statevector) ** 2)
            # Hamiltonian represented by square matrix
            elif hamiltonian.shape[0] == hamiltonian.shape[1]:
                energy = np.inner(np.conjugate(statevector),
                                  np.dot(hamiltonian, statevector))
        # Hamiltonian represented by a Pauli list
        else:
            # Execute trial circuit with final rotations for each Pauli in
            # hamiltonian and store from circuits[1] on
            n_qubits = input_circuit.regs['q'].size
            q = QuantumRegister(n_qubits, "q")
            i = 1
github markf94 / ibmq_code_epl_119_60002 / qiskit_distance_based_classifier.py View on Github external
def simulate(self, quantum_circuit):
        """
        Compile and run the quantum circuit
        on a simulator backend.
        """

        # noisy simulation
        backend_sim = Aer.get_backend('qasm_simulator')

        job_sim = execute(quantum_circuit, backend_sim)

        # retrieve the results from the simulation
        return job_sim.result()
github kmatt10 / Quantum-Casino / QHoldem / Dealer.py View on Github external
def evaluate(self):
        """for after the game is finished and it is time to measure and
            process the results
        """
        self.circ.measure(range(5),range(5))
        simulator = Aer.get_backend('qasm_simulator')
        job = execute(self.circ, simulator, shots=1)
        result = job.result()
        counts = result.get_counts(self.circ)
        return max(counts, key=counts.get)