Ejemplo n.º 1
0
    def __init__(self, *args, **kw):

        xax = kw.pop("xax", "f")
        self.xtrans = ReciprocalTransform()
        # self._aux_trans = btf(ReciprocalTransform(), IdentityTransform())

        SubplotHost.__init__(self, *args, **kw)
        self.parasite = self.twin()
Ejemplo n.º 2
0
    def __init__(self, *args, **kws):

        # self.xtrans =  kws.pop( 'xtrans', IdentityTransform() )
        # self.ytrans =  kws.pop( 'ytrans', IdentityTransform() )
        self.aux_trans = kws.pop("aux_trans", btf(IdentityTransform(), IdentityTransform()))
        # embed()
        SubplotHost.__init__(self, *args, **kws)  # self.__class__, self

        # Initialize the parasite axis
        self.parasite = self.twin(self.aux_trans)  # ax2 is responsible for "top" axis and "right" axis
Ejemplo n.º 3
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.º 4
0
def make_axes_grid_fig(num=None):
    """Create an mpl Figure and add to it an axes_grid.SubplotHost subplot
    (`hostax`).
    
    Returns
    -------
    fig, hostax
    """
    if num is not None:
        fig = plt.figure(num)
    else:
        fig = plt.figure()
    hostax = SubplotHost(fig, 111)
    fig.add_axes(hostax)
    return fig, hostax
Ejemplo n.º 5
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.º 6
0
def _plot(p1_infiles,p2_infiles2,bottom_label,left_label,tau_b=1000):
    fig = plt.figure(figsize=(12,9))
    ax_host = SubplotHost(fig, 1,1,1)
    fig.add_subplot(ax_host)
    for p1_file, p2_file in zip(p1_infiles,p2_infiles):
        p1, p2 = get_ave_ste(p1_file, p2_file, tau_b=1000)
        ax_host.errorbar(p1[0],p2[0], xerr=p1[1], yerr=p2[1],label=p1_file[:4])
        ax_host.text(p1[0]*1.02,p2[0]*1.02,p1_file[:7])
    ax_host.axis["bottom"].set_label(bottom_label)
    ax_host.axis["left"].set_label(left_label)
    ax_host.grid()
    # if wanna legend, uncomment the following line
    # plt.legend()
    plt.show()
error = np.random.normal(0.,0.1,shape_z)

#Generating noisy data
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)
Ejemplo n.º 8
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
Ejemplo n.º 9
0
y = 2
for key in indiv_dict:
    #pdb.set_trace()

    a_hat = indiv_dict[key][0]
    se = indiv_dict[key][1]
    l95 = float(a_hat) - 1.96 * float(se)
    new_se = float(a_hat) - l95

    temp_list = [key, a_hat, y, new_se]
    y += 1
    plot_list.append(temp_list)

figsize = (6, 6)
fig = figure(figsize=figsize, dpi=80)
ax_kms = SubplotHost(fig, 1, 1, 1, aspect=1.)

fig.add_subplot(ax_kms)

## Add overall OR first
summ_lines = summ_handle.readlines()
summ_list = []
for line in summ_lines:
    entry = line.rstrip('\n').split(' ')
    summ_list.append(entry[2])
#pdb.set_trace()
ov_a_hat = summ_list[0]
ov_se = summ_list[1]
# ov_odds	= math.exp(float(ov_a_hat))

##
Ejemplo n.º 10
0
        plt.clf()
        plt.plot(MI_vec)
        plt.xlabel('MCMC iteration x ' + str(skip))
        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'])
Ejemplo n.º 11
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.º 12
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
Ejemplo n.º 13
0
        mtransforms.Transform.__init__(self)

    def transform_non_affine(self, wl):
        return (wl * un.k).to(un.micron, equivalencies=un.spectral()).value

    def inverted(self):
        return Micron2WNTransform()


aux_trans = mtransforms.BlendedGenericTransform(
    Micron2WNTransform(), mtransforms.IdentityTransform())

fig = plt.figure(1)

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")
Ejemplo n.º 14
0
    def transform_non_affine(self, wl):
        return (wl*un.micron).to(un.k, equivalencies=un.spectral()).value

    def inverted(self):
        return WN2MicronTransform()



aux_trans = mtransforms.BlendedGenericTransform(WN2MicronTransform(), mtransforms.IdentityTransform())

fig = plt.figure(1)
fig.set_size_inches(7,4)

offset=0

ax_wn = SubplotHost(fig, 1, 1, 1)

fig.add_subplot(ax_wn)

ax_mn = ax_wn.twin(aux_trans)
ax_mn.set_viewlim_mode("transform")
#	x_micron=np.array([12, 10, 8, 6])
#	ax_mn.set_xticks(x_micron)
ax_mn.xaxis.tick_bottom()
ax_mn.tick_params(axis='x', direction = 'in', labelsize=11)
ax_mn.tick_params(axis='y', right=False, labelright=False)

