Esempio n. 1
0
def plotSpectrum(paths):
    if type(paths) == str:
        paths = [paths]
    fig = plt.figure()
    fig.patch.set_alpha(0)
    ax1 = SubplotHost(fig, 111)
    fig.add_subplot(ax1)
    for p in paths:
        data = np.loadtxt(p, skiprows=9)
        ax1.plot(eV_To_nm / data[:, 0], data[:, 1])

    ax1.set_ylabel('Intensity (arb. units)')
    ax2 = ax1.twin()
    ax1.set_xlabel('Energy (eV)')
    # ax2 is responsible for "top" axis and "right" axis
    #    ticks = ax1.get_xticks()
    tticks = np.round(eV_To_nm / ax1.get_xticks(), 2)
    tticks = np.array(tticks, np.int)
    ax2.set_xticks([eV_To_nm / t for t in tticks])
    ax2.set_xticklabels(tticks)
    #ax2.axis["top"].label.set_visible(True)
    ax1.ticklabel_format(axis='y', style='sci', scilimits=(0, 0))
    ax2.set_xlabel('Wavelength (nm)')
    ax2.set_yticks([])


#def main():
#    path = input("Enter the path of your file: ")
#    path=path.replace('"','')
#    path=path.replace("'",'')
##    path = r'C:/Users/sylvain.finot/Documents/data/2019-03-11 - T2597 - 5K/Fil3/TRCL-cw455nm/TRCL.dat'
#    plotSpectrum(path)
#
#if __name__ == '__main__':
#    main()
Esempio n. 2
0
def plotComponentStress(r, sigmaR, sigmaTheta, sigmaZ,
                        sigmaEq, filename, i, loc):
    a = r[0,0]; b = r[0,-1]
    trX = Q_(1, 'inch').to('mm').magnitude
    trY = Q_(1, 'ksi').to('MPa').magnitude
    trans = mtransforms.Affine2D().scale(trX,trY)
    fig = plt.figure(figsize=(4, 3.5))
    ax = SubplotHost(fig, 1, 1, 1)
    axa = ax.twin(trans)
    axa.set_viewlim_mode("transform")
    axa.axis["top"].set_label(r'\textsc{radius}, $r$ (in.)')
    axa.axis["top"].label.set_visible(True)
    axa.axis["right"].set_label(r'\textsc{stress component}, $\sigma$ (ksi)')
    axa.axis["right"].label.set_visible(True)
    ax = fig.add_subplot(ax)
    ax.plot(r[i,:]*1e3, sigmaR[i,:]*1e-6, '^-',
            label='$\sigma_r$')
    ax.plot(r[i,:]*1e3, sigmaTheta[i,:]*1e-6, 'o-',
            label=r'$\sigma_\theta$')
    ax.plot(r[i,:]*1e3, sigmaZ[i,:]*1e-6, 'v-',
            label='$\sigma_z$')
    ax.plot(r[i,:]*1e3, sigmaEq[i,:]*1e-6, 's-',
            label='$\sigma_\mathrm{eq}$')
    ax.set_xlabel(r'\textsc{radius}, $r$ (mm)')
    ax.set_xlim((a*1e3)-0.1,(b*1e3)+0.1)
    ax.set_ylabel(r'\textsc{stress component}, $\sigma$ (MPa)')
    ax.legend(loc=loc)
    #labels = ax.get_xticklabels()
    #plt.setp(labels, rotation=30)
    fig.tight_layout()
    fig.savefig(filename, transparent=True)
    plt.close(fig)
