27from igwn_ligolw
import lsctables
28from igwn_ligolw
import utils
31import matplotlib.pyplot
as pp
36import scipy.stats
as ss
38from lalinference
import bayespputils
as bppu
40posterior_name_to_latex_name = {
45 'mc' :
r'$\mathcal{M}$',
50 'phi_orb' :
r'$\phi_\mathrm{orb}$',
55 'theta1' :
r'$\theta_1$',
56 'theta2' :
r'$\theta_2$',
59 'phi12':
r'$\phi_{12}$',
60 'phi_jl':
r'$\phi_{jl}$',
61 'theta_jn':
r'$\theta_{jn}$',
64 'dchiMinus2':
r'$d\chi_{-2}$',
65 'dchiMinus1':
r'$d\chi_{-1}$',
70 'dchi3S':
r'$d\chi_{3S}$',
71 'dchi3NS':
r'$d\chi_{3NS}$',
73 'dchi4S':
r'$d\chi_{4S}$',
74 'dchi4NS':
r'$d\chi_{4NS}$',
76 'dchi5S':
r'$d\chi_{5S}$',
77 'dchi5NS':
r'$d\chi_{5NS}$',
78 'dchi5l':
r'$d\chi_{5l}$',
79 'dchi5lS':
r'$d\chi_{5lS}$',
80 'dchi5lNS':
r'$d\chi_{5lNS}$',
82 'dchi6S':
r'$d\chi_{6S}$',
83 'dchi6NS':
r'$d\chi_{6NS}$',
84 'dchi6l':
r'$d\chi_{6l}$',
86 'dchi7S':
r'$d\chi_{7S}$',
87 'dchi7NS':
r'$d\chi_{7NS}$',
88 'dsigma1':
r'$d\sigma_1$',
89 'dsigma2':
r'$d\sigma_2$',
90 'dsigma3':
r'$d\sigma_3$',
91 'dsigma4':
r'$d\sigma_4$',
92 'dalpha1':
r'$d\alpha_1$',
93 'dalpha2':
r'$d\alpha_2$',
94 'dalpha3':
r'$d\alpha_3$',
95 'dalpha4':
r'$d\alpha_4$',
96 'dalpha5':
r'$d\alpha_5$',
97 'dbeta1':
r'$d\beta_1$',
98 'dbeta2':
r'$d\beta_2$',
99 'dbeta3':
r'$d\beta_3$',
100 'dbeta4':
r'$d\beta_4$',
101 'dchikappaS':
r'$d\chi_{\kappa_{S}}$',
102 'dchikappaA':
r'$d\chi_{\kappa_{A}}$'
106 """Returns the fraction of samples, ``xs``, that fall below the value
110 nbelow = np.sum(xs < x)
112 return float(nbelow)/float(xs.shape[0])
114def pp_plot(ps, title=None, outfile=None):
115 """Generates a p-p plot for the given ps.
117 :param ps: The p-values whose cumulative distribution is to be
120 :param title: An (optional) title
for the plot.
122 :param outfile: An (optional) basename
for the plot file; both
123 basename.png
and basename.pdf will be created.
127 ps = np.atleast_1d(ps)
129 ys = np.zeros(ps.shape[0]+2)
130 ys[:-1] = np.linspace(0, 1, ps.shape[0]+1)
132 xs = np.zeros(ps.shape[0]+2)
136 pp.figure(figsize=(6,6), dpi=100)
139 syn_ps = np.random.uniform(size=ps.shape[0])
140 syn_xs = np.zeros(ps.shape[0]+2)
142 syn_xs[1:-1] = np.sort(syn_ps)
143 pp.plot(syn_xs, ys,
'-', color=
'0.9')
145 pp.plot(xs, ys,
'-k')
146 pp.plot(ys, ys,
'--k')
150 if title
is not None:
153 if outfile
is not None:
154 pp.savefig(outfile +
'.png')
155 pp.savefig(outfile +
'.pdf')
158 """Returns the K-S p-value for the test of the given ``ps`` against a
159 uniform distribution on [0,1].
162 stat, p = ss.kstest(ps, lambda x: x)
167 """Returns a bppu posterior sample object
169 peparser=bppu.PEOutputParser('common')
170 commonResultsObj=peparser.parse(open(f,
'r'))
171 data = bppu.Posterior(commonResultsObj,SimInspiralTableEntry=injrow,injFref=100.0)
174 data.extend_posterior()
175 except Exception
as e:
179def output_html(outdir, ks_pvalues, injnum,skypp=False):
180 """Outputs the HTML page summarizing the results.
183 table_row_template = string.Template("""<tr> <td> ${name} </td>
185 <td> <img src="${name}.png" alt=
"${name} p-p plot" width=
"300" height=
"300" /> </td> <td> <a href=
"${name}.png">PNG</a> <a href=
"${name}.pdf">PDF</a> <a href=
"${name}-ps.dat">p-values</a> </td> </tr>
189 html_template = string.Template("""<!DOCTYPE html>
192 <title> LALInference P-P Plots </title>
197 <p>This page was generated with the output of ${injnum} simulations.</p>
202 <th> Parameter </th> <th> K-S p-value </th> <th> p-p Plot </th> <th> Links </th>
216 if os.path.isdir(os.path.join(outdir,
'prior')):
217 links+=
'<li><a href="prior/">Prior Samples used in this test</a>'
218 if os.path.isdir(os.path.join(outdir,
'injections')):
219 links+=
'<li><a href="injections/">Posteriors for each injection</a>'
223 for par, pv
in ks_pvalues.items():
224 tablerows.append(table_row_template.substitute(name=par, pvalue=
str(pv)))
225 tablerows =
'\n'.join(tablerows)
230 skysub=
'<tr> <td> sky </td> <td> See Plot </td> <td> <img src="sky_p-p.png" alt="sky p-p plot" width="300" height="300" /> </td> <td> <a href="sky_p-p.png">PNG</a> <a href="sky_p-p.pdf">PDF</a></td> </tr>'
232 html = html_template.substitute(tablerows=tablerows, injnum=
str(injnum), linkstr=links,skypp=skysub)
234 with open(os.path.join(outdir,
'index.html'),
'w')
as out:
237if __name__ ==
'__main__':
238 USAGE=
'''%prog [options] posfile1.dat posfile2.dat ...
239 Generate PP analysis for a set of injections. posfiles must be
in same order
as injections.
'''
240 parser = optparse.OptionParser(USAGE)
241 parser.add_option('--injXML', action=
'store', type=
'string', dest=
'injxml',
242 help=
'sim_inspiral XML file for injections')
243 parser.add_option(
'--outdir', action=
'store', type=
'string',
244 help=
'output directory')
246 parser.add_option(
'--postsamples', action=
'store', type=
'string',
247 default=
'posterior_samples.dat',
248 help=
'filename for posterior samples files')
250 parser.add_option(
'--par', action=
'append', default=[], type=
'string',
251 help=
'parameter names for the p-p plot')
252 parser.add_option(
'--skyPPfolder', action=
'store',dest=
'skypp',type=
'string',default=
None,help=
'Path to folder containing png/pdf with 2D skyarea PP plots')
254 (options, args) = parser.parse_args()
256 injs = lsctables.SimInspiralTable.get_table(utils.load_filename(options.injxml))
258 if options.par == []:
259 parameters = [
'm1',
'm2',
'mc',
'eta',
'q',
'theta_jn',
'a1',
'a2',
'tilt1',
'tilt2',
'phi12',
'phi_jl',
'ra',
'dec',
'distance',
'time',
'phi_orb',
'psi']
261 parameters = options.par
264 os.mkdir(options.outdir)
271 for index,posfile
in enumerate(posfiles):
279 for par
in parameters:
281 samples = psamples[par].samples
282 true_value=psamples[par].injval
285 pvalues[par].append(p)
294 for par, ps
in pvalues.items():
295 print(
"Trying to create the plot for",par,
".")
297 pp_plot(ps, title=posterior_name_to_latex_name[par], outfile=os.path.join(options.outdir, par))
300 np.savetxt(os.path.join(options.outdir, par +
'-ps.dat'), np.reshape(ps, (-1, 1)))
302 print(
"Could not create the plot for",par,
"!!!")
305 if options.skypp
is not None:
307 if os.path.isdir(options.skypp):
308 for i
in [
'png',
'pdf']:
309 if os.path.isfile(os.path.join(options.skypp,
'p-p.%s'%i)):
310 inf=os.path.join(os.path.realpath(options.skypp),
'p-p.%s'%i)
311 outf=os.path.join(options.outdir,
'sky_p-p.%s'%i)
312 os.system(
'cp %s %s'%(inf,outf))
315 print(
"could not find %s\n"%os.path.join(options.skypp,
'p-p.%s'%i))
317 print(
"skyPPfolder %s doesn't seem to be a valid folder or cannot be read. Skipping skyPP plot\n"%os.path.realpath(options.skypp))
def read_posterior_samples(f, injrow)
Returns a bppu posterior sample object.
def pp_plot(ps, title=None, outfile=None)
Generates a p-p plot for the given ps.
def pp_kstest_pvalue(ps)
Returns the K-S p-value for the test of the given ps against a uniform distribution on [0,...
def output_html(outdir, ks_pvalues, injnum, skypp=False)
Outputs the HTML page summarizing the results.
def fractional_rank(x, xs)
Returns the fraction of samples, xs, that fall below the value x.