Ejemplo 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()
Ejemplo 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)
Ejemplo n.º 3
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)
Ejemplo n.º 4
0
def Arrhenius_outline(xlow=6., xhigh=11., ybottom=-18., ytop=-8.,
                      celsius_labels = np.arange(0, 2000, 100),
                      shrink_axes_to_fit_legend_by = 0.3, make_legend=False,
                      lower_legend_by=-2., ncol=2):
    """
    Make Arrhenius diagram outline. 
    
    Returns figure, axis, legend handle.
    
    low, high, top, and bottom set the x and y axis limits. 

    celsius_labels sets where to make the temperature tick marks.
    
    If you have issues with the legend position or overlap with main diagram,
    play with the numbers for shrink_legend_by and lower_legend_by
    
    ncol sets the number of columns in the legend.
    """
    fig = plt.figure()
    ax = SubplotHost(fig, 1,1,1)
    ax_celsius = ax.twin()
    parasite_tick_locations = 1e4/(celsius_labels + 273.15)
    ax_celsius.set_xticks(parasite_tick_locations)
    ax_celsius.set_xticklabels(celsius_labels)
    fig.add_subplot(ax)
    ax.axis["bottom"].set_label("10$^4$/Temperature (K$^{-1}$)")
    ax.axis["left"].set_label("log$_{10}$diffusivity (m$^{2}$/s)")
    ax_celsius.axis["top"].set_label("Temperature ($\degree$C)")
    ax_celsius.axis["top"].label.set_visible(True)
    ax_celsius.axis["right"].major_ticklabels.set_visible(False)
    ax.set_xlim(xlow, xhigh)
    ax.set_ylim(ybottom, ytop)
    ax.grid()
    
    # main legend below
    if make_legend is True:
        legend_handles_main = []
        box = ax.get_position()
        ax.set_position([box.x0, box.y0 + box.height*shrink_axes_to_fit_legend_by, 
                         box.width, box.height*(1.0-shrink_axes_to_fit_legend_by)])
        main_legend = plt.legend(handles=legend_handles_main, numpoints=1, 
                                 ncol=ncol, 
                                 bbox_to_anchor=(xlow, ybottom, xhigh-xlow, 
                                                 lower_legend_by),
                                 bbox_transform=ax.transData, mode='expand')
        plt.gca().add_artist(main_legend)
    else:
        legend_handles_main = None
    return fig, ax, legend_handles_main
Ejemplo n.º 5
0
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)
Ejemplo n.º 6
0
def create_datetime_mjd_axes(fig=None, *args, **kwargs):
    '''
    Create a plot with two x-axis, bottom axis using
    dates, top axis using mjd.

    Parameters
    ----------
    fig: matplotlib.Figure or None
        the figure to use, if None use plt.gcf()

    Returns
    -------
    ax: mpl_toolkits.axes_grid1.parasite_axes.SubplotHost
        The ax for the dates
    mjd_ax: mpl_toolkits.axes_grid1.parasite_axes.ParasiteAxis
        The axis with the mjd axis

    '''
    if fig is None:
        fig = plt.gcf()

    if args == []:
        ax = SubplotHost(fig, 1, 1, 1, **kwargs)
    else:
        ax = SubplotHost(fig, *args, **kwargs)

    # The second axis shows MJD if the first axis uses dates
    mjd_ax = ax.twin(MJD_AXES_TRANSFORM)
    mjd_ax.set_viewlim_mode('transform')

    # disable unwanted axes
    mjd_ax.axis['right'].toggle(ticklabels=False, ticks=False)
    mjd_ax.axis['bottom'].toggle(ticklabels=False, ticks=False)
    mjd_ax.axis['bottom'].toggle(label=False)

    # add/remove label
    mjd_ax.axis['top'].set_label('MJD')

    # Deactivate offset
    mjd_ax.ticklabel_format(useOffset=False)

    fig.add_subplot(ax)

    return ax, mjd_ax
