Commit a7f30e08 authored by Marcelo Luda's avatar Marcelo Luda
Browse files

update

parent b25a253b
Loading
Loading
Loading
Loading
+123 −253
Changes for analisis/plots/20231123_CPTconmicromocion3/lolo_graficos_pub.py: 123 added lines, 253 removed lines.
Original line number Diff line number Diff line
@@ -312,45 +312,31 @@ def hiperbola(x,a,y0,b,x0):
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#%% Graficamos todos los fiteos

# tmp_datos=(Detuningsshort_vec,Counts_vec,Detuningslong_vec,FittedCounts_vec,SelectedCurveVec)

# for Detunings_3_SA_short,CountsDR,Detunings_3_SA_long,FittedEITpi_3_SA_long,selectedcurve in zip(*tmp_datos):
#     plt.figure()
#     plt.errorbar(Detunings_3_SA_short, CountsDR, yerr=2*np.sqrt(CountsDR), fmt='o', color='darkgreen', alpha=0.5, capsize=2, markersize=2)
#     plt.plot(Detunings_3_SA_long, FittedEITpi_3_SA_long, color='darkolivegreen', linewidth=3, label=f'med {selectedcurve}')
#     #plt.title(f'Sdop: {round(popt[0], 2)}, Spr: {round(popt[1], 2)}, T: {round(popt[2]*1e3, 2)} mK, detDop: {DetDoppler} MHz')
#     plt.xlabel('Detuning (MHz)')
#     plt.ylabel('Counts')
#     plt.legend(loc='upper left', fontsize=20)
#     plt.grid()

#     print(f'listo med {selectedcurve}')
#     print(popt_3_SA)

# fig, axx = plt.subplots( 3,4, figsize=(13,8) ,  constrained_layout=True, sharex=True , sharey=True )
# fig.set_constrained_layout_pads(w_pad=2/72, h_pad=2/72, hspace=0, wspace=0)

fig, axx = plt.subplots( 3,4, figsize=(13,8) ,  constrained_layout=True, sharex=True , sharey=True )
fig.set_constrained_layout_pads(w_pad=2/72, h_pad=2/72, hspace=0, wspace=0)

tmp_datos=(Detuningsshort_vec,Counts_vec,Detuningslong_vec,FittedCounts_vec,SelectedCurveVec,axx.flatten())
# tmp_datos=(Detuningsshort_vec,Counts_vec,Detuningslong_vec,FittedCounts_vec,SelectedCurveVec,axx.flatten())

for Detunings_3_SA_short,CountsDR,Detunings_3_SA_long,FittedEITpi_3_SA_long,selectedcurve,ax in zip(*tmp_datos):
    ax.errorbar(Detunings_3_SA_short, CountsDR, yerr=2*np.sqrt(CountsDR), fmt='o', color='darkgreen', alpha=0.3, capsize=2, markersize=2)
    ax.plot(Detunings_3_SA_long, FittedEITpi_3_SA_long, color='black', linewidth=2, label=f'med {selectedcurve}', alpha=0.7)
    #plt.title(f'Sdop: {round(popt[0], 2)}, Spr: {round(popt[1], 2)}, T: {round(popt[2]*1e3, 2)} mK, detDop: {DetDoppler} MHz')
    # ax.set_xlabel('Detuning (MHz)')
    # ax.set_ylabel('Counts')
    ax.legend(loc='upper left', fontsize=12)
    ax.grid(True, ls=":")
# for Detunings_3_SA_short,CountsDR,Detunings_3_SA_long,FittedEITpi_3_SA_long,selectedcurve,ax in zip(*tmp_datos):
#     ax.errorbar(Detunings_3_SA_short, CountsDR, yerr=2*np.sqrt(CountsDR), fmt='o', color='darkgreen', alpha=0.3, capsize=2, markersize=2)
#     ax.plot(Detunings_3_SA_long, FittedEITpi_3_SA_long, color='black', linewidth=2, label=f'med {selectedcurve}', alpha=0.7)
#     #plt.title(f'Sdop: {round(popt[0], 2)}, Spr: {round(popt[1], 2)}, T: {round(popt[2]*1e3, 2)} mK, detDop: {DetDoppler} MHz')
#     # ax.set_xlabel('Detuning (MHz)')
#     # ax.set_ylabel('Counts')
#     ax.legend(loc='upper left', fontsize=12)
#     ax.grid(True, ls=":")

    print(f'listo med {selectedcurve}')
    # print(popt_3_SA)