Esempio n. 3
0
def diffusion1D(length_microns, log10D_m2s, time_seconds, init=1., fin=0.,
                erf_or_sum='erf', show_plot=True, 
                style=styles.style_blue, infinity=100, points=100, 
                centered=True, axes=None, symmetric=True,
                maximum_value=1.):
    """
    Simplest implementation for 1D diffusion.
    
    Takes required inputs length, diffusivity, and time 
    and plots diffusion curve on new or specified figure. 
    Optional inputs are unit initial value and final values. 
    Defaults assume diffusion out, so init=1. and fin=0. 
    Reverse these for diffusion in.
    
    Change scale of y-values with maximum_value keyword.
    
    Returns figure, axis, x vector in microns, and model y data.
    """    
    if symmetric is True:
        params = params_setup1D(length_microns, log10D_m2s, time_seconds,
                                init=init, fin=fin)
        x_diffusion, y_diffusion = diffusion1D_params(params, points=points)
        if centered is False:
            a_length = (max(x_diffusion) - min(x_diffusion)) / 2
            x_diffusion = x_diffusion + a_length
    else:
        # multiply length by two
        params = params_setup1D(length_microns*2, log10D_m2s, time_seconds,
                                init=init, fin=fin)
        x_diffusion, y_diffusion = diffusion1D_params(params, points=points)        

        # divide elongated profile in half
        x_diffusion = x_diffusion[int(points/2):]
        y_diffusion = y_diffusion[int(points/2):]
        if centered is True:
            a_length = (max(x_diffusion) - min(x_diffusion)) / 2
            x_diffusion = x_diffusion - a_length 

    if show_plot is True:
        if axes is None:
            fig = plt.figure()          
            ax  = SubplotHost(fig, 1,1,1)
            ax.grid()
            ax.set_ylim(0, maximum_value)
            ax.set_xlabel('position ($\mu$m)')
            ax.set_xlim(min(x_diffusion), max(x_diffusion))
            ax.plot(x_diffusion, y_diffusion*maximum_value, **style)
            ax.set_ylabel('Unit concentration or final/initial')
            fig.add_subplot(ax)
        else:
            axes.plot(x_diffusion, y_diffusion*maximum_value, **style)
            fig = None
            ax = None            
    else:
        fig = None
        ax = None
    
    return fig, ax, x_diffusion, y_diffusion
Esempio n. 4
0
def plotNACA(r, sigma, fea, i, filename, loc, ylabel):
    a = r[0,0]; b = r[0,-1]
    trX = Q_(1, 'inch').to('mm').magnitude
    trY = Q_(1, 'ksi').to('MPa').magnitude
    trans = mtransforms.Affine2D().scale(trX,trY)
    fig = plt.figure(figsize=(4, 3.5))
    ax = SubplotHost(fig, 1, 1, 1)
    axa = ax.twin(trans)
    axa.set_viewlim_mode("transform")
    axa.axis["top"].set_label(r'\textsc{radius}, $r$ (in.)')
    axa.axis["top"].label.set_visible(True)
    axa.axis["right"].set_label(ylabel+' (ksi)')
    axa.axis["right"].label.set_visible(True)
    ax = fig.add_subplot(ax)
    ax.plot(r[0,:]*1e3, sigma[0,:]*1e-6, '-',
            color='C0',label=r'$\theta=0^\circ$')
    ax.plot((a+fea[0][:,0])*1e3, fea[0][:,i]*1e-6, 'o',
            color='C0', markevery=1)
    ax.plot(r[0,:]*1e3, sigma[20,:]*1e-6, '-',
            color='C1', label=r'$\theta=60^\circ$')
    ax.plot((a+fea[1][:,0])*1e3, fea[1][:,i]*1e-6, '^',
            color='C1', markevery=1)
    ax.plot(r[0,:]*1e3, sigma[40,:]*1e-6, '-',
            color='C2', label=r'$\theta=120^\circ$')
    ax.plot((a+fea[2][:,0])*1e3, fea[2][:,i]*1e-6, 'v',
            color='C2', markevery=1)
    ax.plot(r[0,:]*1e3, sigma[60,:]*1e-6, '-',
            color='C3', label=r'$\theta=180^\circ$')
    ax.plot((a+fea[3][:,0])*1e3, fea[3][:,i]*1e-6, 's',
            color='C3', markevery=1)
    ax.set_xlabel(r'\textsc{radius}, $r$ (mm)')
    ax.set_xlim((a*1e3)-10,(b*1e3)+10)
    ax.set_ylabel(ylabel+' (MPa)')
    #ax.set_ylim(-400, 400)
    c0line = Line2D([], [], color='C0', marker='o',
                   label=r'$\theta=0^\circ$')
    c1line = Line2D([], [], color='C1', marker='^',
                   label=r'$\theta=60^\circ$')
    c2line = Line2D([], [], color='C2', marker='v',
                   label=r'$\theta=120^\circ$')
    c3line = Line2D([], [], color='C3', marker='s',
                   label=r'$\theta=180^\circ$')
    handles=[c0line, c1line, c2line, c3line]
    labels = [h.get_label() for h in handles]
    ax.legend([handle for i,handle in enumerate(handles)],
              [label for i,label in enumerate(labels)], loc=loc)
    fig.tight_layout()
    fig.savefig(filename, transparent=True)
    plt.close(fig)
