Add link to Python wiki's parallel processing page.
[sawsim.git] / pysawsim / histogram.py
1 # Copyright (C) 2009-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 """Histogram generation and comparison.
21 """
22
23 import numpy
24
25
26 class Histogram (object):
27     """A histogram with a flexible comparison method, `residual()`.
28
29     >>> h = Histogram()
30     """
31     def calculate_bin_edges(self, data, bin_width):
32         """
33         >>> h = Histogram()
34         >>> h.calculate_bin_edges(numpy.array([-7.5, 18.2, 4]), 10)
35         array([-10.,   0.,  10.,  20.])
36         >>> h.calculate_bin_edges(numpy.array([-7.5, 18.2, 4, 20]), 10)
37         array([-10.,   0.,  10.,  20.])
38         >>> h.calculate_bin_edges(numpy.array([0, 18.2, 4, 20]), 10)
39         array([  0.,  10.,  20.])
40         >>> h.calculate_bin_edges(numpy.array([18.2, 4, 20]), 10)
41         array([  0.,  10.,  20.])
42         >>> h.calculate_bin_edges(numpy.array([18.2, 20]), 10)
43         array([ 10.,  20.])
44         """
45         m = data.min()
46         M = data.max()
47         bin_start = m - m % bin_width
48         return numpy.arange(bin_start, M+bin_width, bin_width, dtype=data.dtype)
49
50     def from_data(self, data, bin_edges):
51         """Initialize from `data`.
52
53         All bins should be of equal width (so we can calculate which
54         bin a data point belongs to).
55
56         `data` should be a numpy array.
57         """
58         self.headings = None
59         self.bin_edges = bin_edges
60         bin_width = self.bin_edges[1] - self.bin_edges[0]
61
62         bin_is = numpy.floor((data - self.bin_edges[0])/bin_width)
63         self.counts = []
64         for i in range(len(self.bin_edges)-1):
65             self.counts.append(sum(bin_is == i))
66         self.total = float(len(data)) # some data might be outside the bins
67         self.mean = data.mean()
68         self.std_dev = data.std()
69         self.normalize()
70
71     def from_stream(self, stream):
72         """Initialize from `stream`.
73
74         File format:
75
76             # comment and blank lines ignored
77             <bin_edge><whitespace><count>
78             ...
79
80         For example:
81
82
83         `<bin_edge>` should mark the left-hand side of the bin, and
84         all bins should be of equal width (so we know where the last
85         one ends).
86
87         >>> import StringIO
88         >>> h = Histogram()
89         >>> h.from_stream(StringIO.StringIO('''# Force (N)\\tUnfolding events
90         ... 150e-12\\t10
91         ... 200e-12\\t40
92         ... 250e-12\\t5
93         ... '''))
94         >>> h.headings
95         ['Force (N)', 'Unfolding events']
96         >>> h.total
97         55.0
98         >>> h.counts
99         [10.0, 40.0, 5.0]
100         >>> h.bin_edges  # doctest: +ELLIPSIS
101         [1.5e-10, 2.000...e-10, 2.500...e-10, 3e-10]
102         >>> h.probabilities  # doctest: +ELLIPSIS
103         [0.181..., 0.727..., 0.0909...]
104         """
105         self.headings = None
106         self.bin_edges = []
107         self.counts = []
108         for line in stream.readlines():
109             line = line.strip()
110             if len(line) == 0 or line.startswith('#'):
111                 if self.headings == None and line.startswith('#'):
112                     line = line[len('#'):]
113                     self.headings = [x.strip() for x in line.split('\t')]
114                 continue # ignore blank lines and comments
115             bin_edge,count = line.split()
116             self.bin_edges.append(float(bin_edge))
117             self.counts.append(float(count))
118         bin_width = self.bin_edges[1] - self.bin_edges[0]
119         self.bin_edges.append(self.bin_edges[-1]+bin_width)
120         self.total = float(sum(self.counts))
121         self.mean = 0
122         for bin,count in zip(self.bin_edges, self.counts):
123             bin += bin_width / 2.0
124             self.mean += bin * count
125         self.mean /=  float(self.total)
126         variance = 0
127         for bin,count in zip(self.bin_edges, self.counts):
128             bin += bin_width / 2.0
129             variance += (bin - self.mean)**2 * count
130         self.std_dev = numpy.sqrt(variance)
131         self.normalize()
132
133     def to_stream(self, stream):
134         """Write to `stream` with the same format as `from_stream()`.
135
136         >>> import sys
137         >>> h = Histogram()
138         >>> h.headings = ['Force (N)', 'Unfolding events']
139         >>> h.bin_edges = [1.5e-10, 2e-10, 2.5e-10, 3e-10]
140         >>> h.counts = [10, 40, 5]
141         >>> h.to_stream(sys.stdout)
142         ... # doctest: +NORMALIZE_WHITESPACE, +REPORT_UDIFF
143         # Force (N)\tUnfolding events
144         1.5e-10\t10
145         2e-10\t40
146         2.5e-10\t5
147         """
148         if self.headings != None:
149             stream.write('# %s\n' % '\t'.join(self.headings))
150         for bin,count in zip(self.bin_edges, self.counts):
151             stream.write('%g\t%g\n' % (bin, count))
152
153     def normalize(self):
154         self.total = float(self.total)
155         self.probabilities = [count/self.total for count in self.counts]
156
157     def mean_residual(self, other):
158         return abs(other.mean - self.mean)
159
160     def std_dev_residual(self, other):
161         return abs(other.std_dev - self.std_dev)
162
163     def chi_squared_residual(self, other):
164         assert self.bin_edges == other.bin_edges
165         residual = 0
166         for probA,probB in zip(self.probabilities, other.probabilities):
167             residual += (probA-probB)**2 / probB
168         return residual
169
170     def jensen_shannon_residual(self, other):
171         assert self.bin_edges == other.bin_edges
172         def d_KL_term(p,q):
173             """
174             Kullback-Leibler divergence for a single bin, with the
175             exception that we return 0 if q==0, rather than
176             exploding like d_KL should.  We can do this because
177             the way d_KL_term is used in the Jensen-Shannon
178             divergence, if q (really m) == 0, then p also == 0,
179             and the Jensen-Shannon divergence for the entire term
180             should be zero.
181             """
182             if p==0 or q==0 or p==q:
183                 return 0.0
184             return p * numpy.log2(p/q)
185         residual = 0
186         for probA,probB in zip(self.probabilities, other.probabilities):
187             m = (probA+probB) / 2.0
188             residual += 0.5*(d_KL_term(probA,m) + d_KL_term(probB,m))
189         return residual
190
191     def _method_to_type(self, name):
192         return name[:-len('_residual')].replace('_', '-')
193
194     def _type_to_method(self, name):
195         return '%s_residual' % name.replace('-', '_')
196
197     def types(self):
198         """Return a list of supported residual types.
199         """
200         return sorted([self._method_to_type(x)
201                        for x in dir(self) if x.endswith('_residual')])
202
203     def residual(self, other, type='jensen-shannon'):
204         """Compare this histogram with `other`.
205
206         Supported comparison `type`\s may be found with `types()`:
207
208         >>> h = Histogram()
209         >>> h.types()
210         ['chi-squared', 'jensen-shannon', 'mean', 'std-dev']
211
212         Selecting an invalid `type` raises an exception.
213
214         >>> h.residual(other=None, type='invalid-type')
215         Traceback (most recent call last):
216           ...
217         AttributeError: 'Histogram' object has no attribute 'invalid_type_residual'
218
219         For residual types where there is a convention, this histogram
220         is treated as the experimental histogram and the other
221         histogram is treated as the theoretical one.
222         """
223         r_method = getattr(self, self._type_to_method(type))
224         return r_method(other)