コード例 #1
0
ファイル: half_adder.py プロジェクト: jjhorder/qiskit_scripts
def half_adder(a, b):
    print('Computing %d + %d.\n' % (a, b))

    qc = QuantumCircuit(4, 2)

    # qc[i] = 0, so need to flip according to a, b input
    if a == 1:
        qc.x(0)
    if b == 1:
        qc.x(1)
    qc.barrier()

    # store binary addition on qc[2, 3]
    qc.cx(0, 2)
    qc.cx(1, 2)
    qc.ccx(0, 1, 3)
    qc.barrier()

    # read result to classical register
    qc.measure(2, 0)
    qc.measure(3, 1)

    qc.draw(output='mpl')
    job = execute(qc, Aer.get_backend('qasm_simulator'))
    hist = job.result().get_counts()
    plot_histogram(hist)
コード例 #2
0
 def display(self, circuit):
     if self.qiskit_backend != 'local_unitary_simulator':
         print('drawing circuit...')
         circuit_drawer(circuit)
         print('drawing histogram...,')
         print('   (close graph windows to proceed)')
         plot_histogram(self.job_exp.result().get_counts(circuit))
コード例 #3
0
def plot_results(result, title=''):
    counts = result.get_counts()
    print('\ncounts : {}\n'.format(counts))
    plot_histogram(counts)
    plt.title(title)
    plt.savefig("img/qt_res.png")
    plt.show()
コード例 #4
0
    def start_quantum(self):
        start_time = time.time()

        q = QuantumRegister(5, 'q')
        c = ClassicalRegister(5, 'c')
        a = self.ui.q_input.currentText()

        shor = QuantumCircuit(q, c)
        # circuit for a = 7, and plot the results:
        self.circuit_a_period_15(shor, q, c, int(a))
        backend = Aer.get_backend('qasm_simulator')
        sim_job = execute([shor], backend)
        sim_result = sim_job.result()

        sim_data = sim_result.get_counts(shor)
        plot_histogram([sim_data]).show()
        self.ui.q_period_label.setText(str(len(sim_data)))

        time_diff = time.time() - start_time
        self.ui.q_time_label.setText(str(time_diff))

        factor_p = math.gcd(
            int(self.ui.q_input.currentText())**int(len(sim_data) / 2) + 1,
            15)  # compute the factor classically
        factor_q = math.gcd(
            int(self.ui.q_input.currentText())**int(len(sim_data) / 2) - 1,
            15)  # compute the factor classically

        self.ui.q_upper_factor_label.setText(str(factor_q))
        self.ui.q_lower_factor_label.setText(str(factor_p))
コード例 #5
0
def get_result(ckt):
    shots = 10000
    backend = 'local_qasm_simulator'
    job = execute(ckt, backend=backend, shots=shots)
    results = job.result()
    answer = results.get_counts()
    plot_histogram(answer)
def run_grover(algorithm,oracle_type,oracle_method):
    # Run the algorithm on a simulator, printing the most frequently occurring result

    backend = Aer.get_backend('qasm_simulator')
    result = algorithm.run(backend)
    print("Oracle method:",oracle_method)
    print("Oracle for:", oracle_type)
    print("Aer Result:",result['top_measurement'])
    display(plot_histogram(result['measurement']))
    
    # Run the algorithm on an IBM Q backend, printing the most frequently occurring result
    print("Getting provider...")
    if not IBMQ.active_account():
        IBMQ.load_account()
    provider = IBMQ.get_provider()
    from qiskit.providers.ibmq import least_busy
    
    filtered_backend = least_busy(provider.backends(n_qubits=5, operational=True, simulator=False))
        
    result = algorithm.run(filtered_backend)

    print("Oracle method:",oracle_method)
    print("Oracle for:", oracle_type)
    print("IBMQ "+filtered_backend.name()+" Result:",result['top_measurement'])
    display(plot_histogram(result['measurement']))

    print(result)
