def rp_dilutedpdf(pop,r=1,dr=0.1,fb=0.4,n=1e4,fig=None,plot=True,allpdfs=False): #add contrast curves here simr = rand.normal(size=n)*dr + r mainpdf = utils.gaussian(r,dr,norm=1-fb) inds = rand.randint(size(pop.dkepmag),size=n) diluted1 = utils.kde(dilutedradius(simr,pop.dkepmag[inds]),norm=fb/2,adaptive=False) diluted2 = utils.kde(dilutedradius(simr,-pop.dkepmag[inds]),norm=fb/2,adaptive=False) diluted2.renorm((fb/2)**2/quad(diluted2,0,20)[0]) totpdf = mainpdf + diluted1 + diluted2 if plot: pu.setfig(fig) rs = arange(0,2*r,0.01) p.plot(rs,totpdf(rs)) if allpdfs: p.plot(rs,mainpdf(rs)) p.plot(rs,diluted1(rs)) p.plot(rs,diluted2(rs)) if allpdfs: return totpdf,mainpdf,diluted1,diluted2 else: return totpdf
def plot(self, fig=None, **kwargs): setfig(fig) plt.plot(self.rs, self.dmags, **kwargs) plt.title('%s band contrast curve' % self.band) plt.gca().invert_yaxis() plt.xlabel('Separation [arcsec]') plt.ylabel('$\Delta %s$' % self.band)
def plot_ccs(self,fig=None): plu.setfig(fig) for cc in self.ccs: cc.plot(fig=0,label=cc.name) plt.ylabel('$\Delta$ mag') if len(self.ccs) % 2 == 0: plt.gca().invert_yaxis() plt.title(self.name) plt.legend()
def fpp_of_b(fig=None, symbol='+', dbin=0.05, plot_points=True): plu.setfig(fig) cands = FPPDATA[OK_CANDIDATE] #xbins = np.arange(0,1.01,dbin) xbins = np.array([0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 0.95, 1]) xvals = xbins * 0 yvals = xbins * 0 yerrs_p = xbins * 0 yerrs_m = xbins * 0 for i in np.arange(len(xbins)): lo = xbins[i] if i == len(xbins) - 1: hi = np.inf else: hi = xbins[i + 1] inbin = (cands['b'] >= lo) & (cands['b'] < hi) xvals[i] = lo + dbin / 2 data = cands[inbin]['fpp'] yvals[i] = data.median() yerrs_p[i] = data.quantile(0.84) - data.median() yerrs_m[i] = data.median() - data.quantile(0.16) ax = plt.subplot(111) ax.set_yscale('log') if plot_points: n = len(cands) ax.plot(cands['b'] + rand.normal(size=n) * 0.01, cands['fpp'] * (1 + rand.normal(size=n) * 0.01), 'o', ms=1, mew=1, alpha=0.5) ax.errorbar(xvals, yvals, yerr=[np.abs(yerrs_m), np.abs(yerrs_p)], fmt='o', color='k', lw=3) ax.plot(xvals, yvals, 'wo', ms=15) ax.plot(xvals, yvals, 'ko', ms=13) ax.plot(xvals, yvals, 'co', ms=12) ax.set_ylim((1e-4, 1)) ax.set_xlim((0, 1.1)) plt.xlabel('Impact Parameter') plt.ylabel('False Positive Probability')
def plothist(self,fig=None,**kwargs): """Plots a histogram of samples using provided bins. Parameters ---------- fig : None or int Parameter passed to `setfig`. kwargs Keyword arguments passed to `plt.hist`. """ setfig(fig) plt.hist(self.samples,bins=self.bins,**kwargs)
def plot(self,minval=None,maxval=None,fig=None,log=False, npts=500,**kwargs): """ Plots distribution. Parameters ---------- minval : float,optional minimum value to plot. Required if minval of Distribution is `-np.inf`. maxval : float, optional maximum value to plot. Required if maxval of Distribution is `np.inf`. fig : None or int, optional Parameter to pass to `setfig`. If `None`, then a new figure is created; if a non-zero integer, the plot will go to that figure (clearing everything first), if zero, then will overplot on current axes. log : bool, optional If `True`, the x-spacing of the points to plot will be logarithmic. npoints : int, optional Number of points to plot. kwargs Keyword arguments are passed to plt.plot Raises ------ ValueError If finite lower and upper bounds are not provided. """ if minval is None: minval = self.minval if maxval is None: maxval = self.maxval if maxval==np.inf or minval==-np.inf: raise ValueError('must have finite upper and lower bounds to plot. (use minval, maxval kws)') if log: xs = np.logspace(np.log10(minval),np.log10(maxval),npts) else: xs = np.linspace(minval,maxval,npts) setfig(fig) plt.plot(xs,self(xs),**kwargs) plt.xlabel(self.name) plt.ylim(ymin=0,ymax=self(xs).max()*1.2)
def fpp_of_b(fig=None,symbol='+',dbin=0.05,plot_points=True): plu.setfig(fig) cands = FPPDATA[OK_CANDIDATE] #xbins = np.arange(0,1.01,dbin) xbins = np.array([0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,0.95,1]) xvals = xbins*0 yvals = xbins*0 yerrs_p = xbins*0 yerrs_m = xbins*0 for i in np.arange(len(xbins)): lo = xbins[i] if i==len(xbins)-1: hi = np.inf else: hi = xbins[i+1] inbin = (cands['b'] >= lo) & (cands['b'] < hi) xvals[i] = lo + dbin/2 data = cands[inbin]['fpp'] yvals[i] = data.median() yerrs_p[i] = data.quantile(0.84) - data.median() yerrs_m[i] = data.median() - data.quantile(0.16) ax = plt.subplot(111) ax.set_yscale('log') if plot_points: n = len(cands) ax.plot(cands['b']+rand.normal(size=n)*0.01, cands['fpp']*(1+rand.normal(size=n)*0.01), 'o',ms=1,mew=1,alpha=0.5) ax.errorbar(xvals,yvals,yerr=[np.abs(yerrs_m),np.abs(yerrs_p)], fmt='o',color='k',lw=3) ax.plot(xvals,yvals,'wo',ms=15) ax.plot(xvals,yvals,'ko',ms=13) ax.plot(xvals,yvals,'co',ms=12) ax.set_ylim((1e-4,1)) ax.set_xlim((0,1.1)) plt.xlabel('Impact Parameter') plt.ylabel('False Positive Probability')
def cand_piechart(fig=None): plu.setfig(fig) badstar = ISCANDIDATE & ((FPPDATA['error']=='AllWithinRocheError') | \ (FPPDATA['error']=='EmptyPopulationError') | \ (FPPDATA['error']=='NoStellarPropsError')) nophot = ISCANDIDATE & ((FPPDATA['error'] == 'MissingKOIError') | \ (FPPDATA['error'] == 'BadPhotometryError')) badmcmc = ISCANDIDATE & (FPPDATA['error'] == 'MCMCNotConvergedError') companion = ISCANDIDATE & (FPPDATA['error'] == 'DetectedCompanionError') offtarget = ISCANDIDATE & HASFPP & ~ONTARGET good = ISCANDIDATE & HASFPP & ONTARGET n_badstar = badstar.sum() n_nophot = nophot.sum() n_mcmc = badmcmc.sum() n_comp = companion.sum() n_offtarget = offtarget.sum() n_good = good.sum() labels = [ 'Stellar properties (%i)' % n_badstar, 'Bad/missing photometry (%i)' % n_nophot, 'MCMC not converged (%i)' % n_mcmc, 'Transit off target (%i)' % n_offtarget, 'AO-detected companion (%i)' % n_comp, 'Calculated FPPs (%i)' % n_good ] sizes = [n_badstar, n_nophot, n_mcmc, n_offtarget, n_comp, n_good] ax = plt.axes([0.2, 0.2, 0.6, 0.6]) explode = [0, 0, 0, 0, 0, 0.1] colors = ['y', 'c', 'm', 'b', 'r', 'g'] #ax.pie(sizes,explode=explode,shadow=True,startangle=90,colors=colors) ax.pie(sizes, explode=explode, shadow=True, colors=colors) plt.legend(labels, loc='lower right', bbox_to_anchor=[1., 0.0], prop={'size': 12}) ax.axis('equal')
def plot(self, fig=None, plot_trap=False, name=False, trap_color='g', trap_kwargs=None, **kwargs): setfig(fig) plt.plot(self.ts, self.fs, '.', **kwargs) if plot_trap and hasattr(self, 'trapfit'): if trap_kwargs is None: trap_kwargs = {} plt.plot(self.ts, traptransit(self.ts, self.trapfit), color=trap_color, **trap_kwargs) if name is not None: if type(name) == type(''): text = name else: text = self.name plt.annotate(text, xy=(0.1, 0.1), xycoords='axes fraction', fontsize=22) if hasattr(self, 'depthfit') and not np.isnan(self.depthfit[0]): lo = 1 - 3 * self.depthfit[0] hi = 1 + 2 * self.depthfit[0] else: lo = 1 hi = 1 sig = qstd(self.fs, 0.005) hi = max(hi, self.fs.mean() + 7 * sig) lo = min(lo, self.fs.mean() - 7 * sig) logging.debug('lo={}, hi={}'.format(lo, hi)) plt.ylim((lo, hi)) plt.xlabel('time [days]') plt.ylabel('Relative flux')
def all_piechart(fig=None): plu.setfig(fig) nconf = ISCONFIRMED.sum() ncand = ISCANDIDATE.sum() nfp = ISFP.sum() labels = ['Confirmed (%i)' % nconf,'Candidate (%i)' % ncand, 'False Positive (%i)' % nfp] sizes = [nconf,ncand,nfp] #explode = (0.05,0.05,0.05) explode = (0.,0.1,0.) colors = ['g','y','r'] ax = plt.axes([0.2,0.2,0.6,0.6]) #ax.pie(sizes,explode=explode,labels=labels,shadow=True,startangle=90) ax.pie(sizes,explode=explode,labels=labels,shadow=True) ax.axis('equal')
def cand_piechart(fig=None): plu.setfig(fig) badstar = ISCANDIDATE & ((FPPDATA['error']=='AllWithinRocheError') | \ (FPPDATA['error']=='EmptyPopulationError') | \ (FPPDATA['error']=='NoStellarPropsError')) nophot = ISCANDIDATE & ((FPPDATA['error'] == 'MissingKOIError') | \ (FPPDATA['error'] == 'BadPhotometryError')) badmcmc = ISCANDIDATE & (FPPDATA['error'] == 'MCMCNotConvergedError') companion = ISCANDIDATE & (FPPDATA['error'] == 'DetectedCompanionError') offtarget = ISCANDIDATE & HASFPP & ~ONTARGET good = ISCANDIDATE & HASFPP & ONTARGET n_badstar = badstar.sum() n_nophot = nophot.sum() n_mcmc = badmcmc.sum() n_comp = companion.sum() n_offtarget = offtarget.sum() n_good = good.sum() labels = ['Stellar properties (%i)' % n_badstar, 'Bad/missing photometry (%i)' % n_nophot, 'MCMC not converged (%i)' % n_mcmc, 'Transit off target (%i)' % n_offtarget, 'AO-detected companion (%i)' % n_comp, 'Calculated FPPs (%i)' % n_good] sizes = [n_badstar,n_nophot,n_mcmc,n_offtarget, n_comp,n_good] ax = plt.axes([0.2,0.2,0.6,0.6]) explode = [0,0,0,0,0,0.1] colors = ['y','c','m','b','r','g'] #ax.pie(sizes,explode=explode,shadow=True,startangle=90,colors=colors) ax.pie(sizes,explode=explode,shadow=True,colors=colors) plt.legend(labels,loc='lower right',bbox_to_anchor=[1.,0.0],prop={'size':12}) ax.axis('equal')
def plot(self,minval=None,maxval=None,fig=None,log=False,npts=500,plotprior=True,**kwargs): if minval is None: minval = self.minval if maxval is None: maxval = self.maxval if maxval==np.inf or minval==-np.inf: raise ValueError('must have finite upper and lower bounds to plot. (set minval, maxval kws)') if log: xs = np.logspace(np.log10(minval),np.log10(maxval),npts) else: xs = np.linspace(minval,maxval,npts) plu.setfig(fig) plt.plot(xs,self(xs),**kwargs) if plotprior: lhoodnorm = quad(self.lhood,self.minval,self.maxval)[0] plt.plot(xs,self.lhood(xs)/lhoodnorm,ls=':') plt.xlabel(self.name) plt.ylim(ymin=0)
def all_piechart(fig=None): plu.setfig(fig) nconf = ISCONFIRMED.sum() ncand = ISCANDIDATE.sum() nfp = ISFP.sum() labels = [ 'Confirmed (%i)' % nconf, 'Candidate (%i)' % ncand, 'False Positive (%i)' % nfp ] sizes = [nconf, ncand, nfp] #explode = (0.05,0.05,0.05) explode = (0., 0.1, 0.) colors = ['g', 'y', 'r'] ax = plt.axes([0.2, 0.2, 0.6, 0.6]) #ax.pie(sizes,explode=explode,labels=labels,shadow=True,startangle=90) ax.pie(sizes, explode=explode, labels=labels, shadow=True) ax.axis('equal')
def summary_plot(self,fig=None,title=''): setfig(fig) ax1 = plt.subplot(221) ax2 = plt.subplot(222) ax3 = plt.subplot(223) plt.sca(ax1) self.plot(fig=0) plt.yticks([]) plt.xlabel('Cos(I)',labelpad=2) plt.sca(ax2) self.veq_dist.R_dist.plot(fig=0) plt.yticks([]) plt.xlabel('Stellar Raidus',labelpad=2) plt.xlim(xmin=0) plt.sca(ax3) self.veq_dist.plot(fig=0,label='V_eq') plt.yticks([]) self.vsini_dist.plot(fig=0,label='VsinI') #plt.legend() plt.xlabel('Rotational Velocity [km/s]') plt.annotate('Veq',xy=(0.05,0.8),color='b', xycoords='axes fraction', fontsize=14) plt.annotate('VsinI',xy=(0.05,0.67),color='g', xycoords='axes fraction', fontsize=14) plt.subplots_adjust(hspace=.4) plt.annotate('$P = {:.2f}\pm{:.2f}$d'.format(self.veq_dist.Prot_dist.mu, self.veq_dist.Prot_dist.sig), xy=(0.5,0.3),xycoords='figure fraction',fontsize=24) plt.suptitle(title)
def FPPsummary(self, fig=None, figsize=(10, 8), folder='.', saveplot=False, starinfo=True, siginfo=True, priorinfo=True, constraintinfo=True, tag=None, simple=False, figformat='png'): if simple: starinfo = False siginfo = False priorinfo = False constraintinfo = False setfig(fig, figsize=figsize) # three pie charts priors = [] lhoods = [] Ls = [] for model in self.popset.modelnames: priors.append(self.prior(model)) lhoods.append(self.lhood(model)) if np.isnan(priors[-1]): raise ValueError('{} prior is nan; priorfactors={}'.format( model, self.priorfactors)) Ls.append(priors[-1] * lhoods[-1]) priors = np.array(priors) lhoods = np.array(lhoods) Ls = np.array(Ls) logging.debug('modelnames={}'.format(self.popset.modelnames)) logging.debug('priors={}'.format(priors)) logging.debug('lhoods={}'.format(lhoods)) #colors = ['b','g','r','m','c'] nmodels = len(self.popset.modelnames) colors = [cm.jet(1. * i / nmodels) for i in range(nmodels)] legendprop = {'size': 11} ax1 = plt.axes([0.15, 0.45, 0.35, 0.43]) try: plt.pie(priors / priors.sum(), colors=colors) labels = [] for i, model in enumerate(self.popset.modelnames): labels.append('%s: %.1e' % (model, priors[i])) plt.legend(labels, bbox_to_anchor=(-0.25, -0.1), loc='lower left', prop=legendprop) plt.title('Priors') except: msg = 'Error calculating priors.\n' for i, mod in enumerate(self.popset.shortmodelnames): msg += '%s: %.1e' % (model, priors[i]) plt.annotate(msg, xy=(0.5, 0.5), xy_coords='axes fraction') ax2 = plt.axes([0.5, 0.45, 0.35, 0.43]) try: plt.pie(lhoods / lhoods.sum(), colors=colors) labels = [] for i, model in enumerate(self.popset.modelnames): labels.append('%s: %.1e' % (model, lhoods[i])) plt.legend(labels, bbox_to_anchor=(1.25, -0.1), loc='lower right', prop=legendprop) plt.title('Likelihoods') except: msg = 'Error calculating lhoods.\n' for i, mod in enumerate(self.popset.shortmodelnames): msg += '%s: %.1e' % (model, lhoods[i]) plt.annotate(msg, xy=(0.5, 0.5), xy_coords='axes fraction') ax3 = plt.axes([0.3, 0.03, 0.4, 0.5]) plt.pie(Ls / Ls.sum(), colors=colors) labels = [] #for i,model in enumerate(['eb','heb','bgeb','bgpl','pl']): for i, model in enumerate(self.popset.modelnames): labels.append('%s: %.3f' % (model, Ls[i] / Ls.sum())) plt.legend(labels, bbox_to_anchor=(1.6, 0.44), loc='right', prop={'size': 14}, shadow=True) plt.annotate('Final Probability', xy=(0.5, -0.01), ha='center', xycoords='axes fraction', fontsize=18) """ #starpars = 'Star parameters used\nin simulations' starpars = '' if 'M' in self['heb'].stars.keywords and 'DM_P' in self.keywords: starpars += '\n$M/M_\odot = %.2f^{+%.2f}_{-%.2f}$' % (self['M'],self['DM_P'],self['DM_N']) else: starpars += '\n$(M/M_\odot = %.2f \pm %.2f)$' % (self['M'],0) #this might not always be right? if 'DR_P' in self.keywords: starpars += '\n$R/R_\odot = %.2f^{+%.2f}_{-%.2f}$' % (self['R'],self['DR_P'],self['DR_N']) else: starpars += '\n$R/R_\odot = %.2f \pm %.2f$' % (self['R'],self['DR']) if 'FEH' in self.keywords: if 'DFEH_P' in self.keywords: starpars += '\n$[Fe/H] = %.2f^{+%.2f}_{-%.2f}$' % (self['FEH'],self['DFEH_P'],self['DFEH_N']) else: starpars += '\n$[Fe/H] = %.2f \pm %.2f$' % (self['FEH'],self['DFEH']) for kw in self.keywords: if re.search('-',kw): try: starpars += '\n$%s = %.2f (%.2f)$ ' % (kw,self[kw],self['COLORTOL']) except TypeError: starpars += '\n$%s = %s (%.2f)$ ' % (kw,self[kw],self['COLORTOL']) #if 'J-K' in self.keywords: # starpars += '\n$J-K = %.2f (%.2f)$ ' % (self['J-K'],self['COLORTOL']) #if 'G-R' in self.keywords: # starpars += '\n$g-r = %.2f (%.2f)$' % (self['G-R'],self['COLORTOL']) if starinfo: plt.annotate(starpars,xy=(0.03,0.91),xycoords='figure fraction',va='top') #p.annotate('Star',xy=(0.04,0.92),xycoords='figure fraction',va='top') priorpars = r'$f_{b,short} = %.2f$ $f_{trip} = %.2f$' % (self.priorfactors['fB']*self.priorfactors['f_Pshort'], self.priorfactors['ftrip']) if 'ALPHA' in self.priorfactors: priorpars += '\n'+r'$f_{pl,bg} = %.2f$ $\alpha_{pl,bg} = %.1f$' % (self.priorfactors['fp'],self['ALPHA']) else: priorpars += '\n'+r'$f_{pl,bg} = %.2f$ $\alpha_1,\alpha_2,r_b = %.1f,%.1f,%.1f$' % \ (self.priorfactors['fp'],self['bgpl'].stars.keywords['ALPHA1'], self['bgpl'].stars.keywords['ALPHA2'], self['bgpl'].stars.keywords['RBREAK']) rbin1,rbin2 = self['RBINCEN']-self['RBINWID'],self['RBINCEN']+self['RBINWID'] priorpars += '\n$f_{pl,specific} = %.2f, \in [%.2f,%.2f] R_\oplus$' % (self.priorfactors['fp_specific'],rbin1,rbin2) priorpars += '\n$r_{confusion} = %.1f$"' % sqrt(self.priorfactors['area']/pi) if self.priorfactors['multboost'] != 1: priorpars += '\nmultiplicity boost = %ix' % self.priorfactors['multboost'] if priorinfo: plt.annotate(priorpars,xy=(0.03,0.4),xycoords='figure fraction',va='top') sigpars = '' sigpars += '\n$P = %s$ d' % self['P'] depth,ddepth = self.trsig.depthfit sigpars += '\n$\delta = %i^{+%i}_{-%i}$ ppm' % (depth*1e6,ddepth[1]*1e6,ddepth[0]*1e6) dur,ddur = self.trsig.durfit sigpars += '\n$T = %.2f^{+%.2f}_{-%.2f}$ h' % (dur*24.,ddur[1]*24,ddur[0]*24) slope,dslope = self.trsig.slopefit sigpars += '\n'+r'$T/\tau = %.1f^{+%.1f}_{-%.1f}$' % (slope,dslope[1],dslope[0]) sigpars += '\n'+r'$(T/\tau)_{max} = %.1f$' % (self.trsig.maxslope) if siginfo: plt.annotate(sigpars,xy=(0.81,0.91),xycoords='figure fraction',va='top') #p.annotate('${}^a$Not used for FP population simulations',xy=(0.02,0.02), # xycoords='figure fraction',fontsize=9) """ constraints = 'Constraints:' for c in self.popset.constraints: try: constraints += '\n %s' % self['heb'].constraints[c] except KeyError: constraints += '\n %s' % self['beb'].constraints[c] if constraintinfo: plt.annotate(constraints, xy=(0.03, 0.22), xycoords='figure fraction', va='top', color='red') odds = 1. / self.FPP() if odds > 1e6: fppstr = 'FPP: < 1 in 1e6' else: fppstr = 'FPP: 1 in %i' % odds plt.annotate('$f_{pl,V} = %.3f$\n%s' % (self.fpV(), fppstr), xy=(0.7, 0.02), xycoords='figure fraction', fontsize=16, va='bottom') plt.suptitle(self.trsig.name, fontsize=22) #if not simple: # plt.annotate('n = %.0e' % self.n,xy=(0.5,0.85),xycoords='figure fraction', # fontsize=14,ha='center') if saveplot: if tag is not None: plt.savefig('%s/FPPsummary_%s.%s' % (folder, tag, figformat)) else: plt.savefig('%s/FPPsummary.%s' % (folder, figformat)) plt.close()
def fpp_summaryplot(data=FPPDATA,fig=None,symbol='o',ms=1,color='k', markrs=[1,1.5,2,2.5,3,4,10],nbins=None,alpha=0.5, title=None,hlineval=0.01,labelpos=(0.75,0.15), summarylabel=True,erasedata=None,titlefontsize=20, titlexy=(0.25,0.85),showcc=False,cc_symbol='o', cc_ms=2,cc_color='b',rao_color='c',prelim=True, **kwargs): plu.setfig(fig) inds = np.argsort(data['rp']) ypts = data['FPP'][inds].clip(1e-4,1) xpts = np.arange(len(data)) plt.semilogy(ypts,symbol,ms=ms,color=color,alpha=alpha,**kwargs) if showcc: hascc = data['AO'][inds] != 'None' has_rao = data['RAO'][inds] plt.semilogy(xpts[np.where(hascc & ~has_rao)],ypts[hascc & ~has_rao], cc_symbol,ms=cc_ms,color=cc_color, mec=cc_color) plt.semilogy(xpts[np.where(has_rao)],ypts[has_rao],cc_symbol, ms=cc_ms,color=rao_color, mec=rao_color) if erasedata is not None: plt.semilogy(ypts,symbol,ms=ms,color=color,alpha=alpha,**kwargs) plt.ylim(ymin=8e-5) xmax = inds.max()+1 plt.xlim(xmax=xmax) plt.xticks([]) ax = plt.gca() plt.axhline(hlineval,color='k',lw=2) for r in markrs: i = np.argmin(np.absolute(data['rp'][inds]-r)) ax.axvline(i,color='k',lw=3,ls=':') ax.annotate(r'%.1f' % r,xy=(float(i)/xmax,-0.05),xycoords='axes fraction',ha='center', annotation_clip=False,fontsize=14) if nbins is not None: N = len(ypts) binsize = N/nbins xbins = [] ybins = [] yerrs = [] for i in range(nbins): xbins.append((xpts[i*binsize:(i+1)*binsize]).mean()) ybins.append(np.median(ypts[i*binsize:(i+1)*binsize])) yerrs.append((ypts[i*binsize:(i+1)*binsize]).std()) #plt.errorbar(xbins,ybins,yerr=yerrs,color=linecolor,fmt='o',ms=5) plt.plot(xbins,ybins,'wo',ms=15) plt.plot(xbins,ybins,'ko',ms=13) plt.plot(xbins,ybins,'ro',ms=12) plt.xlabel('Planet Radius [$R_\oplus$]',labelpad=30) plt.ylabel('False Positive Probability') if title is not None: plt.annotate(title,xy=titlexy,xycoords='axes fraction', fontsize=titlefontsize, bbox=dict(boxstyle='round',fc='w',lw=2),ha='center') if summarylabel: N = float(len(data)) gt_50pct = (data['fpp'] > 0.5).sum() lt_1pct = (data['fpp'] < 0.01).sum() #lt_03pct = (data['fpp'] < 0.003).sum() plt.annotate('%i/%i FPP > 50%%\n%i/%i FPP < 1%%' % (gt_50pct,N,lt_1pct,N),xy=labelpos,xycoords='axes fraction', fontsize=15,bbox=dict(boxstyle='round',fc='w',lw=2),ha='center') if prelim: plt.annotate('Preliminary',xy=(0.05,0.12),xycoords='axes fraction', fontsize=14,color='r',rotation=-30, bbox=dict(boxstyle='round',fc='w',lw=2,color='r'),va='center')
def fpp_summaryplot(data=FPPDATA, fig=None, symbol='o', ms=1, color='k', markrs=[1, 1.5, 2, 2.5, 3, 4, 10], nbins=None, alpha=0.5, title=None, hlineval=0.01, labelpos=(0.75, 0.15), summarylabel=True, erasedata=None, titlefontsize=20, titlexy=(0.25, 0.85), showcc=False, cc_symbol='o', cc_ms=2, cc_color='b', rao_color='c', prelim=True, **kwargs): plu.setfig(fig) inds = np.argsort(data['rp']) ypts = data['FPP'][inds].clip(1e-4, 1) xpts = np.arange(len(data)) plt.semilogy(ypts, symbol, ms=ms, color=color, alpha=alpha, **kwargs) if showcc: hascc = data['AO'][inds] != 'None' has_rao = data['RAO'][inds] plt.semilogy(xpts[np.where(hascc & ~has_rao)], ypts[hascc & ~has_rao], cc_symbol, ms=cc_ms, color=cc_color, mec=cc_color) plt.semilogy(xpts[np.where(has_rao)], ypts[has_rao], cc_symbol, ms=cc_ms, color=rao_color, mec=rao_color) if erasedata is not None: plt.semilogy(ypts, symbol, ms=ms, color=color, alpha=alpha, **kwargs) plt.ylim(ymin=8e-5) xmax = inds.max() + 1 plt.xlim(xmax=xmax) plt.xticks([]) ax = plt.gca() plt.axhline(hlineval, color='k', lw=2) for r in markrs: i = np.argmin(np.absolute(data['rp'][inds] - r)) ax.axvline(i, color='k', lw=3, ls=':') ax.annotate(r'%.1f' % r, xy=(float(i) / xmax, -0.05), xycoords='axes fraction', ha='center', annotation_clip=False, fontsize=14) if nbins is not None: N = len(ypts) binsize = N / nbins xbins = [] ybins = [] yerrs = [] for i in range(nbins): xbins.append((xpts[i * binsize:(i + 1) * binsize]).mean()) ybins.append(np.median(ypts[i * binsize:(i + 1) * binsize])) yerrs.append((ypts[i * binsize:(i + 1) * binsize]).std()) #plt.errorbar(xbins,ybins,yerr=yerrs,color=linecolor,fmt='o',ms=5) plt.plot(xbins, ybins, 'wo', ms=15) plt.plot(xbins, ybins, 'ko', ms=13) plt.plot(xbins, ybins, 'ro', ms=12) plt.xlabel('Planet Radius [$R_\oplus$]', labelpad=30) plt.ylabel('False Positive Probability') if title is not None: plt.annotate(title, xy=titlexy, xycoords='axes fraction', fontsize=titlefontsize, bbox=dict(boxstyle='round', fc='w', lw=2), ha='center') if summarylabel: N = float(len(data)) gt_50pct = (data['fpp'] > 0.5).sum() lt_1pct = (data['fpp'] < 0.01).sum() #lt_03pct = (data['fpp'] < 0.003).sum() plt.annotate('%i/%i FPP > 50%%\n%i/%i FPP < 1%%' % (gt_50pct, N, lt_1pct, N), xy=labelpos, xycoords='axes fraction', fontsize=15, bbox=dict(boxstyle='round', fc='w', lw=2), ha='center') if prelim: plt.annotate('Preliminary', xy=(0.05, 0.12), xycoords='axes fraction', fontsize=14, color='r', rotation=-30, bbox=dict(boxstyle='round', fc='w', lw=2, color='r'), va='center')
def plothist(self,fig=None,**kwargs): plu.setfig(fig) plt.hist(self.samples,bins=self.bins,**kwargs)
def plot_posterior(x,px,name='x',ax=None,fig=None,conf=0.683,shortest=True,median=False,justline=False,shade=True,label=True,\ labelpos=(0.05,0.7),horizontal=False,axislabels=True,fmt='%.2f',conflabel=True,evidence=False): """Plots a 1-D posterior pdf described by x and px. Default is to put a vertical dotted line at the best fit value, to shade the shortest 68% confidence interval, and to annotate the graph with the numerical result. Inputs: x : vector abcissa values px : probability or likelihood as function of x; must be same size as x, not necessarily normalized Optional Inputs: name : variable name; for use in labels ax : matplotlib 'axis' object; in case you want to specify the plot to be on a specific axis object fig : the number of the figure to put the plot on; empty creates a new figure if 'ax' is not specified conf : confidence level for shade region shortest: make False for symmetric confidence region median : make True to draw vertical line at median value instead of max. likelihood justline: make True to plot just the posterior pdf; nothing else shade : make False to turn off shading label : make False to turn off the label w/ the value and error bars labelpos: the position to place the label, in axis coordinates horizontal: make True to make the plot horizontal (e.g. for a 2d posterior plot) axislabels: make False to turn off fmt: format string for label conflabel: make False to not include the confidence level in the label Results: Makes a nifty plot Dependencies: -numpy,matplotlib -conf_interval """ if ax == None: plu.setfig(fig) lo,hi = conf_interval(x,px,conf,shortest=shortest) if ax==None: ax = plt.gca() if not median: best = x[argmax(px)] else: cum = cumsum(px) cdf = cum/max(cum) best = x[argmin(abs(cdf-0.5))] loerr = best-lo hierr = hi - best if not horizontal: ax.plot(x,px,'k') if axislabels: ax.set_xlabel('$ %s $' % name,fontsize=16) ax.set_ylabel('$ p(%s) $' % name,fontsize=16) else: ax.plot(px,x,'k') if axislabels: ax.set_xlabel('$ p(%s) $' % name,fontsize=16) ax.set_ylabel('$ %s $' % name,fontsize=16) if justline: return if not horizontal: ax.axvline(best,color='k',ls=':') else: ax.axhline(best,color='k',ls=':') w = where((x > lo) & (x < hi)) if shade: if not horizontal: ix = x[w] iy = px[w] verts = [(lo,0)] + zip(ix,iy) + [(hi,0)] else: ix = px[w] iy = x[w] verts = [(0,lo)] + zip(ix,iy) + [(0,hi)] poly = plt.Polygon(verts,facecolor='0.8',edgecolor='k') ax.add_patch(poly) beststr = fmt % best hierrstr = fmt % hierr loerrstr = fmt % loerr if hierrstr == loerrstr: resultstr = '$%s=%s \pm %s$' % (name,beststr,hierrstr) else: resultstr = '$ %s =%s^{+%s}_{-%s}$' % (name,beststr,hierrstr,loerrstr) if conflabel: #print conf resultstr += '\n\n(%i%% confidence)' % int(conf*100) if evidence: resultstr += '\n\nevidence = %.2e' % trapz(px,x) if label: ax.annotate(resultstr,xy=labelpos,xycoords='axes fraction',fontsize=16)
def plot_posterior2d(x,y,L,name1='x',name2='y',confs=[0.68,0.95,0.99],conf=0.683,ax=None,fig=None,\ labelpos1=(0.6,0.5),labelpos2=(0.3,0.8),fmt1='%.2f',fmt2='%.2f',evidence=False,\ evidencelabelpos=(0.05,0.85),labels=True,shade=True,justline=False, symmetric=False,justcontour=False): """Plots contour plot of 2D posterior surface, with given contour levels, including marginalized 1D posteriors of the two individual parameters. Inputs: x,y : vectors that represent the two directions of the parameter grid L : 2D grid of likelihood values; not necessarily normalized Optional Inputs: confs : list of confidence contours to plot name1,name2 : names of variables ax : matplotlib 'axis' object, in case you want to specify fig : the number of the figure to put the plot on; creates a new figure if not specified labelpos1,labelpos2 : where to put the labels on the 1D posterior plots fmt1, fmt2 : format strings for labels Results: Makes a nifty plot Dependencies: --numpy, matplotlib --plot_posterior, conf_interval, conf2d """ plu.setfig(fig) if ax == None: ax = plt.gca() if symmetric: foo1,foo2 = meshgrid(x,y) L[where(foo1-foo2 < 0)] = 0 px = trapz(L,y,axis=0) py = trapz(L,x,axis=1) X,Y = meshgrid(x,y) plt.clf() if not justcontour: left, width = 0.1, 0.6 bottom, height = 0.1, 0.6 bottom_h = left_h = left+width #+0.05 nullfmt = matplotlib.ticker.NullFormatter() rect_center = [left, bottom, width, height] rect_top = [left, bottom_h, width, 0.2] rect_right = [left_h, bottom, 0.2, height] axcenter = plt.axes(rect_center) axtop = plt.axes(rect_top) axright = plt.axes(rect_right) else: axcenter = plt.gca() levels = zeros(len(confs)) i=0 for c in confs: levels[i] = conf2d(x,y,L,c) i+=1 axcenter.contour(X,Y,L,lw=1,levels=levels) w = where(L==max(L.ravel())) axcenter.plot(x[w[1]],y[w[0]],'k+') axcenter.set_xlabel('$%s$' % name1,fontsize=16) axcenter.set_ylabel('$%s$' % name2,fontsize=16) if not justcontour: plot_posterior(x,px,name1,conf=conf,ax=axtop,axislabels=False,labelpos=labelpos1,fmt=fmt1, conflabel=False,label=labels,shade=shade,justline=justline,fig=0) plot_posterior(y,py,name2,conf=conf,ax=axright,horizontal=True,axislabels=False,labelpos=labelpos2, fmt=fmt2,conflabel=False,label=labels,shade=shade,justline=justline,fig=0) axtop.yaxis.set_major_formatter(nullfmt) axtop.xaxis.set_major_formatter(nullfmt) axright.xaxis.set_major_formatter(nullfmt) axright.yaxis.set_major_formatter(nullfmt) if evidence: axcenter.annotate('evidence = %.2e' % trapz2d(L,x,y),xy=evidencelabelpos,xycoords='axes fraction')