Add --help, --stack, and --output to sawsim_plot_histogram_file.py.
[sawsim.git] / bin / sawsim_plot_histogram_file.py
1 #!/usr/bin/env python
2
3 """Plot a sawsim histogram file.
4 """
5
6 import argparse as _argparse
7
8 from matplotlib import pyplot
9
10 from pysawsim.parameter_scan import HistogramMatcher
11 from pysawsim.histogram import FIGURE
12
13
14 def main(argv=None):
15     parser = _argparse.ArgumentParser(description=__doc__)
16     parser.add_argument('files', metavar='FILE', nargs='+')
17     parser.add_argument(
18         '-s', '--stack', action='store_const', const=True,
19         help='stack all histograms into a single plot')
20     parser.add_argument(
21         '-o', '--output',
22         help='filename for saving the stacked output plot')
23
24     args = parser.parse_args(argv)
25
26     if args.output and not args.stack:
27         raise ValueError('cannot set --output without setting --stack')
28
29     stack = []
30     for histfile in args.files:
31         with open(histfile, 'r') as f:
32             histograms = HistogramMatcher._read_force_histograms(f)
33             for params,histogram in sorted(histograms.items()):
34                 if args.stack:
35                     stack.append((params,histogram))
36                 else:
37                     histogram.plot(
38                         title=params,
39                         filename='histogram{}.png'.format(
40                             params.replace(' ','_')))
41     if stack:
42         # fairly similar to pysawsim.histogram.Histogram.plot
43         FIGURE.clear()
44         axes = FIGURE.add_subplot(1, 1, 1)
45         axes.hold(True)
46         bin_width = stack[0][1].bin_edges[1] - stack[0][1].bin_edges[0]
47         dx = bin_width / (2*len(stack))  # small offset for readability
48         for i,(params,histogram) in enumerate(stack):
49             n,bins,patches = axes.hist(
50                 x=[x + i*dx for x in histogram.bin_edges[:-1]],
51                 weights=histogram.probabilities,
52                 bins=[x + i*dx for x in histogram.bin_edges],
53                 align='mid', histtype='stepfilled',
54                 alpha=0.15, label=params)
55             axes.legend(loc='best')
56         axes.set_title('histograms')
57         pyplot.show()
58         FIGURE.savefig(args.output)
59
60
61 if __name__ == '__main__':
62     main()