25from time
import strftime
31from numpy
import floor
33import scipy.stats
as ss
35import matplotlib
as mpl
37from matplotlib
import pyplot
as plt
38from matplotlib
import colors
as mpl_colors
39from matplotlib
import cm
as mpl_cm
44from lalinference
import git_version
46__author__=
"Ben Aylott <benjamin.aylott@ligo.org>, Will M. Farr <will.farr@ligo.org>"
47__version__=
"git id %s"%git_version.id
48__date__= git_version.date
51oneDMenu=[
'mtotal',
'm1',
'm2',
'mchirp',
'mc',
'chirpmass',
'distance',
'distMPC',
'dist',
'iota',
'psi',
'eta',
'q',
'asym_massratio',
'spin1',
'spin2',
'a1',
'a2',
'phi1',
'theta1',
'phi2',
'theta2',
'costilt1',
'costilt2',
'costhetas',
'cosbeta',
'phi_orb',
'lambdat',
'dlambdat',
'lambda1',
'lambda2',
'lam_tilde',
'dlam_tilde',
'theta_jn',
'a1z',
'a2z'] + bppu.spininducedquadParams + bppu.snrParams + bppu.spinParams + bppu.cosmoParam + bppu.calParams + bppu.tigerParams + bppu.lorentzInvarianceViolationParams + bppu.qnmtestParams
53twoDGreedyMenu=[[
'mc',
'eta'],[
'mchirp',
'eta'],[
'chirpmass',
'eta'],[
'mc',
'q'],[
'mchirp',
'q'],[
'chirpmass',
'q'],[
'mc',
'asym_massratio'],[
'mchirp',
'asym_massratio'],[
'chirpmass',
'asym_massratio'],[
'm1',
'm2'],[
'mtotal',
'eta'],[
'distance',
'iota'],[
'dist',
'iota'],[
'dist',
'm1'],[
'ra',
'dec'],[
'dist',
'cos(iota)'],[
'phi_orb',
'iota'],[
'theta_jn',
'dist'],[
'spin1',
'spin2'],[
'spin1',
'mchirp'],[
'spin1',
'm1'],[
'a1',
'a2'],[
'a1',
'mchirp'],[
'a1',
'm1'],[
'tilt1',
'tilt2'],[
'tilt1',
'mchirp'],[
'tilt1',
'm1'],[
'a1z',
'a2z']]
57paramNameLatexMap = {
'm1':
'm_1',
'm2' :
'm_2',
'mtotal' :
r'M_{\rm tot}',
'mchirp' :
r'\mathcal{M}',
58 'mc':
r'\mathcal{M}',
'distance' :
'd',
'distMPC' :
'd',
'dist':
'd',
59 'iota':
r'\iota',
'psi':
r'\psi',
'eta':
r'\eta',
'asym_massratio':
'q',
'a1':
'a_1',
60 'a2':
'a_2',
'phi1':
r'\phi_1',
'phi2':
r'\phi_2',
'theta1':
r'\theta_1',
'theta2':
r'\theta_2',
61 'cos(tilt1)':
r'\cos t_1',
'cos(tilt2)':
r'\cos t_2',
'cos(thetas)':
r'\cos \theta_s',
62 'cosbeta':
r'\cos \beta',
'phi_orb':
r'\phi_{\rm orb}',
'cos(beta)':
r'\cos \beta',
63 'cos(iota)':
r'\cos \iota',
'tilt1':
r't_1',
'tilt2':
r't_2',
'ra':
r'\alpha',
'dec':
r'\delta',
64 'lambdat' :
r'\tilde{\Lambda}',
'dlambdat':
r'\delta \tilde{\Lambda}',
65 'lambda1' :
r'\lambda_1',
'lambda2':
r'\lambda_2',
66 'lam_tilde' :
r'\tilde{\Lambda}',
'dlam_tilde':
r'\delta \tilde{\Lambda}',
'dchiMinus2':
r'$d\chi_{-2}$',
'dchiMinus1':
r'$d\chi_{-1}$',
'dchi0':
r'\delta\chi_0',
'dchi1':
r'\delta\chi_1',
'dchi2':
r'\delta\chi_2',
'dchi3':
r'\delta\chi_3',
'dchi3S':
r'\delta\chi_{3S}',
'dchi3NS':
r'\delta\chi_{3NS}',
'dchi4':
r'\delta\chi_4',
'dchi4S':
r'\delta\chi_{4S}',
'dchi4NS':
r'\delta\chi_{4NS}',
'dchi5':
r'\delta\chi_5',
'dchi5S':
r'\delta\chi_{5S}',
'dchi5NS':
r'\delta\chi_{5NS}',
'dchi5l':
r'\delta\chi_{5l}',
'dchi5lS':
r'\delta\chi_{5lS}',
'dchi5lNS':
r'\delta\chi_{5lNS}',
'dchi6':
r'\delta\chi_6',
'dchi6S':
r'\delta\chi_{6S}',
'dchi6NS':
r'\delta\chi_{6NS}',
'dchi6l':
r'\delta\chi_{6l}',
'dchi7':
r'\delta\chi_7',
'dchi7S':
r'\delta\chi_{7S}',
'dchi7NS':
r'\delta\chi_{7NS}',
'dbeta2':
r'\delta\beta_2',
'dbeta3':
r'\delta\beta_3',
'dsigma2':
r'\delta\sigma_2',
'dsigma3':
r'\delta\sigma_3',
'dsigma4':
r'\delta\sigma_4',
'dbeta2':
r'\delta\beta_2',
'dbeta3':
r'\delta\beta_3' ,
'log10lambda_a':
r'$\log\lambda_{\mathbb{A}}$',
'log10lambda_eff':
r'$\log\lambda_{eff}$',
'log10livamp':
r'$\log \mathbb{A}$',
'lambda_a':
r'$\lambda_{\mathbb{A}}$',
'lambda_eff':
r'$\lambda_{eff}$',
'liv_amp':
r'$\mathbb{A}$',
'dquadmons':
r'\delta\kappa_s',
'dchikappaS':
r'\delta\chi_{kappa_{S}}',
'dchikappaA':
r'\delta\chi_{\kappa_{A}}',
67'domega220':
r'$d\omega_{220}$',
'dtau220':
r'$d\tau_{220}$',
68 'domega210':
r'$d\omega_{210}$',
'dtau210':
r'$d\tau_{210}$',
69 'domega330':
r'$d\omega_{330}$',
'dtau330':
r'$d\tau_{330}$',
70 'domega440':
r'$d\omega_{440}$',
'dtau440':
r'$d\tau_{440}$',
71 'domega550':
r'$d\omega_{550}$',
'dtau550':
r'$d\tau_{550}$',
72 'dc1':
r'$\delta c_1$',
'dc2':
r'$\delta c_2$',
'dc4':
r'$\delta c_4$',
'dcl':
r'$\delta c_l$',
'db1':
r'$\delta b_1$',
'db2':
r'$\delta b_2$',
'db3':
r'$\delta b_3$',
'db4':
r'$\delta b_4$'
76clTableParams = [
'mchirp',
'mc',
'chirpmass',
'eta',
'q',
'm1',
'm2',
'distance',
'distMPC',
'dist',
'cos(iota)',
'iota',
'theta_jn',
'psi',
'ra',
'dec',
'time',
'phase',
'a1',
'a2',
'costilt1',
'costilt2',
'dchiMinus2',
'dchiMinus1',
'dchi0',
'dchi1',
'dchi2',
'dchi3',
'dchi3S',
'dchi3NS',
'dchi4',
'dchi4S',
'dchi4NS',
'dchi5',
'dchi5S',
'dchi5NS',
'dchi5l',
'dchi5lS',
'dchi5lNS',
'dchi6',
'dchi6S',
'dchi6NS',
'dchi6l',
'dchi7',
'dchi7S',
'dchi7NS',
'dbeta2',
'dbeta3',
'dsigma2',
'dsigma3',
'dsigma4',
'dbeta2',
'dbeta3',
'log10lambda_eff',
'log10lambda_a',
'log10livamp',
'lambda_eff',
'lambda_a',
'liv_amp',
'dquadmons',
'dchikappaS',
'dchikappaA',
'domega220',
'dtau220',
'domega210',
'dtau210',
'domega330',
'dtau330',
'domega440',
'dtau440',
'domega550',
'dtau550',
'db1',
'db2',
'db3',
'db4',
'dc1',
'dc2',
'dc4',
'dcl']
80greedyBinSizes={
'mc':0.001,
'm1':0.1,
'm2':0.1,
'mass1':0.1,
'mass2':0.1,
'mtotal':0.1,
'eta':0.001,
'q':0.001,
'asym_massratio':0.001,
'iota':0.05,
'time':1e-4,
'distance':5.0,
'dist':1.0,
'mchirp':0.01,
'chirpmass':0.01,
'a1':0.02,
'a2':0.02,
'phi1':0.05,
'phi2':0.05,
'theta1':0.05,
'theta2':0.05,
'ra':0.05,
'dec':0.005,
'psi':0.1,
'cos(iota)':0.01,
'cos(tilt1)':0.01,
'cos(tilt2)':0.01,
'tilt1':0.05,
'tilt2':0.05,
'cos(thetas)':0.01,
'cos(beta)':0.01,
'phi_orb':0.2,
'inclination':0.05,
'theta_jn':0.05,
'spin1':0.02,
'spin2':0.02}
81for s
in bppu.snrParams:
82 greedyBinSizes[s]=0.02
83for s
in bppu.calParams:
84 greedyBinSizes[s]=0.02
85for s
in bppu.tigerParams + bppu.lorentzInvarianceViolationParams + bppu.qnmtestParams:
86 greedyBinSizes[s]=0.01
87for s
in bppu.spinParams:
88 greedyBinSizes[s]=0.02
89for s
in bppu.cosmoParam:
91greedyBinSizes[
'redshift']=0.005
94OneDconfidenceLevels=[0.9]
95TwoDconfidenceLevels=OneDconfidenceLevels
99twoDplots=[[
'm1',
'm2'],[
'mass1',
'mass2'],[
'RA',
'dec'],[
'ra',
'dec'],[
'cos(thetas)',
'cos(beta)'],[
'distance',
'iota'],[
'dist',
'iota'],[
'dist',
'cosiota'],[
'distance',
'cosiota'],[
'psi',
'iota'],[
'psi',
'distance'],[
'psi',
'phi0'],[
'dist',
'cos(iota)'],[
'phi_orb',
'iota'],[
'distance',
'inclination'],[
'dist',
'inclination'],[
'theta_jn',
'dist'],[
'spin1',
'spin2'],[
'spin1',
'mchirp'],[
'spin1',
'm1'],[
'a1',
'a2'],[
'a1',
'mchirp'],[
'a1',
'm1'],[
'tilt1',
'tilt2'],[
'tilt1',
'mchirp'],[
'tilt1',
'm1']]
100allowed_params=[
'mtotal',
'm1',
'm2',
'mchirp',
'mc',
'chirpmass',
'q',
'asym_massratio',
'distance',
'distMPC',
'dist',
'iota',
'psi',
'eta',
'ra',
'dec',
'a1',
'a2',
'spin1',
'spin2',
'phi1',
'theta1',
'phi2',
'theta2',
'cos(iota)',
'cos(tilt1)',
'cos(tilt2)',
'tilt1',
'tilt2',
'cos(thetas)',
'cos(beta)',
'phi_orb',
'inclination',
'logl',
'lambdat',
'dlambdat',
'lambda1',
'lambda2',
'lam_tilde',
'dlam_tilde',
'theta_jn',
'a1z',
'a2z',
'dquadmons',
'dquadmona',
'dquadmon1',
'dquadmon2']+bppu.snrParams + bppu.spinParams + bppu.cosmoParam + bppu.calParams + bppu.tigerParams
108 parsed_url=urlparse.urlparse(url)
109 url=urlparse.urljoin(parsed_url.geturl(),
'posterior_samples.dat')
112 opener = urllib2.build_opener(urllib2.HTTPCookieProcessor())
113 urllib2.install_opener(opener)
115 body={
'username':username,
'password':password}
116 txdata = urllib.urlencode(body)
117 txheaders = {
'User-agent' :
'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'}
119 req = urllib2.Request(parsed_url[0]+
'://'+parsed_url[1], txdata, txheaders)
121 resp = opener.open(req)
125 req = urllib2.Request(url, txdata, txheaders)
126 handle = opener.open(req)
128 f =
file(
'posterior_samples.dat',
'w')
133 print(
'We failed to open "%s".' % url)
134 if hasattr(e,
'code'):
135 print(
'We failed with error code - %s.' % e.code)
136 elif hasattr(e,
'reason'):
137 print(
"The error object has the following 'reason' attribute :", e.reason)
138 print(
"This usually means the server doesn't exist, is down, or we don't have an internet connection.")
141 print(
'Here are the headers of the page :')
149 for j
in L:
yield i, j
154 kerberos_args =
"--insecure -c /tmp/{0}_cookies -b /tmp/{0}_cookies --negotiate --user : --location-trusted".format(getpass.getuser()).split()
156 retcode=subprocess.call([
'curl'] + kerberos_args + [url] + args)
162 idx=common_output_table_header.index(test)
163 common_output_table_header[idx]=switch
164 print(
"Re-labelled %s -> %s"%(test,switch))
172 Plots a gaussian kernel density estimate for a set
173 of Posteriors onto the same axis.
175 @param list_of_pos_by_name: a dictionary of {name:Posterior}
class instances.
177 @param param: parameter name to compare
179 @param analyticPDF: Optional function to over-plot
184 myfig=plt.figure(figsize=(6,4.5),dpi=150)
186 list_of_pos=list(list_of_pos_by_name.values())
187 list_of_pos_names=list(list_of_pos_by_name.keys())
189 allmins=map(
lambda a: np.min(a[param].samples), list_of_pos)
190 allmaxes=map(
lambda a: np.max(a[param].samples), list_of_pos)
191 min_pos=np.min(allmins)
192 max_pos=np.max(allmaxes)
193 print(
'Found global min: %f, max: %f'%(min_pos,max_pos))
197 for name,posterior
in list_of_pos_by_name.items():
199 pos_samps=posterior[param].samples
200 if posterior[param].injval
is not None:
201 injvals.append(posterior[param].injval)
203 min_pos_temp=np.min(pos_samps)
204 max_pos_temp=np.max(pos_samps)
206 if min_pos_temp<min_pos:
208 if max_pos_temp>max_pos:
211 injpar=posterior[param].injval
213 gkdes[name]=posterior[param].gaussian_kde
216 ind=np.linspace(min_pos,max_pos,101)
219 for name,gkde
in gkdes.items():
220 kdepdf=gkde.evaluate(ind)
221 kdepdfs.append(kdepdf)
222 plt.plot(ind,np.transpose(kdepdf),label=name)
225 plt.xlabel(bppu.plot_label(param))
226 plt.xlim(min_pos,max_pos)
227 plt.ylabel(
'Probability Density')
233 print(
"Injection parameter is %f"%(float(injvals[0])))
235 if min(pos_samps)<injpar
and max(pos_samps)>injpar:
236 plt.plot([injpar,injpar],[0,
max(kdepdf)],
'r-.',scalex=
False,scaley=
False)
237 if analyticPDF
is not None:
238 plt.plot(ind,map(analyticPDF,ind),
'r')
246 Plots a gaussian kernel density estimate for a set
247 of Posteriors onto the same axis.
249 @param list_of_pos_by_name: a dict of Posterior
class instances indexed by name
251 @param param: parameter name to plot
253 @param cl: list of credible levels to plot
255 @param color_by_name: dict of colours indexed by name
257 @param cl_lines_flag: option to plot credible level lines
259 @param legend: matplotlib position
for legend
261 @param analyticPDF: Optional analytic function to over-plot
266 myfig=plt.figure(figsize=(6,4.5),dpi=150)
269 axes=plt.Axes(myfig,[0.15,0.15,0.6,0.76])
271 majorFormatterX=ScalarFormatter(useMathText=
True)
272 majorFormatterX.format_data=
lambda data:
'%.6g'%(data)
273 majorFormatterY=ScalarFormatter(useMathText=
True)
274 majorFormatterY.format_data=
lambda data:
'%.6g'%(data)
275 majorFormatterX.set_scientific(
True)
276 majorFormatterY.set_scientific(
True)
278 list_of_pos=list(list_of_pos_by_name.values())
279 list_of_pos_names=list(list_of_pos_by_name.keys())
281 allmins=map(
lambda a: np.min(a[param].samples), list_of_pos)
282 allmaxes=map(
lambda a: np.max(a[param].samples), list_of_pos)
283 min_pos=np.min(allmins)
284 max_pos=np.max(allmaxes)
291 posbins=np.linspace(min_pos,max_pos,50)
293 for name,posterior
in list_of_pos_by_name.items():
294 colour=color_by_name[name]
296 if posterior[param].injval:
297 injvals.append(posterior[param].injval)
300 n,bins=np.histogram(posterior[param].samples,bins=posbins,density=
True,new=
True)
302 n,bins=np.histogram(posterior[param].samples,bins=posbins,density=
True)
303 if min(bins)==
max(bins):
304 print(
'Skipping '+param)
307 if locmaxy>max_y: max_y=locmaxy
309 (n, bins, patches)=plt.hist(posterior[param].samples,bins=bins,histtype=
'step',label=name,density=
True,hold=
True,color=color_by_name[name])
310 patch_list.append(patches[0])
312 Nchars=
max(map(
lambda d:len(majorFormatterX.format_data(d)),axes.get_xticks()))
321 locatorX=mpl.ticker.MaxNLocator(nbins=Nticks)
322 locatorX.view_limits(bins[0],bins[-1])
323 axes.xaxis.set_major_locator(locatorX)
325 plt.xlim(min_pos,max_pos)
326 top_cl_intervals_list={}
327 pos_names=list(list_of_pos_by_name.keys())
330 for name,posterior
in list_of_pos_by_name.items():
332 cl_intervals=posterior[param].prob_interval([cl])
333 colour=color_by_name[name]
334 if cl_intervals[0]
is not None and cl_lines_flag:
336 plt.plot([cl_intervals[0][0],cl_intervals[0][0]],[0,max_y],color=colour,linestyle=
'--')
337 plt.plot([cl_intervals[0][1],cl_intervals[0][1]],[0,max_y],color=colour,linestyle=
'--')
339 print(
"MAX_Y",max_y,[cl_intervals[0][0],cl_intervals[0][0]],[cl_intervals[0][1],cl_intervals[0][1]])
340 top_cl_intervals_list[name]=(cl_intervals[0][0],cl_intervals[0][1])
343 pos_names.append(
str(
int(cl*100))+
'%')
344 patch_list.append(mpl.lines.Line2D(np.array([0.,1.]),np.array([0.,1.]),linestyle=
'--',color=
'black'))
347 plt.xlim(min_pos,max_pos)
348 if legend
is not None:
349 oned_legend=plt.figlegend(patch_list,pos_names,
'right')
350 for text
in oned_legend.get_texts():
351 text.set_fontsize(
'small')
352 plt.xlabel(bppu.plot_label(param))
353 plt.ylabel(
'Probability density')
357 print(
"Injection parameter is %f"%(float(injvals[0])))
360 plt.plot([injpar,injpar],[0,max_y],
'r-.',scalex=
False,scaley=
False,linewidth=4,label=
'Injection')
363 if analyticPDF
is not None:
364 plt.plot(posbins,map(analyticPDF,posbins),
'r')
365 return myfig,top_cl_intervals_list
369 """Returns a matrix of ks p-value tests between pairs of
370 posteriors on the 1D marginalized distributions for param.
"""
372 poss=list_of_pos_by_name.values()
376 matrix=np.zeros((N,N))
377 matrix[:,:]=float('nan')
381 for j
in range(i+1, N):
384 d,pvalue=ss.ks_2samp(pi[param].samples.flatten(), pj[param].samples.flatten())
394 Plots a gaussian kernel density estimate for a set
395 of Posteriors onto the same axis.
397 @param list_of_pos_by_name: a dict of Posterior
class instances indexed by name
399 @param param: name of parameter to plot
401 @param cl: list of confidence levels to show
403 @param color_by_name: dict of colours indexed by name
405 @param cl_lines_flag: Show confidence level lines
407 @param analyticCDF: Analytic CDF function to over-plot
409 @param legend: legend position to
pass to matplotlib
414 myfig=plt.figure(figsize=(6,4.5),dpi=150)
415 myfig.add_axes([0.15,0.15,0.6,0.76])
416 list_of_pos=list(list_of_pos_by_name.values())
417 list_of_pos_names=list(list_of_pos_by_name.keys())
420 allmins=map(
lambda a: np.min(a[param].samples), list_of_pos)
421 allmaxes=map(
lambda a: np.max(a[param].samples), list_of_pos)
422 min_pos=np.min(allmins)
423 max_pos=np.max(allmaxes)
428 posbins=np.linspace(min_pos,max_pos,50)
430 for name,posterior
in list_of_pos_by_name.items():
431 colour=color_by_name[name]
433 if posterior[param].injval:
434 injvals.append(posterior[param].injval)
437 n,bins=np.histogram(posterior[param].samples,bins=posbins,density=
True,new=
True)
439 n,bins=np.histogram(posterior[param].samples,bins=posbins,density=
True)
441 if min(bins)==
max(bins):
442 print(
'Skipping '+param)
445 (n, bins, patches)=plt.hist(posterior[param].samples,bins=bins,histtype=
'step',label=name,density=
True,hold=
True,color=color_by_name[name],cumulative=
'True')
447 patch_list.append(patches[0])
449 top_cl_intervals_list={}
450 pos_names=list(list_of_pos_by_name.keys())
453 for name,posterior
in list_of_pos_by_name.items():
455 cl_intervals=posterior[param].prob_interval([cl])
456 colour=color_by_name[name]
457 if cl_intervals[0]
is not None and cl_lines_flag:
459 plt.plot([cl_intervals[0][0],cl_intervals[0][0]],[0,max_y],color=colour,linestyle=
'--')
460 plt.plot([cl_intervals[0][1],cl_intervals[0][1]],[0,max_y],color=colour,linestyle=
'--')
462 print(
"MAX_Y",max_y,[cl_intervals[0][0],cl_intervals[0][0]],[cl_intervals[0][1],cl_intervals[0][1]])
463 top_cl_intervals_list[name]=(cl_intervals[0][0],cl_intervals[0][1])
466 pos_names.append(
str(
int(cl*100))+
'%')
467 patch_list.append(mpl.lines.Line2D(np.array([0.,1.]),np.array([0.,1.]),linestyle=
'--',color=
'black'))
470 plt.xlim(min_pos,max_pos)
473 oned_legend=plt.figlegend(patch_list,pos_names,
'right')
474 for text
in oned_legend.get_texts():
475 text.set_fontsize(
'small')
476 plt.xlabel(bppu.plot_label(param))
477 plt.ylabel(
'Cumulative Probability')
481 print(
"Injection parameter is %f"%(float(injvals[0])))
484 plt.plot([injpar,injpar],[0,max_y],
'r-.',scalex=
False,scaley=
False,linewidth=4,label=
'Injection')
485 if analyticCDF
is not None:
486 plt.plot(posbins,map(analyticCDF,posbins),
'r')
487 return myfig,top_cl_intervals_list
490def compare_bayes(outdir,names_and_pos_folders,injection_path,eventnum,username,password,reload_flag,clf,ldg_flag,contour_figsize=(4.5,4.5),contour_dpi=250,contour_figposition=[0.15,0.15,0.5,0.75],fail_on_file_err=
True,covarianceMatrices=
None,meanVectors=
None,Npixels2D=50):
494 if injection_path
is not None and os.path.exists(injection_path)
and eventnum
is not None:
495 eventnum=
int(eventnum)
496 from igwn_ligolw
import ligolw, lsctables, utils
497 injections = lsctables.SimInspiralTable.get_table(
498 utils.load_filename(injection_path))
499 if eventnum
is not None:
500 if(len(injections)<eventnum):
501 print(
"Error: You asked for event %d, but %s contains only %d injections" %(eventnum,injection_path,len(injections)))
504 injection=injections[eventnum]
507 analyticLikelihood =
None
508 if covarianceMatrices
and meanVectors:
509 analyticLikelihood = bppu.AnalyticLikelihood(covarianceMatrices, meanVectors)
510 peparser=bppu.PEOutputParser(
'common')
514 working_folder=os.getcwd()
515 for name,pos_folder
in names_and_pos_folders:
518 pos_folder_url=urlparse.urlparse(pos_folder)
519 pfu_scheme,pfu_netloc,pfu_path,pfu_params,pfu_query,pfu_fragment=pos_folder_url
521 if 'http' in pfu_scheme:
524 Retrieve a file over http(s).
526 downloads_folder=os.path.join(os.getcwd(),"downloads")
527 pos_folder_parse=urlparse.urlparse(pos_folder)
528 pfp_scheme,pfp_netloc,pfp_path,pfp_params,pfp_query,pfp_fragment=pos_folder_parse
529 head,tail=os.path.split(pfp_path)
530 if tail
is 'posplots.html' or tail:
533 pos_file_part=pfp_path
534 pos_file_url=urlparse.urlunsplit((pfp_scheme,pfp_netloc,os.path.join(pos_file_part,
'posterior_samples.dat'),
'',
''))
536 pos_file=os.path.join(os.getcwd(),downloads_folder,
"%s.dat"%name)
538 if not os.path.exists(pos_file):
542 if os.path.exists(pos_file):
544 if not os.path.exists(downloads_folder):
545 os.makedirs(downloads_folder)
548 elif pfu_scheme
is '' or pfu_scheme
is 'file':
549 pos_file=os.path.join(pos_folder,
'%s.dat'%name)
551 if not os.path.exists(pos_file):
552 print(
'%s does not exist, trying posterior_samples.dat'%(pos_file))
553 pos_file=os.path.join(pos_folder,
'posterior_samples.dat')
555 print(
"Unknown scheme for input data url: %s\nFull URL: %s"%(pfu_scheme,
str(pos_folder_url)))
558 print(
"Reading posterior samples from %s ..."%pos_file)
561 common_output_table_header,common_output_table_raw=peparser.parse(open(pos_file,
'r'))
563 print(
'Unable to read file '+pos_file)
577 if 'LI_MCMC' in name
or 'FU_MCMC' in name:
581 idx=common_output_table_header.index(
'iota')
582 print(
"Inverting iota!")
584 common_output_table_raw[:,idx]= np.pi*np.ones(len(common_output_table_raw[:,0])) - common_output_table_raw[:,idx]
599 print(
"Converting iota-> cos(iota)")
600 idx=common_output_table_header.index(
'iota')
601 common_output_table_header[idx]=
'cos(iota)'
602 common_output_table_raw[:,idx]=np.cos(common_output_table_raw[:,idx])
623 print(
"Converting thetas -> cos(thetas)")
624 idx=common_output_table_header.index(
'thetas')
625 common_output_table_header[idx]=
'cos(thetas)'
626 common_output_table_raw[:,idx]=np.cos(common_output_table_raw[:,idx])
631 print(
"Converting beta -> cos(beta)")
632 idx=common_output_table_header.index(
'beta')
633 common_output_table_header[idx]=
'cos(beta)'
634 common_output_table_raw[:,idx]=np.cos(common_output_table_raw[:,idx])
639 idx=common_output_table_header.index(
'f_ref')
640 injFrefs=np.unique(common_output_table_raw[:,idx])
641 if len(injFrefs) == 1:
642 injFref = injFrefs[0]
643 print(
"Using f_ref in results as injected value")
648 pos_temp=bppu.Posterior((common_output_table_header,common_output_table_raw),SimInspiralTableEntry=injection, injFref=injFref)
650 if 'a1' in pos_temp.names
and min(pos_temp[
'a1'].samples)[0] < 0:
651 pos_temp.append_mapping(
'spin1',
lambda a:a,
'a1')
653 pos_temp.append_mapping(
'a1',
lambda a:np.abs(a),
'spin1')
654 if 'a2' in pos_temp.names
and min(pos_temp[
'a2'].samples)[0] < 0:
655 pos_temp.append_mapping(
'spin2',
lambda a:a,
'a2')
657 pos_temp.append_mapping(
'a2',
lambda a:np.abs(a),
'spin2')
660 if 'm1' in pos_temp.names
and 'm2' in pos_temp.names:
661 print(
"Calculating total mass")
662 pos_temp.append_mapping(
'mtotal',
lambda m1,m2: m1+m2, [
'm1',
'm2'])
663 if 'mass1' in pos_temp.names
and 'mass2' in pos_temp.names:
664 print(
"Calculating total mass")
665 pos_temp.append_mapping(
'mtotal',
lambda m1,m2: m1+m2, [
'mass1',
'mass2'])
668 idx=common_output_table_header.index(
'm1')
670 idx2=common_output_table_header.index(
'm2')
672 if pos_temp[
'm1'].mean<pos_temp[
'm2'].mean:
673 print(
"SWAPPING MASS PARAMS!")
674 common_output_table_header[idx]=
'x'
675 common_output_table_header[idx2]=
'm1'
676 common_output_table_header[idx]=
'm2'
677 pos_temp=bppu.Posterior((common_output_table_header,common_output_table_raw),SimInspiralTableEntry=injection)
681 pos_list[name]=pos_temp
683 if common_params
is None:
684 common_params=pos_temp.names
686 set_of_pars = set(pos_temp.names)
687 common_params=list(set_of_pars.intersection(common_params))
689 print(
"Common parameters are %s"%
str(common_params))
691 if injection
is None and injection_path
is not None:
692 injections = SimInspiralUtils.ReadSimInspiralFromFiles([injection_path])
693 injection=bppu.get_inj_by_time(injections,pos_temp.means[
'time'])
694 if injection
is not None:
695 for pos
in pos_list.values():
696 pos.set_injection(injection)
698 set_of_pars = set(allowed_params)
699 common_params=list(set_of_pars.intersection(common_params))
701 print(
"Using parameters %s"%
str(common_params))
703 if not os.path.exists(os.path.join(os.getcwd(),
'results')):
704 os.makedirs(
'results')
706 if not os.path.exists(outdir):
709 pdfdir=os.path.join(outdir,
'pdfs')
710 if not os.path.exists(pdfdir):
715 if common_params
is not []
and common_params
is not None:
716 colorlst=bppu.__default_color_lst
718 if len(common_params)>1:
719 temp=copy.copy(common_params)
728 color_idx_max=len(names_and_pos_folders)
729 cmap_array=my_cm(np.array(range(cmap_size)))
731 hatches=[
'/',
'\\',
'|',
'-',
'+',
'x',
'o',
'O',
'.',
'*']
735 for name,infolder
in names_and_pos_folders:
737 color_by_name[name]=cmap_array[
int(floor(color_idx*cmap_size/color_idx_max)),:]
738 color_idx=(color_idx+1) % color_idx_max
739 hatches_by_name[name]=hatches[color_idx]
746 pplst_cond=(pplst
in twoDplots)
747 rpplst_cond=(rpplst
in twoDplots)
748 if pplst_cond
or rpplst_cond:
751 print(
'2d plots: building ',i,j)
752 greedy2Params={i:greedyBinSizes[i],j:greedyBinSizes[j]}
759 slinestyles=[
'solid',
'dashed',
'dashdot',
'dotted']
761 fig=bppu.plot_two_param_kde_greedy_levels(pos_list,greedy2Params,TwoDconfidenceLevels,color_by_name,figsize=contour_figsize,dpi=contour_dpi,figposition=contour_figposition,legend=ldg,line_styles=slinestyles,hatches_by_name=hatches_by_name,Npixels=Npixels2D)
762 if fig
is None:
continue
764 greedy2savepaths.append(
'%s-%s.png'%(pplst[0],pplst[1]))
765 fig.savefig(os.path.join(outdir,
'%s-%s.png'%(pplst[0],pplst[1])),bbox_inches=
'tight')
766 fig.savefig(os.path.join(pdfdir,
'%s-%s.pdf'%(pplst[0],pplst[1])),bbox_inches=
'tight')
772 confidence_levels=[{},{},{},{}]
773 confidence_uncertainty={}
774 for param
in common_params:
775 print(
"Plotting comparison for '%s'"%param)
777 cl_table_header=
'<table><th>Run</th>'
780 cl_table_min_max_str=
'<tr><td> Min | Max </td>'
782 for confidence_level
in OneDconfidenceLevels:
783 if analyticLikelihood:
784 pdf=analyticLikelihood.pdf(param)
785 cdf=analyticLikelihood.cdf(param)
789 cl_table_header+=
'<th colspan="2">%i%% (Lower|Upper)</th>'%(
int(100*confidence_level))
795 confidence_levels[level_index][param]=[]
797 for name,pos
in pos_list.items():
798 median=pos[param].median
799 low,high=cl_intervals[name]
801 confidence_levels[level_index][param].append((name,low,median,high))
803 level_index=level_index+1
806 for name,pos
in pos_list.items():
807 cl_bounds.append(cl_intervals[name])
808 poses.append(pos[param])
809 confidence_uncertainty[param]=bppu.confidence_interval_uncertainty(confidence_level, cl_bounds, poses)
812 if hist_fig
is not None:
813 save_path=os.path.join(outdir,
'%s_%i.png'%(param,
int(100*confidence_level)))
814 save_path_pdf=os.path.join(pdfdir,
'%s_%i.pdf'%(param,
int(100*confidence_level)))
816 plt.tight_layout(hist_fig)
817 plt.tight_layout(hist_fig2)
820 hist_fig.savefig(save_path,bbox_inches=
'tight')
821 hist_fig.savefig(save_path_pdf,bbox_inches=
'tight')
822 save_paths.append(save_path)
823 save_path=os.path.join(outdir,
'%s_%i_cum.png'%(param,
int(100*confidence_level)))
824 save_path_pdf=os.path.join(pdfdir,
'%s_%i_cum.pdf'%(param,
int(100*confidence_level)))
825 hist_fig2.savefig(save_path,bbox_inches=
'tight')
826 hist_fig2.savefig(save_path_pdf,bbox_inches=
'tight')
827 save_paths.append(save_path)
828 min_low,max_high=cl_intervals.values()[0]
829 for name,interval
in cl_intervals.items():
836 cl_table[name]+=
'<td>%s</td><td>%s</td>'%(low,high)
838 cl_table[name]=
'<td>%s</td><td>%s</td>'%(low,high)
839 cl_table_min_max_str+=
'<td>%s</td><td>%s</td>'%(min_low,max_high)
840 cl_table_str=cl_table_header
841 for name,row_contents
in cl_table.items():
842 cl_table_str+=
'<tr><td>%s<font color="%s"></font></td>'%(name,
str(mpl_colors.rgb2hex(color_by_name[name][0:3])))
844 cl_table_str+=row_contents+
'</tr>'
845 cl_table_str+=cl_table_min_max_str+
'</tr>'
846 cl_table_str+=
'</table>'
848 cl_uncer_str=
'<table> <th>Confidence Relative Uncertainty</th> <th>Confidence Fractional Uncertainty</th> <th>Confidence Percentile Uncertainty</th>\n'
849 cl_uncer_str+=
'<tr> <td> %g </td> <td> %g </td> <td> %g </td> </tr> </table>'%(confidence_uncertainty[param][0], confidence_uncertainty[param][1], confidence_uncertainty[param][2])
853 N=ks_matrix.shape[0]+1
856 ks_table_str=
'<table><th colspan="%d"> K-S test p-value matrix </th>'%N
859 ks_table_str+=
'<tr> <td> -- </td> '
860 for name,pos
in pos_list.items():
861 ks_table_str+=
'<td> %s </td>'%name
862 ks_table_str+=
'</tr>'
865 for i
in range(len(pos_list)):
866 ks_table_str+=
'<tr> <td> %s </td>'%(pos_list.keys()[i])
867 for j
in range(len(pos_list)):
869 ks_table_str+=
'<td> -- </td>'
870 elif ks_matrix[i,j] < 0.05:
872 ks_table_str+=
'<td> <b> %g </b> </td>'%ks_matrix[i,j]
874 ks_table_str+=
'<td> %g </td>'%ks_matrix[i,j]
876 ks_table_str+=
'</tr>'
878 ks_table_str+=
'</table>'
880 oned_data[param]=(save_paths,cl_table_str,ks_table_str,cl_uncer_str)
883 max_logls = [[name,
max(pos._logL)]
for name,pos
in pos_list.items()]
884 dics = [pos.DIC
for name, pos
in pos_list.items()]
886 return greedy2savepaths,oned_data,confidence_uncertainty,confidence_levels,max_logls,dics
889 """Outputs a LaTeX table of parameter and run medians and confidence levels."""
890 outfile=open(os.path.join(outpath,
'confidence_table.tex'),
'w')
891 for level_index
in range(len(OneDconfidenceLevels)):
892 params=list(clevels[level_index].keys())
895 for param
in clTableParams:
897 for name,low,med,high
in clevels[level_index][param]:
898 if name
in clevels_by_name:
899 clevels_by_name[name].append((param,low,med,high))
901 clevels_by_name[name] = [(param,low,med,high)]
904 outfile.write(
'confidence level %1.3g\n'%OneDconfidenceLevels[level_index])
905 outfile.write(
r'\begin{tabular}{|l||')
906 for param
in clTableParams:
911 outfile.write(
r'\hline ')
912 for param
in clTableParams:
914 tparam=paramNameLatexMap.get(param,param)
915 outfile.write(
r'& $%s$ '%tparam)
916 outfile.write(
'\\\\ \n \\hline \\hline ')
918 for name,levels
in clevels_by_name.items():
920 for param,low,med,high
in levels:
921 outfile.write(
r' & $%0.5g^{%0.5g}_{%0.5g}$ '%(med,high,low))
922 outfile.write(
'\\\\ \n')
924 outfile.write(
'\\hline \n \\end{tabular}')
926 outfile.write(
'\n\n')
931 """Outputs a LaTeX table of parameter and run medians and confidence levels."""
932 outfile=open(os.path.join(outpath,
'confidence_table.dat'),
'w')
933 for level_index
in range(len(OneDconfidenceLevels)):
934 params=list(clevels[level_index].keys())
937 for param
in clTableParams:
939 for name,low,med,high
in clevels[level_index][param]:
940 if name
in clevels_by_name:
941 clevels_by_name[name].append((param,low,med,high))
943 clevels_by_name[name] = [(param,low,med,high)]
946 outfile.write(
'%1.3g\t'%OneDconfidenceLevels[level_index])
947 for param
in clTableParams:
949 tparam=paramNameLatexMap.get(param,param)
950 outfile.write(
'%s\t'%param)
953 for name,levels
in clevels_by_name.items():
955 for param,low,med,high
in levels:
956 outfile.write(
'\t%6.6g - %6.6g'%(low,high))
964 outfile=open(os.path.join(outpath,
'confidence_uncertainty.dat'),
'w')
966 params=list(cluncertainty.keys())
967 uncer=list(cluncertainty.values())
969 outfile.write(
'# Uncertainty in confidence levels.\n')
970 outfile.write(
'# First row is relative uncertainty (wrt to parameter mean).\n')
971 outfile.write(
'# Second row is fractional uncertainty (wrt to combined conf interval).\n')
972 outfile.write(
'# Third row is percentile uncertainty (wrt combined samples).\n')
975 outfile.write(
str(param) +
' ')
978 rel = np.array([d[0]
for d
in uncer])
979 fracs = np.array([d[1]
for d
in uncer])
980 quants = np.array([d[2]
for d
in uncer])
982 np.savetxt(outfile, np.reshape(rel, (1, -1)))
983 np.savetxt(outfile, np.reshape(fracs, (1, -1)))
984 np.savetxt(outfile, np.reshape(quants, (1,-1)))
988if __name__ ==
'__main__':
989 from optparse
import OptionParser
990 parser=OptionParser()
991 parser.add_option(
"-o",
"--outpath", dest=
"outpath",help=
"Make page and plots in DIR.", metavar=
"DIR")
992 parser.add_option(
"-p",
"--pos",dest=
"pos_list",action=
"append",help=
"Path to folders containing output of cbcBayesPostProc.")
993 parser.add_option(
"-n",
"--name",dest=
"names",action=
"append",help=
"Name of posterior result e.g. followupMCMC 2.5PN (optional)")
994 parser.add_option(
"-i",
"--inj",dest=
"inj",help=
"Path of injection XML containing SimInspiralTable (optional).")
995 parser.add_option(
"-e",
"--eventnum",dest=
"eventnum",help=
"Sim ID of injection described in injection XML (optional).")
996 parser.add_option(
"-u",dest=
"username",help=
"User name for https authenticated content (optional).")
997 parser.add_option(
"-x",dest=
"password",help=
"Password for https authenticated content (optional).")
998 parser.add_option(
"--reload",dest=
"reload_flag",action=
"store_true",help=
"Re-download all pos files (optional).")
999 parser.add_option(
"--hide-cl-lines",dest=
"clf",action=
"store_false",default=
True,help=
"Hide confidence level lines on 1D plots for clarity (optional).")
1000 parser.add_option(
"--contour-dpi",dest=
"cdpi",default=250,help=
"DPI for contour plot (optional).")
1001 parser.add_option(
"--contour-width",dest=
"cw",default=7,help=
"Width (in inches) of contour plots (optional).")
1002 parser.add_option(
"--contour-height",dest=
"ch",default=6,help=
"Height (in inches) of contour plots (optional).")
1003 parser.add_option(
"--contour-plot-width",dest=
"cpw",default=0.5,help=
"Relative width of plot element 0.15<width<1 (optional).")
1004 parser.add_option(
"--contour-plot-height",dest=
"cph",default=0.76,help=
"Relative height of plot element 0.15<width<1 (optional).")
1005 parser.add_option(
"--no-legend",dest=
"ldg_flag",action=
"store_false",default=
True,help=
"Hide legend (optional).")
1006 parser.add_option(
"--ignore-missing-files",dest=
"readFileErr",default=
False,action=
"store_true",help=
"Do not fail when files are missing (optional).")
1007 parser.add_option(
"-c",
"--covarianceMatrix",dest=
"covarianceMatrices",action=
"append",default=
None,help=
"CSV file containing covariance (must give accompanying mean vector CSV. Can add more than one matrix.")
1008 parser.add_option(
"-m",
"--meanVectors",dest=
"meanVectors",action=
"append",default=
None,help=
"Comma separated list of locations of the multivariate gaussian described by the correlation matrix. First line must be list of params in the order used for the covariance matrix. Provide one list per covariance matrix.")
1009 parser.add_option(
"--no2D",dest=
"no2d",action=
"store_true",default=
False,help=
"Disable 2D plots")
1010 parser.add_option(
"--npixels-2d",dest=
"npixels_2d",action=
"store",type=
"int",default=50,help=
"Number of pixels on a side of the 2D plots (default 50)",metavar=
"N")
1012 (opts,args)=parser.parse_args()
1014 if opts.outpath
is None:
1015 print(
"No output directory specified. Output will be saved to PWD : %s"%os.getcwd())
1018 outpath=opts.outpath
1020 if opts.pos_list
is None:
1021 print(
"No input paths given!")
1024 if opts.names
is None:
1025 print(
"No names given, making some up!")
1027 for i
in range(len(opts.pos_list)):
1028 names.append(
str(i))
1032 if len(opts.pos_list)!=len(names):
1033 print(
"Either add names for all posteriors or dont put any at all!")
1036 names,pos_list = zip(*sorted(zip(names,opts.pos_list)))
1042 greedy2savepaths,oned_data,confidence_uncertainty,confidence_levels,max_logls,dics=
compare_bayes(outpath,zip(names,pos_list),opts.inj,opts.eventnum,opts.username,opts.password,opts.reload_flag,opts.clf,opts.ldg_flag,contour_figsize=(float(opts.cw),float(opts.ch)),contour_dpi=
int(opts.cdpi),contour_figposition=[0.15,0.15,float(opts.cpw),float(opts.cph)],fail_on_file_err=
not opts.readFileErr,covarianceMatrices=opts.covarianceMatrices,meanVectors=opts.meanVectors,Npixels2D=
int(opts.npixels_2d))
1053 compare_page=bppu.htmlPage(
'Compare PDFs (single event)',css=bppu.__default_css_string)
1055 param_section=compare_page.add_section(
'Meta')
1057 param_section_write=
'<div><p>This comparison was created from the following analyses</p>'
1058 param_section_write+=
'<table border="1">'
1059 param_section_write+=
'<th>Analysis</th> <th> max(log(L)) </th> <th> DIC </th>'
1060 for (name,logl_max), dic
in zip(max_logls, dics):
1061 param_section_write+=
'<tr><td><a href="%s">%s</a></td> <td>%g</td> <td>%.1f</td></tr>'%(dict(zip(names,pos_list))[name],name,logl_max,dic)
1062 param_section_write+=
'</table></div>'
1064 param_section.write(param_section_write)
1065 param_section.write(
'<div><p><a href="confidence_table.tex">LaTeX table</a> of medians and confidence levels.</p></div>')
1068 param_section=compare_page.add_section(
'1D marginal posteriors')
1070 for param_name,data
in oned_data.items():
1071 param_section.h3(param_name)
1072 save_paths,cl_table_str,ks_table_str,cl_uncer_str=data
1074 for save_path
in save_paths:
1075 head,plotfile=os.path.split(save_path)
1076 param_section.write(
'<img src="%s"/>'%
str(plotfile))
1078 param_section.write(cl_table_str)
1079 param_section.write(cl_uncer_str)
1080 param_section.write(ks_table_str)
1082 if greedy2savepaths:
1084 param_section=compare_page.add_section(
'2D greedy bin histograms')
1085 for plot_path
in greedy2savepaths:
1086 temp,param_name=os.path.split(plot_path)
1087 param_name=param_name.split(
'.')[0]
1088 head,plotfile=os.path.split(plot_path)
1089 param_section.write(
'<img src="%s"/>'%
str(plotfile))
1093 compare_page_footer=compare_page.add_section(
'')
1094 compare_page_footer.p(
'Produced using cbcBayesCompPos.py at '+strftime(
"%Y-%m-%d %H:%M:%S")+
' .')
1096 cc_args=copy.deepcopy(sys.argv)
1100 user_idx=cc_args.index(
'-u')
1101 cc_args[user_idx+1]=
'<LIGO username>'
1106 pass_idx=cc_args.index(
'-x')
1107 cc_args[pass_idx+1]=
'<LIGO password>'
1112 for cc_arg
in cc_args:
1113 cc_args_str+=cc_arg+
' '
1115 compare_page_footer.p(
'Command line: %s'%cc_args_str)
1116 compare_page_footer.p(git_version.verbose_msg)
1119 resultspage=open(os.path.join(outpath,
'index.html'),
'w')
1120 resultspage.write(
str(compare_page))
def open_url_curl(url, args=[])
def compute_ks_pvalue_matrix(list_of_pos_by_name, param)
Returns a matrix of ks p-value tests between pairs of posteriors on the 1D marginalized distributions...
def compare_bayes(outdir, names_and_pos_folders, injection_path, eventnum, username, password, reload_flag, clf, ldg_flag, contour_figsize=(4.5, 4.5), contour_dpi=250, contour_figposition=[0.15, 0.15, 0.5, 0.75], fail_on_file_err=True, covarianceMatrices=None, meanVectors=None, Npixels2D=50)
def compare_plots_one_param_pdf(list_of_pos_by_name, param, analyticPDF=None)
Plots a gaussian kernel density estimate for a set of Posteriors onto the same axis.
def output_confidence_uncertainty(cluncertainty, outpath)
def output_confidence_levels_dat(clevels, outpath)
Outputs a LaTeX table of parameter and run medians and confidence levels.
def output_confidence_levels_tex(clevels, outpath)
Outputs a LaTeX table of parameter and run medians and confidence levels.
def open_url(url, username, password)
def compare_plots_one_param_line_hist_cum(list_of_pos_by_name, param, cl, color_by_name, cl_lines_flag=True, analyticCDF=None, legend='auto')
Plots a gaussian kernel density estimate for a set of Posteriors onto the same axis.
def compare_plots_one_param_line_hist(list_of_pos_by_name, param, cl, color_by_name, cl_lines_flag=True, legend='right', analyticPDF=None)
Plots a gaussian kernel density estimate for a set of Posteriors onto the same axis.
def test_and_switch_param(common_output_table_header, test, switch)