コード例 #1
0
ファイル: occurrence.py プロジェクト: davidpbennett/epos
def poly_only(epos):
	
	f, ax = plt.subplots()
	
	ax.set_title('Planet Classes')
	
	helpers.set_axes(ax, epos, Trim=True)
	
	# coordinates are from model routine
	occpoly= epos.occurrence['model']['poly']

	for k, (xc, yc, coords, label) in enumerate(
			zip(occpoly['xc'],occpoly['yc'],occpoly['coords'],
				epos.occurrence['poly']['labels'])
			):
			
		# box
		ax.add_patch(matplotlib.patches.Polygon(coords,
			fill=False, zorder=2, ls='-', color='k') )
		 
		size=16 if not 'textsize' in epos.plotpars else epos.plotpars['textsize'] 
			# 12 fit in box, 16 default
		ax.text(xc,yc,label, ha='center', va='center', 
			size=size)

	helpers.save(plt, epos.plotdir+'occurrence/poly_only')
コード例 #2
0
ファイル: occurrence.py プロジェクト: davidpbennett/epos
def integrated(epos, MCMC=False, Planets=False):
	
	f, (ax, axb) = plt.subplots(1,2, gridspec_kw = {'width_ratios':[20, 1]})
	f.subplots_adjust(wspace=0)
	
	sy= 'M' if (epos.MassRadius or epos.RV) else 'R'
	ax.set_title('Occurrence'+ (' (dln'+sy+' dlnP)' if MCMC else ' (Initial Guess)'))
	
	helpers.set_axes(ax, epos, Trim=True, In=epos.MassRadius)
	
	''' color scale? '''
	cmap='jet' # cool, spring
	vmin, vmax= -5, 0
	ticks=np.linspace(vmin, vmax, (vmax-vmin)+1)
	levels=np.linspace(vmin, vmax, 256)
	
	''' 2D pdf '''
	pps, pdf, _, _= periodradius(epos, Init=not MCMC)
	pdflog= np.log10(pdf) # in %
	cs= ax.contourf(epos.X_in, epos.Y_in, pdflog, cmap=cmap, levels=levels)
	cbar= f.colorbar(cs, cax=axb, ticks=ticks)
	axb.set_yticklabels(100*10.**ticks)
	axb.tick_params(axis='y', direction='out')
	axb.set_title('%')
	
	''' integrated occurrence per bin'''
	occbin= epos.occurrence['bin']
	key = 'eta' if MCMC else 'eta0'
	for k, (xbin, ybin, n, inbin, occ) in enumerate(
			zip(occbin['x'],occbin['y in'],occbin['n'],occbin['i'], occbin[key])
			):
		clr= clrs[k%4]
	
		# colored dots
		#ax.plot(epos.obs_xvar[inbin], epos.obs_yvar[inbin], 
		#	ls='', marker='.', mew=0, ms=5.0, color=clr, zorder=1)
	
		# box
		ax.add_patch(patches.Rectangle( (xbin[0],ybin[0]), 
			xbin[1]-xbin[0], ybin[1]-ybin[0],
			fill=False, zorder=2, ls='-', color='k') )
	
		xnudge=1.01
		ynudge=1.02
		size=16 if not 'textsize' in epos.plotpars else epos.plotpars['textsize'] 
				# 12 fit in box, 16 default
		ax.text(xbin[0]*xnudge,ybin[1]/ynudge,'{:.1%}'.format(occ), va='top',size=size)
		if MCMC:
			ax.text(xbin[0]*xnudge,ybin[1]/ynudge,'\n +{:.1%}\n  -{:.1%}'.format(
				occbin['eta+'][k],occbin['eta-'][k]
				), va='top',size=size)

	''' overplot planets '''
	if Planets:
		ax.plot(epos.obs_xvar, epos.obs_yvar, 
			ls='', marker='.', mew=0, ms=5, alpha=1, color='k')

	fname= 'posterior' if MCMC else 'integrated'
	if Planets: fname+= '.planets'
	helpers.save(plt, epos.plotdir+'occurrence/'+fname)
コード例 #3
0
ファイル: parametric.py プロジェクト: dsavransky/epos
def twoD(epos, PlotZoom=False, MCMC=False):

    # where does this go -> run.py
    assert epos.Parametric
    if not epos.Range: epos.set_ranges()

    # pdf
    pps, pdf, _, _ = periodradius(epos, Init=not MCMC)
    pdflog = np.log10(pdf)  # in %

    f, (ax, axb) = plt.subplots(1, 2, gridspec_kw={'width_ratios': [20, 1]})
    f.subplots_adjust(wspace=0)

    ax.set_title('Occurrence [%] / d ln p d ln ' +
                 ('M' if epos.MassRadius else 'R'))
    helpers.set_axes(ax, epos, Trim=True, In=epos.MassRadius)
    ''' color scale? '''
    cmap = 'jet'
    vmin, vmax = -5, 0
    ticks = np.linspace(vmin, vmax, (vmax - vmin) + 1)
    levels = np.linspace(vmin, vmax)
    ax.contourf(epos.X_in, epos.Y_in, pdflog, cmap=cmap, levels=levels)

    # colorbar?
    norm = Normalize(vmin=vmin, vmax=vmax)
    cb1 = clrbar.ColorbarBase(axb,
                              cmap=cmap,
                              norm=norm,
                              ticks=ticks,
                              orientation='vertical')  # horizontal
    axb.set_yticklabels(100 * 10.**ticks)
    axb.tick_params(axis='y', direction='out')

    fname = 'mcmc/posterior' if MCMC else 'input/parametric_initial'
    helpers.save(plt, epos.plotdir + fname)