Ejemplo n.º 7
0
def Arrhenius_outline(low=6.,
                      high=11.,
                      bottom=-18.,
                      top=-8.,
                      celsius_labels=np.arange(0, 2000, 100),
                      figsize_inches=(6, 4),
                      shrinker_for_legend=0.3,
                      generic_legend=True,
                      sunk=-2.,
                      ncol=2):
    """Make Arrhenius diagram outline. Returns figure, axis, legend handle"""
    fig = plt.figure(figsize=figsize_inches)
    ax = SubplotHost(fig, 1, 1, 1)
    ax_celsius = ax.twin()
    parasite_tick_locations = 1e4 / (celsius_labels + 273.15)
    ax_celsius.set_xticks(parasite_tick_locations)
    ax_celsius.set_xticklabels(celsius_labels)
    fig.add_subplot(ax)
    ax.axis["bottom"].set_label("10$^4$/Temperature (K$^{-1}$)")
    ax.axis["left"].set_label("log$_{10}$diffusivity (m$^{2}$/s)")
    ax_celsius.axis["top"].set_label("Temperature ($\degree$C)")
    ax_celsius.axis["top"].label.set_visible(True)
    ax_celsius.axis["right"].major_ticklabels.set_visible(False)
    ax.set_xlim(low, high)
    ax.set_ylim(bottom, top)
    ax.grid()

    # main legend below
    legend_handles_main = []
    box = ax.get_position()
    ax.set_position([
        box.x0, box.y0 + box.height * shrinker_for_legend, box.width,
        box.height * (1.0 - shrinker_for_legend)
    ])
    main_legend = plt.legend(handles=legend_handles_main,
                             numpoints=1,
                             ncol=ncol,
                             bbox_to_anchor=(low, bottom, high - low, sunk),
                             bbox_transform=ax.transData,
                             mode='expand')
    plt.gca().add_artist(main_legend)
    return fig, ax, legend_handles_main
Ejemplo n.º 8
0
def get_axis_two_scales(fig, scale_x = 1.0, scale_y = 1.0, \
                        ax2_xlabel = None, ax2_ylabel = None, \
                        subplot = 111,
                        sharex = None,
                        sharey = None):
    kargs = {}
    if (sharex != None):
        kargs['sharex'] = sharex
    if (sharey != None):
        kargs['sharey'] = sharey
    ax1 = SubplotHost(fig, subplot, **kargs)
    ax1_to_2 = mtransforms.Affine2D().scale(1.0/scale_x, 1.0/scale_y)
    ax2 = ax1.twin(ax1_to_2)
    ax2.set_viewlim_mode("transform")
    fig.add_subplot(ax1)
    if (ax2_xlabel != None):
        ax2.set_xlabel(ax2_xlabel)
    if (ax2_ylabel != None):
        ax2.set_ylabel(ax2_ylabel)
    if (scale_x == 1.0):
        ax2.get_xaxis().set_visible(False)
    if (scale_y == 1.0):
        ax2.get_yaxis().set_visible(False)
    return ax1, ax2
Ejemplo n.º 9
0
E_t0            = saved_data['E_t0']
E_t1            = saved_data['E_t1']
E_delta         = saved_data['E_delta']
NumericalHeating= saved_data['NumericalHeating']

print "base_potentials =", base_potentials
print "potential_shapes =", potential_shapes
print "dts =", dts

fig1 = plot.figure()
fig2 = plot.figure()
figs = [fig1, fig2]

ax1_eV = SubplotHost(fig1, 1,1,1)
ax1_eV_to_Eh = mtransforms.Affine2D().scale(1.0, cst.Eh_to_eV)
ax1_Eh = ax1_eV.twin(ax1_eV_to_Eh)
ax1_Eh .set_viewlim_mode("transform")
fig1.add_subplot(ax1_eV)

ax2_eV = SubplotHost(fig2, 1,1,1)
ax2_eV_to_Eh = mtransforms.Affine2D().scale(cst.eV_to_Eh, cst.Eh_to_eV)
ax2_Eh = ax2_eV.twin(ax2_eV_to_Eh)
ax2_Eh .set_viewlim_mode("transform")
fig2.add_subplot(ax2_eV)


# Plot NumericalHeating as a function of dt for every potential depth
dbase_potentials = (base_potentials[-1] - base_potentials[0]) / float(max_plot-1) # -1 since we want the number of intervals
c = 0
for j in xrange(len(potential_shapes)):
    for base_potentials_close in np.arange(base_potentials[-1]+dbase_potentials/2.0, base_potentials[0], -dbase_potentials):