コード例 #7
0
def main():
    Q_program = QuantumProgram()
    Q_program.register(Qconfig.APItoken, Qconfig.config["url"])
    #Creating registers
    q = Q_program.create_quantum_register("q", 2)
    c = Q_program.create_classical_register("c", 2)
    #Quantum circuit to make shared entangled state
    superdense = Q_program.create_circuit("superdense", [q], [c])
    #Party A : Alice
    superdense.h(q[0])
    superdense.cx(q[0], q[1])
    #00:do nothing, 10:apply x, 01:apply z
    superdense.x(q[0])
    superdense.z(q[0])
    #11:apply zx
    superdense.z(q[0])
    superdense.x(q[0])
    superdense.barrier()

    #Party B : Bob
    superdense.cx(q[0], q[1])
    superdense.h(q[0])
    superdense.measure(q[0], c[0])
    superdense.measure(q[1], c[1])

    circuits = ["superdense"]
    print(Q_program.get_qasms(circuits)[0])

    backend = "ibmq_qasm_simulator"
    shots = 1024

    result = Q_program.execute(circuits, backend=backend, shots=shots, max_credits=3, timeout=240)

    print("Counts:" + str(result.get_counts("superdense")))
    plot_histogram(result.get_counts("superdense"))
コード例 #8
0
def plot(pt,counts):
    if pt == 'hist':
        from qiskit.tools.visualization import plot_histogram
        plot_histogram(counts)
    if pt == 'bloch_mv':
        from qiskit.tools.visualization import plot_bloch_multivector
        plot_bloch_multivector(counts)
コード例 #9
0
def draw_results(circuit, result, title=''):
    counts = result.get_counts(circuit)
    print(counts)
    plot_histogram(counts)
    plt.title(title)
    plt.savefig("img/qe_res.png")
    plt.show()
コード例 #10
0
def get_job_status(backend, job_id):
    backend = IBMQ.get_backend(backend)
    try:
        print("Backend {0} is operational? {1}".format(
            backend.name(),
            backend.status()['operational']))
        print("Backend was last updated in {0}".format(
            backend.properties()['last_update_date']))
        print("Backend has {0} pending jobs".format(
            backend.status()['pending_jobs']))
    except:
        print("Maybe some errors in the properties of backend")
    ibmq_job = backend.retrieve_job(job_id)
    status = ibmq_job.status()
    print(status.name)
    print(ibmq_job.creation_date())
    if (status.name == 'DONE'):
        print("EUREKA")
        result = ibmq_job.result()
        counts = result.get_counts()
        print("Result is: {0}".format(counts))
        plot_histogram(counts)
    else:
        print("... Work in progress ...")
        print("Queue position = {0}".format(ibmq_job.queue_position()))
        print("Error message = {0}".format(ibmq_job.error_message()))