コード例 #4
0
def vetting(epos, PlotBox=False):
    assert hasattr(epos, 'vetting')

    f, (ax, axb) = plt.subplots(1, 2, gridspec_kw={'width_ratios': [20, 1]})
    f.subplots_adjust(wspace=0)
    #f.set_size_inches(7, 5)

    ax.set_title('Vetting Efficiency')
    helpers.set_axes(ax, epos, Trim=False, Eff=True)
    ''' color map and ticks'''
    cmap = 'plasma'
    levels = np.linspace(0, 1, 256)
    ticks = np.array([0.0, 0.25, 0.5, 0.75, 1.0])
    ticks_percent = ['0', '25', '50', '75', '100']

    cs = ax.contourf(epos.eff_xvar,
                     epos.eff_yvar,
                     epos.vetting.T,
                     cmap=cmap,
                     levels=levels)

    cbar = f.colorbar(cs, cax=axb, ticks=ticks)
    axb.set_yticklabels(ticks_percent)
    axb.tick_params(axis='y', direction='out')
    axb.set_title('%')
    ''' Plot the zoom box or a few black contours'''
    if PlotBox:
        fname = '.box'
        assert epos.Range
        ax.add_patch(
            patches.Rectangle((epos.xtrim[0], epos.ytrim[0]),
                              epos.xtrim[1] - epos.xtrim[0],
                              epos.ytrim[1] - epos.ytrim[0],
                              fill=False,
                              zorder=1,
                              ls='--'))
        if epos.Zoom:
            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))
    else:

        cs = ax.contour(epos.eff_xvar,
                        epos.eff_yvar,
                        epos.vetting.T,
                        colors='k',
                        levels=ticks)
        fmt_percent = lambda x: '{:g} %'.format(100. * x)
        plt.clabel(cs, cs.levels, inline=True, fmt=fmt_percent)

        fname = ''
        if hasattr(epos, 'xtrim'):
            ax.set_xlim(*epos.xtrim)
            ax.set_ylim(*epos.ytrim)

    helpers.save(plt, epos.plotdir + 'survey/vetting' + fname)
コード例 #5
0
def periodradius(epos, SNR=True, Parametric=False):

	f, (ax, axR, axP)= helpers.make_panels(plt)
	
	sim=epos.synthetic_survey
	title='Simulated Detections'
	fsuffix='detect'

	if SNR:
		transit=epos.transit
		title= 'Simulated Transiting Planets'
		fsuffix='transit'
	
	''' plot R(P), main panel'''
	ax.set_title(title)
	helpers.set_axes(ax, epos, Trim=True)
	if SNR: ax.plot(transit['P'], transit['Y'], ls='', marker='.', color='C6')
	ax.plot(sim['P'], sim['Y'], ls='', marker='.', color='C0')

	''' Period side panel '''
	#helpers.set_axis_distance(axP, epos, Trim=True)
	axP.set_xlabel(ax.get_xlabel())
	#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')
	
	if SNR: axP.hist(transit['P'], bins=epos.MC_xvar, color='C6')
	axP.hist(sim['P'], bins=epos.MC_xvar)

	''' Radius side panel'''
	#helpers.set_axis_size(axR, epos, Trim=True, In= epos.MassRadius)
	axR.set_ylabel(ax.get_ylabel())

	#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')

	if SNR: axR.hist(transit['Y'],orientation='horizontal', bins=epos.MC_yvar, color='C6')
	axR.hist(sim['Y'],orientation='horizontal', bins=epos.MC_yvar)
	
	# labels
	if SNR:
		xpos= epos.MC_xvar[-1]
		ypos= axP.get_ylim()[-1]/1.05
		axP.text(xpos, ypos, 'Detected ', color='C0', ha='right', va='top')
		axP.text(xpos, ypos/1.3, 'Undetected ', color='C6', ha='right', va='top')
	
	#ax.legend(loc='lower left', shadow=False, prop={'size':14}, numpoints=1)
	helpers.save(plt, '{}output/periodradius.{}'.format(epos.plotdir,fsuffix))
コード例 #6
0
def model(epos):

    f, ax = plt.subplots()

    name = 'Model Occurrence Rate, $\eta={:.2g}$'.format(
        epos.occurrence['model']['eta'])
    ax.set_title(name)

    helpers.set_axes(ax, epos, Trim=True)

    ax.plot(epos.pfm['P'],
            epos.pfm['R'],
            ls='',
            marker='o',
            mew=0,
            ms=4,
            color='C0',
            zorder=0)
    ''' bins'''
    occbin = epos.occurrence['model']['bin']
    for k, (xbin, ybin, n, inbin, occ) in enumerate(
            zip(occbin['x'], occbin['y'], occbin['n'], occbin['i'],
                occbin['occ'])):

        # box
        ax.add_patch(
            patches.Rectangle((xbin[0], ybin[0]),
                              xbin[1] - xbin[0],
                              ybin[1] - ybin[0],
                              fill=False,
                              zorder=2,
                              ls='-',
                              color='k'))

        xnudge = 1.01
        ynudge = 1.02

        size = 16 if not 'textsize' in epos.plotpars else epos.plotpars[
            'textsize']
        # 12 fit in box, 16 default
        ax.text(xbin[0] * xnudge,
                ybin[1] / ynudge,
                '{:.1%}'.format(occ),
                va='top',
                size=size)
        ax.text(xbin[0] * xnudge,
                ybin[1] / ynudge,
                '\n$\pm${:.1f}'.format(occbin['err'][k] * 100),
                va='top',
                size=size)
        ax.text(xbin[1] / xnudge,
                ybin[0] * ynudge,
                'n={}'.format(n),
                ha='right',
                size=size)

    helpers.save(plt, epos.plotdir + 'occurrence/model')