Ejemplo n.º 10
0
obs = [["01_S1", 3.88, 0.14, 1970, 63],
       ["01_S4", 5.6, 0.82, 1622, 150],
       ["02_S1", 2.4, 0.54, 1570, 40],
       ["03_S1", 4.1, 0.62, 2380, 170]]


fig = plt.figure()

ax_kms = SubplotHost(fig, 1,1,1, aspect=1.)

# angular proper motion("/yr) to linear velocity(km/s) at distance=2.3kpc
pm_to_kms = 1./206265.*2300*3.085e18/3.15e7/1.e5

aux_trans = mtransforms.Affine2D().scale(pm_to_kms, 1.)
ax_pm = ax_kms.twin(aux_trans)
ax_pm.set_viewlim_mode("transform")

fig.add_subplot(ax_kms)

for n, ds, dse, w, we in obs:
    time = ((2007+(10. + 4/30.)/12)-1988.5)
    v = ds / time * pm_to_kms
    ve = dse / time * pm_to_kms
    ax_kms.errorbar([v], [w], xerr=[ve], yerr=[we], color="k")


ax_kms.axis["bottom"].set_label("Linear velocity at 2.3 kpc [km/s]")
ax_kms.axis["left"].set_label("FWHM [km/s]")
ax_pm.axis["top"].set_label("Proper Motion [$^{''}$/yr]")
ax_pm.axis["top"].label.set_visible(True)
                 -11.02,
                 -11.1, 
                 Jaipur.whatIsD(Celsius, orient='y')
                 ])

x = np.log10(Al)

#%% Plotting

# setup plot, twin axes, labels
fig = plt.figure(figsize=(3, 4))
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) 
Ejemplo n.º 12
0
               s.sigmaZ.min(), s.sigmaZ.max(),
               'S31609_liquidSodium_sigmaZ.pdf')
    plotStressAnnotate(g.theta, g.r, s.sigmaEq,
                       s.sigmaEq.min(), s.sigmaEq.max(),
                       'right', 'S31609_liquidSodium_sigmaEq.pdf')

    headerprint(' Tube property parameter variation ')

    iterator='numpy'
    nr=12; nt=61

    trX = Q_(1, 'ksi').to('MPa').magnitude
    trans = mtransforms.Affine2D().scale(trX,1)
    fig1 = plt.figure(figsize=(5, 3))
    ax1 = SubplotHost(fig1, 1, 1, 1)
    ax1a = ax1.twin(trans)
    ax1a.set_viewlim_mode("transform")
    ax1a.axis["top"].set_label(r'\textsc{max. equiv. stress}, '+\
                               '$\max\sigma_\mathrm{Eq}$ (ksi)')
    ax1a.axis["top"].label.set_visible(True)
    ax1a.axis["right"].label.set_visible(False)
    ax1a.axis["right"].major_ticklabels.set_visible(False)
    ax1a.axis["right"].major_ticks.set_visible(False)
    ax1 = fig1.add_subplot(ax1)

    P_i = 0e5          # internal pipe pressure

    # salt
    h_int = 10e3

    align = ['left', 'center', 'right']
Ejemplo n.º 13
0
for n in range(1, 4, 1):
    ax_mn = SubplotHost(fig, 1, 3, n)

    fig.add_subplot(ax_mn)
    ax_mn.set_xlabel('Wavelength (micron)')
    #	x_micron=np.array([15,10,5,3])
    #	ax_mn.set_xticks(x_micron)
    #	ax_mn.set_xlim(5,15)
    ax_mn.set_ylim(0, 6)
    ax_mn.set_xscale('log')

    test_spectrum = np.genfromtxt('sample_spectrum.dpt', delimiter=',')
    xvals = 10000 / test_spectrum[:, 0]
    data = test_spectrum[:, 1]

    ax_wn = ax_mn.twin(aux_trans)
    ax_wn.set_viewlim_mode("transform")

    ax_wn.set_xlabel("Wavenumber, cm$^{-1}$")
    x_wn = np.array([1600, 1400, 1200, 1000, 800])
    ax_wn.set_xlim(1700, 700)
    ax_wn.set_xticks(x_wn)

    ax_wn.axis["right"].toggle(ticklabels=False)
    ax_wn.set_xscale('linear')

    ax_mn.semilogx(xvals, data)
