Пример #1
0
def period(epos,
           Population=False,
           Occurrence=False,
           Observation=False,
           Tag=False,
           color='C1'):
    ''' Model occurrence as function of orbital period'''
    f, ax = plt.subplots()
    helpers.set_axis_distance(ax, epos, Trim=True)
    ax.set_xlim(0.5, 200)

    ax.set_ylabel(r'Planet Occurrence 1-4 $R_\bigoplus$')
    ax.set_yscale('log')

    pfm = epos.pfm
    eta = epos.modelpars.get('eta', Init=True)

    if not 'R' in pfm:
        pfm['R'], _ = epos.MR(pfm['M'])

    if Tag:
        # function that return a simulation subset based on the tag
        subset = {
            'Fe/H<=0': lambda tag: tag <= 0,
            'Fe/H>0': lambda tag: tag > 0
        }
    ''' Bins '''
    #xbins= np.geomspace(1,1000,10)/(10.**(1./3.))
    xbins = np.geomspace(0.5, 200, 15)
    ''' Plot model occurrence or observed counts'''
    weights = np.full(pfm['np'], eta / pfm['ns'])

    if 'draw prob' in pfm and not Tag:
        prob = pfm['draw prob'][pfm['ID']]
        weights *= prob * pfm['ns']  # system weights sum up to 1

    # histograms
    if Tag:
        for key, f in subset.iteritems():
            toplot = f(pfm['tag'])  #& (pfm['R']>1.)
            weights = np.where(toplot, eta, 0.) / f(pfm['system tag']).sum()

            ax.hist(pfm['P'],
                    bins=xbins,
                    weights=weights,
                    histtype='step',
                    label=key,
                    color='#88CCEE' if key == 'Fe/H<=0' else '#332288')
    else:
        ax.hist(pfm['P'], bins=xbins, weights=weights, color=color)

    if Tag:
        fname = '.tag'
        ax.set_title(epos.name + ': Disk Fe/H')
        ax.legend(fontsize='small', loc='lower right')
    else:
        fname = ''

    helpers.save(plt, '{}model/input.period{}'.format(epos.plotdir, fname))
Пример #2
0
def periodinner(epos, MC=False, N=False, Input=False, MCMC=False, color='C1'):
    # plot multiplicity
    f, ax = plt.subplots()
    ax.set_title('Period of the Innermost Planet')
    #ax.set_xlabel('Orbital Period [days]')
    ax.set_ylabel('Planet Counts')

    #ax.set_xscale('log')
    #ax.set_xlim(epos.xtrim)
    helpers.set_axis_distance(ax, epos, Trim=True)

    #bins= np.geomspace(*epos.xtrim)
    bins = epos.MC_xvar

    #pdf= regression.sliding_window_log(P, None, xgrid) #, width=2. )
    #ax3.plot(xgrid, pdf, ls='-', marker='', color=clrs[k % 4],label='{} x{:.3f}'.format(sg['name'], sg['weight']))

    # MC data
    if MC or MCMC:
        ss = epos.synthetic_survey
        if MCMC:
            for ss in epos.ss_sample:
                ax.hist(ss['multi']['Pinner'],
                        bins=bins,
                        color='b',
                        alpha=0.1,
                        histtype='step')

        else:
            ax.hist(ss['multi']['Pinner'],
                    bins=bins,
                    color=color,
                    histtype='stepfilled',
                    label='Simulated')  #epos.name)
            if hasattr(epos, 'pfm'):
                ax.hist(epos.pfm['Pin'],
                        bins=bins,
                        color='C7',
                        histtype='step',
                        label='Input',
                        ls=':')  #epos.name)

            # Solar system analologs (from dr25_solarsystem.py)
    # 		Pcut=45
    # 		Pcut=130
    # 		print 'P_in > {} days:'.format(Pcut)
    # 		print '  obs: {}'.format((epos.obs_zoom['multi']['Pinner']>Pcut).sum())
    # 		print '  sim: {}'.format((ss['multi']['Pinner']>Pcut).sum())
    # 		print ''

    #if False:
        if hasattr(epos, 'ss_extra'):
            # advance color cycle
            # ax._get_lines.get_next_color()
            ax.plot([], [])
            ax.plot([], [])

            # plot extra epos runs
            for ss in epos.ss_extra:
                ax.hist(ss['multi']['Pinner'],
                        bins=bins,
                        histtype='step',
                        label=ss['name'])

        if N:
            # Innermost is nth planet
            #ax.hist(ss['multi']['PN'][0], bins=bins,
            #		ec='k', histtype='step', label='actual inner planet')
            # Not actual inner planet
            ax.hist(np.concatenate(ss['multi']['PN'][1:]),
                    bins=bins,
                    color='r',
                    histtype='stepfilled',
                    label='Not Inner Planet')
        else:
            ax.hist(epos.obs_zoom['multi']['Pinner'],
                    bins=bins,
                    ec='C3',
                    histtype='step',
                    label='Kepler',
                    ls='--')

    else:
        # observed all
        ax.hist(epos.multi['Pinner'],
                bins=bins,
                color='0.7',
                label='Kepler all')
    ''' Initial distribution or zoomed observations '''
    if Input and epos.Parametric:
        Pingrid = np.geomspace(*epos.xtrim)
        _, _, pdf0_X, _ = draw_PR(epos,
                                  Init=True,
                                  ybin=epos.yzoom,
                                  xgrid=Pingrid)
        norm = 0.95 * ax.get_ylim()[1] / max(pdf0_X)
        ax.plot(Pingrid,
                pdf0_X * norm,
                marker='',
                ls='-',
                color='r',
                label='Intrinsic')

    prefix = 'output' if MC else 'survey'
    suffix = '.index' if N else ''
    suffix = '.input' if Input else suffix
    if MCMC: prefix = 'mcmc'

    if MC:
        ax.legend(loc='upper right',
                  shadow=False,
                  prop={'size': 14},
                  numpoints=1)

    helpers.save(plt, '{}{}/innerperiod{}'.format(epos.plotdir, prefix,
                                                  suffix))