コード例 #7
0
ファイル: parametric.py プロジェクト: dsavransky/epos
def panels(epos, PlotZoom=False, MCMC=False):
    ''' Initial distribution, panel layout'''
    f, (ax, axb, axR, axP) = helpers.make_panels_clrbar(plt)

    # pdf
    pps, pdf, pdf_X, pdf_Y = periodradius(epos, Init=not MCMC)
    pdflog = np.log10(pdf)  # in %

    ax.set_title('Planet Occurrence / dlnP dln' +
                 ('M' if epos.MassRadius else 'R'))
    helpers.set_axes(ax, epos, Trim=True, In=epos.MassRadius)

    # Side panels
    axP.plot(epos.MC_xvar, pdf_X, marker='', ls='-', color='k')
    axR.plot(pdf_Y, epos.in_yvar, marker='', ls='-', color='k')

    #helpers.set_axis_distance(axP, epos, Trim=True)
    #helpers.set_axis_size(axR, epos, Trim=True, In= epos.MassRadius)
    axP.set_xlabel(ax.get_xlabel())
    axR.set_ylabel(ax.get_ylabel())

    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=False, right=False)

    axR.set_xscale('log')
    axR.set_xlim([2e-3, 5])
    axR.set_xticks([0.01, 0.1, 1])
    axR.set_xticklabels(['1%', '10%', '100%'], rotation=70)
    axR.tick_params(axis='x', which='minor', top=False, bottom=False)
    axP.tick_params(axis='y', which='minor', left=False, right=False)
    axP.tick_params(axis='y', which='major', left=False, right=True)
    ''' color scale? '''
    cmap = 'jet'
    vmin, vmax = -5, 0
    ticks = np.linspace(vmin, vmax, (vmax - vmin) + 1)
    levels = np.linspace(vmin, vmax)
    ax.contourf(epos.X_in, epos.Y_in, pdflog, cmap=cmap, levels=levels)

    # colorbar?
    norm = Normalize(vmin=vmin, vmax=vmax)
    cb1 = clrbar.ColorbarBase(axb,
                              cmap=cmap,
                              norm=norm,
                              ticks=ticks,
                              orientation='vertical')  # horizontal
    axb.set_yticklabels(100 * 10.**ticks)
    axb.tick_params(axis='y', direction='out')
    axb.set_title('%')

    helpers.save(plt, epos.plotdir + 'input/panels')
コード例 #8
0
def observed(epos, PlotBox=True):
    assert epos.Observation
    f, ax = plt.subplots()
    ax.set_title('Observed Population')

    helpers.set_axes(ax, epos, Trim=epos.Range)

    ax.plot(epos.obs_xvar,
            epos.obs_yvar,
            ls='',
            marker='.',
            mew=0,
            ms=5.0,
            color='k')
    # add multis?

    if PlotBox:
        fname = '.box'
        assert epos.Range
        ax.add_patch(
            patches.Rectangle((epos.xtrim[0], epos.ytrim[0]),
                              epos.xtrim[1] - epos.xtrim[0],
                              epos.ytrim[1] - epos.ytrim[0],
                              fill=False,
                              zorder=1,
                              ls='--'))
        if epos.Zoom:
            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))
    else:
        fname = ''

    helpers.save(plt, epos.plotdir + 'survey/planets' + fname)
コード例 #9
0
def observed(epos, PlotBox=True, PlotScore=False):
    assert epos.Observation

    if PlotScore:
        f, (ax, axb) = plt.subplots(1,
                                    2,
                                    gridspec_kw={'width_ratios': [20, 1]})
        f.subplots_adjust(wspace=0)
    else:
        f, ax = plt.subplots()
    ax.set_title('Observed Population')

    helpers.set_axes(ax, epos, Trim=epos.Range)

    if PlotScore:
        ''' color scale? '''
        cmap = 'plasma'  # viridis, plasma, inferno, magma, spring, cool
        vmin, vmax = 0, 1
        #ticks=np.linspace(vmin, vmax, (vmax-vmin)+1)
        clrs, norm = helpers.color_array(epos.obs_score,
                                         vmin=vmin,
                                         vmax=vmax,
                                         cmap=cmap)
        ax.scatter(epos.obs_xvar, epos.obs_yvar, color=clrs, s=3)

        # colorbar?
        cb1 = clrbar.ColorbarBase(axb,
                                  cmap=cmap,
                                  norm=norm,
                                  orientation='vertical')  # horizontal
        axb.tick_params(axis='y', direction='out')

        fname = '.score'
    else:
        ax.plot(epos.obs_xvar,
                epos.obs_yvar,
                ls='',
                marker='.',
                mew=0,
                ms=5.0,
                color='k')
        fname = ''
        # add multis?

    if PlotBox:
        fname = '.box'
        assert epos.Range
        ax.add_patch(
            patches.Rectangle((epos.xtrim[0], epos.ytrim[0]),
                              epos.xtrim[1] - epos.xtrim[0],
                              epos.ytrim[1] - epos.ytrim[0],
                              fill=False,
                              zorder=1,
                              ls='--'))
        if epos.Zoom:
            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))

    helpers.save(plt, epos.plotdir + 'survey/planets' + fname)
コード例 #10
0
def completeness(epos, PlotBox=False, Transit=False, Vetting=True):
    assert epos.DetectionEfficiency

    f, (ax, axb) = plt.subplots(1, 2, gridspec_kw={'width_ratios': [20, 1]})
    f.subplots_adjust(wspace=0)
    #f.set_size_inches(7, 5)

    ax.set_title('Detection Efficiency' if Transit else 'Survey Completeness')
    helpers.set_axes(ax, epos, Trim=False, Eff=True)

    if Transit:
        toplot = epos.eff_2D
        if Vetting and hasattr(epos, 'vetting'): toplot *= epos.vetting
    else:
        toplot = epos.completeness if Vetting else epos.completeness_novet

    with np.errstate(divide='ignore'):
        log_completeness = np.log10(toplot)
    ''' color map and ticks'''
    cmap = 'YlOrBr' if Transit else 'PuRd'
    #cmap = 'rainbow' if Transit else 'PuRd'

    vmin, vmax = -4, 0
    if Transit: vmin = -3
    ticks = np.linspace(vmin, vmax, (vmax - vmin) + 1)
    levels = np.linspace(vmin, vmax, 256)

    cs = ax.contourf(epos.eff_xvar,
                     epos.eff_yvar,
                     log_completeness.T,
                     cmap=cmap,
                     levels=levels,
                     vmin=vmin,
                     vmax=vmax)

    cbar = f.colorbar(cs, cax=axb, ticks=ticks)
    axb.set_yticklabels(100 * 10.**ticks)
    axb.tick_params(axis='y', direction='out')
    axb.set_title('%')
    ''' Plot the zoom box or a few black contours'''
    if PlotBox:
        fname = '.box'
        assert epos.Range
        ax.add_patch(
            patches.Rectangle((epos.xtrim[0], epos.ytrim[0]),
                              epos.xtrim[1] - epos.xtrim[0],
                              epos.ytrim[1] - epos.ytrim[0],
                              fill=False,
                              zorder=1,
                              ls='--'))
        if epos.Zoom:
            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))
    else:
        if hasattr(epos, 'xtrim'):
            ax.set_xlim(*epos.xtrim)
            ax.set_ylim(*epos.ytrim)

        if epos.RV:
            levels = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]
            labels = ['10', '20', '30', '40', '50', '60', '70', '80', '90']
            cs= ax.contour(epos.eff_xvar, epos.eff_yvar, toplot.T,\
              levels= levels, colors = 'k', linewidths=2.)
        else:
            levels = [1e-3, 0.01, 0.1, 0.5, 0.9] if Transit else 10.**ticks
            cs = ax.contour(epos.eff_xvar,
                            epos.eff_yvar,
                            toplot.T,
                            colors='k',
                            levels=levels)
            fmt_percent = lambda x: '{:g} %'.format(100. * x)
            plt.clabel(cs, cs.levels, inline=True, fmt=fmt_percent)

        fname = ''

    if not Vetting: fname += '.novet'
    helpers.save(plt, epos.plotdir+'survey/'+('efficiency' if Transit else 'completeness')+ \
       fname)