#     print(f'listo med {selectedcurve}')
#     # print(popt_3_SA)


for ax in axx[:,0]:
    ax.set_ylabel('Counts')
# for ax in axx[:,0]:
#     ax.set_ylabel('Counts')

for ax in axx[-1,:]:
    ax.set_xlabel('Detuning (MHz)')
# for ax in axx[-1,:]:
#     ax.set_xlabel('Detuning (MHz)')



@@ -360,7 +346,7 @@ for ax in axx[-1,:]:


#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#%% Gráfico central 
#%% Gráfico central OPCION A

import matplotlib.pyplot as plt
plt.rcParams.update({'font.size': 8})
@@ -508,284 +494,168 @@ fig.savefig('grafico_central_opcion_A.pdf')







# import matplotlib.pyplot as plt
# from matplotlib import gridspec

# fig = plt.figure()
# gs = gridspec.GridSpec(1,2)
# ax1 = fig.add_subplot(gs[0])
# ax2 = fig.add_subplot(gs[1], sharey=ax1)
# plt.setp(ax2.get_yticklabels(), visible=False)

# plt.setp([ax1, ax2], title='Test')
# fig.suptitle('An overall title', size=20)
# gs.tight_layout(fig, rect=[0, 0, 1, 0.97])

# plt.show()

#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#%% Endcap hiperbola (con residuos)
"""
Veamos cómo varía el Beta con el voltaje del endcap
"""

import seaborn as sns
paleta = sns.color_palette("rocket")


I = slice(None,9)

voltages_dcA  = Voltages[0][SelectedCurveVec]

#%% Gráfico central OPCION A

import matplotlib.pyplot as plt
plt.rcParams.update({'font.size': 8})

def lineal(x,a,b):
    return a*x+b
# Para esto hace falta:
# sudo apt install dvipng

def hiperbola(x,a,y0,b,x0):
    """
    Hiperbola de ecuación:
        1 =(y-y0)²/a² - (x-x0)²/b² 
    """
    return a*np.sqrt(((x-x0)**2+b**2))+y0
plt.rcParams['text.usetex']=True
# plt.rcParams['text.latex.unicode']=True
# params= {'text.latex.preamble' : [r'\usepackage{amsmath}']}
# plt.rcParams.update(params)

es_hiperbola = False

# fig, axx = plt.subplots( 3,4, figsize=(8.6/2.54*2,4) ,  constrained_layout=True, sharex=True , sharey=True )
# fig.set_constrained_layout_pads(w_pad=2/72, h_pad=2/72, hspace=0, wspace=0)

# par_inicial = (100,0.1,1,-0.15)
#               a   y0   b  x0
par_inicial = (12,0.1,1,-0.13)

## Layout ###########################
from matplotlib import gridspec
figsize=(8.6/2.54*2,4)
width_ratios=[1,2,1]

popthip,pcovhip = curve_fit(hiperbola,voltages_dcA[I],Betas_vec[I],p0=par_inicial)
fig, axx = plt.subplots(ncols=3, nrows=3, sharex=True, sharey=False,   constrained_layout=True,
                        figsize=figsize, gridspec_kw=dict(width_ratios=width_ratios))
fig.set_constrained_layout_pads(w_pad=1/72, h_pad=1/72, hspace=0, wspace=0)
fig.set_constrained_layout_pads(w_pad=0, h_pad=0, hspace=0, wspace=0)

xhip = np.linspace(-0.23,0.005,200)
gs = axx[0, 0].get_gridspec()
# remove the underlying axes
for ax in axx[:,1]:
    ax.remove()
    