#	ax_wn.set_xlim(675, 1700)
ax_wn.invert_xaxis()
#	x_wn=np.array([800, 1000, 1200, 1400, 1600])
#	ax_wn.set_xticks(x_wn)
Ejemplo n.º 15
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.º 16
0
potential_shapes= saved_data['potential_shapes']
dts             = saved_data['dts']
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
Ejemplo n.º 17
0
    def transform_non_affine(self, wl):
        return (wl * un.micron).to(un.k, equivalencies=un.spectral()).value

    def inverted(self):
        return WN2MicronTransform()


aux_trans = mtransforms.BlendedGenericTransform(
    WN2MicronTransform(), mtransforms.IdentityTransform())

fig = plt.figure(1)

name = ['Tetracene', 'Chrysene', 'Pyrene']

for n in range(1, 4, 1):
    ax_wn = SubplotHost(fig, 1, 3, n)

    fig.add_subplot(ax_wn)
    ax_wn.set_xlim(700, 1700)
    x_wn = np.array([800, 1000, 1200, 1400, 1600])
    ax_wn.tick_params(axis='x',
                      direction='in',
                      labelsize=11,
                      labelbottom=False,
                      labeltop=True,
                      top=True,
                      bottom=False)
    ax_wn.tick_params(axis='y', left=False, labelleft=False)
    ax_wn.set_xticks(x_wn)

    ax_mn = ax_wn.twin(aux_trans)
    mu_data[i] = float(columns[2])
    sigma_data[i] = float(columns[3])
    i += 1
f.close()

print len(sigma_data)

#mu_data = np.array(data.mu(), dtype=dtype)
#z_data = data[:]['z']
#sigma_data = data[:]['sigma']
#---------------------
#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,mu[0,:],'r-',lw=1.5,label="$\Omega_m = 0.2$")
p2 = host.plot(z,mu[1,:],'b--',lw=1.5,label="$\Omega_m = 0.3$")
p3 = host.plot(z,mu[2,:],'k-.',lw=1.5,label="$\Omega_m = 0.4$")
p4 = host.plot(z,mu[3,:],'m:',lw=1.5,label="$\Omega_m = 0.5$")
p5 = host.errorbar(z_data,mu_data,yerr=sigma_data,fmt='o',color='k',lw=1.5,label="SN data")

leg = pl.legend(loc=4,fontsize=18)
#host.set_ylim(0,48)
Ejemplo n.º 19
0
        plt.subplots_adjust(hspace=0.0)
    figs_N = 1
    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:
Ejemplo n.º 20
0
    plotStress(g.theta, g.r, s.sigmaZ,
               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
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.º 22
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.º 23
0
y = 2
for key in indiv_dict:
	#pdb.set_trace()

	a_hat = indiv_dict[key][0]
	se = indiv_dict[key][1]
	l95 = float(a_hat) - 1.96*float(se)
	new_se = float(a_hat) - l95

	temp_list = [key,a_hat, y, new_se]
	y += 1
	plot_list.append(temp_list)

figsize = (6,6)
fig = figure(figsize=figsize, dpi=80)
ax_kms = SubplotHost(fig, 1,1,1, aspect=1.)

fig.add_subplot(ax_kms)

## Add overall OR first 
summ_lines = summ_handle.readlines()
summ_list =[]
for line in summ_lines:
	entry = line.rstrip('\n').split(' ')
	summ_list.append(entry[2])
#pdb.set_trace()
ov_a_hat = summ_list[0]
ov_se = summ_list[1]
# ov_odds	= math.exp(float(ov_a_hat))

##
Ejemplo n.º 24
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.º 25
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
bulk = np.array([Jaipur.whatIsD(Celsius, orient=direction), 
                 Nushan.whatIsD(Celsius, orient=direction),
                 -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.)')
Ejemplo n.º 27
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.º 28
0
import matplotlib.transforms as mtransforms
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.parasite_axes import SubplotHost

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]")
Ejemplo n.º 29
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.º 30
0
#    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)
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.)')
Ejemplo n.º 31
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
Omega_m = np.array([0.2,0.3,0.4,0.5])

shape_Omega = np.asarray(Omega_m.shape, dtype=np.int)
shape_z = np.asarray(z.shape, dtype=np.int)

mu = np.zeros((shape_Omega, shape_z), dtype = np.float32, order = 'C')

for i in range (shape_Omega):
    for j in range (shape_z):
        mu[i,j] = cosmo.dist_modulus(z[j],Omega_m[i],(1.-Omega_m[i]),h)



fig = pl.figure()

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

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

fig.add_subplot(host)

p1 = host.plot(z,mu[0,:],'r-',lw=1.5,label="$\Omega_m = 0.2$")
p2 = host.plot(z,mu[1,:],'b--',lw=1.5,label="$\Omega_m = 0.3$")
p3 = host.plot(z,mu[2,:],'k-.',lw=1.5,label="$\Omega_m = 0.4$")
p4 = host.plot(z,mu[3,:],'m:',lw=1.5,label="$\Omega_m = 0.5$")

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

#pl.xticks(visible=False)
Ejemplo n.º 33
0
================

"""
import matplotlib.transforms as mtransforms
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.parasite_axes import SubplotHost

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")
Ejemplo n.º 34
0
        plt.plot(MI_vec)
        plt.xlabel('MCMC iteration x '+str(skip))
        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)
Ejemplo n.º 35
0
#    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)
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.)')
Ejemplo n.º 36
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