コード例 #11
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))
コード例 #12
0
def cdf(epos):
	
	f, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)
	f.set_size_inches(9, 7) # default 7, 5

	''' 
	top left: synthetic obsservation
	'''
	sim= epos.synthetic_survey
	helpers.set_axes(ax1, epos, Trim=True)
	ax1.set_title('Synthetic ({})'.format(sim['nobs']))
	if epos.MonteCarlo:
		ax1.plot(sim['P'], sim['Y'], ls='', marker='.', mew=0, ms=5.0, color='r', alpha=0.5)
	else:
		levels= np.linspace(0,np.max(sim['pdf']))		
		ax1.contourf(epos.MC_xvar, epos.MC_yvar, sim['pdf'].T, cmap='Reds', levels=levels)
	
	if epos.Zoom:
		ax1.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) )
		
	''' 
	Top right: observed population 
	'''
	ax2.set_title('Observed ({})'.format(epos.obs_zoom['x'].size))
	helpers.set_axes(ax2, epos, Trim=True)

	ax2.plot(epos.obs_xvar, epos.obs_yvar, ls='', marker='.', mew=0, ms=5.0, color='b')		
	if epos.Zoom:
		ax2.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) )

	''' 
	cdf orbital period 
	'''
	if 'xvar' in epos.prob:
		ax3.set_title('Period, p={:.3g}'.format(epos.prob['xvar']))
	else:
		ax3.set_title('Orbital Period')
	ax3.set_xlabel('Orbital Period [days]')
	ax3.set_ylabel('CDF')
	ax3.set_xscale('log')
	ax3.set_ylim([-0.05,1.05])

	ax3.set_xlim(*epos.xzoom)

	if epos.MonteCarlo:
		#model histogram x
		P= sim['P zoom']
		ax3.plot(np.sort(P), np.arange(P.size, dtype=float)/P.size, ls='-', marker='', color='r')
	else:
		ax3.plot(sim['P zoom'], sim['P zoom cdf'], ls='-', marker='', color='r')
	
	#obs histogram x
	P= epos.obs_zoom['x']
	ax3.plot(np.sort(P), np.arange(P.size, dtype=float)/P.size, ls='-', marker='', color='b')		

	''' 
	CDF planet radius
	'''
	if 'yvar' in epos.prob:
		ax4.set_title('{}, p={:.3g}'.format('M sin i' if epos.RV else 'Radius', epos.prob['yvar']))
	else:
		ax4.set_title('{}'.format('M sin i' if epos.RV else 'Radius'))
	if epos.RV:	ax4.set_xlabel(r'Planet M sin i [M$_\bigoplus$]')
	else:		ax4.set_xlabel(r'Planet Radius [R$_\bigoplus$]')
	ax4.set_ylabel('CDF')
	ax4.set_xscale('log')
	ax4.set_ylim([-0.05,1.05])
	ax4.set_xlim(*epos.yzoom)
	
	ax4.set_xticks(epos.yticks)
	ax4.get_xaxis().set_major_formatter(tck.ScalarFormatter())

	if epos.MonteCarlo:
		#model histogram x
		R= sim['Y zoom']
		ax4.plot(np.sort(R), np.arange(R.size, dtype=float)/R.size, ls='-', marker='', color='r')
	else:
		ax4.plot(sim['Y zoom'], sim['Y zoom cdf'], ls='-', marker='', color='r')

	#obs histogram x
	R= epos.obs_zoom['y']
	ax4.plot(np.sort(R), np.arange(R.size, dtype=float)/R.size, ls='-', marker='', color='b')		
		
	f.tight_layout()
	helpers.save(plt, epos.plotdir+'output/cdf.diag')
