<jupyter_start><jupyter_text>Phase estimation<jupyter_code>def phaseEstimate(op,xbits,cuj):
    N=len(xbits)
    for i in reversed(range(N)):
        op=op.H(xbits[i])
        op=cuj(xbits[i],2**i,op)
    op=qft(op,mask=xbits,inverse=True)
    return op

# Simple U = {{ Exp[I 2pi phi], 0}, { 0, Exp[-I 2pi phi] }}, always acting on LSB
def CU(i,k,op,phi): # i is control qubit, k is power
    return op.Rz(0,2.*np.pi*phi*k).CNOT(i,0).Rz(0,-2.*np.pi*phi*k).CNOT(i,0)

def measure(Nxbits,Nmeasure,cuj):
    Nbits=Nxbits+1
    xbits=list(range(1,Nbits))
    
    st0=sqc.state(Nbits,basis=["|%g>|%d>" % ( (i//2) / 2**Nxbits,i%2) for i in range(2**Nbits)])
    print("Initial = 0\n",st0)

    st1=phaseEstimate(sqc.operator(Nbits).H(0),xbits,cuj)*st0

    if Nmeasure == 0:
        print("State after phaseEstimate\n",st1)
    else:
        res=sqc.sample(st1,Nmeasure,mask=xbits)
        
        plt.bar([ x / 2**Nxbits for x in res.keys() ],res.values(),width=0.01)
        plt.xlabel('phi')
        plt.xlim(0,1)
        plt.ylabel('count')
        plt.show()
        
        print(res)
        
    

measure(4,0,lambda i,k,op: CU(i,k,op,0.25))
measure(4,10000,lambda i,k,op: CU(i,k,op,0.3))
Nphi0t=4392
Nphi0tM1=295
Nphi0tP1=108

eps=2**-4

phi0tilde=5*eps
print(phi0tilde)

r=Nphi0tM1/Nphi0tP1
phi=phi0tilde+eps*(1.-r**0.5)/(1.+r**0.5)
print(phi)
print(eps*(1.-r**0.5)/(1.+r**0.5)*0.1)
measure(4,1000,lambda i,k,op: CU(i,k,op,0.4))
measure(5,1000,lambda i,k,op: CU(i,k,op,0.4))
measure(6,1000,lambda i,k,op: CU(i,k,op,0.4))
measure(7,1000,lambda i,k,op: CU(i,k,op,0.4))<jupyter_output>Initial = 0
    1 * |0>|0><jupyter_text>More general one-qubit matrices<jupyter_code>def CU2(i,k,op,phi,theta): # i is control qubit, k is power
    return op.Rz(0,np.pi*(phi-theta)*k).CNOT(i,0).Rz(0,np.pi*(theta-phi)*k).CNOT(i,0).Rz(i,np.pi*(theta+phi)*k)


measure(7,1000,lambda i,k,op: CU2(i,k,op,0.2,0.5))
def CU2H(i,k,op,phi,theta): # i is control qubit, k is power
    return op.H(0).Rz(0,np.pi*(phi-theta)*k).CNOT(i,0).Rz(0,np.pi*(theta-phi)*k).CNOT(i,0).Rz(i,np.pi*(theta+phi)*k).H(0)


measure(7,1000,lambda i,k,op: CU2H(i,k,op,0.2,0.5))<jupyter_output>Initial = 0
    1 * |0>|0>
{'fraction_non_alphanumeric': 0.2263544536271809, 'fraction_numerical': 0.06978879706152434, 'mean_word_length': 4.127058823529412, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 13, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '2', 'dir': 'jupyter-structured-clean-dedup', 'id': '279543', 'license': 'MIT', 'n_tokens_mistral': 1137, 'n_tokens_neox': 1071, 'n_words': 137, 'path': 'examples/chapter1/phase.ipynb', 'repo_name': 'gnrraphi/sqc', 'size': '2178'}