1 # Copyright (C) 2010 W. Trevor King <wking@drexel.edu>
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.
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.
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/>.
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.
20 """Experiment vs. simulation comparison error bar calculation.
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
33 _multiprocess_can_split_ = True
34 """Allow nosetests to split tests between processes.
38 def find_error_bounds(histogram_matcher, param_range, log_scale, threshold):
39 if log_scale == False:
40 ps = numpy.linspace(*param_range)
43 ps = numpy.exp(numpy.linspace(numpy.log(m), numpy.log(M), n))
46 for i,p in enumerate(ps):
47 residual[p] = histogram_matcher.residual([p])
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))
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]
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]
74 return point, residual
80 >>> f = tempfile.NamedTemporaryFile()
81 >>> f.write(EXAMPLE_HISTOGRAM_FILE_CONTENTS)
83 >>> main(['-s', 'bin/sawsim',
84 ... '-r', '[1e-6,1e-4,3]', '--log',
85 ... '-N', '4', '-t', '0.8',
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)
97 from optparse import OptionParser
105 usage = '%prog [options] histogram_file'
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:',
113 EXAMPLE_HISTOGRAM_FILE_CONTENTS,
115 '`#HISTOGRAM: <params>` lines start each histogram. `params`',
116 'lists the `sawsim` parameters that are unique to that',
119 'Each histogram line is of the format:',
121 '<bin_edge><whitespace><count>',
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',
127 parser = OptionParser(usage, epilog=epilog)
128 for option in sr.optparse_options:
129 if option.dest == 'param_string':
131 parser.add_option(option)
132 parser.add_option('-f','--param-format', dest='param_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',
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',
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).')
155 options,args = parser.parse_args(argv)
157 param_ranges = parse_param_ranges_string(options.param_range)
158 assert len(param_ranges) == 1, param_ranges
159 param_range = param_ranges[0]
161 histogram_file = args[0]
162 sr_call_params = sr.initialize_from_options(options)
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)
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]])