コード例 #13
0
ファイル: workflow.py プロジェクト: davidpbennett/epos
def periodradius(epos, color='C4', alpha=1):
    gs = gridspec.GridSpec(nrows=9, ncols=3)
    f = plt.figure()
    f.set_size_inches(13, 7)  # default 7, 5
    f.subplots_adjust(wspace=0.5, hspace=0.0)

    ax1 = f.add_subplot(gs[3:6, 0])
    ax2 = f.add_subplot(gs[0:3, 1], sharex=ax1, sharey=ax1)
    ax3 = f.add_subplot(gs[6:9, 1], sharex=ax1, sharey=ax1)
    ax4 = f.add_subplot(gs[3:6, 2], sharex=ax1, sharey=ax1)

    if True:
        #f.suptitle(epos.name)
        f.suptitle(
            "Compare Planet Formation Models to Observed Exoplanets with epos",
            bbox=dict(boxstyle='round', fc='w', ec='k'))
    else:
        words = [
            'Compare', 'Planet Formation Models', 'to', 'Observed Exoplanets',
            'with', 'epos'
        ]
        colors = ['C0', color, '0.5', 'C3', '0.5', 'C2']

        helpers.rainbow_text(0.1, 0.95, words, colors, size=20, f=f, fudge=1.5)
        #helpers.rainbow_text(0.05, 1.1, words, colors, size=18, ax=axes[0,0])
    ''' Left: model '''
    ax = ax1
    helpers.set_axes(ax, epos, Trim=True)
    ax.set_xlabel('')

    ax.set_title('Formation Model: {}'.format(epos.name))
    pfm = epos.pfm
    ax.plot(pfm['P'],
            pfm['R'],
            ls='',
            marker='.',
            ms=5.0,
            color=color,
            alpha=alpha)
    ''' Top middle: synthetic obs'''
    ax = ax2
    ax.set_title('Simulated Observations')
    if epos.MonteCarlo:
        sim = epos.synthetic_survey
        ax.plot(sim['P'],
                sim['Y'],
                ls='',
                marker='.',
                mew=0,
                ms=5.0,
                color='C2',
                alpha=0.5)
    else:
        levels = np.linspace(0, np.max(sim['pdf']))
        ax.contourf(epos.MC_xvar,
                    epos.MC_yvar,
                    sim['pdf'].T,
                    cmap='Greens',
                    levels=levels)
    ''' Bottom middle: occurrnce rates'''
    ax = ax3
    ax.set_title('Occurrence Rates')
    ax.set_xlabel('Orbital Period [days]')

    occbin = epos.occurrence['bin']
    maxocc = np.max(occbin['occ'])
    for k, (xbin, ybin, n, inbin, occ) in enumerate(
            zip(occbin['x'], occbin['y'], occbin['n'], occbin['i'],
                occbin['occ'])):

        # box
        ax.add_patch(
            patches.Rectangle((xbin[0], ybin[0]),
                              xbin[1] - xbin[0],
                              ybin[1] - ybin[0],
                              fill=True,
                              ls='-',
                              fc=cm.Greens(occ / maxocc)))

        #xnudge=1.01
        #ynudge=1.02
        #ax.text(xbin[0]*xnudge,ybin[1]/ynudge,'{:.1%}'.format(occ), va='top',
        #	size=8)

    # colored dots
    #ax.plot(epos.obs_xvar, epos.obs_yvar,
    #	ls='', marker='.', mew=0, ms=2.0, color='k')
    ''' right: observations '''
    ax = ax4
    ax.set_title('Observed Planets')
    ax.plot(epos.obs_xvar,
            epos.obs_yvar,
            ls='',
            marker='.',
            mew=0,
            ms=5.0,
            color='C3')
    ''' 
	Draw horizontal bars
	'''
    xl = 0.07
    xw, dy = 0.85, 0.08
    yb, yt = 0.22, 0.75
    props = dict(transform=f.transFigure, alpha=0.3, zorder=-10)
    bar_fw = patches.Rectangle((xl, yt - dy), xw, 2 * dy, color='C1', **props)
    bar_occ = patches.Rectangle((xl, yb - dy), xw, 2 * dy, color='C6', **props)

    bbox = dict(boxstyle='round', fc='w', ec='k')
    props = dict(rotation=0,
                 ha='left',
                 va='center',
                 transform=f.transFigure,
                 bbox=bbox)

    f.patches.extend([bar_fw, bar_occ])
    f.text(xl - 0.03, yt, 'Forward Model', color='k', **props)
    f.text(xl - 0.03, yb, 'Inverse Model', color='k', **props)
    ''' Draw arrows between plots'''
    props = dict(transform=f.transFigure,
                 arrowstyle='simple',
                 connectionstyle='arc3,rad=-0.3',
                 alpha=0.3,
                 fc='g',
                 mutation_scale=50.)
    xl, xr = 0.3, 0.62
    yt, yb = 0.7, 0.2
    xw, yw = 0.1, 0.1
    arrow1 = patches.FancyArrowPatch((xl, yt), (xl + xw, yt + yw), **props)
    arrow2 = patches.FancyArrowPatch((xr + xw, yb + yw), (xr, yb), **props)

    f.text(xl - 0.05,
           yt + 0.06,
           'Apply Survey\nDetection Bias',
           color='g',
           ha='center',
           va='center',
           transform=f.transFigure)
    f.text(xr + xw + 0.07,
           yb,
           'Account for\nSurvey Completeness',
           color='g',
           ha='center',
           va='center',
           transform=f.transFigure)

    # and top-bottom
    props['connectionstyle'] = 'arc3,rad=0.0'
    props['mutation_scale'] = 30.
    props['fc'] = 'b'
    #props['shape']= 'full'
    #props['arrowstyle']='darrow'

    xl, xr = 0.33, 0.63
    yt, yb = 0.7, 0.25

    xw, yw = 0.005, 0.01
    dy = 0.04
    xs, ys = 0.05, 0.03

    arrow3 = patches.FancyArrowPatch((xl - xw, yb + dy),
                                     (xl - xw + xs, yb - dy), **props)
    arrow4 = patches.FancyArrowPatch((xl + xw + xs, yb - dy + ys),
                                     (xl + xw, yb + dy + ys), **props)
    #for x,y in zip([xl-0.04, xr+xs+0.04],[yb-dy,yt+dy]):
    #	f.text(x,y,'Compare',color='b',
    #		ha='center', va='center', transform=f.transFigure)
    f.text(xr + xs + 0.1,
           yt + dy,
           'Compare Distribution\nof Detections',
           color='b',
           ha='center',
           va='center',
           transform=f.transFigure)

    f.text(xl - 0.07,
           yb - dy,
           'Compare Intrinsic\n Planet Population',
           color='b',
           ha='center',
           va='center',
           transform=f.transFigure)

    arrow5 = patches.FancyArrowPatch((xr - xw, yt + dy),
                                     (xr - xw + xs, yt - dy), **props)
    arrow6 = patches.FancyArrowPatch((xr + xw + xs, yt - dy + ys),
                                     (xr + xw, yt + dy + ys), **props)

    f.patches.extend([arrow1, arrow2, arrow3, arrow4, arrow5, arrow6])
    ''' Draw crossed out arrow '''
    props['mutation_scale'] = 50.
    props['fc'] = 'w'
    props['zorder'] = -1
    xc, yc = 0.5, 0.5
    xw = 0.15
    if False:
        arrow_left = patches.FancyArrowPatch((xc, yc), (xc - xw, yc), **props)
        arrow_right = patches.FancyArrowPatch((xc, yc), (xc + xw, yc), **props)
    else:
        yw = 0.02
        arrow_left = patches.FancyArrowPatch((xc + xw - 0.01, yc + yw),
                                             (xc - xw, yc + yw), **props)
        arrow_right = patches.FancyArrowPatch((xc - xw + 0.01, yc - yw),
                                              (xc + xw, yc - yw), **props)

    f.patches.extend([arrow_left, arrow_right])

    dx, dy = 0.05, 0.05
    redcross = plt.scatter(xc,
                           yc,
                           s=2000,
                           c='red',
                           transform=f.transFigure,
                           marker='x',
                           lw=7,
                           clip_on=False)
    ax.add_artist(redcross)

    #f.tight_layout()
    helpers.save(plt, epos.plotdir + 'workflow/arrows')