#	ax_wn.invert_xaxis()

plt.draw()
plt.show()
Ejemplo n.º 14
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)
Ejemplo n.º 15
0
    fig1_y = 1
    fig2_y = 1
else:
    fig1 = plot.figure()
    fig2 = fig1
    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)
Ejemplo n.º 16
0
        plt.ylabel('Mutual information')
        plt.title('MI, ' + fnname + ' MI: %.5f' % MI)
        plt.savefig(os.path.join(outputdir, fnname + '_MItrace.png'))
        plt.close()
        emat0 = emat_mean
        emat = emat0 - emat0.min(axis=0)

        # now make the plot
        site_seq = plottingutils.getwtseq(infofn[namedict[fn]], barcodefn,
                                          datafnbase)

        fig = plt.figure()
        ax1 = SubplotHost(fig, 1, 1, 1)
        fig.add_subplot(ax1)

        ax2 = ax1.twin()
        ax1.imshow(emat, interpolation='nearest')

        ax1.set_xlabel('Position w.r.t. transcription start site')
        ax1.set_yticks([0, 1, 2, 3])
        ax1.set_yticklabels(['A', 'C', 'G', 'T'])

        # label positions with respect to transcription start site
        tick_start = int(start_dict[info_dict['exp_name']]) + int(
            info_dict['mut_region_start'])
        tick_end = int(start_dict[info_dict['exp_name']]) + int(
            info_dict['mut_region_start']) + int(
                info_dict['mut_region_length'])
        indices, xtick_labels = clean_up_xticklabels(tick_start,
                                                     tick_end - tick_start)
        ax1.set_xticks(indices)
Ejemplo n.º 17
0
def make_3DWB_water_profile(final_profile,
                            water_ppmH2O_initial=None,
                            initial_profile=None,
                            initial_area_list=None,
                            initial_area_positions_microns=None,
                            show_plot=True,
                            top=1.2,
                            fig_ax=None):
    """Take a profile and initial water content.
    Returns the whole-block water concentration profile based on
    the profile's attribute wb_areas. If wb_areas have not been made, 
    some initial profile information and various options are passed
    to make_3DWB_area_profile().
    Default makes a plot showing A/Ao and water on parasite y-axis
    """
    fin = final_profile
    init = initial_profile

    # Set initial water
    if water_ppmH2O_initial is not None:
        w0 = water_ppmH2O_initial
    else:
        if fin.sample is not None:
            if fin.sample.initial_water is not None:
                w0 = fin.sample.initial_water
        elif init is not None:
            if init.sample is not None:
                if init.sample.initial_water is not None:
                    w0 = init.sample.initial_water
        else:
            print 'Need initial water content.'
            return False

    # Set whole-block areas
    if (fin.wb_areas is not None) and (len(fin.wb_areas) > 0):
        wb_areas = fin.wb_areas
    else:
        wb_areas = make_3DWB_area_profile(fin, initial_profile,
                                          initial_area_list,
                                          initial_area_positions_microns)
    water = wb_areas * w0
    if show_plot is True:
        # Use a parasite y-axis to show water content
        fig = plt.figure()
        ax_areas = SubplotHost(fig, 1, 1, 1)
        fig.add_subplot(ax_areas)
        area_tick_marks = np.arange(0, 100, 0.2)
        ax_areas.set_yticks(area_tick_marks)
        ax_water = ax_areas.twin()
        ax_water.set_yticks(area_tick_marks)
        if isinstance(w0, uncertainties.Variable):
            ax_water.set_yticklabels(area_tick_marks * w0.n)
        else:
            ax_water.set_yticklabels(area_tick_marks * w0)
        ax_areas.axis["bottom"].set_label('Position ($\mu$m)')
        ax_areas.axis["left"].set_label('Final area / Initial area')
        ax_water.axis["right"].set_label('ppm H$_2$O')
        ax_water.axis["top"].major_ticklabels.set_visible(False)
        ax_water.axis["right"].major_ticklabels.set_visible(True)
        ax_areas.grid()
        ax_areas.set_ylim(0, 1.2)
        if fin.len_microns is not None:
            leng = fin.len_microns
        else:
            leng = fin.set_len()
        ax_areas.set_xlim(-leng / 2.0, leng / 2.0)

        style = fin.choose_marker_style()
        ax_areas.plot([-leng / 2.0, leng / 2.0], [1, 1], **style_1)
        ax_areas.plot(fin.positions_microns - leng / 2.0, wb_areas, **style)
        return water, fig, ax_areas
    else:
        return water
