1 # Copyright (C) 2010 W. Trevor King <wking@drexel.edu>
3 # This file is part of Hooke.
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.
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.
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/>.
19 """Provide :class:`ModelFitter` to make arbitrary model fitting easy.
22 from numpy import arange, ndarray
23 from scipy.optimize import leastsq
26 class PoorFit (ValueError):
29 class ModelFitter (object):
30 """A convenient wrapper around :func:`scipy.optimize.leastsq`.
35 Deflection data to be analyzed for the contact position.
37 Store any extra information useful inside your overridden
45 You'll want to subclass `ModelFitter`, overriding at least
46 `.model` and potentially the parameter and scale guessing
49 >>> class LinearModel (ModelFitter):
50 ... '''Simple linear model.
52 ... Levenberg-Marquardt is not how you want to solve this problem
53 ... for real systems, but it's a simple test case.
55 ... def model(self, params):
56 ... '''A linear model.
60 ... .. math:: y = p_0 x + p_1
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),
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
74 ... offset_scale = self._data.std()/10.0
75 ... if offset_scale == 0: # data is completely flat
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()
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).
86 >>> print '%.3f' % slope
88 >>> print '%.3f' % offset
91 The offset is a bit off because, the range is not a multiple of
94 def __init__(self, data, info=None):
98 def set_data(self, data):
100 self._model_data = ndarray(shape=data.shape, dtype=data.dtype)
102 def model(self, params):
103 p = params # convenient alias
104 self._model_data[:] = arange(len(self._data))
105 raise NotImplementedError
107 def guess_initial_params(self, outqueue=None):
110 def guess_scale(self, params, outqueue=None):
113 def residual(self, params):
114 return self._data - self.model(params)
116 def fit(self, initial_params=None, scale=None, outqueue=None, **kwargs):
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
128 outqueue : Queue or None
129 If given, will be used to output the data and fitted model
130 for user verification.
132 Any additional arguments are passed through to `leastsq`.
134 if initial_params == None:
135 initial_params = self.guess_initial_params(outqueue)
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)
143 'initial parameters': initial_params,
145 'fitted parameters': params,
146 'covariance matrix': cov,
149 'convergence flag': ier,