Пример #3
0
def periodradius(epos, Nth=False, MC=True):

    f, (ax, axR, axP) = helpers.make_panels(plt)

    if MC:
        sim = epos.synthetic_survey
        ID = sim['ID']
        P = sim['P']
        Y = sim['Y']
        outdir = 'output'
        title = 'Simulated Detections'
    else:
        ID = epos.obs_starID
        P = epos.obs_xvar
        Y = epos.obs_yvar
        outdir = 'survey'
        title = r'Planet Candidates (score$\geq$0.9)'
    ''' plot R(P), main panel'''
    ax.set_title(title)
    helpers.set_axes(ax, epos, Trim=True)
    ''' Period side panel '''
    helpers.set_axis_distance(axP, epos, Trim=True)
    #axP.set_yscale('log')
    #axP.set_ylim([2e-3,5])
    #axP.set_yticks([0.01,0.1,1])
    #axP.set_yticklabels(['1%','10%','100%'])
    axP.yaxis.tick_right()
    axP.yaxis.set_ticks_position('both')
    #axP.tick_params(axis='y', which='minor',left='off',right='off')

    #axP.hist(sim['P'], bins=epos.MC_xvar, color='0.7')
    ''' Radius side panel'''
    helpers.set_axis_size(axR, epos, Trim=True, In=epos.MassRadius)

    #axR.set_xscale('log')
    #axR.set_xlim([2e-3,5])
    #axR.set_xticks([1,10,100,1000])
    #axR.set_xticklabels(['1','10','100','1000'], rotation=70)
    for tick in axR.get_xticklabels():
        tick.set_rotation(70)
    #axR.tick_params(axis='x', which='minor',top='off',bottom='off')
    #axP.tick_params(axis='y', which='minor',left='off',right='off')
    ''' which multiplanets to color '''
    # 	single, multi= EPOS.multi.indices(sim['ID'])
    # 	for k, (label, subset) in enumerate(zip(['single','multi'],[single, multi])):
    # 		ax.plot(sim['P'][subset], sim['Y'][subset], ls='', marker='.', mew=0, ms=5.0, \
    # 			label=label)

    if Nth:
        single, multi, ksys, multis = EPOS.multi.nth_planet(ID, P)
        suffix = '.nth'
        label_single = 'single'
    else:
        single, multi, ksys, multis = EPOS.multi.indices(ID)
        suffix = ''
        label_single = '1'

    ax.plot(P[single], Y[single], ls='', marker='.', \
      color='0.7', label=label_single)
    ''' Multiplanets with colors'''
    Stacked = True
    plist = []
    ylist = []
    colors = []
    CDF = False
    #stacked histogram

    for k, subset in zip(ksys, multis):
        ht, = ax.plot(P[subset], Y[subset], ls='', marker='.', \
         label=k)

        if not CDF:
            if Stacked:
                plist.insert(0, P[subset])
                ylist.insert(0, Y[subset])
                colors.insert(0, ht.get_color())
            # pdf
            else:
                axP.hist(P[subset],
                         bins=epos.MC_xvar,
                         color=ht.get_color(),
                         histtype='step')
                if k == ksys[-1]:
                    axP.hist(P[single],
                             bins=epos.MC_xvar,
                             color='0.7',
                             histtype='step')
        else:
            # cumulative
            Plist = np.sort(P[subset])
            axP.step(Plist, np.arange(Plist.size, dtype=float) / Plist.size)

    if Stacked:
        plist.append(P[single])
        ylist.append(Y[single])
        colors.append('0.7')
        axP.hist(plist, bins=epos.MC_xvar, color=colors, histtype='barstacked')
        axR.hist(ylist,
                 bins=epos.MC_yvar,
                 orientation='horizontal',
                 color=colors,
                 histtype='barstacked')

    else:
        #axR.hist(Y,orientation='horizontal', bins=epos.MC_yvar, color='0.7')
        axR.hist(Y,
                 orientation='horizontal',
                 bins=epos.MC_yvar,
                 color='k',
                 histtype='step')
        axR.hist(Y[single],
                 orientation='horizontal',
                 bins=epos.MC_yvar,
                 color='0.7')

    #ax.legend(loc='lower left', shadow=False, prop={'size':14}, numpoints=1)
    ax.legend(bbox_to_anchor=(1.0, 1.0),
              markerscale=2,
              frameon=True,
              borderpad=0.2,
              handlelength=1,
              handletextpad=0.2)

    helpers.save(plt, '{}{}/PR.multi{}'.format(epos.plotdir, outdir, suffix))