# plt.figure()
# plt.errorbar(voltages_dcA[I],Betas_vec[I],yerr=ErrorBetas_vec[I],fmt='o',capsize=5,markersize=5,color=paleta[1])
# plt.plot(xhip,hiperbola(xhip,*popthip))
# # plt.plot(xhip,hiperbola(xhip,*par_inicial),'--',color='red')
# plt.xlabel('Endcap voltage (V)')
# plt.ylabel('Modulation factor')
# plt.grid()

gs2 = gridspec.GridSpec(4,3, width_ratios=width_ratios,left=0.16,right=0.9,bottom=0.12)

ax_central = fig.add_subplot(gs2[1:-1, 1])

ax_dib = fig.add_subplot(gs2[0, 1])
ax_dib.spines[:].set_visible(False)
ax_dib.xaxis.set_tick_params(labelbottom=False)
ax_dib.yaxis.set_tick_params(labelleft=False)
ax_dib.set_xticks([])
ax_dib.set_yticks([])

fig, axx = plt.subplots( 2, figsize=(10,7) ,  
                        constrained_layout=True, sharex=True,
                        gridspec_kw=dict(height_ratios=[10,2]))
fig.set_constrained_layout_pads(w_pad=2/72, h_pad=2/72, hspace=0, wspace=0)
ax_res = fig.add_subplot(gs2[-1, 1], sharex=ax_central,zorder=-5)
plt.setp(ax_central.get_xticklabels(), visible=False)

ax = axx[0]
for ax in axx[:,2]:
    ax.yaxis.tick_right()
    ax.yaxis.set_label_position("right")

ax.errorbar(voltages_dcA[I],Betas_vec[I],yerr=ErrorBetas_vec[I],fmt='o',capsize=5,markersize=5,color=paleta[1])
ax.plot(xhip,hiperbola(xhip,*popthip))
# plt.plot(xhip,hiperbola(xhip,*par_inicial),'--',color='red')

ax.set_ylabel('Modulation factor')

ax = axx[1]
## CPTs ########################################
selection= (0,1,3,4,7,8)
axes_vec = (axx[0,0],axx[1,0],axx[2,0],axx[2,2],axx[1,2],axx[0,2])

ax.errorbar(voltages_dcA[I],Betas_vec[I]-hiperbola(voltages_dcA[I],*popthip),
            yerr=ErrorBetas_vec[I],fmt='o',capsize=5,markersize=5,color=paleta[1])
tmp_datos=(Detuningsshort_vec[selection,:],
           Counts_vec[selection,:],
           Detuningslong_vec[selection,:],
           FittedCounts_vec[selection,:],
           np.array(selection)+1,
           axes_vec,'abcfed')

ax.set_ylabel('Res.')
ax.set_xlabel('Endcap voltage (V)')
for Detunings_3_SA_short,CountsDR,Detunings_3_SA_long,FittedEITpi_3_SA_long,selectedcurve,ax,le in zip(*tmp_datos):
    ax.errorbar(Detunings_3_SA_short, CountsDR, yerr=2*np.sqrt(CountsDR), 
                fmt='o', color='darkgreen', alpha=0.2, capsize=2, 
                markersize=2, label='measured data')
    ax.plot(Detunings_3_SA_long, FittedEITpi_3_SA_long, 
            color='black', linewidth=2, label=f'micromotion model', alpha=0.7)
    
for ax in axx:
    ax.grid(True, ls=":", color='lightgray')
    
    ax.set_yticklabels([ f"{int(y/1000)}k" for y in ax.get_yticks() ])
    
print([t*1e3 for t in Temp_vec])


#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#%% Este hay que armarlo aún

plt.figure()
plt.errorbar(voltages_dcA,[t*1e3 for t in Temp_vec],yerr=[t*1e3 for t in ErrorTemp_vec],fmt='o',capsize=5,markersize=5,color=paleta[3])
# plt.axvline(minimum_voltage,linestyle='dashed',color='grey')
print(f'\n\nTE FALTA DEFINIR LA VARIABLE minimum_voltage\n\n')
plt.axhline(0.538)
plt.xlabel('Endcap voltage (V)')
plt.ylabel('Temperature (mK)')
plt.grid()
#plt.ylim(0,2)



