№ 2074Квантовые вычисленияУровень 4

Точность и вероятность QPE

Исследуйте связь между числом счётных кубитов, точностью и вероятностью успеха квантовой оценки фазы QPE. Оценивается фаза φ=1/3 вентиля $P(2\pi/3)=\operatorname{diag}(1,e^{2\pi i/3})$ на собственном состоянии $|1\rangle$. Регистр счётных кубитов начинают в равномерной суперпозиции, применяют управляемые степени вентиля, обратное QFT и измеряют.

1. Найдите вероятность успешной оценки с точностью $2^{-2}$ при четырёх счётных кубитах.
A. Создайте схему qc4, выполните её на qasm_simulator и постройте гистограмму. Исходный образец — «Getting More Precision» в главе QPE; все параметры схемы заданы здесь, необходимая функция QFT сохранена в условии.
B. Пусть m — измеренная оценка фазы, b — лучшая оценка, здесь b=0.3125 (0101), t=4. Найдите максимальное целое e, при котором все исходы с $|m-b|\leq e/2^t$ приближают 1/3 с точностью $2^{-2}$. Например, e=1 включает 0100,0101,0110 — оценки 0.25,0.3125,0.375.
C. Вычислите вероятность получить приближение нужной точности и проверьте нижнюю границу $1-1/[2(2^{t-n}-2)]$, где n=2. В исходной процедуре суммируются исходы, отобранные симметричным окном e вокруг b.
2. Повторите для t=4,5,6,7,8,9 и сравните с $t=n+\log_2(2+1/(2\epsilon))$, где $1-\epsilon$ — требуемая вероятность.
A. Создайте все шесть схем для φ=1/3 и сохраните их списком circ; выполните одним заданием.
B. Найдите e для каждого t и проверьте $e=2^{t-n}-1$ при n=2.
C. Вычислите вероятности нужной точности и сохраните в prob_success.
D. Нанесите эти значения на исходный график нижней границы и разберитесь в результате.

Исходный график нижней границы дан в условии; готовые авторские гистограммы и итоговые графики — только в разборе. В предоставленном коде shots=20000. Далее автор также показывает кривые границ для n=2,3,4.

Исходные определения и заготовки (код сохранён без исполнения):

from qiskit import *
import numpy as np
from qiskit.visualization import plot_histogram
import qiskit.tools.jupyter
from qiskit.tools.monitor import job_monitor
from qiskit.ignis.mitigation.measurement import *
import matplotlib.pyplot as plt

def qft(n):
    """Creates an n-qubit QFT circuit"""
    circuit = QuantumCircuit(n)
    def swap_registers(circuit, n):
        for qubit in range(n//2):
            circuit.swap(qubit, n-qubit-1)
        return circuit
    def qft_rotations(circuit, n):
        """Performs qft on the first n qubits in circuit (without swaps)"""
        if n == 0:
            return circuit
        n -= 1
        circuit.h(n)
        for qubit in range(n):
            circuit.cp(np.pi/2**(n-qubit), qubit, n)
        qft_rotations(circuit, n)
    
    qft_rotations(circuit, n)
    swap_registers(circuit, n)
    return circuit

## Start your code to create the circuit, qc4











qc4.draw()

## Run this cell to simulate 'qc4' and to plot the histogram of the result
sim = Aer.get_backend('qasm_simulator')
shots = 20000
count_qc4 = execute(qc4, sim, shots=shots).result().get_counts()
plot_histogram(count_qc4, figsize=(9,5))

phi_est = np.array([round(int(key, 2)/2**t,3) for key in list(count_qc4.keys())])
key_new = list(map(str, phi_est))
count_new = dict(zip(key_new, count_qc4.values()))
plot_histogram(count_new, figsize=(9,5))

## Your code goes here











## Your code goes here














y = lambda t, n: 1-1/(2*(2**(t-n)-2))
t_q = np.linspace(3.5, 9.5, 100 )
p_min = y(t_q, 2)

plt.figure(figsize=(7, 5))
plt.plot(t_q, p_min, label='$p_{min}$')
plt.xlabel('t: number of counting qubits')
plt.ylabel('probability of success for the accuracy $2^{-2}$')
plt.legend(loc='lower right')
plt.title('Probability of success for different number of counting qubits')
plt.show()

## Your Code to create the list variable 'circ' goes here



















# Run this cell to simulate `circ` and plot the histograms of the results

results = execute(circ, sim, shots=shots).result()

n_circ = len(circ)
counts = [results.get_counts(idx) for idx in range(n_circ)]

fig, ax = plt.subplots(n_circ,1,figsize=(25,40))
for idx in range(n_circ):
    plot_histogram(counts[idx], ax=ax[idx])
plt.tight_layout()

## Your Code goes here



















## Your code to create the list variable, 'prob_success',  goes here




















## Your code goes here























t = np.linspace(5.1, 10, 100)
prob_success_n = [y(t, n) for n in [2, 3, 4]]
prob_n2, prob_n3, prob_n4  = prob_success_n[0], prob_success_n[1], prob_success_n[2]

plt.figure(figsize=(7, 5))
plt.plot(t, prob_n2, t, prob_n3, t, prob_n4, t, [1]*len(t),'--' )
plt.axis([5, 10, 0.7, 1.05])
plt.xlabel('t: number of counting qubits')
plt.ylabel('probability of success for the accuracy $2^{-n}$')
plt.legend(['n = 2', 'n = 3', 'n = 4'], loc='lower right')
plt.grid(True)
Рисунок к задаче 2074