Пример #4
0
def period(epos,
           Population=False,
           Occurrence=False,
           Observation=False,
           Tag=False,
           color='C1',
           Zoom=False,
           Rbin=[1., 4.]):
    ''' Model occurrence as function of orbital period'''
    f, ax = plt.subplots()
    helpers.set_axis_distance(ax, epos, Trim=True)
    ax.set_xlim(0.5, 200)

    ax.set_ylabel(
        r'Planet Occurrence {:.2g}-{:.2g} $R_\bigoplus$'.format(*Rbin))
    ax.set_yscale('log')

    pfm = epos.pfm
    eta = epos.modelpars.get('eta', Init=True)

    if not 'R' in pfm:
        pfm['R'], _ = epos.MR(pfm['M'])

    if Tag:
        # function that return a simulation subset based on the tag
        subset = {
            'Fe/H<=0': lambda tag: tag <= 0,
            'Fe/H>0': lambda tag: tag > 0
        }
    ''' Bins '''
    #xbins= np.geomspace(1,1000,10)/(10.**(1./3.))
    #xbins= np.geomspace(0.5,200,15)

    dwP = 0.3  # bin width in ln space

    if Zoom:
        xbins = np.exp(
            np.arange(np.log(epos.xzoom[0]),
                      np.log(epos.xzoom[-1]) + dwP, dwP))
    else:
        xbins = np.exp(
            np.arange(np.log(epos.xtrim[0]),
                      np.log(epos.xtrim[-1]) + dwP, dwP))
    ''' Plot model occurrence or observed counts'''
    weights = np.full(pfm['np'], eta / pfm['ns'])

    if 'draw prob' in pfm and not Tag:
        prob = pfm['draw prob'][pfm['ID']]
        weights *= prob * pfm['ns']  # system weights sum up to 1

    # histograms
    if Tag:
        for key, f in subset.iteritems():
            toplot = f(pfm['tag'])  #& (pfm['R']>1.)
            weights = np.where(toplot, eta, 0.) / f(pfm['system tag']).sum()

            ax.hist(pfm['P'],
                    bins=xbins,
                    weights=weights,
                    histtype='step',
                    label=key,
                    color='#88CCEE' if key == 'Fe/H<=0' else '#332288')
    else:
        ax.hist(pfm['P'],
                bins=xbins,
                weights=weights,
                color=color,
                histtype='step')

    if Tag:
        fname = '.tag'
        ax.set_title(epos.name + ': Disk Fe/H')
        ax.legend(fontsize='small', loc='lower right')
    else:
        fname = ''

    if Occurrence:
        cut = (Rbin[0] < epos.obs_yvar) & (epos.obs_yvar < Rbin[-1])

        weights = epos.occurrence['planet']['occ'][cut]
        ax.hist(epos.obs_xvar[cut],
                bins=xbins,
                weights=weights,
                histtype='step',
                color='k')

        helpers.save(plt,
                     '{}occurrence/model.period{}'.format(epos.plotdir, fname))

    # elif Observation: # counts
    else:
        helpers.save(plt, '{}model/input.period{}'.format(epos.plotdir, fname))