#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#%% Ajuste de los betas y la temperatura

from scipy.special import jv


def expo(x,tau,A,B):
    return A*np.exp(x/tau)+B

def cuadratica(x,a,c):
    return a*(x**2)+c

def InverseMicromotionSpectra(beta, A, det, x0, gamma, B):
    ftrap=22.1
    #gamma=30
    P = ((jv(0, beta)**2)/((((det-x0)**2)+(0.5*gamma)**2)**2))*(-2*(det-x0))
    i = 1
    #print(P)
    while i <= 5:
        P = P + (-2*(det-x0))*((jv(i, beta))**2)/(((((det-x0)+i*ftrap)**2)+(0.5*gamma)**2)**2) + (-2*(det-x0))*(((jv(-i, beta))**2)/((((det-x0)-i*ftrap)**2)+(0.5*gamma)**2)**2)
        i = i + 1
        #print(P)
    #return 1/(A*P+B)
    return 1/(A*P+B)
    ax.set_title(f'({le})', x=0.1, y=0.78, color='gray')
    # ax.legend()
    # ax.legend(ax.get_legend_handles_labels()[0], f'{selectedcurve}')
    print(f'listo med {selectedcurve}')


def InverseMicromotionSpectra_raw(beta, A, det, B):
    ftrap=22.1
    gamma=21
    P = ((jv(0, beta)**2)/((((det)**2)+(0.5*gamma)**2)**2))*(-2*(det))
    i = 1
    #print(P)
    while i <= 3:
        P = P + (-2*(det))*((jv(i, beta))**2)/(((((det)+i*ftrap)**2)+(0.5*gamma)**2)**2) + (-2*(det))*(((jv(-i, beta))**2)/((((det)-i*ftrap)**2)+(0.5*gamma)**2)**2)
        i = i + 1
        #print(P)
    return A/P+B
axx[2,0].set_xlabel('Detuning [MHz]')
axx[2,2].set_xlabel('Detuning [MHz]')

axx[1,0].set_ylabel('Counts')
axx[1,2].set_ylabel('Counts')

"""
Temperatura vs beta con un ajuste exponencial 
"""

popt_exp, pcov_exp = curve_fit(expo,Betas_vec[:10],[t*1e3 for t in Temp_vec[:10]])
popt_quad, pcov_quad = curve_fit(cuadratica,Betas_vec[:10],[t*1e3 for t in Temp_vec[:10]],p0=(1,10))
#popt_rho22, pcov_rho22 = curve_fit(InverseMicromotionSpectra,Betas_vec,[t*1e3 for t in Temp_vec],p0=(10,10,-10,1,20)) #esto ajusta muy bien
#popt_rho22, pcov_rho22 = curve_fit(InverseMicromotionSpectra,Betas_vec, [t*1e3 for t in Temp_vec],p0=(-10,-10,10,1,20)) #esto ajusta muy bien
popt_rho22_raw, pcov_rho22_raw = curve_fit(InverseMicromotionSpectra_raw,Betas_vec[:10], [t*1e3 for t in Temp_vec[:10]],p0=(-10, -10, 1)) #esto ajusta muy bien


print(popt_rho22_raw)

betaslong = np.arange(0,2*2.7,0.01)
## Grafico central ###############################
I = slice(None,9)
par_inicial = (12,0.1,1,-0.13)
param,pcov = curve_fit(hiperbola,voltages_dcA[I],Betas_vec[I],p0=par_inicial)
x_hip = np.linspace(-0.23,0.005,200)

print(f'Min temp predicted: {InverseMicromotionSpectra_raw(betaslong,*popt_rho22_raw)[100]}')