Esempio n. 5
0
def plot_diffusion1D(x_microns,
                     model,
                     initial_value=None,
                     fighandle=None,
                     axishandle=None,
                     top=1.2,
                     style=None,
                     fitting=False,
                     show_km_scale=False,
                     show_initial=True):
    """Takes x and y diffusion data and plots 1D diffusion profile input"""
    a_microns = (max(x_microns) - min(x_microns)) / 2.
    a_meters = a_microns / 1e3

    if fighandle is None and axishandle is not None:
        print 'Remember to pass in handles for both figure and axis'
    if fighandle is None or axishandle is None:
        fig = plt.figure()
        ax = SubplotHost(fig, 1, 1, 1)
        ax.grid()
        ax.set_ylim(0, top)
    else:
        fig = fighandle
        ax = axishandle

    if style is None:
        if fitting is True:
            style = {'linestyle': 'none', 'marker': 'o'}
        else:
            style = styles.style_lightgreen

    if show_km_scale is True:
        ax.set_xlabel('Distance (km)')
        ax.set_xlim(0., 2. * a_meters / 1e3)
        x_km = x_microns / 1e6
        ax.plot((x_km) + a_meters / 1e3, model, **style)
    else:
        ax.set_xlabel('position ($\mu$m)')
        ax.set_xlim(-a_microns, a_microns)
        ax.plot(x_microns, model, **style)

    if initial_value is not None and show_initial is True:
        ax.plot(ax.get_xlim(), [initial_value, initial_value], '--k')

    ax.set_ylabel('Unit concentration or final/initial')
    fig.add_subplot(ax)

    return fig, ax
def plotTIMO(r, s, feaCmp, feaEq, filename):
    a = r[0,0]; b = r[0,-1]
    trX = Q_(1, 'inch').to('mm').magnitude
    trY = Q_(1, 'ksi').to('MPa').magnitude
    trans = mtransforms.Affine2D().scale(trX,trY)
    fig = plt.figure(figsize=(4, 3.5))
    ax = SubplotHost(fig, 1, 1, 1)
    axa = ax.twin(trans)
    axa.set_viewlim_mode("transform")
    axa.axis["top"].set_label(r'\textsc{radius}, $r$ (in.)')
    axa.axis["top"].label.set_visible(True)
    axa.axis["right"].set_label(r'\textsc{stress component}, $\sigma$ (ksi)')
    axa.axis["right"].label.set_visible(True)
    ax = fig.add_subplot(ax)
    ax.plot(r[0,:]*1e3, s.sigmaTheta[0,:]*1e-6, '-', color='C0')
    ax.plot((a+feaCmp[:,0])*1e3, feaCmp[:,4]*1e-6, 'o', color='C0')
    ax.plot(r[0,:]*1e3, s.sigmaR[0,:]*1e-6, '-', color='C1')
    ax.plot((a+feaCmp[:,0])*1e3, feaCmp[:,5]*1e-6, '^', color='C1')
    ax.plot(r[0,:]*1e3, s.sigmaZ[0,:]*1e-6, '-', color='C2')
    ax.plot((a+feaCmp[:,0])*1e3, feaCmp[:,6]*1e-6, 'v', color='C2')
    ax.plot(r[0,:]*1e3, s.sigmaEq[0,:]*1e-6, '-', color='C3')
    ax.plot((a+feaEq[:,0])*1e3, feaEq[:,1]*1e-6, 's', color='C3')
    ax.plot(r[0,:]*1e3, s.sigmaRTheta[0,:]*1e-6, '-', color='C4')
    ax.plot((a+feaCmp[:,0])*1e3, feaCmp[:,7]*1e-6, '+', color='C4')
    ax.set_xlabel(r'\textsc{radius}, $r$ (mm)')
    ax.set_xlim((a*1e3)-10,(b*1e3)+10)
    ax.set_ylabel(r'\textsc{stress component}, $\sigma$ (MPa)')
    #ax.set_ylim(-400, 400)
    c0line = Line2D([], [], color='C0', marker='o',
                    label=r'$\sigma_\theta$')
    c1line = Line2D([], [], color='C1', marker='^',
                    label=r'$\sigma_r$')
    c2line = Line2D([], [], color='C2', marker='v',
                    label=r'$\sigma_z$')
    c3line = Line2D([], [], color='C3', marker='s',
                    label=r'$\sigma_\mathrm{eq}$')
    c4line = Line2D([], [], color='C4', marker='+',
                    label=r'$\tau_{r\theta}$')
    handles=[c0line, c1line, c2line, c4line, c3line]
    labels = [h.get_label() for h in handles]
    ax.legend([handle for i,handle in enumerate(handles)],
              [label for i,label in enumerate(labels)], loc='best')
    fig.tight_layout()
    fig.savefig(filename, transparent=True)
    plt.close(fig)
