_models.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. """ Collection of Model instances for use with the odrpack fitting package.
  2. """
  3. import numpy as np
  4. from scipy.odr._odrpack import Model
  5. __all__ = ['Model', 'exponential', 'multilinear', 'unilinear', 'quadratic',
  6. 'polynomial']
  7. def _lin_fcn(B, x):
  8. a, b = B[0], B[1:]
  9. b.shape = (b.shape[0], 1)
  10. return a + (x*b).sum(axis=0)
  11. def _lin_fjb(B, x):
  12. a = np.ones(x.shape[-1], float)
  13. res = np.concatenate((a, x.ravel()))
  14. res.shape = (B.shape[-1], x.shape[-1])
  15. return res
  16. def _lin_fjd(B, x):
  17. b = B[1:]
  18. b = np.repeat(b, (x.shape[-1],)*b.shape[-1], axis=0)
  19. b.shape = x.shape
  20. return b
  21. def _lin_est(data):
  22. # Eh. The answer is analytical, so just return all ones.
  23. # Don't return zeros since that will interfere with
  24. # ODRPACK's auto-scaling procedures.
  25. if len(data.x.shape) == 2:
  26. m = data.x.shape[0]
  27. else:
  28. m = 1
  29. return np.ones((m + 1,), float)
  30. def _poly_fcn(B, x, powers):
  31. a, b = B[0], B[1:]
  32. b.shape = (b.shape[0], 1)
  33. return a + np.sum(b * np.power(x, powers), axis=0)
  34. def _poly_fjacb(B, x, powers):
  35. res = np.concatenate((np.ones(x.shape[-1], float),
  36. np.power(x, powers).flat))
  37. res.shape = (B.shape[-1], x.shape[-1])
  38. return res
  39. def _poly_fjacd(B, x, powers):
  40. b = B[1:]
  41. b.shape = (b.shape[0], 1)
  42. b = b * powers
  43. return np.sum(b * np.power(x, powers-1), axis=0)
  44. def _exp_fcn(B, x):
  45. return B[0] + np.exp(B[1] * x)
  46. def _exp_fjd(B, x):
  47. return B[1] * np.exp(B[1] * x)
  48. def _exp_fjb(B, x):
  49. res = np.concatenate((np.ones(x.shape[-1], float), x * np.exp(B[1] * x)))
  50. res.shape = (2, x.shape[-1])
  51. return res
  52. def _exp_est(data):
  53. # Eh.
  54. return np.array([1., 1.])
  55. class _MultilinearModel(Model):
  56. r"""
  57. Arbitrary-dimensional linear model
  58. This model is defined by :math:`y=\beta_0 + \sum_{i=1}^m \beta_i x_i`
  59. Examples
  60. --------
  61. We can calculate orthogonal distance regression with an arbitrary
  62. dimensional linear model:
  63. >>> from scipy import odr
  64. >>> import numpy as np
  65. >>> x = np.linspace(0.0, 5.0)
  66. >>> y = 10.0 + 5.0 * x
  67. >>> data = odr.Data(x, y)
  68. >>> odr_obj = odr.ODR(data, odr.multilinear)
  69. >>> output = odr_obj.run()
  70. >>> print(output.beta)
  71. [10. 5.]
  72. """
  73. def __init__(self):
  74. super().__init__(
  75. _lin_fcn, fjacb=_lin_fjb, fjacd=_lin_fjd, estimate=_lin_est,
  76. meta={'name': 'Arbitrary-dimensional Linear',
  77. 'equ': 'y = B_0 + Sum[i=1..m, B_i * x_i]',
  78. 'TeXequ': r'$y=\beta_0 + \sum_{i=1}^m \beta_i x_i$'})
  79. multilinear = _MultilinearModel()
  80. def polynomial(order):
  81. """
  82. Factory function for a general polynomial model.
  83. Parameters
  84. ----------
  85. order : int or sequence
  86. If an integer, it becomes the order of the polynomial to fit. If
  87. a sequence of numbers, then these are the explicit powers in the
  88. polynomial.
  89. A constant term (power 0) is always included, so don't include 0.
  90. Thus, polynomial(n) is equivalent to polynomial(range(1, n+1)).
  91. Returns
  92. -------
  93. polynomial : Model instance
  94. Model instance.
  95. Examples
  96. --------
  97. We can fit an input data using orthogonal distance regression (ODR) with
  98. a polynomial model:
  99. >>> import numpy as np
  100. >>> import matplotlib.pyplot as plt
  101. >>> from scipy import odr
  102. >>> x = np.linspace(0.0, 5.0)
  103. >>> y = np.sin(x)
  104. >>> poly_model = odr.polynomial(3) # using third order polynomial model
  105. >>> data = odr.Data(x, y)
  106. >>> odr_obj = odr.ODR(data, poly_model)
  107. >>> output = odr_obj.run() # running ODR fitting
  108. >>> poly = np.poly1d(output.beta[::-1])
  109. >>> poly_y = poly(x)
  110. >>> plt.plot(x, y, label="input data")
  111. >>> plt.plot(x, poly_y, label="polynomial ODR")
  112. >>> plt.legend()
  113. >>> plt.show()
  114. """
  115. powers = np.asarray(order)
  116. if powers.shape == ():
  117. # Scalar.
  118. powers = np.arange(1, powers + 1)
  119. powers.shape = (len(powers), 1)
  120. len_beta = len(powers) + 1
  121. def _poly_est(data, len_beta=len_beta):
  122. # Eh. Ignore data and return all ones.
  123. return np.ones((len_beta,), float)
  124. return Model(_poly_fcn, fjacd=_poly_fjacd, fjacb=_poly_fjacb,
  125. estimate=_poly_est, extra_args=(powers,),
  126. meta={'name': 'Sorta-general Polynomial',
  127. 'equ': 'y = B_0 + Sum[i=1..%s, B_i * (x**i)]' % (len_beta-1),
  128. 'TeXequ': r'$y=\beta_0 + \sum_{i=1}^{%s} \beta_i x^i$' %
  129. (len_beta-1)})
  130. class _ExponentialModel(Model):
  131. r"""
  132. Exponential model
  133. This model is defined by :math:`y=\beta_0 + e^{\beta_1 x}`
  134. Examples
  135. --------
  136. We can calculate orthogonal distance regression with an exponential model:
  137. >>> from scipy import odr
  138. >>> import numpy as np
  139. >>> x = np.linspace(0.0, 5.0)
  140. >>> y = -10.0 + np.exp(0.5*x)
  141. >>> data = odr.Data(x, y)
  142. >>> odr_obj = odr.ODR(data, odr.exponential)
  143. >>> output = odr_obj.run()
  144. >>> print(output.beta)
  145. [-10. 0.5]
  146. """
  147. def __init__(self):
  148. super().__init__(_exp_fcn, fjacd=_exp_fjd, fjacb=_exp_fjb,
  149. estimate=_exp_est,
  150. meta={'name': 'Exponential',
  151. 'equ': 'y= B_0 + exp(B_1 * x)',
  152. 'TeXequ': r'$y=\beta_0 + e^{\beta_1 x}$'})
  153. exponential = _ExponentialModel()
  154. def _unilin(B, x):
  155. return x*B[0] + B[1]
  156. def _unilin_fjd(B, x):
  157. return np.ones(x.shape, float) * B[0]
  158. def _unilin_fjb(B, x):
  159. _ret = np.concatenate((x, np.ones(x.shape, float)))
  160. _ret.shape = (2,) + x.shape
  161. return _ret
  162. def _unilin_est(data):
  163. return (1., 1.)
  164. def _quadratic(B, x):
  165. return x*(x*B[0] + B[1]) + B[2]
  166. def _quad_fjd(B, x):
  167. return 2*x*B[0] + B[1]
  168. def _quad_fjb(B, x):
  169. _ret = np.concatenate((x*x, x, np.ones(x.shape, float)))
  170. _ret.shape = (3,) + x.shape
  171. return _ret
  172. def _quad_est(data):
  173. return (1.,1.,1.)
  174. class _UnilinearModel(Model):
  175. r"""
  176. Univariate linear model
  177. This model is defined by :math:`y = \beta_0 x + \beta_1`
  178. Examples
  179. --------
  180. We can calculate orthogonal distance regression with an unilinear model:
  181. >>> from scipy import odr
  182. >>> import numpy as np
  183. >>> x = np.linspace(0.0, 5.0)
  184. >>> y = 1.0 * x + 2.0
  185. >>> data = odr.Data(x, y)
  186. >>> odr_obj = odr.ODR(data, odr.unilinear)
  187. >>> output = odr_obj.run()
  188. >>> print(output.beta)
  189. [1. 2.]
  190. """
  191. def __init__(self):
  192. super().__init__(_unilin, fjacd=_unilin_fjd, fjacb=_unilin_fjb,
  193. estimate=_unilin_est,
  194. meta={'name': 'Univariate Linear',
  195. 'equ': 'y = B_0 * x + B_1',
  196. 'TeXequ': '$y = \\beta_0 x + \\beta_1$'})
  197. unilinear = _UnilinearModel()
  198. class _QuadraticModel(Model):
  199. r"""
  200. Quadratic model
  201. This model is defined by :math:`y = \beta_0 x^2 + \beta_1 x + \beta_2`
  202. Examples
  203. --------
  204. We can calculate orthogonal distance regression with a quadratic model:
  205. >>> from scipy import odr
  206. >>> import numpy as np
  207. >>> x = np.linspace(0.0, 5.0)
  208. >>> y = 1.0 * x ** 2 + 2.0 * x + 3.0
  209. >>> data = odr.Data(x, y)
  210. >>> odr_obj = odr.ODR(data, odr.quadratic)
  211. >>> output = odr_obj.run()
  212. >>> print(output.beta)
  213. [1. 2. 3.]
  214. """
  215. def __init__(self):
  216. super().__init__(
  217. _quadratic, fjacd=_quad_fjd, fjacb=_quad_fjb, estimate=_quad_est,
  218. meta={'name': 'Quadratic',
  219. 'equ': 'y = B_0*x**2 + B_1*x + B_2',
  220. 'TeXequ': '$y = \\beta_0 x^2 + \\beta_1 x + \\beta_2'})
  221. quadratic = _QuadraticModel()