Loading [MathJax]/extensions/TeX/AMSsymbols.js
LALInference 4.1.9.1-b246709
All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Modules Pages
lalinference_merge_posteriors.py
Go to the documentation of this file.
1##python
2
3# resample posteriors (C) John Veitch, 2015
4
5from numpy import vstack,log
6from optparse import OptionParser
7import sys
8from lalinference import bayespputils as bppu
9
10from lalinference.nest2pos import draw_posterior, draw_N_posterior
11
12usage='''%prog [-N NPOS]-o output.dat -p pos1.dat -w weight1 [-p pos2.dat -w weight2 ...]
13%prog takes a list of posterior files and weights and draws samples from the combined,
14reweighted distribution
15'''
16
17def load_data(filename,header=None):
18 peparser=bppu.PEOutputParser('common')
19 commonObj=peparser.parse(open(filename,'r'),info=[header,None])
20 pos=bppu.Posterior(commonObj)
21 return pos
22
23if __name__=='__main__':
24 parser=OptionParser(usage)
25 parser.add_option('-o','--output',action='store',type='string',default=None,help='output file',metavar='output.dat')
26 parser.add_option('-p','--posterior',action='append',type='string',default=[],metavar='pos.dat',help='posterior input file')
27 parser.add_option('-w','--weight',action='append',type='float',default=[],metavar='NUM',help='weight of an input file')
28 parser.add_option('-N','--npos',action='store',default=None,metavar='NPOS',help='Optional number of posterior samples to draw')
29 parser.add_option('--verbose',action='store_true',default=False,help='Prints additional information')
30 (opts,args) = parser.parse_args()
31
32 if len(opts.posterior)==0:
33 sys.stderr.write('No input files given\n')
34 sys.exit(1)
35 if len(opts.weight) != len(opts.posterior):
36 sys.stderr.write('Error: must specify same number of weights and posteriors\n')
37 sys.exit(1)
38
39 # Create posterior samples for each input file
40 datas=map(load_data,opts.posterior)
41 weights=[]
42 for d,w in zip(datas,opts.weight):
43 theseweights = (log(w) + logl + logp for logl,logp in zip(d['logl'].samples,d['logprior'].samples))
44 weights.extend(theseweights)
45 bigdata=vstack([d.samples()[0] for d in datas])
46
47 # Call reweighting function
48 if opts.npos is not None:
49 merged=draw_N_posterior(bigdata,weights,opts.npos,verbose=opts.verbose)
50 else:
51 merged=draw_posterior(bigdata,weights,verbose=opts.verbose)
52
53 outObj=bppu.Posterior((datas[0].names,merged))
54
55 # Write output file
56 if opts.output is not None:
57 outObj.write_to_file(opts.output)
def draw_N_posterior(data, log_wts, N, verbose=False)
Draw N samples from the input data, weighted by log_wt.
Definition: nest2pos.py:97
def draw_posterior(data, log_wts, verbose=False)
Draw points from the given data (of shape (Nsamples, Ndim)) with associated log(weight) (of shape (Ns...
Definition: nest2pos.py:55