Esempio n. 1
0
def plot_dist(real_sample):
    alphascale = 1 / real_sample['gdir_prad_err1']
    alphascale /= np.max(alphascale)
    real_sample['alpha'] = alphascale

    for i, row in real_sample.iterrows():
        p = row['koi_period']
        r = row['gdir_prad']
        e = row['gdir_prad_err1']
        a = row['alpha']
        pl.errorbar(p, r, yerr=e, alpha=a, fmt='k.')
    # pl.errorbar(real_sample['koi_period'], real_sample['gdir_prad'],
    #             yerr=real_sample['gdir_prad_err1'], fmt='k.')
    pl.loglog()
    cksgaia.plot.config.logscale_rad(axis='y')

    ax = pl.gca()
    ax.xaxis.set_major_formatter(matplotlib.ticker.ScalarFormatter())
    ax.xaxis.set_major_formatter(matplotlib.ticker.FormatStrFormatter('%0.1f'))
    pl.xlim(0.3, 100)
    pl.xlabel('Orbital Period [days]')
    # pl.axhline(1.75, lw=3, color='r', linestyle='dashed')

    plot_box(e_corners, 'b-', lw=2)
    plot_box(sn_corners, 'b-', lw=2)
    plot_box(gap_corners, 'g-', lw=2)

    xt = [0.3, 1, 3, 10, 30, 100]
    yt = [0.7, 1, 1.5, 2, 3, 4, 6]
    pl.xticks(xt, xt)
    pl.yticks(yt, yt)

    pl.minorticks_off()
    pl.grid(False)
Esempio n. 2
0
File: tool.py Progetto: qsnake/gpaw
def plot_setticks(x=True, y=True):

    pl.minorticks_on()
    ax = pl.gca()
    if x:
        ax.xaxis.set_major_locator(pl.AutoLocator())
        x_major = ax.xaxis.get_majorticklocs()
        dx_minor = (x_major[-1] - x_major[0]) / (len(x_major) - 1) / 5.0
        ax.xaxis.set_minor_locator(pl.MultipleLocator(dx_minor))
    else:
        pl.minorticks_off()

    if y:
        ax.yaxis.set_major_locator(pl.AutoLocator())
        y_major = ax.yaxis.get_majorticklocs()
        dy_minor = (y_major[-1] - y_major[0]) / (len(y_major) - 1) / 5.0
        ax.yaxis.set_minor_locator(pl.MultipleLocator(dy_minor))
    else:
        pl.minorticks_off()
Esempio n. 3
0
def plot_setticks(x=True, y=True):

    pl.minorticks_on()
    ax = pl.gca()
    if x:
        ax.xaxis.set_major_locator(pl.AutoLocator())
        x_major = ax.xaxis.get_majorticklocs()
        dx_minor = (x_major[-1] - x_major[0]) / (len(x_major) - 1) / 5.
        ax.xaxis.set_minor_locator(pl.MultipleLocator(dx_minor))
    else:
        pl.minorticks_off()

    if y:
        ax.yaxis.set_major_locator(pl.AutoLocator())
        y_major = ax.yaxis.get_majorticklocs()
        dy_minor = (y_major[-1] - y_major[0]) / (len(y_major) - 1) / 5.
        ax.yaxis.set_minor_locator(pl.MultipleLocator(dy_minor))
    else:
        pl.minorticks_off()
Esempio n. 4
0
def fig_per_prad():
    fig = pl.figure(figsize=(4, 3.5))
    pl.loglog()
    df = cksgaia.io.load_table('cksgaia-planets')
    df = df
    #df = df.query('cks_fp==0 and ((gdir_prad /gdir_prad_err1)  > 0.1 ) ')
    df = df.query('cks_fp==0')
    pl.plot(df.koi_period, df.gdir_prad, '.', color='RoyalBlue', ms=2)

    yt = [0.2, 0.3, 0.5, 0.7, 1, 2, 3, 5, 7, 10, 20]
    pl.yticks(yt, yt)
    xt = [0.1, 0.3, 1, 3, 10, 30, 100, 300, 1000]
    _xt, _xtl = pl.xticks(xt, xt)
    pl.setp(_xtl, rotation=0)
    pl.xlim(0.1, 1000)
    pl.ylim(0.25, 20)
    pl.xlabel('Period [days]')
    pl.ylabel('Planet Size [Earth radii]')
    pl.tight_layout(True)
    pl.minorticks_off()