Ejemplo n.º 18
0
        plt.savefig(os.path.join(outputdir,fnname+'_MItrace.png'))
        plt.close()
        emat0 = emat_mean
        emat = emat0 - emat0.min(axis=0)
        

        # now make the plot
        site_seq = plottingutils.getwtseq(infofn[namedict[fn]],barcodefn,datafnbase)


        fig = plt.figure()
        ax1 = SubplotHost(fig, 1,1,1)
        fig.add_subplot(ax1)
        

        ax2 = ax1.twin()
        ax1.imshow(emat,interpolation='nearest')
        
        ax1.set_xlabel('Position w.r.t. transcription start site')
        ax1.set_yticks([0,1,2,3])
        ax1.set_yticklabels(['A','C','G','T'])


        # label positions with respect to transcription start site
        tick_start = int(start_dict[info_dict['exp_name']])+int(info_dict['mut_region_start'])
        tick_end = int(start_dict[info_dict['exp_name']])+int(info_dict['mut_region_start']) + int(info_dict['mut_region_length'])
        indices, xtick_labels = clean_up_xticklabels(tick_start,tick_end-tick_start)
        ax1.set_xticks(indices)
        ax1.set_xticklabels(xtick_labels)

        # put the sequence above it
Ejemplo n.º 19
0
obs = [["01_S1", 3.88, 0.14, 1970, 63],
       ["01_S4", 5.6, 0.82, 1622, 150],
       ["02_S1", 2.4, 0.54, 1570, 40],
       ["03_S1", 4.1, 0.62, 2380, 170]]


fig = plt.figure()

ax_kms = SubplotHost(fig, 1, 1, 1, aspect=1.)

# angular proper motion("/yr) to linear velocity(km/s) at distance=2.3kpc
pm_to_kms = 1./206265.*2300*3.085e18/3.15e7/1.e5

aux_trans = mtransforms.Affine2D().scale(pm_to_kms, 1.)
ax_pm = ax_kms.twin(aux_trans)
ax_pm.set_viewlim_mode("transform")

fig.add_subplot(ax_kms)

for n, ds, dse, w, we in obs:
    time = ((2007 + (10. + 4/30.)/12) - 1988.5)
    v = ds / time * pm_to_kms
    ve = dse / time * pm_to_kms
    ax_kms.errorbar([v], [w], xerr=[ve], yerr=[we], color="k")


ax_kms.axis["bottom"].set_label("Linear velocity at 2.3 kpc [km/s]")
ax_kms.axis["left"].set_label("FWHM [km/s]")
ax_pm.axis["top"].set_label(r"Proper Motion [$''$/yr]")
ax_pm.axis["top"].label.set_visible(True)
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()
Ejemplo n.º 21
0
#    ax.axis["bottom"].set_label("10$^4$/Temperature (K$^{-1}$)")
#    ax.axis["left"].set_label("log$_{10}$diffusivity (m$^{2}$/s)")
#    ax_celsius.axis["top"].set_label("Temperature ($\degree$C)")
#    ax_celsius.axis["top"].label.set_visible(True)
#    ax_celsius.axis["right"].major_ticklabels.set_visible(False)
#    ax.set_xlim(low, high)
#    ax.set_ylim(bottom, top)
x = np.log10(Fe)
fig = plt.figure(figsize=(6, 5))
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]:
Ejemplo n.º 22
0
#    ax.axis["bottom"].set_label("10$^4$/Temperature (K$^{-1}$)")
#    ax.axis["left"].set_label("log$_{10}$diffusivity (m$^{2}$/s)")
#    ax_celsius.axis["top"].set_label("Temperature ($\degree$C)")
#    ax_celsius.axis["top"].label.set_visible(True)
#    ax_celsius.axis["right"].major_ticklabels.set_visible(False)
#    ax.set_xlim(low, high)
#    ax.set_ylim(bottom, top)
x = np.log10(Fe)
fig = plt.figure(figsize=(6, 5))
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