plt.figure()
plt.errorbar(Betas_vec[:10],[t*1e3 for t in Temp_vec[:10]],xerr=ErrorBetas_vec[:10], yerr=[t*1e3 for t in ErrorTemp_vec[:10]],fmt='o',capsize=5,markersize=5,color=paleta[3])
#plt.plot(betaslong,expo(betaslong,*popt_exp),label='Ajuste exponencial')
#plt.plot(betaslong,cuadratica(betaslong,*popt_quad),label='Ajuste cuadratico')
#plt.plot(betaslong,InverseMicromotionSpectra(betaslong,*popt_rho22),label='Ajuste cuadratico')
plt.plot(betaslong,InverseMicromotionSpectra_raw(betaslong,*popt_rho22_raw),label='Ajuste cuadratico')
ax = ax_central
ax.errorbar(voltages_dcA[I],Betas_vec[I],yerr=ErrorBetas_vec[I],fmt='o',
            capsize=4,markersize=3,color='C3', label=r'fitted $\beta$')
ax.plot(x_hip,hiperbola(xhip,*popthip),color='C0', label=r'hyperbola model')
ax.set_ylabel(r'Modulation factor $\beta$', labelpad=-5)
ax.set_ylim(-0.05,3)
ax.set_xlim(-0.22,0)
ax.set_title(f'(g)', x=0.95, y=0.006, color='gray')

#plt.axvline(minimum_voltage,linestyle='dashed',color='grey')
#plt.axhline(0.538)
plt.xlabel('Modulation factor')
plt.ylabel('Temperature (mK)')
plt.grid()
ax = ax_res
ax.errorbar(voltages_dcA[I],Betas_vec[I]-hiperbola(voltages_dcA[I],*popthip),
            yerr=ErrorBetas_vec[I],fmt='o',capsize=4,markersize=3,color='C3')
ax.axhline( 0 , color='C0')
ax.set_ylabel('Res.', labelpad=-5)
ax.set_xlabel('Endcap voltage [V]')
ax.set_title(f'(h)', x=0.95, y=0.72, color='gray')


#%%
"""
Esto no es del super ajuste sino de los ajustes anteriores en donde DetDoppler y offset son puestos a mano
Aca grafico los betas con su error en funcion de la tension variada.
Ademas, hago ajuste lineal para primeros y ultimos puntos, ya que espero que
si la tension hace que la posicion del ion varie linealmente, el beta varia proporcional a dicha posicion.
"""
ax_res.get_xticklabels()[-1].set_visible(False)

import seaborn as sns
for ax in [ax_central,ax_res]:
    ax.grid(True, ls=":", color='lightgray')

def lineal(x,a,b):
    return a*x+b

paleta = sns.color_palette("rocket")
# print([t*1e3 for t in Temp_vec])

betavector = [beta1,beta2,beta3,beta4,beta5,beta6,beta7,beta8,beta9]
errorbetavector = [errorbeta1,errorbeta2,errorbeta3,errorbeta4,errorbeta5,errorbeta6,errorbeta7,errorbeta8,errorbeta9]
voltages_dcA = Voltages[0][1:10]

poptini,pcovini = curve_fit(lineal,voltages_dcA[0:3],betavector[0:3])
poptfin,pcovfin = curve_fit(lineal,voltages_dcA[4:],betavector[4:])
# Anotaciones ##########################
for jj,ax in zip(selection,axes_vec):
    
minimum_voltage = -(poptini[1]-poptfin[1])/(poptini[0]-poptfin[0]) #voltaje donde se intersectan las rectas, es decir, donde deberia estar el minimo de micromocion
minimum_modulationfactor = lineal(minimum_voltage,*poptini) #es lo mismo si pongo *poptfin
    Axes_x = 1 if axx.flatten().tolist().index(ax)%3==0 else 0
    ax_central.annotate("",
                         xy=(ax_central.get_lines()[0].get_xdata()[jj], ax_central.get_lines()[0].get_ydata()[jj]), 
                         xycoords=ax_central.transData,
                         xytext=(Axes_x, 0.5), textcoords=ax.transAxes,
                         arrowprops=dict(arrowstyle="<-",connectionstyle="arc3,rad=-0.2", color='gray', alpha=0.5),
                         zorder=-2)
    
xini = np.linspace(-0.23,-0.13,100)
xfin = np.linspace(-0.15,0.005,100)