Пример #5
0
def panels_radius(epos,
                  Population=False,
                  Occurrence=False,
                  Observation=False,
                  Tag=False,
                  color='C0',
                  clr_obs='C3',
                  Shade=True,
                  Fancy=True,
                  Zoom=False):
    f, (ax, axR, axP) = helpers.make_panels(plt, Fancy=Fancy)
    pfm = epos.pfm
    eta = epos.modelpars.get('eta', Init=True)

    title = ''
    if not 'R' in pfm:
        pfm['R'], _ = epos.MR(pfm['M'])

    if Tag:
        # function that return a simulation subset based on the tag
        subset = {
            'Fe/H<=0': lambda tag: tag <= 0,
            'Fe/H>0': lambda tag: tag > 0
        }
    ''' Bins '''
    dwR = 0.2  # bin width in ln space
    dwP = 0.3
    if Zoom:
        xbins = np.exp(
            np.arange(np.log(epos.xzoom[0]),
                      np.log(epos.xzoom[-1]) + dwP, dwP))
        ybins = np.exp(
            np.arange(np.log(epos.yzoom[0]),
                      np.log(epos.yzoom[-1]) + dwR, dwR))
    else:
        xbins = np.exp(
            np.arange(np.log(epos.xtrim[0]),
                      np.log(epos.xtrim[-1]) + dwP, dwP))
        ybins = np.exp(
            np.arange(np.log(epos.ytrim[0]),
                      np.log(epos.ytrim[-1]) + dwR, dwR))
    ''' Plot model occurrence or observed counts'''
    if Observation:
        # plot model planets * completeness
        weights = eta * epos.occurrence['model']['completeness'] / pfm['ns']
    else:
        weights = np.full(pfm['np'], eta / pfm['ns'])

    if 'draw prob' in pfm and not Tag:
        prob = pfm['draw prob'][pfm['ID']]
        weights *= prob * pfm['ns']  # system weights sum up to 1
        #nonzero= np.where(prob>0, 1., 0.)
        #weights*= nonzero*(pfm['np']/nonzero.sum())

    # histograms
    if Tag:
        for key, f in subset.iteritems():
            toplot = f(pfm['tag'])
            #weights= eta*epos.occurrence['model']['completeness'] \
            #		*np.where(toplot,1.,0.)/f(pfm['system tag']).sum()
            weights = np.where(toplot, eta, 0.) / f(pfm['system tag']).sum()
            axP.hist(pfm['P'],
                     bins=xbins,
                     weights=weights,
                     histtype='step',
                     label=key)
            axR.hist(pfm['R'],
                     bins=ybins,
                     orientation='horizontal',
                     weights=weights,
                     histtype='step')
    else:
        # color have to be 1-element lists ??
        axP.hist(pfm['P'], bins=xbins, weights=weights, color=[color])
        axR.hist(pfm['R'],
                 bins=ybins,
                 orientation='horizontal',
                 weights=weights,
                 color=[color])
    ''' Overplot observations? '''
    if Population:
        assert hasattr(epos, 'func')
        fname = '.pop' + ('.zoom' if Zoom else '')

        title = epos.title

        pps, pdf, pdf_X, pdf_Y = periodradius(epos, Init=True)
        _, _, pdf_X, _ = periodradius(epos, Init=True, ybin=ybins)
        _, _, _, pdf_Y = periodradius(epos, Init=True, xbin=xbins)
        pps, _, _, _ = periodradius(epos, Init=True, xbin=xbins, ybin=ybins)
        #pdf/= np.max(pdf)
        #pdflog= np.log10(pdf) # in %
        levels = np.linspace(0, np.max(pdf))
        lines = np.array([0.1, 0.5]) * np.max(pdf)

        if Shade:
            ax.contourf(epos.X_in,
                        epos.Y_in,
                        pdf,
                        cmap='Purples',
                        levels=levels)
            #ax.contour(epos.X_in, epos.Y_in, pdf, levels=lines)

            # Side panels
            #print 'pps model= {}'.format(eta)
            axP.plot(epos.MC_xvar,
                     pdf_X * dwP,
                     marker='',
                     ls='-',
                     color='purple')
            axR.plot(pdf_Y * dwR,
                     epos.in_yvar,
                     marker='',
                     ls='-',
                     color='purple')
        else:
            # renormalize
            xnorm = axP.get_ylim()[1] / max(pdf_X)
            ynorm = axR.get_xlim()[1] / max(pdf_Y)

            axP.plot(epos.MC_xvar,
                     pdf_X * xnorm,
                     marker='',
                     ls='-',
                     color=clr_obs)
            axR.plot(pdf_Y * ynorm,
                     epos.in_yvar,
                     marker='',
                     ls='-',
                     color=clr_obs)

    elif Observation:
        fname = '.obs' + ('.zoom' if Zoom else '')

        title = epos.title + ': Counts'

        ax.plot(epos.obs_xvar,
                epos.obs_yvar,
                ls='',
                marker='.',
                ms=5.0,
                color='0.5')

        weights = np.full(epos.obs_xvar.size, 1. / epos.nstars)
        axP.hist(epos.obs_xvar,
                 bins=xbins,
                 weights=weights,
                 histtype='step',
                 color='0.5')
        axR.hist(epos.obs_yvar,
                 bins=ybins,
                 weights=weights,
                 orientation='horizontal',
                 histtype='step',
                 color='0.5')

    elif Occurrence:
        fname = '.occ' + ('.zoom' if Zoom else '')
        title = epos.title + r': Occurrence, $\eta={:.2g}$'.format(eta)

        ax.plot(epos.obs_xvar,
                epos.obs_yvar,
                ls='',
                marker='.',
                ms=5.0,
                color='0.5')

        cut = epos.obs_yvar > 0.45

        weights = 1. / (epos.occurrence['planet']['completeness'][cut] *
                        epos.nstars)
        axP.hist(epos.obs_xvar[cut],
                 bins=xbins,
                 weights=weights,
                 histtype='step',
                 color='k')
        axR.hist(epos.obs_yvar[cut],
                 bins=ybins,
                 weights=weights,
                 orientation='horizontal',
                 histtype='step',
                 color='k')

    elif Tag:
        fname = '.tag'
        ax.set_title(epos.title + ': Tag')

        axP.legend(frameon=False, fontsize='small')
        # 		for k, tag in enumerate(subset):
        # 			axP.text(0.98,0.95-0.05*k,tag,ha='right',va='top',color='C1',
        # 				transform=axP.transAxes)

    else:
        fname = ''

    if Fancy:
        plt.suptitle(title, ha='center')  #, x=0.05)
    else:
        ax.set_title(title)
    ''' plot main panel'''
    #helpers.set_axes(ax, epos, Trim=True)

    helpers.set_axes(ax, epos, Trim=True)
    if Tag:
        for key, f in subset.iteritems():
            todraw = f(pfm['tag'])
            ax.plot(pfm['P'][todraw], pfm['R'][todraw], **fmt_symbol)
    elif 'draw prob' in pfm:
        #fmt_symbol['alpha']= 0.6*pfm['draw prob'][pfm['ID']] # alpha can't be array
        todraw = pfm['draw prob'][pfm['ID']] > 0
        ax.plot(pfm['P'][todraw], pfm['R'][todraw], color=color, **fmt_symbol)
    else:
        ax.plot(pfm['P'], pfm['R'], color=color, **fmt_symbol)
    ''' Period side panel '''
    #axP.yaxis.tick_right()
    #axP.yaxis.set_ticks_position('both')
    #axP.tick_params(axis='y', which='minor',left='off',right='off')
    helpers.set_axis_distance(axP, epos, Trim=True)
    ''' Mass side panel'''
    helpers.set_axis_size(axR, epos, Trim=True)  #, In= epos.MassRadius)

    helpers.save(plt, '{}model/input.radius{}'.format(epos.plotdir, fname))