Esempio n. 5
0
def fig_insol_prad():
    fig = pl.figure(figsize=(4, 3.5))
    pl.loglog()
    df = cksgaia.io.load_table('cksgaia-planets')
    df = df
    df = df.query('cks_fp==0')

    pl.plot(df.giso_insol, df.gdir_prad, '.', color='RoyalBlue', ms=2)

    yt = [0.2, 0.3, 0.5, 0.7, 1, 2, 3, 5, 7, 10, 20]
    pl.yticks(yt, yt)
    #xt = [10000,3000,1000,300,100,30,10,3,1]
    #_xt, _xtl = pl.xticks(xt,xt)
    #pl.setp(_xtl, rotation=45)

    pl.xlim(10000, 1)
    pl.ylim(0.25, 20)
    pl.xlabel('Stellar light intensity relative to Earth')
    pl.ylabel('Planet Size [Earth radii]')
    pl.tight_layout(True)
    pl.minorticks_off()
Esempio n. 6
0
def plot_fit(obs, obs_err, photbands, pars={}, constraints={}, grids=[], gridnames=[], result='best', plot_components=True, plot_colors=False, plot_constraints=False):
   
   pars = pars.copy()
   
   # use model from 'best' results or 'pc' results
   resi = 0 if result == 'best' else 1

   print(gridnames)
   
   colors = np.array([filters.is_color(p) for p in photbands])
   psystems = np.array([p.split('.')[0] for p in photbands])
   waves = np.array([filters.eff_wave(p) for p in photbands[~colors]])
   
   #-- def system colors
   all_systems = set(psystems)
   colorcycle = cm.rainbow(np.linspace(0, 1, len(all_systems)))
   system_colors = {}
   for p, c in zip(all_systems, colorcycle):
      system_colors[p] = c
   
   abs_xlim = (0.9 * np.min(waves), 1.1 * np.max(waves) )
   
   if not len(list(pars.keys())) == 0:
      ipars = pars.copy()
      for key, value in list(pars.items()):
         ipars[key] = [value[resi]]
         pars[key] = value[resi]
      _ = ipars.pop('d')
      _ = pars.pop('d')
      
      syn, Labs = model.get_itable(grid=grids, photbands=photbands, **ipars)
      syn = syn[:,0]
      
      scale = pars['scale']
   
   # plot the fit of the absolute data
   #====================================
   if not plot_colors and not plot_constraints:
      ax1 = pl.subplot2grid((3,3), (0, 0), colspan=3, rowspan=2)
   else:
      ax1 = pl.subplot2grid((3,3), (0, 0), colspan=2, rowspan=2)
   
   
   if not len(list(pars.keys())) == 0:
      
      #-- synthetic integrated fluxes
      pl.plot(waves, scale*syn[~colors], 'xr')
      
      #-- if possible, plot a non integrated model
      #   can only be done if provided gridnames are not paths to integrated files.
      if len(gridnames) > 0 and not os.path.isfile(gridnames[0]):
         #-- synthetic model
         ebv = pars['ebv']
         wave, flux = model.get_table(grid=gridnames, **pars)
         flux = reddening.redden(flux, wave=wave, ebv=ebv, rtype='flux', law='fitzpatrick2004')
         
         #ascii.write([wave, scale*flux], 'binary_model.txt', names=['wave', 'flux'], overwrite=True)
         
         pl.plot(wave, scale*flux, '-r')
         
         #-- plot components
         if plot_components and 'teff2' in pars:
            wave, flux = model.get_table(grid=gridnames[0], teff=pars['teff'], logg=pars['logg'], rad=pars['rad'], ebv=pars['ebv'])
            flux = reddening.redden(flux, wave=wave, ebv=ebv, rtype='flux', law='fitzpatrick2004')
            #ascii.write([wave, scale*flux], 'primary_model.txt', names=['wave', 'flux'], overwrite=True)
            pl.plot(wave, scale*flux, '--g')
            
            wave, flux = model.get_table(grid=gridnames[1], teff=pars['teff2'], logg=pars['logg2'], rad=pars['rad2'], ebv=pars['ebv'])
            flux = reddening.redden(flux, wave=wave, ebv=ebv, rtype='flux', law='fitzpatrick2004')
            #ascii.write([wave, scale*flux], 'secondary_model.txt', names=['wave', 'flux'], overwrite=True)
            pl.plot(wave, scale*flux, '--b')
         
         
      
   wave, flux, error, band = [], [], [], []
   for system in all_systems:
      s = np.where((psystems == system) & (~colors))
      if len(obs[s]) == 0: continue
   
      w = np.array([filters.eff_wave(p) for p in photbands[s]])
      pl.errorbar(w, obs[s], yerr=obs_err[s], ls='', marker='o', 
                  color=system_colors[system], label=system)
      
      wave.extend(w)
      flux.extend(obs[s])
      error.extend(obs_err[s])
      band.extend([system for i in w])
      
    
   ascii.write([wave, flux, error, band], 'observations.txt', names=['wave', 'flux', 'error', 'band'], overwrite=True)
   
      
   pl.xlim(abs_xlim)
   pl.ylim([0.9*np.min(obs[~colors]), 1.1*np.max(obs[~colors])])
   pl.legend(loc='best', prop={'size': 9}, numpoints=1)
   ax1.set_xscale("log", nonposx='clip')
   ax1.set_yscale("log", nonposy='clip')
   
   pl.ylabel('Absolute Flux')
   
   #-- add band names to top of axis
   ax2 = ax1.twiny()
   ax2.set_xscale("log", nonposx='clip')
   ax2.set_xlim(abs_xlim)
   waves = np.array([filters.eff_wave(p) for p in photbands[~colors]])
   bandnames = np.array([b.split('.')[-1] for b in photbands[~colors]])
   ax2.set_xticks(waves)
   ax2.set_xticklabels(bandnames)
   ax2.xaxis.tick_top()
   pl.minorticks_off()
   
   
   
   # plot O-C of the absolute measurements
   #====================================
   if not plot_colors and not plot_constraints:
      ax = pl.subplot2grid((3,3), (2, 0), colspan=3, rowspan=1)
   else:
      ax = pl.subplot2grid((3,3), (2, 0), colspan=2, rowspan=1)
   
   for system in all_systems:
      s = np.where((psystems == system) & (~colors))
      if len(obs[s]) == 0: continue
      
      w = np.array([filters.eff_wave(p) for p in photbands[s]])
      y = ((obs - syn*scale) / obs)[s]
      yerr = (obs_err / obs)[s]
      
      y = 2.5*np.log10(syn[s]*scale / obs[s])
      yerr = 2.5 / np.log(10.0) * obs_err[s] / obs[s]
      
      pl.errorbar(w, -y , yerr=yerr, ls='', marker='o', color=system_colors[system])
   
   pl.figtext(0.96, 0.96, '$\chi^2$ = {:0.2f}'.format(pars['chi2']), ha='right')
   
   pl.axhline(y=0, color='k', ls='--')
   
   pl.xlim(abs_xlim)
   pl.gca().set_xscale('log',nonposx='clip')
   
   pl.ylabel('(O-C) (mag)')
   pl.xlabel('Wavelength (AA)')
   

   # plot O-C of the color fits
   #====================================
   if len(obs[colors]) > 0 and plot_colors:
      
      ax = pl.subplot2grid((3,3), (0, 2), colspan=1, rowspan=2)
      
      y = np.array(list(range(len(obs[colors]))))
      x = obs[colors] - syn[colors]
      x_err = obs_err[colors]
      oc_sys = psystems[colors]
      
      for system in all_systems:
         s = np.where(oc_sys == system)
         if len(x[s]) == 0: continue
      
         pl.errorbar(x[s], y[s], xerr=x_err[s], ls='', marker='o',
                     color=system_colors[system])
      
      pl.axvline(x=0, color='k', ls='--')
      
      yticknames = [b.split('.')[1] for b in photbands[colors]]
      pl.yticks(y, yticknames)
      pl.ylim([-y[-1]*0.1, y[-1]*1.1])
      
      ax.yaxis.tick_right()
      ax.xaxis.tick_top()
      ax.xaxis.set_label_position('top') 
      
      pl.xlabel('O-C')
   
   
   # plot fractional O-C of the constraints
   #=======================================
   if plot_constraints:
      ax = pl.subplot2grid((3,3), (2, 2), colspan=1, rowspan=1)
      
      x, xticknames = [], []
      
      if 'q' in constraints:
         
         q, ql, qu = constraints['q']
         
         ax.plot([1], pars['q'], 'k_', ms=15, mew=2)
         ax.errorbar([1], [q], yerr = [[ql], [qu]], marker='o')
         
         x.append(1)
         xticknames.append('q')
      
      
      if 'distance' in constraints:
         
         ax2 = ax.twinx()
         
         d  = constraints['distance'][0] / 44365810.04823812
         de = constraints['distance'][1] / 44365810.04823812
         
         
         ax2.plot([2], pars['d'], 'k_', ms=15, mew=2)
         ax2.errorbar([2], [d], yerr = de, marker='o')
         
         x.append(2)
         xticknames.append('distance')
      
      pl.xlim([0.5, 2.5])
      pl.xticks(x, xticknames)
   
   
   pl.figtext(0.03, 0.96, 'model = {}'.format(result))