plt.figure()
plt.errorbar(voltages_dcA,betavector,yerr=errorbetavector,fmt='o',capsize=5,markersize=5,color=paleta[1])
plt.plot(xini,lineal(xini,*poptini))
plt.plot(xfin,lineal(xfin,*poptfin))
plt.axvline(minimum_voltage,linestyle='dashed',color='grey')
plt.xlabel('Endcap voltage (V)')
plt.ylabel('Modulation factor')
plt.grid()

# dibujos ##########################

#%%
"""
Aca veo la temperatura del ion en funcion del voltaje del endcap, ya que
al cambiar la cantidad de micromocion, cambia la calidad del enfriado
"""
tempvector = np.array([temp1,temp2,temp3,temp4,temp5,temp6,temp7,temp8,temp9])*1e3
errortempvector = np.array([errortemp1,errortemp2,errortemp3,errortemp4,errortemp5,errortemp6,errortemp7,errortemp8,errortemp9])*1e3
a, y0, b, x0 = param

voltages_dcA = Voltages[0][1:10]
ax_dib.plot( x_hip , x_hip*0+y0 , color='gray)
ax_dib.set_ylim(0,y0*1.1')

plt.figure()
plt.errorbar(voltages_dcA,tempvector,yerr=errortempvector,fmt='o',capsize=5,markersize=5,color=paleta[3])
plt.axvline(minimum_voltage,linestyle='dashed',color='grey')
plt.xlabel('Endcap voltage (V)')
plt.ylabel('Temperature (mK)')
plt.grid()
plt.ylim(0,2)

# Leyenda ##############################
h1, l1 = ax_central.get_legend_handles_labels()
h2, l2 = axx[0,0].get_legend_handles_labels()
ax_central.legend(h1+h2, l1+l2, loc='upper left')

#%%
"""
Por las dudas, temperatura en funcion de beta
"""
plt.figure()
plt.errorbar(betavector,tempvector,yerr=errortempvector,xerr=errorbetavector,fmt='o',capsize=5,markersize=5)
plt.xlabel('Modulation factor')
plt.ylabel('Temperature (mK)')
plt.grid()


fig.align_ylabels([ax_central,ax_res])
fig.tight_layout()

#%%
"""
Si quiero ver algun parametro del ajuste puntual. el orden es: 0:SG, 1:SP, 2:SCALE1, 3:OFFSET
"""
ki=2
plt.errorbar(np.arange(0,9,1),[popt_1[ki],popt_2[ki],popt_3[ki],popt_4[ki],popt_5[ki],popt_6[ki],popt_7[ki],popt_8[ki],popt_9[ki]],yerr=[np.sqrt(pcov_1[ki,ki]),np.sqrt(pcov_2[ki,ki]),np.sqrt(pcov_3[ki,ki]),np.sqrt(pcov_4[ki,ki]),np.sqrt(pcov_5[ki,ki]),np.sqrt(pcov_6[ki,ki]),np.sqrt(pcov_7[ki,ki]),np.sqrt(pcov_8[ki,ki]),np.sqrt(pcov_9[ki,ki])], fmt='o',capsize=3,markersize=3)

# fig.savefig('grafico_central_opcion_B.png', dpi=300)
# fig.savefig('grafico_central_opcion_B.pdf')

#%%

if False:
    GUARDAR = {}
    # for var in [ kk for kk in globals().keys() if kk.startswith('pop') ]:
    #     print(var)
    #     GUARDAR[var] = globals()[var]
    # print('')
    # for var in [ kk for kk in globals().keys() if kk.startswith('pcov') ]:
    #     print(var)
    #     GUARDAR[var] = globals()[var]

    # print('')
    # for var in [ kk for kk in globals().keys() if kk.startswith('Fitted') ]:
    #     print(var)
    #     GUARDAR[var] = globals()[var]
    # print('')
    for var in [ kk for kk in globals().keys() if kk.endswith('_vec') ]:
        print(var)
        GUARDAR[var] = globals()[var]

    np.savez('analisis_superajuste_PARAMETROS.npz', **GUARDAR )