コード例 #14
0
ファイル: occurrence.py プロジェクト: davidpbennett/epos
def model(epos, color='C0', alpha_fac=None, Bins=False, Poly=False, Gradient=False):
	
	f, ax = plt.subplots()
	
	name= '{}, $\eta={:.2g}$'.format(epos.name, epos.occurrence['model']['eta'])
	ax.set_title(name)
	
	helpers.set_axes(ax, epos, Trim=True)
	
	# set transparency / color gradient
	if Gradient:
		suffix= '.gradient'

		weigths= epos.occurrence['model']['completeness']
		cmin, cmax= 0.001, 0.1

		weigths= np.maximum(np.minimum(weigths,cmax), cmin)

		cmap='copper_r'
		#ticks=np.linspace(vmin, vmax, (vmax-vmin)+1)
		clrs, norm= helpers.color_array(np.log10(weigths),
			vmin=np.log10(cmin),vmax=np.log10(cmax), cmap=cmap)
		
		ax.scatter(epos.pfm['P'], epos.pfm['R'], 
			marker='o', s=13, lw=0, color=clrs,zorder=0)

		# colorbar?
		# cb1 = clrbar.ColorbarBase(axb, cmap=cmap, norm=norm, ticks=ticks,
		#                             orientation='vertical') # horizontal
		# axb.set_yticklabels(100*10.**ticks)
		# axb.tick_params(axis='y', direction='out')


	elif alpha_fac is not None:
		suffix= '.alpha'

		weigths= epos.occurrence['model']['completeness']*alpha_fac #*epos.nstars
		alpha= np.maximum(np.minimum(weigths,1.), 0.0) # 0.2?

		if True:
			# color issues with  to_rgba_array
			clr_rgba = np.empty((len(alpha), 4), float)
			for i, a in enumerate(alpha):
				clr_rgba[i] = matplotlib.colors.to_rgba(color, a)

		else:
			clr= np.full_like(weigths,color,dtype=str)
			clr_rgba= matplotlib.colors.to_rgba_array(clr) # alpha
			#print clr_rgba[0,:]
			clr_rgba[:,3]= alpha

		ax.scatter(epos.pfm['P'], epos.pfm['R'], 
			marker='o', s=13, lw=0, color=clr_rgba,zorder=0)
	else:
		suffix=''
		clr= matplotlib.colors.to_rgba(color)
		ax.plot(epos.pfm['P'], epos.pfm['R'], ls='', marker='o', mew=0, ms=4, 
			color=clr, zorder=0)
	
	''' bins'''
	if Bins:
		occbin= epos.occurrence['model']['bin']
		for k, (xbin, ybin, n, inbin, occ) in enumerate(
				zip(occbin['x'],occbin['y'],occbin['n'],occbin['i'], occbin['occ'])
				):
		
			# box
			ax.add_patch(patches.Rectangle( (xbin[0],ybin[0]), 
				xbin[1]-xbin[0], ybin[1]-ybin[0],
				fill=False, zorder=2, ls='-', color='k') )
		
			xnudge=1.01
			ynudge=1.02
			 
			size=16 if not 'textsize' in epos.plotpars else epos.plotpars['textsize'] 
				# 12 fit in box, 16 default
			ax.text(xbin[0]*xnudge,ybin[1]/ynudge,'{:.1%}'.format(occ), va='top', 
				size=size)
			ax.text(xbin[0]*xnudge,ybin[1]/ynudge,'\n$\pm${:.1f}'.format(
				occbin['err'][k]*100), va='top', size=size)
			ax.text(xbin[1]/xnudge,ybin[0]*ynudge,'n={}'.format(n), ha='right',
				size=size)
		helpers.save(plt, epos.plotdir+'occurrence/model_bins'+suffix)
	elif Poly:
		occpoly= epos.occurrence['model']['poly']
		for k, (xc, yc, coords, n, inbin, occ, err) in enumerate(
				zip(occpoly['xc'],occpoly['yc'],occpoly['coords'],
					occpoly['n'],occpoly['i'], occpoly['occ'], occpoly['err'])
				):
				
			# box
			ax.add_patch(matplotlib.patches.Polygon(coords,
				fill=False, zorder=2, ls='-', color='k') )
			 
			size=16 if not 'textsize' in epos.plotpars else epos.plotpars['textsize'] 
				# 12 fit in box, 16 default
			ax.text(xc,yc,'{:.1%}\n$\pm${:.1%}'.format(occ, err), ha='center', va='center', 
				size=size)
		helpers.save(plt, epos.plotdir+'occurrence/model_poly'+suffix)
	else:
		helpers.save(plt, epos.plotdir+'occurrence/model'+suffix)
