ee915b2dcfdf5113a644a30f1084e2501806dd76
[sawsim.git] / pysawsim / parameter_error.py
1 # Copyright (C) 2010  W. Trevor King <wking@drexel.edu>
2 #
3 # This program is free software: you can redistribute it and/or modify
4 # it under the terms of the GNU General Public License as published by
5 # the Free Software Foundation, either version 3 of the License, or
6 # (at your option) any later version.
7 #
8 # This program is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11 # GNU General Public License for more details.
12 #
13 # You should have received a copy of the GNU General Public License
14 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
15 #
16 # The author may be contacted at <wking@drexel.edu> on the Internet, or
17 # write to Trevor King, Drexel University, Physics Dept., 3141 Chestnut St.,
18 # Philadelphia PA 19104, USA.
19
20 """Experiment vs. simulation comparison error bar calculation.
21 """
22
23 import numpy
24
25 from .histogram import Histogram
26 from .parameter_scan import (
27     EXAMPLE_HISTOGRAM_FILE_CONTENTS, HistogramMatcher,
28     parse_param_ranges_string)
29 from .sawsim_histogram import sawsim_histogram
30 from .sawsim import SawsimRunner
31
32
33 _multiprocess_can_split_ = True
34 """Allow nosetests to split tests between processes.
35 """
36
37
38 def find_error_bounds(histogram_matcher, param_range, log_scale, threshold):
39     if log_scale == False:
40         ps = numpy.linspace(*param_range)
41     else:
42         m,M,n = param_range
43         ps = numpy.exp(numpy.linspace(numpy.log(m), numpy.log(M), n))
44
45     residual = {}
46     for i,p in enumerate(ps):
47         residual[p] = histogram_matcher.residual([p])
48
49     point = {}
50     r_best = min(residual.itervalues())
51     p_best = min([p for p,r in residual.iteritems() if r == r_best])
52     point['best fit'] = (p_best, r_best)
53     assert r_best <= threshold, (
54         'min residual %g (at %g) is over the threshold of %g'
55         % (r_best, p_best, threshold))
56     p_last = None
57     for p in ps:
58         if residual[p] < threshold:
59             assert p_last != None, (
60                 'range did not bracket lower error bound: residual(%g) = %g < %g'
61                 % (p, residual[p], threshold))
62             point['error (low)'] = p_last, residual[p_last]
63             break
64         p_last = p
65     p_last = None
66     for p in reversed(ps):
67         if residual[p] < threshold:
68             assert p_last != None, (
69                 'range did not bracket upper error bound: residual(%g) = %g < %g'
70                 % (p, residual[p], threshold))
71             point['error (high)'] = p_last, residual[p_last]
72             break
73         p_last = p
74     return point, residual
75
76
77 def main(argv=None):
78     """
79     >>> import tempfile
80     >>> f = tempfile.NamedTemporaryFile()
81     >>> f.write(EXAMPLE_HISTOGRAM_FILE_CONTENTS)
82     >>> f.flush()
83     >>> main(['-s', 'bin/sawsim',
84     ...       '-r', '[1e-6,1e-4,3]', '--log',
85     ...       '-N', '4', '-t', '0.8',
86     ...       f.name])
87     ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE, +REPORT_UDIFF
88     #parameter value\tresidual\tdescription
89     #1e-05\t0...\tbest fit
90     #0.0001\t1...\terror (high)
91     #1e-06\t1...\terror (low)
92     1e-06\t1...
93     1e-05\t0...
94     0.0001\t1...
95     >>> f.close()
96     """
97     from optparse import OptionParser
98     import sys
99
100     if argv == None:
101         argv = sys.argv[1:]
102
103     sr = SawsimRunner()
104
105     usage = '%prog [options] histogram_file'
106     epilog = '\n'.join([
107             'Compare simulated results against experimental over a sweep of',
108             'a single parameter.  Prints `(<paramter value>, <residual>)`',
109             'pairs for every tested point, with comments listing the',
110             'best-fit, + error bound, and - error bound.  The histogram file',
111             'should look something like:',
112             '',
113             EXAMPLE_HISTOGRAM_FILE_CONTENTS,
114             ''
115             '`#HISTOGRAM: <params>` lines start each histogram.  `params`',
116             'lists the `sawsim` parameters that are unique to that',
117             'experiment.',
118             '',
119             'Each histogram line is of the format:',
120             '',
121             '<bin_edge><whitespace><count>',
122             '',
123             '`<bin_edge>` should mark the left-hand side of the bin, and',
124             'all bins should be of equal width (so we know where the last',
125             'one ends).',
126             ])
127     parser = OptionParser(usage, epilog=epilog)
128     for option in sr.optparse_options:
129         if option.dest == 'param_string':
130             continue
131         parser.add_option(option)
132     parser.add_option('-f','--param-format', dest='param_format',
133                       metavar='FORMAT',
134                       help='Convert params to sawsim options (%default).',
135                       default=('-s cantilever,hooke,0.05 -N1 -s folded,null -N8 -s "unfolded,wlc,{0.39e-9,28e-9}" -k "folded,unfolded,bell,{%g,0.25e-9}" -q folded'))
136     parser.add_option('-r','--param-range', dest='param_range',
137                       metavar='PARAMS',
138                       help='Param range for plotting (%default).',
139                       default='[1e-5,1e-3,30]')
140     parser.add_option('--log', dest='log',
141                       help='Use a log scale for the parameter range.',
142                       default=False, action='store_true')
143     parser.add_option('-R','--residual', dest='residual',
144                       metavar='STRING',
145                       help='Residual type (from %s; default: %%default).'
146                            % ', '.join(Histogram().types()),
147                       default='jensen-shannon')
148     parser.add_option('-P','--plot-residuals', dest='plot_residuals',
149                       help='Generate residual difference plots for each point in the plot range.',
150                       default=False, action='store_true')
151     parser.add_option('-t', '--threshold', dest='threshold',
152                       metavar='FLOAT', type='float', default='0.2',
153                       help='Residual value that defines the location of the error bar (%default).')
154
155     options,args = parser.parse_args(argv)
156
157     param_ranges = parse_param_ranges_string(options.param_range)
158     assert len(param_ranges) == 1, param_ranges
159     param_range = param_ranges[0]
160
161     histogram_file = args[0]
162     sr_call_params = sr.initialize_from_options(options)
163
164     try:
165         hm = HistogramMatcher(
166             file(histogram_file, 'r'),
167             param_format_string=options.param_format,
168             sawsim_runner=sr, residual_type=options.residual,
169             plot=options.plot_residuals, **sr_call_params)
170         points,residuals = find_error_bounds(hm, param_range, options.log, options.threshold)
171     finally:
172         sr.teardown()
173
174     print '#%s' % '\t'.join(['parameter value', 'residual', 'description'])
175     for key,value in sorted(points.iteritems()):
176         print '#%s' % '\t'.join([str(x) for x in [value[0], value[1], key]])
177     for key,value in sorted(residuals.iteritems()):
178         print '%s' % '\t'.join([str(x) for x in [key, value]])