Esempio n. 7
0
def plot_area_profile_outline(centered=True, peakwn=None,
                              set_size=(6.5, 4), ytop=1.2, 
                              wholeblock=False, heights_instead=False,
                              show_water_ppm=True):
    """
    Set up area profile outline and style defaults. 
    Default is for 0 to be the middle of the profile (centered=True).
    """
    fig = plt.figure(figsize=set_size)
    ax = SubplotHost(fig, 1,1,1)
    fig.add_subplot(ax)

    ax_ppm = ax.twinx()
    ax_ppm.axis["top"].major_ticklabels.set_visible(False)
    
    if show_water_ppm is True:
        pass
    else:
        ax_ppm.axis["right"].major_ticklabels.set_visible(False)    
    
    ax.set_xlabel('Position ($\mu$m)')
    
    # Set y-label
    if wholeblock is True:
        if heights_instead is False:
            ax.set_ylabel('Area/Area$_0$')
        else:
            ax.set_ylabel('Height/Height$_0$')            
    else:
        if heights_instead is False:
            ax.set_ylabel('Area (cm$^{-2}$)')
        else:
            ax.set_ylabel('Height (cm$^{-1}$)')

    ax.set_ylim(0, ytop)

    ax.grid()
    return fig, ax, ax_ppm
Esempio n. 8
0
gs = gridspec.GridSpec(1, 1)
#ax = plt.subplot(gs[0, 0])
ax = SubplotHost(fig, 1, 1, 1)
fig.add_subplot(ax)
ax.set_ylim(-17, -10)

ax_Fe = ax.twin()
Fe_labels = list(np.arange(0.0, 0.1, 0.02)) + list(np.arange(0.1, 0.9, 0.1))
parasite_tick_locations = np.log10(Fe_labels)
ax_Fe.set_xticks(parasite_tick_locations)
ax_Fe.set_xticklabels(Fe_labels)
ax_Fe.axis["top"].set_label("Fe (a.p.f.u.)")
ax_Fe.axis["top"].label.set_visible(True)
ax_Fe.axis["right"].major_ticklabels.set_visible(False)

ax.set_ylabel('log$_{10}$ diffusivity$_{H}$ $(m^2/s)$ at 800 $\degree$C')
ax.set_xlabel('log$_{10}$ Fe (a.p.f.u.)')

label = ['name'] * 10

#for idx in range(len(Names)):
for idx in [0, 1, 2, 3, 4, 6, 7]:
    ax.plot(
        x[idx],
        bulk[idx],  #label=Names[idx], 
        clip_on=False,
        **style[idx])

    # individual labels
    xyloc = (x[idx], bulk[idx])
    if np.isnan(FeOwt[idx]):
gs = gridspec.GridSpec(1,1)
ax = SubplotHost(fig, 1,1,1)
fig.add_subplot(ax)
ax.set_ylim(-12.5, -10.5)
ax_Al = ax.twin()

#Al_labels = list(np.arange(0.0, 0.1, 0.02)) + list(np.arange(0.1, 0.9, 0.1))
Al_labels = [0.01, 0.02, 0.05, 0.1, 0.2]
parasite_tick_locations = np.log10(Al_labels)
ax_Al.set_xticks(parasite_tick_locations)
ax_Al.set_xticklabels(Al_labels)

ax_Al.axis["top"].set_label("IV-Al (a.p.f.u.)")
ax_Al.axis["top"].label.set_visible(True)
ax_Al.axis["right"].major_ticklabels.set_visible(False)
ax.set_ylabel('log$_{10}$ diffusivity$_{H}$ $(m^{-2}/s)$ at 800 $\degree$C')
ax.set_xlabel('log$_{10}$ IV-Al (a.p.f.u.)')
#ax.set_xlim(-2.0, -0.4) 
ax.set_xlim(-1.7, -0.5) 

Names = ['Jaipur diopside\n(|| a, c*)',
         unicode('N\374shan cpx', 'latin-1'),
         'augite PMR-53',
         'Fuego\nphenocryst',
         'Jaipur diopside\n(|| b)',
         ]