コード例 #11
0
    def run(self):
        for i in range(self.n):
            self.qc.x(self.q[i])
        self.qc.barrier()
        for i in range(self.n // 2):
            self.qc.h(self.q[i])
        self.qc.barrier()

        for i in range(int(self.n)):
            self.oracle()
            self.qc.barrier()
            self.diffusion_gate()
        self.qc.barrier()

        self.qc.measure(self.q, self.c)
        """run_sim"""
        # See a list of available local simulators
        # print("Local backends: ", Aer.available_backends())

        # compile and run the Quantum circuit on a simulator backend
        backend_sim = Aer.get_backend('qasm_simulator')
        job_sim = execute(self.qc, backend_sim)
        result_sim = job_sim.result()
        # Show the results
        print("simulation: ", result_sim)
        counts = result_sim.get_counts(self.qc)

        counts_l = [(i, counts[i]) for i in counts.keys()]
        print('Sim: ', sorted(counts_l, key=lambda x: x[1], reverse=True)[:5])
        plot_histogram(counts)
コード例 #12
0
ファイル: myAlgo.py プロジェクト: alfa871212/shor_paper
def shorSequential(N, a, args=None):
    n = math.ceil(math.log(N, 2))
    ctrl = QuantumRegister(1, name='ctrl')
    down = QuantumRegister(n, name='x')
    down_b = QuantumRegister(n + 1, name='b')
    ancilla = QuantumRegister(1, name='ancilla')
    qc = QuantumCircuit(ctrl, down, down_b, ancilla)
    cr_lis = []
    for i in range(0, 2 * n):
        cr = ClassicalRegister(1)
        qc.add_register(cr)
        cr_lis.append(cr)
    qc.x(down[n - 1])
    for i in range(2 * n):
        qc.x(ctrl).c_if(cr_lis[i], 1)
        neighbor_range = range(np.max([0, i - 2 * n + 1]), 2 * n - i - 1)
        qc.h(ctrl)
        gate = cu_a(n, a**(2**(2 * n - 1 - i)), N)
        qc.append(gate, qargs=ctrl[:] + down[:] + down_b[:] + ancilla[:])
        qc.h(ctrl)
        # qc.measure(ctrl,i)
        qc.measure(ctrl, cr_lis[i])
        if neighbor_range != range(0, 0):
            gate = myR(i, neighbor_range, cr_lis)
            qc.append(gate, qargs=ctrl[:])
    if args == None:
        return qc
    if args.draw:
        qcpath = f'./sequential/circuit'
        if not os.path.exists(qcpath):
            os.makedirs(qcpath)
        circuit_drawer(qc,
                       output='mpl',
                       filename=f'./sequential/circuit/{N}_{a}.png',
                       scale=0.6)

    res = sim.mySim(qc, args)
    print(res)
    new_dict = {}

    for iter in list(res):
        tmp = iter
        tmp = tmp.replace(" ", "")
        new_dict[tmp] = res.pop(iter)
    # print(new_dict)
    lis = sim.sort_by_prob(new_dict)
    # print(lis)
    if args.output:
        respath = f'./sequential/result'
        if not os.path.exists(respath):
            os.makedirs(respath)
        plot_histogram(
            new_dict, figsize=(10, 10),
            title=f'N={N} a={a} result(Seq)').savefig(respath +
                                                      f'/{N}_{a}_res.png')
    with open(f'./sequential/result/{N}_{a}.csv', 'w') as out:
        csv_out = csv.writer(out)
        for i in lis:
            csv_out.writerow(i)
コード例 #13
0
ファイル: myAlgo.py プロジェクト: alfa871212/shor_paper
def shorNormal(N, a, args=None):
    # check whether a, N is coprime
    if math.gcd(a, N) != 1:
        raise Exception("a,N are not coprime.")
    # circuit preparation
    n = math.ceil(math.log(N, 2))
    up = QuantumRegister(2 * n, name='up')
    down = QuantumRegister(n, name='x')
    down_b = QuantumRegister(n + 1, name='b')
    ancilla = QuantumRegister(1, name='ancilla')
    cr = ClassicalRegister(2 * n, name='cr')
    qc = QuantumCircuit(up, down, down_b, ancilla, cr)
    # initialize
    qc.h(up)
    qc.x(down[n - 1])
    # control-unitary gate application
    for i in range(0, 2 * n):
        gate = cu_a(n, a**(2**i), N, print_qc=False)
        qc.append(gate, qargs=[up[i]] + down[:] + down_b[:] + ancilla[:])
    # rest circuit construction
    qftgate = myQFT(2 * n, inverse=True)
    qc.append(qftgate, qargs=up)
    for i in range(0, 2 * n):
        qc.measure(up[i], cr[2 * n - 1 - i])
    # ===========================================================================
    # Result formation
    if args is None:
        return qc
    if args.draw:
        qcpath = f'./normal/circuit'
        if not os.path.exists(qcpath):
            os.makedirs(qcpath)
        circuit_drawer(qc,
                       output='mpl',
                       filename=f'./normal/circuit/{N}_{a}.png',
                       scale=0.6)
    if args.simcmp:
        sim.gpuSim(qc)
        sim.cpuSim(qc)
        return

    res = sim.mySim(qc, args)

    lis = sim.sort_by_prob(res)
    if args.output:
        respath = f'./normal/result'
        if not os.path.exists(respath):
            os.makedirs(respath)
        plot_histogram(
            res, figsize=(10, 10),
            title=f'N={N} a={a} result(Nor)').savefig(respath +
                                                      f'/{N}_{a}_res.png')
    path = f'./normal/result/{N}_{a}.csv'
    if os.path.exists(path):
        print("Overwriting the existing data....")
    with open(f'./normal/result/{N}_{a}.csv', 'w') as out:
        csv_out = csv.writer(out)
        for i in lis:
            csv_out.writerow(i)
コード例 #14
0
def execute_circuit(backend, noise_model):
    # Construct the GHZ-state quantum circuit
    circ = QuantumCircuit(3, 3)
    circ.h(0)
    circ.cx(0, 1)
    circ.cx(0, 2)
    circ.measure([0, 1, 2], [0, 1, 2])
    print(circ)

    # Execute on QASM simulator and get counts
    counts = execute(
        circ, Aer.get_backend('qasm_simulator')).result().get_counts(circ)
    display(
        plot_histogram(
            counts,
            title='Ideal counts for 3-qubit GHZ state on local qasm_simulator')
    )

    # Execute noisy simulation on QASM simulator and get counts
    counts_noise = execute(circ,
                           Aer.get_backend('qasm_simulator'),
                           noise_model=noise_model).result().get_counts(circ)
    display(
        plot_histogram(
            counts_noise,
            title=
            "Counts for 3-qubit GHZ state with noise model on local qasm simulator"
        ))

    # Execute noisy simulation on the ibmq_qasm_simulator and get counts
    counts_noise_ibmq = execute(
        circ,
        provider.get_backend('ibmq_qasm_simulator'),
        noise_model=noise_model).result().get_counts(circ)
    display(
        plot_histogram(
            counts_noise_ibmq,
            title=
            "Counts for 3-qubit GHZ state with noise model on IBMQ qasm simulator"
        ))

    # Execute job on IBM Q backend and get counts
    job = execute(circ, backend)
    job_monitor(job)
    counts_ibmq = job.result().get_counts()

    title = "Counts for 3-qubit GHZ state on IBMQ backend " + backend.name()
    display(plot_histogram(counts_ibmq, title=title))

    # Display the results for all runs
    display(
        plot_histogram([counts, counts_noise, counts_noise_ibmq, counts_ibmq],
                       bar_labels=True,
                       legend=[
                           "Baseline", "Noise on simulator",
                           "Noise on IBMQ simulator", "IBM Q backend"
                       ],
                       title="Comparison"))
コード例 #15
0
def iqft(qci, q, n):
                for i in range(n):
                        for j in range(i): qci.cu1(-math.pi/float(2**(i-j)), q[i], q[j])
                                qci.h(q[i])

                                #量子ビット数
                                bx = 3
                                #量子ビット数
                                by = 4
                                #古典的ビット数
                                cn = 4

                                qx = QuantumRegister(bx) #bx個の 量子 レジスタqの 生成
                                qy = QuantumRegister(by) #by個の 量子 レジスタqの 生成
                                c = ClassicalRegister(cn) #cn個の 古典 的 レジスタcの 生成
                                qcx = QuantumCircuit(qx, c) #量子回路の生成
                                qcy = QuantumCircuit(qy, c) #量子回路の生成

                                qc = qcx + qcy

                                for i in range(bx):
                                    qc.h(qx[i])

                                        # 量子ゲート部分 ****************
                                        qc.x(qy[3])

                                        # 制御NOTゲート部分
                                        qc.cx(qx[2],qy[1])
                                        qc.cx(qx[2],qy[2])
                                        qc.cx(qx[1],qy[1])
                                        qc.cx(qx[1],qy[3])

                                        # 制御・制御NOTゲート(トフォリゲート)部分
                                        for i in range(by):
                                            qc.ccx(qx[1],qx[2],qy[i])

                                            # 逆量子フーリエ変換
                                            iqft(qc,qx,3)

                                            # スワップゲート
                                            swap(qc,qx[0],qx[2])


                                                # 古典的レジスタで観測
                                                for i in range(bx):
                                                    qc.measure(qx[bx-1-i],c[i])

                                                        # 量子ゲート部分 ****************

                                                        #量子 回路 を 実 行 し、 結 果 rに 代入 する
                                                        # Use Aer's qasm_simulator
                                                        backend_sim = BasicAer.get_backend('qasm_simulator')
                                                        r = execute(qc, backend_sim, shots=8192).result()
                                                        rc = r.get_counts()
                                                        print(rc)
                                                        # circuit_drawer(qc)
                                                        plot_histogram(rc)
コード例 #16
0
def test_circuit_C_MOD_GROVER_COIN(d, c, sh):
    Q_program = QuantumProgram()

    build_circuit_C_MOD_GROVER_COIN(Q_program, d, c)
    result = Q_program.execute(["test"],
                               backend="local_qasm_simulator",
                               shots=sh,
                               silent=True)
    plot_histogram(result.get_counts('test'))
コード例 #17
0
ファイル: QAOA.py プロジェクト: soosub/bachelor-thesis
def sample(G, gamma, beta, backend, n_samples = 1024, plot_histogram = False):
    circ = create_circuit(G,beta,gamma)
    result = qiskit.execute(circ, backend = backend, shots = n_samples).result()
    counts = result.get_counts()
    
    if plot_histogram:
        from qiskit.tools.visualization import plot_histogram
        plot_histogram(counts)
        
    return counts
コード例 #18
0
def test_circuit_C_GROVER_DIFF_OPER(c, sh):
    Q_program = QuantumProgram()
    initpattern = numpy.zeros((c + 1), dtype=bool)
    initpattern[0] = True
    build_circuit_C_GROVER_DIFF_OPER(Q_program, c, initpattern)
    result = Q_program.execute(["test"],
                               backend="local_qasm_simulator",
                               shots=sh,
                               silent=True)
    plot_histogram(result.get_counts('test'))
コード例 #19
0
ファイル: QAOA.py プロジェクト: soosub/bachelor-thesis
    def counts_to_valueCounts(self, counts, plot_histogram=False):
        d2 = defaultdict(int)
        for k, v in counts.items():
            d2[self.objective(k)] += v

        if plot_histogram:
            from qiskit.tools.visualization import plot_histogram
            plot_histogram(d2)

        return d2
コード例 #20
0
ファイル: myAlgo.py プロジェクト: alfa871212/shor_paper
def test_adder(a, b, n, args):
    if args.log:
        if not os.path.exists('adder/log'):
            os.makedirs('adder/log')
        path = f'adder/log/a{a}_b{b}_n{n}.log'
        sys.stdout = open(path, 'w')
    qc = adder(a, b, n)

    # print("="*40)
    print('=========================')
    print(f"Executing adder with a={a}, b={b}, n={n}...")
    if args.draw:
        figdir = f'./adder/qcfig'
        if not os.path.exists(figdir):
            os.makedirs(figdir)
        figpath = f'./adder/qcfig/a{a}_b{b}_n{n}.png'
        if not os.path.isfile(figpath):
            circuit_drawer(qc, filename=figpath, output='mpl')
    res = sim.mySim(qc, args)
    res_lis = list(res)
    expect_res = a + b
    meas_lis = []
    for i in range(len(res_lis)):
        meas_lis.append(int(res_lis[i], 2))
    equal_flag = False
    if args.simulation:
        dir_name = args.simulation
        if len(res) != 1:
            raise Exception("The measurement result should be determinisitic!")
        print(f"Expect ans = {expect_res}, Measure res = {meas_lis[0]}")
        if expect_res == meas_lis[0]:
            equal_flag = True
    else:
        dir_name = 'real'
        for i in range(len(meas_lis)):
            print(f"Expect ans = {expect_res}, Measure res = {meas_lis[i]}")
            if meas_lis[i] == expect_res:
                equal_flag = True
    if equal_flag:
        print("Result correct! Adder success!")
    else:
        print("Result wrong! Adder failed!")
        if expect_res >= (2**n):
            print("Overflow occurs!")
    if args.output:
        dir = f'./adder/result/{dir_name}'
        if not os.path.exists(dir):
            os.makedirs(dir)
        path = f'./adder/result/{dir_name}/adder{a}_{b}.png'
        plot_histogram(res, figsize=(10, 10),
                       title=f'adder{a}_{b}').savefig(path)

    # print("="*40)
    print('=========================')
コード例 #21
0
def qft3u(g):
    Q_program = QuantumProgram()
    qr = Q_program.create_quantum_register("qr", 3)
    cr = Q_program.create_classical_register("cr", 3)
    qc = Q_program.create_circuit("superposition", [qr], [cr])

    #Entradas
    #qc.h(qr[1])
    qc.h(qr[0])
    #qc.x(qr[0])
    #qc.x(qr[1])
    #qc.x(qr[2])

    #QFT 3
    
    qc.h(qr[2]) #aplica H no 1 qubit

    #S controlada de 2 para 1
    qc.u1(pi/4, qr[2])
    qc.cx(qr[1], qr[2])
    qc.u1(pi/4, qr[1])
    qc.u1(-pi/4, qr[2])
    qc.cx(qr[1], qr[2])

    #T controlada de 0 para 2
    qc.u1(pi/8, qr[2]) #u1=sqrt(T)
    qc.cx(qr[0], qr[2])
    qc.u1(pi/8, qr[0])
    qc.u1(-pi/8, qr[2])
    qc.cx(qr[0], qr[2])

    qc.h(qr[1]) #aplica H no 2 qubit

    #S controlada de 1 para 2
    qc.u1(pi/4, qr[1])
    qc.cx(qr[0], qr[1])
    qc.u1(pi/4, qr[0])
    qc.u1(-pi/4, qr[1])
    qc.cx(qr[0], qr[1])

    qc.h(qr[0]) #aplica H no 3 qubit

    qc.swap(qr[2], qr[0]) # troca o 1 e 3 qubit



    qc.measure(qr, cr)
    result = Q_program.execute(["superposition"], backend='local_qasm_simulator', shots=g)
    print(result)
    print(result.get_data("superposition"))

    tmp = result.get_data("superposition")
    plot_histogram(tmp['counts'])
コード例 #22
0
    def visualize(self, nsamples=20):
        """ Plot a histogram of the top 'nsamples' results from the grover run
    
    Returns:
        dict: top nsamples solutions and their count
    """
        d = self.result['measurement']
        ks = sorted(d.keys(), key=lambda a: d[a])[-nsamples:]
        d = {k: d[k] for k in ks}
        plot_histogram(self.result['measurement'])

        return d
コード例 #23
0
def test_circuit_CNOT(N, sh):
    Q_program = QuantumProgram()
    pattern = numpy.ones((N + 1), dtype=bool)
    pattern[0] = False
    pattern[1] = False
    pattern[2] = False
    pattern[3] = True
    build_circuit_CNOT(Q_program, N, pattern)
    result = Q_program.execute(["test"],
                               backend="local_qasm_simulator",
                               shots=sh,
                               silent=True)
    plot_histogram(result.get_counts('test'))
コード例 #24
0
def run(input, shot):
    #Define the Hamiltonian extracted from the picture
    Picture_Hamilt = np.array(input)
    #Make it Hermitian
    Hermitian_Hamilt = 1 / (np.matrix.trace(Picture_Hamilt)) * Picture_Hamilt
    #Classically get its eigenvalues "l" and eigenvectors "u", we will use the later to intialize one of the qubits
    l, u = LA.eig(Hermitian_Hamilt)

    #Let's create the circuit!
    q = QuantumRegister(2)
    c = ClassicalRegister(2)
    qc = QuantumCircuit(q, c)

    #The inithial state of the second qubit of our circuit will be one of the eigenvectors of the Hamiltonian, we define it:
    state_vector = [u[0][j] for j in range(2)]
    qc.initialize(state_vector, [q[1]])
    #Quantum Phase Estimation begins
    #create superposition wuth the Hadamard gate
    qc.h(q[0])
    #The unitary matrix of the controlled unitary gate of the quantum phase estimation circuit is the following:
    UH = expm(1j * Hermitian_Hamilt)
    (th, ph, lam
     ) = qiskit.quantum_info.synthesis.two_qubit_decompose.euler_angles_1q(UH)
    qc.cu3(th, ph, lam, q[0], q[1])
    #Inverse QFT
    qc.h(q[0])

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

    #Run on qasm simulator
    backend_qasm = BasicAer.get_backend('qasm_simulator')
    job_qasm = execute(qc, backend_qasm, shots=shot)
    result_qasm = job_qasm.result()
    counts = result_qasm.get_counts(qc)
    print(counts)
    Emo1 = (counts.get('11') or 0)
    Emo2 = (counts.get('10') or 0)
    Emo3 = (counts.get('01') or 0)
    Emo4 = (counts.get('00') or 0)
    ProbEmo1 = round(Emo1 / shot, 2)
    ProbEmo2 = round(Emo2 / shot, 2)
    ProbEmo3 = round(Emo3 / shot, 2)
    ProbEmo4 = round(Emo4 / shot, 2)
    plot_histogram(counts)
    probs = {"11": ProbEmo1, "10": ProbEmo2, "01": ProbEmo3, "00": ProbEmo4}
    return probs
コード例 #25
0
def test_circuit_C_DECR(N, flag, sh, iter):
    Q_program = QuantumProgram()
    initpattern = numpy.zeros((N + 1), dtype=bool)
    cpattern = numpy.zeros((N), dtype=bool)
    initpattern[0] = False
    initpattern[1] = False
    initpattern[2] = False
    initpattern[3] = True
    build_circuit_C_DECR(Q_program, N, flag, initpattern, iter)
    result = Q_program.execute(["test"],
                               backend="local_qasm_simulator",
                               shots=sh,
                               silent=True)
    plot_histogram(result.get_counts('test'))
コード例 #26
0
def get_value_distribution(circuit, key_bits, value_bits, neg=False):
    probs = get_probs(circuit, False)

    ordered_probs = sorted(probs.items(), key=lambda x: x[1], reverse=True)
    print("Probabilities: ", ordered_probs)

    v_freq = process_values(key_bits, value_bits, probs, neg)

    from qiskit.tools import visualization
    visualization.plot_histogram(v_freq)

    ordered_freq = sorted(v_freq.items(), key=lambda x: x[1], reverse=True)

    print("Value Distribution", ordered_freq)
コード例 #27
0
def get_value_for_key(circuit, key_bits, value_bits, neg=False):
    probs = get_probs(circuit, False)

    from qiskit.tools import visualization
    visualization.plot_histogram(probs)

    ordered_probs = sorted(probs.items(), key=lambda x: x[1], reverse=True)
    print("Probabilities: ", ordered_probs)

    _, outcomes = process(key_bits, value_bits, probs, neg)
    ordered_outcomes = sorted(outcomes.items(), key=lambda x: x[1], reverse=True)

    print("Outcomes", ordered_outcomes)
    return ordered_probs[0][0]
コード例 #28
0
    def get_value_distribution(self):
        circuit = self.__build_circuit(self.key_bits, self.value_bits, self.f, None, None)
        probs = get_probs((circuit, None, None), 'sim', False)

        ordered_probs = sorted(probs.items(), key=lambda x: x[1], reverse=True)
        print("Probabilities: ", ordered_probs)

        v_freq = self.__process_values(self.key_bits, self.value_bits, probs)

        from qiskit.tools import visualization
        visualization.plot_histogram(v_freq)

        ordered_freq = sorted(v_freq.items(), key=lambda x: x[1], reverse=True)

        print("Value Distribution", ordered_freq)
コード例 #29
0
    def get_value_for_key(self, key, neg = False):
        circuit = self.__build_circuit(self.key_bits, self.value_bits, self.f, key)
        probs = get_probs((circuit, None, None), 'sim', False)

        from qiskit.tools import visualization
        visualization.plot_histogram(probs)

        ordered_probs = sorted(probs.items(), key=lambda x: x[1], reverse=True)
        print("Probabilities: ", ordered_probs)

        _, outcomes = self.__process(self.key_bits, self.value_bits, probs, neg)
        ordered_outcomes = sorted(outcomes.items(), key=lambda x: x[1], reverse=True)

        print("Outcomes", ordered_outcomes)
        return ordered_probs[0][0]
コード例 #30
0
def execute_quantum_circuit(cir,
                            shots=100,
                            number_qubits=None,
                            use_ibmq=False,
                            specific_ibmq_backend=None):

    # Select a specific quantum circuit
    quantum_instance = get_quantumcomputer_quantum_instance(
        shots, number_qubits, use_ibmq, specific_ibmq_backend)

    # Execute quantum circut
    result = quantum_instance.execute(cir)
    plot_histogram(result.get_counts(cir))

    return quantum_instance.backend_name