Esempio n. 7
0
def contour_plot_kde(physmerge,
                     xcol,
                     ycol,
                     xlim,
                     ylim,
                     ylog=True,
                     pltxlim=None,
                     pltylim=None,
                     epos=[3000, 5],
                     cont=True,
                     nodata=False,
                     weighted=False,
                     nstars=36075.,
                     eaoff=(0, -30),
                     clabel=None,
                     vlims=(0.0, 0.05),
                     kwidth=None,
                     single=False,
                     cbar=True):
    """Plot contour plots

    Make the contour plots associated with Figures 8-10 in Fulton et al. (2017)

    Args:
        physmerge (DataFrame): Pandas DataFrame with the input planet catalogue
        xcol (string): name of x-axis column to plot
        ycol (string): name of y-axis column to plot
        xlim (tuple): x axis limits (min, max) for the wKDE calculation, should be slightly outside the pltxlim parameter
        ylim (tuple): y axis limits (min, max) for the wKDE calculation, should be slightly outside the pltylim parameter
        ylog (bool): (optional) log scale for y-axis?
        pltxlim (tuple): (optional) x-axis limit to display on plot (if different from xlim)
        pltylim (tuple): (optional) y-axis limit to display on plot (if different from ylim)
        epos (tuple): (optional) position to plot the typical uncertainty error bar
        cont (bool): (optional) plot the contours (default = True)
        nodata (bool): (optional) omit the datapoints from the plot (default = False)
        weighted (bool): (optional) use the 'weight' column to calculate a weighted KDE (default = False)
        nstars (float): (optional) total number of stars observed in sample (default = 36075.0). Used to calculate
            absolute occurrence scale
        eaoff (tuple): (optional) text offset for label of the typical uncertainty error bar (default = (0, -70))
        clabel (string): (optional) string to label color bar scale
        vlims (tuple): (optional) colorscale limits (default = (0.0, 0.05))
        kwidth (tuple): (optional) kernel width in units of (x,y)
        cbar (bool): (optional) plot colorbar?

    Returns:
        tuple: (axes object, 10**(grid x values), 10**(grid y values), grid z values)

    """

    # fig = pl.figure(figsize=(13, 8))

    crop = physmerge[(physmerge[ycol] < ylim[1]) & (physmerge[ycol] > ylim[0])
                     & (physmerge[xcol] < xlim[1]) &
                     (physmerge[xcol] < xlim[1])]

    nplanets = float(len(crop))

    if weighted:
        weights = crop['weight'].values
    else:
        weights = np.ones_like(crop[xcol].values)

    xerr1 = crop[xcol + '_err1'].values
    yerr1 = crop[ycol + '_err1'].values
    if kwidth != None:
        print(kwidth)
        xerr1 = np.zeros_like(xerr1) + kwidth[0] * crop[xcol].values
        yerr1 = np.zeros_like(yerr1) + kwidth[1] * crop[ycol].values

    xi, yi, zi = fitting.wkde2D(crop[xcol].values,
                                crop[ycol].values,
                                xerr1,
                                yerr1,
                                weights,
                                xlim=xlim,
                                ylim=ylim,
                                nstars=nstars)

    print(nplanets, (crop['gdir_prad_err1'] / crop['gdir_prad']).median())

    # cmap = plt.cm.inferno_r
    # cmap = plt.cm.gray_r
    # cmap = plt.cm.bone_r
    # cmap = plt.cm.gist_heat_r
    # cmap = plt.cm.magma_r
    cmap = plt.cm.afmhot_r
    # cmap = plt.cm.Blues_r

    vmin, vmax = vlims
    levels = np.arange(vmin, vmax + 0.0001, 0.005)
    if len(levels) <= 7:
        levels = np.linspace(vmin, vmax + 1e-4, 11)

    if single:
        levels = [0, np.mean([vmin, vmax])]

    if cont and not single:
        CS = plt.contourf(10**xi,
                          10**yi,
                          zi,
                          levels=levels,
                          cmap=cmap,
                          vmin=vmin,
                          vmax=vmax)
        for c in CS.collections:
            c.set_edgecolor("face")
    if single:
        CS = plt.contour(10**xi,
                         10**yi,
                         zi,
                         levels=levels,
                         cmap=cmap,
                         vmin=vmin,
                         vmax=vmax,
                         lw=3)
        for c in CS.collections:
            c.set_edgecolor("face")

    # pl.plot(big_sdist, big_pdist, 'k.', color='0.3', ms=1.0)
    if not nodata:
        pl.plot(crop[xcol],
                crop[ycol],
                'ko',
                ms=3,
                markeredgewidth=0.5,
                markeredgecolor='w')

    from .. import misc
    xe, ye = epos
    xerr1, xerr2 = misc.frac_err(physmerge, xe, xcol)
    yerr1, yerr2 = misc.frac_err(physmerge, ye, ycol)

    _, caps, _ = pl.errorbar(xe,
                             ye,
                             yerr=[[yerr1], [yerr2]],
                             xerr=[[xerr1], [xerr2]],
                             markeredgewidth=0,
                             lw=1,
                             capsize=2,
                             markeredgecolor='w',
                             fmt='k.',
                             ms=0.1)
    for cap in caps:
        cap.set_markeredgewidth(1)
    pl.annotate("typical\nuncert.",
                xy=(xe, ye),
                xytext=eaoff,
                xycoords="data",
                textcoords="offset points",
                horizontalalignment='center',
                fontsize=12)

    # pl.semilogx()
    if ylog:
        pl.loglog()
        pl.xlim(pltxlim)
        pl.ylim(pltylim)
    else:
        pl.semilogx()
        pl.xlim(pltxlim)
        pl.ylim(pltylim)

    yticks = np.array([0.3, 1, 2, 4, 6, 10, 30])
    xticks = np.array([0.3, 1, 3, 10, 30, 100, 300, 1000, 3000, 10000, 3e4])
    yt = yticks[(yticks >= ylim[0]) & (yticks <= ylim[1])]
    xt = xticks[(xticks >= xlim[0]) & (xticks <= xlim[1])]

    ax = pl.gca()
    if ylog:
        # pl.yticks(yt)
        pl.xticks(xt)
    else:
        pl.xticks(xt)

    pl.xlim(pltxlim)
    pl.ylim(pltylim)

    if cbar:
        if clabel is not None:
            clabel = clabel
        elif weighted:
            clabel = 'Relative Occurrence'
        else:
            clabel = 'Relative Density of Planets'

        ct = [0.0, 0.005, 0.01, 0.015, 0.02, 0.025, 0.03, 0.035, 0.04]
        cmap = pl.colorbar(pad=0, ticks=ct, label=clabel)

    ax.xaxis.grid(True)
    pl.minorticks_off()

    return (ax, 10**xi, 10**yi, zi)