コード例 #15
0
ファイル: model.py プロジェクト: davidpbennett/epos
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))
コード例 #16
0
ファイル: workflow.py プロジェクト: davidpbennett/epos
def periodradius_2x2(epos):
    f, axes = plt.subplots(2, 2, sharex=True, sharey=True)
    ((ax1, ax2), (ax3, ax4)) = axes
    f.set_size_inches(9, 7)  # default 7, 5
    f.subplots_adjust(wspace=0.5, hspace=0.5)

    if False:
        #f.suptitle(epos.name)
        f.suptitle(
            "Compare Planet Formation Models to Observed Exoplanets with epos")
    else:
        words = [
            'Compare', 'Planet Formation Models', 'to', 'Observed Exoplanets',
            'with', 'epos'
        ]
        colors = ['b', '0.5', 'k', 'r', 'k', 'g']

        helpers.rainbow_text(0.05,
                             0.95,
                             words,
                             colors,
                             size=16,
                             f=f,
                             fudge=1.5)
        #helpers.rainbow_text(0.05, 1.1, words, colors, size=18, ax=axes[0,0])

    helpers.set_axes(axes[1, 0], epos, Trim=True)
    ''' Top left: model '''
    ax = axes[0, 0]
    ax.set_title('Formation Model: {}'.format(epos.name))
    pfm = epos.pfm
    ax.plot(pfm['P'], pfm['R'], ls='', marker='.', ms=5.0, color='0.5')
    ''' Top right: synthetic obs'''
    ax = axes[0, 1]
    ax.set_title('Simulated Observations')

    if epos.MonteCarlo:
        sim = epos.synthetic_survey
        ax.plot(sim['P'],
                sim['Y'],
                ls='',
                marker='.',
                mew=0,
                ms=5.0,
                color='r',
                alpha=0.5)
    else:
        levels = np.linspace(0, np.max(sim['pdf']))
        ax.contourf(epos.MC_xvar,
                    epos.MC_yvar,
                    sim['pdf'].T,
                    cmap='Reds',
                    levels=levels)
    ''' Bottom left: occurrnce rates'''
    ax = axes[1, 0]
    ax.set_title('Occurrence Rates')

    occbin = epos.occurrence['bin']
    maxocc = np.max(occbin['occ'])
    for k, (xbin, ybin, n, inbin, occ) in enumerate(
            zip(occbin['x'], occbin['y'], occbin['n'], occbin['i'],
                occbin['occ'])):

        # box
        ax.add_patch(
            patches.Rectangle((xbin[0], ybin[0]),
                              xbin[1] - xbin[0],
                              ybin[1] - ybin[0],
                              fill=True,
                              ls='-',
                              fc=cm.binary(occ / maxocc)))

        #xnudge=1.01
        #ynudge=1.02
        #ax.text(xbin[0]*xnudge,ybin[1]/ynudge,'{:.1%}'.format(occ), va='top',
        #	size=8)

    # colored dots
    #ax.plot(epos.obs_xvar, epos.obs_yvar,
    #	ls='', marker='.', mew=0, ms=2.0, color='k')
    ''' Bottom right: observations '''
    ax = axes[1, 1]
    ax.set_title('Observed Planets')
    ax.plot(epos.obs_xvar,
            epos.obs_yvar,
            ls='',
            marker='.',
            mew=0,
            ms=5.0,
            color='C3')
    ''' Draw arrows between plots'''
    props = dict(transform=f.transFigure,
                 arrowstyle='simple',
                 connectionstyle='arc3',
                 alpha=0.3,
                 fc='g',
                 mutation_scale=80.)
    xl, xr = 0.44, 0.57
    yt, yb = 0.75, 0.25
    arrow1 = patches.FancyArrowPatch((xl, yt), (xr, yt), **props)
    arrow2 = patches.FancyArrowPatch((xr, yb), (xl, yb), **props)

    f.text((xl + xr) / 2,
           yt,
           'Bias',
           color='k',
           ha='center',
           va='center',
           transform=f.transFigure)
    f.text((xl + xr) / 2,
           yb,
           'Debias',
           color='k',
           ha='center',
           va='center',
           transform=f.transFigure)

    # and top-bottom
    props['connectionstyle'] = 'arc3,rad=0.9'
    props['mutation_scale'] = 30.
    props['fc'] = 'b'
    xl, xr = 0.27, 0.75
    xw = 0.03
    yt, yb = 0.55, 0.46

    arrow3 = patches.FancyArrowPatch((xl - xw, yt), (xl - xw, yb), **props)
    arrow4 = patches.FancyArrowPatch((xl + xw, yb), (xl + xw, yt), **props)
    for xt in [xl, xr]:
        f.text(xt, (yt + yb) / 2,
               'Compare',
               color='b',
               ha='center',
               va='center',
               transform=f.transFigure)

    arrow5 = patches.FancyArrowPatch((xr - xw, yt), (xr - xw, yb), **props)
    arrow6 = patches.FancyArrowPatch((xr + xw, yb), (xr + xw, yt), **props)

    f.patches.extend([arrow1, arrow2, arrow3, arrow4, arrow5, arrow6])

    #f.tight_layout()
    helpers.save(plt, epos.plotdir + 'workflow/arrows_2x2')