Пример #6
0
def panels(epos, MCMC=False):

	f, (ax, axR, axP)= helpers.make_panels(plt)
	
	sim=epos.synthetic_survey
	
	clr_bf= 'g'
		
	''' plot R(P), main panel'''
	ax.set_title('Simulated Detections')
	helpers.set_axes(ax, epos, Trim=True)
	if epos.MonteCarlo:
		ax.plot(sim['P'], sim['Y'], ls='', marker='.', color=clr_bf if MCMC else 'C0')
	else:
		levels= np.linspace(0,np.max(sim['pdf']))		
		ax.contourf(epos.MC_xvar, epos.MC_yvar, sim['pdf'].T, cmap='Blues', levels=levels)

	''' Period side panel '''
	helpers.set_axis_distance(axP, epos, Trim=True)
	#axP.set_yscale('log')
	#axP.set_ylim([2e-3,5])	
	#axP.set_yticks([0.01,0.1,1])
	#axP.set_yticklabels(['1%','10%','100%'])
	axP.yaxis.tick_right()
	axP.yaxis.set_ticks_position('both')
	#axP.tick_params(axis='y', which='minor',left='off',right='off')
			
	''' Radius side panel'''
	helpers.set_axis_size(axR, epos, Trim=True) #, In= epos.MassRadius)

	#axR.set_xscale('log')
	#axR.set_xlim([2e-3,5])
	#axR.set_xticks([1,10,100,1000])
	#axR.set_xticklabels(['1','10','100','1000'], rotation=70)
	for tick in axR.get_xticklabels():
		tick.set_rotation(70)
	#axR.tick_params(axis='x', which='minor',top='off',bottom='off')
	#axP.tick_params(axis='y', which='minor',left='off',right='off')

	''' Histograms / posterior samples '''
	try:
		xbins= np.geomspace(*epos.xzoom, num=20)
		ybins= np.geomspace(*epos.yzoom, num=10)
	except:
		xbins= np.logspace(*np.log10(epos.xzoom), num=20)
		ybins= np.logspace(*np.log10(epos.yzoom), num=10)
	xscale= np.log(xbins[1]/xbins[0])
	yscale= np.log(ybins[1]/ybins[0])

	if MCMC:
		histkeys= {'color':'b', 'alpha':0.1}
		for ss in epos.ss_sample:
			if epos.MonteCarlo:
				axP.hist(ss['P zoom'], bins=xbins, histtype='step', **histkeys)
				axR.hist(ss['Y zoom'], bins=ybins, orientation='horizontal', \
					histtype='step', **histkeys)
			else:
				axP.plot(ss['P zoom'], ss['P zoom pdf']*xscale, 
					marker='', ls='-', **histkeys)
				axR.plot(ss['Y zoom pdf']*yscale, ss['Y zoom'], 
					marker='', ls='-', **histkeys)
		histdict= {'histtype':'step', 'color':clr_bf}
	else:
		histdict={}
	
	if epos.MonteCarlo:
		axP.hist(sim['P zoom'], bins=xbins, **histdict)
		axR.hist(sim['Y zoom'], bins=ybins, orientation='horizontal', **histdict)
	else:
		axP.plot(sim['P zoom'], sim['P zoom pdf']*xscale, marker='', ls='-')
		axR.plot(sim['Y zoom pdf']*yscale, sim['Y zoom'], marker='', ls='-')

	''' Observations'''
	axP.hist(epos.obs_zoom['x'], bins=xbins,histtype='step', color='C1')
	axR.hist(epos.obs_zoom['y'], bins=ybins, orientation='horizontal',histtype='step', color='C1')
	
	''' Box/ lines'''
	if epos.Zoom:
		for zoom in epos.xzoom: axP.axvline(zoom, ls='--', color='k')
		for zoom in epos.yzoom: axR.axhline(zoom, ls='--', color='k')
		ax.add_patch(patches.Rectangle( (epos.xzoom[0],epos.yzoom[0]), 
			epos.xzoom[1]-epos.xzoom[0], epos.yzoom[1]-epos.yzoom[0],fill=False, zorder=1) )
	
	#ax.legend(loc='lower left', shadow=False, prop={'size':14}, numpoints=1)
	
	fdir= 'mcmc' if MCMC else 'output'
	helpers.save(plt, '{}{}/pdf.zoom'.format(epos.plotdir, fdir))