# original convention from normalization spreadsheet from SERC website
# http://serc.carleton.edu/research_education/equilibria/mineralformulaerecalculation.html
Al = np.array([
               0.016, # Jaipur
def plot_em(ifile, lf_file, cmd_file, age, z, track):
    print 'Plotting', ifile

    logL, logTe, mbol, j, k, mcore, co, dmdt = np.loadtxt(ifile,
                                             usecols=(4, 5, 10, 11, 13, 14, 15, 18),
                                             unpack=True)

    nAGB = (mcore == 0)
    cAGB = ((co >= 1) & (dmdt <= -5))
    oAGB = ((co <= 1) & (logL >= 3.3) & (dmdt < -5))

    jk = j - k
    bins = np.arange(-10, 20, 0.1)

    ###### HRD
    fig = plt.figure()
    ax = fig.add_axes([.1, .1, .8, .8])
    ax.plot(logTe[nAGB], logL[nAGB], '.k')
    ax.plot(logTe[cAGB], logL[cAGB], 'o', mfc='None', ms=5, mew=1, mec=colorC,
            alpha=0.3)
    ax.plot(logTe[oAGB], logL[oAGB], 'o', mfc='None', ms=5, mew=1, mec=colorO,
            alpha=0.3)

    ax.annotate('Age=%.2e' % age, (.7, .1), va='center',
                xycoords='axes fraction')
    ax.annotate('Z=%.2e' % z, (.7, .15), va='center',
                xycoords='axes fraction')
    ax.annotate('[M/H]=%.2f' % ztomh(z), (.7, .2), va='center',
                xycoords='axes fraction')

    ax.annotate(r'$%s$' % track.replace('_', '\ '), (.1, .9), va='center',
                xycoords='axes fraction')

    ax.set_xlim(ax.get_xlim()[::-1])
    #ax.set_ylim(-3.1, -9.5)
    ax.set_xlabel(r'$\log\ T_{\\eff}$')
    ax.set_ylabel(r'$\log L$')
    plt.savefig(cmd_file.replace('cmd', 'hrd'))


    ###### CMD
    fig = plt.figure()
    ax = fig.add_axes([.1, .1, .8, .8])
    ax.plot(jk[nAGB], k[nAGB], '.k')
    ax.plot(jk[cAGB], k[cAGB], 'o', mfc='None', ms=5, mew=1, mec=colorC,
            alpha=0.3)
    ax.plot(jk[oAGB], k[oAGB], 'o', mfc='None', ms=5, mew=1, mec=colorO,
            alpha=0.3)

    ax.annotate('Age=%.2e' % age, (.7, .1), va='center',
                xycoords='axes fraction')
    ax.annotate('Z=%.2e' % z, (.7, .15), va='center',
                xycoords='axes fraction')
    ax.annotate('[M/H]=%.2f' % ztomh(z), (.7, .2), va='center',
                xycoords='axes fraction')

    ax.annotate(r'$%s$' % track.replace('_', '\ '), (.1, .9), va='center',
                xycoords='axes fraction')

    ax.set_xlim(.1, 2.4)
    ax.set_ylim(-3.1, -9.5)
    ax.set_xlabel(r'$J-K$')
    ax.set_ylabel(r'$K$')
    plt.savefig(cmd_file)
    plt.close()
    ###### LF
    fig = plt.figure()

    ax1 = SubplotHost(fig, 2, 1, 1)
    ax2 = SubplotHost(fig, 2, 1, 2)
    fig.add_subplot(ax1)
    fig.add_subplot(ax2)
    aux_trans = mtransforms.Affine2D().scale(-2.5, 1.).translate(4.77, 0)

    ax_logl = ax1.twin(aux_trans)
    ax_logl.set_viewlim_mode('transform')

    if sum(cAGB):
        pdf, bins, patches = ax1.hist(mbol[cAGB], bins, histtype='stepfilled',
                                      color=colorC)
        ax1.set_ylim(0.01, pdf.max()*1.1)

    if sum(oAGB):
        pdf, bins, patches = ax2.hist(mbol[oAGB], bins, histtype='stepfilled',
                                      color=colorO)
        ax2.set_ylim(0.01, pdf.max() * 1.1)

    ax1.annotate('Age=%.2e' % age, (.7, .1), va='center',
                 xycoords='axes fraction')
    ax1.annotate('Z=%.2e' % z, (.7, .2), va='center',
                 xycoords='axes fraction')
    ax1.annotate('[M/H]=%.2f' % ztomh(z), (.7, .3), va='center',
                 xycoords='axes fraction')

    ax1.annotate('C-rich', (.7, .8), va='center',
                 xycoords='axes fraction')
    ax2.annotate('O-rich', (.7, .8), va='center',
                 xycoords='axes fraction')

    ax2.annotate(r'$%s$' % track.replace('_', '\ '), (.1, .8), va='center',
                 xycoords='axes fraction')

    for ax in [ax1, ax2]:
        ax.set_xlim(0.2, -7.2)
        ax.axis['left'].set_label('N')

    #ax1.set_xlabel('Log L/L_sun')
    ax1.set_ylabel(r'$N$')
    ax2.set_ylabel(r'$N$')

    ax_logl.axis['right'].major_ticklabels.set_visible(False)
    ax1.axis['bottom'].major_ticklabels.set_visible(False)
    ax2.axis['bottom'].set_label('M$_\mathsf{bol}$')

    ax_logl.annotate(r'$\log L/L_\mathsf{sun}$', (.5, 1.1),
                     xycoords='axes fraction')
    #ax_logl.axis['top'].set_label('log L/L$_{\odot}$')
    fig.subplots_adjust(left=.1, bottom=None, right=0.98, top=None,
                        wspace=0, hspace=0)
    plt.savefig(lf_file)
    plt.close()
for j in range (shape_z):
    mu[j] = cosmo.dist_modulus(z[j],Omega_m,(1.-Omega_m),h) + error[j]

#generating the fitting function
for j in range (shape_z_ana):
    mu_ana[j] = cosmo.dist_modulus(z_ana[j],Omega_m,(1.-Omega_m),h)
    
#---------------------
#Plotting the analytical models and the data
#-------------------
fig = pl.figure()

host = SubplotHost(fig, 1,1,1)

host.set_xlabel('$z$',fontsize=21)
host.set_ylabel('$\mu$',fontsize=21)

fig.add_subplot(host)

p1 = host.plot(z_ana,mu_ana,'r-',lw=1.5,label="$\Omega_m = 0.3$")

p2 = host.errorbar(z,mu,yerr=0.1,fmt='o',color='k',lw=1.5,label="SN data")

leg = pl.legend(loc=4,fontsize=18)
#host.set_ylim(0,48)

#pl.xticks(visible=False)
#pl.yticks(visible=False)
#host.yaxis.get_label().set_color(p1.get_color())
#leg.texts[0].set_color(p1.get_color())
#host.yaxis.get_label().set_color(p2.get_color())
Esempio n. 12
0
ax_wn.tick_params(axis='x', direction = 'in', labelsize=11)
ax_wn.tick_params(axis='y', left=False, labelleft=False)
ax_wn.xaxis.set_label_position('top')
ax_mn.xaxis.tick_bottom()
ax_mn.xaxis.set_label_position('bottom')

print('load data')
datat=np.loadtxt('dpt_files/Chrysene/p1_08_chry_v2.dpt', delimiter = ',')
data2=nrmlze(datat, 0)

ax_wn.plot(datat[:,0], data2 + offset, 'k-', lw=0.5, linestyle='-')

offset=offset+1.15

ax_wn.set_ylim([-.5, offset+0.5])
ax_wn.set_ylabel('intensity, a.u.', fontsize=11)
ax_mn.set_xlabel('wavelength, $\mu$m', fontsize=11)
ax_wn.set_xlabel('wavenumber, cm$^{-1}$', fontsize=11)

#fig.suptitle('wavenumber, cm$^{-1}$', fontsize=11)

#plt.subplots_adjust(top=0.88,
#bottom=0.11,
#left=0.035,
#right=0.965,
#hspace=0.2,
#wspace=0.12)

plt.draw()
plt.show()
Esempio n. 13
0
    def plot(self,
             r1=None,
             r2=None,
             nav_im=None,
             norm='log',
             scroll_step=1,
             alpha=0.3,
             cmap=None,
             pct=0.1,
             mradpp=None,
             widget=None):
        '''
        Interactive plotting of the virtual aperture images.

        The sliders control the parameters and may be clicked, dragged or scrolled.
        Clicking on inner (r1) and outer (r2) slider labels sets the radii values
        to the minimum and maximum, respectively.

        Parameters
        ----------
        r1 : scalar
            Inner radius of aperture in pixels.
        r2 : scalar
            Inner radius of aperture in pixels.
        nav_im : None or ndarray
            Image used for the navigation plot. If None, a blank image is used.
        norm : None or string:
            If not None and norm='log', a logarithmic cmap normalisation is used.
        scroll_step : int
            Step in pixels used for each scroll event.
        alpha : float
            Alpha for aperture plot in [0, 1].
        cmap : None or a matplotlib colormap
            If not None, the colormap used for both plots.
        pct : scalar
            Slice image percentile in [0, 50).
        mradpp : None or scalar
            mrad per pixel.
        widget : Pop_Up_Widget
            A custom class consisting of mutliple widgets

        '''

        from matplotlib.widgets import Slider

        self._scroll_step = max([1, int(scroll_step)])
        self._pct = pct

        if norm is not None:
            if norm.lower() == 'log':
                from matplotlib.colors import LogNorm
                norm = LogNorm()

        # condition rs
        if r1 is not None:
            self.r1 = r1
        else:
            if self.r1 is None:
                self.r1 = 0
        if r2 is not None:
            self.r2 = r2
        else:
            if self.r2 is None:
                self.r2 = int((self.data_shape[-2:] / 4).mean())
        self.rc = (self.r2 + self.r1) / 2.0

        if nav_im is None:
            nav_im = np.zeros(self.data_shape[-2:])

        # calculate data
        virtual_image = self.annular_slice(self.r1, self.r2)
        print("MRADPP", mradpp)
        # prepare plots
        if mradpp is None:
            if widget is not None:
                print("True")
                docked = widget.setup_docking("Virtual Annular",
                                              "Bottom",
                                              figsize=(8.4, 4.8))
                fig = docked.get_fig()
                fig.clf()
                (ax_nav, ax_cntrst) = fig.subplots(1, 2)
                self._f_nav = fig
            else:
                self._f_nav, (ax_nav, ax_cntrst) = plt.subplots(1,
                                                                2,
                                                                figsize=(8.4,
                                                                         4.8))

        else:
            # add 2nd x-axis
            # https://matplotlib.org/examples/axes_grid/parasite_simple2.html
            from mpl_toolkits.axes_grid1.parasite_axes import SubplotHost
            import matplotlib.transforms as mtransforms
            if widget is not None:
                print("False")
                docked = widget.setup_docking("Virtual Annular",
                                              "Bottom",
                                              figsize=(8.4, 4.8))
                self._f_nav = docked.get_fig()
                self._f_nav.clf()
            else:
                self._f_nav = plt.figure(figsize=(8.4, 4.8))
            ax_nav = SubplotHost(self._f_nav, 1, 2, 1)
            ax_cntrst = SubplotHost(self._f_nav, 1, 2, 2)

            aux_trans = mtransforms.Affine2D().scale(1.0 / mradpp, 1.0)
            ax_mrad = ax_cntrst.twin(aux_trans)
            ax_mrad.set_viewlim_mode("transform")

            self._f_nav.add_subplot(ax_nav)
            self._f_nav.add_subplot(ax_cntrst)

            ax_mrad.axis["top"].set_label('mrad')
            ax_mrad.axis["top"].label.set_visible(True)
            ax_mrad.axis["right"].major_ticklabels.set_visible(False)

        self._f_nav.subplots_adjust(bottom=0.3, wspace=0.3)
        if widget is not None:
            axr1 = fig.add_axes([0.10, 0.05, 0.80, 0.03])
            axr2 = fig.add_axes([0.10, 0.10, 0.80, 0.03])
            axr3 = fig.add_axes([0.10, 0.15, 0.80, 0.03])

        else:
            axr1 = plt.axes([0.10, 0.05, 0.80, 0.03])
            axr2 = plt.axes([0.10, 0.10, 0.80, 0.03])
            axr3 = plt.axes([0.10, 0.15, 0.80, 0.03])

        val_max = self.r_pix.max()
        try:
            self._sr1 = Slider(axr1,
                               'r1',
                               0,
                               val_max - 1,
                               valinit=self.r1,
                               valfmt='%0.0f',
                               valstep=1)
            self._sr2 = Slider(axr2,
                               'r2',
                               1,
                               val_max,
                               valinit=self.r2,
                               valfmt='%0.0f',
                               valstep=1)
        except AttributeError:
            self._sr1 = Slider(axr1,
                               'r1',
                               0,
                               val_max - 1,
                               valinit=self.r1,
                               valfmt='%0.0f')
            self._sr2 = Slider(axr2,
                               'r2',
                               1,
                               val_max,
                               valinit=self.r2,
                               valfmt='%0.0f')
        self._sr3 = Slider(axr3,
                           'rc',
                           1,
                           val_max,
                           valinit=self.rc,
                           valfmt='%0.1f')

        # these don't seem to work
        #self._sr1.slider_max = self._sr2
        #self._sr2.slider_min = self._sr1

        self._sr1.on_changed(self._update_r_from_slider)
        self._sr2.on_changed(self._update_r_from_slider)
        self._sr3.on_changed(self._update_rc_from_slider)

        ax_nav.imshow(nav_im, norm=norm, cmap=cmap)
        ax_nav.set_xlabel('Detector X (pixels)')
        ax_nav.set_ylabel('Detector Y (pixels)')

        # line plot
        r_cntrst_max = int(np.abs(self.data_shape[-2:] - self.cyx).max())
        dw = 1
        rs = np.arange(dw, r_cntrst_max)

        r1, r2 = self.r1, self.r2
        sls = np.array([self.annular_slice(r - dw, r) for r in rs])
        self.r1, self.r2 = r1, r2

        self._contrast_y = np.std(sls, (1, 2))**2 / np.mean(sls, (1, 2))
        self._contrast_x = rs - dw / 2.0
        ax_cntrst.plot(self._contrast_x, self._contrast_y)
        ax_cntrst.minorticks_on()
        ax_cntrst.set_xlabel('Radius (pixels)')
        ax_cntrst.set_ylabel('Contrast (std^2/mean)')
        self._span = ax_cntrst.axvspan(self.r1,
                                       self.r2,
                                       color=[1, 0, 0, 0.1],
                                       ec='r')

        # wedges
        fc = [0, 0, 0, alpha]
        ec = 'r'
        from matplotlib.patches import Wedge
        self._rmax = val_max + 1
        self._w2 = Wedge(self.cyx[::-1],
                         self._rmax,
                         0,
                         360,
                         width=self._rmax - self.r2,
                         fc=fc,
                         ec=ec)
        self._w1 = Wedge(self.cyx[::-1],
                         self.r1,
                         0,
                         360,
                         width=self.r1,
                         fc=fc,
                         ec=ec)
        ax_nav.add_artist(self._w2)
        ax_nav.add_artist(self._w1)

        if widget is not None:
            docked = widget.setup_docking("Virtual Annular",
                                          "Bottom",
                                          figsize=(8.4, 4.8))
            fig = docked.get_fig()
            fig.clf()
            ax_im = fig.subplots(1, 1)
            self._f_im = fig
        else:
            self._f_im, ax_im = plt.subplots(1, 1)
        vmin, vmax = np.percentile(virtual_image, [self._pct, 100 - self._pct])
        self._vim = ax_im.imshow(virtual_image,
                                 cmap=cmap,
                                 vmin=vmin,
                                 vmax=vmax)
        if widget is not None:
            self._cb = fig.colorbar(self._vim)
        else:
            self._cb = plt.colorbar(self._vim)
        self._cb.set_label('Counts')
        ax_im.set_xlabel('Scan X (pixels)')
        ax_im.set_ylabel('Scan Y (pixels)')

        cid = self._f_nav.canvas.mpl_connect('scroll_event', self._onscroll)

        self._sr1.label.set_picker(True)
        self._sr2.label.set_picker(True)
        cid_pick = self._f_nav.canvas.mpl_connect('pick_event', self._onpick)
Esempio n. 14
0
    figs = [fig1]
    figs_N = 2
    fig1_y = 1
    fig2_y = 2
    plt.subplots_adjust(hspace=0.0)
axprops = dict()

if plot_V:
    ax_V_Eh = SubplotHost(fig1, figs_N, 1, fig1_y, **axprops)
    ax_V_Eh_to_Volt = mtransforms.Affine2D().scale(1.0, cst.eV_to_Eh)
    ax_V_Volt = ax_V_Eh.twin(ax_V_Eh_to_Volt)
    ax_V_Volt.set_viewlim_mode("transform")
    ax_V_Eh.grid(True)

    ax_V_Volt.set_ylabel("Potential (Volt)")
    ax_V_Eh.set_ylabel("Potential energy of a 1+ (Hartree)")

    axprops["sharex"] = ax_V_Volt

    plt.setp(ax_V_Volt.get_xticklabels(), visible=False)

    # ax_V_Eh.set_title(r"Potential")

if plot_U:
    ax_U_Eh = SubplotHost(fig2, figs_N, 1, fig2_y, **axprops)
    ax_U_Eh_to_eV = mtransforms.Affine2D().scale(1.0, cst.eV_to_Eh)
    ax_U_eV = ax_U_Eh.twin(ax_U_Eh_to_eV)
    ax_U_eV.set_viewlim_mode("transform")
    ax_U_Eh.grid(True)

    ax_U_Eh.set_xlabel("Position (Bohr)")