コード例 #17
0
ファイル: occurrence.py プロジェクト: davidpbennett/epos
def colored(epos, Bins=False, Poly=False):
	
	f, (ax, axb) = plt.subplots(1,2, gridspec_kw = {'width_ratios':[20, 1]})
	f.subplots_adjust(wspace=0)
	
	name= 'Survey Completeness'
	if epos.name in ['dr25_F','dr25_G','dr25_K','dr25_M','dr25_GK']: name+= ' ('+epos.name[5:]+')'
	ax.set_title(name)
	
	helpers.set_axes(ax, epos, Trim=True)
	#if epos.plot['']
	
	#ax.plot(epos.obs_xvar, epos.obs_yvar, ls='', marker='.', mew=0, ms=5.0, color='k')

	''' color scale? '''
	cmap='magma' # viridis, plasma, inferno, magma, spring, cool
	cmap='viridis'
	vmin, vmax= -4, 0
	ticks=np.linspace(vmin, vmax, (vmax-vmin)+1)
	clrs, norm= helpers.color_array(np.log10(epos.occurrence['planet']['completeness']),
		vmin=vmin,vmax=vmax, cmap=cmap)
	ax.scatter(epos.obs_xvar, epos.obs_yvar, color=clrs, s=4)
	
	# colorbar?
	cb1 = clrbar.ColorbarBase(axb, cmap=cmap, norm=norm, ticks=ticks,
                                orientation='vertical') # horizontal
	axb.set_yticklabels(100*10.**ticks)
	axb.tick_params(axis='y', direction='out')
	
	''' bins?'''
	if Bins:
		occbin= epos.occurrence['bin']
		for k, (xbin, ybin, n, inbin, occ) in enumerate(
				zip(occbin['x'],occbin['y'],occbin['n'],occbin['i'], occbin['occ'])
				):
			clr= clrs[k%4]
		
			# colored dots
			#ax.plot(epos.obs_xvar[inbin], epos.obs_yvar[inbin], 
			#	ls='', marker='.', mew=0, ms=5.0, color=clr, zorder=1)
		
			# box
			ax.add_patch(patches.Rectangle( (xbin[0],ybin[0]), 
				xbin[1]-xbin[0], ybin[1]-ybin[0],
				fill=False, zorder=2, ls='-', color='k') )
		
			xnudge=1.01
			ynudge=1.02
			 
			size=16 if not 'textsize' in epos.plotpars else epos.plotpars['textsize'] 
				# 12 fit in box, 16 default
			ax.text(xbin[0]*xnudge,ybin[1]/ynudge,'{:.1%}'.format(occ), va='top', 
				size=size)
			ax.text(xbin[0]*xnudge,ybin[1]/ynudge,'\n$\pm${:.1f}'.format(
				occbin['err'][k]*100), va='top', size=size)
			ax.text(xbin[1]/xnudge,ybin[0]*ynudge,'n={}'.format(n), ha='right',
				size=size)
	
		helpers.save(plt, epos.plotdir+'occurrence/bins')
	elif Poly:
		occpoly= epos.occurrence['poly']
		for k, (xc, yc, coords, n, inbin, occ, err) in enumerate(
				zip(occpoly['xc'],occpoly['yc'],occpoly['coords'],
					occpoly['n'],occpoly['i'], occpoly['occ'], occpoly['err'])
				):
				
			# box
			ax.add_patch(matplotlib.patches.Polygon(coords,
				fill=False, zorder=2, ls='-', color='k') )
			 
			size=16 if not 'textsize' in epos.plotpars else epos.plotpars['textsize'] 
				# 12 fit in box, 16 default
			ax.text(xc,yc,'{:.1%}\n$\pm${:.1f}'.format(occ, err*100), ha='center', va='center', 
				size=size)
			#ax.text(xbin[1]/xnudge,ybin[0]*ynudge,'n={}'.format(n), ha='right',
			#	size=size)
	
		helpers.save(plt, epos.plotdir+'occurrence/poly')
	else:
		helpers.save(plt, epos.plotdir+'occurrence/colored')
コード例 #18
0
ファイル: multi.py プロジェクト: davidpbennett/epos
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))
コード例 #19
0
ファイル: periodradius.py プロジェクト: davidpbennett/epos
def periodradius(epos, SNR=True, Model=False, color='C1'):

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

    sim = epos.synthetic_survey
    title = 'Simulated Detections: {}'.format(epos.name)
    fsuffix = 'detect'
    xbins = epos.MC_xvar
    ybins = epos.MC_yvar

    if SNR:
        transit = epos.transit
        title = 'Simulated Transiting Planets'
        fsuffix = 'transit'
    elif Model:
        pfm = epos.pfm
        fsuffix = 'population'

        dwR = 0.2  # bin width in ln space
        dwP = 0.3

        xbins = np.exp(
            np.arange(np.log(epos.mod_xlim[0]),
                      np.log(epos.mod_xlim[-1]) + dwP, dwP))
        ybins = np.exp(
            np.arange(np.log(epos.ytrim[0]),
                      np.log(epos.ytrim[-1]) + dwR, dwR))
    ''' plot R(P), main panel'''
    f.suptitle(title)
    helpers.set_axes(ax, epos, Trim=True)
    if SNR:
        ax.plot(transit['P'], transit['Y'], ls='', marker='.', color='C6')
    elif Model:
        ax.plot(pfm['P'], pfm['R'], ls='', marker='.', ms=5.0, color='0.5')
    ax.plot(sim['P'], sim['Y'], ls='', marker='.', color=color)

    if Model:
        xlim = ax.get_xlim()
        ax.set_xlim(xlim[0], epos.mod_xlim[-1])
        #ax.set_ylim(epos.mod_ylim)
    ''' Period side panel '''
    #helpers.set_axis_distance(axP, epos, Trim=True)
    axP.set_xlabel(ax.get_xlabel())
    #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')

    if SNR:
        axP.hist(transit['P'], bins=xbins, color='C6', density=True)
    elif Model:
        axP.hist(pfm['P'], bins=xbins, color='0.5', density=True, log=True)
        axP.hist(pfm['P'],
                 bins=xbins,
                 color='k',
                 density=True,
                 log=True,
                 histtype='step',
                 zorder=10,
                 ls='-')
    axP.hist(sim['P'], bins=xbins, density=Model, log=Model, color=color)
    ''' Radius side panel'''
    #helpers.set_axis_size(axR, epos, Trim=True, In= epos.MassRadius)
    axR.set_ylabel(ax.get_ylabel())

    #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')

    if SNR:
        axR.hist(transit['Y'],
                 orientation='horizontal',
                 bins=ybins,
                 color='C6',
                 density=True)
    elif Model:
        axR.hist(pfm['R'],
                 orientation='horizontal',
                 bins=ybins,
                 color='0.5',
                 density=True,
                 log=True)
        axR.hist(pfm['R'],
                 orientation='horizontal',
                 bins=ybins,
                 color='k',
                 density=True,
                 log=True,
                 histtype='step',
                 zorder=10,
                 ls='-')
    axR.hist(sim['Y'],
             orientation='horizontal',
             bins=ybins,
             density=Model,
             log=Model,
             color=color)

    # labels
    if SNR:
        xpos = epos.MC_xvar[-1]
        ypos = axP.get_ylim()[-1] / 1.05
        axP.text(xpos, ypos, 'Detected ', color=color, ha='right', va='top')
        axP.text(xpos,
                 ypos / 1.3,
                 'Undetected ',
                 color='C6',
                 ha='right',
                 va='top')
    elif Model:
        xpos = ax.get_xlim()[-1]
        ypos = ax.get_ylim()[-1] / 1.05
        ax.text(xpos, ypos, 'Detected ', color=color, ha='right', va='top')
        ax.text(xpos,
                ypos / 1.3,
                'Undetected ',
                color='0.5',
                ha='right',
                va='top')

    #ax.legend(loc='lower left', shadow=False, prop={'size':14}, numpoints=1)
    helpers.save(plt, '{}output/periodradius.{}'.format(epos.plotdir, fsuffix))