Added hooke.util.fit for easy Levenberg-Marquardt fitting.
[hooke.git] / hooke / util / fit.py
1 # Copyright (C) 2010 W. Trevor King <wking@drexel.edu>
2 #
3 # This file is part of Hooke.
4 #
5 # Hooke is free software: you can redistribute it and/or
6 # modify it under the terms of the GNU Lesser General Public
7 # License as published by the Free Software Foundation, either
8 # version 3 of the License, or (at your option) any later version.
9 #
10 # Hooke is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU Lesser General Public License for more details.
14 #
15 # You should have received a copy of the GNU Lesser General Public
16 # License along with Hooke.  If not, see
17 # <http://www.gnu.org/licenses/>.
18
19 """Provide :class:`ModelFitter` to make arbitrary model fitting easy.
20 """
21
22 from numpy import arange, ndarray
23 from scipy.optimize import leastsq
24
25
26 class PoorFit (ValueError):
27     pass
28
29 class ModelFitter (object):
30     """A convenient wrapper around :func:`scipy.optimize.leastsq`.
31
32     Parameters
33     ----------
34     d_data : array_like
35         Deflection data to be analyzed for the contact position.
36     info :
37         Store any extra information useful inside your overridden
38         methods.
39
40     Examples
41     --------
42
43     >>> import numpy
44
45     You'll want to subclass `ModelFitter`, overriding at least
46     `.model` and potentially the parameter and scale guessing
47     methods.
48
49     >>> class LinearModel (ModelFitter):
50     ...     '''Simple linear model.
51     ...
52     ...     Levenberg-Marquardt is not how you want to solve this problem
53     ...     for real systems, but it's a simple test case.
54     ...     '''
55     ...     def model(self, params):
56     ...         '''A linear model.
57     ...
58     ...         Notes
59     ...         -----
60     ...         .. math:: y = p_0 x + p_1
61     ...         '''
62     ...         p = params  # convenient alias
63     ...         self._model_data[:] = p[0]*arange(len(self._data)) + p[1]
64     ...         return self._model_data
65     ...     def guess_initial_params(self, outqueue=None):
66     ...         return [float(self._data[-1] - self._data[0])/len(self._data),
67     ...                 self._data[0]]
68     ...     def guess_scale(self, params, outqueue=None):
69     ...         slope_scale = params[0]/10.
70     ...         if slope_scale == 0:  # data is expected to be flat
71     ...             slope_scale = float(self._data.max()-self._data.min())/len(self._data)
72     ...             if slope_scale == 0:  # data is completely flat
73     ...                 slope_scale = 1.
74     ...         offset_scale = self._data.std()/10.0
75     ...         if offset_scale == 0:  # data is completely flat
76     ...             offset_scale = 1.
77     ...         return [slope_scale, offset_scale]
78     >>> data = 20*numpy.sin(arange(1000)) + 7.*arange(1000) - 33.0
79     >>> m = LinearModel(data)
80     >>> slope,offset = m.fit()
81
82     We round the outputs to protect the doctest against differences in
83     machine rounding during computation.  We expect the values to be close
84     to the input settings (slope 7, offset -33).
85
86     >>> print '%.3f' % slope
87     7.000
88     >>> print '%.3f' % offset
89     -32.890
90
91     The offset is a bit off because, the range is not a multiple of
92     :math:`2\pi`.
93     """
94     def __init__(self, data, info=None):
95         self.set_data(data)
96         self.info = info
97
98     def set_data(self, data):
99         self._data = data
100         self._model_data = ndarray(shape=data.shape, dtype=data.dtype)
101
102     def model(self, params):
103         p = params  # convenient alias
104         self._model_data[:] = arange(len(self._data))
105         raise NotImplementedError
106
107     def guess_initial_params(self, outqueue=None):
108         return []
109
110     def guess_scale(self, params, outqueue=None):
111         return []
112
113     def residual(self, params):
114         return self._data - self.model(params)
115
116     def fit(self, initial_params=None, scale=None, outqueue=None, **kwargs):
117         """
118         Parameters
119         ----------
120         initial_params : iterable or None
121             Initial parameter values for residual minimization.  If
122             `None`, they are estimated from the data using
123             :meth:`guess_initial_params`.
124         scale : iterable or None
125             Parameter length scales for residual minimization.  If
126             `None`, they are estimated from the data using
127             :meth:`guess_scale`.
128         outqueue : Queue or None
129             If given, will be used to output the data and fitted model
130             for user verification.
131         kwargs :
132             Any additional arguments are passed through to `leastsq`.
133         """
134         if initial_params == None:
135             initial_params = self.guess_initial_params(outqueue)
136         if scale == None:
137             scale = self.guess_scale(initial_params, outqueue)
138         params,cov,info,mesg,ier = leastsq(
139             func=self.residual, x0=initial_params, full_output=True,
140             diag=scale, **kwargs)
141         if outqueue != None:
142             outqeue.put({
143                     'initial parameters': initial_params,
144                     'scale': scale,
145                     'fitted parameters': params,
146                     'covariance matrix': cov,
147                     'info': info,
148                     'message': mesg,
149                     'convergence flag': ier,
150                     })
151         return params