1 # Copyright (C) 2009-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 and scanning.
23 from os import getpid # for rss()
26 from StringIO import StringIO
29 matplotlib.use('Agg') # select backend that doesn't require X Windows
34 from .histogram import Histogram
35 from .sawsim_histogram import sawsim_histogram
36 from .sawsim import SawsimRunner
39 _multiprocess_can_split_ = True
40 """Allow nosetests to split tests between processes.
43 FIGURE = pylab.figure() # avoid memory problems.
44 """`pylab` keeps internal references to all created figures, so share
47 EXAMPLE_HISTOGRAM_FILE_CONTENTS = """# Velocity histograms
48 # Other general comments...
51 #Force (N)\tUnfolding events
73 #Force (N)\tUnfolding events
102 #Force (N)\tUnfolding events
132 For debugging memory usage.
134 resident set size, the non-swapped physical memory that a task has
135 used (in kilo-bytes).
137 call = "ps -o rss= -p %d" % getpid()
138 status,stdout,stderr = invoke(call)
142 class HistogramMatcher (object):
143 """Compare experimental histograms to simulated data.
145 The main entry points are `fit()` and `plot()`.
147 The input `histogram_stream` should contain a series of
148 experimental histograms with '#HISTOGRAM: <params>` lines starting
149 each histogram. `<params>` lists the `sawsim` parameters that are
150 unique to that experiment.
152 >>> from .manager.thread import ThreadManager
153 >>> histogram_stream = StringIO(EXAMPLE_HISTOGRAM_FILE_CONTENTS)
154 >>> param_format_string = (
155 ... '-s cantilever,hooke,0.05 -N1 '
156 ... '-s folded,null -N8 '
157 ... '-s "unfolded,wlc,{0.39e-9,28e-9}" '
158 ... '-k "folded,unfolded,bell,{%g,%g}" -q folded')
159 >>> m = ThreadManager()
160 >>> sr = SawsimRunner(manager=m)
161 >>> hm = HistogramMatcher(histogram_stream, param_format_string, sr, N=3)
162 >>> hm.plot([[1e-5,1e-3,3],[0.1e-9,1e-9,3]], logx=True, logy=False)
165 def __init__(self, histogram_stream, param_format_string,
166 sawsim_runner, N=400, residual_type='jensen-shannon',
168 self.experiment_histograms = self._read_force_histograms(
170 self.param_format_string = param_format_string
171 self.sawsim_runner = sawsim_runner
173 self.residual_type = residual_type
176 def _read_force_histograms(self, stream):
180 # comment and blank lines ignored
181 #HISTOGRAM: <histogram-specific params>
182 <pysawsim.histogram.Histogram-compatible histogram>
183 #HISTOGRAM: <other histogram-specific params>
184 <another pysawsim.histogram.Histogram-compatible histogram>
188 >>> stream = StringIO(EXAMPLE_HISTOGRAM_FILE_CONTENTS)
189 >>> hm = HistogramMatcher(StringIO(), None, None, None)
190 >>> histograms = hm._read_force_histograms(stream)
191 >>> sorted(histograms.iterkeys())
192 ['-v 1e-6', '-v 6e-7', '-v 8e-7']
193 >>> histograms['-v 1e-6'].to_stream(sys.stdout)
194 ... # doctest: +NORMALIZE_WHITESPACE, +REPORT_UDIFF
195 #Force (N)\tUnfolding events
217 token = '#HISTOGRAM:'
218 hist_blocks = {None: []}
220 for line in stream.readlines():
222 if line.startswith(token):
223 params = line[len(token):].strip()
224 assert params not in hist_blocks, params
225 hist_blocks[params] = []
227 hist_blocks[params].append(line)
230 for params,block in hist_blocks.iteritems():
234 h.from_stream(StringIO('\n'.join(block)))
235 histograms[params] = h
238 def param_string(self, params, hist_params):
239 """Generate a string of options to pass to `sawsim`.
242 self.param_format_string % tuple(params), hist_params)
244 def residual(self, params):
246 for hist_params,experiment_hist in self.experiment_histograms.iteritems():
247 sawsim_hist = sawsim_histogram(
248 sawsim_runner=self.sawsim_runner,
249 param_string=self.param_string(params, hist_params),
250 N=self.N, bin_edges=experiment_hist.bin_edges)
251 r = experiment_hist.residual(sawsim_hist, type=self.residual_type)
253 if self._plot == True:
254 title = ", ".join(["%g" % p for p in params]+[hist_params])
255 filename = "residual-%s-%g.png" % (
256 title.replace(', ', '_').replace(' ', '_'), r)
257 self._plot_residual_comparison(
258 experiment_hist, sawsim_hist, residual=r,
259 title=title, filename=filename)
260 log().debug('residual %s: %g' % (params, residual))
263 def plot(self, param_ranges, logx=False, logy=False, contour=False):
264 xranges = param_ranges[0]
265 yranges = param_ranges[1]
267 x = numpy.linspace(*xranges)
270 x = numpy.exp(numpy.linspace(numpy.log(m), numpy.log(M), n))
272 y = numpy.linspace(*yranges)
275 y = numpy.exp(numpy.linspace(numpy.log(m), numpy.log(M), n))
276 X, Y = pylab.meshgrid(x,y)
277 C = numpy.zeros((len(y)-1, len(x)-1))
278 for i,xi in enumerate(x[:-1]):
279 for j,yj in enumerate(y[:-1]):
280 log().info('point %d %d (%d of %d)'
281 % (i, j, i*(len(y)-1) + j, (len(x)-1)*(len(y)-1)))
283 r = self.residual(params)
284 C[j,i] = numpy.log(r) # better resolution in valleys
285 if MEM_DEBUG == True:
286 log().debug('RSS: %d KB' % rss())
287 C = numpy.nan_to_num(C) # NaN -> 0
288 fid = file("histogram_matcher-XYC.pkl", "wb")
289 pickle.dump([X,Y,C], fid)
293 # [X,Y,C] = pickle.load(file("histogram_matcher-XYC.pkl", "rb"))
296 axes = FIGURE.add_subplot(111)
298 axes.set_xscale('log')
300 axes.set_yscale('log')
302 p = axes.contour(X[:-1,:-1], Y[:-1,:-1], C)
303 # [:-1,:-1] to strip dummy last row & column from X&Y.
304 else: # pseudocolor plot
305 p = axes.pcolor(X, Y, C)
306 axes.autoscale_view(tight=True)
308 FIGURE.savefig("figure.png")
310 def _plot_residual_comparison(self, experiment_hist, theory_hist,
311 residual, title, filename):
313 p = pylab.plot(experiment_hist.bin_edges[:-1],
314 experiment_hist.probabilities, 'r-',
315 theory_hist.bin_edges[:-1],
316 theory_hist.probabilities, 'b-')
318 FIGURE.savefig(filename)
321 def parse_param_ranges_string(string):
322 """Parse parameter range stings.
324 '[Amin,Amax,Asteps],[Bmin,Bmax,Bsteps],...'
326 [[Amin,Amax,Asteps],[Bmin,Bmax,Bsteps],...]
328 >>> parse_param_ranges_string('[1,2,3],[4,5,6]')
329 [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]
330 >>> parse_param_ranges_string('[1,2,3]')
334 for range_string in string.split("],["):
335 range_number_strings = range_string.strip("[]").split(",")
336 ranges.append([float(x) for x in range_number_strings])
343 >>> f = tempfile.NamedTemporaryFile()
344 >>> f.write(EXAMPLE_HISTOGRAM_FILE_CONTENTS)
346 >>> main(['-r', '[1e-5,1e-3,3],[0.1e-9,1e-9,3]',
351 from optparse import OptionParser
359 usage = '%prog [options] histogram_file'
361 'Compare simulated results against experimental values over a',
362 'range of parameters. Generates a plot of fit quality over',
363 'the parameter space. The histogram file should look something',
366 EXAMPLE_HISTOGRAM_FILE_CONTENTS,
368 '`#HISTOGRAM: <params>` lines start each histogram. `params`',
369 'lists the `sawsim` parameters that are unique to that',
372 'Each histogram line is of the format:',
374 '<bin_edge><whitespace><count>',
376 '`<bin_edge>` should mark the left-hand side of the bin, and',
377 'all bins should be of equal width (so we know where the last',
380 parser = OptionParser(usage, epilog=epilog)
381 parser.format_epilog = lambda formatter: epilog+'\n'
382 for option in sr.optparse_options:
383 if option.dest == 'param_string':
385 parser.add_option(option)
386 parser.add_option('-f','--param-format', dest='param_format',
388 help='Convert params to sawsim options (%default).',
389 default=('-s cantilever,hooke,0.05 -N1 -s folded,null -N8 -s "unfolded,wlc,{0.39e-9,28e-9}" -k "folded,unfolded,bell,{%g,%g}" -q folded'))
390 parser.add_option('-p','--initial-params', dest='initial_params',
392 help='Initial params for fitting (%default).',
393 default='3.3e-4,0.25e-9')
394 parser.add_option('-r','--param-range', dest='param_range',
396 help='Param range for plotting (%default).',
397 default='[1e-5,1e-3,20],[0.1e-9,1e-9,20]')
398 parser.add_option('--logx', dest='logx',
399 help='Use a log scale for the x range.',
400 default=False, action='store_true')
401 parser.add_option('--logy', dest='logy',
402 help='Use a log scale for the y range.',
403 default=False, action='store_true')
404 parser.add_option('-R','--residual', dest='residual',
406 help='Residual type (from %s; default: %%default).'
407 % ', '.join(Histogram().types()),
408 default='jensen-shannon')
409 parser.add_option('-P','--plot-residuals', dest='plot_residuals',
410 help='Generate residual difference plots for each point in the plot range.',
411 default=False, action='store_true')
412 parser.add_option('-c','--contour-plot', dest='contour_plot',
413 help='Select contour plot (vs. the default pseudocolor plot).',
414 default=False, action='store_true')
416 options,args = parser.parse_args(argv)
418 initial_params = [float(p) for p in options.initial_params.split(",")]
419 param_ranges = parse_param_ranges_string(options.param_range)
420 histogram_file = args[0]
421 sr_call_params = sr.initialize_from_options(options)
424 hm = HistogramMatcher(
425 file(histogram_file, 'r'),
426 param_format_string=options.param_format,
427 sawsim_runner=sr, residual_type=options.residual,
428 plot=options.plot_residuals, **sr_call_params)
429 #hm.fit(initial_params)
430 hm.plot(param_ranges, logx=options.logx, logy=options.logy,
431 contour=options.contour_plot)