Пример #7
0
def oneD_x(epos, PlotZoom=False, MCMC=False, Occ=False, Log=True):

    if Occ:
        fname = 'occurrence/posterior' if MCMC else 'occurrence/input'
        ybin = epos.yzoom
        unit = r'$M_\bigoplus$' if epos.RV else r'$R_\bigoplus$'
        title = r'Planet Occurrence ({1:.1f}-{2:.0f} {0})'.format(
            unit, *epos.yzoom)
    else:
        fname = 'mcmc/posterior' if MCMC else 'input/parametric_initial'
        ybin = None
        title = r'Marginalized Distribution ({:.1f}-{:.0f} $R_\bigoplus$)'.format(
            *epos.ytrim)

    if not Log:
        fname += '.linear'

    # initial guess
    pps, _, pdf0_X, _ = periodradius(epos, Init=True, ybin=ybin)
    if MCMC:
        # best-fit parameters
        pps, _, pdf_X, _ = periodradius(epos, ybin=ybin)
    ''' construct the posterior parameters '''
    if MCMC:
        plotsample = epos.samples[np.random.randint(len(epos.samples),
                                                    size=100)]
    ''' Orbital Period '''
    f, ax = plt.subplots()
    ax.set_title(title)
    ax.set_ylabel('Occurrence / {}P'.format(epos.plotpars['area']))

    #ax.set_xlabel('Orbital Period [days]')
    #ax.set_xscale('log')
    #ax.set_xlim(epos.xtrim)
    helpers.set_axis_distance(ax, epos, Trim=True)

    if Log:
        ax.set_yscale('log')
        if 'occrange' in epos.plotpars:
            ax.set_ylim(epos.plotpars['occrange'])
        else:
            ax.set_ylim([1e-3, 1e1])
    else:
        ax.set_ylim([0, 0.45])

    if MCMC:
        for fpara in plotsample:
            _, _, xpdf, _ = periodradius(epos, fpara=fpara, ybin=ybin)
            ax.plot(epos.MC_xvar, xpdf, color='b', alpha=0.1)

        ax.plot(epos.MC_xvar,
                pdf0_X,
                marker='',
                ls=':',
                color='k',
                label='Starting Guess')
        ax.plot(epos.MC_xvar,
                pdf_X,
                marker='',
                ls='-',
                color='k',
                label='Best Fit')
    else:
        if 'P break' in epos.fitpars.keys2d:
            ax.axvline(epos.fitpars.get('P break', Init=True),
                       ls='-',
                       color='gray')
        ax.plot(epos.MC_xvar, pdf0_X, marker='', ls='-', color='k')

    # plot posterior excluding low detection regions (arbitrary 2000 planets assumed)
    if not (epos.RV or epos.MassRadius):
        cens = np.where(epos.f_det < 1. / 3000., 0, 1.)
        _, _, cens_pdf_X, _ = periodradius(epos, ybin=ybin, fdet=cens)
        ax.plot(epos.MC_xvar,
                cens_pdf_X,
                marker='',
                ls='-',
                color='green',
                label='biased')

    if epos.Zoom:
        for zoom in epos.xzoom:
            ax.axvline(zoom, ls='--', color='k')

    if Occ:
        occbin = epos.occurrence['yzoom']
        ax.errorbar(occbin['xc'],
                    occbin['occ'] / occbin['dlnx'],
                    yerr=occbin['err'] / occbin['dlnx'],
                    color='r',
                    marker='_',
                    ls='',
                    capsize=3)  #,capthick=2

    # lognormal inner disk edge?
    #from scipy.stats import norm
    #gauss= 2.*norm(loc=1., scale=0.4).pdf(np.log10(epos.MC_xvar))
    #ax.plot(epos.MC_xvar, gauss, ls='-', marker='', color='r')

    if not Log:
        if 'Pinner all' in epos.plotpars:
            xx = np.geomspace(20, 400)
            a, b, c = epos.plotpars['Pinner all']
            ax.plot(xx,
                    a * (xx / b)**c,
                    marker='',
                    ls='-',
                    color='g',
                    label='All Planets')
        if 'Pinner ylim' in epos.plotpars:
            ax.set_ylim(epos.plotpars['Pinner ylim'])

    if MCMC:
        ax.legend(loc='upper left')

    helpers.save(plt, epos.plotdir + fname + '_x')